From f185de0cd63590f4dea23dc7fdf2c32e84a19124 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 16:19:41 -0800 Subject: [PATCH 01/19] BDSP AutoStory: no route ends beside a warp walking toward it 01.05's open walk west to (2, 13), beside the Oreburgh Gate's mouth, slid onto the warp (lab-B 2026-11-08, four runs). A table test plans every ROUTE step as the walker does and fails on an open leg that may end on the tile before a door it walks toward. It flagged 01.05's old by_the_gate and four more: 00.03 above_the_door_again (now counted legs from the west), 01.02 by_the_east_mouth and 01.05 through_the_gate (two tiles short of the Gate's mouths, the taps go the rest), and 01.03 above_the_mine (two rows above the warp row, the door run goes on). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryTable.cpp | 11 ++- ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 81 +++++++++++++++++++ 2 files changed, 88 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index a6e5a30c63..2f7cb7123d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -124,6 +124,8 @@ StoryStep make(StoryStepKind kind, std::string name, std::string why){ step.why = std::move(why); return step; } +// A route toward a door or a warp stops two tiles short, not beside it: an +// open walk there can slide onto it (01.05, lab-B 2026-11-08). StoryStep route(std::string name, Pose target, std::string why, std::string costs = ""){ StoryStep step = make(StoryStepKind::ROUTE, std::move(name), std::move(why)); step.target = std::move(target); @@ -337,7 +339,8 @@ std::vector lake_and_pokedex(){ // Line up on the table's corner west first: a plan from either tile // ran east into Mom at (7, 8), who talks (r29). route("by_the_counter", at(HOME, 4, 8, WEST), "west against the table's corner (3, 8)"), - route("above_the_door_again", at(HOME, 6, 9, SOUTH), "to above the door"), + anchored(legs("above_the_door_again", {{.direction = EAST, .tiles = 1}, {.direction = SOUTH, .tiles = 1}, {.direction = EAST, .tiles = 1}}, + "east, south past the wall (4, 9), and east to above the door: not south toward it"), at(HOME, 6, 9, EAST)), step_into("out_of_the_house_again", SOUTH, "onto the door's tile (6, 10), and out", at(TWINLEAF, "house_doorstep", SOUTH)), // Through the grass now, with a starter: wild battles are run from. route("short_of_dawn", at(ROUTE_201, 63, 5, EAST), "Twinleaf, then east along Route 201 to its east edge"), @@ -637,7 +640,7 @@ StoryCheckpoint oreburgh_to_route_203(){ // for a banner already gone (lab-B, 2026-11-08 15:31, 15:39, 15:47, // 15:54; frames in Screenshots/AutoStory/banner/). step_into("into_oreburgh_gate", WEST, "the Gate's mouth (1, 13)", arrival(GATE, {27, 22}, WEST)), - route("through_the_gate", at(GATE, 4, 22, WEST), "west along row 22 to the warp tile by the west mouth (3, 22)"), + route("through_the_gate", at(GATE, 5, 22, WEST), "west along row 22 to two tiles short of the west mouth's warp (3, 22)"), // Route 203's banner or a failure here: the old walk west "until the // banner" went on into the pond's pocket (r75). 01.06 heads south. tap_into("out_of_oreburgh_gate", WEST, "the west mouth (3, 22)", out_of_oreburgh_gate()), @@ -674,7 +677,7 @@ StoryCheckpoint route_203_to_oreburgh(){ // can come up a moment after them; the scene's B closes it. scene("the_hiker", at(GATE, 7, 22, EAST), "HM Rock Smash, then the Hidden Moves card"), route("past_curtis", at(GATE, 20, 22, EAST), "east along row 22 past Camper Curtis's column (17), fighting him"), - route("by_the_east_mouth", at(GATE, 27, 22, EAST), "east past Picnicker Diana's column (24), fighting her"), + route("by_the_east_mouth", at(GATE, 26, 22, EAST), "east past Picnicker Diana's column (24), fighting her, to two short of the mouth"), tap_into("into_oreburgh", EAST, "the Gate's east mouth (28, 22)", arrival(OREBURGH, map_point(OREBURGH, "gate_mouth").next(EAST), EAST)), route("west_of_the_welcome", at(OREBURGH, 9, 13, EAST), "east along row 13"), @@ -766,7 +769,7 @@ StoryCheckpoint oreburgh_center_heal(){ StoryCheckpoint oreburgh_mine_to_roark(){ const Pose below_roark = next_to(MINE, "roark", SOUTH, NORTH); return row("01.03", "Oreburgh Mine to Roark", out_of_oreburgh_center(), { - route("above_the_mine", at(OREBURGH, 46, 58, SOUTH), "down the door's column to above the mine's warp tiles", "town"), + route("above_the_mine", at(OREBURGH, 46, 57, SOUTH), "down the door's column to two above the mine's warp tiles (44..48, 59)", "town"), step_into("into_the_mine", SOUTH, "the warp tile (46, 59)", at(MINE_HALL, 12, 1, SOUTH)), step_into("into_the_coal_room", SOUTH, "down the entrance hall through the cave mouth", at(MINE, 15, 2, SOUTH)), anchored(to_walls("south_to_the_rock", {{.direction = SOUTH, .tiles = 8}}, "south against the corridor rock (15, 11)"), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index c16b365d7f..a6797a9190 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -19,7 +19,10 @@ #include "Data/PokemonBDSP_AutoStory_PlanCosts.h" #include "Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "Data/PokemonBDSP_AutoStory_StoryMaps.h" +#include "Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "Actions/PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_StoryTable_Tests.h" @@ -218,6 +221,80 @@ UnitTestResult test_route204_north_line(Logger& logger){ return true; } +// The legs a ROUTE step from `from` plans, as walk_route() plans them (the +// step's costs, then the default ones), on `world`; nothing if none. +std::optional> route_step_plan(const StoryWorld& world, const Pokemon::Pose& from, const Pokemon::StoryStep& step){ + std::vector start; + for (const TilePos& pos : Pokemon::tiles_of(from)){ + start.push_back(story_to_world(world, from.map, pos)); + } + std::vector targets; + for (const TilePos& pos : Pokemon::tiles_of(*step.target)){ + targets.push_back(story_to_world(world, step.target->map, pos)); + } + const auto goal = [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }; + std::optional> legs = plan_recovered_route(world, start, goal, *story_route_costs(step.variant)); + return legs ? legs : plan_recovered_route(world, start, goal, RobustPlanCosts()); +} + +// Why `planned` may slide into a door or a warp, or "": an open leg (not to +// a wall) that may end on the tile before one, walking toward it. A part of +// a tile too far takes the warp (lab-B 2026-11-08 15:31 to 15:54: 01.05's +// open walk west to (2, 13), beside the Oreburgh Gate's mouth, slid into +// the Gate, and the tap after it waited for a banner already gone). The +// maps draw every warp as a door tile, cave mouths too. +std::string slides_into_door(const StoryWorld& world, const PlannedLeg& planned){ + if (planned.leg.ends_at_wall){ + return ""; + } + for (const TilePos& pos : planned.after){ + const TilePos ahead = pos.next(planned.leg.direction); + if (world.tile(ahead) == Pokemon::TileKind::DOOR){ + return std::format("the open leg {} may end on {}, the tile before the door {}", + to_string(planned.leg), describe(world, pos), describe(world, ahead)); + } + } + return ""; +} + +// No ROUTE step of the table plans an open leg that ends before a door it +// walks toward: a door is gone through by a step that runs or taps into it +// from where the route ends on a wall or off its line. Where a row's steps +// leave the player is followed from its start through each step's target +// or pose_after; a route from an unknown place is not checked. +UnitTestResult test_story_routes_stop_short_of_doors(Logger& logger){ + std::vector found; + size_t checked = 0; + for (const StoryCheckpoint& row : story_checkpoints()){ + std::optional at = row.start; + for (const Pokemon::StoryStep& step : row.steps){ + const bool known = at && !Pokemon::tiles_of(*at).empty(); + const StoryWorld* world = step.kind == StoryStepKind::ROUTE && known + ? story_plan_world(at->map, step.target->map) : nullptr; + if (step.kind == StoryStepKind::ROUTE && world == nullptr){ + logger.log(std::format("{} {}: not checked, from {}.", row.id, step.name, at ? Pokemon::to_string(*at) : "nowhere known")); + } + const std::optional> legs = world ? route_step_plan(*world, *at, step) : std::nullopt; + checked += legs ? 1 : 0; + for (const PlannedLeg& planned : legs ? *legs : std::vector{}){ + const std::string why = slides_into_door(*world, planned); + if (!why.empty()){ + found.push_back(std::format("{} {}: {}.", row.id, step.name, why)); + } + } + at = step.kind == StoryStepKind::ROUTE ? step.target + : step.pose_after ? step.pose_after + : step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP ? std::nullopt : at; + } + } + logger.log(std::format("{} routes planned.", checked)); + std::string out; + for (const std::string& line : found){ + out += "\n " + line; + } + return found.empty() ? UnitTestResult(true) : UnitTestResult("Open legs that end before a door they walk toward:" + out); +} + struct AutoStoryStoryTableInput{ std::string name; @@ -270,6 +347,10 @@ const AutoStoryStoryTableCase AUTO_STORY_STORY_TABLE_CASES[] = { .input = {"Route 204 North: the line into Floaroma", test_route204_north_line}, .expectation = {}, }, + { + .input = {"Story table: no open leg ends before a door it walks toward (lab-B, 2026-11-08)", test_story_routes_stop_short_of_doors}, + .expectation = {}, + }, }; void add_tests_AutoStory_StoryTable(UnitTestDatabase& database){ From c19b41111f15c10b226c975899677715c5cf88f1 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 16:34:51 -0800 Subject: [PATCH 02/19] BDSP AutoStory: the story sim's old steps in their own file Moved unchanged out of StorySim_Tests.cpp, which is at the 1000-line limit: r75's and r81's old cave exits and the old mine steps. The next commit adds 01.05's old tap into the Oreburgh Gate beside them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_OldStorySteps.cpp | 80 +++++++++++++++++++ .../PokemonBDSP_AutoStory_OldStorySteps.h | 50 ++++++++++++ .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 63 +-------------- SerialPrograms/cmake/SourceFiles.cmake | 2 + 4 files changed, 133 insertions(+), 62 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp new file mode 100644 index 0000000000..1d7c4db01e --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp @@ -0,0 +1,80 @@ +/* BDSP AutoStory - Old story steps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP_AutoStory_OldStorySteps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::Direction; +using Pokemon::Pose; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + + +StoryStep r75_old_gate_exit(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "out_of_oreburgh_gate"; + step.legs = {{.direction = Direction::WEST, .tiles = 8}}; + step.variant = "to_map"; + step.pose_after = Pokemon::tile_pose("Route203", {TilePos{55, 9}}, Direction::WEST); + return step; +} +Pose r75_pond_pocket(){ + std::vector tiles; + for (int y = 6; y <= 13; y++){ + for (int x = 49; x <= 54; x++){ + tiles.push_back({x, y}); + } + } + return Pokemon::tile_pose("Route203", tiles); +} + +StoryStep r81_old_cave_exit(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "out_of_the_ravaged_path"; + step.legs = {{.direction = Direction::SOUTH, .tiles = 4}}; + step.variant = "to_wall"; + step.pose_after = Pokemon::tile_pose("Route204North", {TilePos{20, 26}}, Direction::SOUTH); + return step; +} +Pose r81_below_the_mouth(){ + return Pokemon::tile_pose("Route204North", {TilePos{20, 27}, TilePos{20, 28}, TilePos{20, 29}, TilePos{20, 30}}); +} + +StoryStep old_mine_hall_19(std::string name, Direction direction){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = std::move(name); + step.legs = {{.direction = direction, .tiles = 19}}; + return step; +} + +StoryStep old_coal_room_crate_cut(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "to_roarks_corner"; + step.legs = { + {.direction = Direction::EAST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 2}, + {.direction = Direction::WEST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 5}, + {.direction = Direction::EAST, .tiles = 14}, {.direction = Direction::SOUTH, .tiles = 10}, + {.direction = Direction::SOUTH, .tiles = 2}, {.direction = Direction::WEST, .tiles = 11}, + }; + return step; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h new file mode 100644 index 0000000000..a9dabdf0bb --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h @@ -0,0 +1,50 @@ +/* BDSP AutoStory - Old story steps + * + * From: https://github.com/PokemonAutomation/ + * + * Steps the story table had that went wrong on the console, as they were: + * the story simulation's regression tests run them in place of the + * table's step of the same name and check they still go wrong there. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OldStorySteps_H +#define PokemonAutomation_PokemonBDSP_AutoStory_OldStorySteps_H + +#include +#include "Pokemon/AutoStory/Pokemon_StorySteps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// r75: out of the Oreburgh Gate as a run west until Route 203's banner +// (the old event west_until_transition()). The banner reads a few tiles +// in: the run ends west of the Gate's warp tile (55, 9), in the pocket by +// the pond (Route 203's x 49 to 54, rows 6 to 13). +Pokemon::StoryStep r75_old_gate_exit(); +// Where r75's run west ended: the pocket by Route 203's pond. +Pokemon::Pose r75_pond_pocket(); + +// r81: out of the Ravaged Path as a timed walk south (the old event's +// 4 s walk_dir()), its fade missed: on past cave_exit (20, 26) to the +// cliff, column 20 down to row 30. +Pokemon::StoryStep r81_old_cave_exit(); +// Where r81's walk south ended: below the Ravaged Path's mouth. +Pokemon::Pose r81_below_the_mouth(); + +// Oreburgh Mine B1F: tapping 19 tiles leaves the player 1 tile short of the warp door. +Pokemon::StoryStep old_mine_hall_19(std::string name, Pokemon::Direction direction); + +// Oreburgh Mine: stepping south at col 29 without bypassing the crate +// hits the wooden crate at (29, 28) on the south leg, a tile down. +Pokemon::StoryStep old_coal_room_crate_cut(); + + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 85f4792206..753d084692 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -41,6 +41,7 @@ #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_OldStorySteps.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" @@ -740,44 +741,6 @@ UnitTestResult run_exit_test(Logger& logger, const std::string& row_id, const St return true; } -// r75: out of the Oreburgh Gate as a run west until Route 203's banner -// (the old event west_until_transition()). The banner reads a few tiles -// in: the run ends west of the Gate's warp tile (55, 9), in the pocket by -// the pond (Route 203's x 49 to 54, rows 6 to 13). -StoryStep r75_old_gate_exit(){ - StoryStep step; - step.kind = StoryStepKind::LEGS; - step.name = "out_of_oreburgh_gate"; - step.legs = {{.direction = Direction::WEST, .tiles = 8}}; - step.variant = "to_map"; - step.pose_after = Pokemon::tile_pose("Route203", {TilePos{55, 9}}, Direction::WEST); - return step; -} -Pose r75_pond_pocket(){ - std::vector tiles; - for (int y = 6; y <= 13; y++){ - for (int x = 49; x <= 54; x++){ - tiles.push_back({x, y}); - } - } - return Pokemon::tile_pose("Route203", tiles); -} -// r81: out of the Ravaged Path as a timed walk south (the old event's -// 4 s walk_dir()), its fade missed: on past cave_exit (20, 26) to the -// cliff, column 20 down to row 30. -StoryStep r81_old_cave_exit(){ - StoryStep step; - step.kind = StoryStepKind::LEGS; - step.name = "out_of_the_ravaged_path"; - step.legs = {{.direction = Direction::SOUTH, .tiles = 4}}; - step.variant = "to_wall"; - step.pose_after = Pokemon::tile_pose("Route204North", {TilePos{20, 26}}, Direction::SOUTH); - return step; -} -Pose r81_below_the_mouth(){ - return Pokemon::tile_pose("Route204North", {TilePos{20, 27}, TilePos{20, 28}, TilePos{20, 29}, TilePos{20, 30}}); -} - UnitTestResult test_coord_events(Logger&){ for (const auto& [map, json] : bdsp_map_json()){ const StoryWorld* world = story_plan_world(map, map); @@ -860,30 +823,6 @@ UnitTestResult test_exit_ravaged_path(Logger& logger){ return run_exit_test(logger, "01.09", r81_old_cave_exit(), SimMisses{.fade = 0, .banner = std::nullopt}, r81_below_the_mouth()); } -// Oreburgh Mine B1F: tapping 19 tiles leaves the player 1 tile short of the warp door. -StoryStep old_mine_hall_19(std::string name, Direction direction){ - StoryStep step; - step.kind = StoryStepKind::LEGS; - step.name = std::move(name); - step.legs = {{.direction = direction, .tiles = 19}}; - return step; -} - -// Oreburgh Mine: stepping south at col 29 without bypassing the crate -// hits the wooden crate at (29, 28) on the south leg, a tile down. -StoryStep old_coal_room_crate_cut(){ - StoryStep step; - step.kind = StoryStepKind::LEGS; - step.name = "to_roarks_corner"; - step.legs = { - {.direction = Direction::EAST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 2}, - {.direction = Direction::WEST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 5}, - {.direction = Direction::EAST, .tiles = 14}, {.direction = Direction::SOUTH, .tiles = 10}, - {.direction = Direction::SOUTH, .tiles = 2}, {.direction = Direction::WEST, .tiles = 11}, - }; - return step; -} - UnitTestResult test_story_sim_step_failure(Logger& logger, const std::string& row, const StoryStep& old_step, const std::string& expected_failed_step, const std::string& expected_error){ SimExecutor executor(logger); const std::vector rows = table_with(row, old_step); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 437d83cce7..c6a21120c8 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1707,6 +1707,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp From 26b4ed4aeefe533d34f06823da161c60b1292bf7 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 16:35:01 -0800 Subject: [PATCH 03/19] BDSP AutoStory: a dim cave floor is not a tap step's fade On lab-B (2026-11-08 15:31 to 15:54) 01.05's walk slid into the Oreburgh Gate, and its tap step read the Gate's floor (about 46) as the fade and waited 8 s for a banner already gone. A look after a tap is the fade only when black (< 25) or a drop to dark from the look before the tap (tap_faded()). A banner before the first tap means the walk before took us through: the step ends with no tap. A tap step taps at most two past the door its map has ahead, so one begun through the warp with its banner gone fails a few tiles in, not across the Gate. Tests: tap_faded() on the Gate's floor and real fades; the story sim's 01.05 tap step begun through the Gate's mouth, banner up and gone (red before: 24 taps across the Gate); GridSim's part-tile offset taking the warp on the old open walk west. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 42 ++++++++++++---- .../PokemonBDSP_AutoStory_StoryStepIO.h | 9 +++- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 48 ++++++++++++++++--- .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 2 +- .../PokemonBDSP_AutoStory_Walk_Tests.cpp | 33 +++++++++++++ .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 28 +++++++++++ .../PokemonBDSP_AutoStory_OldStorySteps.cpp | 10 ++++ .../PokemonBDSP_AutoStory_OldStorySteps.h | 4 ++ .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 48 +++++++++++++++++-- 9 files changed, 202 insertions(+), 22 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index 299796c325..c0d9661af7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -213,8 +213,11 @@ enum class TapLook{ BANNER, }; -// Looks for the location banner `banner` (and, if `dark_too`, the fade) -// for up to `wait`. +// The mean of r, g and b over the screen, 0 to 255; 255 with no frame. +double brightness_of(const VideoSnapshot& screen){ + return screen ? image_average(*screen.frame).sum() / 3 : 255; +} + void keep_banner_frame(const ImageViewRGB32& frame, const std::string& folder, const std::string& banner){ Filesystem::create_directories(Filesystem::Path(folder)); frame.save(folder + now_to_filestring() + "-" + normalize_location_name(banner) + ".png"); @@ -228,10 +231,12 @@ void log_new_banner_read(VideoStream& stream, const std::string& read, std::stri last_read = read; } +// Looks for the location banner `banner` for up to `wait`, and with +// `before` (the brightness before the tap) for the fade (tap_faded()). // Logs each distinct banner read and how the wait ended: the Oreburgh Gate's // entry missed its banner twice (lab-B, 2026-11-08 15:31 and 15:39) though // a hand probe saw it 1.5 s after the fade, and nothing said why. -TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const std::string& banner, Milliseconds wait, bool dark_too){ +TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const std::string& banner, Milliseconds wait, std::optional before){ const WallClock start = current_time(); const WallClock deadline = start + wait; std::string last_read; @@ -243,7 +248,7 @@ TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const while (true){ context.wait_for_all_requests(); const VideoSnapshot screen = stream.video().snapshot(); - if (!dark_too && screen && current_time() >= next_frame){ + if (!before && screen && current_time() >= next_frame){ keep_banner_frame(*screen.frame, folder, banner); next_frame += 500ms; } @@ -252,9 +257,9 @@ TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const if (screen && location_banner_matches(read, banner)){ return TapLook::BANNER; } - const double brightness = screen ? image_average(*screen.frame).sum() / 3 : 255; + const double brightness = brightness_of(screen); darkest = std::min(darkest, brightness); - if (dark_too && brightness < FADE_DARKNESS){ + if (before && tap_faded(*before, brightness)){ return TapLook::DARK; } if (current_time() >= deadline){ @@ -269,6 +274,16 @@ TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const } // namespace +// Black as the Gym's door fades (< 25), or a drop to dark: a look under +// FADE_DARKNESS is not a fade by itself, since a cave's floor is that dim +// (the Oreburgh Gate's about 46, lab-B 2026-11-08), but a fade into a cave +// from a lit street goes from about 120 to 45..64. +constexpr double TAP_FADE_BLACK = 25; +constexpr double TAP_FADE_DROP = 0.7; +bool tap_faded(double before, double after){ + return after < TAP_FADE_BLACK || (after < FADE_DARKNESS && after < before * TAP_FADE_DROP); +} + ConsoleStoryStepIO::ConsoleStoryStepIO(VideoStream& stream, ProControllerContext& context) : m_stream(stream) , m_context(context) @@ -305,15 +320,23 @@ bool ConsoleStoryStepIO::run_into_door(Direction direction, bool run, Millisecon // A held walk can carry on past a fade that goes unseen: out of the Gym it // walked on south (r219g), and through the Oreburgh Gate's west mouth on // west into a pocket by Route 203's pond (r75). Taps during the fade are -// eaten. +// eaten. The banner before the first tap means we are through already: +// the walk before slid onto the warp (lab-B 2026-11-08 15:31). std::optional ConsoleStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ const std::string& banner = story_banner_name(map); + m_context.wait_for_all_requests(); + VideoSnapshot screen = m_stream.video().snapshot(); + if (screen && location_banner_matches(read_location_banner(*screen.frame), banner)){ + m_stream.log("[Banner] \"" + banner + "\" shows before the first tap: through already."); + return 0; + } for (size_t tap = 1; tap <= max_taps; tap++){ + const double before = brightness_of(screen); pbf_press_dpad(m_context, dpad_toward(direction), 160ms, 0ms); - TapLook look = look_after_tap(m_stream, m_context, banner, 1500ms, true); + TapLook look = look_after_tap(m_stream, m_context, banner, 1500ms, before); const bool faded = look == TapLook::DARK; if (faded){ - look = look_after_tap(m_stream, m_context, banner, 8000ms, false); + look = look_after_tap(m_stream, m_context, banner, 8000ms, std::nullopt); } if (look == TapLook::BANNER){ m_context.wait_for(1000ms); @@ -322,6 +345,7 @@ std::optional ConsoleStoryStepIO::tap_to_banner(Direction direction, con if (faded){ break; } + screen = m_stream.video().snapshot(); } return std::nullopt; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h index 52470d8fcd..a48007ee2f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h @@ -51,7 +51,8 @@ class StoryStepIO{ // D-pad taps `direction` one at a time, each looked at, toward a door // or cave mouth, until the fade (then no more taps) and the location // banner of `map` (a JSON map's name), for at most `max_taps`. Returns - // the taps it took, or nothing if no banner showed. + // the taps it took (0 if the banner shows before the first: through + // already), or nothing if no banner showed. virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) = 0; // Presses through any text until the overworld is quiet; with `fade`, a // fade must come first (a map change). Fails otherwise. @@ -59,6 +60,12 @@ class StoryStepIO{ }; +// Whether a look after a tap toward a door or a cave mouth shows its fade, +// from its brightness `after` and that of the look before the tap, +// `before` (the mean of r, g and b, 0 to 255). +bool tap_faded(double before, double after); + + // The console. class ConsoleStoryStepIO : public StoryStepIO{ public: diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index 514efc1725..8a0d50e0b9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -158,16 +158,52 @@ Outcome StoryWalkSteps::leg_to_map(const StoryStep& step){ return arrived ? Pokemon::outcome_ok() : Pokemon::outcome_failed("no_banner", map); } +namespace{ +// Taps toward a door with no table door ahead of it. +constexpr size_t TAPS_TO_BANNER = 30; +// How many taps `direction` a tap step from `from` takes at most: the +// tiles to the door its map has ahead of every tile of `from`, and two +// more; TAPS_TO_BANNER where the map has none. A step through already, +// its banner gone, then stops a few tiles on (lab-B 2026-11-08: 01.05's +// walk slid into the Oreburgh Gate, whose row 22 runs 24 tiles on). +size_t taps_to_banner(const Pose& from, Direction direction){ + size_t most = 0; + try{ + const Pokemon::MapData& map = story_map(from.map); + for (const TilePos& pos : Pokemon::tiles_of(from)){ + const size_t tiles = Pokemon::tiles_to_door(map, pos, direction); + TilePos door = pos; + for (size_t i = 0; i < tiles; i++){ + door = door.next(direction); + } + if (tiles == 0 || map.tiles.at(door) != Pokemon::TileKind::DOOR){ + return TAPS_TO_BANNER; + } + most = std::max(most, tiles); + } + }catch (...){ + return TAPS_TO_BANNER; + } + return most == 0 ? TAPS_TO_BANNER : most + 2; +} +} // namespace + // A STEP "to_banner": D-pad taps toward a door or cave mouth until the fade // and pose_after's map's location banner. No banner fails the step right -// there. -Outcome StoryWalkSteps::tap_to_banner(const StoryStep& step){ +// there; a banner before any tap means the walk before took us through. +Outcome StoryWalkSteps::tap_to_banner(const Pose& from, const StoryStep& step){ const std::string map = step.pose_after ? step.pose_after->map : ""; - const std::optional taps = m_io.tap_to_banner(step.direction, map, 30); + const size_t limit = taps_to_banner(from, step.direction); + const std::optional taps = m_io.tap_to_banner(step.direction, map, limit); if (!taps){ - return Pokemon::outcome_failed("no_banner", map); + return Pokemon::outcome_failed("no_banner", std::format("{} in {} taps {}: through already, its banner gone?", + map, limit, direction_name(step.direction))); + } + if (*taps == 0){ + log(std::format("[{}] {}: {}'s banner before any tap: through already.", m_row, step.name, map)); + }else{ + log(std::format("[{}] {}: {}'s banner after {} taps {}.", m_row, step.name, map, *taps, direction_name(step.direction))); } - log(std::format("[{}] {}: {}'s banner after {} taps {}.", m_row, step.name, map, *taps, direction_name(step.direction))); return Pokemon::outcome_ok(); } @@ -340,7 +376,7 @@ Outcome StoryWalkSteps::legs(RunState& state, const StoryStep& step){ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ if (step.variant == "to_banner"){ turn(step.direction); - return tap_to_banner(step); + return tap_to_banner(state.pose, step); } if (step.variant == "tap"){ // No separate turn tap first: at 1 tile from the door, a turn tap diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index a25435dd55..a7c4aad024 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -75,7 +75,7 @@ class StoryWalkSteps{ Pokemon::Outcome counted_wall(const Pokemon::Pose& from, const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_dialogue(const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_map(const Pokemon::StoryStep& step); - Pokemon::Outcome tap_to_banner(const Pokemon::StoryStep& step); + Pokemon::Outcome tap_to_banner(const Pokemon::Pose& from, const Pokemon::StoryStep& step); void turn(Pokemon::Direction direction); void log(const std::string& text); 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 252f0ef541..4bacc207a3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp @@ -15,6 +15,7 @@ #include "Utils/PokemonBDSP_AutoStory_Location.h" #include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "Actions/PokemonBDSP_AutoStory_Talks.h" +#include "PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP_AutoStory_Walk_Tests.h" namespace PokemonAutomation{ @@ -120,6 +121,34 @@ UnitTestResult test_door_fade(Logger&){ return true; } +// A tap step's fade is a real one: black, or a drop to dark from the look +// before the tap. The Oreburgh Gate's floor, about 46 before and after a +// tap inside it, is no fade: read as one, the tap into the Gate from +// Oreburgh, already through, waited 8 s for a banner gone (lab-B, +// 2026-11-08 15:31 to 15:54). +UnitTestResult test_tap_fade(Logger&){ + struct Case{ + std::string name; + double before; + double after; + bool faded; + }; + const std::vector cases{ + {.name = "inside the Gate, its floor", .before = 46, .after = 46, .faded = false}, + {.name = "inside the Gate, a darker patch", .before = 52, .after = 44, .faded = false}, + {.name = "on a street", .before = 120, .after = 112, .faded = false}, + {.name = "the street into the Gate's mouth, to black", .before = 120, .after = 8, .faded = true}, + {.name = "the street into a cave, a dim fade (45 to 64 measured)", .before = 120, .after = 60, .faded = true}, + {.name = "out of the Gate, from its floor to black", .before = 46, .after = 12, .faded = true}, + }; + for (const Case& item : cases){ + if (tap_faded(item.before, item.after) != item.faded){ + return item.name + (item.faded ? ": no fade read." : ": read as a fade."); + } + } + return true; +} + UnitTestResult test_location_banner(Logger&){ struct Case{ @@ -285,6 +314,10 @@ const AutoStoryWalkCase AUTO_STORY_WALK_CASES[] = { .input = {"out of a door needs its fade", test_door_fade}, .expectation = {}, }, + { + .input = {"a tap into a door fades to black or drops to dark, not a dim floor (lab-B, 2026-11-08)", test_tap_fade}, + .expectation = {}, + }, { .input = {"location banner match", test_location_banner}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 190f7409da..11ccb344d4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -562,6 +562,30 @@ UnitTestResult test_roarks_room_from_a_row_off(Logger& logger){ return true; } +// lab-B 2026-11-08 15:31 to 15:54: 01.05's open walk west 3 from (5, 13), +// where Barry's push leaves us, to (2, 13) beside the Oreburgh Gate's mouth +// (1, 13) went on into the Gate. D-pad taps move whole tiles but keep a +// part-tile offset: 0.375 of a tile west of (5, 13), the three taps take +// the warp; on the tile, they stop beside it. +UnitTestResult test_gate_walk_part_tile_off(Logger&){ + const StoryWorld& world = *story_plan_world("OreburghCity", "OreburghCity"); + for (const bool off : {false, true}){ + GridSim sim({.world = &world}, story_to_world(world, "OreburghCity", {5, 13}), Direction::WEST, true); + if (off){ + sim.tap(Direction::WEST, 60ms, true); + } + SimStop stop = SimStop::DONE; + for (int tap = 0; tap < 3 && stop == SimStop::DONE; tap++){ + stop = sim.tap(Direction::WEST, 160ms, false).stop; + } + if ((stop == SimStop::WARP) != off){ + return std::format("{} (5, 13): three taps west ended {} at {}.", off ? "0.375 west of" : "on", + sim_stop_name(stop), to_string(sim.player().pos)); + } + } + return true; +} + UnitTestResult test_wandering_npc_mechanics(Logger& logger){ StoryWorld world = make_world({ "#######", @@ -909,6 +933,10 @@ const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { .input = {"01.03, Oreburgh Mine B1F entrance hall corridor runs to and back", test_oreburgh_mine_hall_corridor}, .expectation = {}, }, + { + .input = {"01.05, a part of a tile off, the old open walk west takes the Gate's warp (lab-B, 2026-11-08)", test_gate_walk_part_tile_off}, + .expectation = {}, + }, }; void add_tests_AutoStory_GridSim(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp index 1d7c4db01e..657513f382 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp @@ -73,6 +73,16 @@ StoryStep old_coal_room_crate_cut(){ return step; } +StoryStep old_tap_into_the_gate(){ + StoryStep step; + step.kind = StoryStepKind::STEP; + step.name = "into_oreburgh_gate"; + step.direction = Direction::WEST; + step.variant = "to_banner"; + step.pose_after = Pokemon::tile_pose("OreburghGate", {TilePos{27, 22}, TilePos{26, 22}}, Direction::WEST); + return step; +} + } // namespace PokemonBDSP diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h index a9dabdf0bb..580eb84f32 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h @@ -41,6 +41,10 @@ Pokemon::StoryStep old_mine_hall_19(std::string name, Pokemon::Direction directi // hits the wooden crate at (29, 28) on the south leg, a tile down. Pokemon::StoryStep old_coal_room_crate_cut(); +// 01.05's old tap into the Oreburgh Gate, west to its banner, after an +// open walk to the tile beside its mouth (1, 13) that slid onto the warp: +// the tap step began inside the Gate (lab-B 2026-11-08 15:31 to 15:54). +Pokemon::StoryStep old_tap_into_the_gate(); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 753d084692..5f6a1a86b7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -71,13 +71,18 @@ using Pokemon::TilePos; // (run_until_map()) of the run goes unseen, though the player did go // through. The console missed both (r75, r81). The `dark`th door run reads // dark SIM_FALSE_DARK in, short of the door, as lab-B's did on 2026-11-08. -// The counts and flags below are the run's: how many fades and banners it -// looked for, whether a miss happened since the executor last looked, and -// whether a missed fade is still unseen. +// The `through`th tap step (tap_to_banner(), from 0) starts on its far side, +// its banner gone unless `through_banner`: the walk before it slid onto the +// warp (lab-B 2026-11-08). The counts and flags below are the run's: how +// many fades and banners it looked for, whether a miss happened since the +// executor last looked, and whether a missed fade is still unseen. struct SimMisses{ std::optional fade; std::optional banner; std::optional dark = {}; + std::optional through = {}; + bool through_banner = false; + size_t tap_steps = 0; size_t fades = 0; size_t banners = 0; size_t doors = 0; @@ -227,10 +232,17 @@ bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, cons } // D-pad taps, each looked at, until the fade and then the banner (the -// console's ConsoleStoryStepIO::tap_to_banner()). Each look stands still, -// so a banner on the far side reads at once. A fade seen ends the taps, +// console's ConsoleStoryStepIO::tap_to_banner()): none if the banner shows +// before the first. Each look stands still, so a banner on the far side +// reads at once. A fade seen ends the taps, // banner or not; with the fade missed the next look still sees the banner. std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ + if (m_misses.through == m_misses.tap_steps++){ + m_misses.missed = true; + if (m_far_side() && m_misses.through_banner){ + return 0; + } + } bool crossed = false; for (size_t tap = 1; tap <= max_taps; tap++){ const SimMove move = m_sim.tap(direction, 160ms, false); @@ -823,6 +835,26 @@ UnitTestResult test_exit_ravaged_path(Logger& logger){ return run_exit_test(logger, "01.09", r81_old_cave_exit(), SimMisses{.fade = 0, .banner = std::nullopt}, r81_below_the_mouth()); } +// lab-B 2026-11-08 15:31 to 15:54: 01.05's walk to the tile beside the +// Oreburgh Gate's mouth slid onto the warp, and the tap step after it began +// inside the Gate. With its banner up, the step ends there with no tap and +// no fade (the clean run's fade into the Gate is not seen); with it gone, +// it fails a few taps on, not across the Gate. +UnitTestResult test_tap_through_already(Logger& logger, bool banner){ + const std::vector rows = table_with("01.05", old_tap_into_the_gate()); + SimExecutor clean(logger); + run_rows_on(clean, logger, {.from = "01.05", .to = "01.05"}, rows); + SimExecutor through(logger, {.fade = {}, .banner = {}, .through = 1, .through_banner = banner}); + run_rows_on(through, logger, {.from = "01.05", .to = "01.05"}, rows); + const SimRun& run = through.result(); + const std::optional at = run.world ? story_to_local(*run.world, "OreburghGate", run.end) : std::nullopt; + const bool passed = banner + ? run.error.empty() && through.misses().fades + 1 == clean.misses().fades + : run.failed_step == "01.05 into_oreburgh_gate" && at && at->y == 22 && at->x >= 21; + return passed ? UnitTestResult(true) : UnitTestResult(std::format("failed in '{}' on {} after {} fades (clean {}): {}", + run.failed_step, end_of(run), through.misses().fades, clean.misses().fades, run.error.empty() ? "no failure" : run.error)); +} + UnitTestResult test_story_sim_step_failure(Logger& logger, const std::string& row, const StoryStep& old_step, const std::string& expected_failed_step, const std::string& expected_error){ SimExecutor executor(logger); const std::vector rows = table_with(row, old_step); @@ -894,6 +926,12 @@ const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { }}, .expectation = {}}, {.input = {"r75, out of the Oreburgh Gate", test_exit_gate}, .expectation = {}}, {.input = {"r81, out of the Ravaged Path", test_exit_ravaged_path}, .expectation = {}}, + {.input = {"01.05, a tap step begun through the Gate's mouth, its banner up (lab-B, 2026-11-08)", [](Logger& logger){ + return test_tap_through_already(logger, true); + }}, .expectation = {}}, + {.input = {"01.05, a tap step begun through the Gate's mouth, its banner gone (lab-B, 2026-11-08)", [](Logger& logger){ + return test_tap_through_already(logger, false); + }}, .expectation = {}}, { .input = {"01.03, a dark frame 1.8 s down the mine's entrance hall is not its mouth (lab-B, 2026-11-08)", [](Logger& logger){ SimExecutor executor(logger, {.fade = {}, .banner = {}, .dark = 1}); From a6641e723c01f99d16fd54165e3e8c4c7b55839a Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 16:43:51 -0800 Subject: [PATCH 04/19] BDSP AutoStory: mark the tap step's fade and through-already checks as stopgaps Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index c0d9661af7..43df0cf73f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -278,6 +278,9 @@ TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const // FADE_DARKNESS is not a fade by itself, since a cave's floor is that dim // (the Oreburgh Gate's about 46, lab-B 2026-11-08), but a fade into a cave // from a lit street goes from about 120 to 45..64. +// TODO(#268 slice 3): stopgap. A uniform-screen fade watcher (the shared +// Black/WhiteScreen stddev test, as in upstream #1717) should replace this +// brightness drop; remove it once that watcher passes the Gate frames. constexpr double TAP_FADE_BLACK = 25; constexpr double TAP_FADE_DROP = 0.7; bool tap_faded(double before, double after){ @@ -322,6 +325,9 @@ bool ConsoleStoryStepIO::run_into_door(Direction direction, bool run, Millisecon // west into a pocket by Route 203's pond (r75). Taps during the fade are // eaten. The banner before the first tap means we are through already: // the walk before slid onto the warp (lab-B 2026-11-08 15:31). +// TODO(#268 slice 2): stopgap. The "through already" check sees only a +// banner still on screen; once walkers report the fade or banner they saw +// (WalkResult::warp), read that instead and remove this check. std::optional ConsoleStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ const std::string& banner = story_banner_name(map); m_context.wait_for_all_requests(); From 8758c353d16a4a9db69335bd809fe0b8e1a34c67 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 16:50:06 -0800 Subject: [PATCH 05/19] BDSP AutoStory: dump every story ROUTE step's planned legs to a golden file Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 283 ++++++++++++++++-- 1 file changed, 250 insertions(+), 33 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index a6797a9190..63b2207f8f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -5,6 +5,7 @@ */ #include +#include #include #include #include @@ -12,6 +13,7 @@ #include #include #include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Filesystem/FileIO.h" #include "Common/Cpp/TestRunners/UnitTest.h" #include "Pokemon/AutoStory/Pokemon_StoryEvents.h" #include "Pokemon/AutoStory/Pokemon_StorySteps.h" @@ -221,20 +223,70 @@ UnitTestResult test_route204_north_line(Logger& logger){ return true; } -// The legs a ROUTE step from `from` plans, as walk_route() plans them (the -// step's costs, then the default ones), on `world`; nothing if none. -std::optional> route_step_plan(const StoryWorld& world, const Pokemon::Pose& from, const Pokemon::StoryStep& step){ - std::vector start; - for (const TilePos& pos : Pokemon::tiles_of(from)){ - start.push_back(story_to_world(world, from.map, pos)); +// A ROUTE step of the table, and where the steps before it in its row leave +// the player: the row's start, then each step's target or pose_after. A LEGS +// or STEP step that does not say where it ends leaves the start unknown. +struct TableRoute{ + std::string row; + const Pokemon::StoryStep* step; + std::optional from; + // The world the step is planned on; none if the start is unknown or no + // world joins its map and the target's. + const StoryWorld* world; +}; + +std::optional pose_after_step(const std::optional& at, const Pokemon::StoryStep& step){ + if (step.kind == StoryStepKind::ROUTE){ + return step.target; } - std::vector targets; - for (const TilePos& pos : Pokemon::tiles_of(*step.target)){ - targets.push_back(story_to_world(world, step.target->map, pos)); + if (step.pose_after){ + return step.pose_after; } + return step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP ? std::nullopt : at; +} + +std::vector table_routes(){ + std::vector routes; + for (const StoryCheckpoint& row : story_checkpoints()){ + std::optional at = row.start; + for (const Pokemon::StoryStep& step : row.steps){ + if (step.kind == StoryStepKind::ROUTE){ + const bool known = at && !Pokemon::tiles_of(*at).empty(); + routes.push_back({row.id, &step, at, known ? story_plan_world(at->map, step.target->map) : nullptr}); + } + at = pose_after_step(at, step); + } + } + return routes; +} + +std::vector world_tiles(const StoryWorld& world, const Pokemon::Pose& pose){ + std::vector tiles; + for (const TilePos& pos : Pokemon::tiles_of(pose)){ + tiles.push_back(story_to_world(world, pose.map, pos)); + } + return tiles; +} + +// The legs a table ROUTE step plans, as walk_route() plans them: the step's +// costs, then the default ones; no legs if neither plans. +struct RouteStepPlan{ + std::vector start; + std::optional> legs; + bool default_costs = false; // the step's own costs found no plan +}; + +RouteStepPlan plan_table_route(const TableRoute& route){ + const StoryWorld& world = *route.world; + const std::vector targets = world_tiles(world, *route.step->target); const auto goal = [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }; - std::optional> legs = plan_recovered_route(world, start, goal, *story_route_costs(step.variant)); - return legs ? legs : plan_recovered_route(world, start, goal, RobustPlanCosts()); + RouteStepPlan plan{.start = world_tiles(world, *route.from)}; + plan.legs = plan_recovered_route(world, plan.start, goal, *story_route_costs(route.step->variant)); + if (!plan.legs){ + plan.legs = plan_recovered_route(world, plan.start, goal, RobustPlanCosts()); + plan.default_costs = plan.legs.has_value(); + } + return plan; } // Why `planned` may slide into a door or a warp, or "": an open leg (not to @@ -259,32 +311,24 @@ std::string slides_into_door(const StoryWorld& world, const PlannedLeg& planned) // No ROUTE step of the table plans an open leg that ends before a door it // walks toward: a door is gone through by a step that runs or taps into it -// from where the route ends on a wall or off its line. Where a row's steps -// leave the player is followed from its start through each step's target -// or pose_after; a route from an unknown place is not checked. +// from where the route ends on a wall or off its line. A route from an +// unknown place is not checked. UnitTestResult test_story_routes_stop_short_of_doors(Logger& logger){ std::vector found; size_t checked = 0; - for (const StoryCheckpoint& row : story_checkpoints()){ - std::optional at = row.start; - for (const Pokemon::StoryStep& step : row.steps){ - const bool known = at && !Pokemon::tiles_of(*at).empty(); - const StoryWorld* world = step.kind == StoryStepKind::ROUTE && known - ? story_plan_world(at->map, step.target->map) : nullptr; - if (step.kind == StoryStepKind::ROUTE && world == nullptr){ - logger.log(std::format("{} {}: not checked, from {}.", row.id, step.name, at ? Pokemon::to_string(*at) : "nowhere known")); - } - const std::optional> legs = world ? route_step_plan(*world, *at, step) : std::nullopt; - checked += legs ? 1 : 0; - for (const PlannedLeg& planned : legs ? *legs : std::vector{}){ - const std::string why = slides_into_door(*world, planned); - if (!why.empty()){ - found.push_back(std::format("{} {}: {}.", row.id, step.name, why)); - } + for (const TableRoute& route : table_routes()){ + if (route.world == nullptr){ + logger.log(std::format("{} {}: not checked, from {}.", route.row, route.step->name, + route.from ? Pokemon::to_string(*route.from) : "nowhere known")); + continue; + } + const RouteStepPlan plan = plan_table_route(route); + checked += plan.legs ? 1 : 0; + for (const PlannedLeg& planned : plan.legs ? *plan.legs : std::vector{}){ + const std::string why = slides_into_door(*route.world, planned); + if (!why.empty()){ + found.push_back(std::format("{} {}: {}.", route.row, route.step->name, why)); } - at = step.kind == StoryStepKind::ROUTE ? step.target - : step.pose_after ? step.pose_after - : step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP ? std::nullopt : at; } } logger.log(std::format("{} routes planned.", checked)); @@ -296,6 +340,175 @@ UnitTestResult test_story_routes_stop_short_of_doors(Logger& logger){ } +// The route plan dump: every table ROUTE step's legs, in a golden file +// beside the story data, so a planner or table change shows its plans' diff +// in review. + +constexpr const char* ROUTE_PLANS_HEADER = + "BDSP AutoStory: the legs each ROUTE step of the story table plans.\n" + "Planned as the console's RouteWalker plans them: plan_recovered_route() on\n" + "story_plan_world(), from the tiles the row's steps before it leave the\n" + "player on, with the step's costs, then the default costs if those find none.\n" + "Written by the StoryTable test \"every ROUTE step plans as\n" + "Data/route_plans.golden.txt says\". After a planner or table change, run\n" + "that test with PA_UPDATE_ROUTE_PLANS=1 to rewrite this file\n" + "(PA_ROUTE_PLANS_GOLDEN= reads or writes another copy), and review\n" + "its diff.\n" + "turns: direction changes between legs. open: legs that stop in the open\n" + "(tapped, not held to a wall). localization: the wall holds at the start\n" + "that only bring several start tiles to one (plan_recovered_route()'s\n" + "anchor); 0 from one start tile.\n"; + +std::string tile_list(const StoryWorld& world, const std::vector& tiles){ + std::string out; + for (const TilePos& pos : tiles){ + out += (out.empty() ? "" : ", ") + describe(world, pos); + } + return out; +} + +// plan_recovered_route()'s wall holds from several start tiles: the legs up +// to where the tiles the player may be on first become one. +size_t localization_legs(const std::vector& start, const std::vector& legs){ + if (start.size() < 2){ + return 0; + } + for (size_t i = 0; i < legs.size(); i++){ + if (legs[i].after.size() == 1){ + return i + 1; + } + } + return 0; +} + +std::string plan_totals(const RouteStepPlan& plan){ + const std::vector& legs = *plan.legs; + size_t turns = 0; + size_t open = 0; + for (size_t i = 0; i < legs.size(); i++){ + turns += i > 0 && legs[i].leg.direction != legs[i - 1].leg.direction ? 1 : 0; + open += legs[i].leg.ends_at_wall ? 0 : 1; + } + return std::format(" totals: {} legs, {} turns, {} open, {} localization\n", + legs.size(), turns, open, localization_legs(plan.start, legs)); +} + +std::string dump_plan(const StoryWorld& world, const RouteStepPlan& plan){ + std::string out = " start candidates: " + tile_list(world, plan.start) + "\n"; + if (!plan.legs){ + return out + " NO PLAN\n"; + } + if (plan.default_costs){ + out += " the step's costs found no plan; planned with the default costs\n"; + } + for (size_t i = 0; i < plan.legs->size(); i++){ + const PlannedLeg& planned = (*plan.legs)[i]; + out += std::format(" {}. {} -> {}\n", i + 1, to_string(planned.leg), tile_list(world, planned.after)); + } + return out + plan_totals(plan); +} + +std::string dump_route(const TableRoute& route){ + const Pokemon::StoryStep& step = *route.step; + std::string out = std::format("== {} {} (costs: {})\n", route.row, step.name, step.variant.empty() ? "route" : step.variant); + out += " from: " + (route.from ? Pokemon::to_string(*route.from) : std::string("unknown")) + "\n"; + out += " target: " + Pokemon::to_string(*step.target) + "\n"; + if (route.world == nullptr){ + return out + (route.from && !Pokemon::tiles_of(*route.from).empty() + ? " not planned: no story world joins the two maps\n" + : " not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends)\n"); + } + return out + dump_plan(*route.world, plan_table_route(route)); +} + +std::string route_plans_text(){ + std::string out = ROUTE_PLANS_HEADER; + for (const TableRoute& route : table_routes()){ + out += "\n" + dump_route(route); + } + return out; +} + +// The golden file, in the Data folder beside this file's. +std::string route_plans_golden_path(){ + const char* path = std::getenv("PA_ROUTE_PLANS_GOLDEN"); + if (path != nullptr && path[0] != '\0'){ + return path; + } + const std::string self = __FILE__; + const size_t slash = self.find_last_of("/\\"); + return (slash == std::string::npos ? std::string() : self.substr(0, slash + 1)) + "Data/route_plans.golden.txt"; +} + +// `text` without carriage returns or a byte order mark. +std::string plain_lines(const std::string& text){ + std::string out = text.starts_with("\xef\xbb\xbf") ? text.substr(3) : text; + std::erase(out, '\r'); + return out; +} + +// `text` split into the header and one block per "== " step line. +std::vector plan_blocks(const std::string& text){ + std::vector blocks{""}; + size_t begin = 0; + while (begin < text.size()){ + const size_t end = std::min(text.find('\n', begin), text.size() - 1) + 1; + const std::string line = text.substr(begin, end - begin); + if (line.starts_with("== ")){ + blocks.push_back(""); + } + blocks.back() += line; + begin = end; + } + return blocks; +} + +// Each step whose block changed, as "-" (golden) and "+" (planned) blocks. +std::string plan_differences(const std::string& golden, const std::string& planned){ + const std::vector expected = plan_blocks(golden); + const std::vector actual = plan_blocks(planned); + std::string out; + size_t changed = 0; + for (size_t i = 0; i < std::max(expected.size(), actual.size()); i++){ + const std::string& was = i < expected.size() ? expected[i] : ""; + const std::string& now = i < actual.size() ? actual[i] : ""; + if (was != now && changed++ < 5){ + out += "\n--- golden:\n" + was + "+++ planned:\n" + now; + } + } + return changed == 0 ? "" : std::format("{} block(s) differ, the first ones:{}", changed, out); +} + +// Every table ROUTE step plans the legs the golden file lists. +UnitTestResult test_route_plans_golden(Logger& logger){ + const std::string path = route_plans_golden_path(); + const std::string planned = route_plans_text(); + const char* update = std::getenv("PA_UPDATE_ROUTE_PLANS"); + if (update != nullptr && update[0] != '\0' && update[0] != '0'){ + std::string crlf; + for (char ch : planned){ + crlf += ch == '\n' ? std::string("\r\n") : std::string(1, ch); + } + FileIO file; + if (!file.open(path, FileMode::WRITE | FileMode::BINARY) || file.write(crlf) != crlf.size()){ + return "Could not write " + path + "."; + } + logger.log("Wrote " + path + "."); + return true; + } + std::string golden; + if (!file_to_string(path, golden)){ + return "Could not read " + path + " (set PA_ROUTE_PLANS_GOLDEN to its path)."; + } + const std::string differences = plan_differences(plain_lines(golden), planned); + if (differences.empty()){ + return true; + } + return "The route plans differ from " + path + ". If the change is meant, rerun with PA_UPDATE_ROUTE_PLANS=1 " + "and review the file's diff. " + differences; +} + + struct AutoStoryStoryTableInput{ std::string name; std::function body; @@ -351,6 +564,10 @@ const AutoStoryStoryTableCase AUTO_STORY_STORY_TABLE_CASES[] = { .input = {"Story table: no open leg ends before a door it walks toward (lab-B, 2026-11-08)", test_story_routes_stop_short_of_doors}, .expectation = {}, }, + { + .input = {"Story table: every ROUTE step plans as Data/route_plans.golden.txt says", test_route_plans_golden}, + .expectation = {}, + }, }; void add_tests_AutoStory_StoryTable(UnitTestDatabase& database){ From b73ffa53a1a8bf982cf118c3cc9884ece33cca1f Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 16:51:07 -0800 Subject: [PATCH 06/19] BDSP AutoStory: the story's route plans golden file Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Data/route_plans.golden.txt | 462 ++++++++++++++++++ 1 file changed, 462 insertions(+) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt new file mode 100644 index 0000000000..33677f8d33 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt @@ -0,0 +1,462 @@ +BDSP AutoStory: the legs each ROUTE step of the story table plans. +Planned as the console's RouteWalker plans them: plan_recovered_route() on +story_plan_world(), from the tiles the row's steps before it leave the +player on, with the step's costs, then the default costs if those find none. +Written by the StoryTable test "every ROUTE step plans as +Data/route_plans.golden.txt says". After a planner or table change, run +that test with PA_UPDATE_ROUTE_PLANS=1 to rewrite this file +(PA_ROUTE_PLANS_GOLDEN= reads or writes another copy), and review +its diff. +turns: direction changes between legs. open: legs that stop in the open +(tapped, not held to a wall). localization: the wall holds at the start +that only bring several start tiles to one (plan_recovered_route()'s +anchor); 0 from one start tile. + +== 00.01 below_the_flute (costs: route) + from: PlayerHouse2F (4, 6) facing north (tile) + target: PlayerHouse2F (7, 5) facing north (tile) + start candidates: PlayerHouse2F (4, 6) + 1. north 1 (to wall) -> PlayerHouse2F (4, 5) + 2. east 3 (open) -> PlayerHouse2F (7, 5) + totals: 2 legs, 1 turns, 1 open, 0 localization + +== 00.01 above_the_door (costs: route) + from: PlayerHouse1F (10, 3) (10, 4) (set) + target: PlayerHouse1F (6, 9) facing south (tile) + start candidates: PlayerHouse1F (10, 3), PlayerHouse1F (10, 4) + 1. north 1 (to wall) -> PlayerHouse1F (10, 3) + 2. south 6 (open) -> PlayerHouse1F (10, 9) + 3. west 4 (open) -> PlayerHouse1F (6, 9) + totals: 3 legs, 2 turns, 2 open, 1 localization + +== 00.01 short_of_barrys_door (costs: route) + from: TwinleafTown (20, 22) facing south (tile) + target: TwinleafTown (10, 12) facing west (tile) + start candidates: Twinleaf Town (20, 22) + 1. west 7 (open) -> Twinleaf Town (13, 22) + 2. north 10 (to wall) -> Twinleaf Town (13, 12) + 3. west 3 (open) -> Twinleaf Town (10, 12) + totals: 3 legs, 2 turns, 2 open, 0 localization + +== 00.01 below_barrys_stairs (costs: route) + from: unknown + target: RivalHouse1F (2, 3) facing east (tile) + not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends) + +== 00.01 above_barrys_stairs (costs: route) + from: RivalHouse2F (3, 5) facing north (tile) + target: RivalHouse2F (3, 4) facing west (tile) + start candidates: RivalHouse2F (3, 5) + 1. north 1 (to wall) -> RivalHouse2F (3, 4) + totals: 1 legs, 0 turns, 0 open, 0 localization + +== 00.01 above_barrys_door (costs: route) + from: RivalHouse1F (2, 3) (tile) + target: RivalHouse1F (6, 9) facing south (tile) + start candidates: RivalHouse1F (2, 3) + 1. south 6 (open) -> RivalHouse1F (2, 9) + 2. east 4 (open) -> RivalHouse1F (6, 9) + totals: 2 legs, 1 turns, 2 open, 0 localization + +== 00.01 below_the_lake_entrance (costs: route) + from: unknown + target: VerityLakefront (17, 14) facing north (tile) + not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends) + +== 00.03 short_of_rowan (costs: route) + from: VerityLakefront (17, 14) (17, 15) (set) + target: Route201 (4, 14) facing east (tile) + start candidates: Verity Lakefront (17, 14), Verity Lakefront (17, 15) + 1. north 4 (to wall) -> Verity Lakefront (17, 11) + 2. south 10 (to wall) -> Verity Lakefront (17, 21) + 3. east 19 (open) -> Route 201 (4, 14) + totals: 3 legs, 2 turns, 1 open, 1 localization + +== 00.03 by_the_counter (costs: route) + from: PlayerHouse1F (5, 8) (6, 8) facing east (set) + target: PlayerHouse1F (4, 8) facing west (tile) + start candidates: PlayerHouse1F (5, 8), PlayerHouse1F (6, 8) + 1. west 2 (to wall) -> PlayerHouse1F (4, 8) + totals: 1 legs, 0 turns, 0 open, 1 localization + +== 00.03 short_of_dawn (costs: route) + from: TwinleafTown (20, 22) facing south (tile) + target: Route201 (63, 5) facing east (tile) + start candidates: Twinleaf Town (20, 22) + 1. west 3 (open) -> Twinleaf Town (17, 22) + 2. north 34 (to wall) -> Route 201 (17, 13) + 3. east 40 (to wall) -> Route 201 (57, 13) + 4. west 7 (open) -> Route 201 (50, 13) + 5. north 10 (to wall) -> Route 201 (50, 3) + 6. east 13 (to wall) -> Route 201 (63, 3) + 7. south 2 (open) -> Route 201 (63, 5) + totals: 7 legs, 6 turns, 3 open, 0 localization + +== 00.04 onto_the_path (costs: town) + from: SandgemTown (26, 11) (27, 11) (28, 11) (26, 12) (27, 12) (28, 12) facing north (set) + target: SandgemTown (29, 12) facing west (tile) + start candidates: Sandgem Town (26, 11), Sandgem Town (27, 11), Sandgem Town (28, 11), Sandgem Town (26, 12), Sandgem Town (27, 12), Sandgem Town (28, 12) + 1. east 3 (to wall) -> Sandgem Town (29, 11), Sandgem Town (29, 12) + 2. north 1 (to wall) -> Sandgem Town (29, 11) + 3. south 1 (open) -> Sandgem Town (29, 12) + totals: 3 legs, 2 turns, 1 open, 2 localization + +== 00.04 to_ledge_column (costs: line) + from: Route201 (57, 5) (58, 5) (59, 5) (60, 5) (61, 5) (62, 5) (63, 5) facing west (set) + target: Route201 (55, 5) facing west (tile) + start candidates: Route 201 (57, 5), Route 201 (58, 5), Route 201 (59, 5), Route 201 (60, 5), Route 201 (61, 5), Route 201 (62, 5), Route 201 (63, 5) + 1. west 21 (to wall) -> Route 201 (42, 5) + 2. east 13 (open) -> Route 201 (55, 5) + totals: 2 legs, 1 turns, 1 open, 1 localization + +== 00.04 along_route_201_road (costs: line) + from: Route201 (55, 14) facing south (tile) + target: Route201 (15, 14) facing west (tile) + start candidates: Route 201 (55, 14) + 1. west 16 (open) -> Route 201 (39, 14) + 2. north 3 (open) -> Route 201 (39, 11) + 3. west 24 (open) -> Route 201 (15, 11) + 4. south 2 (open) -> Route 201 (15, 14) + totals: 4 legs, 3 turns, 4 open, 0 localization + +== 00.04 into_twinleaf (costs: line) + from: Route201 (15, 14) facing west (tile) + target: TwinleafTown (15, 22) facing south (tile) + start candidates: Route 201 (15, 14) + 1. south 33 (open) -> Twinleaf Town (15, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.04 to_moms_doorstep (costs: line) + from: TwinleafTown (15, 22) facing south (tile) + target: TwinleafTown (20, 22) facing north (tile) + start candidates: Twinleaf Town (15, 22) + 1. east 5 (open) -> Twinleaf Town (20, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.04 beside_mom (costs: route) + from: PlayerHouse1F (6, 9) facing north (tile) + target: PlayerHouse1F (6, 8) facing east (tile) + start candidates: PlayerHouse1F (6, 9) + 1. north 1 (open) -> PlayerHouse1F (6, 8) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.04 short_of_the_catch_tutorial (costs: route) + from: TwinleafTown (19, 22) facing east (tile) + target: Route202 (22, 27) facing west (tile) + start candidates: Twinleaf Town (19, 22) + 1. west 2 (open) -> Twinleaf Town (17, 22) + 2. north 34 (to wall) -> Route 201 (17, 13) + 3. east 40 (to wall) -> Route 201 (57, 13) + 4. west 7 (open) -> Route 201 (50, 13) + 5. north 7 (open) -> Route 201 (50, 6) + 6. east 43 (to wall) -> Sandgem Town (29, 13) + 7. west 5 (open) -> Sandgem Town (24, 13) + 8. north 21 (to wall) -> Route 202 (25, 24) + 9. west 3 (to wall) -> Route 202 (22, 24) + 10. south 3 (open) -> Route 202 (22, 27) + totals: 10 legs, 9 turns, 5 open, 0 localization + +== 00.04b to_catch_grass (costs: route) + from: Route202 (15, 25) (16, 25) (17, 25) (18, 25) (19, 25) (20, 25) (21, 25) (15, 26) (16, 26) (17, 26) (18, 26) (19, 26) (20, 26) (21, 26) (15, 27) (16, 27) (17, 27) (18, 27) (19, 27) (20, 27) (21, 27) (21, 28) (21, 29) (set) + target: Route202 (18, 25) (19, 25) (20, 25) (18, 26) (19, 26) (20, 26) (18, 27) (19, 27) (20, 27) (set) + start candidates: Route 202 (15, 25), Route 202 (16, 25), Route 202 (17, 25), Route 202 (18, 25), Route 202 (19, 25), Route 202 (20, 25), Route 202 (21, 25), Route 202 (15, 26), Route 202 (16, 26), Route 202 (17, 26), Route 202 (18, 26), Route 202 (19, 26), Route 202 (20, 26), Route 202 (21, 26), Route 202 (15, 27), Route 202 (16, 27), Route 202 (17, 27), Route 202 (18, 27), Route 202 (19, 27), Route 202 (20, 27), Route 202 (21, 27), Route 202 (21, 28), Route 202 (21, 29) + 1. north 4 (to wall) -> Route 202 (15, 25), Route 202 (16, 25), Route 202 (17, 25), Route 202 (18, 25), Route 202 (19, 25), Route 202 (20, 25), Route 202 (21, 25) + 2. east 8 (to wall) -> Route 202 (23, 25) + 3. west 3 (open) -> Route 202 (20, 25) + totals: 3 legs, 2 turns, 1 open, 2 localization + +== 00.04b into_sandgem (costs: robust) + from: Route202 (18, 25) (19, 25) (20, 25) (18, 26) (19, 26) (20, 26) (18, 27) (19, 27) (20, 27) (set) + target: SandgemTown (29, 5) (tile) + start candidates: Route 202 (18, 25), Route 202 (19, 25), Route 202 (20, 25), Route 202 (18, 26), Route 202 (19, 26), Route 202 (20, 26), Route 202 (18, 27), Route 202 (19, 27), Route 202 (20, 27) + 1. north 2 (to wall) -> Route 202 (18, 25), Route 202 (19, 25), Route 202 (20, 25) + 2. east 5 (to wall) -> Route 202 (23, 25) + 3. south 6 (to wall) -> Route 202 (23, 31) + 4. east 7 (to wall) -> Route 202 (30, 31) + 5. south 6 (to wall) -> Sandgem Town (29, 5) + totals: 5 legs, 4 turns, 0 open, 2 localization + +== 00.04b to_center_sign (costs: town) + from: SandgemTown (29, 5) (tile) + target: SandgemTown (20, 11) (tile) + start candidates: Sandgem Town (29, 5) + 1. west 5 (open) -> Sandgem Town (24, 5) + 2. south 6 (open) -> Sandgem Town (24, 11) + 3. west 4 (open) -> Sandgem Town (20, 11) + totals: 3 legs, 2 turns, 3 open, 0 localization + +== 00.04d north_to_jubilife (costs: route) + from: Route202 (30, 24) (tile) + target: Route202 (11, 0) (12, 0) (13, 0) (14, 0) (15, 0) (16, 0) (17, 0) (18, 0) (11, 1) (12, 1) (13, 1) (14, 1) (15, 1) (16, 1) (17, 1) (18, 1) (11, 2) (12, 2) (13, 2) (14, 2) (15, 2) (16, 2) (17, 2) (18, 2) (11, 3) (12, 3) (13, 3) (14, 3) (15, 3) (16, 3) (17, 3) (18, 3) (set) + start candidates: Route 202 (30, 24) + 1. south 2 (open) -> Route 202 (30, 26) + 2. west 27 (to wall) -> Route 202 (3, 26) + 3. north 12 (to wall) -> Route 202 (3, 14) + 4. east 14 (to wall) -> Route 202 (17, 14) + 5. south 8 (to wall) -> Route 202 (17, 22) + 6. east 13 (to wall) -> Route 202 (30, 22) + 7. north 18 (to wall) -> Route 202 (30, 4) + 8. south 1 (open) -> Route 202 (30, 5) + 9. west 12 (open) -> Route 202 (18, 5) + 10. north 2 (open) -> Route 202 (18, 3) + totals: 10 legs, 9 turns, 4 open, 0 localization + +== 00.05 to_the_center (costs: town) + from: unknown + target: JubilifeCity (52, 41) facing north (tile) + not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends) + +== 00.05 to_the_school (costs: town) + from: JubilifeCity (52, 41) facing north (tile) + target: JubilifeCity (40, 41) facing north (tile) + start candidates: Jubilife City (52, 41) + 1. west 12 (open) -> Jubilife City (40, 41) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.05b below_the_presidents_trigger (costs: town) + from: JubilifeCity (40, 41) facing south (tile) + target: JubilifeCity (46, 41) facing north (tile) + start candidates: Jubilife City (40, 41) + 1. east 6 (open) -> Jubilife City (46, 41) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.05b below_the_mart_clown (costs: town) + from: unknown + target: JubilifeCity (55, 34) facing north (tile) + not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends) + +== 00.05b below_the_tv_clown (costs: town) + from: JubilifeCity (55, 34) facing north (tile) + target: JubilifeCity (36, 17) facing north (tile) + start candidates: Jubilife City (55, 34) + 1. west 23 (to wall) -> Jubilife City (32, 34) + 2. north 18 (to wall) -> Jubilife City (32, 16) + 3. south 1 (open) -> Jubilife City (32, 17) + 4. east 4 (open) -> Jubilife City (36, 17) + totals: 4 legs, 3 turns, 2 open, 0 localization + +== 00.05b below_the_company_clown (costs: town) + from: JubilifeCity (36, 17) facing north (tile) + target: JubilifeCity (15, 19) facing north (tile) + start candidates: Jubilife City (36, 17) + 1. south 4 (open) -> Jubilife City (36, 21) + 2. west 21 (open) -> Jubilife City (15, 21) + 3. north 2 (open) -> Jubilife City (15, 19) + totals: 3 legs, 2 turns, 3 open, 0 localization + +== 00.05c to_main_boulevard (costs: line) + from: JubilifeCity (15, 19) facing north (tile) + target: JubilifeCity (15, 22) facing south (tile) + start candidates: Jubilife City (15, 19) + 1. south 3 (open) -> Jubilife City (15, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.05c along_main_boulevard (costs: line) + from: JubilifeCity (15, 22) facing south (tile) + target: JubilifeCity (45, 22) facing south (tile) + start candidates: Jubilife City (15, 22) + 1. east 30 (open) -> Jubilife City (45, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.05c beside_the_president (costs: line) + from: JubilifeCity (45, 22) facing south (tile) + target: JubilifeCity (45, 35) facing east (tile) + start candidates: Jubilife City (45, 22) + 1. south 13 (open) -> Jubilife City (45, 35) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.05c to_the_route_203_street (costs: line) + from: JubilifeCity (45, 35) facing east (tile) + target: JubilifeCity (58, 22) facing east (tile) + start candidates: Jubilife City (45, 35) + 1. north 13 (open) -> Jubilife City (45, 22) + 2. east 13 (open) -> Jubilife City (58, 22) + totals: 2 legs, 1 turns, 2 open, 0 localization + +== 01.01 west_of_barrys_trigger (costs: town) + from: JubilifeCity (58, 22) facing east (tile) + target: Route203 (4, 18) facing east (tile) + start candidates: Jubilife City (58, 22) + 1. east 9 (open) -> Route 203 (4, 18) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.02 by_the_gate (costs: route) + from: Route203 (5, 20) facing south (tile) + target: Route203 (55, 9) facing east (tile) + start candidates: Route 203 (5, 20) + 1. north 2 (open) -> Route 203 (5, 18) + 2. east 50 (to wall) -> Route 203 (55, 18) + 3. north 9 (open) -> Route 203 (55, 9) + totals: 3 legs, 2 turns, 2 open, 0 localization + +== 01.02 west_of_the_hikers_trigger (costs: route) + from: OreburghGate (4, 22) (5, 22) facing east (set) + target: OreburghGate (6, 22) facing east (tile) + start candidates: OreburghGate (4, 22), OreburghGate (5, 22) + 1. south 1 (to wall) -> OreburghGate (4, 23), OreburghGate (5, 23) + 2. west 1 (to wall) -> OreburghGate (4, 23) + 3. east 2 (to wall) -> OreburghGate (6, 23) + 4. north 1 (open) -> OreburghGate (6, 22) + totals: 4 legs, 3 turns, 1 open, 2 localization + +== 01.02 past_curtis (costs: route) + from: OreburghGate (7, 22) facing east (tile) + target: OreburghGate (20, 22) facing east (tile) + start candidates: OreburghGate (7, 22) + 1. east 13 (open) -> OreburghGate (20, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.02 by_the_east_mouth (costs: route) + from: OreburghGate (20, 22) facing east (tile) + target: OreburghGate (26, 22) facing east (tile) + start candidates: OreburghGate (20, 22) + 1. east 6 (open) -> OreburghGate (26, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.02 west_of_the_welcome (costs: route) + from: OreburghCity (2, 13) (3, 13) facing east (set) + target: OreburghCity (9, 13) facing east (tile) + start candidates: Oreburgh City (2, 13), Oreburgh City (3, 13) + 1. north 3 (to wall) -> Oreburgh City (2, 10), Oreburgh City (3, 10) + 2. west 1 (to wall) -> Oreburgh City (2, 10) + 3. south 3 (open) -> Oreburgh City (2, 13) + 4. east 7 (open) -> Oreburgh City (9, 13) + totals: 4 legs, 3 turns, 2 open, 2 localization + +== 01.02b below_the_centers_door (costs: town) + from: OreburghCity (26, 22) facing north (tile) + target: OreburghCity (47, 21) facing north (tile) + start candidates: Oreburgh City (26, 22) + 1. east 22 (to wall) -> Oreburgh City (48, 22) + 2. north 1 (to wall) -> Oreburgh City (48, 21) + 3. west 1 (open) -> Oreburgh City (47, 21) + totals: 3 legs, 2 turns, 1 open, 0 localization + +== 01.03 above_the_mine (costs: town) + from: OreburghCity (47, 21) (46, 21) facing south (set) + target: OreburghCity (46, 57) facing south (tile) + start candidates: Oreburgh City (47, 21), Oreburgh City (46, 21) + 1. east 2 (to wall) -> Oreburgh City (48, 21) + 2. south 28 (to wall) -> Oreburgh City (48, 49) + 3. west 2 (open) -> Oreburgh City (46, 49) + 4. south 8 (open) -> Oreburgh City (46, 57) + totals: 4 legs, 3 turns, 2 open, 1 localization + +== 01.05 east_of_barrys_trigger (costs: town) + from: OreburghCity (26, 21) (26, 22) facing south (set) + target: OreburghCity (7, 13) facing west (tile) + start candidates: Oreburgh City (26, 21), Oreburgh City (26, 22) + 1. south 5 (to wall) -> Oreburgh City (26, 26) + 2. west 2 (to wall) -> Oreburgh City (24, 26) + 3. north 5 (to wall) -> Oreburgh City (24, 21) + 4. west 9 (open) -> Oreburgh City (15, 21) + 5. north 8 (open) -> Oreburgh City (15, 13) + 6. west 8 (open) -> Oreburgh City (7, 13) + totals: 6 legs, 5 turns, 3 open, 1 localization + +== 01.05 through_the_gate (costs: route) + from: OreburghGate (27, 22) (26, 22) facing west (set) + target: OreburghGate (5, 22) facing west (tile) + start candidates: OreburghGate (27, 22), OreburghGate (26, 22) + 1. north 2 (to wall) -> OreburghGate (27, 20), OreburghGate (26, 21) + 2. east 1 (to wall) -> OreburghGate (27, 20), OreburghGate (27, 21) + 3. north 1 (to wall) -> OreburghGate (27, 20) + 4. south 3 (to wall) -> OreburghGate (27, 23) + 5. west 19 (to wall) -> OreburghGate (8, 23) + 6. north 1 (to wall) -> OreburghGate (8, 22) + 7. west 3 (open) -> OreburghGate (5, 22) + totals: 7 legs, 6 turns, 1 open, 3 localization + +== 01.06 below_rowans_trigger (costs: town) + from: Route203 (55, 9) facing west (tile) + target: JubilifeCity (47, 8) facing north (tile) + start candidates: Route 203 (55, 9) + 1. south 10 (to wall) -> Route 203 (55, 19) + 2. west 17 (to wall) -> Route 203 (38, 19) + 3. north 1 (open) -> Route 203 (38, 18) + 4. west 57 (open) -> Jubilife City (44, 22) + 5. north 14 (to wall) -> Jubilife City (44, 8) + 6. east 3 (to wall) -> Jubilife City (47, 8) + totals: 6 legs, 5 turns, 2 open, 0 localization + +== 01.08 below_the_ravaged_path (costs: town) + from: JubilifeCity (44, 5) facing west (tile) + target: Route204South (11, 2) facing north (tile) + start candidates: Jubilife City (44, 5) + 1. east 1 (open) -> Jubilife City (45, 5) + 2. north 35 (to wall) -> Route 204 (13, 2) + 3. west 2 (to wall) -> Route 204 (11, 2) + totals: 3 legs, 2 turns, 1 open, 0 localization + +== 01.09 west_of_the_rock (costs: route) + from: RavagedPath (19, 50) facing north (tile) + target: RavagedPath (21, 43) facing east (tile) + start candidates: RavagedPath (19, 50) + 1. north 7 (open) -> RavagedPath (19, 43) + 2. east 2 (open) -> RavagedPath (21, 43) + totals: 2 legs, 1 turns, 2 open, 0 localization + +== 01.09 above_the_way_out (costs: route) + from: RavagedPath (21, 43) facing east (tile) + target: RavagedPath (28, 44) facing south (tile) + start candidates: RavagedPath (21, 43) + 1. east 8 (to wall) -> RavagedPath (29, 43) + 2. south 1 (to wall) -> RavagedPath (29, 44) + 3. west 1 (open) -> RavagedPath (28, 44) + totals: 3 legs, 2 turns, 1 open, 0 localization + +== 01.10 line_1 (costs: line) + from: Route204North (20, 26) facing south (tile) + target: Route204North (20, 27) (tile) + start candidates: Route 204 (20, 26) + 1. south 1 (open) -> Route 204 (20, 27) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.10 line_2 (costs: line) + from: Route204North (20, 27) (tile) + target: Route204North (11, 27) (tile) + start candidates: Route 204 (20, 27) + 1. west 9 (open) -> Route 204 (11, 27) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.10 line_3 (costs: line) + from: Route204North (11, 27) (tile) + target: Route204North (11, 22) (tile) + start candidates: Route 204 (11, 27) + 1. north 5 (open) -> Route 204 (11, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.10 line_4 (costs: line) + from: Route204North (11, 22) (tile) + target: Route204North (19, 22) (tile) + start candidates: Route 204 (11, 22) + 1. east 8 (open) -> Route 204 (19, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.10 line_5 (costs: line) + from: Route204North (19, 22) (tile) + target: Route204North (19, 12) (tile) + start candidates: Route 204 (19, 22) + 1. north 10 (open) -> Route 204 (19, 12) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.10 line_6 (costs: line) + from: Route204North (19, 12) (tile) + target: Route204North (11, 12) (tile) + start candidates: Route 204 (19, 12) + 1. west 8 (open) -> Route 204 (11, 12) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.10 line_7 (costs: line) + from: Route204North (11, 12) (tile) + target: Route204North (11, 5) (tile) + start candidates: Route 204 (11, 12) + 1. north 7 (open) -> Route 204 (11, 5) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.10 into_floaroma (costs: line) + from: Route204North (11, 5) (tile) + target: FloaromaTown (11, 29) facing north (tile) + start candidates: Route 204 (11, 5) + 1. north 8 (open) -> Floaroma Town (11, 29) + totals: 1 legs, 0 turns, 1 open, 0 localization From afe4c45a3b05149e22ee1b0e8719a1e3b25fe39d Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 17:01:39 -0800 Subject: [PATCH 07/19] BDSP AutoStory: a wall leg that never moved waits, then plans from its start On lab-B (2026-11-08 16:50, 01.08 below_the_ravaged_path) the leg "west 2 (to wall)" from Route 204 (13, 2) stopped at once, 0 chunks moved: the youngster who wanders (12, 2) to (14, 2) stood a tile ahead. The wait for the way needed a stop three tiles short of the wall, so he was talked to at once, and the replan from both (12, 2) and (13, 2) found no plan: an uncertain start needs a wall both tiles reach, and no wall is anchored from a tile someone wanders on. A walk to the wall that never moved stopped where it began, so someone stands on the next tile: it now waits for the way on short legs too, and if they stay, the replan starts from the start tile alone with their tile marked. Two Planned route tests replay the run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...kemonBDSP_AutoStory_PlannedRoute_Tests.cpp | 128 ++++++++++++++++++ .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 27 +++- 2 files changed, 152 insertions(+), 3 deletions(-) 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 ca7f599636..bbd9056ff9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp @@ -17,8 +17,10 @@ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Data/PokemonBDSP_AutoStory_Maps.h" #include "Data/PokemonBDSP_AutoStory_StoryMaps.h" +#include "Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "Utils/PokemonBDSP_AutoStory_RouteIO.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_PlannedRoute_Tests.h" namespace PokemonAutomation{ @@ -352,6 +354,124 @@ UnitTestResult test_open_leg_known_trainer(Logger&){ } +// 01.08's walk below the Ravaged Path (lab-B 2026-11-08 16:50): the leg +// north up Route 204 South ended at (13, 2), and the leg "west 2 (to +// wall)" to (11, 2) stopped at once, 0 chunks moved: the wandering +// youngster (the map's youngster_3, wandering (12, 2) to (14, 2)) stood on +// (12, 2). The world joins Jubilife and Route 204 South, as the step's. +const StoryWorld& ravaged_path_world(){ + static const StoryWorld* const world = story_plan_world("JubilifeCity", "Route204South"); + return *world; +} +TilePos on_route204_south(TilePos local){ + return story_to_world(ravaged_path_world(), "Route204South", local); +} + +// The console's first walk west: blocked after 800 ms, no chunk moved. +ScriptStep west_never_moved(){ + return walk_step("wall: T: west 2 (to wall)", WalkStop::BLOCKED, 1050ms, 0); +} + +// A youngster who steps off the leg's next tile while we wait is waited +// out, on a leg of two tiles too: the walk west then reaches the wall at +// (11, 2). The wait used to need a stop at least three tiles short of the +// wall, so the person one tile ahead was talked to instead. +UnitTestResult test_short_leg_waits_for_the_way(Logger&){ + Script script{.steps = { + west_never_moved(), + press_step("wait 2500 ms x1"), + walk_step("wall: T: west 2 (to wall)", WalkStop::BLOCKED, 3000ms, 2), + answer_step("dialog within 500 ms", false), + }}; + ScriptedWalk walk; + try{ + walk = walk_script(ravaged_path_world(), on_route204_south({13, 2}), on_route204_south({11, 2}), {}, script); + }catch (const ScriptMismatch& e){ + return e.message; + } + if (!walk.failure.empty() || !walk.fights.empty()){ + return std::format("expected to wait and walk on; fought {}, failure \"{}\".", walk.fights.size(), walk.failure); + } + if (walk.at != std::vector{on_route204_south({11, 2})}){ + return "did not arrive at Route 204 South (11, 2)."; + } + const std::string left = script_left(script); + return left.empty() ? UnitTestResult(true) : UnitTestResult(left); +} + +// Whether the replan after the youngster's talk starts from (13, 2) alone, +// with (12, 2) marked, and plans a route. +std::string check_never_moved_replan(const Script& script){ + const std::string replan = check_replan_from(script, {"Route 204 (13, 2)"}); + if (!replan.empty()){ + return replan; + } + const auto replan_note = std::find_if(script.notes.begin(), script.notes.end(), [](const std::string& note){ + return note.find("planning again") != std::string::npos; + }); + if (replan_note->find("(12, 2)") != std::string::npos){ + return "the replan still starts from the youngster's tile: " + *replan_note; + } + const auto marked = std::find_if(script.notes.begin(), script.notes.end(), [](const std::string& note){ + return note.find("marked it") != std::string::npos; + }); + if (marked == script.notes.end() || marked->find("(12, 2)") == std::string::npos){ + return "the youngster's tile (12, 2) was not marked."; + } + const size_t plans = std::count_if(script.notes.begin(), script.notes.end(), [](const std::string& note){ + return note.find("legs planned") != std::string::npos; + }); + if (plans != 2){ + return std::format("{} plans made, expected the first and the replan.", plans); + } + return ""; +} + +// The youngster stays on (12, 2) through both waits and talks without a +// battle. The console then planned from {(12, 2), (13, 2)}, one tile per +// tile the walk may have moved, and found no plan: an uncertain start +// needs a wall both tiles reach (wall_recovery_candidates()), and no wall +// is anchored from a tile someone wanders on, which both are. A walk that +// never moved stopped where it began: the replan starts from (13, 2) +// alone, with the youngster's tile marked. +UnitTestResult test_never_moved_plans_from_the_start(Logger& logger){ + const StoryWorld& world = ravaged_path_world(); + const std::vector console_from{on_route204_south({12, 2}), on_route204_south({13, 2})}; + if (!wall_recovery_candidates(world, console_from).empty()){ + return "the console's two tiles have a wall to anchor on: the cause is not the wander box."; + } + logger.log("No wall anchors from Route 204 South (12, 2) and (13, 2): both are in youngster_3's wander box."); + Script script{.steps = { + west_never_moved(), + press_step("wait 2500 ms x1"), + west_never_moved(), + press_step("wait 2500 ms x1"), + west_never_moved(), + press_step("A 80 ms x1"), + answer_step("dialog within 2000 ms", true), + }}; + ScriptedWalk walk; + std::string stopped_at; + try{ + walk = walk_script(world, on_route204_south({13, 2}), on_route204_south({11, 2}), {}, script); + }catch (const ScriptMismatch& e){ + // The walk after the replan is not scripted. + stopped_at = e.message; + } + if (!walk.failure.empty()){ + return "failed: " + walk.failure; + } + if (script.next != script.steps.size()){ + return "stopped at: " + stopped_at; + } + for (const std::string& note : script.notes){ + logger.log(note); + } + const std::string replan = check_never_moved_replan(script); + return replan.empty() ? UnitTestResult(true) : UnitTestResult(replan); +} + + struct PlannedRouteInput{ std::string name; std::function body; @@ -399,6 +519,14 @@ const PlannedRouteCase PLANNED_ROUTE_CASES[] = { .input = {"a known trainer stops an open leg", test_open_leg_known_trainer}, .expectation = {}, }, + { + .input = {"a person a tile ahead on a short leg is waited out", test_short_leg_waits_for_the_way}, + .expectation = {}, + }, + { + .input = {"a wall leg that never moved plans from its start", test_never_moved_plans_from_the_start}, + .expectation = {}, + }, }; void add_tests_AutoStory_PlannedRoute(UnitTestDatabase& database){ 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 014870b7b5..45add5572c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -165,6 +165,19 @@ size_t tiles_moved(const WalkResult& walk, Milliseconds per_tile){ return moving.count() <= 0 ? (size_t)0 : (size_t)(moving / per_tile); } +// Whether a walk to the wall never moved: no chunk changed and its time +// counts no tile. It stopped where it began, so whoever stopped it stands +// on the next tile, however short the leg. On lab-B (2026-11-08 16:50, +// 01.08) Route 204's youngster, who wanders (12, 2) to (14, 2), stood a +// tile ahead of the leg "west 2 (to wall)" from (13, 2). The wait for the +// way needed a stop three tiles short of the wall, so he was talked to at +// once, and the replan from both (12, 2) and (13, 2) found no plan: an +// uncertain start needs a wall both tiles reach, and no wall is anchored +// from a tile someone wanders on. +bool never_moved(const WalkResult& walk, size_t walked_tiles){ + return walk.stop == WalkStop::BLOCKED && walk.moved_chunks == 0 && walked_tiles == 0; +} + // Whether a leg's walk goes on to the next leg or the route plans again. enum class LegNext{ NEXT_LEG, @@ -454,8 +467,13 @@ size_t RouteWalker::unstick_wall_leg(LegWalk& walk, size_t walked_tiles, size_t 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++){ + // walk to the wall again before calling it an obstacle. A walk that + // never moved waits on a short leg too (never_moved()). + const auto in_the_way = [&]{ + return walk.result.stop == WalkStop::BLOCKED && + (walked_tiles + 2 < nearest || (nearest > 0 && never_moved(walk.result, walked_tiles))); + }; + for (size_t again = 0; again < 2 && in_the_way(); again++){ 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); @@ -469,10 +487,13 @@ 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); + // A walk that never moved is where it began (never_moved()); any other + // stop may be a tile either side of the tiles its time counts. + const size_t last = never_moved(walk.result, walked_tiles) ? 0 : walked_tiles + 1; 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++){ + for (size_t k = walked_tiles == 0 ? 0 : walked_tiles - 1; k <= last && k <= path.size(); k++){ stopped.push_back(k == 0 ? pos : path[k - 1]); } } From e94a6550bcac33cb775ca42e8a4bbc25db5c121b Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 18:06:04 -0800 Subject: [PATCH 08/19] BDSP AutoStory: red tests for routes along wander zones and short wall legs On lab-B (2026-11-08, 01.08 below_the_ravaged_path) the plan "north 35 (to wall) to (13, 2), west 2 (to wall) to (11, 2)" walked along the row Route 204 South's youngster wanders, (12..14, 2). He stopped the leg west after 1 of 2 tiles; the check at the wall allowed a tile short on legs of two or three tiles, so the route logged arriving at (11, 2) from (13, 2). New tests, red on this commit: - Route planner: a leg may cross a row zone (one tile of it) but not run along it (two tiles, the start among them); no plan when the row is the only way. - Story table: every ROUTE step plans and none runs along a wander zone; 01.08's plan walks at most one tile of (12..14, 2). - Planned route: a 2-tile leg to a wall that ran out of time after 1 tile is a stop short of the wall, not the wall. The two #271 tests that replayed the console's leg along the youngster's row now replay it on a plain room: the planner will no longer plan it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...kemonBDSP_AutoStory_PlannedRoute_Tests.cpp | 69 ++++++-- ...kemonBDSP_AutoStory_RoutePlanner_Tests.cpp | 48 +++++- ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 163 ++++++++++++++++-- 3 files changed, 253 insertions(+), 27 deletions(-) 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 bbd9056ff9..a6368eccd3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp @@ -367,6 +367,14 @@ TilePos on_route204_south(TilePos local){ return story_to_world(ravaged_path_world(), "Route204South", local); } +// Routes no longer run along a wander zone, so that leg is no longer +// planned on Route 204 South: the walks below replay it on a plain room, +// from (3, 1) "west 2 (to wall)" to (1, 1), the person on (2, 1), with a +// row below to plan round them. +StoryWorld youngster_room(){ + return make_world({"#####", "#...#", "#...#", "#####"}); +} + // The console's first walk west: blocked after 800 ms, no chunk moved. ScriptStep west_never_moved(){ return walk_step("wall: T: west 2 (to wall)", WalkStop::BLOCKED, 1050ms, 0); @@ -385,38 +393,38 @@ UnitTestResult test_short_leg_waits_for_the_way(Logger&){ }}; ScriptedWalk walk; try{ - walk = walk_script(ravaged_path_world(), on_route204_south({13, 2}), on_route204_south({11, 2}), {}, script); + walk = walk_script(youngster_room(), {3, 1}, {1, 1}, {}, script); }catch (const ScriptMismatch& e){ return e.message; } if (!walk.failure.empty() || !walk.fights.empty()){ return std::format("expected to wait and walk on; fought {}, failure \"{}\".", walk.fights.size(), walk.failure); } - if (walk.at != std::vector{on_route204_south({11, 2})}){ - return "did not arrive at Route 204 South (11, 2)."; + if (walk.at != std::vector{{1, 1}}){ + return "did not arrive at (1, 1)."; } const std::string left = script_left(script); return left.empty() ? UnitTestResult(true) : UnitTestResult(left); } -// Whether the replan after the youngster's talk starts from (13, 2) alone, -// with (12, 2) marked, and plans a route. +// Whether the replan after the youngster's talk starts from (3, 1) alone, +// with (2, 1) marked, and plans a route. std::string check_never_moved_replan(const Script& script){ - const std::string replan = check_replan_from(script, {"Route 204 (13, 2)"}); + const std::string replan = check_replan_from(script, {"(3, 1)"}); if (!replan.empty()){ return replan; } const auto replan_note = std::find_if(script.notes.begin(), script.notes.end(), [](const std::string& note){ return note.find("planning again") != std::string::npos; }); - if (replan_note->find("(12, 2)") != std::string::npos){ + if (replan_note->find("(2, 1)") != std::string::npos){ return "the replan still starts from the youngster's tile: " + *replan_note; } const auto marked = std::find_if(script.notes.begin(), script.notes.end(), [](const std::string& note){ return note.find("marked it") != std::string::npos; }); - if (marked == script.notes.end() || marked->find("(12, 2)") == std::string::npos){ - return "the youngster's tile (12, 2) was not marked."; + if (marked == script.notes.end() || marked->find("(2, 1)") == std::string::npos){ + return "the youngster's tile (2, 1) was not marked."; } const size_t plans = std::count_if(script.notes.begin(), script.notes.end(), [](const std::string& note){ return note.find("legs planned") != std::string::npos; @@ -432,8 +440,8 @@ std::string check_never_moved_replan(const Script& script){ // tile the walk may have moved, and found no plan: an uncertain start // needs a wall both tiles reach (wall_recovery_candidates()), and no wall // is anchored from a tile someone wanders on, which both are. A walk that -// never moved stopped where it began: the replan starts from (13, 2) -// alone, with the youngster's tile marked. +// never moved stopped where it began: the replan starts from the start +// alone, with the youngster's tile marked (on youngster_room()). UnitTestResult test_never_moved_plans_from_the_start(Logger& logger){ const StoryWorld& world = ravaged_path_world(); const std::vector console_from{on_route204_south({12, 2}), on_route204_south({13, 2})}; @@ -453,7 +461,7 @@ UnitTestResult test_never_moved_plans_from_the_start(Logger& logger){ ScriptedWalk walk; std::string stopped_at; try{ - walk = walk_script(world, on_route204_south({13, 2}), on_route204_south({11, 2}), {}, script); + walk = walk_script(youngster_room(), {3, 1}, {1, 1}, {}, script); }catch (const ScriptMismatch& e){ // The walk after the replan is not scripted. stopped_at = e.message; @@ -471,6 +479,39 @@ UnitTestResult test_never_moved_plans_from_the_start(Logger& logger){ return replan.empty() ? UnitTestResult(true) : UnitTestResult(replan); } +// A leg to the wall two tiles away that runs out of time after one tile +// (one chunk moved): someone stands in it, as Route 204's youngster did on +// 01.08's "west 2 (to wall)" (lab-B 2026-11-08). The check at the wall +// allowed a tile short on legs of two or three tiles, so the stop against +// him passed as the wall and the route went on a tile off. Now it is a +// stop short of the wall: talk to whoever is there, then plan again. +UnitTestResult test_short_leg_a_tile_short_is_not_arrived(Logger&){ + const StoryWorld room = make_world({"####", "#..#", "#..#", "#..#", "####"}); + Script script{.steps = { + walk_step("wall: T: north 2 (to wall)", WalkStop::LIMIT, 1850ms, 1), + press_step("A 80 ms x1"), + answer_step("dialog within 2000 ms", false), + }}; + ScriptedWalk walk; + std::string stopped_at; + try{ + walk = walk_script(room, {1, 3}, {1, 1}, {}, script); + }catch (const ScriptMismatch& e){ + // The walk after the replan is not scripted. + stopped_at = e.message; + } + if (!walk.failure.empty()){ + return "failed: " + walk.failure; + } + if (script.next != script.steps.size()){ + return "went on as at the wall: " + stopped_at; + } + const bool replanned = std::any_of(script.notes.begin(), script.notes.end(), [](const std::string& note){ + return note.find("stopped early after about 1 tiles") != std::string::npos && note.find("planning again") != std::string::npos; + }); + return replanned ? UnitTestResult(true) : UnitTestResult("no replan after the stop a tile short."); +} + struct PlannedRouteInput{ std::string name; @@ -523,6 +564,10 @@ const PlannedRouteCase PLANNED_ROUTE_CASES[] = { .input = {"a person a tile ahead on a short leg is waited out", test_short_leg_waits_for_the_way}, .expectation = {}, }, + { + .input = {"a short leg to a wall a tile short is a stop, not the wall", test_short_leg_a_tile_short_is_not_arrived}, + .expectation = {}, + }, { .input = {"a wall leg that never moved plans from its start", test_never_moved_plans_from_the_start}, .expectation = {}, 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 5696886887..13029be081 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp @@ -30,7 +30,8 @@ namespace{ using Pokemon::Direction; using Pokemon::TilePos; -StoryWorld make_world(const std::vector& rows){ +// A map of `rows`, with someone wandering `wander` if given. +StoryWorld make_world(const std::vector& rows, const std::optional& wander = std::nullopt){ Pokemon::MapData map; map.name = "Test"; map.tiles = Pokemon::Grid{(int)rows[0].size(), (int)rows.size(), {}}; @@ -39,6 +40,10 @@ StoryWorld make_world(const std::vector& rows){ map.tiles.cells.push_back(*Pokemon::tile_from_glyph(glyph)); } } + if (wander){ + map.objects.push_back({.name = "wanderer", .x = wander->x0, .y = wander->y0, .facing = std::nullopt, + .wander = wander, .trainer = std::nullopt, .hide_flag = std::nullopt}); + } StoryWorld world; world.add("Test", map, {0, 0}); return world; @@ -137,6 +142,43 @@ UnitTestResult test_plan_robust_route(Logger&){ return true; } +// Someone wanders a row, (2..4, 2): a leg may cross the row through one of +// their tiles, but not run along it through two, the leg's start among +// them. On lab-B (2026-11-08, 01.08) Route 204's youngster stopped a leg +// west along his row twice. With no other way there is no plan. +UnitTestResult test_plan_robust_route_wander_zone(Logger&){ + const Pokemon::TileBox row_zone{.x0 = 2, .y0 = 2, .x1 = 4, .y1 = 2}; + const StoryWorld room = make_world({"#######", "#.....#", "#.....#", "#.....#", "#######"}, row_zone); + const StoryWorld corridor = make_world({"#######", "#.....#", "#######"}, Pokemon::TileBox{.x0 = 2, .y0 = 1, .x1 = 4, .y1 = 1}); + RobustPlanCosts exact; + exact.exact_open_tiles = exact.max_open_tiles; + struct ZoneCase{ + std::string name; + const StoryWorld& world; + TilePos from; + TilePos goal; + std::string legs; + }; + const std::vector cases{ + {.name = "south across the row", .world = room, .from = {3, 1}, .goal = {3, 3}, .legs = "south 2 (to wall) to (3, 3)"}, + {.name = "north across the row", .world = room, .from = {3, 3}, .goal = {3, 1}, .legs = "north 2 (to wall) to (3, 1)"}, + {.name = "east into the row's first tile", .world = room, .from = {1, 2}, .goal = {2, 2}, .legs = "east 1 (open) to (2, 2)"}, + {.name = "east along the row goes round it", .world = room, .from = {1, 2}, .goal = {5, 2}, + .legs = "north 1 (to wall) to (1, 1); east 4 (to wall) to (5, 1); south 1 (open) to (5, 2)"}, + {.name = "west along the row from inside it goes round", .world = room, .from = {3, 2}, .goal = {1, 2}, + .legs = "north 1 (to wall) to (3, 1); west 2 (to wall) to (1, 1); south 1 (open) to (1, 2)"}, + {.name = "no plan when the row is the only way", .world = corridor, .from = {1, 1}, .goal = {5, 1}, .legs = ""}, + }; + for (const ZoneCase& item : cases){ + const auto legs = plan_robust_route(item.world, {item.from}, [&](const TilePos& pos){ return pos == item.goal; }, exact); + const std::string read = legs ? describe(*legs) : ""; + if (read != item.legs){ + return std::format("{}: planned \"{}\", expected \"{}\".", item.name, read, item.legs); + } + } + return true; +} + // November 5 mine report: credited taps need not establish physical pose. // The two phases are explicit diagnostics, not inferred console timing. @@ -347,6 +389,10 @@ const RoutePlannerCase ROUTE_PLANNER_CASES[] = { .input = {"robust plans", test_plan_robust_route}, .expectation = {}, }, + { + .input = {"robust plans cross a wander zone, never along it", test_plan_robust_route_wander_zone}, + .expectation = {}, + }, { .input = {"trainers' sight lines", test_trainer_sight}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index a6797a9190..9bbbe47c36 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -5,11 +5,14 @@ */ #include +#include #include +#include #include #include #include #include +#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" @@ -257,14 +260,21 @@ std::string slides_into_door(const StoryWorld& world, const PlannedLeg& planned) return ""; } -// No ROUTE step of the table plans an open leg that ends before a door it -// walks toward: a door is gone through by a step that runs or taps into it -// from where the route ends on a wall or off its line. Where a row's steps -// leave the player is followed from its start through each step's target -// or pose_after; a route from an unknown place is not checked. -UnitTestResult test_story_routes_stop_short_of_doors(Logger& logger){ - std::vector found; - size_t checked = 0; +// A ROUTE step of the table from a known place: the world it plans on and +// its plan, or nothing if it finds none. +struct PlannedStoryRoute{ + std::string name; // " " + const StoryWorld* world; + std::vector from; + std::optional> legs; +}; + +// Every ROUTE step of the table that starts from a known place, planned as +// walk_route() plans it. Where a row's steps leave the player is followed +// from its start through each step's target or pose_after; a route from an +// unknown place is logged, not planned. +std::vector plan_story_routes(Logger& logger){ + std::vector routes; for (const StoryCheckpoint& row : story_checkpoints()){ std::optional at = row.start; for (const Pokemon::StoryStep& step : row.steps){ @@ -274,19 +284,36 @@ UnitTestResult test_story_routes_stop_short_of_doors(Logger& logger){ if (step.kind == StoryStepKind::ROUTE && world == nullptr){ logger.log(std::format("{} {}: not checked, from {}.", row.id, step.name, at ? Pokemon::to_string(*at) : "nowhere known")); } - const std::optional> legs = world ? route_step_plan(*world, *at, step) : std::nullopt; - checked += legs ? 1 : 0; - for (const PlannedLeg& planned : legs ? *legs : std::vector{}){ - const std::string why = slides_into_door(*world, planned); - if (!why.empty()){ - found.push_back(std::format("{} {}: {}.", row.id, step.name, why)); + if (world != nullptr){ + std::vector from; + for (const TilePos& pos : Pokemon::tiles_of(*at)){ + from.push_back(story_to_world(*world, at->map, pos)); } + routes.push_back({row.id + " " + step.name, world, std::move(from), route_step_plan(*world, *at, step)}); } at = step.kind == StoryStepKind::ROUTE ? step.target : step.pose_after ? step.pose_after : step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP ? std::nullopt : at; } } + return routes; +} + +// No ROUTE step of the table plans an open leg that ends before a door it +// walks toward: a door is gone through by a step that runs or taps into it +// from where the route ends on a wall or off its line. +UnitTestResult test_story_routes_stop_short_of_doors(Logger& logger){ + std::vector found; + size_t checked = 0; + for (const PlannedStoryRoute& route : plan_story_routes(logger)){ + checked += route.legs ? 1 : 0; + for (const PlannedLeg& planned : route.legs ? *route.legs : std::vector{}){ + const std::string why = slides_into_door(*route.world, planned); + if (!why.empty()){ + found.push_back(std::format("{}: {}.", route.name, why)); + } + } + } logger.log(std::format("{} routes planned.", checked)); std::string out; for (const std::string& line : found){ @@ -295,6 +322,106 @@ UnitTestResult test_story_routes_stop_short_of_doors(Logger& logger){ return found.empty() ? UnitTestResult(true) : UnitTestResult("Open legs that end before a door they walk toward:" + out); } +// The tiles a planned leg walks over from `from`, `from` first: to the wall, +// or its tiles' worth of steps. +std::vector walked_tiles(const StoryWorld& world, const TilePos& from, const TileLeg& leg){ + std::vector tiles{from}; + size_t walked = 0; + while (leg.ends_at_wall || walked < leg.tiles){ + const std::optional next = step(world, tiles.back(), leg.direction); + if (!next){ + break; + } + walked += (size_t)(std::abs(next->x - tiles.back().x) + std::abs(next->y - tiles.back().y)); + tiles.push_back(*next); + } + return tiles; +} + +// The most tiles of `zone` one leg of `legs` walks over, from any tile the +// player may be on, and that leg. +std::pair most_zone_tiles( + const StoryWorld& world, std::vector from, const std::vector& legs, + const std::function& zone +){ + std::pair most{0, ""}; + for (const PlannedLeg& planned : legs){ + for (const TilePos& pos : from){ + const std::vector tiles = walked_tiles(world, pos, planned.leg); + const size_t in_zone = (size_t)std::count_if(tiles.begin(), tiles.end(), zone); + if (in_zone > most.first){ + most = {in_zone, to_string(planned.leg) + " from " + describe(world, pos)}; + } + } + from = planned.after; + } + return most; +} + +// Where a planned leg from `from` runs along a zone where someone wanders, +// or "": two zone tiles in a row on a straight leg are tiles of one zone. +std::string along_wander_zone(const StoryWorld& world, const TilePos& from, const TileLeg& leg){ + const std::vector tiles = walked_tiles(world, from, leg); + for (size_t i = 1; i < tiles.size(); i++){ + if (wandering_hazard(world, tiles[i - 1]) && wandering_hazard(world, tiles[i])){ + return std::format("{} from {} runs along a wander zone at {}", to_string(leg), describe(world, from), describe(world, tiles[i])); + } + } + return ""; +} + +// Every ROUTE step of the table from a known place has a plan, and no leg +// of it runs along a zone where someone wanders: plan_robust_route() never +// plans one, so a step with no other way finds no plan here. +UnitTestResult test_story_routes_keep_off_wander_zones(Logger& logger){ + std::string out; + for (const PlannedStoryRoute& route : plan_story_routes(logger)){ + if (!route.legs){ + out += "\n " + route.name + ": no plan."; + continue; + } + std::vector from = route.from; + for (const PlannedLeg& planned : *route.legs){ + for (const TilePos& pos : from){ + const std::string along = along_wander_zone(*route.world, pos, planned.leg); + out += along.empty() ? "" : "\n " + route.name + ": " + along + "."; + } + from = planned.after; + } + } + return out.empty() ? UnitTestResult(true) : UnitTestResult("ROUTE steps:" + out); +} + +// 01.08's walk below the Ravaged Path keeps off the row Route 204 South's +// youngster_3 wanders, (12, 2) to (14, 2): on lab-B (2026-11-08) the plan +// "north 35 (to wall) to (13, 2), west 2 (to wall) to (11, 2)" walked along +// it, and he stopped the leg west twice. A leg may cross his row through +// one of his tiles, not walk two of them. +UnitTestResult test_ravaged_path_keeps_off_the_youngster(Logger& logger){ + for (const PlannedStoryRoute& route : plan_story_routes(logger)){ + if (route.name != "01.08 below_the_ravaged_path"){ + continue; + } + if (!route.legs){ + return "01.08 below_the_ravaged_path: no plan."; + } + const StoryWorld& world = *route.world; + for (const PlannedLeg& planned : *route.legs){ + logger.log("01.08 below_the_ravaged_path: " + to_string(planned)); + } + const auto youngster_row = [&](const TilePos& pos){ + const std::optional local = story_to_local(world, "Route204South", pos); + return local && local->y == 2 && local->x >= 12 && local->x <= 14; + }; + const auto [most, leg] = most_zone_tiles(world, route.from, *route.legs, youngster_row); + if (most >= 2){ + return std::format("the leg {} walks {} tiles of the youngster's row (12..14, 2).", leg, most); + } + return true; + } + return "01.08 below_the_ravaged_path is not a ROUTE step from a known place."; +} + struct AutoStoryStoryTableInput{ std::string name; @@ -351,6 +478,14 @@ const AutoStoryStoryTableCase AUTO_STORY_STORY_TABLE_CASES[] = { .input = {"Story table: no open leg ends before a door it walks toward (lab-B, 2026-11-08)", test_story_routes_stop_short_of_doors}, .expectation = {}, }, + { + .input = {"Story table: every route plans, and none runs along a wander zone", test_story_routes_keep_off_wander_zones}, + .expectation = {}, + }, + { + .input = {"01.08: the walk below the Ravaged Path keeps off the youngster's row (lab-B, 2026-11-08)", test_ravaged_path_keeps_off_the_youngster}, + .expectation = {}, + }, }; void add_tests_AutoStory_StoryTable(UnitTestDatabase& database){ From 814a825d5b38e9ef982fae8bff2cea7da924ead6 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 18:06:04 -0800 Subject: [PATCH 09/19] BDSP AutoStory: no route runs along a wander zone; short wall legs walk every tile plan_robust_route() no longer uses a leg that walks two tiles in a row of a zone where someone wanders (the leg's start among them): along a row zone, or through a 2-D one. Crossing a row zone through one tile is still planned at per_wander_tile, with #271's wait if he stands there. With no other way there is no plan; nothing falls back. A leg to a wall of 3 tiles or fewer that runs out of time short of its tiles is now a stop short of the wall (talk, then plan again), and the check at the wall needs every tile on such legs. Plans that change: 01.08 below_the_ravaged_path goes up column 14, then 12, and crosses the youngster's row at (12, 2) only; 00.05b below_the_tv_clown and 01.03 above_the_mine go round their wanderers. The story sim now plans ROUTE steps as walk_route() does (from a wall for a few start tiles, then default costs): from 01.03's two start tiles the search over both ran out of budget on the longer way. The grid sim's wait test crosses a row zone on a plain room, and Segment00Lines' reference line for 00.03 goes along Route 201's row 13, above the Breeder. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_RoutePlanner.cpp | 14 ++++++-- .../Data/PokemonBDSP_AutoStory_RoutePlanner.h | 9 +++-- .../PokemonBDSP_AutoStory_Segment00Lines.cpp | 4 ++- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 34 +++++++++---------- ...onBDSP_AutoStory_StorySimulation_Tests.cpp | 10 +++++- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 20 +++++++++-- 6 files changed, 66 insertions(+), 25 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 184549ce82..0c2303cf3f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp @@ -222,10 +222,14 @@ struct Stepped{ TilePos end; int grass = 0; int wander = 0; + // Two tiles in a row where someone wanders, the start among them: the + // walk runs along their zone, and plan_robust_route() does not use it. + bool along_wander = false; }; std::optional step_tiles(const StoryWorld& world, TilePos from, Direction direction, int tiles){ Stepped stepped; int travelled = 0; + bool in_wander = wandering_hazard(world, from); while (travelled < tiles){ const std::optional next = step(world, from, direction); if (!next){ @@ -238,9 +242,12 @@ std::optional step_tiles(const StoryWorld& world, TilePos from, Directi if (tall_grass(world, *next)){ stepped.grass++; } - if (wandering_hazard(world, *next)){ + const bool next_wander = wandering_hazard(world, *next); + if (next_wander){ stepped.wander++; + stepped.along_wander |= in_wander; } + in_wander = next_wander; from = *next; } stepped.end = from; @@ -282,6 +289,9 @@ std::optional to_wall_leg(const StoryWorld& world, const Spread& spre return std::nullopt; } if (const std::optional stepped = step_tiles(world, pos, direction, (int)hit.tiles)){ + if (stepped->along_wander){ + return std::nullopt; + } grass = std::max(grass, stepped->grass); wander = std::max(wander, stepped->wander); } @@ -307,7 +317,7 @@ std::optional open_leg(const StoryWorld& world, const Spread& spread, 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){ + if (!stepped || stepped->along_wander){ return std::nullopt; } grass = std::max(grass, stepped->grass); 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 2376e8e59b..8e22ac6c33 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h @@ -129,8 +129,13 @@ struct RobustPlanCosts : TilePlanCosts{ // 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. +// Legs that would leave the maps or enter a door are not used, nor legs that +// run along a zone where someone wanders: two tiles of it in a row, the +// leg's start among them. Crossing a zone (one tile of it) costs +// `per_wander_tile`. On lab-B (2026-11-08, 01.08) Route 204's youngster, +// who wanders (12, 2) to (14, 2), stopped the leg "west 2 (to wall)" from +// (13, 2) twice. 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, 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 c247bc3a35..c32ae18be4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp @@ -131,8 +131,10 @@ const std::vector& lines(){ 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"}), + // Row 13, a row above the Breeder, who wanders (26..28, 14..16): no + // route runs along a wander zone (plan_robust_route()). walked("00.03", "Rowan to Dawn at Sandgem's entrance", { - route201_point("rowan_stop"), route201({17, 14}), route201({29, 14}), route201({41, 14}), + route201_point("rowan_stop"), route201({17, 14}), route201({17, 13}), route201({29, 13}), route201({41, 13}), 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"}), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 11ccb344d4..b87c43da62 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -46,7 +46,8 @@ using Pokemon::TileBox; using Pokemon::TilePos; -StoryWorld make_world(const std::vector& rows){ +// A map of `rows`, with someone wandering `wander` if given. +StoryWorld make_world(const std::vector& rows, const std::optional& wander = std::nullopt){ Pokemon::MapData map; map.name = "Test"; map.tiles = Pokemon::Grid{(int)rows[0].size(), (int)rows.size(), {}}; @@ -55,6 +56,10 @@ StoryWorld make_world(const std::vector& rows){ map.tiles.cells.push_back(*Pokemon::tile_from_glyph(glyph)); } } + if (wander){ + map.objects.push_back({.name = "wanderer", .x = wander->x0, .y = wander->y0, .facing = std::nullopt, + .wander = wander, .trainer = std::nullopt, .hide_flag = std::nullopt}); + } StoryWorld world; world.add("Test", map, {0, 0}); return world; @@ -684,30 +689,25 @@ UnitTestResult test_wandering_npc_routes_multi_seed(Logger& logger){ return true; } +// Routes never run along a wander zone, but cross one: a row someone +// wanders, (2..4, 2), crossed south at (3, 2) while they stand there. UnitTestResult test_wandering_npc_wait_clearance(Logger& logger){ - const StoryWorld* world = story_plan_world("OreburghCity", "OreburghCity"); - if (world == nullptr){ - return "OreburghCity world not found"; - } - const TilePos start = story_to_world(*world, "OreburghCity", {48, 22}); - const TilePos target = story_to_world(*world, "OreburghCity", {48, 30}); - const TileBox hiker_box{ - story_to_world(*world, "OreburghCity", {46, 25}).x, - story_to_world(*world, "OreburghCity", {46, 25}).y, - story_to_world(*world, "OreburghCity", {48, 27}).x, - story_to_world(*world, "OreburghCity", {48, 27}).y - }; + const TileBox row_zone{.x0 = 2, .y0 = 2, .x1 = 4, .y1 = 2}; + const StoryWorld room = make_world({"#######", "#.....#", "#.....#", "#.....#", "#.....#", "#######"}, row_zone); + const StoryWorld* world = &room; + const TilePos start{3, 1}; + const TilePos target{3, 4}; SimWanderer hiker{ .name = "hiker_0", - .box = hiker_box, - .pos = story_to_world(*world, "OreburghCity", {48, 26}), + .box = row_zone, + .pos = {3, 2}, .seed = 2, .step_interval = 2000ms, }; - GridSim sim({.world = world, .trainers = story_trainers(*world), .wanderers = {hiker}}, start, Direction::NORTH, true); + GridSim sim({.world = world, .trainers = {}, .wanderers = {hiker}}, start, Direction::NORTH, true); std::vector notes; GridSimRouteIO sim_io(sim, notes); - RouteTrainers trainers{story_trainers(*world), [&sim](const std::string&){ sim.end_dialogue(); }}; + RouteTrainers trainers{{}, [&sim](const std::string&){ sim.end_dialogue(); }}; const auto result = walk_route(sim_io, *world, {start}, trainers, { .goal = [&](const TilePos& pos){ return pos == target; }, .label = "walk_through_hiker", diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index 27c100db13..80f9c9f358 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -26,6 +26,7 @@ #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_StorySimulation_Tests.h" @@ -113,7 +114,14 @@ Walked plan_route(const Pose& from, const StoryStep& step){ targets.push_back(story_to_world(*world, goal.map, pos)); } const std::function at_goal = [&](const TilePos& pos){ return contains(targets, pos); }; - const auto plan = plan_robust_route(*world, start, at_goal, *costs); + // As walk_route() plans: from a wall when the start is one of a few + // tiles, then with the default costs if the step's find nothing. From + // 01.03's two start tiles a search over both found no plan within its + // budget once routes kept off the hiker's zone. + std::optional> plan = plan_recovered_route(*world, start, at_goal, *costs); + if (!plan){ + plan = plan_recovered_route(*world, start, at_goal, RobustPlanCosts()); + } if (!plan){ return {std::nullopt, step.name + ": no plan from" + describe(from.map, Pokemon::tiles_of(from)) + ".", ""}; } 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 45add5572c..b2f2d0354f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -178,6 +178,19 @@ bool never_moved(const WalkResult& walk, size_t walked_tiles){ return walk.stop == WalkStop::BLOCKED && walk.moved_chunks == 0 && walked_tiles == 0; } +// Legs to a wall this many tiles or shorter must walk every tile: a tile +// short is someone in the way, not the time count's slack. On lab-B +// (2026-11-08, 01.08) Route 204's youngster stopped "west 2 (to wall)" +// after 1 tile; a tile short passed as at the wall, the route logged +// arriving at (11, 2) from (13, 2), and the taps north hit the cliff. +constexpr size_t EXACT_WALL_LEG_TILES = 3; + +// The fewest tiles a leg to a wall `expected_tiles` away must have walked +// to count as at its wall. +size_t min_tiles_at_wall(size_t expected_tiles){ + return expected_tiles > EXACT_WALL_LEG_TILES ? expected_tiles * 7 / 10 : expected_tiles; +} + // Whether a leg's walk goes on to the next leg or the route plans again. enum class LegNext{ NEXT_LEG, @@ -421,6 +434,10 @@ LegNext RouteWalker::wall_leg(LegWalk& walk){ // 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)){ + // A short leg a tile short stopped against someone in the way. + if (nearest <= EXACT_WALL_LEG_TILES && walked_tiles < nearest){ + return stopped_short_of_wall(walk, walked_tiles); + } check_at_wall(walk, walked_tiles, nearest); } return LegNext::NEXT_LEG; @@ -507,8 +524,7 @@ LegNext RouteWalker::stopped_short_of_wall(LegWalk& walk, size_t walked_tiles){ void RouteWalker::check_at_wall(LegWalk& walk, size_t walked_tiles, size_t expected_tiles){ if (expected_tiles != SIZE_MAX && expected_tiles > 0 && walked_tiles != SIZE_MAX){ - const size_t min_tiles = expected_tiles > 3 ? (expected_tiles * 7 / 10) : (expected_tiles > 1 ? expected_tiles - 1 : 1); - if (walked_tiles < min_tiles){ + if (walked_tiles < min_tiles_at_wall(expected_tiles)){ fail(m_io, walk.label + ": ran out of time well short of the wall (" + std::to_string(walked_tiles) + " of " + std::to_string(expected_tiles) + " tiles): not where the plan has us."); } From b9c2d8b45e706cc00d4ea7506aa7923ff509b140 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 18:27:11 -0800 Subject: [PATCH 10/19] BDSP AutoStory: red tests for 01.10's line-5 recovery wall and a battle on line 7 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 136 ++++++++++++++++++ ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 32 +++++ 2 files changed, 168 insertions(+) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index 794a08bc30..071ed50f3d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -8,6 +8,7 @@ * physical cause. Run the real story step and route walker on GridSim. */ #include +#include #include #include #include @@ -643,6 +644,140 @@ const MineExitCase MINE_EXIT_CASES[] = { .expectation = {.below_the_door = false, .west_of_column_46 = std::nullopt}}, }; +// A wild battle after the third tile of the first walk north of more than +// three tiles, tapped or run until a banner; the walk goes on after it, as +// walk_tiles_dpad() and walk_until_dpad() go on after running. +class ColumnBattle{ +public: + explicit ColumnBattle(std::vector& notes) : m_notes(notes){} + // Whether the battle comes after `tile` tiles of a walk `direction`. + bool after(Direction direction, size_t tiles, size_t tile){ + if (m_taken || direction != Direction::NORTH || tiles <= BATTLE_AFTER || tile != BATTLE_AFTER){ + return false; + } + m_taken = true; + m_notes.push_back(std::format("[Sim] a wild battle after {} tiles north.", tile)); + return true; + } + static constexpr size_t BATTLE_AFTER = 3; +private: + std::vector& m_notes; + bool m_taken = false; +}; + +class ColumnBattleRouteIO : public GridSimRouteIO{ +public: + ColumnBattleRouteIO(GridSim& sim, std::vector& notes, ColumnBattle& battle) + : GridSimRouteIO(sim, notes), m_battle(battle) + {} + virtual WalkResult walk_taps(Direction direction, size_t tiles, const std::string& label) override{ + if (!m_battle.after(direction, tiles, ColumnBattle::BATTLE_AFTER)){ + return GridSimRouteIO::walk_taps(direction, tiles, label); + } + WalkResult result = GridSimRouteIO::walk_taps(direction, ColumnBattle::BATTLE_AFTER, label); + const WalkResult rest = GridSimRouteIO::walk_taps(direction, tiles - ColumnBattle::BATTLE_AFTER, label); + result.stop = rest.stop; + result.walked += rest.walked; + result.moved_chunks += rest.moved_chunks; + result.wild_battles++; + return result; + } +private: + ColumnBattle& m_battle; +}; + +// RecoveryStepIO that also runs until a map's banner: it reads +// SIM_BANNER_TILES into the map, as the story simulation's does, or where +// something stops the run on it. +class BannerStepIO : public RecoveryStepIO{ +public: + static constexpr size_t SIM_BANNER_TILES = 3; + BannerStepIO(RouteIO& route, GridSim& sim, ColumnBattle& battle) : RecoveryStepIO(route), m_sim(sim), m_battle(battle){} + virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override{ + size_t on = 0; + size_t tiles = 0; + for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ + m_battle.after(direction, SIZE_MAX, tiles); + const SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + tiles++; + const bool stopped = move.distance == 0 || move.stop != SimStop::DONE; + on = story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)) ? on + 1 : 0; + if (on > 0 && (on >= SIM_BANNER_TILES || stopped)){ + return true; + } + if (stopped){ + return false; + } + } + return false; + } +private: + GridSim& m_sim; + ColumnBattle& m_battle; +}; + +// 01.10's last stretch, north up column 11 from (11, 12) through the grass +// on (11, 5..11) into Floaroma (lab-B 2026-11-08 18:17:53): a wild battle +// on "north 7 (open)" to (11, 5) left (11, 5..12), and no plan came, for +// column 11 has no wall to the north and no other wall brings those tiles +// together. The table's steps after line 6, with a wild battle three tiles +// up, must end in Floaroma where the row's last walk says. +UnitTestResult test_line_7_battle_reaches_floaroma(Logger& logger){ + const StoryWorld& world = *story_plan_world("Route204North", "FloaromaTown"); + GridSim sim({.world = &world}, story_to_world(world, "Route204North", {11, 12}), Direction::WEST, true); + std::vector notes; + ColumnBattle battle(notes); + ColumnBattleRouteIO route(sim, notes, battle); + BannerStepIO io(route, sim, battle); + StoryWalkSteps walks(io); + walks.begin_attempt("01.10"); + Pokemon::RunState state{.pose = Pokemon::tile_pose("Route204North", {{11, 12}}, Direction::WEST), .flags = {}}; + std::string failure; + std::optional last; + try{ + bool after_line_6 = false; + for (const Pokemon::StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const Pokemon::StoryStep& step : checkpoint.id == "01.10" ? checkpoint.steps : std::vector{}){ + const bool walks_here = after_line_6 && (step.kind == Pokemon::StoryStepKind::ROUTE || step.kind == Pokemon::StoryStepKind::LEGS); + after_line_6 |= step.name == "line_6"; + if (!walks_here || !failure.empty()){ + continue; + } + const Pokemon::Outcome outcome = step.kind == Pokemon::StoryStepKind::ROUTE ? walks.route(state, step) : walks.legs(state, step); + failure = outcome.failure; + last = step.pose_after ? step.pose_after : step.target; + state.pose = outcome.pose ? *outcome.pose : *last; + logger.log(std::format("01.10 {} ended at {}.", step.name, to_string(sim.player().pos))); + } + } + }catch (const GridSimFailure& error){ + failure = error.message; + } + for (const std::string& note : notes){ + logger.log(note); + } + if (!failure.empty() || !last){ + return "01.10 after line 6: " + (failure.empty() ? std::string("no walk") : failure); + } + const std::vector tiles = Pokemon::tiles_of(*last); + const auto end = story_to_local(world, last->map, nearest_tile(sim.player().pos)); + if (!end || std::find(tiles.begin(), tiles.end(), *end) == tiles.end()){ + return std::format("01.10 ended at {}, not on {}.", to_string(sim.player().pos), Pokemon::to_string(*last)); + } + if (last->map != "FloaromaTown"){ + return "01.10 ends on " + last->map + ", not in Floaroma."; + } + return true; +} + +class Test_LineSevenBattle : public UnitTest{ +public: + Test_LineSevenBattle() : UnitTest("PokemonBDSP::AutoStory - Recovery walk: 01.10 a wild battle on the last line reaches Floaroma (lab-B, 2026-11-08)"){} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + return test_line_7_battle_reaches_floaroma(logger); + } +}; + } // namespace void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ @@ -672,6 +807,7 @@ void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ for (const MineExitCase& scenario : MINE_EXIT_CASES){ database.add(scenario); } + database.add(); } } // namespace PokemonBDSP } // namespace NintendoSwitch diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index 9bbbe47c36..a11e09f379 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -224,6 +224,34 @@ UnitTestResult test_route204_north_line(Logger& logger){ return true; } +// 01.10's line 5, "north 10 (open)" to (19, 12), after Aroma Lady Taylor's +// battle (lab-B 2026-11-08 18:15:47): we may stand anywhere on (19, 12..20). +// Column 19 is open floor from row 7 to 13 below the wall on row 6, so north +// to that wall and 5 south reach the goal; the console's plan, "south 12 (to +// wall) to (19, 24), north 12 (open) to (19, 12)", pinned the wall with the +// fewest held tiles and walked back twice as far. +UnitTestResult test_line_5_recovery_pins_the_wall_nearest_the_goal(Logger& logger){ + const StoryWorld& world = *story_plan_world("Route204North", "Route204North"); + std::vector from; + for (int y = 12; y <= 20; y++){ + from.push_back(story_to_world(world, "Route204North", {19, y})); + } + const TilePos goal = story_to_world(world, "Route204North", {19, 12}); + const auto legs = plan_recovered_route(world, from, [&](const TilePos& pos){ return pos == goal; }, *story_route_costs("line")); + if (!legs || legs->empty()){ + return "no plan from (19, 12..20)."; + } + for (const PlannedLeg& planned : *legs){ + logger.log("01.10 line 5 recovery: " + to_string(planned)); + } + const PlannedLeg& first = legs->front(); + const TilePos wall = story_to_world(world, "Route204North", {19, 7}); + if (first.leg.direction != Direction::NORTH || !first.leg.ends_at_wall || first.after != std::vector{wall}){ + return "the recovery starts " + to_string(first) + ", not north to the wall at (19, 7)."; + } + return true; +} + // The legs a ROUTE step from `from` plans, as walk_route() plans them (the // step's costs, then the default ones), on `world`; nothing if none. std::optional> route_step_plan(const StoryWorld& world, const Pokemon::Pose& from, const Pokemon::StoryStep& step){ @@ -474,6 +502,10 @@ const AutoStoryStoryTableCase AUTO_STORY_STORY_TABLE_CASES[] = { .input = {"Route 204 North: the line into Floaroma", test_route204_north_line}, .expectation = {}, }, + { + .input = {"01.10: line 5's recovery pins the wall nearest its goal (lab-B, 2026-11-08)", test_line_5_recovery_pins_the_wall_nearest_the_goal}, + .expectation = {}, + }, { .input = {"Story table: no open leg ends before a door it walks toward (lab-B, 2026-11-08)", test_story_routes_stop_short_of_doors}, .expectation = {}, From f84492311fdc0c012c02a991a300827b8ceb30c8 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 18:30:01 -0800 Subject: [PATCH 11/19] BDSP AutoStory: recovery takes the cheapest whole walk; 01.10 runs into Floaroma Recovery from a few possible tiles pinned the wall with the fewest held tiles and ignored the way on to the goal: after Taylor's battle on line 5 it held south 12 and walked 12 back where north 13 and 5 south would do. It now plans the way on from every anchor and keeps the cheapest whole walk. 01.10's last line ran an open leg up column 11, which has no wall north; a wild battle on it left no plan. The row now runs north until Floaroma's banner, which ends the same from any tile of the column, and 01.11 starts from the rows the run may stop on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_RoutePlanner.cpp | 32 +++++++++++++++++++ .../Data/PokemonBDSP_AutoStory_RoutePlanner.h | 10 ++++++ .../PokemonBDSP_AutoStory_WallRecovery.cpp | 27 ++++++++++------ .../Data/PokemonBDSP_AutoStory_WallRecovery.h | 2 ++ .../PokemonBDSP_AutoStory_StoryTable.cpp | 31 +++++++++++++++--- ...onBDSP_AutoStory_StorySimulation_Tests.cpp | 4 +++ 6 files changed, 91 insertions(+), 15 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 0c2303cf3f..78e68ef048 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp @@ -469,6 +469,38 @@ std::optional> plan_robust_route( return RobustSearch(world, costs).run(from, goal); } +long long robust_route_cost( + const StoryWorld& world, + const std::vector& from, const std::vector& legs, + const RobustPlanCosts& costs +){ + long long total = 0; + Spread spread = from; + normalize(spread); + const TileLeg* previous = nullptr; + for (const PlannedLeg& planned : legs){ + const TileLeg& leg = planned.leg; + const std::optional expansion = leg.ends_at_wall + ? to_wall_leg(world, spread, leg.direction, costs) + : open_leg(world, spread, leg.direction, (int)leg.tiles, costs); + long long cost = (long long)costs.per_leg + (long long)costs.per_tile * (long long)leg.tiles; + if (!leg.ends_at_wall){ + cost += costs.leg_not_at_wall + (long long)costs.per_open_tile * (long long)leg.tiles; + } + if (expansion){ + cost = expansion->cost; + } + if (previous != nullptr && previous->direction == leg.direction && !previous->ends_at_wall){ + cost -= costs.per_leg; + } + total += cost; + spread = planned.after; + normalize(spread); + previous = ⋚ + } + return total; +} + } // namespace PokemonBDSP 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 8e22ac6c33..718d4bf513 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h @@ -148,6 +148,16 @@ std::optional> plan_robust_route( const RobustPlanCosts& costs = RobustPlanCosts() ); +// What plan_robust_route() charges for walking `legs` from any of `from`, +// each leg from the tiles the one before may end on. A leg it would not +// plan (along a wander zone, or off the maps) costs its tiles and legs +// without grass or wander tiles. +long long robust_route_cost( + const StoryWorld& world, + const std::vector& from, const std::vector& legs, + const RobustPlanCosts& costs +); + } // namespace PokemonBDSP diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp index 7ccc8549c5..3d73a54243 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp @@ -135,19 +135,26 @@ std::optional> plan_recovered_route( if (from.size() == 1){ return plan_robust_route(world, from, goal, costs); } - auto anchors = wall_recovery_candidates(world, from); - std::stable_sort(anchors.begin(), anchors.end(), [&](const auto& a, const auto& b){ - return goal(a.at) && !goal(b.at); - }); - for (const auto& anchor : anchors){ + // The cheapest whole walk, holds and the way on from the wall: the + // fewest held tiles alone chose "south 12 (to wall), north 12 (open)" + // over "north 13 (to wall), south 5 (open)" for 01.10's line 5 (lab-B + // 2026-11-08 18:15:47). Ties keep find_wall_anchors()' order. + std::optional> best; + long long best_cost = 0; + for (const auto& anchor : wall_recovery_candidates(world, from)){ const auto back = plan_robust_route(world, std::vector{anchor.at}, goal, costs); - if (back){ - auto route = recovery_legs(world, from, anchor.holds); - route.insert(route.end(), back->begin(), back->end()); - return route; + if (!back){ + continue; + } + auto route = recovery_legs(world, from, anchor.holds); + route.insert(route.end(), back->begin(), back->end()); + const long long cost = robust_route_cost(world, from, route, costs); + if (!best || cost < best_cost){ + best = std::move(route); + best_cost = cost; } } - return std::nullopt; + return best; } } // namespace PokemonBDSP diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h index 862e2a2f14..954f02c4ae 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h @@ -32,6 +32,8 @@ std::vector interrupted_leg_positions( // Establish a common wall anchor before continuing from an uncertain pose. // Single positions retain the existing planner. Ambiguous positions without // a safe anchor fail instead of choosing one. Goals already held need no walk. +// Of the anchors, the one whose whole walk, holds and the way on to the +// goal, costs least (robust_route_cost()). std::optional> plan_recovered_route( const StoryWorld& world, const std::vector& from, const std::function& goal, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 2f7cb7123d..8a92a1feab 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -847,6 +847,15 @@ StoryCheckpoint through_the_ravaged_path(){ }); } +// Where 01.10's run north up column 11 stops: Floaroma's banner reads a +// tile or a few past the border (route_201_by_the_path()), and the path in +// (10..12, 30..31) opens onto the field at row 29, so from the arrival +// tile (11, 29) to two rows north of it. +Pose into_floaroma(){ + const TilePos arrival = map_point(FLOAROMA, "route_204_arrival"); + return Pokemon::tile_pose(FLOAROMA, {arrival, arrival.next(NORTH), arrival.next(NORTH).next(NORTH)}, NORTH); +} + // 01.10: the line a human walked up Route 204's north half (2026-10-31, // r246a to r251a), corner to corner (Test_Route204NorthLine checks each // stretch is one straight leg), then north between the flower beds into @@ -855,12 +864,22 @@ StoryCheckpoint through_the_ravaged_path(){ StoryCheckpoint route_204_to_floaroma(){ std::vector steps; const std::vector line = map_region(ROUTE_204_NORTH, "floaroma_waypoints"); - for (size_t i = 0; i < line.size(); i++){ + // The line's last corner, (11, 5) up column 11, is not walked to: the + // run into Floaroma below goes past it. + for (size_t i = 0; i + 1 < line.size(); i++){ steps.push_back(route(std::format("line_{}", i + 1), Pokemon::tile_pose(ROUTE_204_NORTH, {line[i]}), "a corner of the human's line", "line")); } - // 01.11 walks on from here: west 8 along row 29, north to the old woman. - steps.push_back(route("into_floaroma", at(FLOAROMA, "route_204_arrival", NORTH), "north up column 11 into Floaroma", "line")); + // From (11, 12) north up column 11, through the grass on (11, 5..11), + // until Floaroma's banner: the end is the banner, not a count. An open + // leg to (11, 5) met a wild battle there and found no plan back, for + // column 11 has no wall north to pin (lab-B 2026-11-08 18:17:53); the + // run goes on north after a battle, and any tile of the column ends the + // same way. + StoryStep run = legs("into_floaroma", {{.direction = NORTH, .tiles = 17}}, + "run north up column 11 until Floaroma's banner", "to_map"); + run.pose_after = into_floaroma(); + steps.push_back(std::move(run)); steps.push_back(save()); return row("01.10", "Route 204 to Floaroma", at(ROUTE_204_NORTH, "cave_exit", SOUTH), std::move(steps)); } @@ -891,11 +910,13 @@ std::vector to_oreburgh(){ // west of her stand still above the flower field's bottom row (r251a). // The walk to her is the one that ran on the console: 8 taps west along // row 29, then north until she stops us (r250a: 3 steps, then bumps). +// 01.10's run may stop on rows 27 to 29: the taps west go along whichever, +// and the walk north ends below her all the same. StoryCheckpoint floaromas_old_couple(){ const Pose below_the_old_woman = next_to(FLOAROMA, "old_woman", SOUTH, NORTH); const Pose below_the_old_man = next_to(FLOAROMA, "old_man", SOUTH, NORTH); - return row("01.11", "Floaroma's old couple", at(FLOAROMA, "route_204_arrival", NORTH), { - legs("west_along_the_field", {{.direction = WEST, .tiles = 8}}, "8 taps west along row 29"), + return row("01.11", "Floaroma's old couple", into_floaroma(), { + legs("west_along_the_field", {{.direction = WEST, .tiles = 8}}, "8 taps west along the row we stopped on"), anchored(to_walls("up_to_the_old_woman", {{.direction = NORTH, .tiles = 5}}, "north until she stops us"), below_the_old_woman), talk("old_woman", "she gives Mew when a Let's Go save is on the console"), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index 80f9c9f358..e2eda64d12 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -171,6 +171,10 @@ Walked walk_legs(const Pose& from, const StoryStep& step){ if (step.variant == "to_wall"){ return {std::nullopt, "", ""}; } + // A run until a map's banner ends where the banner reads. + if (step.variant == "to_map"){ + return {step.pose_after, "", ""}; + } const StoryWorld* world = story_plan_world(from.map, from.map); if (world == nullptr){ return {std::nullopt, step.name + ": no world holds " + from.map + ".", ""}; From b6a554a24a6ba0340957a2f5256b305ed12059a9 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 18:33:33 -0800 Subject: [PATCH 12/19] BDSP AutoStory: keep the story table under the length limit; line-7 cases as a table Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 58 +++++++++++++------ .../PokemonBDSP_AutoStory_StoryTable.cpp | 36 +++--------- 2 files changed, 49 insertions(+), 45 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index 071ed50f3d..d448d579f4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -644,24 +644,25 @@ const MineExitCase MINE_EXIT_CASES[] = { .expectation = {.below_the_door = false, .west_of_column_46 = std::nullopt}}, }; -// A wild battle after the third tile of the first walk north of more than -// three tiles, tapped or run until a banner; the walk goes on after it, as -// walk_tiles_dpad() and walk_until_dpad() go on after running. +// A wild battle after `tiles` tiles of the first walk north longer than +// that, tapped or run until a banner (none if 0); the walk goes on after +// it, as walk_tiles_dpad() and walk_until_dpad() go on after running. class ColumnBattle{ public: - explicit ColumnBattle(std::vector& notes) : m_notes(notes){} - // Whether the battle comes after `tile` tiles of a walk `direction`. + ColumnBattle(std::vector& notes, size_t tiles) : m_notes(notes), m_tiles(tiles){} + size_t tiles() const{ return m_tiles; } + // Whether the battle comes after `tile` tiles of a walk of `tiles` `direction`. bool after(Direction direction, size_t tiles, size_t tile){ - if (m_taken || direction != Direction::NORTH || tiles <= BATTLE_AFTER || tile != BATTLE_AFTER){ + if (m_taken || m_tiles == 0 || direction != Direction::NORTH || tiles <= m_tiles || tile != m_tiles){ return false; } m_taken = true; m_notes.push_back(std::format("[Sim] a wild battle after {} tiles north.", tile)); return true; } - static constexpr size_t BATTLE_AFTER = 3; private: std::vector& m_notes; + size_t m_tiles; bool m_taken = false; }; @@ -671,11 +672,11 @@ class ColumnBattleRouteIO : public GridSimRouteIO{ : GridSimRouteIO(sim, notes), m_battle(battle) {} virtual WalkResult walk_taps(Direction direction, size_t tiles, const std::string& label) override{ - if (!m_battle.after(direction, tiles, ColumnBattle::BATTLE_AFTER)){ + if (!m_battle.after(direction, tiles, m_battle.tiles())){ return GridSimRouteIO::walk_taps(direction, tiles, label); } - WalkResult result = GridSimRouteIO::walk_taps(direction, ColumnBattle::BATTLE_AFTER, label); - const WalkResult rest = GridSimRouteIO::walk_taps(direction, tiles - ColumnBattle::BATTLE_AFTER, label); + WalkResult result = GridSimRouteIO::walk_taps(direction, m_battle.tiles(), label); + const WalkResult rest = GridSimRouteIO::walk_taps(direction, tiles - m_battle.tiles(), label); result.stop = rest.stop; result.walked += rest.walked; result.moved_chunks += rest.moved_chunks; @@ -720,13 +721,24 @@ class BannerStepIO : public RecoveryStepIO{ // on (11, 5..11) into Floaroma (lab-B 2026-11-08 18:17:53): a wild battle // on "north 7 (open)" to (11, 5) left (11, 5..12), and no plan came, for // column 11 has no wall to the north and no other wall brings those tiles -// together. The table's steps after line 6, with a wild battle three tiles -// up, must end in Floaroma where the row's last walk says. -UnitTestResult test_line_7_battle_reaches_floaroma(Logger& logger){ +// together. The table's steps after line 6, with a wild battle the input's +// tiles up, must end in Floaroma where the row's last walk says. +struct LineSevenInput{ + std::string name; + size_t battle_after_tiles = 0; +}; +struct LineSevenExpectation{ +}; +struct LineSevenCase{ + LineSevenInput input; + LineSevenExpectation expectation; +}; + +UnitTestResult test_line_7_battle_reaches_floaroma(Logger& logger, const LineSevenInput& input){ const StoryWorld& world = *story_plan_world("Route204North", "FloaromaTown"); GridSim sim({.world = &world}, story_to_world(world, "Route204North", {11, 12}), Direction::WEST, true); std::vector notes; - ColumnBattle battle(notes); + ColumnBattle battle(notes, input.battle_after_tiles); ColumnBattleRouteIO route(sim, notes, battle); BannerStepIO io(route, sim, battle); StoryWalkSteps walks(io); @@ -772,10 +784,20 @@ UnitTestResult test_line_7_battle_reaches_floaroma(Logger& logger){ class Test_LineSevenBattle : public UnitTest{ public: - Test_LineSevenBattle() : UnitTest("PokemonBDSP::AutoStory - Recovery walk: 01.10 a wild battle on the last line reaches Floaroma (lab-B, 2026-11-08)"){} + explicit Test_LineSevenBattle(LineSevenCase data) + : UnitTest("PokemonBDSP::AutoStory - Recovery walk: 01.10 into Floaroma, " + data.input.name), m_case(std::move(data)) + {} virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - return test_line_7_battle_reaches_floaroma(logger); + return test_line_7_battle_reaches_floaroma(logger, m_case.input); } +private: + LineSevenCase m_case; +}; + +const LineSevenCase LINE_SEVEN_CASES[] = { + {.input = {.name = "no battle", .battle_after_tiles = 0}, .expectation = {}}, + {.input = {.name = "a wild battle 3 tiles up (lab-B, 2026-11-08)", .battle_after_tiles = 3}, .expectation = {}}, + {.input = {.name = "a wild battle 6 tiles up", .battle_after_tiles = 6}, .expectation = {}}, }; } // namespace @@ -807,7 +829,9 @@ void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ for (const MineExitCase& scenario : MINE_EXIT_CASES){ database.add(scenario); } - database.add(); + for (const LineSevenCase& scenario : LINE_SEVEN_CASES){ + database.add(scenario); + } } } // namespace PokemonBDSP } // namespace NintendoSwitch diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 8a92a1feab..650259e1e5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -847,39 +847,21 @@ StoryCheckpoint through_the_ravaged_path(){ }); } -// Where 01.10's run north up column 11 stops: Floaroma's banner reads a -// tile or a few past the border (route_201_by_the_path()), and the path in -// (10..12, 30..31) opens onto the field at row 29, so from the arrival -// tile (11, 29) to two rows north of it. -Pose into_floaroma(){ - const TilePos arrival = map_point(FLOAROMA, "route_204_arrival"); - return Pokemon::tile_pose(FLOAROMA, {arrival, arrival.next(NORTH), arrival.next(NORTH).next(NORTH)}, NORTH); -} - // 01.10: the line a human walked up Route 204's north half (2026-10-31, -// r246a to r251a), corner to corner (Test_Route204NorthLine checks each -// stretch is one straight leg), then north between the flower beds into -// Floaroma. Its trainers who see us are fought: Taylor on the line, the -// Twins as a pair. +// r246a to r251a; Test_Route204NorthLine), then north up column 11 until +// Floaroma's banner, which reads on (11, 27..29): the column has no wall +// north, so a wild battle on an open leg to the line's last corner (11, 5) +// found no plan back (lab-B 2026-11-08 18:17:53). Taylor and the Twins fight. +Pose into_floaroma(){ return Pokemon::tile_pose(FLOAROMA, {TilePos{11, 27}, TilePos{11, 28}, TilePos{11, 29}}, NORTH); } StoryCheckpoint route_204_to_floaroma(){ std::vector steps; const std::vector line = map_region(ROUTE_204_NORTH, "floaroma_waypoints"); - // The line's last corner, (11, 5) up column 11, is not walked to: the - // run into Floaroma below goes past it. for (size_t i = 0; i + 1 < line.size(); i++){ steps.push_back(route(std::format("line_{}", i + 1), Pokemon::tile_pose(ROUTE_204_NORTH, {line[i]}), "a corner of the human's line", "line")); } - // From (11, 12) north up column 11, through the grass on (11, 5..11), - // until Floaroma's banner: the end is the banner, not a count. An open - // leg to (11, 5) met a wild battle there and found no plan back, for - // column 11 has no wall north to pin (lab-B 2026-11-08 18:17:53); the - // run goes on north after a battle, and any tile of the column ends the - // same way. - StoryStep run = legs("into_floaroma", {{.direction = NORTH, .tiles = 17}}, - "run north up column 11 until Floaroma's banner", "to_map"); - run.pose_after = into_floaroma(); - steps.push_back(std::move(run)); + steps.push_back(anchored(legs("into_floaroma", {{.direction = NORTH, .tiles = 17}}, + "run north until Floaroma's banner; on after a wild battle", "to_map"), into_floaroma())); steps.push_back(save()); return row("01.10", "Route 204 to Floaroma", at(ROUTE_204_NORTH, "cave_exit", SOUTH), std::move(steps)); } @@ -909,9 +891,7 @@ std::vector to_oreburgh(){ // 01.11 on Floaroma's map: the old woman (3, 25) and the old man (2, 25) // west of her stand still above the flower field's bottom row (r251a). // The walk to her is the one that ran on the console: 8 taps west along -// row 29, then north until she stops us (r250a: 3 steps, then bumps). -// 01.10's run may stop on rows 27 to 29: the taps west go along whichever, -// and the walk north ends below her all the same. +// row 29 (or 27, 28), then north until she stops us (r250a: 3 steps, bumps). StoryCheckpoint floaromas_old_couple(){ const Pose below_the_old_woman = next_to(FLOAROMA, "old_woman", SOUTH, NORTH); const Pose below_the_old_man = next_to(FLOAROMA, "old_man", SOUTH, NORTH); From 83c09c779a7ddde7489af050ca16119b7bf68008 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 19:04:18 -0800 Subject: [PATCH 13/19] BDSP AutoStory: red sim test for 01.11's walk to the old woman lab-B 2026-11-08 18:41: 01.11's 8 taps west, then north, ended below the old man and no one answered the old woman's talk. A grid sim test walks 01.11 to her from each of the nine tiles Floaroma's banner stops us on: the old taps (OldStorySteps) must miss her from x 10 and 12, and the table's walk must end below her from all nine. The westedge batch found the field's edge 3 taps west of the old man, a column west of Floaroma's map. SimGround adds that column beside the map, for this test and for the story sim's 01.11 from now on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 37 +++++++++ .../PokemonBDSP_AutoStory_OldStorySteps.cpp | 8 ++ .../PokemonBDSP_AutoStory_OldStorySteps.h | 5 ++ .../PokemonBDSP_AutoStory_SimGround.cpp | 75 +++++++++++++++++++ .../PokemonBDSP_AutoStory_SimGround.h | 45 +++++++++++ .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 16 +++- SerialPrograms/cmake/SourceFiles.cmake | 2 + 7 files changed, 184 insertions(+), 4 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.h diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index b87c43da62..177439cd52 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -22,6 +23,8 @@ #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" #include "PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_OldStorySteps.h" +#include "PokemonBDSP_AutoStory_SimGround.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" @@ -591,6 +594,36 @@ UnitTestResult test_gate_walk_part_tile_off(Logger&){ return true; } +// lab-B 2026-11-08 18:41: 01.11's 8 taps west, then north, ended below the +// old man, and no one answered the old woman's talk. Floaroma's banner +// stops us on any of (10..12, 27..29): the old taps miss her from x 10 and +// 12; the table's walk west to the field's edge and 4 taps east end below +// her from all nine. +UnitTestResult test_old_couple_from_each_arrival(Logger& logger){ + const std::optional table = table_steps("01.11", "west_to_the_field_edge", "old_woman"); + const auto ground = std::ranges::find(sim_ground(), std::string("FloaromaTown"), &SimGround::map); + if (!table || table->steps.empty() || ground == sim_ground().end()){ + return "01.11 has no walk west to the field's edge, or Floaroma no ground west of its map."; + } + const TableSteps old_taps{table->start, {old_west_along_the_field(), table->steps.back()}}; + const std::unique_ptr world = with_ground(*story_plan_world("FloaromaTown", "FloaromaTown"), *ground); + const TilePos below_her = story_to_world(*world, "FloaromaTown", map_point("FloaromaTown", "old_woman").next(Direction::SOUTH)); + for (int x = 10; x <= 12; x++){ + for (int y = 27; y <= 29; y++){ + const TilePos start = story_to_world(*world, "FloaromaTown", {x, y}); + const std::string old_miss = walk_misses(*world, old_taps, start, {{"up_to_the_old_woman", below_her}}, logger); + if (old_miss.empty() != (x == 11)){ + return std::format("The old taps from ({}, {}): {}", x, y, old_miss.empty() ? "ended below her." : old_miss); + } + const std::string miss = walk_misses(*world, *table, start, {{"up_to_the_old_woman", below_her}}, logger); + if (!miss.empty()){ + return "The table's walk " + miss; + } + } + } + return true; +} + UnitTestResult test_wandering_npc_mechanics(Logger& logger){ StoryWorld world = make_world({ "#######", @@ -937,6 +970,10 @@ const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { .input = {"01.05, a part of a tile off, the old open walk west takes the Gate's warp (lab-B, 2026-11-08)", test_gate_walk_part_tile_off}, .expectation = {}, }, + { + .input = {"01.11, the old woman from each tile Floaroma's banner stops us on (lab-B, 2026-11-08)", test_old_couple_from_each_arrival}, + .expectation = {}, + }, }; void add_tests_AutoStory_GridSim(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp index 657513f382..a508c54be5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp @@ -83,6 +83,14 @@ StoryStep old_tap_into_the_gate(){ return step; } +StoryStep old_west_along_the_field(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "west_along_the_field"; + step.legs = {{.direction = Direction::WEST, .tiles = 8}}; + return step; +} + } // namespace PokemonBDSP diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h index 580eb84f32..7c4608e445 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h @@ -46,6 +46,11 @@ Pokemon::StoryStep old_coal_room_crate_cut(); // the tap step began inside the Gate (lab-B 2026-11-08 15:31 to 15:54). Pokemon::StoryStep old_tap_into_the_gate(); +// 01.11's old walk toward the old woman: 8 taps west along the row +// Floaroma's banner stopped us on, from x 10 to 12, so north of it ended +// below the old man (lab-B 2026-11-08 18:41). +Pokemon::StoryStep old_west_along_the_field(); + } // namespace PokemonBDSP diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.cpp new file mode 100644 index 0000000000..bf45e6068a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.cpp @@ -0,0 +1,75 @@ +/* BDSP AutoStory - Simulated ground + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_SimGround.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::TileKind; +using Pokemon::TilePos; + + +const std::vector& sim_ground(){ + static const std::vector ground{ + // Floaroma's flower field goes on a column west of the map: from + // below the old man (2, 26), taps west moved 3 tiles and the 4th + // bumped (westedge batch 2026-11-08). + {.map = "FloaromaTown", .tiles = {{-1, 26}, {-1, 27}, {-1, 28}, {-1, 29}}, .row = "01.11"}, + }; + return ground; +} + +namespace{ + +// The offset `map` is placed at on `world`: a wall placed at offset (0, 0) +// of a copy shows where that offset lands. +TilePos placed_at(const StoryWorld& world, const std::string& map){ + Pokemon::MapData probe; + probe.name = "probe"; + probe.tiles = Pokemon::Grid{1, 1, {TileKind::WALL}}; + StoryWorld copy = world; + copy.add(probe.name, probe, {0, 0}); + const TilePos corner = story_to_world(copy, map, {0, 0}); + const TilePos zero = copy.to_world(probe.name, {0, 0}); + return {corner.x - zero.x, corner.y - zero.y}; +} + +} // namespace + +std::unique_ptr with_ground(const StoryWorld& world, const SimGround& ground){ + if (ground.tiles.empty()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No ground beside " + ground.map + "."); + } + TilePos low = ground.tiles.front(); + TilePos high = ground.tiles.front(); + for (const TilePos& pos : ground.tiles){ + low = {std::min(low.x, pos.x), std::min(low.y, pos.y)}; + high = {std::max(high.x, pos.x), std::max(high.y, pos.y)}; + } + Pokemon::MapData strip; + strip.name = ground.map + " ground"; + const int width = high.x - low.x + 1; + const int height = high.y - low.y + 1; + strip.tiles = Pokemon::Grid{width, height, std::vector((size_t)width * height, TileKind::WALL)}; + for (const TilePos& pos : ground.tiles){ + Pokemon::cell_at(strip.tiles, {pos.x - low.x, pos.y - low.y}) = TileKind::OPEN; + } + const TilePos corner = placed_at(world, ground.map); + auto out = std::make_unique(world); + out->add(strip.name, strip, {corner.x + low.x, corner.y + low.y}); + return out; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.h new file mode 100644 index 0000000000..2647626983 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.h @@ -0,0 +1,45 @@ +/* BDSP AutoStory - Simulated ground + * + * From: https://github.com/PokemonAutomation/ + * + * Ground the story's maps lack that the console showed, for the story + * simulation to walk on: tiles past a map's edge, as a map of their own + * beside it. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_SimGround_H +#define PokemonAutomation_PokemonBDSP_AutoStory_SimGround_H + +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Open `tiles` of `map` (a JSON map's name), in its own coordinates past +// its edge, from story row `row` on. +struct SimGround{ + std::string map; + std::vector tiles; + std::string row; +}; + +// The ground the story's maps lack. +const std::vector& sim_ground(); + +// A copy of `world`, which holds `ground`'s map, with `ground`'s tiles +// beside that map. Throws InternalProgramError for no tiles. +std::unique_ptr with_ground(const StoryWorld& world, const SimGround& ground); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 5f6a1a86b7..a1d993191b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -42,6 +42,7 @@ #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP_AutoStory_GridSim.h" #include "PokemonBDSP_AutoStory_OldStorySteps.h" +#include "PokemonBDSP_AutoStory_SimGround.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" @@ -439,7 +440,7 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ GridSim m_sim; SimStoryStepIO m_io; StoryWalkSteps m_walks; - // The planner's worlds with sim_people() on them, by world and who. + // The planner's worlds with sim_people() and sim_ground() on them, by world and who. mutable std::map, std::unique_ptr> m_peopled; // The steps of this row that have run. std::set m_ran; @@ -470,14 +471,21 @@ const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ who += person.name + ";"; } } - if (here.empty()){ + const SimGround* ground = nullptr; + for (const SimGround& item : sim_ground()){ + if (world != nullptr && m_row >= item.row && story_plan_world(item.map, item.map) == world){ + ground = &item; + who += item.map + " ground;"; + } + } + if (who.empty()){ return world; } std::unique_ptr& peopled = m_peopled[{world, who}]; if (!peopled){ - peopled = std::make_unique(*world); + peopled = ground != nullptr ? with_ground(*world, *ground) : std::make_unique(*world); for (const SimPerson& person : here){ - peopled->block(story_to_world(*world, person.map, person.tile)); + peopled->block(story_to_world(*peopled, person.map, person.tile)); } } return peopled.get(); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index ce5d08921a..3cf67423fd 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1712,6 +1712,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp From dd502a123d4d9f88e145269c1ad81a1a0383fca1 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 19:05:37 -0800 Subject: [PATCH 14/19] BDSP AutoStory: 01.11 walks west to the field's edge, then 4 taps east 8 taps west from where Floaroma's banner stops us (any of x 10..12) did not end below the old woman: on lab-B (2026-11-08 18:41) they ended below the old man. A walk west until the field's edge stops us ends on one column from every arrival; from below the old man the edge is 3 taps west (westedge batch 2026-11-08), so her column is 4 taps east of it. That edge is x = -1, a column west of Floaroma's map. The map is left as it is (a TODO in the table): the field may go on past it, or the old couple may stand a tile east of their map points. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 650259e1e5..1306b106c2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -888,17 +888,17 @@ std::vector to_oreburgh(){ }; } -// 01.11 on Floaroma's map: the old woman (3, 25) and the old man (2, 25) -// west of her stand still above the flower field's bottom row (r251a). -// The walk to her is the one that ran on the console: 8 taps west along -// row 29 (or 27, 28), then north until she stops us (r250a: 3 steps, bumps). +// 01.11: the old woman (3, 25), the old man (2, 25) west of her (r251a). 8 taps west from the banner's x 10..12 ended below +// him (lab-B 2026-11-08 18:41). The field's edge is 3 taps west of him (westedge batch 2026-11-08): x = -1, off the map. +// TODO(map points): the field goes on west of the map (the sim adds it, sim_ground()), or the couple stand a tile east. StoryCheckpoint floaromas_old_couple(){ const Pose below_the_old_woman = next_to(FLOAROMA, "old_woman", SOUTH, NORTH); const Pose below_the_old_man = next_to(FLOAROMA, "old_man", SOUTH, NORTH); + const Pose at_the_field_edge = Pokemon::tile_pose(FLOAROMA, {TilePos{-1, 27}, TilePos{-1, 28}, TilePos{-1, 29}}, WEST); return row("01.11", "Floaroma's old couple", into_floaroma(), { - legs("west_along_the_field", {{.direction = WEST, .tiles = 8}}, "8 taps west along the row we stopped on"), - anchored(to_walls("up_to_the_old_woman", {{.direction = NORTH, .tiles = 5}}, "north until she stops us"), - below_the_old_woman), + anchored(to_walls("west_to_the_field_edge", {{.direction = WEST, .tiles = 13}}, "until the field's edge stops us"), at_the_field_edge), + legs("below_her_column", {{.direction = EAST, .tiles = 4}}, "4 taps east to her column (westedge batch 2026-11-08)"), + anchored(to_walls("up_to_the_old_woman", {{.direction = NORTH, .tiles = 5}}, "north until she stops us"), below_the_old_woman), talk("old_woman", "she gives Mew when a Let's Go save is on the console"), scene("old_woman_talks", below_the_old_woman, "her lines"), // He stands above that tile, so talk() turning north only turns. From 8c9ba9bed03470ca92700049f1c8c7dcfc789c95 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 19:19:29 -0800 Subject: [PATCH 15/19] BDSP AutoStory: regenerate the route plans golden after #277, #278 and #279 Rewritten with PA_UPDATE_ROUTE_PLANS=1 on the merged tree: the recovery goal (#278) shortens several localizations, the wander-zone costs (#277) reroute 00.05b and 01.08, and 01.10's line 7 and into_floaroma are no longer ROUTE steps (#279). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Data/route_plans.golden.txt | 87 ++++++++----------- 1 file changed, 36 insertions(+), 51 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt index 33677f8d33..41d46a087a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt @@ -24,8 +24,8 @@ anchor); 0 from one start tile. from: PlayerHouse1F (10, 3) (10, 4) (set) target: PlayerHouse1F (6, 9) facing south (tile) start candidates: PlayerHouse1F (10, 3), PlayerHouse1F (10, 4) - 1. north 1 (to wall) -> PlayerHouse1F (10, 3) - 2. south 6 (open) -> PlayerHouse1F (10, 9) + 1. south 7 (to wall) -> PlayerHouse1F (10, 10) + 2. north 1 (open) -> PlayerHouse1F (10, 9) 3. west 4 (open) -> PlayerHouse1F (6, 9) totals: 3 legs, 2 turns, 2 open, 1 localization @@ -67,10 +67,9 @@ anchor); 0 from one start tile. from: VerityLakefront (17, 14) (17, 15) (set) target: Route201 (4, 14) facing east (tile) start candidates: Verity Lakefront (17, 14), Verity Lakefront (17, 15) - 1. north 4 (to wall) -> Verity Lakefront (17, 11) - 2. south 10 (to wall) -> Verity Lakefront (17, 21) - 3. east 19 (open) -> Route 201 (4, 14) - totals: 3 legs, 2 turns, 1 open, 1 localization + 1. south 7 (to wall) -> Verity Lakefront (17, 21) + 2. east 19 (open) -> Route 201 (4, 14) + totals: 2 legs, 1 turns, 1 open, 1 localization == 00.03 by_the_counter (costs: route) from: PlayerHouse1F (5, 8) (6, 8) facing east (set) @@ -169,12 +168,10 @@ anchor); 0 from one start tile. from: Route202 (18, 25) (19, 25) (20, 25) (18, 26) (19, 26) (20, 26) (18, 27) (19, 27) (20, 27) (set) target: SandgemTown (29, 5) (tile) start candidates: Route 202 (18, 25), Route 202 (19, 25), Route 202 (20, 25), Route 202 (18, 26), Route 202 (19, 26), Route 202 (20, 26), Route 202 (18, 27), Route 202 (19, 27), Route 202 (20, 27) - 1. north 2 (to wall) -> Route 202 (18, 25), Route 202 (19, 25), Route 202 (20, 25) - 2. east 5 (to wall) -> Route 202 (23, 25) - 3. south 6 (to wall) -> Route 202 (23, 31) - 4. east 7 (to wall) -> Route 202 (30, 31) - 5. south 6 (to wall) -> Sandgem Town (29, 5) - totals: 5 legs, 4 turns, 0 open, 2 localization + 1. south 2 (to wall) -> Route 202 (18, 27), Route 202 (19, 27), Route 202 (20, 27) + 2. east 12 (to wall) -> Route 202 (30, 27) + 3. south 10 (to wall) -> Sandgem Town (29, 5) + totals: 3 legs, 2 turns, 0 open, 2 localization == 00.04b to_center_sign (costs: town) from: SandgemTown (29, 5) (tile) @@ -230,10 +227,10 @@ anchor); 0 from one start tile. target: JubilifeCity (36, 17) facing north (tile) start candidates: Jubilife City (55, 34) 1. west 23 (to wall) -> Jubilife City (32, 34) - 2. north 18 (to wall) -> Jubilife City (32, 16) - 3. south 1 (open) -> Jubilife City (32, 17) - 4. east 4 (open) -> Jubilife City (36, 17) - totals: 4 legs, 3 turns, 2 open, 0 localization + 2. north 10 (open) -> Jubilife City (32, 24) + 3. east 4 (open) -> Jubilife City (36, 24) + 4. north 7 (open) -> Jubilife City (36, 17) + totals: 4 legs, 3 turns, 3 open, 0 localization == 00.05b below_the_company_clown (costs: town) from: JubilifeCity (36, 17) facing north (tile) @@ -294,10 +291,9 @@ anchor); 0 from one start tile. target: OreburghGate (6, 22) facing east (tile) start candidates: OreburghGate (4, 22), OreburghGate (5, 22) 1. south 1 (to wall) -> OreburghGate (4, 23), OreburghGate (5, 23) - 2. west 1 (to wall) -> OreburghGate (4, 23) - 3. east 2 (to wall) -> OreburghGate (6, 23) - 4. north 1 (open) -> OreburghGate (6, 22) - totals: 4 legs, 3 turns, 1 open, 2 localization + 2. east 2 (to wall) -> OreburghGate (6, 23) + 3. north 1 (open) -> OreburghGate (6, 22) + totals: 3 legs, 2 turns, 1 open, 2 localization == 01.02 past_curtis (costs: route) from: OreburghGate (7, 22) facing east (tile) @@ -318,9 +314,9 @@ anchor); 0 from one start tile. target: OreburghCity (9, 13) facing east (tile) start candidates: Oreburgh City (2, 13), Oreburgh City (3, 13) 1. north 3 (to wall) -> Oreburgh City (2, 10), Oreburgh City (3, 10) - 2. west 1 (to wall) -> Oreburgh City (2, 10) - 3. south 3 (open) -> Oreburgh City (2, 13) - 4. east 7 (open) -> Oreburgh City (9, 13) + 2. east 4 (to wall) -> Oreburgh City (6, 10) + 3. south 3 (open) -> Oreburgh City (6, 13) + 4. east 3 (open) -> Oreburgh City (9, 13) totals: 4 legs, 3 turns, 2 open, 2 localization == 01.02b below_the_centers_door (costs: town) @@ -337,10 +333,12 @@ anchor); 0 from one start tile. target: OreburghCity (46, 57) facing south (tile) start candidates: Oreburgh City (47, 21), Oreburgh City (46, 21) 1. east 2 (to wall) -> Oreburgh City (48, 21) - 2. south 28 (to wall) -> Oreburgh City (48, 49) - 3. west 2 (open) -> Oreburgh City (46, 49) - 4. south 8 (open) -> Oreburgh City (46, 57) - totals: 4 legs, 3 turns, 2 open, 1 localization + 2. west 4 (open) -> Oreburgh City (44, 21) + 3. south 20 (to wall) -> Oreburgh City (44, 41) + 4. west 1 (open) -> Oreburgh City (43, 41) + 5. south 16 (to wall) -> Oreburgh City (43, 57) + 6. east 3 (open) -> Oreburgh City (46, 57) + totals: 6 legs, 5 turns, 3 open, 1 localization == 01.05 east_of_barrys_trigger (costs: town) from: OreburghCity (26, 21) (26, 22) facing south (set) @@ -360,12 +358,11 @@ anchor); 0 from one start tile. start candidates: OreburghGate (27, 22), OreburghGate (26, 22) 1. north 2 (to wall) -> OreburghGate (27, 20), OreburghGate (26, 21) 2. east 1 (to wall) -> OreburghGate (27, 20), OreburghGate (27, 21) - 3. north 1 (to wall) -> OreburghGate (27, 20) - 4. south 3 (to wall) -> OreburghGate (27, 23) - 5. west 19 (to wall) -> OreburghGate (8, 23) - 6. north 1 (to wall) -> OreburghGate (8, 22) - 7. west 3 (open) -> OreburghGate (5, 22) - totals: 7 legs, 6 turns, 1 open, 3 localization + 3. south 3 (to wall) -> OreburghGate (27, 23) + 4. west 19 (to wall) -> OreburghGate (8, 23) + 5. north 1 (to wall) -> OreburghGate (8, 22) + 6. west 3 (open) -> OreburghGate (5, 22) + totals: 6 legs, 5 turns, 1 open, 3 localization == 01.06 below_rowans_trigger (costs: town) from: Route203 (55, 9) facing west (tile) @@ -383,10 +380,12 @@ anchor); 0 from one start tile. from: JubilifeCity (44, 5) facing west (tile) target: Route204South (11, 2) facing north (tile) start candidates: Jubilife City (44, 5) - 1. east 1 (open) -> Jubilife City (45, 5) - 2. north 35 (to wall) -> Route 204 (13, 2) - 3. west 2 (to wall) -> Route 204 (11, 2) - totals: 3 legs, 2 turns, 1 open, 0 localization + 1. east 2 (open) -> Jubilife City (46, 5) + 2. north 19 (to wall) -> Route 204 (14, 18) + 3. west 2 (open) -> Route 204 (12, 18) + 4. north 16 (to wall) -> Route 204 (12, 2) + 5. west 1 (to wall) -> Route 204 (11, 2) + totals: 5 legs, 4 turns, 2 open, 0 localization == 01.09 west_of_the_rock (costs: route) from: RavagedPath (19, 50) facing north (tile) @@ -446,17 +445,3 @@ anchor); 0 from one start tile. start candidates: Route 204 (19, 12) 1. west 8 (open) -> Route 204 (11, 12) totals: 1 legs, 0 turns, 1 open, 0 localization - -== 01.10 line_7 (costs: line) - from: Route204North (11, 12) (tile) - target: Route204North (11, 5) (tile) - start candidates: Route 204 (11, 12) - 1. north 7 (open) -> Route 204 (11, 5) - totals: 1 legs, 0 turns, 1 open, 0 localization - -== 01.10 into_floaroma (costs: line) - from: Route204North (11, 5) (tile) - target: FloaromaTown (11, 29) facing north (tile) - start candidates: Route 204 (11, 5) - 1. north 8 (open) -> Floaroma Town (11, 29) - totals: 1 legs, 0 turns, 1 open, 0 localization From 9167ebacd23f9da0db0dd98538fd74587868bcd0 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 19:33:27 -0800 Subject: [PATCH 16/19] BDSP AutoStory: move the story sim's executor out of its tests SimStoryStepIO, SimExecutor and the run helpers move unchanged from StorySim_Tests.cpp to Simulation/PokemonBDSP_AutoStory_StorySim.{h,cpp}, so other test files can run rows on the same simulation. The header qualifies Pokemon:: names; the helpers that were file-local stay in an anonymous namespace. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StorySim.cpp | 479 +++++++++++++ .../PokemonBDSP_AutoStory_StorySim.h | 292 ++++++++ .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 663 +----------------- SerialPrograms/cmake/SourceFiles.cmake | 2 + 4 files changed, 774 insertions(+), 662 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp new file mode 100644 index 0000000000..fd6b86de1e --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -0,0 +1,479 @@ +/* BDSP AutoStory - Story simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_SimGround.h" +#include "PokemonBDSP_AutoStory_StorySim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::Outcome; +using Pokemon::Pose; +using Pokemon::RunState; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + + +// A hold until something stops us. A door stops it at the fade, which +// fails the step; a fade missed lets the hold go on past the mouth (r81's +// timed walk south out of the Ravaged Path, onto Route 204's cliff). +void SimStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ + m_sim.tap(direction, ROUTE_TURN_TAP, false); + Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); + SimMove move = m_sim.hold(direction, limit, SimPace::WALK); + if (move.stop == SimStop::WARP && fade_missed() && m_far_side()){ + limit -= std::min(limit, move.time); + move = m_sim.hold(direction, limit, SimPace::WALK); + } + if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ + m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); + } +} + +// The D-pad, a tile at a time, until `map`'s banner reads; through a door +// the walk goes on beyond it (the fade eats no tiles of a hold). +bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&){ + const bool miss = banner_missed(); + size_t on = 0; + for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ + SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + const bool crossed = move.stop == SimStop::WARP && m_far_side(); + const bool stopped = !crossed && (move.distance == 0 || move.stop != SimStop::DONE); + on = on_map(map) ? on + 1 : 0; + if (on > 0 && (on > SIM_BANNER_TILES || stopped) && !miss){ + return true; + } + if (stopped){ + return false; + } + } + return false; +} + +// D-pad taps, each looked at, until the fade and then the banner (the +// console's ConsoleStoryStepIO::tap_to_banner()): none if the banner shows +// before the first. Each look stands still, so a banner on the far side +// reads at once. A fade seen ends the taps, +// banner or not; with the fade missed the next look still sees the banner. +std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ + if (m_misses.through == m_misses.tap_steps++){ + m_misses.missed = true; + if (m_far_side() && m_misses.through_banner){ + return 0; + } + } + bool crossed = false; + for (size_t tap = 1; tap <= max_taps; tap++){ + const SimMove move = m_sim.tap(direction, 160ms, false); + if (move.stop == SimStop::DIALOG){ + return std::nullopt; + } + bool faded = false; + if (move.stop == SimStop::WARP){ + faded = !fade_missed(); + crossed = m_far_side(); + } + if (crossed && on_map(map) && !banner_missed()){ + return tap; + } + if (faded){ + return std::nullopt; + } + } + return std::nullopt; +} + +// The story variables whose coord events the table walks onto, from the +// row (and step) the table's reasons give, with the maps' coord events +// (Diamond's zone events; Platinum's for the houses): Barry's doorstep and +// Mom's warning in 00.01, Barry's Route 201 warning, then its pull-back +// row 19 once he has warned us (r14, r16); the lake's entrance in 00.02; +// Rowan's stop and Dawn at Sandgem's edge in 00.03; Dawn's catching +// tutorial on Route 202 from 00.04's start, Mom's call once she has healed +// us; the Poketch president on Jubilife's row 40 in 00.05b; Barry on Route +// 203 in 01.01; the Gate's Hiker and Oreburgh's welcome in 01.02; Barry's +// bump in Oreburgh after Roark in 01.05; and Rowan in Jubilife in 01.07. +// Left out: the Twinleaf guitarist (spent upstairs), Platinum's rival +// steps around our bedroom's start, Dawn at Jubilife's steps (BDSP starts +// her below them: an event), and Floaroma's (10..12, 29) (Diamond only). +std::vector story_vars(){ + return { + {.var = "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", .value = 0, .row = "00.01", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 0, .row = "00.01", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 1, .row = "00.01", .after = "barry_warns_us"}, + {.var = "VAR_VERITY_LAKEFRONT_STATE", .value = 0, .row = "00.02", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 2, .row = "00.03", .after = ""}, + {.var = "VAR_SANDGEM_TOWN_STATE", .value = 0, .row = "00.03", .after = ""}, + {.var = "VAR_ROUTE_202_STATE", .value = 0, .row = "00.04", .after = ""}, + {.var = "CONSOLE_MOMS_CALL", .value = 0, .row = "00.04", .after = "mom_heals_us"}, + {.var = "VAR_POKETCH_CAMPAIGN_STATE", .value = 1, .row = "00.05b", .after = ""}, + {.var = "VAR_ROUTE_203_RIVAL_STATE", .value = 0, .row = "01.01", .after = ""}, + {.var = "VAR_OREBURGH_GATE_1F_HIKER_STATE", .value = 1, .row = "01.02", .after = ""}, + {.var = "VAR_OREBURGH_CITY_STATE", .value = 0, .row = "01.02", .after = ""}, + {.var = "VAR_OREBURGH_CITY_STATE", .value = 2, .row = "01.05", .after = ""}, + {.var = "VAR_JUBILIFE_CITY_STATE", .value = 3, .row = "01.07", .after = ""}, + }; +} + +namespace{ + +// The maps' coord events (story_coord_events()) whose variable holds. +std::optional var_state(const CoordEvent& event){ + for (const VarState& state : story_vars()){ + if (state.var == event.var && state.value == event.value){ + return state; + } + } + return std::nullopt; +} + +RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ + return {.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; +} + +} // namespace + +std::vector story_triggers(){ + std::vector triggers; + for (const auto& [map, json] : bdsp_map_json()){ + for (const CoordEvent& event : story_coord_events(map)){ + const std::optional state = var_state(event); + if (state){ + triggers.push_back(row_trigger(map, event, *state)); + } + } + } + return triggers; +} + +namespace{ + +// Someone the maps do not have, on `tile` of `map`, talked to or walked round: +// from row `row` on, until row `until_row`'s step `until` has run if it is set. +struct SimPerson{ + std::string name; + std::string map; + TilePos tile; + std::string row; + std::string until_row = {}; + std::string until = {}; +}; +std::vector sim_people(){ + return { + // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). + {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04"}, + // Barry in the Gym's door, from the welcome (lab-B 2026-11-08) to his lines (r101, r104). + {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.02b", .until_row = "01.02b", .until = "barrys_lines"}, + }; +} + +// A house's stairs, entered by a step `side` from the map's "stairs" +// point into what the map draws as a wall (the table's 00.01: r8 and r9 +// for ours, r11 for Barry's). +struct SimStairs{ + std::string map; + Direction side; +}; +std::vector sim_stairs(){ + return { + {.map = "PlayerHouse2F", .side = Direction::EAST}, + {.map = "RivalHouse1F", .side = Direction::EAST}, + {.map = "RivalHouse2F", .side = Direction::WEST}, + }; +} + +} // namespace + +// The world the player walks on for `map`: the planner's, with what the +// console showed that the maps lack. Nothing for a room with no map. +const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ + const StoryWorld* world = story_plan_world(map, map); + std::vector here; + std::string who; + for (const SimPerson& person : sim_people()){ + const bool now = m_row >= person.row && (person.until.empty() || m_row < person.until_row || + (m_row == person.until_row && !m_ran.contains(person.until))); + if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ + here.push_back(person); + who += person.name + ";"; + } + } + const SimGround* ground = nullptr; + for (const SimGround& item : sim_ground()){ + if (world != nullptr && m_row >= item.row && story_plan_world(item.map, item.map) == world){ + ground = &item; + who += item.map + " ground;"; + } + } + if (who.empty()){ + return world; + } + std::unique_ptr& peopled = m_peopled[{world, who}]; + if (!peopled){ + peopled = ground != nullptr ? with_ground(*world, *ground) : std::make_unique(*world); + for (const SimPerson& person : here){ + peopled->block(story_to_world(*peopled, person.map, person.tile)); + } + } + return peopled.get(); +} + +SimWorld SimExecutor::setup(const StoryWorld* world) const{ + // B runs once the shoes' scene has given them: the scene ends at home. + SimWorld out{.world = world, .trainers = story_trainers(*world), .can_run = m_walks.can_run()}; + for (const SimStairs& stairs : sim_stairs()){ + if (sim_world(stairs.map) == world){ + out.doors.push_back(story_to_world(*world, stairs.map, map_point(stairs.map, "stairs").next(stairs.side))); + } + } + for (const RowTrigger& armed : m_armed){ + if (sim_world(armed.map) != world){ + continue; + } + SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; + for (const TilePos& pos : armed.trigger.tiles){ + trigger.tiles.push_back(story_to_world(*world, armed.map, pos)); + } + out.triggers.push_back(std::move(trigger)); + } + return out; +} + +// Arms the triggers of this row that start after `after`. +void SimExecutor::arm(const std::string& after){ + size_t armed = 0; + for (const RowTrigger& trigger : story_triggers()){ + if (trigger.row == m_row && trigger.after == after){ + m_armed.push_back(trigger); + armed++; + } + } + const SimPlayer& player = m_sim.player(); + if (armed > 0 && m_placed && on_grid(player.pos) && !player.dialog){ + m_sim.place(setup(&m_sim.world()), nearest_tile(player.pos), player.facing); + } +} + +// Puts the player on `pose`, on the world `on` if given, unless they stand +// on one of its tiles already. Returns whether the pose is on a map the +// simulation has. +bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ + const std::vector tiles = Pokemon::tiles_of(pose); + const StoryWorld* world = on != nullptr ? on : pose.map.empty() ? nullptr : sim_world(pose.map); + if (world == nullptr || tiles.empty()){ + return false; + } + const SimPlayer& player = m_sim.player(); + const std::optional local = !m_placed || &m_sim.world() != world + ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); + if (local && on_grid(player.pos) && std::find(tiles.begin(), tiles.end(), *local) != tiles.end()){ + return true; + } + m_sim.place(setup(world), story_to_world(*world, pose.map, tiles.front()), Pokemon::facing_of(pose)); + m_placed = true; + return true; +} + +// Through a door or a cave mouth onto the step's far side, the player's +// facing kept: a hold goes on from there. +bool SimExecutor::cross(){ + const StoryWorld* world = m_far ? sim_world(m_far->map) : nullptr; + const std::vector tiles = m_far ? Pokemon::tiles_of(*m_far) : std::vector{}; + if (world == nullptr || tiles.empty()){ + return false; + } + m_sim.place(setup(world), story_to_world(*world, m_far->map, tiles.front()), std::nullopt); + return true; +} + +// Why the player does not stand on one of `pose`'s tiles, or "" if they +// do or the simulation cannot tell (no map, or not placed yet). +std::string SimExecutor::off_pose(const Pose& pose) const{ + const std::vector tiles = Pokemon::tiles_of(pose); + if (!m_placed || tiles.empty() || sim_world(pose.map) == nullptr){ + return ""; + } + const SimPlayer& player = m_sim.player(); + const TilePos at = nearest_tile(player.pos); + // In world tiles: a pose a leg worked out from the map it started on + // may lie past that map's edge, on the next map (Twinleaf's exit). + // story_to_world() throws for a map not on the player's world. + try{ + const auto there = [&](const TilePos& tile){ return story_to_world(m_sim.world(), pose.map, tile) == at; }; + if (on_grid(player.pos) && std::ranges::any_of(tiles, there)){ + return ""; + } + }catch (const InternalProgramError&){} + return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), at), Pokemon::to_string(pose)); +} + +// The program's run into the Center: past its door, the inside shows, a missed fade or not. +Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ + if (!sync(state.pose)){ + return Pokemon::outcome_ok(); + } + run_into_center(m_io, m_walks.can_run(), [this]{ + m_misses.fade_unseen = false; + return m_sim.player().warped.has_value(); + }, [&]{ + throw GridSimFailure{step.name + ": no door north of " + to_string(m_sim.player().pos)}; + }); + return Pokemon::outcome_ok(); +} + +// Why a walking step did not end where the table says, or "". A step +// through a door the simulation did not cross is not checked: the sim's +// maps have no warps' destinations. +std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ + const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP; + const std::optional expected = step.pose_after ? step.pose_after : outcome.pose; + if (!walks || !m_placed){ + return ""; + } + if (!expected || Pokemon::tiles_of(*expected).empty()){ + m_result.unchecked.push_back(m_row + " " + step.name); + return ""; + } + const SimPlayer& player = m_sim.player(); + if (player.warped && !story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos))){ + return ""; + } + return off_pose(*expected); +} + +Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ + if (!m_start_mismatch.empty()){ + return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); + } + m_far = step.pose_after; + if (story_events().contains(step.variant)){ + return stub(); + } + // A scene goes on from where the step before left us. A route walks + // on the world it plans on (Jubilife alone has no Route 204 north of it). + const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || + step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK; + const StoryWorld* on = step.kind == StoryStepKind::ROUTE && step.target && !state.pose.map.empty() + ? story_plan_world(state.pose.map, step.target->map) : nullptr; + // A world of one map is sim_world()'s, with its people. + if (on != nullptr && on == story_plan_world(state.pose.map, state.pose.map)){ + on = nullptr; + } + if (walks && !sync(state.pose, on)){ + m_logger.log(std::format("[{}] {}: no map for {}; passed over.", m_row, step.name, Pokemon::to_string(state.pose))); + m_passed_over = true; + return Pokemon::outcome_ok(); + } + return Pokemon::StoryStepExecutor::run(state, step); +} + +Outcome SimExecutor::run(RunState& state, const StoryStep& step){ + Outcome outcome; + m_passed_over = false; + try{ + outcome = run_step(state, step); + }catch (const GridSimFailure& e){ + outcome = Pokemon::outcome_failed("sim_failure", e.message); + } + const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; + if (!mismatch.empty()){ + outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); + } + // What the simulation does not play (scenes, events, battles) ends + // where the table says it does. + if (outcome.succeeded() && step.pose_after){ + sync(*step.pose_after); + } + m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); + if (std::exchange(m_misses.missed, false) && m_result.missed_step.empty()){ + m_result.missed_step = m_row + " " + step.name; + } + if (!outcome.succeeded() && m_result.error.empty()){ + // The walker's last notes, to see why. + for (size_t i = m_notes.size() - std::min(m_notes.size(), 40); i < m_notes.size(); i++){ + m_logger.log(std::format("[{}] note: {}", m_row, m_notes[i])); + } + m_result.error = m_row + " " + Pokemon::to_string(outcome); + m_result.failed_step = m_row + " " + step.name; + } + m_result.world = m_placed ? &m_sim.world() : nullptr; + m_result.end = nearest_tile(m_sim.player().pos); + m_ran.insert(step.name); + arm(step.name); + return outcome; +} + +// Runs `range` of `rows` (the table unless given) on `executor`, stopping +// at the first failure. +Pokemon::SegmentReport run_rows_on( + SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, + const std::vector& rows +){ + std::set saved; + Pokemon::Segment segment = make_story_segment(rows, executor, saved); + Pokemon::SegmentPolicy policy; + policy.stop_at_first_failure = true; + Pokemon::SegmentHooks hooks; + hooks.reload = [](RunState&){ return Pokemon::outcome_ok(); }; + hooks.log = [&logger](const std::string& line){ logger.log(line); }; + RunState state; + return Pokemon::run_segment(state, segment, range, policy, hooks); +} + +// Runs `range` of the table on the simulation, stopping at the first failure. +UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ + SimExecutor executor(logger); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, range); + for (const std::string& step : executor.result().unchecked){ + logger.log("No end to check after " + step + "."); + } + if (!report.completed){ + return std::format("stopped at {} {}: {}", report.failed_checkpoint, report.failed_event, executor.result().error); + } + return true; +} + +// The table with row `row`'s step of `step`'s name replaced by `step`. +std::vector table_with(const std::string& row, const StoryStep& step){ + std::vector rows = story_checkpoints(); + for (StoryCheckpoint& checkpoint : rows){ + for (StoryStep& old : checkpoint.steps){ + if (checkpoint.id == row && old.name == step.name){ + old = step; + return rows; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + step.name + " in " + row); +} + +bool ends_on(const SimRun& run, const Pose& pose){ + const std::vector tiles = Pokemon::tiles_of(pose); + const std::optional local = run.world ? story_to_local(*run.world, pose.map, run.end) : std::nullopt; + return local && std::find(tiles.begin(), tiles.end(), *local) != tiles.end(); +} +std::string end_of(const SimRun& run){ + return run.world ? describe(*run.world, run.end) : "nowhere"; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h new file mode 100644 index 0000000000..7193ac8992 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -0,0 +1,292 @@ +/* BDSP AutoStory - Story simulation + * + * From: https://github.com/PokemonAutomation/ + * + * The story table's rows run as the program runs them (the segment + * runner, make_story_segment()), with the program's own walking steps + * (StoryWalkSteps) on the grid simulation; see StorySim_Tests.cpp for + * what is simulated and what is stubbed. Moved out of the tests so the + * console failure cases (SimFailureCases_Tests) run on the same executor. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StorySim_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StorySim_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_GridSim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Which detections the simulation misses on purpose (#162): the `fade`th +// door fade (run_into_door(), from 0) or the `banner`th map banner +// (run_until_map()) of the run goes unseen, though the player did go +// through. The console missed both (r75, r81). The `dark`th door run reads +// dark SIM_FALSE_DARK in, short of the door, as lab-B's did on 2026-11-08. +// The `through`th tap step (tap_to_banner(), from 0) starts on its far side, +// its banner gone unless `through_banner`: the walk before it slid onto the +// warp (lab-B 2026-11-08). The counts and flags below are the run's: how +// many fades and banners it looked for, whether a miss happened since the +// executor last looked, and whether a missed fade is still unseen. +struct SimMisses{ + std::optional fade; + std::optional banner; + std::optional dark = {}; + std::optional through = {}; + bool through_banner = false; + size_t tap_steps = 0; + size_t fades = 0; + size_t banners = 0; + size_t doors = 0; + bool missed = false; + bool fade_unseen = false; +}; + +// How many tiles a held walk goes on into a map before its location +// banner reads: "it shows a tile or a few past the border" (the table's +// route_201_by_the_path(), measured on the console). Standing still, it +// reads at once. Through a cave mouth the fade comes first, and a hold +// whose fade went unseen goes on the same way (r75, r81). +constexpr size_t SIM_BANNER_TILES = 3; +constexpr Milliseconds SIM_FALSE_DARK = Milliseconds(1800); + +// What a run on the simulation did. +struct SimRun{ + // The first failure, as "row outcome", or "". + std::string error; + // The rows and steps where an injected miss happened and where the run + // first failed, as "row step": "" if none. + std::string missed_step; + std::string failed_step; + // Walking steps that end where nothing says, as "row step". + std::vector unchecked; + // Each row run, with the fades and banners looked for before it. + struct RowStart{ + std::string row; + size_t fades; + size_t banners; + }; + std::vector rows; + // Where the player stood after the last step, if placed. + const StoryWorld* world = nullptr; + Pokemon::TilePos end; +}; + +// StoryStepIO on the simulation. A walk through a door or a cave mouth +// stops on its tile, as the console stops at the fade; a hold that misses +// the fade carries on, onto `far_side()` (the step's pose_after: the +// sim's maps have no warps' destinations) and on along it. +class SimStoryStepIO : public StoryStepIO{ +public: + SimStoryStepIO(GridSim& sim, std::vector& notes, SimMisses& misses, std::function far_side) + : m_sim(sim) + , m_route(sim, notes) + , m_misses(misses) + , m_far_side(std::move(far_side)) + {} + + virtual RouteIO& route() override{ + return m_route; + } + virtual void fight(const std::string&) override{ + m_sim.end_dialogue(); + } + virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; + virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; + virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) override{ + const SimPace pace = run ? SimPace::RUN : SimPace::WALK; + if (false_dark() && dark_from <= SIM_FALSE_DARK && SIM_FALSE_DARK < timeout){ + m_sim.hold(direction, SIM_FALSE_DARK, pace); + return true; + } + const bool warped = m_sim.hold(direction, timeout, pace).stop == SimStop::WARP; + if (warped && fade_missed()){ + m_misses.fade_unseen = true; + return false; + } + return warped; + } + // A scene may take us to another map (Mom walks us out, 00.04): with a + // dialogue open the stub scene plays it. Otherwise only a door fades. + // A fade missed on the way in stays missed: it was over before settle() + // looked, which then fails as it does on the console after 120 s. + virtual void settle(Button, const std::string& label, bool fade) override{ + const bool scene_fades = m_sim.player().dialog && m_far_side(); + if (fade && ((!m_sim.player().warped && !scene_fades) || m_misses.fade_unseen)){ + m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); + } + m_misses.fade_unseen = false; + m_sim.end_dialogue(); + } + virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) override; + +private: + // Whether the run misses this fade or this banner (SimMisses). + bool fade_missed(){ + const bool miss = m_misses.fade == m_misses.fades++; + m_misses.missed |= miss; + return miss; + } + bool false_dark(){ + const bool dark = m_misses.dark == m_misses.doors++; + m_misses.missed |= dark; + return dark; + } + bool banner_missed(){ + const bool miss = m_misses.banner == m_misses.banners++; + m_misses.missed |= miss; + return miss; + } + bool on_map(const std::string& map) const{ + return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); + } + + GridSim& m_sim; + GridSimRouteIO m_route; + SimMisses& m_misses; + std::function m_far_side; +}; + +// A scene's trigger the simulation fires from row `row` on, once the step +// `after` has run ("" from the row's start), on `map`'s `tiles`. +struct RowTrigger{ + std::string row; + std::string after; + std::string map; + SimTrigger trigger; +}; + +// When a story variable holds the value its coord events wait for: from +// row `row` on, once the step `after` has run ("" from the row's start). +struct VarState{ + std::string var; + int value; + std::string row; + std::string after; +}; + +// The story variables whose coord events the table walks onto, and from +// which row and step each holds (the definition says why each). +std::vector story_vars(); +// The maps' coord events whose story variable holds, as triggers. +std::vector story_triggers(); + +// The program's walking steps on the simulation, the rest stubbed. +class SimExecutor : public Pokemon::StoryStepExecutor{ +public: + explicit SimExecutor(Logger& logger, SimMisses misses = {}) + : m_logger(logger) + , m_misses(misses) + , m_sim({}, {0, 0}, Pokemon::Direction::NORTH, false) + , m_io(m_sim, m_notes, m_misses, [this]{ return cross(); }) + , m_walks(m_io) + {} + + const SimMisses& misses() const{ + return m_misses; + } + const SimRun& result() const{ + return m_result; + } + virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ + m_row = data.id; + m_start_mismatch = data.start ? off_pose(*data.start) : ""; + m_ran.clear(); + m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); + m_walks.begin_attempt(data.id); + arm(""); + } + virtual Pokemon::Outcome run(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; + +protected: + virtual Pokemon::Outcome route(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.route(state, step); } + virtual Pokemon::Outcome legs(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.legs(state, step); } + virtual Pokemon::Outcome step(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.step(state, step); } + virtual Pokemon::Outcome talk(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.talk(state, step); } + virtual Pokemon::Outcome mash(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.mash(state, step); } + virtual Pokemon::Outcome heal(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; + virtual Pokemon::Outcome new_game(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome options(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome answer(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome battle(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome train(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome shop(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome save(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome game(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + +private: + // A step the simulation does not play: its dialogue opened and closed. + Pokemon::Outcome stub(){ + m_sim.end_dialogue(); + return Pokemon::outcome_ok(); + } + const StoryWorld* sim_world(const std::string& map) const; + SimWorld setup(const StoryWorld* world) const; + void arm(const std::string& after); + bool sync(const Pokemon::Pose& pose, const StoryWorld* on = nullptr); + bool cross(); + std::string off_pose(const Pokemon::Pose& pose) const; + std::string check(const Pokemon::StoryStep& step, const Pokemon::Outcome& outcome); + Pokemon::Outcome run_step(Pokemon::RunState& state, const Pokemon::StoryStep& step); + + Logger& m_logger; + std::vector m_notes; + SimMisses m_misses; + GridSim m_sim; + SimStoryStepIO m_io; + StoryWalkSteps m_walks; + // The planner's worlds with sim_people() and sim_ground() on them, by world and who. + mutable std::map, std::unique_ptr> m_peopled; + // The steps of this row that have run. + std::set m_ran; + std::string m_row; + std::vector m_armed; + // Where the step running now ends, if it says: a door's far side. + std::optional m_far; + // Why the player is not on this row's start, or "". + std::string m_start_mismatch; + // Whether the player has been put on a map yet. + bool m_placed = false; + // Whether the step running now is on a room with no map. + bool m_passed_over = false; + SimRun m_result; +}; + +// Runs `range` of `rows` (the table unless given) on `executor`, stopping +// at the first failure. +Pokemon::SegmentReport run_rows_on( + SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, + const std::vector& rows = story_checkpoints() +); +// Runs `range` of the table on the simulation, stopping at the first failure. +UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range); +// The table with row `row`'s step of `step`'s name replaced by `step`. +std::vector table_with(const std::string& row, const Pokemon::StoryStep& step); +// Whether the run ended on one of `pose`'s tiles. +bool ends_on(const SimRun& run, const Pokemon::Pose& pose); +// Where the run ended, described; "nowhere" if never placed. +std::string end_of(const SimRun& run); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index a1d993191b..5097b78bca 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -50,6 +50,7 @@ #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_StorySim.h" #include "PokemonBDSP_AutoStory_StorySim_Tests.h" namespace PokemonAutomation{ @@ -67,668 +68,6 @@ using Pokemon::StoryStep; using Pokemon::StoryStepKind; using Pokemon::TilePos; -// Which detections the simulation misses on purpose (#162): the `fade`th -// door fade (run_into_door(), from 0) or the `banner`th map banner -// (run_until_map()) of the run goes unseen, though the player did go -// through. The console missed both (r75, r81). The `dark`th door run reads -// dark SIM_FALSE_DARK in, short of the door, as lab-B's did on 2026-11-08. -// The `through`th tap step (tap_to_banner(), from 0) starts on its far side, -// its banner gone unless `through_banner`: the walk before it slid onto the -// warp (lab-B 2026-11-08). The counts and flags below are the run's: how -// many fades and banners it looked for, whether a miss happened since the -// executor last looked, and whether a missed fade is still unseen. -struct SimMisses{ - std::optional fade; - std::optional banner; - std::optional dark = {}; - std::optional through = {}; - bool through_banner = false; - size_t tap_steps = 0; - size_t fades = 0; - size_t banners = 0; - size_t doors = 0; - bool missed = false; - bool fade_unseen = false; -}; - -// How many tiles a held walk goes on into a map before its location -// banner reads: "it shows a tile or a few past the border" (the table's -// route_201_by_the_path(), measured on the console). Standing still, it -// reads at once. Through a cave mouth the fade comes first, and a hold -// whose fade went unseen goes on the same way (r75, r81). -constexpr size_t SIM_BANNER_TILES = 3; -constexpr Milliseconds SIM_FALSE_DARK = 1800ms; - -// What a run on the simulation did. -struct SimRun{ - // The first failure, as "row outcome", or "". - std::string error; - // The rows and steps where an injected miss happened and where the run - // first failed, as "row step": "" if none. - std::string missed_step; - std::string failed_step; - // Walking steps that end where nothing says, as "row step". - std::vector unchecked; - // Each row run, with the fades and banners looked for before it. - struct RowStart{ - std::string row; - size_t fades; - size_t banners; - }; - std::vector rows; - // Where the player stood after the last step, if placed. - const StoryWorld* world = nullptr; - TilePos end; -}; - -// StoryStepIO on the simulation. A walk through a door or a cave mouth -// stops on its tile, as the console stops at the fade; a hold that misses -// the fade carries on, onto `far_side()` (the step's pose_after: the -// sim's maps have no warps' destinations) and on along it. -class SimStoryStepIO : public StoryStepIO{ -public: - SimStoryStepIO(GridSim& sim, std::vector& notes, SimMisses& misses, std::function far_side) - : m_sim(sim) - , m_route(sim, notes) - , m_misses(misses) - , m_far_side(std::move(far_side)) - {} - - virtual RouteIO& route() override{ - return m_route; - } - virtual void fight(const std::string&) override{ - m_sim.end_dialogue(); - } - virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string& label) override; - virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; - virtual bool run_into_door(Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) override{ - const SimPace pace = run ? SimPace::RUN : SimPace::WALK; - if (false_dark() && dark_from <= SIM_FALSE_DARK && SIM_FALSE_DARK < timeout){ - m_sim.hold(direction, SIM_FALSE_DARK, pace); - return true; - } - const bool warped = m_sim.hold(direction, timeout, pace).stop == SimStop::WARP; - if (warped && fade_missed()){ - m_misses.fade_unseen = true; - return false; - } - return warped; - } - // A scene may take us to another map (Mom walks us out, 00.04): with a - // dialogue open the stub scene plays it. Otherwise only a door fades. - // A fade missed on the way in stays missed: it was over before settle() - // looked, which then fails as it does on the console after 120 s. - virtual void settle(Button, const std::string& label, bool fade) override{ - const bool scene_fades = m_sim.player().dialog && m_far_side(); - if (fade && ((!m_sim.player().warped && !scene_fades) || m_misses.fade_unseen)){ - m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); - } - m_misses.fade_unseen = false; - m_sim.end_dialogue(); - } - virtual std::optional tap_to_banner(Direction direction, const std::string& map, size_t max_taps) override; - -private: - // Whether the run misses this fade or this banner (SimMisses). - bool fade_missed(){ - const bool miss = m_misses.fade == m_misses.fades++; - m_misses.missed |= miss; - return miss; - } - bool false_dark(){ - const bool dark = m_misses.dark == m_misses.doors++; - m_misses.missed |= dark; - return dark; - } - bool banner_missed(){ - const bool miss = m_misses.banner == m_misses.banners++; - m_misses.missed |= miss; - return miss; - } - bool on_map(const std::string& map) const{ - return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); - } - - GridSim& m_sim; - GridSimRouteIO m_route; - SimMisses& m_misses; - std::function m_far_side; -}; - -// A hold until something stops us. A door stops it at the fade, which -// fails the step; a fade missed lets the hold go on past the mouth (r81's -// timed walk south out of the Ravaged Path, onto Route 204's cliff). -void SimStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ - m_sim.tap(direction, ROUTE_TURN_TAP, false); - Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); - SimMove move = m_sim.hold(direction, limit, SimPace::WALK); - if (move.stop == SimStop::WARP && fade_missed() && m_far_side()){ - limit -= std::min(limit, move.time); - move = m_sim.hold(direction, limit, SimPace::WALK); - } - if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ - m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); - } -} - -// The D-pad, a tile at a time, until `map`'s banner reads; through a door -// the walk goes on beyond it (the fade eats no tiles of a hold). -bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&){ - const bool miss = banner_missed(); - size_t on = 0; - for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ - SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); - const bool crossed = move.stop == SimStop::WARP && m_far_side(); - const bool stopped = !crossed && (move.distance == 0 || move.stop != SimStop::DONE); - on = on_map(map) ? on + 1 : 0; - if (on > 0 && (on > SIM_BANNER_TILES || stopped) && !miss){ - return true; - } - if (stopped){ - return false; - } - } - return false; -} - -// D-pad taps, each looked at, until the fade and then the banner (the -// console's ConsoleStoryStepIO::tap_to_banner()): none if the banner shows -// before the first. Each look stands still, so a banner on the far side -// reads at once. A fade seen ends the taps, -// banner or not; with the fade missed the next look still sees the banner. -std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ - if (m_misses.through == m_misses.tap_steps++){ - m_misses.missed = true; - if (m_far_side() && m_misses.through_banner){ - return 0; - } - } - bool crossed = false; - for (size_t tap = 1; tap <= max_taps; tap++){ - const SimMove move = m_sim.tap(direction, 160ms, false); - if (move.stop == SimStop::DIALOG){ - return std::nullopt; - } - bool faded = false; - if (move.stop == SimStop::WARP){ - faded = !fade_missed(); - crossed = m_far_side(); - } - if (crossed && on_map(map) && !banner_missed()){ - return tap; - } - if (faded){ - return std::nullopt; - } - } - return std::nullopt; -} - -// A scene's trigger the simulation fires from row `row` on, once the step -// `after` has run ("" from the row's start), on `map`'s `tiles`. -struct RowTrigger{ - std::string row; - std::string after; - std::string map; - SimTrigger trigger; -}; - -// When a story variable holds the value its coord events wait for: from -// row `row` on, once the step `after` has run ("" from the row's start). -struct VarState{ - std::string var; - int value; - std::string row; - std::string after; -}; - -// The story variables whose coord events the table walks onto, from the -// row (and step) the table's reasons give, with the maps' coord events -// (Diamond's zone events; Platinum's for the houses): Barry's doorstep and -// Mom's warning in 00.01, Barry's Route 201 warning, then its pull-back -// row 19 once he has warned us (r14, r16); the lake's entrance in 00.02; -// Rowan's stop and Dawn at Sandgem's edge in 00.03; Dawn's catching -// tutorial on Route 202 from 00.04's start, Mom's call once she has healed -// us; the Poketch president on Jubilife's row 40 in 00.05b; Barry on Route -// 203 in 01.01; the Gate's Hiker and Oreburgh's welcome in 01.02; Barry's -// bump in Oreburgh after Roark in 01.05; and Rowan in Jubilife in 01.07. -// Left out: the Twinleaf guitarist (spent upstairs), Platinum's rival -// steps around our bedroom's start, Dawn at Jubilife's steps (BDSP starts -// her below them: an event), and Floaroma's (10..12, 29) (Diamond only). -std::vector story_vars(){ - return { - {.var = "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", .value = 0, .row = "00.01", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 0, .row = "00.01", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 1, .row = "00.01", .after = "barry_warns_us"}, - {.var = "VAR_VERITY_LAKEFRONT_STATE", .value = 0, .row = "00.02", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 2, .row = "00.03", .after = ""}, - {.var = "VAR_SANDGEM_TOWN_STATE", .value = 0, .row = "00.03", .after = ""}, - {.var = "VAR_ROUTE_202_STATE", .value = 0, .row = "00.04", .after = ""}, - {.var = "CONSOLE_MOMS_CALL", .value = 0, .row = "00.04", .after = "mom_heals_us"}, - {.var = "VAR_POKETCH_CAMPAIGN_STATE", .value = 1, .row = "00.05b", .after = ""}, - {.var = "VAR_ROUTE_203_RIVAL_STATE", .value = 0, .row = "01.01", .after = ""}, - {.var = "VAR_OREBURGH_GATE_1F_HIKER_STATE", .value = 1, .row = "01.02", .after = ""}, - {.var = "VAR_OREBURGH_CITY_STATE", .value = 0, .row = "01.02", .after = ""}, - {.var = "VAR_OREBURGH_CITY_STATE", .value = 2, .row = "01.05", .after = ""}, - {.var = "VAR_JUBILIFE_CITY_STATE", .value = 3, .row = "01.07", .after = ""}, - }; -} - -// The maps' coord events (story_coord_events()) whose variable holds. -std::optional var_state(const CoordEvent& event){ - for (const VarState& state : story_vars()){ - if (state.var == event.var && state.value == event.value){ - return state; - } - } - return std::nullopt; -} - -RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ - return {.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; -} - -std::vector story_triggers(){ - std::vector triggers; - for (const auto& [map, json] : bdsp_map_json()){ - for (const CoordEvent& event : story_coord_events(map)){ - const std::optional state = var_state(event); - if (state){ - triggers.push_back(row_trigger(map, event, *state)); - } - } - } - return triggers; -} - -// Someone the maps do not have, on `tile` of `map`, talked to or walked round: -// from row `row` on, until row `until_row`'s step `until` has run if it is set. -struct SimPerson{ - std::string name; - std::string map; - TilePos tile; - std::string row; - std::string until_row = {}; - std::string until = {}; -}; -std::vector sim_people(){ - return { - // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). - {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04"}, - // Barry in the Gym's door, from the welcome (lab-B 2026-11-08) to his lines (r101, r104). - {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.02b", .until_row = "01.02b", .until = "barrys_lines"}, - }; -} - -// A house's stairs, entered by a step `side` from the map's "stairs" -// point into what the map draws as a wall (the table's 00.01: r8 and r9 -// for ours, r11 for Barry's). -struct SimStairs{ - std::string map; - Direction side; -}; -std::vector sim_stairs(){ - return { - {.map = "PlayerHouse2F", .side = Direction::EAST}, - {.map = "RivalHouse1F", .side = Direction::EAST}, - {.map = "RivalHouse2F", .side = Direction::WEST}, - }; -} - -// The program's walking steps on the simulation, the rest stubbed. -class SimExecutor : public Pokemon::StoryStepExecutor{ -public: - explicit SimExecutor(Logger& logger, SimMisses misses = {}) - : m_logger(logger) - , m_misses(misses) - , m_sim({}, {0, 0}, Direction::NORTH, false) - , m_io(m_sim, m_notes, m_misses, [this]{ return cross(); }) - , m_walks(m_io) - {} - - const SimMisses& misses() const{ - return m_misses; - } - const SimRun& result() const{ - return m_result; - } - virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ - m_row = data.id; - m_start_mismatch = data.start ? off_pose(*data.start) : ""; - m_ran.clear(); - m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); - m_walks.begin_attempt(data.id); - arm(""); - } - virtual Outcome run(RunState& state, const StoryStep& step) override; - -protected: - virtual Outcome route(RunState& state, const StoryStep& step) override{ return m_walks.route(state, step); } - virtual Outcome legs(RunState& state, const StoryStep& step) override{ return m_walks.legs(state, step); } - virtual Outcome step(RunState& state, const StoryStep& step) override{ return m_walks.step(state, step); } - virtual Outcome talk(RunState& state, const StoryStep& step) override{ return m_walks.talk(state, step); } - virtual Outcome mash(RunState& state, const StoryStep& step) override{ return m_walks.mash(state, step); } - virtual Outcome heal(RunState& state, const StoryStep& step) override; - virtual Outcome new_game(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome options(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome answer(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome battle(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome train(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome shop(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome save(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome game(RunState&, const StoryStep&) override{ return stub(); } - -private: - // A step the simulation does not play: its dialogue opened and closed. - Outcome stub(){ - m_sim.end_dialogue(); - return Pokemon::outcome_ok(); - } - const StoryWorld* sim_world(const std::string& map) const; - SimWorld setup(const StoryWorld* world) const; - void arm(const std::string& after); - bool sync(const Pose& pose, const StoryWorld* on = nullptr); - bool cross(); - std::string off_pose(const Pose& pose) const; - std::string check(const StoryStep& step, const Outcome& outcome); - Outcome run_step(RunState& state, const StoryStep& step); - - Logger& m_logger; - std::vector m_notes; - SimMisses m_misses; - GridSim m_sim; - SimStoryStepIO m_io; - StoryWalkSteps m_walks; - // The planner's worlds with sim_people() and sim_ground() on them, by world and who. - mutable std::map, std::unique_ptr> m_peopled; - // The steps of this row that have run. - std::set m_ran; - std::string m_row; - std::vector m_armed; - // Where the step running now ends, if it says: a door's far side. - std::optional m_far; - // Why the player is not on this row's start, or "". - std::string m_start_mismatch; - // Whether the player has been put on a map yet. - bool m_placed = false; - // Whether the step running now is on a room with no map. - bool m_passed_over = false; - SimRun m_result; -}; - -// The world the player walks on for `map`: the planner's, with what the -// console showed that the maps lack. Nothing for a room with no map. -const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ - const StoryWorld* world = story_plan_world(map, map); - std::vector here; - std::string who; - for (const SimPerson& person : sim_people()){ - const bool now = m_row >= person.row && (person.until.empty() || m_row < person.until_row || - (m_row == person.until_row && !m_ran.contains(person.until))); - if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ - here.push_back(person); - who += person.name + ";"; - } - } - const SimGround* ground = nullptr; - for (const SimGround& item : sim_ground()){ - if (world != nullptr && m_row >= item.row && story_plan_world(item.map, item.map) == world){ - ground = &item; - who += item.map + " ground;"; - } - } - if (who.empty()){ - return world; - } - std::unique_ptr& peopled = m_peopled[{world, who}]; - if (!peopled){ - peopled = ground != nullptr ? with_ground(*world, *ground) : std::make_unique(*world); - for (const SimPerson& person : here){ - peopled->block(story_to_world(*peopled, person.map, person.tile)); - } - } - return peopled.get(); -} - -SimWorld SimExecutor::setup(const StoryWorld* world) const{ - // B runs once the shoes' scene has given them: the scene ends at home. - SimWorld out{.world = world, .trainers = story_trainers(*world), .can_run = m_walks.can_run()}; - for (const SimStairs& stairs : sim_stairs()){ - if (sim_world(stairs.map) == world){ - out.doors.push_back(story_to_world(*world, stairs.map, map_point(stairs.map, "stairs").next(stairs.side))); - } - } - for (const RowTrigger& armed : m_armed){ - if (sim_world(armed.map) != world){ - continue; - } - SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; - for (const TilePos& pos : armed.trigger.tiles){ - trigger.tiles.push_back(story_to_world(*world, armed.map, pos)); - } - out.triggers.push_back(std::move(trigger)); - } - return out; -} - -// Arms the triggers of this row that start after `after`. -void SimExecutor::arm(const std::string& after){ - size_t armed = 0; - for (const RowTrigger& trigger : story_triggers()){ - if (trigger.row == m_row && trigger.after == after){ - m_armed.push_back(trigger); - armed++; - } - } - const SimPlayer& player = m_sim.player(); - if (armed > 0 && m_placed && on_grid(player.pos) && !player.dialog){ - m_sim.place(setup(&m_sim.world()), nearest_tile(player.pos), player.facing); - } -} - -// Puts the player on `pose`, on the world `on` if given, unless they stand -// on one of its tiles already. Returns whether the pose is on a map the -// simulation has. -bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ - const std::vector tiles = Pokemon::tiles_of(pose); - const StoryWorld* world = on != nullptr ? on : pose.map.empty() ? nullptr : sim_world(pose.map); - if (world == nullptr || tiles.empty()){ - return false; - } - const SimPlayer& player = m_sim.player(); - const std::optional local = !m_placed || &m_sim.world() != world - ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); - if (local && on_grid(player.pos) && std::find(tiles.begin(), tiles.end(), *local) != tiles.end()){ - return true; - } - m_sim.place(setup(world), story_to_world(*world, pose.map, tiles.front()), Pokemon::facing_of(pose)); - m_placed = true; - return true; -} - -// Through a door or a cave mouth onto the step's far side, the player's -// facing kept: a hold goes on from there. -bool SimExecutor::cross(){ - const StoryWorld* world = m_far ? sim_world(m_far->map) : nullptr; - const std::vector tiles = m_far ? Pokemon::tiles_of(*m_far) : std::vector{}; - if (world == nullptr || tiles.empty()){ - return false; - } - m_sim.place(setup(world), story_to_world(*world, m_far->map, tiles.front()), std::nullopt); - return true; -} - -// Why the player does not stand on one of `pose`'s tiles, or "" if they -// do or the simulation cannot tell (no map, or not placed yet). -std::string SimExecutor::off_pose(const Pose& pose) const{ - const std::vector tiles = Pokemon::tiles_of(pose); - if (!m_placed || tiles.empty() || sim_world(pose.map) == nullptr){ - return ""; - } - const SimPlayer& player = m_sim.player(); - const TilePos at = nearest_tile(player.pos); - // In world tiles: a pose a leg worked out from the map it started on - // may lie past that map's edge, on the next map (Twinleaf's exit). - // story_to_world() throws for a map not on the player's world. - try{ - const auto there = [&](const TilePos& tile){ return story_to_world(m_sim.world(), pose.map, tile) == at; }; - if (on_grid(player.pos) && std::ranges::any_of(tiles, there)){ - return ""; - } - }catch (const InternalProgramError&){} - return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), at), Pokemon::to_string(pose)); -} - -// The program's run into the Center: past its door, the inside shows, a missed fade or not. -Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ - if (!sync(state.pose)){ - return Pokemon::outcome_ok(); - } - run_into_center(m_io, m_walks.can_run(), [this]{ - m_misses.fade_unseen = false; - return m_sim.player().warped.has_value(); - }, [&]{ - throw GridSimFailure{step.name + ": no door north of " + to_string(m_sim.player().pos)}; - }); - return Pokemon::outcome_ok(); -} - -// Why a walking step did not end where the table says, or "". A step -// through a door the simulation did not cross is not checked: the sim's -// maps have no warps' destinations. -std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ - const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP; - const std::optional expected = step.pose_after ? step.pose_after : outcome.pose; - if (!walks || !m_placed){ - return ""; - } - if (!expected || Pokemon::tiles_of(*expected).empty()){ - m_result.unchecked.push_back(m_row + " " + step.name); - return ""; - } - const SimPlayer& player = m_sim.player(); - if (player.warped && !story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos))){ - return ""; - } - return off_pose(*expected); -} - -Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ - if (!m_start_mismatch.empty()){ - return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); - } - m_far = step.pose_after; - if (story_events().contains(step.variant)){ - return stub(); - } - // A scene goes on from where the step before left us. A route walks - // on the world it plans on (Jubilife alone has no Route 204 north of it). - const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || - step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK; - const StoryWorld* on = step.kind == StoryStepKind::ROUTE && step.target && !state.pose.map.empty() - ? story_plan_world(state.pose.map, step.target->map) : nullptr; - // A world of one map is sim_world()'s, with its people. - if (on != nullptr && on == story_plan_world(state.pose.map, state.pose.map)){ - on = nullptr; - } - if (walks && !sync(state.pose, on)){ - m_logger.log(std::format("[{}] {}: no map for {}; passed over.", m_row, step.name, Pokemon::to_string(state.pose))); - m_passed_over = true; - return Pokemon::outcome_ok(); - } - return Pokemon::StoryStepExecutor::run(state, step); -} - -Outcome SimExecutor::run(RunState& state, const StoryStep& step){ - Outcome outcome; - m_passed_over = false; - try{ - outcome = run_step(state, step); - }catch (const GridSimFailure& e){ - outcome = Pokemon::outcome_failed("sim_failure", e.message); - } - const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; - if (!mismatch.empty()){ - outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); - } - // What the simulation does not play (scenes, events, battles) ends - // where the table says it does. - if (outcome.succeeded() && step.pose_after){ - sync(*step.pose_after); - } - m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); - if (std::exchange(m_misses.missed, false) && m_result.missed_step.empty()){ - m_result.missed_step = m_row + " " + step.name; - } - if (!outcome.succeeded() && m_result.error.empty()){ - // The walker's last notes, to see why. - for (size_t i = m_notes.size() - std::min(m_notes.size(), 40); i < m_notes.size(); i++){ - m_logger.log(std::format("[{}] note: {}", m_row, m_notes[i])); - } - m_result.error = m_row + " " + Pokemon::to_string(outcome); - m_result.failed_step = m_row + " " + step.name; - } - m_result.world = m_placed ? &m_sim.world() : nullptr; - m_result.end = nearest_tile(m_sim.player().pos); - m_ran.insert(step.name); - arm(step.name); - return outcome; -} - -// Runs `range` of `rows` (the table unless given) on `executor`, stopping -// at the first failure. -Pokemon::SegmentReport run_rows_on( - SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, - const std::vector& rows = story_checkpoints() -){ - std::set saved; - Pokemon::Segment segment = make_story_segment(rows, executor, saved); - Pokemon::SegmentPolicy policy; - policy.stop_at_first_failure = true; - Pokemon::SegmentHooks hooks; - hooks.reload = [](RunState&){ return Pokemon::outcome_ok(); }; - hooks.log = [&logger](const std::string& line){ logger.log(line); }; - RunState state; - return Pokemon::run_segment(state, segment, range, policy, hooks); -} - -// Runs `range` of the table on the simulation, stopping at the first failure. -UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ - SimExecutor executor(logger); - const Pokemon::SegmentReport report = run_rows_on(executor, logger, range); - for (const std::string& step : executor.result().unchecked){ - logger.log("No end to check after " + step + "."); - } - if (!report.completed){ - return std::format("stopped at {} {}: {}", report.failed_checkpoint, report.failed_event, executor.result().error); - } - return true; -} - -// The table with row `row`'s step of `step`'s name replaced by `step`. -std::vector table_with(const std::string& row, const StoryStep& step){ - std::vector rows = story_checkpoints(); - for (StoryCheckpoint& checkpoint : rows){ - for (StoryStep& old : checkpoint.steps){ - if (checkpoint.id == row && old.name == step.name){ - old = step; - return rows; - } - } - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + step.name + " in " + row); -} - -bool ends_on(const SimRun& run, const Pose& pose){ - const std::vector tiles = Pokemon::tiles_of(pose); - const std::optional local = run.world ? story_to_local(*run.world, pose.map, run.end) : std::nullopt; - return local && std::find(tiles.begin(), tiles.end(), *local) != tiles.end(); -} -std::string end_of(const SimRun& run){ - return run.world ? describe(*run.world, run.end) : "nowhere"; -} - UnitTestResult run_exit_test(Logger& logger, const std::string& row_id, const StoryStep& old_step, const SimMisses& misses, const Pose& overshoot){ SimExecutor executor(logger, misses); const std::vector rows = table_with(row_id, old_step); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 3cf67423fd..9d38d35b83 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1714,6 +1714,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp From ca4d9ab7557c4fac4d1cef487501dc1fcec9160f Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 19:41:21 -0800 Subject: [PATCH 17/19] BDSP AutoStory: console failure cases on the story sim, known failing until fixed Sim knobs (SimWorldKnobs, all off unless a case sets them): - slides: an open leg's taps run on; onto a warp the walk sees the fade as it looks to its watchers (black: TRANSITION, dim: nothing, white: a wild battle), and the far map's banner is up or gone for the next step; - floor and fade brightness per map, judged by the program's tap_faded(); - wanderers: everyone with a wander box on the maps walks it, seeded; - late first lines for a talk. SimFailureCases_Tests runs one case per console failure. Those the program fails today are on KNOWN_FAILING with the change that is to fix them; their tests pass while they still fail and fail once they pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 2 + ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 275 ++++++++++++++++++ ...emonBDSP_AutoStory_SimFailureCases_Tests.h | 27 ++ .../PokemonBDSP_AutoStory_StorySim.cpp | 136 ++++++++- .../PokemonBDSP_AutoStory_StorySim.h | 113 ++++++- SerialPrograms/cmake/SourceFiles.cmake | 2 + 6 files changed, 541 insertions(+), 14 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index 72c29a2fa1..04fa3274c4 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/Actions/PokemonBDSP_AutoStory_Actions_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h" +#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h" @@ -40,6 +41,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_GridSim(database); add_tests_AutoStory_RecoveryWalk(database); add_tests_AutoStory_StorySim(database); + add_tests_AutoStory_SimFailureCases(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp new file mode 100644 index 0000000000..9dd3fd9b47 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -0,0 +1,275 @@ +/* BDSP AutoStory - Console failure cases on the story simulation + * + * From: https://github.com/PokemonAutomation/ + * + * One case per failure console B showed in its events and perception + * (#268's design note, the planner note), run on the story simulation + * with the knobs that make it happen there (SimWorldKnobs, SimMisses): + * walks that slide on onto a warp, fades the walks' watchers miss or read + * as a battle, banners missed or gone, dim floors, late first lines and + * people who wander. + * + * A case the program fails today is on KNOWN_FAILING with the change that + * is to fix it. Its test passes while the case still fails, and fails + * once the case passes: then take it off the list. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StorySim.h" +#include "PokemonBDSP_AutoStory_SimFailureCases_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +namespace{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::Pose; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + +// Cases the program fails today, with what is to fix each. +const std::map KNOWN_FAILING{ + {"01.05 old walk slides onto the Gate's west mouth, dim fade, banner gone", "#268 slice 2: walkers report warps"}, + {"01.05 old walk slides onto the Gate's west mouth, black fade", "#268 slice 2: walkers report warps"}, + {"01.05 old walk slides onto the Gate's west mouth, white fade", "#268 slices 2 and 3: a fade watcher that tells white from a battle"}, + {"01.05 through_the_gate is one run west", "planner: goal kinds and ms costs (PLANNER_DESIGN.md)"}, + {"any one missed fade or banner from 00.00 to 01.11: every row still passes", "#268 slice 1: door arrival = fade or banner"}, + {"01.08 with Route 204's youngster wandering (12..14, 2)", "planner: one recovery rule, a sidestep round a wanderer (PLANNER_DESIGN.md 4, 7)"}, +}; + +// The table's step `name` in row `row`. +const StoryStep& table_step(const std::string& row, const std::string& name){ + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const StoryStep& step : checkpoint.steps){ + if (checkpoint.id == row && step.name == name){ + return step; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + name + " in " + row); +} + +// Runs rows `from` to `to` of `rows` with `misses` and `knobs`: "" if they +// all pass, else where and why the run stopped. +std::string run_case( + Logger& logger, const std::string& from, const std::string& to, + SimMisses misses, SimWorldKnobs knobs, const std::vector& rows = story_checkpoints() +){ + SimExecutor executor(logger, std::move(misses), std::move(knobs)); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = from, .to = to}, rows); + return report.completed ? "" : std::format("stopped in {}: {}", executor.result().failed_step, executor.result().error); +} +UnitTestResult passes(const std::string& stopped){ + return stopped.empty() ? UnitTestResult(true) : UnitTestResult(stopped); +} + +// The old 01.05 walk west along row 22 to the tile beside the west mouth's +// warp (3, 22), as before #269 stopped routes two short of warps. +StoryStep old_walk_beside_the_west_mouth(){ + StoryStep step = table_step("01.05", "through_the_gate"); + step.target = Pokemon::tile_pose("OreburghGate", {TilePos{4, 22}}, Direction::WEST); + return step; +} + +// 01.05's walk west through the Gate whose last open leg runs a tile on; +// the old walk's slides onto the west mouth's warp to Route 203. +SimWorldKnobs gate_slide(SimFade fade, bool banner_up){ + const Pose far = *table_step("01.05", "out_of_oreburgh_gate").pose_after; + return {.slides = {{.step = "through_the_gate", .direction = Direction::WEST, .tiles = 1, + .far = far, .fade = fade, .banner_up = banner_up}}}; +} +UnitTestResult gate_old_walk_slides(Logger& logger, SimFade fade, bool banner_up){ + const std::vector rows = table_with("01.05", old_walk_beside_the_west_mouth()); + return passes(run_case(logger, "01.05", "01.05", {.fade = {}, .banner = {}}, gate_slide(fade, banner_up), rows)); +} + +// The planner's legs for 01.05's walk through the Gate: one run west +// along row 22 works on the console; at most a hold to find the row first. +UnitTestResult gate_plan_one_run(Logger& logger){ + const StoryWorld* world = story_plan_world("OreburghGate", "OreburghGate"); + const std::vector from{story_to_world(*world, "OreburghGate", {27, 22}), story_to_world(*world, "OreburghGate", {26, 22})}; + const TilePos goal = story_to_world(*world, "OreburghGate", {5, 22}); + const auto plan = plan_recovered_route(*world, from, [&](const TilePos& pos){ return pos == goal; }, *story_route_costs(table_step("01.05", "through_the_gate").variant)); + if (!plan){ + return "no plan"; + } + std::string legs; + for (const PlannedLeg& leg : *plan){ + legs += (legs.empty() ? "" : ", ") + to_string(leg.leg); + } + logger.log("through_the_gate plans: " + legs); + return plan->size() <= 2 ? UnitTestResult(true) : UnitTestResult(std::format("{} legs: {}", plan->size(), legs)); +} + +// Each fade and each banner the clean run looks for, missed alone: the +// row it falls in must still pass. A door step accepts only its fade +// today, so a missed fade there fails a real arrival (#268's Monte Carlo, +// 19/20 on 01.05). +UnitTestResult every_single_miss(Logger& logger){ + SimExecutor clean(logger); + if (!run_rows_on(clean, logger, {.from = "00.00", .to = "01.11"}).completed){ + return "the run fails without misses: " + clean.result().error; + } + const std::vector& rows = clean.result().rows; + std::vector failed; + const auto miss = [&](bool fade, size_t index){ + size_t k = 0; + while (k + 1 < rows.size() && (fade ? rows[k + 1].fades : rows[k + 1].banners) <= index){ + k++; + } + SimMisses misses{.fade = {}, .banner = {}}; + (fade ? misses.fade : misses.banner) = index - (fade ? rows[k].fades : rows[k].banners); + const std::string stopped = run_case(logger, rows[k].row, rows[k].row, misses, {}); + if (!stopped.empty()){ + failed.push_back(std::format("{} {} missed: {}", fade ? "fade" : "banner", index, stopped)); + } + }; + for (size_t i = 0; i < clean.misses().fades; i++){ + miss(true, i); + } + for (size_t i = 0; i < clean.misses().banners; i++){ + miss(false, i); + } + std::string out = std::format("{} of {} single misses fail their row:", failed.size(), clean.misses().fades + clean.misses().banners); + for (const std::string& line : failed){ + out += "\n " + line; + } + return failed.empty() ? UnitTestResult(true) : UnitTestResult(out); +} + +// Oreburgh's street at night (88, game clock 00:25; 104 by day, r74), the +// Gate's dim floor (46) and a cave mouth's dim fade (45 to 64): the tap +// steps judge their fades with tap_faded(), which took the Gate's floor +// for a fade under the old "brightness under 75" (lab-B 2026-11-08). +UnitTestResult night_and_dim_floors(Logger& logger){ + SimWorldKnobs knobs{ + .floor = {{"OreburghCity", 88}, {"Route203", 88}, {"OreburghGate", 46}}, + .fade_into = {{"OreburghGate", 64}, {"OreburghCity", 255}, {"Route203", 255}}, + }; + return passes(run_case(logger, "01.02", "01.05", {.fade = {}, .banner = {}}, knobs)); +} + +// 01.03: Roark's first line in the mine comes after the camera zooms in on +// us, some seconds after the A press (r98; the old event waited 8 s). +UnitTestResult roark_speaks_late(Logger& logger){ + std::string talk; + for (const StoryCheckpoint& row : story_checkpoints()){ + for (const StoryStep& step : row.steps){ + if (row.id == "01.03" && step.kind == StoryStepKind::TALK){ + talk = step.name; + } + } + } + return passes(run_case(logger, "01.03", "01.03", {.fade = {}, .banner = {}}, {.first_line = {{talk, 7000ms}}})); +} + +// `row` with everyone on its maps walking their wander boxes, seeds 1 to 8. +UnitTestResult wanderers_move(Logger& logger, const std::string& row){ + std::vector failed; + for (uint64_t seed = 1; seed <= 8; seed++){ + const std::string stopped = run_case(logger, row, row, {.fade = {}, .banner = {}}, {.wander_seed = seed}); + if (!stopped.empty()){ + failed.push_back(std::format("seed {}: {}", seed, stopped)); + } + } + std::string out = std::format("{} of 8 seeds fail:", failed.size()); + for (const std::string& line : failed){ + out += "\n " + line; + } + return failed.empty() ? UnitTestResult(true) : UnitTestResult(out); +} + +struct FailureCaseInput{ + std::string name; + std::function body; +}; +// Whether a case is expected to fail is KNOWN_FAILING's, by name. +struct FailureCaseExpectation{ +}; +struct FailureCase{ + FailureCaseInput input; + FailureCaseExpectation expectation; +}; + +class Test_AutoStoryFailureCase : public UnitTest{ +public: + explicit Test_AutoStoryFailureCase(FailureCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Console failure on the sim: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + UnitTestResult result; + try{ + result = m_case.input.body(logger); + }catch (Exception& e){ + result = std::string(e.name()) + ": " + e.message(); + } + const auto known = KNOWN_FAILING.find(m_case.input.name); + if (known == KNOWN_FAILING.end()){ + return result; + } + if (result.result == UnitTestResult::PASSED){ + return "on KNOWN_FAILING (" + known->second + ") but passes now: take it off the list."; + } + logger.log("Known failing until " + known->second + ": " + result.message); + return true; + } + +private: + FailureCase m_case; +}; + +} // namespace + +const FailureCase AUTO_STORY_FAILURE_CASES[] = { + {.input = {"01.05 through_the_gate's last leg runs a tile on (lab-B 2026-11-08 15:31)", [](Logger& logger){ + return passes(run_case(logger, "01.05", "01.05", {.fade = {}, .banner = {}}, gate_slide(SimFade::DIM, false))); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, dim fade, banner gone", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::DIM, false); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, dim fade, banner up", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::DIM, true); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, black fade", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::BLACK, true); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, white fade", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::WHITE, true); + }}, .expectation = {}}, + {.input = {"01.05 through_the_gate is one run west", gate_plan_one_run}, .expectation = {}}, + {.input = {"any one missed fade or banner from 00.00 to 01.11: every row still passes", every_single_miss}, .expectation = {}}, + {.input = {"01.02 to 01.05 at night, the Gate's dim floor", night_and_dim_floors}, .expectation = {}}, + {.input = {"01.03 Roark's first line 7 s after the A press", roark_speaks_late}, .expectation = {}}, + {.input = {"01.03 with Oreburgh's people wandering (the pokefan on 45, 37..39)", [](Logger& logger){ + return wanderers_move(logger, "01.03"); + }}, .expectation = {}}, + {.input = {"01.08 with Route 204's youngster wandering (12..14, 2)", [](Logger& logger){ + return wanderers_move(logger, "01.08"); + }}, .expectation = {}}, +}; + +void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_FAILURE_CASES){ + database.add(item); + } +} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h new file mode 100644 index 0000000000..b196c4baf9 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h @@ -0,0 +1,27 @@ +/* BDSP AutoStory - Console failure cases on the story simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_SimFailureCases_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_SimFailureCases_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// Each failure console B showed in events and perception, run on the story +// simulation; the ones the program still fails are known failing. +void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index fd6b86de1e..6b2fde5764 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -66,11 +66,21 @@ bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, cons return false; } +double SimStoryStepIO::floor_here() const{ + for (const auto& [map, brightness] : m_knobs.floor){ + if (on_map(map)){ + return brightness; + } + } + return SIM_FLOOR; +} + // D-pad taps, each looked at, until the fade and then the banner (the // console's ConsoleStoryStepIO::tap_to_banner()): none if the banner shows // before the first. Each look stands still, so a banner on the far side -// reads at once. A fade seen ends the taps, -// banner or not; with the fade missed the next look still sees the banner. +// reads at once. A look the program's tap_faded() takes for the fade ends +// the taps, banner or not: a warp's fade, or a dim floor read as one; with +// the fade missed the next look still sees the banner. std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ if (m_misses.through == m_misses.tap_steps++){ m_misses.missed = true; @@ -78,27 +88,79 @@ std::optional SimStoryStepIO::tap_to_banner(Direction direction, const s return 0; } } + if (std::exchange(m_misses.banner_up, "") == map){ + return 0; + } bool crossed = false; for (size_t tap = 1; tap <= max_taps; tap++){ + const double before = floor_here(); const SimMove move = m_sim.tap(direction, 160ms, false); if (move.stop == SimStop::DIALOG){ return std::nullopt; } - bool faded = false; + double look = floor_here(); if (move.stop == SimStop::WARP){ - faded = !fade_missed(); + const auto fade = m_knobs.fade_into.find(map); + look = fade_missed() ? look : fade == m_knobs.fade_into.end() ? SIM_DOOR_FADE : fade->second; crossed = m_far_side(); } if (crossed && on_map(map) && !banner_missed()){ return tap; } - if (faded){ + if (tap_faded(before, look)){ return std::nullopt; } } return std::nullopt; } +WalkResult SimKnobRouteIO::walk_taps(Direction direction, size_t tiles, const std::string& label){ + const WalkResult result = GridSimRouteIO::walk_taps(direction, tiles, label); + if (result.stop != WalkStop::LIMIT || m_slid_steps.contains(m_step)){ + return result; + } + for (const SimSlide& item : m_knobs.slides){ + if (item.step == m_step && item.direction == direction){ + m_slid_steps.insert(m_step); + return slide_on(item, result); + } + } + return result; +} + +// The taps past the leg's end. Onto a warp the walk sees what the fade +// looks like to its watchers: a black fade ends it (TRANSITION), a white +// one is a wild battle to it, a dim one nothing. +WalkResult SimKnobRouteIO::slide_on(const SimSlide& slide, WalkResult result){ + m_misses.slid = true; + for (size_t tap = 0; tap < slide.tiles; tap++){ + const SimMove move = m_grid.tap(slide.direction, ROUTE_MS_PER_TILE_ACROSS, false); + if (move.stop != SimStop::WARP){ + note(std::format("[Sim] slid a tile on to {}.", to_string(m_grid.player().pos)), RouteNote::LOG); + continue; + } + note("[Sim] slid onto a warp to " + Pokemon::to_string(slide.far) + ".", RouteNote::LOG); + m_cross(slide.far); + m_misses.banner_up = slide.banner_up ? slide.far.map : ""; + if (slide.fade == SimFade::BLACK){ + result.stop = WalkStop::TRANSITION; + }else if (slide.fade == SimFade::WHITE){ + result.wild_battles++; + } + return result; + } + return result; +} + +bool SimKnobRouteIO::dialog_within(Milliseconds wait, Color color){ + const auto late = m_knobs.first_line.find(m_step); + if (late != m_knobs.first_line.end() && late->second > wait){ + note(std::format("[Sim] {}: the first line comes after {} ms, past the {} ms wait.", m_step, late->second.count(), wait.count()), RouteNote::LOG); + return false; + } + return GridSimRouteIO::dialog_within(wait, color); +} + // The story variables whose coord events the table walks onto, from the // row (and step) the table's reasons give, with the maps' coord events // (Diamond's zone events; Platinum's for the houses): Barry's doorstep and @@ -252,6 +314,50 @@ SimWorld SimExecutor::setup(const StoryWorld* world) const{ } out.triggers.push_back(std::move(trigger)); } + out.wanderers = wanderers(*world); + return out; +} + +namespace{ +bool on_world(const StoryWorld& world, const std::string& map){ + try{ + story_to_world(world, map, {0, 0}); + return true; + }catch (const InternalProgramError&){ + return false; + } +} +} // namespace + +// Everyone with a wander box on `world`'s maps, walking it from their tile +// (SimWorldKnobs::wander_seed), each with their own seed and start time. +std::vector SimExecutor::wanderers(const StoryWorld& world) const{ + std::vector out; + if (!m_knobs.wander_seed){ + return out; + } + for (const auto& [map, json] : bdsp_map_json()){ + if (!on_world(world, map)){ + continue; + } + for (const auto& object : story_map(map).objects){ + if (!object.wander){ + continue; + } + const uint64_t seed = *m_knobs.wander_seed * 1000003 + out.size() * 7919 + (uint64_t)(object.x * 31 + object.y); + const TilePos low = story_to_world(world, map, {object.wander->x0, object.wander->y0}); + const TilePos high = story_to_world(world, map, {object.wander->x1, object.wander->y1}); + out.push_back({ + .name = object.name, + .box = {.x0 = low.x, .y0 = low.y, .x1 = high.x, .y1 = high.y}, + .pos = story_to_world(world, map, {object.x, object.y}), + .seed = seed, + .step_interval = Milliseconds(2000), + .elapsed = Milliseconds(0), + .time_offset = Milliseconds((int64_t)(seed % 2000)), + }); + } + } return out; } @@ -279,6 +385,10 @@ bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ if (world == nullptr || tiles.empty()){ return false; } + // The program thinks we are on `pose`; we walk on from where the slide left us. + if (m_astray && m_placed){ + return true; + } const SimPlayer& player = m_sim.player(); const std::optional local = !m_placed || &m_sim.world() != world ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); @@ -293,12 +403,15 @@ bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ // Through a door or a cave mouth onto the step's far side, the player's // facing kept: a hold goes on from there. bool SimExecutor::cross(){ - const StoryWorld* world = m_far ? sim_world(m_far->map) : nullptr; - const std::vector tiles = m_far ? Pokemon::tiles_of(*m_far) : std::vector{}; + return m_far && cross_to(*m_far); +} +bool SimExecutor::cross_to(const Pose& far){ + const StoryWorld* world = sim_world(far.map); + const std::vector tiles = Pokemon::tiles_of(far); if (world == nullptr || tiles.empty()){ return false; } - m_sim.place(setup(world), story_to_world(*world, m_far->map, tiles.front()), std::nullopt); + m_sim.place(setup(world), story_to_world(*world, far.map, tiles.front()), std::nullopt); return true; } @@ -346,6 +459,10 @@ std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ if (!walks || !m_placed){ return ""; } + if (m_astray){ + m_result.unchecked.push_back(m_row + " " + step.name + " (slid on)"); + return ""; + } if (!expected || Pokemon::tiles_of(*expected).empty()){ m_result.unchecked.push_back(m_row + " " + step.name); return ""; @@ -386,11 +503,13 @@ Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ Outcome SimExecutor::run(RunState& state, const StoryStep& step){ Outcome outcome; m_passed_over = false; + m_step = step.name; try{ outcome = run_step(state, step); }catch (const GridSimFailure& e){ outcome = Pokemon::outcome_failed("sim_failure", e.message); } + m_astray |= std::exchange(m_misses.slid, false); const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; if (!mismatch.empty()){ outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); @@ -398,6 +517,7 @@ Outcome SimExecutor::run(RunState& state, const StoryStep& step){ // What the simulation does not play (scenes, events, battles) ends // where the table says it does. if (outcome.succeeded() && step.pose_after){ + m_astray = false; sync(*step.pose_after); } m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index 7193ac8992..e4bbe4cfc1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -44,7 +44,9 @@ namespace PokemonBDSP{ // its banner gone unless `through_banner`: the walk before it slid onto the // warp (lab-B 2026-11-08). The counts and flags below are the run's: how // many fades and banners it looked for, whether a miss happened since the -// executor last looked, and whether a missed fade is still unseen. +// executor last looked, whether a missed fade is still unseen, whether a +// walk slid on (SimSlide) since the executor last looked, and the map whose +// banner a slide left up for the next step. struct SimMisses{ std::optional fade; std::optional banner; @@ -57,6 +59,82 @@ struct SimMisses{ size_t doors = 0; bool missed = false; bool fade_unseen = false; + bool slid = false; + std::string banner_up = {}; +}; + +// How a warp's fade looks to the console's watchers (#268's design note). +enum class SimFade{ + // A door's: near black. Every watcher of a black screen sees it. + BLACK, + // A cave mouth's: dim, not black. A walk's strict black watcher (rgb + // sum 100, stddev 10; WalkRunner::hold()) misses it and the walk goes + // on (the Oreburgh Gate, lab-B 2026-11-08 16:03). + DIM, + // A cave exit's white: a walk's encounter-flash watcher reads it as a + // wild battle. + WHITE, +}; + +// An open leg that runs on past its end: the walk taps of the step `step` +// toward `direction` go `tiles` further, once per step. Onto a warp, the +// player lands on `far` (the sim's maps have no warps' destinations), the +// walk sees the fade as `fade` looks, and the far map's banner is still up +// for the next step (`banner_up`) or gone (01.05, lab-B 2026-11-08 15:31). +struct SimSlide{ + std::string step; + Pokemon::Direction direction = Pokemon::Direction::WEST; + size_t tiles = 1; + Pokemon::Pose far = {}; + SimFade fade = SimFade::DIM; + bool banner_up = false; +}; + +// What the console showed that the plain simulation leaves out, each off +// unless set. All of it is deterministic: wanderers walk from `wander_seed`. +struct SimWorldKnobs{ + std::vector slides = {}; + // The mean brightness (0 to 255) of a map's floor, by JSON map name, and + // of the fade into a map; a tap step judges its fade from these with the + // program's tap_faded(). Unset: 104 (Oreburgh's street by day) and 7 + // (a door's black). + std::map floor = {}; + std::map fade_into = {}; + // People with a wander box on their map walk it, a step tried every 2 s. + std::optional wander_seed = std::nullopt; + // How long after the A press a talk's first line shows, by step name. + std::map first_line = {}; +}; + +// The walker's RouteIO on the story simulation, with SimWorldKnobs' slides +// and late first lines. `step` names the step running now; `cross` puts +// the player on a pose past a warp. +class SimKnobRouteIO : public GridSimRouteIO{ +public: + SimKnobRouteIO( + GridSim& sim, std::vector& notes, SimMisses& misses, const SimWorldKnobs& knobs, + const std::string& step, std::function cross + ) + : GridSimRouteIO(sim, notes) + , m_grid(sim) + , m_misses(misses) + , m_knobs(knobs) + , m_step(step) + , m_cross(std::move(cross)) + {} + + virtual WalkResult walk_taps(Pokemon::Direction direction, size_t tiles, const std::string& label) override; + virtual bool dialog_within(Milliseconds wait, Color color) override; + +private: + WalkResult slide_on(const SimSlide& slide, WalkResult result); + + GridSim& m_grid; + SimMisses& m_misses; + const SimWorldKnobs& m_knobs; + const std::string& m_step; + std::function m_cross; + std::set m_slid_steps; }; // How many tiles a held walk goes on into a map before its location @@ -65,7 +143,13 @@ struct SimMisses{ // reads at once. Through a cave mouth the fade comes first, and a hold // whose fade went unseen goes on the same way (r75, r81). constexpr size_t SIM_BANNER_TILES = 3; +// How far into a door run SimMisses::dark reads dark, short of the door. constexpr Milliseconds SIM_FALSE_DARK = Milliseconds(1800); +// Brightness (0 to 255) of a floor where SimWorldKnobs does not say: +// Oreburgh's street by day (r74). +constexpr double SIM_FLOOR = 104; +// Brightness of a fade where SimWorldKnobs does not say: a door's black (by hand: 7). +constexpr double SIM_DOOR_FADE = 7; // What a run on the simulation did. struct SimRun{ @@ -95,10 +179,14 @@ struct SimRun{ // sim's maps have no warps' destinations) and on along it. class SimStoryStepIO : public StoryStepIO{ public: - SimStoryStepIO(GridSim& sim, std::vector& notes, SimMisses& misses, std::function far_side) + SimStoryStepIO( + GridSim& sim, std::vector& notes, SimMisses& misses, const SimWorldKnobs& knobs, + const std::string& step, std::function far_side, std::function cross + ) : m_sim(sim) - , m_route(sim, notes) + , m_route(sim, notes, misses, knobs, step, std::move(cross)) , m_misses(misses) + , m_knobs(knobs) , m_far_side(std::move(far_side)) {} @@ -157,10 +245,13 @@ class SimStoryStepIO : public StoryStepIO{ bool on_map(const std::string& map) const{ return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); } + // The brightness of the floor the player stands on (SimWorldKnobs::floor). + double floor_here() const; GridSim& m_sim; - GridSimRouteIO m_route; + SimKnobRouteIO m_route; SimMisses& m_misses; + const SimWorldKnobs& m_knobs; std::function m_far_side; }; @@ -191,11 +282,12 @@ std::vector story_triggers(); // The program's walking steps on the simulation, the rest stubbed. class SimExecutor : public Pokemon::StoryStepExecutor{ public: - explicit SimExecutor(Logger& logger, SimMisses misses = {}) + explicit SimExecutor(Logger& logger, SimMisses misses = {}, SimWorldKnobs knobs = {}) : m_logger(logger) , m_misses(misses) + , m_knobs(std::move(knobs)) , m_sim({}, {0, 0}, Pokemon::Direction::NORTH, false) - , m_io(m_sim, m_notes, m_misses, [this]{ return cross(); }) + , m_io(m_sim, m_notes, m_misses, m_knobs, m_step, [this]{ return cross(); }, [this](const Pokemon::Pose& far){ cross_to(far); }) , m_walks(m_io) {} @@ -209,6 +301,7 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ m_row = data.id; m_start_mismatch = data.start ? off_pose(*data.start) : ""; m_ran.clear(); + m_astray = false; m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); m_walks.begin_attempt(data.id); arm(""); @@ -242,6 +335,8 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ void arm(const std::string& after); bool sync(const Pokemon::Pose& pose, const StoryWorld* on = nullptr); bool cross(); + bool cross_to(const Pokemon::Pose& far); + std::vector wanderers(const StoryWorld& world) const; std::string off_pose(const Pokemon::Pose& pose) const; std::string check(const Pokemon::StoryStep& step, const Pokemon::Outcome& outcome); Pokemon::Outcome run_step(Pokemon::RunState& state, const Pokemon::StoryStep& step); @@ -249,6 +344,9 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ Logger& m_logger; std::vector m_notes; SimMisses m_misses; + SimWorldKnobs m_knobs; + // The step running now. + std::string m_step; GridSim m_sim; SimStoryStepIO m_io; StoryWalkSteps m_walks; @@ -266,6 +364,9 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ bool m_placed = false; // Whether the step running now is on a room with no map. bool m_passed_over = false; + // Whether a walk slid on (SimSlide), so the player is not where the + // program thinks, until a step's pose_after puts them right. + bool m_astray = false; SimRun m_result; }; diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 9d38d35b83..7f5a6de0a3 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1712,6 +1712,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp From 769e8b7f607d0e986fedb79dcd34bc8dcb446a0c Mon Sep 17 00:00:00 2001 From: Di Fan <26423504+dayfine@users.noreply.github.com> Date: Sun, 8 Nov 2026 19:58:04 -0800 Subject: [PATCH 18/19] BDSP AutoStory: console failure cases on the story sim (known failing until fixed) (#281) * BDSP AutoStory: move the story sim's executor out of its tests SimStoryStepIO, SimExecutor and the run helpers move unchanged from StorySim_Tests.cpp to Simulation/PokemonBDSP_AutoStory_StorySim.{h,cpp}, so other test files can run rows on the same simulation. The header qualifies Pokemon:: names; the helpers that were file-local stay in an anonymous namespace. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: console failure cases on the story sim, known failing until fixed Sim knobs (SimWorldKnobs, all off unless a case sets them): - slides: an open leg's taps run on; onto a warp the walk sees the fade as it looks to its watchers (black: TRANSITION, dim: nothing, white: a wild battle), and the far map's banner is up or gone for the next step; - floor and fade brightness per map, judged by the program's tap_faded(); - wanderers: everyone with a wander box on the maps walks it, seeded; - late first lines for a talk. SimFailureCases_Tests runs one case per console failure. Those the program fails today are on KNOWN_FAILING with the change that is to fix them; their tests pass while they still fail and fail once they pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --------- Co-authored-by: Claude Opus 5.5 --- .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 2 + ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 275 ++++++++ ...emonBDSP_AutoStory_SimFailureCases_Tests.h | 27 + .../PokemonBDSP_AutoStory_StorySim.cpp | 599 ++++++++++++++++ .../PokemonBDSP_AutoStory_StorySim.h | 393 +++++++++++ .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 663 +----------------- SerialPrograms/cmake/SourceFiles.cmake | 4 + 7 files changed, 1301 insertions(+), 662 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index 72c29a2fa1..04fa3274c4 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/Actions/PokemonBDSP_AutoStory_Actions_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h" +#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h" @@ -40,6 +41,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_GridSim(database); add_tests_AutoStory_RecoveryWalk(database); add_tests_AutoStory_StorySim(database); + add_tests_AutoStory_SimFailureCases(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp new file mode 100644 index 0000000000..9dd3fd9b47 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -0,0 +1,275 @@ +/* BDSP AutoStory - Console failure cases on the story simulation + * + * From: https://github.com/PokemonAutomation/ + * + * One case per failure console B showed in its events and perception + * (#268's design note, the planner note), run on the story simulation + * with the knobs that make it happen there (SimWorldKnobs, SimMisses): + * walks that slide on onto a warp, fades the walks' watchers miss or read + * as a battle, banners missed or gone, dim floors, late first lines and + * people who wander. + * + * A case the program fails today is on KNOWN_FAILING with the change that + * is to fix it. Its test passes while the case still fails, and fails + * once the case passes: then take it off the list. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StorySim.h" +#include "PokemonBDSP_AutoStory_SimFailureCases_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +namespace{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::Pose; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + +// Cases the program fails today, with what is to fix each. +const std::map KNOWN_FAILING{ + {"01.05 old walk slides onto the Gate's west mouth, dim fade, banner gone", "#268 slice 2: walkers report warps"}, + {"01.05 old walk slides onto the Gate's west mouth, black fade", "#268 slice 2: walkers report warps"}, + {"01.05 old walk slides onto the Gate's west mouth, white fade", "#268 slices 2 and 3: a fade watcher that tells white from a battle"}, + {"01.05 through_the_gate is one run west", "planner: goal kinds and ms costs (PLANNER_DESIGN.md)"}, + {"any one missed fade or banner from 00.00 to 01.11: every row still passes", "#268 slice 1: door arrival = fade or banner"}, + {"01.08 with Route 204's youngster wandering (12..14, 2)", "planner: one recovery rule, a sidestep round a wanderer (PLANNER_DESIGN.md 4, 7)"}, +}; + +// The table's step `name` in row `row`. +const StoryStep& table_step(const std::string& row, const std::string& name){ + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const StoryStep& step : checkpoint.steps){ + if (checkpoint.id == row && step.name == name){ + return step; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + name + " in " + row); +} + +// Runs rows `from` to `to` of `rows` with `misses` and `knobs`: "" if they +// all pass, else where and why the run stopped. +std::string run_case( + Logger& logger, const std::string& from, const std::string& to, + SimMisses misses, SimWorldKnobs knobs, const std::vector& rows = story_checkpoints() +){ + SimExecutor executor(logger, std::move(misses), std::move(knobs)); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = from, .to = to}, rows); + return report.completed ? "" : std::format("stopped in {}: {}", executor.result().failed_step, executor.result().error); +} +UnitTestResult passes(const std::string& stopped){ + return stopped.empty() ? UnitTestResult(true) : UnitTestResult(stopped); +} + +// The old 01.05 walk west along row 22 to the tile beside the west mouth's +// warp (3, 22), as before #269 stopped routes two short of warps. +StoryStep old_walk_beside_the_west_mouth(){ + StoryStep step = table_step("01.05", "through_the_gate"); + step.target = Pokemon::tile_pose("OreburghGate", {TilePos{4, 22}}, Direction::WEST); + return step; +} + +// 01.05's walk west through the Gate whose last open leg runs a tile on; +// the old walk's slides onto the west mouth's warp to Route 203. +SimWorldKnobs gate_slide(SimFade fade, bool banner_up){ + const Pose far = *table_step("01.05", "out_of_oreburgh_gate").pose_after; + return {.slides = {{.step = "through_the_gate", .direction = Direction::WEST, .tiles = 1, + .far = far, .fade = fade, .banner_up = banner_up}}}; +} +UnitTestResult gate_old_walk_slides(Logger& logger, SimFade fade, bool banner_up){ + const std::vector rows = table_with("01.05", old_walk_beside_the_west_mouth()); + return passes(run_case(logger, "01.05", "01.05", {.fade = {}, .banner = {}}, gate_slide(fade, banner_up), rows)); +} + +// The planner's legs for 01.05's walk through the Gate: one run west +// along row 22 works on the console; at most a hold to find the row first. +UnitTestResult gate_plan_one_run(Logger& logger){ + const StoryWorld* world = story_plan_world("OreburghGate", "OreburghGate"); + const std::vector from{story_to_world(*world, "OreburghGate", {27, 22}), story_to_world(*world, "OreburghGate", {26, 22})}; + const TilePos goal = story_to_world(*world, "OreburghGate", {5, 22}); + const auto plan = plan_recovered_route(*world, from, [&](const TilePos& pos){ return pos == goal; }, *story_route_costs(table_step("01.05", "through_the_gate").variant)); + if (!plan){ + return "no plan"; + } + std::string legs; + for (const PlannedLeg& leg : *plan){ + legs += (legs.empty() ? "" : ", ") + to_string(leg.leg); + } + logger.log("through_the_gate plans: " + legs); + return plan->size() <= 2 ? UnitTestResult(true) : UnitTestResult(std::format("{} legs: {}", plan->size(), legs)); +} + +// Each fade and each banner the clean run looks for, missed alone: the +// row it falls in must still pass. A door step accepts only its fade +// today, so a missed fade there fails a real arrival (#268's Monte Carlo, +// 19/20 on 01.05). +UnitTestResult every_single_miss(Logger& logger){ + SimExecutor clean(logger); + if (!run_rows_on(clean, logger, {.from = "00.00", .to = "01.11"}).completed){ + return "the run fails without misses: " + clean.result().error; + } + const std::vector& rows = clean.result().rows; + std::vector failed; + const auto miss = [&](bool fade, size_t index){ + size_t k = 0; + while (k + 1 < rows.size() && (fade ? rows[k + 1].fades : rows[k + 1].banners) <= index){ + k++; + } + SimMisses misses{.fade = {}, .banner = {}}; + (fade ? misses.fade : misses.banner) = index - (fade ? rows[k].fades : rows[k].banners); + const std::string stopped = run_case(logger, rows[k].row, rows[k].row, misses, {}); + if (!stopped.empty()){ + failed.push_back(std::format("{} {} missed: {}", fade ? "fade" : "banner", index, stopped)); + } + }; + for (size_t i = 0; i < clean.misses().fades; i++){ + miss(true, i); + } + for (size_t i = 0; i < clean.misses().banners; i++){ + miss(false, i); + } + std::string out = std::format("{} of {} single misses fail their row:", failed.size(), clean.misses().fades + clean.misses().banners); + for (const std::string& line : failed){ + out += "\n " + line; + } + return failed.empty() ? UnitTestResult(true) : UnitTestResult(out); +} + +// Oreburgh's street at night (88, game clock 00:25; 104 by day, r74), the +// Gate's dim floor (46) and a cave mouth's dim fade (45 to 64): the tap +// steps judge their fades with tap_faded(), which took the Gate's floor +// for a fade under the old "brightness under 75" (lab-B 2026-11-08). +UnitTestResult night_and_dim_floors(Logger& logger){ + SimWorldKnobs knobs{ + .floor = {{"OreburghCity", 88}, {"Route203", 88}, {"OreburghGate", 46}}, + .fade_into = {{"OreburghGate", 64}, {"OreburghCity", 255}, {"Route203", 255}}, + }; + return passes(run_case(logger, "01.02", "01.05", {.fade = {}, .banner = {}}, knobs)); +} + +// 01.03: Roark's first line in the mine comes after the camera zooms in on +// us, some seconds after the A press (r98; the old event waited 8 s). +UnitTestResult roark_speaks_late(Logger& logger){ + std::string talk; + for (const StoryCheckpoint& row : story_checkpoints()){ + for (const StoryStep& step : row.steps){ + if (row.id == "01.03" && step.kind == StoryStepKind::TALK){ + talk = step.name; + } + } + } + return passes(run_case(logger, "01.03", "01.03", {.fade = {}, .banner = {}}, {.first_line = {{talk, 7000ms}}})); +} + +// `row` with everyone on its maps walking their wander boxes, seeds 1 to 8. +UnitTestResult wanderers_move(Logger& logger, const std::string& row){ + std::vector failed; + for (uint64_t seed = 1; seed <= 8; seed++){ + const std::string stopped = run_case(logger, row, row, {.fade = {}, .banner = {}}, {.wander_seed = seed}); + if (!stopped.empty()){ + failed.push_back(std::format("seed {}: {}", seed, stopped)); + } + } + std::string out = std::format("{} of 8 seeds fail:", failed.size()); + for (const std::string& line : failed){ + out += "\n " + line; + } + return failed.empty() ? UnitTestResult(true) : UnitTestResult(out); +} + +struct FailureCaseInput{ + std::string name; + std::function body; +}; +// Whether a case is expected to fail is KNOWN_FAILING's, by name. +struct FailureCaseExpectation{ +}; +struct FailureCase{ + FailureCaseInput input; + FailureCaseExpectation expectation; +}; + +class Test_AutoStoryFailureCase : public UnitTest{ +public: + explicit Test_AutoStoryFailureCase(FailureCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Console failure on the sim: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + UnitTestResult result; + try{ + result = m_case.input.body(logger); + }catch (Exception& e){ + result = std::string(e.name()) + ": " + e.message(); + } + const auto known = KNOWN_FAILING.find(m_case.input.name); + if (known == KNOWN_FAILING.end()){ + return result; + } + if (result.result == UnitTestResult::PASSED){ + return "on KNOWN_FAILING (" + known->second + ") but passes now: take it off the list."; + } + logger.log("Known failing until " + known->second + ": " + result.message); + return true; + } + +private: + FailureCase m_case; +}; + +} // namespace + +const FailureCase AUTO_STORY_FAILURE_CASES[] = { + {.input = {"01.05 through_the_gate's last leg runs a tile on (lab-B 2026-11-08 15:31)", [](Logger& logger){ + return passes(run_case(logger, "01.05", "01.05", {.fade = {}, .banner = {}}, gate_slide(SimFade::DIM, false))); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, dim fade, banner gone", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::DIM, false); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, dim fade, banner up", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::DIM, true); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, black fade", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::BLACK, true); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, white fade", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::WHITE, true); + }}, .expectation = {}}, + {.input = {"01.05 through_the_gate is one run west", gate_plan_one_run}, .expectation = {}}, + {.input = {"any one missed fade or banner from 00.00 to 01.11: every row still passes", every_single_miss}, .expectation = {}}, + {.input = {"01.02 to 01.05 at night, the Gate's dim floor", night_and_dim_floors}, .expectation = {}}, + {.input = {"01.03 Roark's first line 7 s after the A press", roark_speaks_late}, .expectation = {}}, + {.input = {"01.03 with Oreburgh's people wandering (the pokefan on 45, 37..39)", [](Logger& logger){ + return wanderers_move(logger, "01.03"); + }}, .expectation = {}}, + {.input = {"01.08 with Route 204's youngster wandering (12..14, 2)", [](Logger& logger){ + return wanderers_move(logger, "01.08"); + }}, .expectation = {}}, +}; + +void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_FAILURE_CASES){ + database.add(item); + } +} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h new file mode 100644 index 0000000000..b196c4baf9 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h @@ -0,0 +1,27 @@ +/* BDSP AutoStory - Console failure cases on the story simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_SimFailureCases_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_SimFailureCases_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// Each failure console B showed in events and perception, run on the story +// simulation; the ones the program still fails are known failing. +void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp new file mode 100644 index 0000000000..6b2fde5764 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -0,0 +1,599 @@ +/* BDSP AutoStory - Story simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_SimGround.h" +#include "PokemonBDSP_AutoStory_StorySim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::Outcome; +using Pokemon::Pose; +using Pokemon::RunState; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + + +// A hold until something stops us. A door stops it at the fade, which +// fails the step; a fade missed lets the hold go on past the mouth (r81's +// timed walk south out of the Ravaged Path, onto Route 204's cliff). +void SimStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ + m_sim.tap(direction, ROUTE_TURN_TAP, false); + Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); + SimMove move = m_sim.hold(direction, limit, SimPace::WALK); + if (move.stop == SimStop::WARP && fade_missed() && m_far_side()){ + limit -= std::min(limit, move.time); + move = m_sim.hold(direction, limit, SimPace::WALK); + } + if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ + m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); + } +} + +// The D-pad, a tile at a time, until `map`'s banner reads; through a door +// the walk goes on beyond it (the fade eats no tiles of a hold). +bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&){ + const bool miss = banner_missed(); + size_t on = 0; + for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ + SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + const bool crossed = move.stop == SimStop::WARP && m_far_side(); + const bool stopped = !crossed && (move.distance == 0 || move.stop != SimStop::DONE); + on = on_map(map) ? on + 1 : 0; + if (on > 0 && (on > SIM_BANNER_TILES || stopped) && !miss){ + return true; + } + if (stopped){ + return false; + } + } + return false; +} + +double SimStoryStepIO::floor_here() const{ + for (const auto& [map, brightness] : m_knobs.floor){ + if (on_map(map)){ + return brightness; + } + } + return SIM_FLOOR; +} + +// D-pad taps, each looked at, until the fade and then the banner (the +// console's ConsoleStoryStepIO::tap_to_banner()): none if the banner shows +// before the first. Each look stands still, so a banner on the far side +// reads at once. A look the program's tap_faded() takes for the fade ends +// the taps, banner or not: a warp's fade, or a dim floor read as one; with +// the fade missed the next look still sees the banner. +std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ + if (m_misses.through == m_misses.tap_steps++){ + m_misses.missed = true; + if (m_far_side() && m_misses.through_banner){ + return 0; + } + } + if (std::exchange(m_misses.banner_up, "") == map){ + return 0; + } + bool crossed = false; + for (size_t tap = 1; tap <= max_taps; tap++){ + const double before = floor_here(); + const SimMove move = m_sim.tap(direction, 160ms, false); + if (move.stop == SimStop::DIALOG){ + return std::nullopt; + } + double look = floor_here(); + if (move.stop == SimStop::WARP){ + const auto fade = m_knobs.fade_into.find(map); + look = fade_missed() ? look : fade == m_knobs.fade_into.end() ? SIM_DOOR_FADE : fade->second; + crossed = m_far_side(); + } + if (crossed && on_map(map) && !banner_missed()){ + return tap; + } + if (tap_faded(before, look)){ + return std::nullopt; + } + } + return std::nullopt; +} + +WalkResult SimKnobRouteIO::walk_taps(Direction direction, size_t tiles, const std::string& label){ + const WalkResult result = GridSimRouteIO::walk_taps(direction, tiles, label); + if (result.stop != WalkStop::LIMIT || m_slid_steps.contains(m_step)){ + return result; + } + for (const SimSlide& item : m_knobs.slides){ + if (item.step == m_step && item.direction == direction){ + m_slid_steps.insert(m_step); + return slide_on(item, result); + } + } + return result; +} + +// The taps past the leg's end. Onto a warp the walk sees what the fade +// looks like to its watchers: a black fade ends it (TRANSITION), a white +// one is a wild battle to it, a dim one nothing. +WalkResult SimKnobRouteIO::slide_on(const SimSlide& slide, WalkResult result){ + m_misses.slid = true; + for (size_t tap = 0; tap < slide.tiles; tap++){ + const SimMove move = m_grid.tap(slide.direction, ROUTE_MS_PER_TILE_ACROSS, false); + if (move.stop != SimStop::WARP){ + note(std::format("[Sim] slid a tile on to {}.", to_string(m_grid.player().pos)), RouteNote::LOG); + continue; + } + note("[Sim] slid onto a warp to " + Pokemon::to_string(slide.far) + ".", RouteNote::LOG); + m_cross(slide.far); + m_misses.banner_up = slide.banner_up ? slide.far.map : ""; + if (slide.fade == SimFade::BLACK){ + result.stop = WalkStop::TRANSITION; + }else if (slide.fade == SimFade::WHITE){ + result.wild_battles++; + } + return result; + } + return result; +} + +bool SimKnobRouteIO::dialog_within(Milliseconds wait, Color color){ + const auto late = m_knobs.first_line.find(m_step); + if (late != m_knobs.first_line.end() && late->second > wait){ + note(std::format("[Sim] {}: the first line comes after {} ms, past the {} ms wait.", m_step, late->second.count(), wait.count()), RouteNote::LOG); + return false; + } + return GridSimRouteIO::dialog_within(wait, color); +} + +// The story variables whose coord events the table walks onto, from the +// row (and step) the table's reasons give, with the maps' coord events +// (Diamond's zone events; Platinum's for the houses): Barry's doorstep and +// Mom's warning in 00.01, Barry's Route 201 warning, then its pull-back +// row 19 once he has warned us (r14, r16); the lake's entrance in 00.02; +// Rowan's stop and Dawn at Sandgem's edge in 00.03; Dawn's catching +// tutorial on Route 202 from 00.04's start, Mom's call once she has healed +// us; the Poketch president on Jubilife's row 40 in 00.05b; Barry on Route +// 203 in 01.01; the Gate's Hiker and Oreburgh's welcome in 01.02; Barry's +// bump in Oreburgh after Roark in 01.05; and Rowan in Jubilife in 01.07. +// Left out: the Twinleaf guitarist (spent upstairs), Platinum's rival +// steps around our bedroom's start, Dawn at Jubilife's steps (BDSP starts +// her below them: an event), and Floaroma's (10..12, 29) (Diamond only). +std::vector story_vars(){ + return { + {.var = "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", .value = 0, .row = "00.01", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 0, .row = "00.01", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 1, .row = "00.01", .after = "barry_warns_us"}, + {.var = "VAR_VERITY_LAKEFRONT_STATE", .value = 0, .row = "00.02", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 2, .row = "00.03", .after = ""}, + {.var = "VAR_SANDGEM_TOWN_STATE", .value = 0, .row = "00.03", .after = ""}, + {.var = "VAR_ROUTE_202_STATE", .value = 0, .row = "00.04", .after = ""}, + {.var = "CONSOLE_MOMS_CALL", .value = 0, .row = "00.04", .after = "mom_heals_us"}, + {.var = "VAR_POKETCH_CAMPAIGN_STATE", .value = 1, .row = "00.05b", .after = ""}, + {.var = "VAR_ROUTE_203_RIVAL_STATE", .value = 0, .row = "01.01", .after = ""}, + {.var = "VAR_OREBURGH_GATE_1F_HIKER_STATE", .value = 1, .row = "01.02", .after = ""}, + {.var = "VAR_OREBURGH_CITY_STATE", .value = 0, .row = "01.02", .after = ""}, + {.var = "VAR_OREBURGH_CITY_STATE", .value = 2, .row = "01.05", .after = ""}, + {.var = "VAR_JUBILIFE_CITY_STATE", .value = 3, .row = "01.07", .after = ""}, + }; +} + +namespace{ + +// The maps' coord events (story_coord_events()) whose variable holds. +std::optional var_state(const CoordEvent& event){ + for (const VarState& state : story_vars()){ + if (state.var == event.var && state.value == event.value){ + return state; + } + } + return std::nullopt; +} + +RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ + return {.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; +} + +} // namespace + +std::vector story_triggers(){ + std::vector triggers; + for (const auto& [map, json] : bdsp_map_json()){ + for (const CoordEvent& event : story_coord_events(map)){ + const std::optional state = var_state(event); + if (state){ + triggers.push_back(row_trigger(map, event, *state)); + } + } + } + return triggers; +} + +namespace{ + +// Someone the maps do not have, on `tile` of `map`, talked to or walked round: +// from row `row` on, until row `until_row`'s step `until` has run if it is set. +struct SimPerson{ + std::string name; + std::string map; + TilePos tile; + std::string row; + std::string until_row = {}; + std::string until = {}; +}; +std::vector sim_people(){ + return { + // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). + {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04"}, + // Barry in the Gym's door, from the welcome (lab-B 2026-11-08) to his lines (r101, r104). + {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.02b", .until_row = "01.02b", .until = "barrys_lines"}, + }; +} + +// A house's stairs, entered by a step `side` from the map's "stairs" +// point into what the map draws as a wall (the table's 00.01: r8 and r9 +// for ours, r11 for Barry's). +struct SimStairs{ + std::string map; + Direction side; +}; +std::vector sim_stairs(){ + return { + {.map = "PlayerHouse2F", .side = Direction::EAST}, + {.map = "RivalHouse1F", .side = Direction::EAST}, + {.map = "RivalHouse2F", .side = Direction::WEST}, + }; +} + +} // namespace + +// The world the player walks on for `map`: the planner's, with what the +// console showed that the maps lack. Nothing for a room with no map. +const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ + const StoryWorld* world = story_plan_world(map, map); + std::vector here; + std::string who; + for (const SimPerson& person : sim_people()){ + const bool now = m_row >= person.row && (person.until.empty() || m_row < person.until_row || + (m_row == person.until_row && !m_ran.contains(person.until))); + if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ + here.push_back(person); + who += person.name + ";"; + } + } + const SimGround* ground = nullptr; + for (const SimGround& item : sim_ground()){ + if (world != nullptr && m_row >= item.row && story_plan_world(item.map, item.map) == world){ + ground = &item; + who += item.map + " ground;"; + } + } + if (who.empty()){ + return world; + } + std::unique_ptr& peopled = m_peopled[{world, who}]; + if (!peopled){ + peopled = ground != nullptr ? with_ground(*world, *ground) : std::make_unique(*world); + for (const SimPerson& person : here){ + peopled->block(story_to_world(*peopled, person.map, person.tile)); + } + } + return peopled.get(); +} + +SimWorld SimExecutor::setup(const StoryWorld* world) const{ + // B runs once the shoes' scene has given them: the scene ends at home. + SimWorld out{.world = world, .trainers = story_trainers(*world), .can_run = m_walks.can_run()}; + for (const SimStairs& stairs : sim_stairs()){ + if (sim_world(stairs.map) == world){ + out.doors.push_back(story_to_world(*world, stairs.map, map_point(stairs.map, "stairs").next(stairs.side))); + } + } + for (const RowTrigger& armed : m_armed){ + if (sim_world(armed.map) != world){ + continue; + } + SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; + for (const TilePos& pos : armed.trigger.tiles){ + trigger.tiles.push_back(story_to_world(*world, armed.map, pos)); + } + out.triggers.push_back(std::move(trigger)); + } + out.wanderers = wanderers(*world); + return out; +} + +namespace{ +bool on_world(const StoryWorld& world, const std::string& map){ + try{ + story_to_world(world, map, {0, 0}); + return true; + }catch (const InternalProgramError&){ + return false; + } +} +} // namespace + +// Everyone with a wander box on `world`'s maps, walking it from their tile +// (SimWorldKnobs::wander_seed), each with their own seed and start time. +std::vector SimExecutor::wanderers(const StoryWorld& world) const{ + std::vector out; + if (!m_knobs.wander_seed){ + return out; + } + for (const auto& [map, json] : bdsp_map_json()){ + if (!on_world(world, map)){ + continue; + } + for (const auto& object : story_map(map).objects){ + if (!object.wander){ + continue; + } + const uint64_t seed = *m_knobs.wander_seed * 1000003 + out.size() * 7919 + (uint64_t)(object.x * 31 + object.y); + const TilePos low = story_to_world(world, map, {object.wander->x0, object.wander->y0}); + const TilePos high = story_to_world(world, map, {object.wander->x1, object.wander->y1}); + out.push_back({ + .name = object.name, + .box = {.x0 = low.x, .y0 = low.y, .x1 = high.x, .y1 = high.y}, + .pos = story_to_world(world, map, {object.x, object.y}), + .seed = seed, + .step_interval = Milliseconds(2000), + .elapsed = Milliseconds(0), + .time_offset = Milliseconds((int64_t)(seed % 2000)), + }); + } + } + return out; +} + +// Arms the triggers of this row that start after `after`. +void SimExecutor::arm(const std::string& after){ + size_t armed = 0; + for (const RowTrigger& trigger : story_triggers()){ + if (trigger.row == m_row && trigger.after == after){ + m_armed.push_back(trigger); + armed++; + } + } + const SimPlayer& player = m_sim.player(); + if (armed > 0 && m_placed && on_grid(player.pos) && !player.dialog){ + m_sim.place(setup(&m_sim.world()), nearest_tile(player.pos), player.facing); + } +} + +// Puts the player on `pose`, on the world `on` if given, unless they stand +// on one of its tiles already. Returns whether the pose is on a map the +// simulation has. +bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ + const std::vector tiles = Pokemon::tiles_of(pose); + const StoryWorld* world = on != nullptr ? on : pose.map.empty() ? nullptr : sim_world(pose.map); + if (world == nullptr || tiles.empty()){ + return false; + } + // The program thinks we are on `pose`; we walk on from where the slide left us. + if (m_astray && m_placed){ + return true; + } + const SimPlayer& player = m_sim.player(); + const std::optional local = !m_placed || &m_sim.world() != world + ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); + if (local && on_grid(player.pos) && std::find(tiles.begin(), tiles.end(), *local) != tiles.end()){ + return true; + } + m_sim.place(setup(world), story_to_world(*world, pose.map, tiles.front()), Pokemon::facing_of(pose)); + m_placed = true; + return true; +} + +// Through a door or a cave mouth onto the step's far side, the player's +// facing kept: a hold goes on from there. +bool SimExecutor::cross(){ + return m_far && cross_to(*m_far); +} +bool SimExecutor::cross_to(const Pose& far){ + const StoryWorld* world = sim_world(far.map); + const std::vector tiles = Pokemon::tiles_of(far); + if (world == nullptr || tiles.empty()){ + return false; + } + m_sim.place(setup(world), story_to_world(*world, far.map, tiles.front()), std::nullopt); + return true; +} + +// Why the player does not stand on one of `pose`'s tiles, or "" if they +// do or the simulation cannot tell (no map, or not placed yet). +std::string SimExecutor::off_pose(const Pose& pose) const{ + const std::vector tiles = Pokemon::tiles_of(pose); + if (!m_placed || tiles.empty() || sim_world(pose.map) == nullptr){ + return ""; + } + const SimPlayer& player = m_sim.player(); + const TilePos at = nearest_tile(player.pos); + // In world tiles: a pose a leg worked out from the map it started on + // may lie past that map's edge, on the next map (Twinleaf's exit). + // story_to_world() throws for a map not on the player's world. + try{ + const auto there = [&](const TilePos& tile){ return story_to_world(m_sim.world(), pose.map, tile) == at; }; + if (on_grid(player.pos) && std::ranges::any_of(tiles, there)){ + return ""; + } + }catch (const InternalProgramError&){} + return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), at), Pokemon::to_string(pose)); +} + +// The program's run into the Center: past its door, the inside shows, a missed fade or not. +Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ + if (!sync(state.pose)){ + return Pokemon::outcome_ok(); + } + run_into_center(m_io, m_walks.can_run(), [this]{ + m_misses.fade_unseen = false; + return m_sim.player().warped.has_value(); + }, [&]{ + throw GridSimFailure{step.name + ": no door north of " + to_string(m_sim.player().pos)}; + }); + return Pokemon::outcome_ok(); +} + +// Why a walking step did not end where the table says, or "". A step +// through a door the simulation did not cross is not checked: the sim's +// maps have no warps' destinations. +std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ + const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP; + const std::optional expected = step.pose_after ? step.pose_after : outcome.pose; + if (!walks || !m_placed){ + return ""; + } + if (m_astray){ + m_result.unchecked.push_back(m_row + " " + step.name + " (slid on)"); + return ""; + } + if (!expected || Pokemon::tiles_of(*expected).empty()){ + m_result.unchecked.push_back(m_row + " " + step.name); + return ""; + } + const SimPlayer& player = m_sim.player(); + if (player.warped && !story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos))){ + return ""; + } + return off_pose(*expected); +} + +Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ + if (!m_start_mismatch.empty()){ + return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); + } + m_far = step.pose_after; + if (story_events().contains(step.variant)){ + return stub(); + } + // A scene goes on from where the step before left us. A route walks + // on the world it plans on (Jubilife alone has no Route 204 north of it). + const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || + step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK; + const StoryWorld* on = step.kind == StoryStepKind::ROUTE && step.target && !state.pose.map.empty() + ? story_plan_world(state.pose.map, step.target->map) : nullptr; + // A world of one map is sim_world()'s, with its people. + if (on != nullptr && on == story_plan_world(state.pose.map, state.pose.map)){ + on = nullptr; + } + if (walks && !sync(state.pose, on)){ + m_logger.log(std::format("[{}] {}: no map for {}; passed over.", m_row, step.name, Pokemon::to_string(state.pose))); + m_passed_over = true; + return Pokemon::outcome_ok(); + } + return Pokemon::StoryStepExecutor::run(state, step); +} + +Outcome SimExecutor::run(RunState& state, const StoryStep& step){ + Outcome outcome; + m_passed_over = false; + m_step = step.name; + try{ + outcome = run_step(state, step); + }catch (const GridSimFailure& e){ + outcome = Pokemon::outcome_failed("sim_failure", e.message); + } + m_astray |= std::exchange(m_misses.slid, false); + const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; + if (!mismatch.empty()){ + outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); + } + // What the simulation does not play (scenes, events, battles) ends + // where the table says it does. + if (outcome.succeeded() && step.pose_after){ + m_astray = false; + sync(*step.pose_after); + } + m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); + if (std::exchange(m_misses.missed, false) && m_result.missed_step.empty()){ + m_result.missed_step = m_row + " " + step.name; + } + if (!outcome.succeeded() && m_result.error.empty()){ + // The walker's last notes, to see why. + for (size_t i = m_notes.size() - std::min(m_notes.size(), 40); i < m_notes.size(); i++){ + m_logger.log(std::format("[{}] note: {}", m_row, m_notes[i])); + } + m_result.error = m_row + " " + Pokemon::to_string(outcome); + m_result.failed_step = m_row + " " + step.name; + } + m_result.world = m_placed ? &m_sim.world() : nullptr; + m_result.end = nearest_tile(m_sim.player().pos); + m_ran.insert(step.name); + arm(step.name); + return outcome; +} + +// Runs `range` of `rows` (the table unless given) on `executor`, stopping +// at the first failure. +Pokemon::SegmentReport run_rows_on( + SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, + const std::vector& rows +){ + std::set saved; + Pokemon::Segment segment = make_story_segment(rows, executor, saved); + Pokemon::SegmentPolicy policy; + policy.stop_at_first_failure = true; + Pokemon::SegmentHooks hooks; + hooks.reload = [](RunState&){ return Pokemon::outcome_ok(); }; + hooks.log = [&logger](const std::string& line){ logger.log(line); }; + RunState state; + return Pokemon::run_segment(state, segment, range, policy, hooks); +} + +// Runs `range` of the table on the simulation, stopping at the first failure. +UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ + SimExecutor executor(logger); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, range); + for (const std::string& step : executor.result().unchecked){ + logger.log("No end to check after " + step + "."); + } + if (!report.completed){ + return std::format("stopped at {} {}: {}", report.failed_checkpoint, report.failed_event, executor.result().error); + } + return true; +} + +// The table with row `row`'s step of `step`'s name replaced by `step`. +std::vector table_with(const std::string& row, const StoryStep& step){ + std::vector rows = story_checkpoints(); + for (StoryCheckpoint& checkpoint : rows){ + for (StoryStep& old : checkpoint.steps){ + if (checkpoint.id == row && old.name == step.name){ + old = step; + return rows; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + step.name + " in " + row); +} + +bool ends_on(const SimRun& run, const Pose& pose){ + const std::vector tiles = Pokemon::tiles_of(pose); + const std::optional local = run.world ? story_to_local(*run.world, pose.map, run.end) : std::nullopt; + return local && std::find(tiles.begin(), tiles.end(), *local) != tiles.end(); +} +std::string end_of(const SimRun& run){ + return run.world ? describe(*run.world, run.end) : "nowhere"; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h new file mode 100644 index 0000000000..e4bbe4cfc1 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -0,0 +1,393 @@ +/* BDSP AutoStory - Story simulation + * + * From: https://github.com/PokemonAutomation/ + * + * The story table's rows run as the program runs them (the segment + * runner, make_story_segment()), with the program's own walking steps + * (StoryWalkSteps) on the grid simulation; see StorySim_Tests.cpp for + * what is simulated and what is stubbed. Moved out of the tests so the + * console failure cases (SimFailureCases_Tests) run on the same executor. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StorySim_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StorySim_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_GridSim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Which detections the simulation misses on purpose (#162): the `fade`th +// door fade (run_into_door(), from 0) or the `banner`th map banner +// (run_until_map()) of the run goes unseen, though the player did go +// through. The console missed both (r75, r81). The `dark`th door run reads +// dark SIM_FALSE_DARK in, short of the door, as lab-B's did on 2026-11-08. +// The `through`th tap step (tap_to_banner(), from 0) starts on its far side, +// its banner gone unless `through_banner`: the walk before it slid onto the +// warp (lab-B 2026-11-08). The counts and flags below are the run's: how +// many fades and banners it looked for, whether a miss happened since the +// executor last looked, whether a missed fade is still unseen, whether a +// walk slid on (SimSlide) since the executor last looked, and the map whose +// banner a slide left up for the next step. +struct SimMisses{ + std::optional fade; + std::optional banner; + std::optional dark = {}; + std::optional through = {}; + bool through_banner = false; + size_t tap_steps = 0; + size_t fades = 0; + size_t banners = 0; + size_t doors = 0; + bool missed = false; + bool fade_unseen = false; + bool slid = false; + std::string banner_up = {}; +}; + +// How a warp's fade looks to the console's watchers (#268's design note). +enum class SimFade{ + // A door's: near black. Every watcher of a black screen sees it. + BLACK, + // A cave mouth's: dim, not black. A walk's strict black watcher (rgb + // sum 100, stddev 10; WalkRunner::hold()) misses it and the walk goes + // on (the Oreburgh Gate, lab-B 2026-11-08 16:03). + DIM, + // A cave exit's white: a walk's encounter-flash watcher reads it as a + // wild battle. + WHITE, +}; + +// An open leg that runs on past its end: the walk taps of the step `step` +// toward `direction` go `tiles` further, once per step. Onto a warp, the +// player lands on `far` (the sim's maps have no warps' destinations), the +// walk sees the fade as `fade` looks, and the far map's banner is still up +// for the next step (`banner_up`) or gone (01.05, lab-B 2026-11-08 15:31). +struct SimSlide{ + std::string step; + Pokemon::Direction direction = Pokemon::Direction::WEST; + size_t tiles = 1; + Pokemon::Pose far = {}; + SimFade fade = SimFade::DIM; + bool banner_up = false; +}; + +// What the console showed that the plain simulation leaves out, each off +// unless set. All of it is deterministic: wanderers walk from `wander_seed`. +struct SimWorldKnobs{ + std::vector slides = {}; + // The mean brightness (0 to 255) of a map's floor, by JSON map name, and + // of the fade into a map; a tap step judges its fade from these with the + // program's tap_faded(). Unset: 104 (Oreburgh's street by day) and 7 + // (a door's black). + std::map floor = {}; + std::map fade_into = {}; + // People with a wander box on their map walk it, a step tried every 2 s. + std::optional wander_seed = std::nullopt; + // How long after the A press a talk's first line shows, by step name. + std::map first_line = {}; +}; + +// The walker's RouteIO on the story simulation, with SimWorldKnobs' slides +// and late first lines. `step` names the step running now; `cross` puts +// the player on a pose past a warp. +class SimKnobRouteIO : public GridSimRouteIO{ +public: + SimKnobRouteIO( + GridSim& sim, std::vector& notes, SimMisses& misses, const SimWorldKnobs& knobs, + const std::string& step, std::function cross + ) + : GridSimRouteIO(sim, notes) + , m_grid(sim) + , m_misses(misses) + , m_knobs(knobs) + , m_step(step) + , m_cross(std::move(cross)) + {} + + virtual WalkResult walk_taps(Pokemon::Direction direction, size_t tiles, const std::string& label) override; + virtual bool dialog_within(Milliseconds wait, Color color) override; + +private: + WalkResult slide_on(const SimSlide& slide, WalkResult result); + + GridSim& m_grid; + SimMisses& m_misses; + const SimWorldKnobs& m_knobs; + const std::string& m_step; + std::function m_cross; + std::set m_slid_steps; +}; + +// How many tiles a held walk goes on into a map before its location +// banner reads: "it shows a tile or a few past the border" (the table's +// route_201_by_the_path(), measured on the console). Standing still, it +// reads at once. Through a cave mouth the fade comes first, and a hold +// whose fade went unseen goes on the same way (r75, r81). +constexpr size_t SIM_BANNER_TILES = 3; +// How far into a door run SimMisses::dark reads dark, short of the door. +constexpr Milliseconds SIM_FALSE_DARK = Milliseconds(1800); +// Brightness (0 to 255) of a floor where SimWorldKnobs does not say: +// Oreburgh's street by day (r74). +constexpr double SIM_FLOOR = 104; +// Brightness of a fade where SimWorldKnobs does not say: a door's black (by hand: 7). +constexpr double SIM_DOOR_FADE = 7; + +// What a run on the simulation did. +struct SimRun{ + // The first failure, as "row outcome", or "". + std::string error; + // The rows and steps where an injected miss happened and where the run + // first failed, as "row step": "" if none. + std::string missed_step; + std::string failed_step; + // Walking steps that end where nothing says, as "row step". + std::vector unchecked; + // Each row run, with the fades and banners looked for before it. + struct RowStart{ + std::string row; + size_t fades; + size_t banners; + }; + std::vector rows; + // Where the player stood after the last step, if placed. + const StoryWorld* world = nullptr; + Pokemon::TilePos end; +}; + +// StoryStepIO on the simulation. A walk through a door or a cave mouth +// stops on its tile, as the console stops at the fade; a hold that misses +// the fade carries on, onto `far_side()` (the step's pose_after: the +// sim's maps have no warps' destinations) and on along it. +class SimStoryStepIO : public StoryStepIO{ +public: + SimStoryStepIO( + GridSim& sim, std::vector& notes, SimMisses& misses, const SimWorldKnobs& knobs, + const std::string& step, std::function far_side, std::function cross + ) + : m_sim(sim) + , m_route(sim, notes, misses, knobs, step, std::move(cross)) + , m_misses(misses) + , m_knobs(knobs) + , m_far_side(std::move(far_side)) + {} + + virtual RouteIO& route() override{ + return m_route; + } + virtual void fight(const std::string&) override{ + m_sim.end_dialogue(); + } + virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; + virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; + virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) override{ + const SimPace pace = run ? SimPace::RUN : SimPace::WALK; + if (false_dark() && dark_from <= SIM_FALSE_DARK && SIM_FALSE_DARK < timeout){ + m_sim.hold(direction, SIM_FALSE_DARK, pace); + return true; + } + const bool warped = m_sim.hold(direction, timeout, pace).stop == SimStop::WARP; + if (warped && fade_missed()){ + m_misses.fade_unseen = true; + return false; + } + return warped; + } + // A scene may take us to another map (Mom walks us out, 00.04): with a + // dialogue open the stub scene plays it. Otherwise only a door fades. + // A fade missed on the way in stays missed: it was over before settle() + // looked, which then fails as it does on the console after 120 s. + virtual void settle(Button, const std::string& label, bool fade) override{ + const bool scene_fades = m_sim.player().dialog && m_far_side(); + if (fade && ((!m_sim.player().warped && !scene_fades) || m_misses.fade_unseen)){ + m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); + } + m_misses.fade_unseen = false; + m_sim.end_dialogue(); + } + virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) override; + +private: + // Whether the run misses this fade or this banner (SimMisses). + bool fade_missed(){ + const bool miss = m_misses.fade == m_misses.fades++; + m_misses.missed |= miss; + return miss; + } + bool false_dark(){ + const bool dark = m_misses.dark == m_misses.doors++; + m_misses.missed |= dark; + return dark; + } + bool banner_missed(){ + const bool miss = m_misses.banner == m_misses.banners++; + m_misses.missed |= miss; + return miss; + } + bool on_map(const std::string& map) const{ + return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); + } + // The brightness of the floor the player stands on (SimWorldKnobs::floor). + double floor_here() const; + + GridSim& m_sim; + SimKnobRouteIO m_route; + SimMisses& m_misses; + const SimWorldKnobs& m_knobs; + std::function m_far_side; +}; + +// A scene's trigger the simulation fires from row `row` on, once the step +// `after` has run ("" from the row's start), on `map`'s `tiles`. +struct RowTrigger{ + std::string row; + std::string after; + std::string map; + SimTrigger trigger; +}; + +// When a story variable holds the value its coord events wait for: from +// row `row` on, once the step `after` has run ("" from the row's start). +struct VarState{ + std::string var; + int value; + std::string row; + std::string after; +}; + +// The story variables whose coord events the table walks onto, and from +// which row and step each holds (the definition says why each). +std::vector story_vars(); +// The maps' coord events whose story variable holds, as triggers. +std::vector story_triggers(); + +// The program's walking steps on the simulation, the rest stubbed. +class SimExecutor : public Pokemon::StoryStepExecutor{ +public: + explicit SimExecutor(Logger& logger, SimMisses misses = {}, SimWorldKnobs knobs = {}) + : m_logger(logger) + , m_misses(misses) + , m_knobs(std::move(knobs)) + , m_sim({}, {0, 0}, Pokemon::Direction::NORTH, false) + , m_io(m_sim, m_notes, m_misses, m_knobs, m_step, [this]{ return cross(); }, [this](const Pokemon::Pose& far){ cross_to(far); }) + , m_walks(m_io) + {} + + const SimMisses& misses() const{ + return m_misses; + } + const SimRun& result() const{ + return m_result; + } + virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ + m_row = data.id; + m_start_mismatch = data.start ? off_pose(*data.start) : ""; + m_ran.clear(); + m_astray = false; + m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); + m_walks.begin_attempt(data.id); + arm(""); + } + virtual Pokemon::Outcome run(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; + +protected: + virtual Pokemon::Outcome route(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.route(state, step); } + virtual Pokemon::Outcome legs(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.legs(state, step); } + virtual Pokemon::Outcome step(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.step(state, step); } + virtual Pokemon::Outcome talk(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.talk(state, step); } + virtual Pokemon::Outcome mash(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.mash(state, step); } + virtual Pokemon::Outcome heal(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; + virtual Pokemon::Outcome new_game(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome options(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome answer(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome battle(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome train(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome shop(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome save(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome game(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + +private: + // A step the simulation does not play: its dialogue opened and closed. + Pokemon::Outcome stub(){ + m_sim.end_dialogue(); + return Pokemon::outcome_ok(); + } + const StoryWorld* sim_world(const std::string& map) const; + SimWorld setup(const StoryWorld* world) const; + void arm(const std::string& after); + bool sync(const Pokemon::Pose& pose, const StoryWorld* on = nullptr); + bool cross(); + bool cross_to(const Pokemon::Pose& far); + std::vector wanderers(const StoryWorld& world) const; + std::string off_pose(const Pokemon::Pose& pose) const; + std::string check(const Pokemon::StoryStep& step, const Pokemon::Outcome& outcome); + Pokemon::Outcome run_step(Pokemon::RunState& state, const Pokemon::StoryStep& step); + + Logger& m_logger; + std::vector m_notes; + SimMisses m_misses; + SimWorldKnobs m_knobs; + // The step running now. + std::string m_step; + GridSim m_sim; + SimStoryStepIO m_io; + StoryWalkSteps m_walks; + // The planner's worlds with sim_people() and sim_ground() on them, by world and who. + mutable std::map, std::unique_ptr> m_peopled; + // The steps of this row that have run. + std::set m_ran; + std::string m_row; + std::vector m_armed; + // Where the step running now ends, if it says: a door's far side. + std::optional m_far; + // Why the player is not on this row's start, or "". + std::string m_start_mismatch; + // Whether the player has been put on a map yet. + bool m_placed = false; + // Whether the step running now is on a room with no map. + bool m_passed_over = false; + // Whether a walk slid on (SimSlide), so the player is not where the + // program thinks, until a step's pose_after puts them right. + bool m_astray = false; + SimRun m_result; +}; + +// Runs `range` of `rows` (the table unless given) on `executor`, stopping +// at the first failure. +Pokemon::SegmentReport run_rows_on( + SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, + const std::vector& rows = story_checkpoints() +); +// Runs `range` of the table on the simulation, stopping at the first failure. +UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range); +// The table with row `row`'s step of `step`'s name replaced by `step`. +std::vector table_with(const std::string& row, const Pokemon::StoryStep& step); +// Whether the run ended on one of `pose`'s tiles. +bool ends_on(const SimRun& run, const Pokemon::Pose& pose); +// Where the run ended, described; "nowhere" if never placed. +std::string end_of(const SimRun& run); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index a1d993191b..5097b78bca 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -50,6 +50,7 @@ #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_StorySim.h" #include "PokemonBDSP_AutoStory_StorySim_Tests.h" namespace PokemonAutomation{ @@ -67,668 +68,6 @@ using Pokemon::StoryStep; using Pokemon::StoryStepKind; using Pokemon::TilePos; -// Which detections the simulation misses on purpose (#162): the `fade`th -// door fade (run_into_door(), from 0) or the `banner`th map banner -// (run_until_map()) of the run goes unseen, though the player did go -// through. The console missed both (r75, r81). The `dark`th door run reads -// dark SIM_FALSE_DARK in, short of the door, as lab-B's did on 2026-11-08. -// The `through`th tap step (tap_to_banner(), from 0) starts on its far side, -// its banner gone unless `through_banner`: the walk before it slid onto the -// warp (lab-B 2026-11-08). The counts and flags below are the run's: how -// many fades and banners it looked for, whether a miss happened since the -// executor last looked, and whether a missed fade is still unseen. -struct SimMisses{ - std::optional fade; - std::optional banner; - std::optional dark = {}; - std::optional through = {}; - bool through_banner = false; - size_t tap_steps = 0; - size_t fades = 0; - size_t banners = 0; - size_t doors = 0; - bool missed = false; - bool fade_unseen = false; -}; - -// How many tiles a held walk goes on into a map before its location -// banner reads: "it shows a tile or a few past the border" (the table's -// route_201_by_the_path(), measured on the console). Standing still, it -// reads at once. Through a cave mouth the fade comes first, and a hold -// whose fade went unseen goes on the same way (r75, r81). -constexpr size_t SIM_BANNER_TILES = 3; -constexpr Milliseconds SIM_FALSE_DARK = 1800ms; - -// What a run on the simulation did. -struct SimRun{ - // The first failure, as "row outcome", or "". - std::string error; - // The rows and steps where an injected miss happened and where the run - // first failed, as "row step": "" if none. - std::string missed_step; - std::string failed_step; - // Walking steps that end where nothing says, as "row step". - std::vector unchecked; - // Each row run, with the fades and banners looked for before it. - struct RowStart{ - std::string row; - size_t fades; - size_t banners; - }; - std::vector rows; - // Where the player stood after the last step, if placed. - const StoryWorld* world = nullptr; - TilePos end; -}; - -// StoryStepIO on the simulation. A walk through a door or a cave mouth -// stops on its tile, as the console stops at the fade; a hold that misses -// the fade carries on, onto `far_side()` (the step's pose_after: the -// sim's maps have no warps' destinations) and on along it. -class SimStoryStepIO : public StoryStepIO{ -public: - SimStoryStepIO(GridSim& sim, std::vector& notes, SimMisses& misses, std::function far_side) - : m_sim(sim) - , m_route(sim, notes) - , m_misses(misses) - , m_far_side(std::move(far_side)) - {} - - virtual RouteIO& route() override{ - return m_route; - } - virtual void fight(const std::string&) override{ - m_sim.end_dialogue(); - } - virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string& label) override; - virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; - virtual bool run_into_door(Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) override{ - const SimPace pace = run ? SimPace::RUN : SimPace::WALK; - if (false_dark() && dark_from <= SIM_FALSE_DARK && SIM_FALSE_DARK < timeout){ - m_sim.hold(direction, SIM_FALSE_DARK, pace); - return true; - } - const bool warped = m_sim.hold(direction, timeout, pace).stop == SimStop::WARP; - if (warped && fade_missed()){ - m_misses.fade_unseen = true; - return false; - } - return warped; - } - // A scene may take us to another map (Mom walks us out, 00.04): with a - // dialogue open the stub scene plays it. Otherwise only a door fades. - // A fade missed on the way in stays missed: it was over before settle() - // looked, which then fails as it does on the console after 120 s. - virtual void settle(Button, const std::string& label, bool fade) override{ - const bool scene_fades = m_sim.player().dialog && m_far_side(); - if (fade && ((!m_sim.player().warped && !scene_fades) || m_misses.fade_unseen)){ - m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); - } - m_misses.fade_unseen = false; - m_sim.end_dialogue(); - } - virtual std::optional tap_to_banner(Direction direction, const std::string& map, size_t max_taps) override; - -private: - // Whether the run misses this fade or this banner (SimMisses). - bool fade_missed(){ - const bool miss = m_misses.fade == m_misses.fades++; - m_misses.missed |= miss; - return miss; - } - bool false_dark(){ - const bool dark = m_misses.dark == m_misses.doors++; - m_misses.missed |= dark; - return dark; - } - bool banner_missed(){ - const bool miss = m_misses.banner == m_misses.banners++; - m_misses.missed |= miss; - return miss; - } - bool on_map(const std::string& map) const{ - return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); - } - - GridSim& m_sim; - GridSimRouteIO m_route; - SimMisses& m_misses; - std::function m_far_side; -}; - -// A hold until something stops us. A door stops it at the fade, which -// fails the step; a fade missed lets the hold go on past the mouth (r81's -// timed walk south out of the Ravaged Path, onto Route 204's cliff). -void SimStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ - m_sim.tap(direction, ROUTE_TURN_TAP, false); - Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); - SimMove move = m_sim.hold(direction, limit, SimPace::WALK); - if (move.stop == SimStop::WARP && fade_missed() && m_far_side()){ - limit -= std::min(limit, move.time); - move = m_sim.hold(direction, limit, SimPace::WALK); - } - if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ - m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); - } -} - -// The D-pad, a tile at a time, until `map`'s banner reads; through a door -// the walk goes on beyond it (the fade eats no tiles of a hold). -bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&){ - const bool miss = banner_missed(); - size_t on = 0; - for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ - SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); - const bool crossed = move.stop == SimStop::WARP && m_far_side(); - const bool stopped = !crossed && (move.distance == 0 || move.stop != SimStop::DONE); - on = on_map(map) ? on + 1 : 0; - if (on > 0 && (on > SIM_BANNER_TILES || stopped) && !miss){ - return true; - } - if (stopped){ - return false; - } - } - return false; -} - -// D-pad taps, each looked at, until the fade and then the banner (the -// console's ConsoleStoryStepIO::tap_to_banner()): none if the banner shows -// before the first. Each look stands still, so a banner on the far side -// reads at once. A fade seen ends the taps, -// banner or not; with the fade missed the next look still sees the banner. -std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ - if (m_misses.through == m_misses.tap_steps++){ - m_misses.missed = true; - if (m_far_side() && m_misses.through_banner){ - return 0; - } - } - bool crossed = false; - for (size_t tap = 1; tap <= max_taps; tap++){ - const SimMove move = m_sim.tap(direction, 160ms, false); - if (move.stop == SimStop::DIALOG){ - return std::nullopt; - } - bool faded = false; - if (move.stop == SimStop::WARP){ - faded = !fade_missed(); - crossed = m_far_side(); - } - if (crossed && on_map(map) && !banner_missed()){ - return tap; - } - if (faded){ - return std::nullopt; - } - } - return std::nullopt; -} - -// A scene's trigger the simulation fires from row `row` on, once the step -// `after` has run ("" from the row's start), on `map`'s `tiles`. -struct RowTrigger{ - std::string row; - std::string after; - std::string map; - SimTrigger trigger; -}; - -// When a story variable holds the value its coord events wait for: from -// row `row` on, once the step `after` has run ("" from the row's start). -struct VarState{ - std::string var; - int value; - std::string row; - std::string after; -}; - -// The story variables whose coord events the table walks onto, from the -// row (and step) the table's reasons give, with the maps' coord events -// (Diamond's zone events; Platinum's for the houses): Barry's doorstep and -// Mom's warning in 00.01, Barry's Route 201 warning, then its pull-back -// row 19 once he has warned us (r14, r16); the lake's entrance in 00.02; -// Rowan's stop and Dawn at Sandgem's edge in 00.03; Dawn's catching -// tutorial on Route 202 from 00.04's start, Mom's call once she has healed -// us; the Poketch president on Jubilife's row 40 in 00.05b; Barry on Route -// 203 in 01.01; the Gate's Hiker and Oreburgh's welcome in 01.02; Barry's -// bump in Oreburgh after Roark in 01.05; and Rowan in Jubilife in 01.07. -// Left out: the Twinleaf guitarist (spent upstairs), Platinum's rival -// steps around our bedroom's start, Dawn at Jubilife's steps (BDSP starts -// her below them: an event), and Floaroma's (10..12, 29) (Diamond only). -std::vector story_vars(){ - return { - {.var = "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", .value = 0, .row = "00.01", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 0, .row = "00.01", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 1, .row = "00.01", .after = "barry_warns_us"}, - {.var = "VAR_VERITY_LAKEFRONT_STATE", .value = 0, .row = "00.02", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 2, .row = "00.03", .after = ""}, - {.var = "VAR_SANDGEM_TOWN_STATE", .value = 0, .row = "00.03", .after = ""}, - {.var = "VAR_ROUTE_202_STATE", .value = 0, .row = "00.04", .after = ""}, - {.var = "CONSOLE_MOMS_CALL", .value = 0, .row = "00.04", .after = "mom_heals_us"}, - {.var = "VAR_POKETCH_CAMPAIGN_STATE", .value = 1, .row = "00.05b", .after = ""}, - {.var = "VAR_ROUTE_203_RIVAL_STATE", .value = 0, .row = "01.01", .after = ""}, - {.var = "VAR_OREBURGH_GATE_1F_HIKER_STATE", .value = 1, .row = "01.02", .after = ""}, - {.var = "VAR_OREBURGH_CITY_STATE", .value = 0, .row = "01.02", .after = ""}, - {.var = "VAR_OREBURGH_CITY_STATE", .value = 2, .row = "01.05", .after = ""}, - {.var = "VAR_JUBILIFE_CITY_STATE", .value = 3, .row = "01.07", .after = ""}, - }; -} - -// The maps' coord events (story_coord_events()) whose variable holds. -std::optional var_state(const CoordEvent& event){ - for (const VarState& state : story_vars()){ - if (state.var == event.var && state.value == event.value){ - return state; - } - } - return std::nullopt; -} - -RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ - return {.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; -} - -std::vector story_triggers(){ - std::vector triggers; - for (const auto& [map, json] : bdsp_map_json()){ - for (const CoordEvent& event : story_coord_events(map)){ - const std::optional state = var_state(event); - if (state){ - triggers.push_back(row_trigger(map, event, *state)); - } - } - } - return triggers; -} - -// Someone the maps do not have, on `tile` of `map`, talked to or walked round: -// from row `row` on, until row `until_row`'s step `until` has run if it is set. -struct SimPerson{ - std::string name; - std::string map; - TilePos tile; - std::string row; - std::string until_row = {}; - std::string until = {}; -}; -std::vector sim_people(){ - return { - // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). - {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04"}, - // Barry in the Gym's door, from the welcome (lab-B 2026-11-08) to his lines (r101, r104). - {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.02b", .until_row = "01.02b", .until = "barrys_lines"}, - }; -} - -// A house's stairs, entered by a step `side` from the map's "stairs" -// point into what the map draws as a wall (the table's 00.01: r8 and r9 -// for ours, r11 for Barry's). -struct SimStairs{ - std::string map; - Direction side; -}; -std::vector sim_stairs(){ - return { - {.map = "PlayerHouse2F", .side = Direction::EAST}, - {.map = "RivalHouse1F", .side = Direction::EAST}, - {.map = "RivalHouse2F", .side = Direction::WEST}, - }; -} - -// The program's walking steps on the simulation, the rest stubbed. -class SimExecutor : public Pokemon::StoryStepExecutor{ -public: - explicit SimExecutor(Logger& logger, SimMisses misses = {}) - : m_logger(logger) - , m_misses(misses) - , m_sim({}, {0, 0}, Direction::NORTH, false) - , m_io(m_sim, m_notes, m_misses, [this]{ return cross(); }) - , m_walks(m_io) - {} - - const SimMisses& misses() const{ - return m_misses; - } - const SimRun& result() const{ - return m_result; - } - virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ - m_row = data.id; - m_start_mismatch = data.start ? off_pose(*data.start) : ""; - m_ran.clear(); - m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); - m_walks.begin_attempt(data.id); - arm(""); - } - virtual Outcome run(RunState& state, const StoryStep& step) override; - -protected: - virtual Outcome route(RunState& state, const StoryStep& step) override{ return m_walks.route(state, step); } - virtual Outcome legs(RunState& state, const StoryStep& step) override{ return m_walks.legs(state, step); } - virtual Outcome step(RunState& state, const StoryStep& step) override{ return m_walks.step(state, step); } - virtual Outcome talk(RunState& state, const StoryStep& step) override{ return m_walks.talk(state, step); } - virtual Outcome mash(RunState& state, const StoryStep& step) override{ return m_walks.mash(state, step); } - virtual Outcome heal(RunState& state, const StoryStep& step) override; - virtual Outcome new_game(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome options(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome answer(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome battle(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome train(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome shop(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome save(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome game(RunState&, const StoryStep&) override{ return stub(); } - -private: - // A step the simulation does not play: its dialogue opened and closed. - Outcome stub(){ - m_sim.end_dialogue(); - return Pokemon::outcome_ok(); - } - const StoryWorld* sim_world(const std::string& map) const; - SimWorld setup(const StoryWorld* world) const; - void arm(const std::string& after); - bool sync(const Pose& pose, const StoryWorld* on = nullptr); - bool cross(); - std::string off_pose(const Pose& pose) const; - std::string check(const StoryStep& step, const Outcome& outcome); - Outcome run_step(RunState& state, const StoryStep& step); - - Logger& m_logger; - std::vector m_notes; - SimMisses m_misses; - GridSim m_sim; - SimStoryStepIO m_io; - StoryWalkSteps m_walks; - // The planner's worlds with sim_people() and sim_ground() on them, by world and who. - mutable std::map, std::unique_ptr> m_peopled; - // The steps of this row that have run. - std::set m_ran; - std::string m_row; - std::vector m_armed; - // Where the step running now ends, if it says: a door's far side. - std::optional m_far; - // Why the player is not on this row's start, or "". - std::string m_start_mismatch; - // Whether the player has been put on a map yet. - bool m_placed = false; - // Whether the step running now is on a room with no map. - bool m_passed_over = false; - SimRun m_result; -}; - -// The world the player walks on for `map`: the planner's, with what the -// console showed that the maps lack. Nothing for a room with no map. -const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ - const StoryWorld* world = story_plan_world(map, map); - std::vector here; - std::string who; - for (const SimPerson& person : sim_people()){ - const bool now = m_row >= person.row && (person.until.empty() || m_row < person.until_row || - (m_row == person.until_row && !m_ran.contains(person.until))); - if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ - here.push_back(person); - who += person.name + ";"; - } - } - const SimGround* ground = nullptr; - for (const SimGround& item : sim_ground()){ - if (world != nullptr && m_row >= item.row && story_plan_world(item.map, item.map) == world){ - ground = &item; - who += item.map + " ground;"; - } - } - if (who.empty()){ - return world; - } - std::unique_ptr& peopled = m_peopled[{world, who}]; - if (!peopled){ - peopled = ground != nullptr ? with_ground(*world, *ground) : std::make_unique(*world); - for (const SimPerson& person : here){ - peopled->block(story_to_world(*peopled, person.map, person.tile)); - } - } - return peopled.get(); -} - -SimWorld SimExecutor::setup(const StoryWorld* world) const{ - // B runs once the shoes' scene has given them: the scene ends at home. - SimWorld out{.world = world, .trainers = story_trainers(*world), .can_run = m_walks.can_run()}; - for (const SimStairs& stairs : sim_stairs()){ - if (sim_world(stairs.map) == world){ - out.doors.push_back(story_to_world(*world, stairs.map, map_point(stairs.map, "stairs").next(stairs.side))); - } - } - for (const RowTrigger& armed : m_armed){ - if (sim_world(armed.map) != world){ - continue; - } - SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; - for (const TilePos& pos : armed.trigger.tiles){ - trigger.tiles.push_back(story_to_world(*world, armed.map, pos)); - } - out.triggers.push_back(std::move(trigger)); - } - return out; -} - -// Arms the triggers of this row that start after `after`. -void SimExecutor::arm(const std::string& after){ - size_t armed = 0; - for (const RowTrigger& trigger : story_triggers()){ - if (trigger.row == m_row && trigger.after == after){ - m_armed.push_back(trigger); - armed++; - } - } - const SimPlayer& player = m_sim.player(); - if (armed > 0 && m_placed && on_grid(player.pos) && !player.dialog){ - m_sim.place(setup(&m_sim.world()), nearest_tile(player.pos), player.facing); - } -} - -// Puts the player on `pose`, on the world `on` if given, unless they stand -// on one of its tiles already. Returns whether the pose is on a map the -// simulation has. -bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ - const std::vector tiles = Pokemon::tiles_of(pose); - const StoryWorld* world = on != nullptr ? on : pose.map.empty() ? nullptr : sim_world(pose.map); - if (world == nullptr || tiles.empty()){ - return false; - } - const SimPlayer& player = m_sim.player(); - const std::optional local = !m_placed || &m_sim.world() != world - ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); - if (local && on_grid(player.pos) && std::find(tiles.begin(), tiles.end(), *local) != tiles.end()){ - return true; - } - m_sim.place(setup(world), story_to_world(*world, pose.map, tiles.front()), Pokemon::facing_of(pose)); - m_placed = true; - return true; -} - -// Through a door or a cave mouth onto the step's far side, the player's -// facing kept: a hold goes on from there. -bool SimExecutor::cross(){ - const StoryWorld* world = m_far ? sim_world(m_far->map) : nullptr; - const std::vector tiles = m_far ? Pokemon::tiles_of(*m_far) : std::vector{}; - if (world == nullptr || tiles.empty()){ - return false; - } - m_sim.place(setup(world), story_to_world(*world, m_far->map, tiles.front()), std::nullopt); - return true; -} - -// Why the player does not stand on one of `pose`'s tiles, or "" if they -// do or the simulation cannot tell (no map, or not placed yet). -std::string SimExecutor::off_pose(const Pose& pose) const{ - const std::vector tiles = Pokemon::tiles_of(pose); - if (!m_placed || tiles.empty() || sim_world(pose.map) == nullptr){ - return ""; - } - const SimPlayer& player = m_sim.player(); - const TilePos at = nearest_tile(player.pos); - // In world tiles: a pose a leg worked out from the map it started on - // may lie past that map's edge, on the next map (Twinleaf's exit). - // story_to_world() throws for a map not on the player's world. - try{ - const auto there = [&](const TilePos& tile){ return story_to_world(m_sim.world(), pose.map, tile) == at; }; - if (on_grid(player.pos) && std::ranges::any_of(tiles, there)){ - return ""; - } - }catch (const InternalProgramError&){} - return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), at), Pokemon::to_string(pose)); -} - -// The program's run into the Center: past its door, the inside shows, a missed fade or not. -Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ - if (!sync(state.pose)){ - return Pokemon::outcome_ok(); - } - run_into_center(m_io, m_walks.can_run(), [this]{ - m_misses.fade_unseen = false; - return m_sim.player().warped.has_value(); - }, [&]{ - throw GridSimFailure{step.name + ": no door north of " + to_string(m_sim.player().pos)}; - }); - return Pokemon::outcome_ok(); -} - -// Why a walking step did not end where the table says, or "". A step -// through a door the simulation did not cross is not checked: the sim's -// maps have no warps' destinations. -std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ - const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP; - const std::optional expected = step.pose_after ? step.pose_after : outcome.pose; - if (!walks || !m_placed){ - return ""; - } - if (!expected || Pokemon::tiles_of(*expected).empty()){ - m_result.unchecked.push_back(m_row + " " + step.name); - return ""; - } - const SimPlayer& player = m_sim.player(); - if (player.warped && !story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos))){ - return ""; - } - return off_pose(*expected); -} - -Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ - if (!m_start_mismatch.empty()){ - return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); - } - m_far = step.pose_after; - if (story_events().contains(step.variant)){ - return stub(); - } - // A scene goes on from where the step before left us. A route walks - // on the world it plans on (Jubilife alone has no Route 204 north of it). - const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || - step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK; - const StoryWorld* on = step.kind == StoryStepKind::ROUTE && step.target && !state.pose.map.empty() - ? story_plan_world(state.pose.map, step.target->map) : nullptr; - // A world of one map is sim_world()'s, with its people. - if (on != nullptr && on == story_plan_world(state.pose.map, state.pose.map)){ - on = nullptr; - } - if (walks && !sync(state.pose, on)){ - m_logger.log(std::format("[{}] {}: no map for {}; passed over.", m_row, step.name, Pokemon::to_string(state.pose))); - m_passed_over = true; - return Pokemon::outcome_ok(); - } - return Pokemon::StoryStepExecutor::run(state, step); -} - -Outcome SimExecutor::run(RunState& state, const StoryStep& step){ - Outcome outcome; - m_passed_over = false; - try{ - outcome = run_step(state, step); - }catch (const GridSimFailure& e){ - outcome = Pokemon::outcome_failed("sim_failure", e.message); - } - const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; - if (!mismatch.empty()){ - outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); - } - // What the simulation does not play (scenes, events, battles) ends - // where the table says it does. - if (outcome.succeeded() && step.pose_after){ - sync(*step.pose_after); - } - m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); - if (std::exchange(m_misses.missed, false) && m_result.missed_step.empty()){ - m_result.missed_step = m_row + " " + step.name; - } - if (!outcome.succeeded() && m_result.error.empty()){ - // The walker's last notes, to see why. - for (size_t i = m_notes.size() - std::min(m_notes.size(), 40); i < m_notes.size(); i++){ - m_logger.log(std::format("[{}] note: {}", m_row, m_notes[i])); - } - m_result.error = m_row + " " + Pokemon::to_string(outcome); - m_result.failed_step = m_row + " " + step.name; - } - m_result.world = m_placed ? &m_sim.world() : nullptr; - m_result.end = nearest_tile(m_sim.player().pos); - m_ran.insert(step.name); - arm(step.name); - return outcome; -} - -// Runs `range` of `rows` (the table unless given) on `executor`, stopping -// at the first failure. -Pokemon::SegmentReport run_rows_on( - SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, - const std::vector& rows = story_checkpoints() -){ - std::set saved; - Pokemon::Segment segment = make_story_segment(rows, executor, saved); - Pokemon::SegmentPolicy policy; - policy.stop_at_first_failure = true; - Pokemon::SegmentHooks hooks; - hooks.reload = [](RunState&){ return Pokemon::outcome_ok(); }; - hooks.log = [&logger](const std::string& line){ logger.log(line); }; - RunState state; - return Pokemon::run_segment(state, segment, range, policy, hooks); -} - -// Runs `range` of the table on the simulation, stopping at the first failure. -UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ - SimExecutor executor(logger); - const Pokemon::SegmentReport report = run_rows_on(executor, logger, range); - for (const std::string& step : executor.result().unchecked){ - logger.log("No end to check after " + step + "."); - } - if (!report.completed){ - return std::format("stopped at {} {}: {}", report.failed_checkpoint, report.failed_event, executor.result().error); - } - return true; -} - -// The table with row `row`'s step of `step`'s name replaced by `step`. -std::vector table_with(const std::string& row, const StoryStep& step){ - std::vector rows = story_checkpoints(); - for (StoryCheckpoint& checkpoint : rows){ - for (StoryStep& old : checkpoint.steps){ - if (checkpoint.id == row && old.name == step.name){ - old = step; - return rows; - } - } - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + step.name + " in " + row); -} - -bool ends_on(const SimRun& run, const Pose& pose){ - const std::vector tiles = Pokemon::tiles_of(pose); - const std::optional local = run.world ? story_to_local(*run.world, pose.map, run.end) : std::nullopt; - return local && std::find(tiles.begin(), tiles.end(), *local) != tiles.end(); -} -std::string end_of(const SimRun& run){ - return run.world ? describe(*run.world, run.end) : "nowhere"; -} - UnitTestResult run_exit_test(Logger& logger, const std::string& row_id, const StoryStep& old_step, const SimMisses& misses, const Pose& overshoot){ SimExecutor executor(logger, misses); const std::vector rows = table_with(row_id, old_step); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 3cf67423fd..7f5a6de0a3 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1712,8 +1712,12 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp From d8b812d017baa3dfff49dfd6777e0132c28db891 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 20:12:37 -0800 Subject: [PATCH 19/19] BDSP AutoStory: a warp is a fade or a banner; walks report warps (#268 slices 1-3) Slice 1: a door step is through on its fade or the far map's banner, either alone (story_arrival_banner(): towns, routes and caves show one, houses and other floors none). run_into_door() watches the banner too and returns what it saw; settle() takes the banner after the fact. A tap step ends on a fade or the banner; the banner after a fade is evidence only. Slice 2: walks report the fade that ended a TRANSITION and any banner read (WalkResult::warp, WarpSeen). A planned route whose leg fades with a warp a tile or two past its end hands over as arrived (walk_route_to_warp()), and the door or tap step after it is done. Slice 3: a fade is a uniform screen, dark (to rgb sum 225, a cave's dim fade) or white (fade_of(), the shared watchers' stddev test). A white flash with no battle after it is a cave exit's fade, not an encounter. Removes the tap step's brightness-drop test and its banner-only "through already" check (the TODO(#268 slice 2/3) stopgaps). Banner reads are gated on the box showing, at most two per showing (LocationBannerReads). leg_path() moves to StoryWorld beside warp_within() to keep PlannedRoute.cpp under 1000 lines. Sim: the walk and tap step judge the sim's fades with fade_of(); floors are textured, fades uniform (a model). Three #281 cases pass and leave KNOWN_FAILING; the every-miss case stays, its single-signal warps listed, and a new case checks every warp that shows both. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Data/PokemonBDSP_AutoStory_StoryWorld.cpp | 32 ++++ .../Data/PokemonBDSP_AutoStory_StoryWorld.h | 7 + ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 4 +- .../PokemonBDSP_AutoStory_StoryExecutor.cpp | 4 +- .../PokemonBDSP_AutoStory_StoryPlaces.cpp | 19 +++ .../PokemonBDSP_AutoStory_StoryPlaces.h | 5 + .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 144 ++++++++++-------- .../PokemonBDSP_AutoStory_StoryStepIO.h | 36 ++--- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 53 +++++-- .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 4 + .../PokemonBDSP_AutoStory_Walk_Tests.cpp | 41 ++--- .../PokemonBDSP_AutoStory_GridSim.cpp | 5 +- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 6 +- ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 46 ++++-- .../PokemonBDSP_AutoStory_StorySim.cpp | 43 +++--- .../PokemonBDSP_AutoStory_StorySim.h | 58 ++++--- .../Utils/PokemonBDSP_AutoStory_Location.cpp | 43 ++++++ .../Utils/PokemonBDSP_AutoStory_Location.h | 43 ++++++ .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 55 +++---- .../PokemonBDSP_AutoStory_PlannedRoute.h | 15 ++ .../Utils/PokemonBDSP_AutoStory_Walk.cpp | 67 ++++++-- .../Utils/PokemonBDSP_AutoStory_Walk.h | 45 +++++- 22 files changed, 571 insertions(+), 204 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 fb9e7a89f5..ae35f4b51b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp @@ -5,6 +5,7 @@ */ #include +#include #include #include "Common/Cpp/Exceptions.h" #include "PokemonBDSP_AutoStory_StoryWorld.h" @@ -294,6 +295,37 @@ std::optional step(const StoryWorld& world, const TilePos& from, Direct return std::nullopt; } +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; +} + +bool warp_within(const StoryWorld& world, const std::vector& from, Direction direction, size_t reach){ + for (TilePos pos : from){ + for (size_t i = 0; i < reach; i++){ + if (world.tile(pos.next(direction)) == TileKind::DOOR){ + return true; + } + const std::optional next = step(world, pos, direction); + if (!next){ + break; + } + pos = *next; + } + } + return false; +} + // 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){ 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 9cf790e24f..6940a5be4d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h @@ -128,6 +128,13 @@ std::optional step(const StoryWorld& world, const Pokemon::Til // 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); +// 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, Pokemon::TilePos from, Pokemon::Direction direction, size_t tiles); +// Whether a warp (a door's tile) lies within `reach` tiles `direction` of +// one of `from`, nothing stopping the player before it: where a walk that +// ran on past its leg's end may have gone through (#268 slice 2). +bool warp_within(const StoryWorld& world, const std::vector& from, Pokemon::Direction direction, size_t reach); // "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_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index d448d579f4..b3a2d8b70c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -85,9 +85,9 @@ class RecoveryStepIO : public StoryStepIO{ virtual void fight(const std::string&) override{ throw GridSimFailure{"unexpected trainer"}; } virtual void walk_until_stopped(Direction, size_t, const std::string&) override{ throw GridSimFailure{"unexpected blind hold"}; } virtual bool run_until_map(Direction, Milliseconds, const std::string&, const std::string&) override{ throw GridSimFailure{"unexpected banner walk"}; } - virtual bool run_into_door(Direction, bool, Milliseconds = Milliseconds(12000), Milliseconds = Milliseconds(0)) override{ throw GridSimFailure{"unexpected door"}; } + virtual WarpSeen run_into_door(Direction, bool, Milliseconds = Milliseconds(12000), Milliseconds = Milliseconds(0), const std::string& = "") override{ throw GridSimFailure{"unexpected door"}; } virtual std::optional tap_to_banner(Direction, const std::string&, size_t) override{ throw GridSimFailure{"unexpected banner"}; } - virtual void settle(Button, const std::string&, bool) override{ throw GridSimFailure{"unexpected scene"}; } + virtual void settle(Button, const std::string&, bool, const std::string&) override{ throw GridSimFailure{"unexpected scene"}; } private: RouteIO& m_route; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp index 80e5d6bbe8..47c25de07f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp @@ -241,9 +241,9 @@ Outcome StoryExecutor::heal(RunState&, const StoryStep& step){ // Out the same way: south until the fade. The walk out's indoor check // read "not a room" a step from the counter and stopped inside (r50, r59). route_turn(stream(), context(), Direction::SOUTH); - const bool out = m_io.run_into_door(Direction::SOUTH, m_walks.can_run()); + const bool out = m_io.run_into_door(Direction::SOUTH, m_walks.can_run()).any(); stream().log(std::format("[{}] {}: south out of the Center: {}.", m_checkpoint, step.name, out ? "faded" : "no fade yet")); - m_io.settle(BUTTON_B, label_of(step), !out); + m_io.settle(BUTTON_B, label_of(step), !out, ""); // r143a's heal said it had walked out while still inside. context().wait_for_all_requests(); VideoSnapshot screen = stream().video().snapshot(); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp index 72d05f3667..1493ad8daa 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp @@ -230,6 +230,25 @@ const std::string& story_banner_name(const std::string& map){ return banner_name(map); } +std::string story_arrival_banner(const std::string& from, const std::string& to){ + // The named places, by the place each map is part of: the mine's two floors are one. + static const std::map caves{ + {"OreburghGate", "OreburghGate"}, + {"OreburghMine", "OreburghMine"}, + {"OreburghMineB1F", "OreburghMine"}, + {"RavagedPath", "RavagedPath"}, + }; + const auto place = [](const std::string& map) -> std::string{ + if (banner_names().contains(map)){ + return banner_name(map); + } + const auto cave = caves.find(map); + return cave == caves.end() ? "" : cave->second; + }; + const std::string there = place(to); + return there.empty() || there == place(from) ? "" : story_banner_name(to); +} + const StoryWorld* story_plan_world(const std::string& from, const std::string& to){ for (const PlanWorld& world : plan_worlds()){ if (world.maps.contains(from) && world.maps.contains(to)){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h index 62006d2cf3..a6f0dbbfd0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h @@ -33,6 +33,11 @@ const StoryWorld* story_plan_world(const std::string& from, const std::string& t // The location banner of the JSON map `map` ("Route 204" for both of its // halves), or `map` itself for one no banner list names. const std::string& story_banner_name(const std::string& map); +// The banner (story_banner_name()) a warp from the JSON map `from` onto +// `to` shows, or "" if none: arriving in another town, route or cave shows +// its name (out of the Gym, Oreburgh City's), arriving in a house, a lab, +// a school or another floor of the same cave shows none. +std::string story_arrival_banner(const std::string& from, const std::string& to); // The tile `local` of the map `map` in `world`. Pokemon::TilePos story_to_world(const StoryWorld& world, const std::string& map, const Pokemon::TilePos& local); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index 43df0cf73f..46b0279e63 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -6,6 +6,7 @@ #include #include +#include #include "Common/Cpp/PrettyPrint.h" #include "Common/Cpp/Filesystem/Filesystem.h" #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" @@ -50,16 +51,41 @@ namespace{ // A step or scene that ends on another map (`fade`) must fade on the way, // and only the quiet after the fade counts: r30's scene went quiet for 5 s // before the fade home, and r28 "went out" a tile beside the door and -// walked a whole route in the house. No fade is a map mismatch. +// walked a whole route in the house. No fade is a map mismatch. The far +// map's banner `banner`, if it has one, counts as the fade: a fade the run +// missed is over, but its banner comes after it (#268 slice 1). constexpr double FADE_DARKNESS = 75; // brightness 0 to 255; cave fades reach ~45..64, r24's dim fade goes darker -void settle(VideoStream& stream, ProControllerContext& context, Button button, const std::string& label, bool fade){ +// What settle() has seen of the warp so far: the darkest frame, and the banner. +class SettleWarp{ +public: + explicit SettleWarp(const std::string& banner) + : m_banner(banner) + {} + void look(const ImageViewRGB32& frame, WallClock now){ + m_darkest = std::min(m_darkest, image_average(frame).sum() / 3); + m_banner_seen |= !m_banner.empty() && location_banner_matches(m_reads.read(frame, now), m_banner); + } + bool seen() const{ + return m_darkest < FADE_DARKNESS || m_banner_seen; + } + std::string describe() const{ + return std::format("darkest frame {:.0f}{}", m_darkest, m_banner_seen ? ", banner read" : ""); + } + +private: + const std::string& m_banner; + double m_darkest = 255; + LocationBannerReads m_reads; + bool m_banner_seen = false; +}; +void settle(VideoStream& stream, ProControllerContext& context, Button button, const std::string& label, bool fade, const std::string& banner){ const WallClock none = WallClock::max(); const WallClock deadline = current_time() + 120s; ShortDialogDetector dialog; OverworldDetector overworld; BattleMenuDetector battle_menu(BattleType::STANDARD); WallClock quiet_since = none, calm_since = none; - double darkest = 255; + SettleWarp warp(banner); VideoSnapshot previous; while (current_time() < deadline){ context.wait_for_all_requests(); @@ -71,21 +97,22 @@ void settle(VideoStream& stream, ProControllerContext& context, Button button, c continue; } if (frame){ - darkest = std::min(darkest, image_average(*frame.frame).sum() / 3); + warp.look(*frame.frame, now); } + const bool warped = !fade || warp.seen(); const bool talking = frame && dialog.detect(frame); const bool still = frame && previous && walk_screen_change(*previous.frame, *frame.frame) < WALK_TAP_BLOCKED_CHANGE; previous = frame; - const bool calm = !talking && overworld.detect(frame) && (!fade || darkest < FADE_DARKNESS); + const bool calm = !talking && overworld.detect(frame) && warped; calm_since = calm ? (calm_since == none ? now : calm_since) : none; if (calm && now - calm_since >= 15000ms){ - stream.log(std::format("[Story] {}: settled on calm overworld; darkest frame {:.0f}.", label, darkest)); + stream.log(std::format("[Story] {}: settled on calm overworld; {}.", label, warp.describe())); return; } - if (!talking && still && overworld.detect(frame) && (!fade || darkest < FADE_DARKNESS)){ + if (!talking && still && overworld.detect(frame) && warped){ quiet_since = quiet_since == none ? now : quiet_since; if (now - quiet_since >= 5000ms){ - stream.log(std::format("[Story] {}: settled; darkest frame {:.0f}.", label, darkest)); + stream.log(std::format("[Story] {}: settled; {}.", label, warp.describe())); return; } }else{ @@ -94,8 +121,8 @@ void settle(VideoStream& stream, ProControllerContext& context, Button button, c pbf_press_button(context, talking ? button : BUTTON_B, 80ms, 1200ms); } OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - fade && darkest >= FADE_DARKNESS - ? label + ": no fade within 120 s, so we are not where the step goes (map mismatch)." + fade && !warp.seen() + ? label + ": no fade or banner within 120 s, so we are not where the step goes (map mismatch)." : label + ": not back on a quiet overworld within 120 s.", stream); } @@ -140,25 +167,32 @@ class DarkFrom : public VisualInferenceCallback{ }; // How one hold toward a door ended: run_until()'s index (0 dark, 1 white, -// 2 a line, 3 a wild battle; -1 time up), and when the screen last went dark. +// 2 a line, 3 a wild battle, 4 the far map's banner; -1 time up), when the +// screen last went dark, and the banner read. struct DoorHoldEnd{ int ret; WallClock went_dark; + std::string banner; }; -DoorHoldEnd hold_into_door(VideoStream& stream, ProControllerContext& context, DpadPosition dpad, bool run, Milliseconds hold, Milliseconds dark_from){ +DoorHoldEnd hold_into_door(VideoStream& stream, ProControllerContext& context, DpadPosition dpad, bool run, Milliseconds hold, Milliseconds dark_from, const std::string& banner){ BlackScreenWatcher dark(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, 3 * FADE_DARKNESS, 60, BlackScreenWatcher::FinderType::PRESENT, 50ms); DarkFrom late_dark(dark, current_time() + dark_from); WhiteScreenWatcher white(COLOR_BLUE, {0.1, 0.1, 0.8, 0.8}, WhiteScreenWatcher::FinderType::PRESENT, 60ms); ShortDialogWatcher dialog(COLOR_YELLOW); BattleMenuWatcher battle(BattleType::STANDARD, COLOR_YELLOW); + LocationBannerWatcher far_banner(banner); + std::vector watchers{{late_dark}, {white}, {dialog}, {battle}}; + if (!banner.empty()){ + watchers.emplace_back(far_banner); + } const int ret = run_until(stream, context, [&](ProControllerContext& context){ if (run){ ssf_press_button(context, BUTTON_B, 0ms, hold, 0ms); } pbf_press_dpad(context, dpad, hold, 0ms); - }, {{late_dark}, {white}, {dialog}, {battle}}); - return {.ret = ret, .went_dark = late_dark.went_dark()}; + }, watchers); + return {.ret = ret, .went_dark = late_dark.went_dark(), .banner = ret == 4 ? far_banner.seen() : ""}; } // Wild battles a run into a door flees and runs on after. @@ -171,11 +205,13 @@ constexpr size_t DOOR_RUN_BATTLES = 3; // 2026-11-08: dark at 1.8 s, halfway down the mine's entrance hall). A wild // battle on the way is fled, and the run goes on for the time it had left: // only the running counts, up to the battle's fade. -bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction direction, bool run, Milliseconds timeout, Milliseconds dark_from){ +// The far map's banner `banner` shows after the fade, so it ends the run +// only when the fade went unseen (#268 slice 1). +WarpSeen run_into_door(VideoStream& stream, ProControllerContext& context, Direction direction, bool run, Milliseconds timeout, Milliseconds dark_from, const std::string& banner){ Milliseconds left = timeout; for (size_t battles = 0;; battles++){ const WallClock start = current_time(); - const DoorHoldEnd end = hold_into_door(stream, context, dpad_toward(direction), run, left, dark_from); + const DoorHoldEnd end = hold_into_door(stream, context, dpad_toward(direction), run, left, dark_from, banner); if (end.ret == 3){ const WallClock stopped = std::min(end.went_dark, current_time()); const Milliseconds ran = std::chrono::duration_cast(stopped - start) - ROUTE_START_DELAY; @@ -187,7 +223,7 @@ bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction if (battles < DOOR_RUN_BATTLES && left > 0ms){ continue; } - return false; + return {}; } if (end.ret == 0){ stream.log("[Story] run_into_door: black screen fade detected."); @@ -195,6 +231,8 @@ bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction stream.log("[Story] run_into_door: white screen fade detected."); }else if (end.ret == 2){ stream.log("[Story] run_into_door: dialog detected."); + }else if (end.ret == 4){ + stream.log("[Story] run_into_door: no fade seen, but the banner \"" + end.banner + "\" read."); }else if (end.went_dark != WallClock::max()){ // Dark only before dark_from: early, or the door's fade itself. stream.log(std::format("[Story] run_into_door: timed out; dark {} ms in, before dark_from {} ms.", @@ -202,7 +240,10 @@ bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction }else{ stream.log("[Story] run_into_door: timed out without detecting fade."); } - return end.ret == 0 || end.ret == 1; + return { + .fade = end.ret == 0 ? WarpFade::BLACK : end.ret == 1 ? WarpFade::WHITE : WarpFade::NONE, + .banner = end.banner, + }; } } @@ -232,14 +273,15 @@ void log_new_banner_read(VideoStream& stream, const std::string& read, std::stri } // Looks for the location banner `banner` for up to `wait`, and with -// `before` (the brightness before the tap) for the fade (tap_faded()). -// Logs each distinct banner read and how the wait ended: the Oreburgh Gate's -// entry missed its banner twice (lab-B, 2026-11-08 15:31 and 15:39) though -// a hand probe saw it 1.5 s after the fade, and nothing said why. -TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const std::string& banner, Milliseconds wait, std::optional before){ +// `fade` for the fade (fade_of_screen()). Logs each distinct banner read +// and how the wait ended: the Oreburgh Gate's entry missed its banner twice +// (lab-B, 2026-11-08 15:31 and 15:39) though a hand probe saw it 1.5 s +// after the fade, and nothing said why. +TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const std::string& banner, Milliseconds wait, bool fade){ const WallClock start = current_time(); const WallClock deadline = start + wait; std::string last_read; + LocationBannerReads reads; double darkest = 255; // Every 500 ms of a long wait (the one after a fade) a frame goes to // Screenshots/AutoStory/banner/, to see what the game showed. @@ -248,18 +290,17 @@ TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const while (true){ context.wait_for_all_requests(); const VideoSnapshot screen = stream.video().snapshot(); - if (!before && screen && current_time() >= next_frame){ + if (!fade && screen && current_time() >= next_frame){ keep_banner_frame(*screen.frame, folder, banner); next_frame += 500ms; } - const std::string read = screen ? read_location_banner(*screen.frame) : ""; + const std::string read = screen ? reads.read(*screen.frame, current_time()) : ""; log_new_banner_read(stream, read, last_read, banner, start); if (screen && location_banner_matches(read, banner)){ return TapLook::BANNER; } - const double brightness = brightness_of(screen); - darkest = std::min(darkest, brightness); - if (before && tap_faded(*before, brightness)){ + darkest = std::min(darkest, brightness_of(screen)); + if (fade && screen && fade_of_screen(*screen.frame) != WarpFade::NONE){ return TapLook::DARK; } if (current_time() >= deadline){ @@ -274,19 +315,6 @@ TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const } // namespace -// Black as the Gym's door fades (< 25), or a drop to dark: a look under -// FADE_DARKNESS is not a fade by itself, since a cave's floor is that dim -// (the Oreburgh Gate's about 46, lab-B 2026-11-08), but a fade into a cave -// from a lit street goes from about 120 to 45..64. -// TODO(#268 slice 3): stopgap. A uniform-screen fade watcher (the shared -// Black/WhiteScreen stddev test, as in upstream #1717) should replace this -// brightness drop; remove it once that watcher passes the Gate frames. -constexpr double TAP_FADE_BLACK = 25; -constexpr double TAP_FADE_DROP = 0.7; -bool tap_faded(double before, double after){ - return after < TAP_FADE_BLACK || (after < FADE_DARKNESS && after < before * TAP_FADE_DROP); -} - ConsoleStoryStepIO::ConsoleStoryStepIO(VideoStream& stream, ProControllerContext& context) : m_stream(stream) , m_context(context) @@ -316,48 +344,40 @@ bool ConsoleStoryStepIO::run_until_map(Direction direction, Milliseconds limit, return walk.stop == WalkStop::ARRIVED; } -bool ConsoleStoryStepIO::run_into_door(Direction direction, bool run, Milliseconds timeout, Milliseconds dark_from){ - return PokemonBDSP::run_into_door(m_stream, m_context, direction, run, timeout, dark_from); +WarpSeen ConsoleStoryStepIO::run_into_door(Direction direction, bool run, Milliseconds timeout, Milliseconds dark_from, const std::string& banner){ + return PokemonBDSP::run_into_door(m_stream, m_context, direction, run, timeout, dark_from, banner); } // A held walk can carry on past a fade that goes unseen: out of the Gym it // walked on south (r219g), and through the Oreburgh Gate's west mouth on // west into a pocket by Route 203's pond (r75). Taps during the fade are -// eaten. The banner before the first tap means we are through already: -// the walk before slid onto the warp (lab-B 2026-11-08 15:31). -// TODO(#268 slice 2): stopgap. The "through already" check sees only a -// banner still on screen; once walkers report the fade or banner they saw -// (WalkResult::warp), read that instead and remove this check. +// eaten, so a fade ends the taps; the banner after it is evidence, not +// required (#268 slice 1). The watch starts before the first tap: a walk +// before that slid onto the warp unseen may have left its banner up +// (lab-B 2026-11-08 15:31). std::optional ConsoleStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ const std::string& banner = story_banner_name(map); m_context.wait_for_all_requests(); - VideoSnapshot screen = m_stream.video().snapshot(); - if (screen && location_banner_matches(read_location_banner(*screen.frame), banner)){ + if (look_after_tap(m_stream, m_context, banner, 0ms, true) == TapLook::BANNER){ m_stream.log("[Banner] \"" + banner + "\" shows before the first tap: through already."); return 0; } for (size_t tap = 1; tap <= max_taps; tap++){ - const double before = brightness_of(screen); pbf_press_dpad(m_context, dpad_toward(direction), 160ms, 0ms); - TapLook look = look_after_tap(m_stream, m_context, banner, 1500ms, before); - const bool faded = look == TapLook::DARK; - if (faded){ - look = look_after_tap(m_stream, m_context, banner, 8000ms, std::nullopt); + const TapLook look = look_after_tap(m_stream, m_context, banner, 1500ms, true); + if (look == TapLook::DARK && look_after_tap(m_stream, m_context, banner, 8000ms, false) != TapLook::BANNER){ + m_stream.log("[Banner] a fade, no \"" + banner + "\" banner after it: counting the fade.", COLOR_ORANGE); } - if (look == TapLook::BANNER){ + if (look != TapLook::NOTHING){ m_context.wait_for(1000ms); return tap; } - if (faded){ - break; - } - screen = m_stream.video().snapshot(); } return std::nullopt; } -void ConsoleStoryStepIO::settle(Button button, const std::string& label, bool fade){ - PokemonBDSP::settle(m_stream, m_context, button, label, fade); +void ConsoleStoryStepIO::settle(Button button, const std::string& label, bool fade, const std::string& banner){ + PokemonBDSP::settle(m_stream, m_context, button, label, fade, banner); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h index a48007ee2f..6aa734d890 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h @@ -44,28 +44,27 @@ class StoryStepIO{ // JSON map's name) shows, for at most `limit`. Returns whether it showed. virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string& label) = 0; // Holds the D-pad toward a door (running with `run`) for `timeout` until - // the screen goes dark or a line shows. A dark screen in the first - // `dark_from` of running is not the door's fade, and a wild battle on the - // way is fled, the run going on for the time left. Returns whether it went dark. - virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) = 0; + // the screen goes dark or white, `banner` (a map's banner name, "" for + // none) reads, or a line shows. A dark screen in the first `dark_from` + // of running is not the door's fade, and a wild battle on the way is + // fled, the run going on for the time left. Returns what it saw of the + // warp: the fade or the banner, either one alone (#268 slice 1). + virtual WarpSeen run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), + Milliseconds dark_from = Milliseconds(0), const std::string& banner = "") = 0; // D-pad taps `direction` one at a time, each looked at, toward a door - // or cave mouth, until the fade (then no more taps) and the location - // banner of `map` (a JSON map's name), for at most `max_taps`. Returns - // the taps it took (0 if the banner shows before the first: through - // already), or nothing if no banner showed. + // or cave mouth, until its fade (fade_of(): uniform, so a dim cave floor + // is none) or the location banner of `map` (a JSON map's name), for at + // most `max_taps`; after a fade, no more taps. Either one alone is the + // way through. The watch starts before the first tap: a banner up then + // is 0 taps. Returns the taps it took, or nothing if neither showed. virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) = 0; // Presses through any text until the overworld is quiet; with `fade`, a - // fade must come first (a map change). Fails otherwise. - virtual void settle(Button button, const std::string& label, bool fade) = 0; + // warp must come first (a map change): a fade, or the banner `banner` + // ("" for a fade only). Fails otherwise. + virtual void settle(Button button, const std::string& label, bool fade, const std::string& banner) = 0; }; -// Whether a look after a tap toward a door or a cave mouth shows its fade, -// from its brightness `after` and that of the look before the tap, -// `before` (the mean of r, g and b, 0 to 255). -bool tap_faded(double before, double after); - - // The console. class ConsoleStoryStepIO : public StoryStepIO{ public: @@ -77,9 +76,10 @@ class ConsoleStoryStepIO : public StoryStepIO{ virtual void fight(const std::string& trainer) override; virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string& label) override; - virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) override; + virtual WarpSeen run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), + Milliseconds dark_from = Milliseconds(0), const std::string& banner = "") override; virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) override; - virtual void settle(Button button, const std::string& label, bool fade) override; + virtual void settle(Button button, const std::string& label, bool fade, const std::string& banner) override; private: VideoStream& m_stream; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index 8a0d50e0b9..f79162b485 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -7,12 +7,14 @@ #include #include #include +#include #include "Common/Cpp/Color.h" #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Pokemon/Navigation/Pokemon_MapData.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP_AutoStory_StoryExecutor.h" @@ -52,7 +54,7 @@ std::string label_of(const StoryStep& step){ CenterEntry run_into_center(StoryStepIO& io, bool run, const std::function& inside, const std::function& line_up){ - if (io.run_into_door(Direction::NORTH, run)){ + if (io.run_into_door(Direction::NORTH, run).any()){ return CenterEntry::FADED; } if (inside()){ @@ -67,6 +69,7 @@ void StoryWalkSteps::begin_attempt(const std::string& row){ // A row starts from its save: after the shoes' row, the save has them. m_can_run = row > std::string(RUNNING_SHOES_ROW); m_trainers.clear(); + m_warp = {}; } void StoryWalkSteps::turn(Direction direction){ @@ -105,10 +108,11 @@ Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }, label_of(step), {}, *costs, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK }; - const std::vector at = walk_route(m_io.route(), *maps, start, trainers, plan); + RouteEnd end = walk_route_to_warp(m_io.route(), *maps, start, trainers, plan); sights = std::move(trainers.sights); + m_warp = std::move(end.warp); std::vector local; - for (const TilePos& pos : at){ + for (const TilePos& pos : end.tiles){ const std::optional tile = story_to_local(*maps, goal.map, pos); if (!tile){ fail(m_io.route(), std::format("{}: the walk ended off {}.", step.name, goal.map)); @@ -119,6 +123,7 @@ Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep } Outcome StoryWalkSteps::route(RunState& state, const StoryStep& step){ + m_warp = {}; if (Pokemon::tiles_of(state.pose).empty()){ return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); } @@ -193,20 +198,38 @@ size_t taps_to_banner(const Pose& from, Direction direction){ // there; a banner before any tap means the walk before took us through. Outcome StoryWalkSteps::tap_to_banner(const Pose& from, const StoryStep& step){ const std::string map = step.pose_after ? step.pose_after->map : ""; + if (through_already(step)){ + return Pokemon::outcome_ok(); + } const size_t limit = taps_to_banner(from, step.direction); const std::optional taps = m_io.tap_to_banner(step.direction, map, limit); if (!taps){ - return Pokemon::outcome_failed("no_banner", std::format("{} in {} taps {}: through already, its banner gone?", + return Pokemon::outcome_failed("no_banner", std::format("no fade and no {} banner in {} taps {}", map, limit, direction_name(step.direction))); } if (*taps == 0){ log(std::format("[{}] {}: {}'s banner before any tap: through already.", m_row, step.name, map)); }else{ - log(std::format("[{}] {}: {}'s banner after {} taps {}.", m_row, step.name, map, *taps, direction_name(step.direction))); + log(std::format("[{}] {}: through to {} after {} taps {}.", m_row, step.name, map, *taps, direction_name(step.direction))); } return Pokemon::outcome_ok(); } +// The route before ran on through this step's warp (walk_route_to_warp()): +// the step is done, unless the banner it read names another map. +bool StoryWalkSteps::through_already(const StoryStep& step){ + const WarpSeen through = std::exchange(m_warp, {}); + if (!through.any()){ + return false; + } + const std::string map = step.pose_after ? step.pose_after->map : ""; + if (!through.banner.empty() && !location_banner_matches(through.banner, story_banner_name(map))){ + fail(m_io.route(), std::format("{}: the walk before went through a warp to \"{}\", not {}.", step.name, through.banner, map)); + } + log(std::format("[{}] {}: through already; the walk before saw {}.", m_row, step.name, describe(through))); + return true; +} + namespace{ // A run into a door: how long to hold, and for how long of it a dark screen // is not yet the door's fade (run_into_door()). @@ -352,6 +375,7 @@ Outcome StoryWalkSteps::counted_wall(const Pose& from, const StoryStep& step){ } Outcome StoryWalkSteps::legs(RunState& state, const StoryStep& step){ + m_warp = {}; if (step.variant == "counted_wall"){ return counted_wall(state.pose, step); } @@ -385,7 +409,7 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ if (walk.wild_battles > 0){ return Pokemon::outcome_failed("interrupted_step", step.name); } - m_io.settle(BUTTON_B, label_of(step), false); + m_io.settle(BUTTON_B, label_of(step), false, ""); return Pokemon::outcome_ok(); } // A step through a door: walk (or run) on until the screen goes dark, @@ -394,12 +418,19 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ // 00.01; Dawn's tour, 00.04). Without the fade, settle must see it itself // (r33 was outside, "no fade"). No separate turn tap first: at 1 tile // from the door, a 50 ms turn tap can step in before run_into_door() watches. + // A fade or the far map's banner is the way through, either one (#268 + // slice 1); with neither yet, settle() waits for one. if (step.pose_after && step.pose_after->map != state.pose.map){ + if (through_already(step)){ + m_io.settle(BUTTON_B, label_of(step), false, ""); + return Pokemon::outcome_ok(); + } + const std::string banner = story_arrival_banner(state.pose.map, step.pose_after->map); const DoorRun door = door_run(state.pose.map, state.pose, step.direction, m_can_run); - const bool faded = m_io.run_into_door(step.direction, m_can_run, door.timeout, door.dark_from); + const WarpSeen seen = m_io.run_into_door(step.direction, m_can_run, door.timeout, door.dark_from, banner); log(std::format("[{}] {}: {} through the door (timeout {} ms, dark from {} ms): {}.", m_row, step.name, - direction_name(step.direction), door.timeout.count(), door.dark_from.count(), faded ? "faded" : "no fade yet")); - m_io.settle(BUTTON_B, label_of(step), !faded); + direction_name(step.direction), door.timeout.count(), door.dark_from.count(), seen.any() ? describe(seen) : "nothing yet")); + m_io.settle(BUTTON_B, label_of(step), !seen.any(), banner); return Pokemon::outcome_ok(); } turn(step.direction); @@ -416,6 +447,7 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ } Outcome StoryWalkSteps::talk(RunState& state, const StoryStep& step){ + m_warp = {}; // Face whom we talk to: a route ends facing its last leg, not its goal // (r40 reached Mom facing north). They block the tile, so the tap only turns. if (const std::optional facing = Pokemon::facing_of(state.pose)){ @@ -432,6 +464,7 @@ Outcome StoryWalkSteps::talk(RunState& state, const StoryStep& step){ } Outcome StoryWalkSteps::mash(RunState& state, const StoryStep& step){ + m_warp = {}; // The step before may have played the scene already (a door step settles // its arrival scene), so its first line is not required. if (!m_io.route().dialog_within(15000ms, COLOR_CYAN)){ @@ -439,7 +472,7 @@ Outcome StoryWalkSteps::mash(RunState& state, const StoryStep& step){ } m_io.settle(step.variant == "a" ? BUTTON_A : BUTTON_B, label_of(step), step.pose_after && step.pose_after->map != state.pose.map && - story_plan_world(state.pose.map, step.pose_after->map) == nullptr); + story_plan_world(state.pose.map, step.pose_after->map) == nullptr, ""); if (m_row == RUNNING_SHOES_ROW && step.name == RUNNING_SHOES_STEP){ m_can_run = true; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index a7c4aad024..c284f97065 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -76,6 +76,7 @@ class StoryWalkSteps{ Pokemon::Outcome leg_to_dialogue(const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_map(const Pokemon::StoryStep& step); Pokemon::Outcome tap_to_banner(const Pokemon::Pose& from, const Pokemon::StoryStep& step); + bool through_already(const Pokemon::StoryStep& step); void turn(Pokemon::Direction direction); void log(const std::string& text); @@ -86,6 +87,9 @@ class StoryWalkSteps{ // in its tiles, from its first walk this attempt; all of them again at // each attempt. std::map> m_trainers; + // The warp the last route ran on through at its end (walk_route_to_warp()), + // for the step after it, which goes through that warp. + WarpSeen m_warp; }; 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 4bacc207a3..fd86f221cc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp @@ -14,6 +14,7 @@ #include "Utils/PokemonBDSP_AutoStory_Indoors.h" #include "Utils/PokemonBDSP_AutoStory_Location.h" #include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "Utils/PokemonBDSP_AutoStory_Walk.h" #include "Actions/PokemonBDSP_AutoStory_Talks.h" #include "PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP_AutoStory_Walk_Tests.h" @@ -121,29 +122,33 @@ UnitTestResult test_door_fade(Logger&){ return true; } -// A tap step's fade is a real one: black, or a drop to dark from the look -// before the tap. The Oreburgh Gate's floor, about 46 before and after a -// tap inside it, is no fade: read as one, the tap into the Gate from -// Oreburgh, already through, waited 8 s for a banner gone (lab-B, -// 2026-11-08 15:31 to 15:54). -UnitTestResult test_tap_fade(Logger&){ +// A fade is uniform (fade_of(): the shared watchers' stddev test), dark or +// white; a floor is textured. The Oreburgh Gate's floor, about 46, is no +// fade: read as one, the tap into the Gate from Oreburgh, already +// through, waited 8 s for a banner gone (lab-B, 2026-11-08 15:31 to +// 15:54). A cave mouth's dim fade (45 to 64 measured) is one. The stddevs +// are a model; the Gate's frames on the console are to check them. +UnitTestResult test_fade_of(Logger&){ struct Case{ std::string name; - double before; - double after; - bool faded; + double brightness; + double stddev; + WarpFade fade; }; const std::vector cases{ - {.name = "inside the Gate, its floor", .before = 46, .after = 46, .faded = false}, - {.name = "inside the Gate, a darker patch", .before = 52, .after = 44, .faded = false}, - {.name = "on a street", .before = 120, .after = 112, .faded = false}, - {.name = "the street into the Gate's mouth, to black", .before = 120, .after = 8, .faded = true}, - {.name = "the street into a cave, a dim fade (45 to 64 measured)", .before = 120, .after = 60, .faded = true}, - {.name = "out of the Gate, from its floor to black", .before = 46, .after = 12, .faded = true}, + {.name = "inside the Gate, its floor", .brightness = 46, .stddev = 20, .fade = WarpFade::NONE}, + {.name = "Oreburgh's street at night", .brightness = 88, .stddev = 20, .fade = WarpFade::NONE}, + {.name = "a door's black", .brightness = 7, .stddev = 1, .fade = WarpFade::BLACK}, + {.name = "a cave mouth's dim fade", .brightness = 64, .stddev = 2, .fade = WarpFade::BLACK}, + {.name = "a grey screen, neither dark nor white", .brightness = 120, .stddev = 1, .fade = WarpFade::NONE}, + {.name = "a cave exit's white", .brightness = 250, .stddev = 1, .fade = WarpFade::WHITE}, + {.name = "a bright textured screen", .brightness = 250, .stddev = 20, .fade = WarpFade::NONE}, }; for (const Case& item : cases){ - if (tap_faded(item.before, item.after) != item.faded){ - return item.name + (item.faded ? ": no fade read." : ": read as a fade."); + const ImageStats stats(FloatPixel(item.brightness, item.brightness, item.brightness), FloatPixel(item.stddev, item.stddev, item.stddev), 1); + const WarpFade fade = fade_of(stats); + if (fade != item.fade){ + return item.name + ": " + warp_fade_name(fade) + ", expected " + warp_fade_name(item.fade) + "."; } } return true; @@ -315,7 +320,7 @@ const AutoStoryWalkCase AUTO_STORY_WALK_CASES[] = { .expectation = {}, }, { - .input = {"a tap into a door fades to black or drops to dark, not a dim floor (lab-B, 2026-11-08)", test_tap_fade}, + .input = {"a fade is uniform, dark or white; a dim floor is none (lab-B, 2026-11-08)", test_fade_of}, .expectation = {}, }, { diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp index 909766eb48..8f67d9a827 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -387,7 +387,9 @@ WalkResult GridSimRouteIO::walk_to_wall(const RouteWallWalk& walk){ const SimMove move = m_sim.hold(walk.direction, walk.limit, pace); m_notes.push_back(std::format("[Sim] {}: held {} to {} at {}.", walk.label, direction_name(walk.direction), sim_stop_name(move.stop), to_string(m_sim.player().pos))); - return {.stop = walk_stop(move.stop), .walked = move.time, .wild_battles = 0, .moved_chunks = (size_t)(move.distance / SIM_TILE)}; + WalkResult result{.stop = walk_stop(move.stop), .walked = move.time, .wild_battles = 0, .moved_chunks = (size_t)(move.distance / SIM_TILE)}; + result.warp.fade = move.stop == SimStop::WARP ? WarpFade::BLACK : WarpFade::NONE; + return result; } std::optional GridSimRouteIO::take_encounter(Direction direction, size_t tiles, size_t tap, const std::string& label){ @@ -430,6 +432,7 @@ WalkResult GridSimRouteIO::walk_taps(Direction direction, size_t tiles, const st result.moved_chunks += move.distance > 0 ? 1 : 0; if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ result.stop = walk_stop(move.stop); + result.warp.fade = move.stop == SimStop::WARP ? WarpFade::BLACK : WarpFade::NONE; }else if (still >= 2){ result.stop = WalkStop::BLOCKED; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 177439cd52..adc799531f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -429,15 +429,15 @@ class WalkStepsIO : public StoryStepIO{ unsupported("a run onto " + map); return false; } - virtual bool run_into_door(Direction, bool, Milliseconds, Milliseconds) override{ + virtual WarpSeen run_into_door(Direction, bool, Milliseconds, Milliseconds, const std::string&) override{ unsupported("a run into a door"); - return false; + return {}; } virtual std::optional tap_to_banner(Direction, const std::string& map, size_t) override{ unsupported("taps to " + map + "'s banner"); return std::nullopt; } - virtual void settle(Button, const std::string& label, bool) override{ + virtual void settle(Button, const std::string& label, bool, const std::string&) override{ unsupported(label + "'s settle"); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp index 9dd3fd9b47..a0968abb0f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include "Common/Cpp/Exceptions.h" @@ -44,14 +45,22 @@ using Pokemon::TilePos; // Cases the program fails today, with what is to fix each. const std::map KNOWN_FAILING{ - {"01.05 old walk slides onto the Gate's west mouth, dim fade, banner gone", "#268 slice 2: walkers report warps"}, - {"01.05 old walk slides onto the Gate's west mouth, black fade", "#268 slice 2: walkers report warps"}, - {"01.05 old walk slides onto the Gate's west mouth, white fade", "#268 slices 2 and 3: a fade watcher that tells white from a battle"}, {"01.05 through_the_gate is one run west", "planner: goal kinds and ms costs (PLANNER_DESIGN.md)"}, - {"any one missed fade or banner from 00.00 to 01.11: every row still passes", "#268 slice 1: door arrival = fade or banner"}, + {"any one missed fade or banner from 00.00 to 01.11: every row still passes", + "a third signal where a warp gives one (ONE_SIGNAL_STEPS): position (PLANNER_DESIGN.md 2, 4)"}, {"01.08 with Route 204's youngster wandering (12..14, 2)", "planner: one recovery rule, a sidestep round a wanderer (PLANNER_DESIGN.md 4, 7)"}, }; +// Warps that give one signal only (#268 slice 1: door = fade or banner), so +// a miss there leaves nothing to go on: a fade and no banner (stairs, into +// a building, between the mine's floors), or a banner and no fade (an open +// border crossed by run_until_map()). +const std::set ONE_SIGNAL_STEPS{ + "00.01 down_the_stairs", "00.01 into_barrys_house", "00.01 up_barrys_stairs", "00.01 down_barrys_stairs", + "00.04 into_the_house", "00.05 into_the_school", "01.03 into_the_coal_room", "01.03 up_to_the_hall", + "00.04 to_route_201", "01.10 into_floaroma", +}; + // The table's step `name` in row `row`. const StoryStep& table_step(const std::string& row, const std::string& name){ for (const StoryCheckpoint& checkpoint : story_checkpoints()){ @@ -117,10 +126,10 @@ UnitTestResult gate_plan_one_run(Logger& logger){ } // Each fade and each banner the clean run looks for, missed alone: the -// row it falls in must still pass. A door step accepts only its fade -// today, so a missed fade there fails a real arrival (#268's Monte Carlo, -// 19/20 on 01.05). -UnitTestResult every_single_miss(Logger& logger){ +// row it falls in must still pass, but for a miss in one of `skip`'s steps. +// A door step once accepted only its fade, so a missed fade there failed a +// real arrival (#268's Monte Carlo, 19/20 on 01.05). +UnitTestResult every_single_miss(Logger& logger, const std::set& skip){ SimExecutor clean(logger); if (!run_rows_on(clean, logger, {.from = "00.00", .to = "01.11"}).completed){ return "the run fails without misses: " + clean.result().error; @@ -134,9 +143,12 @@ UnitTestResult every_single_miss(Logger& logger){ } SimMisses misses{.fade = {}, .banner = {}}; (fade ? misses.fade : misses.banner) = index - (fade ? rows[k].fades : rows[k].banners); - const std::string stopped = run_case(logger, rows[k].row, rows[k].row, misses, {}); - if (!stopped.empty()){ - failed.push_back(std::format("{} {} missed: {}", fade ? "fade" : "banner", index, stopped)); + SimExecutor executor(logger, misses); + if (!run_rows_on(executor, logger, {.from = rows[k].row, .to = rows[k].row}).completed + && !skip.contains(executor.result().failed_step) + ){ + failed.push_back(std::format("{} {} missed: stopped in {}: {}", fade ? "fade" : "banner", index, + executor.result().failed_step, executor.result().error)); } }; for (size_t i = 0; i < clean.misses().fades; i++){ @@ -154,8 +166,9 @@ UnitTestResult every_single_miss(Logger& logger){ // Oreburgh's street at night (88, game clock 00:25; 104 by day, r74), the // Gate's dim floor (46) and a cave mouth's dim fade (45 to 64): the tap -// steps judge their fades with tap_faded(), which took the Gate's floor -// for a fade under the old "brightness under 75" (lab-B 2026-11-08). +// steps judge their fades with fade_of(): uniform, so a textured floor +// is none. The old "brightness under 75" took the Gate's floor for a fade +// (lab-B 2026-11-08). UnitTestResult night_and_dim_floors(Logger& logger){ SimWorldKnobs knobs{ .floor = {{"OreburghCity", 88}, {"Route203", 88}, {"OreburghGate", 46}}, @@ -253,7 +266,12 @@ const FailureCase AUTO_STORY_FAILURE_CASES[] = { return gate_old_walk_slides(logger, SimFade::WHITE, true); }}, .expectation = {}}, {.input = {"01.05 through_the_gate is one run west", gate_plan_one_run}, .expectation = {}}, - {.input = {"any one missed fade or banner from 00.00 to 01.11: every row still passes", every_single_miss}, .expectation = {}}, + {.input = {"any one missed fade or banner from 00.00 to 01.11: every row still passes", [](Logger& logger){ + return every_single_miss(logger, {}); + }}, .expectation = {}}, + {.input = {"any one missed fade or banner at a warp that shows both: its row still passes", [](Logger& logger){ + return every_single_miss(logger, ONE_SIGNAL_STEPS); + }}, .expectation = {}}, {.input = {"01.02 to 01.05 at night, the Gate's dim floor", night_and_dim_floors}, .expectation = {}}, {.input = {"01.03 Roark's first line 7 s after the A press", roark_speaks_late}, .expectation = {}}, {.input = {"01.03 with Oreburgh's people wandering (the pokefan on 45, 37..39)", [](Logger& logger){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index 6b2fde5764..bab465a377 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -30,6 +30,10 @@ using Pokemon::StoryStepKind; using Pokemon::TilePos; +ImageStats sim_screen(double brightness, double stddev){ + return ImageStats(FloatPixel(brightness, brightness, brightness), FloatPixel(stddev, stddev, stddev), 1); +} + // A hold until something stops us. A door stops it at the fade, which // fails the step; a fade missed lets the hold go on past the mouth (r81's // timed walk south out of the Ravaged Path, onto Route 204's cliff). @@ -75,12 +79,12 @@ double SimStoryStepIO::floor_here() const{ return SIM_FLOOR; } -// D-pad taps, each looked at, until the fade and then the banner (the -// console's ConsoleStoryStepIO::tap_to_banner()): none if the banner shows -// before the first. Each look stands still, so a banner on the far side -// reads at once. A look the program's tap_faded() takes for the fade ends -// the taps, banner or not: a warp's fade, or a dim floor read as one; with -// the fade missed the next look still sees the banner. +// D-pad taps, each looked at, until the fade or the banner (the console's +// ConsoleStoryStepIO::tap_to_banner()): none if the banner shows before +// the first. Each look stands still, so a banner on the far side reads at +// once. A look the program's fade_of() takes for a fade ends the taps: a +// warp's fade, or a floor read as one; with the fade missed the look still +// sees the banner. std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ if (m_misses.through == m_misses.tap_steps++){ m_misses.missed = true; @@ -93,23 +97,22 @@ std::optional SimStoryStepIO::tap_to_banner(Direction direction, const s } bool crossed = false; for (size_t tap = 1; tap <= max_taps; tap++){ - const double before = floor_here(); const SimMove move = m_sim.tap(direction, 160ms, false); if (move.stop == SimStop::DIALOG){ return std::nullopt; } - double look = floor_here(); + ImageStats look = sim_screen(floor_here(), SIM_FLOOR_STDDEV); if (move.stop == SimStop::WARP){ const auto fade = m_knobs.fade_into.find(map); - look = fade_missed() ? look : fade == m_knobs.fade_into.end() ? SIM_DOOR_FADE : fade->second; + if (!fade_missed()){ + look = sim_screen(fade == m_knobs.fade_into.end() ? SIM_DOOR_FADE : fade->second, SIM_FADE_STDDEV); + } crossed = m_far_side(); } - if (crossed && on_map(map) && !banner_missed()){ + const bool banner = crossed && on_map(map) && !banner_missed(); + if (banner || fade_of(look) != WarpFade::NONE){ return tap; } - if (tap_faded(before, look)){ - return std::nullopt; - } } return std::nullopt; } @@ -128,9 +131,11 @@ WalkResult SimKnobRouteIO::walk_taps(Direction direction, size_t tiles, const st return result; } -// The taps past the leg's end. Onto a warp the walk sees what the fade -// looks like to its watchers: a black fade ends it (TRANSITION), a white -// one is a wild battle to it, a dim one nothing. +// The taps past the leg's end. Onto a warp the walk sees the fade as the +// program's fade_of() judges it, the walk's watchers' test: a fade ends +// it (TRANSITION), a white one too, as no battle follows it. The walk ends +// at the fade, before the banner shows (about 1.5 s after it), so it +// reads none. WalkResult SimKnobRouteIO::slide_on(const SimSlide& slide, WalkResult result){ m_misses.slid = true; for (size_t tap = 0; tap < slide.tiles; tap++){ @@ -142,10 +147,10 @@ WalkResult SimKnobRouteIO::slide_on(const SimSlide& slide, WalkResult result){ note("[Sim] slid onto a warp to " + Pokemon::to_string(slide.far) + ".", RouteNote::LOG); m_cross(slide.far); m_misses.banner_up = slide.banner_up ? slide.far.map : ""; - if (slide.fade == SimFade::BLACK){ + const double brightness = slide.fade == SimFade::BLACK ? SIM_DOOR_FADE : slide.fade == SimFade::DIM ? SIM_DIM_FADE : SIM_WHITE_FADE; + result.warp.fade = fade_of(sim_screen(brightness, SIM_FADE_STDDEV)); + if (result.warp.fade != WarpFade::NONE){ result.stop = WalkStop::TRANSITION; - }else if (slide.fade == SimFade::WHITE){ - result.wild_battles++; } return result; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index e4bbe4cfc1..2b45f99197 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -23,6 +23,7 @@ #include #include "Common/Cpp/Logging/AbstractLogger.h" #include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/ImageTools/ImageStats.h" #include "Pokemon/AutoStory/Pokemon_StorySegments.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" @@ -63,16 +64,17 @@ struct SimMisses{ std::string banner_up = {}; }; -// How a warp's fade looks to the console's watchers (#268's design note). +// How a warp's fade looks on the screen (#268's design note); the +// program's fade_of() judges it, as the walk's watchers do. enum class SimFade{ - // A door's: near black. Every watcher of a black screen sees it. + // A door's: near black (SIM_DOOR_FADE). BLACK, - // A cave mouth's: dim, not black. A walk's strict black watcher (rgb - // sum 100, stddev 10; WalkRunner::hold()) misses it and the walk goes - // on (the Oreburgh Gate, lab-B 2026-11-08 16:03). + // A cave mouth's: dim, not black (SIM_DIM_FADE). The walk's old strict + // black watcher (rgb sum 100) missed it and the walk went on (the + // Oreburgh Gate, lab-B 2026-11-08 16:03). DIM, - // A cave exit's white: a walk's encounter-flash watcher reads it as a - // wild battle. + // A cave exit's white. The walk's old encounter-flash watcher read it + // as a wild battle. WHITE, }; @@ -96,8 +98,9 @@ struct SimWorldKnobs{ std::vector slides = {}; // The mean brightness (0 to 255) of a map's floor, by JSON map name, and // of the fade into a map; a tap step judges its fade from these with the - // program's tap_faded(). Unset: 104 (Oreburgh's street by day) and 7 - // (a door's black). + // program's fade_of(), a floor textured, a fade uniform (SIM_FLOOR_STDDEV, + // SIM_FADE_STDDEV). Unset: 104 (Oreburgh's street by day) and 7 (a + // door's black). std::map floor = {}; std::map fade_into = {}; // People with a wander box on their map walk it, a step tried every 2 s. @@ -150,6 +153,17 @@ constexpr Milliseconds SIM_FALSE_DARK = Milliseconds(1800); constexpr double SIM_FLOOR = 104; // Brightness of a fade where SimWorldKnobs does not say: a door's black (by hand: 7). constexpr double SIM_DOOR_FADE = 7; +// Brightness of a cave mouth's dim fade (45 to 64 measured). +constexpr double SIM_DIM_FADE = 55; +// Brightness of a cave exit's white fade. +constexpr double SIM_WHITE_FADE = 250; +// The spread (stddev a channel) of a fade: uniform. A model, not measured +// on the console. +constexpr double SIM_FADE_STDDEV = 1; +// The spread of a floor, which the game draws with texture. A model too. +constexpr double SIM_FLOOR_STDDEV = 20; +// The screen's middle as fade_of() reads it: `brightness` a channel, `stddev` a channel. +ImageStats sim_screen(double brightness, double stddev); // What a run on the simulation did. struct SimRun{ @@ -198,24 +212,32 @@ class SimStoryStepIO : public StoryStepIO{ } virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; - virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) override{ + // A door's fade stops the run; with the fade missed, the run goes on + // holding and sees the far map's `banner` show after it, if it has one + // (story_arrival_banner(): the sim's maps have no banners of their own). + virtual WarpSeen run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), + Milliseconds dark_from = Milliseconds(0), const std::string& banner = "") override{ const SimPace pace = run ? SimPace::RUN : SimPace::WALK; if (false_dark() && dark_from <= SIM_FALSE_DARK && SIM_FALSE_DARK < timeout){ m_sim.hold(direction, SIM_FALSE_DARK, pace); - return true; + return {.fade = WarpFade::BLACK}; } - const bool warped = m_sim.hold(direction, timeout, pace).stop == SimStop::WARP; - if (warped && fade_missed()){ - m_misses.fade_unseen = true; - return false; + if (m_sim.hold(direction, timeout, pace).stop != SimStop::WARP){ + return {}; } - return warped; + if (!fade_missed()){ + return {.fade = WarpFade::BLACK}; + } + m_misses.fade_unseen = true; + return {.banner = !banner.empty() && !banner_missed() ? banner : ""}; } // A scene may take us to another map (Mom walks us out, 00.04): with a // dialogue open the stub scene plays it. Otherwise only a door fades. // A fade missed on the way in stays missed: it was over before settle() - // looked, which then fails as it does on the console after 120 s. - virtual void settle(Button, const std::string& label, bool fade) override{ + // looked, which then fails as it does on the console after 120 s. The + // run before looked for the banner (run_into_door()), so settle() sees + // none here. + virtual void settle(Button, const std::string& label, bool fade, const std::string&) override{ const bool scene_fades = m_sim.player().dialog && m_far_side(); if (fade && ((!m_sim.player().warped && !scene_fades) || m_misses.fade_unseen)){ m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); 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 df31791552..9556ec5018 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp @@ -6,11 +6,13 @@ #include #include +#include #include #include "CommonFramework/ImageTools/ImageBoxes.h" #include "CommonFramework/ImageTools/ImageStats.h" #include "CommonFramework/ImageTypes/ImageRGB32.h" #include "CommonFramework/Language.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" #include "CommonTools/Images/ImageFilter.h" #include "CommonTools/OCR/OCR_RawTesseractOCR.h" #include "PokemonBDSP_AutoStory_Location.h" @@ -143,6 +145,47 @@ bool location_banner_matches(const std::string& read, const std::string& expecte } +std::string LocationBannerReads::read(const ImageViewRGB32& screen, WallClock now){ + if (!location_banner_showing(screen)){ + m_reads = 0; + return ""; + } + if (m_reads >= 2 || (m_reads == 1 && now - m_first < std::chrono::milliseconds(300))){ + return ""; + } + if (m_reads == 0){ + m_first = now; + } + m_reads++; + return read_location_banner(screen); +} + +LocationBannerWatcher::LocationBannerWatcher(std::string expected) + : VisualInferenceCallback("LocationBannerWatcher") + , m_expected(std::move(expected)) +{} +void LocationBannerWatcher::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_CYAN, LOCATION_BANNER_WHITE); +} +bool LocationBannerWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + const std::string read = m_reads.read(frame, timestamp); + if (read.empty() || m_matched){ + return m_matched; + } + m_last_read = read; + if (!m_expected.empty() && location_banner_matches(read, m_expected)){ + m_seen = read; + m_matched = true; + return true; + } + if (m_seen.empty() && m_expected.empty()){ + m_seen = read; + } + return false; +} + + + } // 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 cb4e4c8626..d2baff6d70 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h @@ -11,8 +11,10 @@ #define PokemonAutomation_PokemonBDSP_AutoStory_Location_H #include +#include "Common/Cpp/Time.h" #include "CommonFramework/Language.h" #include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -63,6 +65,47 @@ std::string read_save_screen_location(const ImageViewRGB32& screen); // read as Route 202. bool location_banner_matches(const std::string& read, const std::string& expected); +// Reads the location banner at most twice per showing: when its box shows, +// and once more 300 ms later in case the first frame caught it sliding in. +// The box test runs on every frame; OCR (tens of ms) only then (#268's cost +// rule: the old look read every poll while the box showed, 30 to 40 reads). +class LocationBannerReads{ +public: + // The banner's text if this frame was read, "" if not. + std::string read(const ImageViewRGB32& screen, WallClock now); + +private: + size_t m_reads = 0; + WallClock m_first = WallClock::min(); +}; + +// Watches the location banner through an action. With `expected` (a map's +// banner name) it stops the action when that banner reads; without, it +// only keeps the first banner read. +class LocationBannerWatcher : public VisualInferenceCallback{ +public: + explicit LocationBannerWatcher(std::string expected = ""); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + // The expected banner if it read, else the first banner read; "" if none. + const std::string& seen() const{ + return m_seen; + } + // The last banner read, for the log. + const std::string& last_read() const{ + return m_last_read; + } + +private: + std::string m_expected; + LocationBannerReads m_reads; + std::string m_seen; + std::string m_last_read; + bool m_matched = false; +}; + } // namespace PokemonBDSP } // namespace NintendoSwitch 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 b2f2d0354f..5a8263eeb2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -69,23 +69,6 @@ void log_leg_done(RouteIO& io, const StoryWorld& maps, const std::string& label, 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 -// 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; -} - // 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; @@ -195,7 +178,10 @@ size_t min_tiles_at_wall(size_t expected_tiles){ enum class LegNext{ NEXT_LEG, REPLAN, + ARRIVED_EARLY, // through a warp at the leg's end (walk_route_to_warp()) }; +// How far past a leg's end a walk that ran on may have gone. +constexpr size_t WARP_SLIDE_TILES = 2; // One planned leg as it is walked: where it goes, and the location // banners read on the way. @@ -246,7 +232,7 @@ class RouteWalker{ , m_plan(plan) {} - std::vector run(std::vector from); + RouteEnd run(std::vector from); private: std::vector plan_legs() const; @@ -290,11 +276,12 @@ 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; + WarpSeen m_warp; // Dialogue the map does not explain, so far on this route. size_t m_unexplained_talks = 0; }; -std::vector RouteWalker::run(std::vector from){ +RouteEnd 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. @@ -309,12 +296,12 @@ std::vector RouteWalker::run(std::vector from){ const std::vector legs = plan_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; + LegNext next = LegNext::NEXT_LEG; + for (size_t number = 1; number <= legs.size() && next == LegNext::NEXT_LEG; number++){ + next = walk_leg(legs[number - 1], number, legs.size()); } - if (!replanned){ - return arrive(); + if (next != LegNext::REPLAN){ + return {next == LegNext::ARRIVED_EARLY ? m_from : arrive(), m_warp}; } } fail(m_io, m_plan.label + ": too many plans."); @@ -356,10 +343,15 @@ LegNext RouteWalker::walk_leg(const PlannedLeg& planned, size_t number, size_t c return next; } m_facing = planned.leg.direction; - check_banners(walk); if (walk.result.stop == WalkStop::TRANSITION){ - fail(m_io, walk.label + ": unexpected transition."); + if (!warp_within(m_grid, m_from, planned.leg.direction, planned.leg.tiles + WARP_SLIDE_TILES)){ + fail(m_io, walk.label + ": unexpected transition."); + } + m_io.note("[Route] " + walk.label + ": through the warp at its end (" + describe(walk.result.warp) + "); handing over.", RouteNote::WARNING); + m_warp = walk.result.warp; + return LegNext::ARRIVED_EARLY; } + check_banners(walk); return after_leg(walk); } @@ -857,6 +849,17 @@ std::vector walk_route( std::vector walk_route( RouteIO& io, const StoryWorld& maps, std::vector from, RouteTrainers& trainers, const RouteWalkPlan& plan +){ + RouteEnd end = walk_route_to_warp(io, maps, std::move(from), trainers, plan); + if (end.warp.any()){ + fail(io, plan.label + ": unexpected transition."); + } + return std::move(end.tiles); +} + +RouteEnd walk_route_to_warp( + RouteIO& io, const StoryWorld& maps, std::vector from, + RouteTrainers& trainers, const RouteWalkPlan& plan ){ return RouteWalker(io, maps, trainers, plan).run(std::move(from)); } 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 0f6efccc0a..777019cfdd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h @@ -71,6 +71,21 @@ std::vector walk_route( RouteTrainers& trainers, const RouteWalkPlan& plan ); +// Where walk_route_to_warp() ended: on `tiles`, or through a warp it saw +// (`warp`), with `tiles` where the leg that went through began. +struct RouteEnd{ + std::vector tiles; + WarpSeen warp = {}; +}; +// walk_route(), but a fade on a leg with a warp at most a tile or two past +// its end ends the walk there, as arrived early: the walk ran on onto the +// warp (01.05's Oreburgh Gate, lab-B 2026-11-08), and the step after goes +// through it (#268 slice 2). Any other fade fails as in walk_route(). +RouteEnd walk_route_to_warp( + 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. struct WaypointWalkPlan{ 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 fdc6357556..f1a18078fb 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp @@ -9,6 +9,7 @@ #include #include "Common/Cpp/Exceptions.h" #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" #include "CommonFramework/ImageTools/ImageDiff.h" #include "CommonFramework/ImageTypes/ImageRGB32.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" @@ -20,6 +21,7 @@ #include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" #include "PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h" #include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP_AutoStory_Walk.h" namespace PokemonAutomation{ @@ -40,6 +42,37 @@ const char* walk_stop_name(WalkStop stop){ return "?"; } +const char* warp_fade_name(WarpFade fade){ + switch (fade){ + case WarpFade::NONE: return "no fade"; + case WarpFade::BLACK: return "black fade"; + case WarpFade::WHITE: return "white fade"; + } + return "?"; +} + +WarpFade fade_of(const ImageStats& middle){ + if (middle.stddev.sum() > FADE_MAX_STDDEV_SUM){ + return WarpFade::NONE; + } + const double sum = middle.average.sum(); + return sum <= FADE_MAX_DARK_SUM ? WarpFade::BLACK : sum >= FADE_MIN_WHITE_SUM ? WarpFade::WHITE : WarpFade::NONE; +} +WarpFade fade_of_screen(const ImageViewRGB32& screen){ + return fade_of(image_stats(extract_box_reference(screen, ImageFloatBox(0.1, 0.1, 0.8, 0.8)))); +} + +std::string describe(const WarpSeen& seen){ + if (!seen.any()){ + return "nothing"; + } + std::string out = seen.fade == WarpFade::NONE ? "" : warp_fade_name(seen.fade); + if (!seen.banner.empty()){ + out += (out.empty() ? "banner \"" : ", banner \"") + seen.banner + "\""; + } + return out; +} + 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)); @@ -80,7 +113,7 @@ DpadPosition dpad_toward(JoystickPosition stick){ 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 gone(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, FADE_MAX_DARK_SUM, FADE_MAX_STDDEV_SUM, BlackScreenWatcher::FinderType::GONE, 500ms); const int ret = wait_until(stream, context, 10s, {{battle_menu}, {battle_dialog}, {gone}}); if (ret == 2){ @@ -95,12 +128,16 @@ bool black_screen_was_battle(VideoStream& stream, ProControllerContext& context) // 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){ +bool battle_follows(VideoStream& stream, ProControllerContext& context, Milliseconds wait = 5000ms){ BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); BattleDialogWatcher battle_dialog(COLOR_YELLOW); - return wait_until(stream, context, 5s, {{battle_menu}, {battle_dialog}}) >= 0; + return wait_until(stream, context, wait, {{battle_menu}, {battle_dialog}}) >= 0; } +// After a white flash: an encounter's, if its battle shows; else a cave +// exit's white fade (#268 slice 3), which the walk once fled as a battle. +constexpr Milliseconds WHITE_FLASH_BATTLE_WAIT = 8000ms; + } // namespace // A step in tall grass that was started before the stick was released still @@ -250,19 +287,24 @@ class WalkUntil{ } private: + // The banner watcher only looks (m_banner keeps the first read); a + // fade ends the chunk: dark (fade_of()'s uniform test, a cave's dim + // fade too) or the white of an encounter or a cave exit. int hold(Milliseconds chunk){ WhiteScreenOverWatcher encounter_flash(COLOR_YELLOW, {0.1, 0.1, 0.8, 0.8}); - BlackScreenWatcher black(COLOR_RED); + BlackScreenWatcher black(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, FADE_MAX_DARK_SUM, FADE_MAX_STDDEV_SUM); BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); ShortDialogWatcher dialog(COLOR_YELLOW); BattleDialogWatcher battle_dialog(COLOR_YELLOW); - return run_until( + const int ret = run_until( m_stream, m_context, [&](ProControllerContext& context){ press(context, chunk); }, - {{encounter_flash}, {black}, {battle_menu}, {dialog}, {battle_dialog}} + {{encounter_flash}, {black}, {battle_menu}, {dialog}, {battle_dialog}, {m_banner}} ); + m_result.warp.banner = m_banner.seen(); + return ret; } void press(ProControllerContext& context, Milliseconds chunk) const{ @@ -286,10 +328,13 @@ class WalkUntil{ // 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); + bool battle = ret == 2 || ret == 4; + if (ret == 0 || ret == 1){ + battle = ret == 0 + ? battle_follows(m_stream, m_context, WHITE_FLASH_BATTLE_WAIT) + : black_screen_was_battle(m_stream, m_context); if (!battle){ + m_result.warp.fade = ret == 0 ? WarpFade::WHITE : WarpFade::BLACK; return {ChunkNext::STOP, WalkStop::TRANSITION}; } } @@ -422,6 +467,7 @@ class WalkUntil{ size_t m_unchanged = 0; size_t m_chunks = 0; double m_largest = 0; + LocationBannerWatcher m_banner; }; WalkResult walk_until_spec( @@ -487,7 +533,7 @@ WalkResult walk_for( 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); + BlackScreenWatcher black(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, FADE_MAX_DARK_SUM, FADE_MAX_STDDEV_SUM); BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); ShortDialogWatcher dialog(COLOR_YELLOW); BattleDialogWatcher battle_dialog(COLOR_YELLOW); @@ -507,6 +553,7 @@ WalkResult walk_for( battle = black_screen_was_battle(stream, context); if (!battle){ result.stop = WalkStop::TRANSITION; + result.warp.fade = WarpFade::BLACK; } } if (battle){ 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 f83f45ce07..311e3c784e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h @@ -14,6 +14,7 @@ #include #include #include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTools/ImageStats.h" #include "CommonFramework/ImageTypes/ImageViewRGB32.h" #include "CommonFramework/Tools/VideoStream.h" #include "Controllers/Joystick.h" @@ -33,7 +34,7 @@ using WildBattleEscape = std::function; // hold where we are. enum class WalkOrigin{ CURRENT_LEG, MAY_PRECEDE_LEG }; +// How a screen's fade looks (#268's design note, slice 3). +enum class WarpFade{ + NONE, + BLACK, // a door's black, or a cave mouth's dim fade + WHITE, // a cave exit's white, with no battle after it +}; +// "black fade", for the log. +const char* warp_fade_name(WarpFade fade); + +// A fade is uniform over the middle 80% of the screen, the shared +// Black/WhiteScreenWatcher's stddev test (upstream #1717): a dim cave floor +// is textured, so it is no fade (the Oreburgh Gate's, mean 46, lab-B +// 2026-11-08). Check against the Gate's frames on the console before +// tightening. +constexpr double FADE_MAX_STDDEV_SUM = 10; +// Dark goes to an rgb sum of 225, as a cave mouth's fade is dim, 45 to 64 +// a channel, not black. +constexpr double FADE_MAX_DARK_SUM = 225; +// White from an rgb sum of 500, as the shared WhiteScreenWatcher's. +constexpr double FADE_MIN_WHITE_SUM = 500; +// The fade `middle` (the stats of the screen's middle 80%) shows, if any. +WarpFade fade_of(const ImageStats& middle); +// fade_of() for a screen. +WarpFade fade_of_screen(const ImageViewRGB32& screen); + +// What a walk or a step saw of a warp (#268): a fade or the location +// banner of the map arrived on. Either one alone is the warp. +struct WarpSeen{ + WarpFade fade = WarpFade::NONE; + // The banner read, "" if none. + std::string banner = {}; + + bool any() const{ + return fade != WarpFade::NONE || !banner.empty(); + } +}; +// How it was seen, for the log: a black fade, banner "Route 203". +std::string describe(const WarpSeen& seen); + // Result metrics and terminal state returned by automated walking execution. struct WalkResult{ WalkStop stop; @@ -59,6 +99,9 @@ struct WalkResult{ // taps into Taylor's freeze). size_t moved_chunks = 0; WalkOrigin origin = WalkOrigin::CURRENT_LEG; + // The fade that ended a TRANSITION, and any location banner read on + // the way (#268 slice 2: walkers report warps). + WarpSeen warp = {}; }; // Holds the left stick at `stick` until one of the WalkStop events. Wild battles on