diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 75af9451cc..6dcc2c6876 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -35,6 +35,7 @@ #include "Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h" #include "Pokemon/Navigation/Pokemon_LegPlanner_Tests.h" +#include "Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.h" #include "Pokemon/Navigation/Pokemon_LegWalker_Tests.h" #include "Pokemon/Navigation/Pokemon_MapData_Tests.h" #include "Pokemon/Navigation/Pokemon_RouteLog_Tests.h" @@ -80,6 +81,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ OCR::add_tests(ret); Kernels::add_tests(ret); Pokemon::add_tests_LegPlanner(ret); + Pokemon::add_tests_RobustLegPlanner(ret); Pokemon::add_tests_LegWalker(ret); Pokemon::add_tests_WallRecovery(ret); Pokemon::add_tests_MapData(ret); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h new file mode 100644 index 0000000000..6c527a19fb --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h @@ -0,0 +1,461 @@ +/* Robust Leg Planner + * + * From: https://github.com/PokemonAutomation/ + * + * Plans walks whose open legs may go a tile short or long. A leg to a wall + * is walked until the player stops; an open leg is walked for its tiles' + * worth of time and may end a few tiles either way. The planner searches + * over the sets of places the player may stand on after each leg, and + * later walls bring them back together, so the plan reaches the goal from + * every place the player may be. + * + * A step model is a class with: + * + * using State = ...; // where the player is: comparable with == + * using StateLess = ...; // a strict order of State, for sets of them: + * // std::less for TilePos and MapPlace + * std::optional step(const State& state, Direction direction) const; + * size_t step_tiles(const State& from, const State& to) const; + * bool held_at(const State& state, Direction direction) const; + * bool wild(const State& state) const; + * bool wander(const State& state) const; + * + * step() is where one step `direction` lands, or nothing if the player is + * stopped. step_tiles() is how many tiles that step counts (a ledge hop + * counts 2). held_at() is whether the player, stopped, stays put however + * long the button is held (a wall); a stop that isn't held (a door, an exit + * off the maps) makes a leg the planner can't tell the end of, and it is + * not used. wild() is a place where a wild battle may stop the walk (tall + * grass); wander() one where someone wanders. + * + * Warps and game actions (doors, Surf, spin tiles) are not legs: a stop + * that isn't held is never used, so a plan never crosses a warp. Callers + * plan each stretch between warps on its own. The step model here and the + * one of Pokemon_LegPlanner.h (press(), Step) describe the same + * world rules for two planners; a game writes one adapter for each. + * + */ + +#ifndef PokemonAutomation_Pokemon_RobustLegPlanner_H +#define PokemonAutomation_Pokemon_RobustLegPlanner_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A leg of a robust plan: walk `direction` for `tiles` tiles, or until +// stopped if `to_wall`. `after` lists every place the player may stand on +// once the leg is done. +template +struct RobustLeg{ + Direction direction = Direction::NORTH; + size_t tiles = 0; // tiles travelled; a ledge hop counts 2 + bool to_wall = false; + std::vector after; +}; + + +// The weights of a robust plan and the limits of its search. +struct RobustLegCosts{ + int per_tile = 1; + int per_wild_tile = 4; // extra for each wild tile entered + int per_wander_tile = 3; // extra for each tile entered where someone wanders + int per_leg = 8; + int leg_not_at_wall = 50; // extra for a leg that stops in the open + // An open leg of n tiles may end open_error + n / open_error_per tiles + // short or long. open_error_per 0 adds no growth: every open leg is + // off by open_error at most, and by nothing if open_error is 0 too. + int open_error = 1; + int open_error_per = 5; + // Open legs this many tiles or shorter land exactly. 0 keeps every + // open leg uncertain. + int exact_open_tiles = 0; + // Extra per tile of an open leg: its timing error grows with its length. + int per_open_tile = 0; + int max_open_tiles = 12; // longest open leg to consider + size_t max_spread = 5; // most places the player may be on after a leg + // Most sets of places to search before giving up. The search is over + // sets, not places, so it grows far faster than the map. + size_t max_searched = 20000; +}; + + +// The cheapest legs that take the player from any of `from` to places that +// all satisfy `goal`, even if every open leg ends up to its error off. +// Legs that run along where someone wanders (two such places in a row, the +// leg's start among them) are not used. Nothing if no such plan exists, or +// none is found within `costs.max_searched` sets. +template +std::optional>> plan_robust_legs( + const Model& model, + std::vector from, + const std::function& goal, + const RobustLegCosts& costs +); + +// What plan_robust_legs() charges for walking `legs` from any of `from`, +// each leg from the places the one before may end on. A leg it would not +// plan costs its tiles and legs without wild or wander tiles. +template +long long robust_legs_cost( + const Model& model, + std::vector from, + const std::vector>& legs, + const RobustLegCosts& costs +); + + + +namespace RobustLegPlannerInternal{ + +// Most steps a leg to a wall may take. No map is this long; a model whose +// steps loop (edge connections that come back round, or a model bug) +// would otherwise slide forever. +inline constexpr size_t MAX_STEPS_TO_WALL = 1024; + +// Where the player stops walking `direction` until stopped. +template +struct WallHit{ + State stop; + size_t tiles = 0; + bool held = false; +}; +// Walks `direction` from `from` until the player is stopped. A walk that +// is not stopped within MAX_STEPS_TO_WALL steps is not held. +template +WallHit slide_to_wall(const Model& model, const typename Model::State& from, Direction direction){ + WallHit hit{from}; + for (size_t steps = 0; steps < MAX_STEPS_TO_WALL; steps++){ + const auto next = model.step(hit.stop, direction); + if (!next){ + hit.held = model.held_at(hit.stop, direction); + return hit; + } + hit.tiles += model.step_tiles(hit.stop, *next); + hit.stop = *next; + } + return hit; +} + +// How many tiles an open leg of `tiles` tiles may end short or long. +inline int open_leg_error(int tiles, const RobustLegCosts& costs){ + if (tiles <= costs.exact_open_tiles){ + return 0; + } + if (costs.open_error_per <= 0){ + return costs.open_error; + } + return costs.open_error + tiles / costs.open_error_per; +} + +// Where `from` ends up after `tiles` tiles `direction`, stopping early +// where it is held, and the wild and wander tiles it enters. Nothing if a +// step is stopped where the player is not held. +template +struct Stepped{ + State end; + int wild = 0; + int wander = 0; + bool along_wander = false; +}; +// Steps `from` up to `tiles` tiles `direction` (see Stepped). +template +std::optional> step_tiles(const Model& model, typename Model::State from, Direction direction, int tiles){ + Stepped stepped{from}; + int travelled = 0; + bool in_wander = model.wander(from); + while (travelled < tiles){ + const auto next = model.step(from, direction); + if (!next){ + if (!model.held_at(from, direction)){ + return std::nullopt; + } + break; + } + travelled += (int)model.step_tiles(from, *next); + stepped.wild += model.wild(*next) ? 1 : 0; + const bool next_wander = model.wander(*next); + if (next_wander){ + stepped.wander++; + stepped.along_wander |= in_wander; + } + in_wander = next_wander; + from = *next; + } + stepped.end = from; + return stepped; +} + +// Sorts a spread and drops repeated places, so equal sets compare equal. +template +void normalize(std::vector& spread){ + using State = typename Model::State; + std::sort(spread.begin(), spread.end(), typename Model::StateLess()); + spread.erase(std::unique(spread.begin(), spread.end(), [](const State& a, const State& b){ return a == b; }), spread.end()); +} +// Orders spreads, for keeping them in a map. +template +struct SpreadLess{ + bool operator()(const std::vector& a, const std::vector& b) const{ + return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), typename Model::StateLess()); + } +}; + +// A leg out of a spread: where every place of it ends, and its cost. +template +struct Expansion{ + long long cost = 0; + RobustLeg leg; +}; + +// To the wall: every place walks until stopped. Nothing unless each is +// held, and one moves. +template +std::optional> to_wall_leg( + const Model& model, const std::vector& spread, Direction direction, const RobustLegCosts& costs +){ + Expansion expansion; + size_t longest = 0; + int wild = 0; + int wander = 0; + for (const auto& place : spread){ + const auto hit = slide_to_wall(model, place, direction); + if (!hit.held){ + return std::nullopt; + } + if (const auto stepped = step_tiles(model, place, direction, (int)hit.tiles)){ + if (stepped->along_wander){ + return std::nullopt; + } + wild = std::max(wild, stepped->wild); + wander = std::max(wander, stepped->wander); + } + longest = std::max(longest, hit.tiles); + expansion.leg.after.push_back(hit.stop); + } + if (longest == 0){ + return std::nullopt; + } + expansion.cost = (long long)costs.per_leg + (long long)costs.per_tile * longest + + (long long)costs.per_wild_tile * wild + (long long)costs.per_wander_tile * wander; + expansion.leg.direction = direction; + expansion.leg.tiles = longest; + expansion.leg.to_wall = true; + return expansion; +} + +// Open: about `tiles` tiles, give or take the error. Nothing if any +// possible end is stopped where the player is not held. +template +std::optional> open_leg( + const Model& model, const std::vector& spread, Direction direction, int tiles, const RobustLegCosts& costs +){ + Expansion expansion; + int wild = 0; + int wander = 0; + const int error = open_leg_error(tiles, costs); + for (const auto& place : spread){ + for (int n = std::max(1, tiles - error); n <= tiles + error; n++){ + const auto stepped = step_tiles(model, place, direction, n); + if (!stepped || stepped->along_wander){ + return std::nullopt; + } + wild = std::max(wild, stepped->wild); + wander = std::max(wander, stepped->wander); + expansion.leg.after.push_back(stepped->end); + } + } + expansion.cost = (long long)costs.per_leg + costs.leg_not_at_wall + + (long long)(costs.per_tile + costs.per_open_tile) * tiles + + (long long)costs.per_wild_tile * wild + (long long)costs.per_wander_tile * wander; + expansion.leg.direction = direction; + expansion.leg.tiles = (size_t)tiles; + return expansion; +} + +// Joins an open leg with the next one the same way: they are one hold. +template +std::vector> consolidate(const std::vector>& legs){ + std::vector> consolidated; + for (const RobustLeg& leg : legs){ + if (!consolidated.empty() && consolidated.back().direction == leg.direction && !consolidated.back().to_wall){ + consolidated.back().tiles += leg.tiles; + consolidated.back().to_wall = leg.to_wall; + consolidated.back().after = leg.after; + }else{ + consolidated.push_back(leg); + } + } + return consolidated; +} + +// Dijkstra over sets of places the player may stand on. +template +class Search{ +public: + using State = typename Model::State; + using Spread = std::vector; + + Search(const Model& model, const RobustLegCosts& costs) + : m_model(model) + , m_costs(costs) + {} + + std::optional>> run(Spread start, const std::function& goal){ + normalize(start); + m_start = start; + m_nodes[start] = Node{}; + m_queue.emplace(0, start); + size_t searched = 0; + while (!m_queue.empty()){ + const auto [cost, spread] = m_queue.top(); + m_queue.pop(); + Node& node = m_nodes[spread]; + if (node.done || node.cost != cost){ + continue; + } + node.done = true; + if (++searched > m_costs.max_searched){ + return std::nullopt; + } + if (std::all_of(spread.begin(), spread.end(), goal)){ + return consolidate(legs_to(spread)); + } + expand(spread, cost); + } + return std::nullopt; + } + +private: + struct Node{ + long long cost = 0; + Spread parent; + RobustLeg leg; + bool done = false; + }; + using Entry = std::pair; + struct EntryGreater{ + bool operator()(const Entry& a, const Entry& b) const{ + return a.first > b.first; + } + }; + + void expand(const Spread& spread, long long cost){ + for (Direction direction : ALL_DIRECTIONS){ + if (auto wall = to_wall_leg(m_model, spread, direction, m_costs)){ + relax(spread, cost, std::move(*wall)); + } + for (int tiles = 1; tiles <= m_costs.max_open_tiles; tiles++){ + auto open = open_leg(m_model, spread, direction, tiles, m_costs); + if (!open){ + break; + } + relax(spread, cost, std::move(*open)); + } + } + } + + // Only the start may be wider than costs.max_spread: every leg must + // bring the player within it. + void relax(const Spread& spread, long long cost, Expansion expansion){ + Spread& next = expansion.leg.after; + normalize(next); + if (next.size() > m_costs.max_spread || next == spread){ + return; + } + if (spread != m_start){ + const RobustLeg& prev = m_nodes.at(spread).leg; + if (expansion.leg.direction == prev.direction && !prev.to_wall){ + expansion.cost -= m_costs.per_leg; + } + } + const long long total = cost + expansion.cost; + auto iter = m_nodes.find(next); + if (iter != m_nodes.end() && iter->second.cost <= total){ + return; + } + m_nodes[next] = Node{total, spread, expansion.leg}; + m_queue.emplace(total, std::move(next)); + } + + std::vector> legs_to(const Spread& end) const{ + std::vector> legs; + for (Spread at = end; at != m_start; ){ + const Node& step = m_nodes.at(at); + legs.push_back(step.leg); + at = step.parent; + } + std::reverse(legs.begin(), legs.end()); + return legs; + } + + const Model& m_model; + const RobustLegCosts& m_costs; + Spread m_start; + std::map> m_nodes; + std::priority_queue, EntryGreater> m_queue; +}; + +} // namespace RobustLegPlannerInternal + + + +template +std::optional>> plan_robust_legs( + const Model& model, + std::vector from, + const std::function& goal, + const RobustLegCosts& costs +){ + return RobustLegPlannerInternal::Search(model, costs).run(std::move(from), goal); +} + +template +long long robust_legs_cost( + const Model& model, + std::vector from, + const std::vector>& legs, + const RobustLegCosts& costs +){ + using State = typename Model::State; + long long total = 0; + std::vector spread = std::move(from); + RobustLegPlannerInternal::normalize(spread); + const RobustLeg* previous = nullptr; + for (const RobustLeg& leg : legs){ + const auto expansion = leg.to_wall + ? RobustLegPlannerInternal::to_wall_leg(model, spread, leg.direction, costs) + : RobustLegPlannerInternal::open_leg(model, 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.to_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->to_wall){ + cost -= costs.per_leg; + } + total += cost; + spread = leg.after; + RobustLegPlannerInternal::normalize(spread); + previous = ⋚ + } + return total; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp new file mode 100644 index 0000000000..6333649e2c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp @@ -0,0 +1,310 @@ +/* Robust Leg Planner Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The robust planner on a small made-up game: walls hold the player, a + * door stops them without holding them, a ledge hops them south, and open + * legs may end a tile off. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_RobustLegPlanner.h" +#include "Pokemon_RobustLegPlanner_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// '#' wall (and everything outside the rows), '.' floor, '"' tall grass, +// 'w' where someone wanders, 'D' a door: the player is stopped there but +// not held, since walking on enters the building. 'v' a ledge: a step south +// onto it hops to the tile past it and counts 2; it holds the player any +// other way. Rows that wrap join their east end to their west end, so a +// walk along them is never stopped. +class ToyGame{ +public: + using State = TilePos; + using StateLess = std::less; + + ToyGame(const std::vector& rows, bool wraps) + : m_rows(rows.begin(), rows.end()) + , m_wraps(wraps) + {} + + std::optional step(const State& state, Direction direction) const{ + TilePos next = wrapped(state.next(direction)); + const char tile = at(next); + if (tile == 'v' && direction == Direction::SOUTH){ + next = next.next(Direction::SOUTH); + return at(next) == '#' ? std::nullopt : std::optional(next); + } + if (tile == '#' || tile == 'D' || tile == 'v'){ + return std::nullopt; + } + return next; + } + size_t step_tiles(const State& from, const State& to) const{ + return to.y - from.y == 2 ? 2 : 1; + } + bool held_at(const State& state, Direction direction) const{ + return at(wrapped(state.next(direction))) != 'D'; + } + bool wild(const State& state) const{ + return at(state) == '"'; + } + bool wander(const State& state) const{ + return at(state) == 'w'; + } + +private: + TilePos wrapped(TilePos pos) const{ + if (m_wraps && pos.y >= 0 && pos.y < (int)m_rows.size()){ + const int width = (int)m_rows[pos.y].size(); + pos.x = (pos.x % width + width) % width; + } + return pos; + } + char at(const TilePos& pos) const{ + if (pos.y < 0 || pos.y >= (int)m_rows.size() || pos.x < 0 || pos.x >= (int)m_rows[pos.y].size()){ + return '#'; + } + return m_rows[pos.y][pos.x]; + } + + std::vector m_rows; + bool m_wraps = false; +}; + +using Legs = std::vector>; + +// Legs as "east 2 to wall: (2, 0); south 1 open: (2, 1) (2, 2)", or "none". +std::string describe(const std::optional& legs){ + if (!legs){ + return "none"; + } + std::string text; + for (const RobustLeg& leg : *legs){ + text += std::format("{}{} {} {}:", text.empty() ? "" : "; ", direction_name(leg.direction), leg.tiles, leg.to_wall ? "to wall" : "open"); + for (const TilePos& pos : leg.after){ + text += " " + to_string(pos); + } + } + return text; +} + +constexpr RobustLegCosts EXACT{.exact_open_tiles = 12}; + + +struct PlanInput{ + std::string_view name; + std::vector rows; + bool wraps = false; + std::vector from; + TilePos goal; + RobustLegCosts costs; +}; +struct PlanExpectation{ + std::string_view legs; // as describe() writes them +}; +struct PlanCase{ + PlanInput input; + PlanExpectation expectation; +}; + +class Test_RobustLegPlanner_Plan : public UnitTest{ +public: + explicit Test_RobustLegPlanner_Plan(PlanCase scenario) + : UnitTest(std::format("Pokemon::RobustLegPlanner - {}", scenario.input.name)) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const PlanInput& input = m_scenario.input; + const ToyGame game(input.rows, input.wraps); + const TilePos goal = input.goal; + const std::optional legs = plan_robust_legs(game, input.from, + std::function([goal](const TilePos& pos){ return pos == goal; }), input.costs); + const std::string actual = describe(legs); + if (actual != m_scenario.expectation.legs){ + return std::format("Planned \"{}\", expected \"{}\".", actual, m_scenario.expectation.legs); + } + return true; + } +private: + PlanCase m_scenario; +}; + +// Open legs on default costs may end a tile either way (two up to 5 tiles). +const PlanCase PLAN_CASES[] = { + { + .input = {.name = "a wall gathers the possible tiles", .rows = {"...#"}, .from = {{0, 0}, {1, 0}}, .goal = {2, 0}}, + .expectation = {.legs = "east 2 to wall: (2, 0)"}, + }, + { + .input = {.name = "no plan ends in the open while open legs may be off", .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}}, + .expectation = {.legs = "none"}, + }, + { + .input = {.name = "an exact open leg ends in the open", .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}, .costs = EXACT}, + .expectation = {.legs = "east 3 open: (3, 0)"}, + }, + { + .input = { + .name = "open_error_per 0 with no open_error is exact", .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}, + .costs = {.open_error = 0, .open_error_per = 0}, + }, + .expectation = {.legs = "east 3 open: (3, 0)"}, + }, + { + .input = { + .name = "open_error_per 0 keeps open_error", .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}, + .costs = {.open_error = 1, .open_error_per = 0}, + }, + .expectation = {.legs = "none"}, + }, + { + .input = {.name = "a door is not a wall", .rows = {"#..D"}, .from = {{1, 0}}, .goal = {2, 0}, .costs = EXACT}, + .expectation = {.legs = "east 1 open: (2, 0)"}, + }, + { + .input = {.name = "no leg along a wander zone", .rows = {".www.", "....."}, .from = {{1, 0}}, .goal = {4, 0}, .costs = EXACT}, + .expectation = {.legs = "south 1 to wall: (1, 1); east 3 to wall: (4, 1); north 1 to wall: (4, 0)"}, + }, + { + .input = {.name = "a ledge hop counts 2 tiles", .rows = {".", "v", "."}, .from = {{0, 0}}, .goal = {0, 2}}, + .expectation = {.legs = "south 2 to wall: (0, 2)"}, + }, + { + .input = {.name = "a ledge cannot be climbed", .rows = {".", "v", "."}, .from = {{0, 2}}, .goal = {0, 0}}, + .expectation = {.legs = "none"}, + }, + { + .input = {.name = "tall grass costs less than a detour", .rows = {".\"\"..", "....."}, .from = {{0, 0}}, .goal = {4, 0}}, + .expectation = {.legs = "east 4 to wall: (4, 0)"}, + }, + { + .input = { + .name = "costly tall grass is walked round", .rows = {".\"\"..", "....."}, .from = {{0, 0}}, .goal = {4, 0}, + .costs = {.per_wild_tile = 20}, + }, + .expectation = {.legs = "south 1 to wall: (0, 1); east 4 to wall: (4, 1); north 1 to wall: (4, 0)"}, + }, + { + // Only an open leg reaches the second row; a wall then gathers. + .input = {.name = "an open leg spreads, a wall gathers", .rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}}, + .expectation = {.legs = "east 1 open: (1, 0) (2, 0); south 1 to wall: (1, 1) (2, 1); east 2 to wall: (3, 1)"}, + }, + { + .input = { + .name = "a spread wider than max_spread is not planned", .rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, + .costs = {.max_spread = 1}, + }, + .expectation = {.legs = "none"}, + }, + { + .input = { + .name = "the search gives up past max_searched", .rows = {".....", "#...#"}, .from = {{0, 0}}, .goal = {3, 1}, + .costs = {.max_searched = 1}, + }, + .expectation = {.legs = "none"}, + }, + { + .input = { + .name = "two open legs the same way are one", .rows = {"........"}, .from = {{0, 0}}, .goal = {3, 0}, + .costs = {.exact_open_tiles = 12, .max_open_tiles = 2}, + }, + .expectation = {.legs = "east 3 open: (3, 0)"}, + }, + { + .input = {.name = "a walk that is never stopped is not a wall", .rows = {"...."}, .wraps = true, .from = {{0, 0}}, .goal = {2, 0}, .costs = EXACT}, + .expectation = {.legs = "east 2 open: (2, 0)"}, + }, +}; + + +struct CostInput{ + std::string_view name; + std::vector rows; + TilePos from; + Legs legs; + RobustLegCosts costs; +}; +struct CostExpectation{ + long long cost = 0; +}; +struct CostCase{ + CostInput input; + CostExpectation expectation; +}; + +class Test_RobustLegPlanner_Cost : public UnitTest{ +public: + explicit Test_RobustLegPlanner_Cost(CostCase scenario) + : UnitTest(std::format("Pokemon::RobustLegPlanner - {}", scenario.input.name)) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const CostInput& input = m_scenario.input; + const ToyGame game(input.rows, false); + const long long actual = robust_legs_cost(game, {input.from}, input.legs, input.costs); + if (actual != m_scenario.expectation.cost){ + return std::format("Cost {} for \"{}\", expected {}.", actual, describe(input.legs), m_scenario.expectation.cost); + } + return true; + } +private: + CostCase m_scenario; +}; + +// Default costs: 8 a leg, 1 a tile, 4 more a grass tile, 50 more for a +// leg that stops in the open. +const CostCase COST_CASES[] = { + { + .input = {.name = "a wall leg costs a leg and its tiles", .rows = {"...#"}, .from = {0, 0}, .legs = {{Direction::EAST, 2, true, {{2, 0}}}}}, + .expectation = {.cost = 8 + 2}, + }, + { + .input = { + .name = "an open leg costs its stop and open tiles on top", .rows = {"...#"}, .from = {0, 0}, + .legs = {{Direction::EAST, 1, false, {{1, 0}}}}, .costs = {.exact_open_tiles = 12, .per_open_tile = 2}, + }, + .expectation = {.cost = 8 + 50 + 3}, + }, + { + .input = {.name = "each grass tile entered costs extra", .rows = {".\"\"#"}, .from = {0, 0}, .legs = {{Direction::EAST, 2, true, {{2, 0}}}}}, + .expectation = {.cost = 8 + 2 + 2 * 4}, + }, + { + .input = { + .name = "a cost with open_error_per 0", .rows = {"........"}, .from = {0, 0}, + .legs = {{Direction::EAST, 3, false, {{3, 0}}}}, .costs = {.open_error_per = 0}, + }, + .expectation = {.cost = 8 + 50 + 3}, + }, +}; + +} // namespace + + +void add_tests_RobustLegPlanner(UnitTestDatabase& database){ + for (const PlanCase& scenario : PLAN_CASES){ + database.add(scenario); + } + for (const CostCase& scenario : COST_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.h new file mode 100644 index 0000000000..fec9e8a2e0 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.h @@ -0,0 +1,23 @@ +/* Robust Leg Planner Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_RobustLegPlanner_Tests_H +#define PokemonAutomation_Pokemon_RobustLegPlanner_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers robust leg planner unit tests. +void add_tests_RobustLegPlanner(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp index a89679cf16..e6ff4357e8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp @@ -7,10 +7,9 @@ #include #include #include -#include -#include #include "Common/Cpp/Exceptions.h" #include "Pokemon/Navigation/Pokemon_LegPlanner.h" +#include "Pokemon/Navigation/Pokemon_RobustLegPlanner.h" #include "PokemonBDSP_AutoStory_RobustRoute.h" #include "PokemonBDSP_AutoStory_RoutePlanner.h" #include "PokemonBDSP_AutoStory_TrainerSight.h" @@ -217,237 +216,74 @@ std::string to_string(const PlannedLeg& leg){ namespace{ -// Where `from` ends up after `tiles` steps in `direction`, stopping early at -// anything that stops the player, and how many tall-grass tiles it enters. -// Nothing if a step would leave the maps or enter a door: the plan cannot -// tell what happens then. -struct Stepped{ - TilePos end; - int grass = 0; - 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){ - if (!at_wall(world, from, direction)){ - return std::nullopt; - } - break; - } - travelled += (int)distance(*next, from); - if (tall_grass(world, *next)){ - stepped.grass++; - } - 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; - return stepped; -} - -using Spread = std::vector; - -bool spread_less(const TilePos& a, const TilePos& b){ - return a.y != b.y ? a.y < b.y : a.x < b.x; -} -void normalize(Spread& spread){ - std::sort(spread.begin(), spread.end(), spread_less); - spread.erase(std::unique(spread.begin(), spread.end()), spread.end()); -} -struct SpreadLess{ - bool operator()(const Spread& a, const Spread& b) const{ - return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), spread_less); - } -}; - -// A leg out of a spread: where every tile of it ends, and its cost. -struct Expansion{ - long long cost = 0; - Spread next; - TileLeg leg; -}; - -// To the wall: every position walks until stopped. Nothing unless each is -// held at a wall, and one moves. -std::optional to_wall_leg(const StoryWorld& world, const Spread& spread, Direction direction, const RobustPlanCosts& costs){ - Expansion expansion; - size_t longest = 0; - int grass = 0; - int wander = 0; - for (const TilePos& pos : spread){ - const WallHit hit = slide_to_wall(world, pos, direction); - if (!hit.anchored){ - 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); - } - longest = std::max(longest, hit.tiles); - expansion.next.push_back(hit.stop); - } - if (longest == 0){ - return std::nullopt; - } - expansion.cost = (long long)costs.per_leg + (long long)costs.per_tile * longest - + (long long)costs.per_grass_tile * grass + (long long)costs.per_wander_tile * wander; - expansion.leg = TileLeg{direction, longest, true}; - return expansion; -} - -// Open: about `tiles` tiles, give or take the error. Nothing if any -// possible end leaves the maps or enters a door. -std::optional open_leg(const StoryWorld& world, const Spread& spread, Direction direction, int tiles, const RobustPlanCosts& costs){ - Expansion expansion; - int grass = 0; - int wander = 0; - const int error = tiles <= costs.exact_open_tiles ? 0 : costs.open_error + tiles / costs.open_error_per; - for (const TilePos& pos : spread){ - for (int n = std::max(1, tiles - error); n <= tiles + error; n++){ - const std::optional stepped = step_tiles(world, pos, direction, n); - if (!stepped || stepped->along_wander){ - return std::nullopt; - } - grass = std::max(grass, stepped->grass); - wander = std::max(wander, stepped->wander); - expansion.next.push_back(stepped->end); +// The world's step rules for the shared robust planner. A ledge hop is one +// step that counts two tiles. +class RobustWorldModel{ +public: + using State = TilePos; + struct StateLess{ + bool operator()(const TilePos& a, const TilePos& b) const{ + return a.y != b.y ? a.y < b.y : a.x < b.x; } - } - expansion.cost = (long long)costs.per_leg + costs.leg_not_at_wall + - (long long)(costs.per_tile + costs.per_open_tile) * tiles - + (long long)costs.per_grass_tile * grass + (long long)costs.per_wander_tile * wander; - expansion.leg = TileLeg{direction, (size_t)tiles, false}; - return expansion; -} + }; -// Dijkstra over sets of tiles the player may stand on. -class RobustSearch{ -public: - RobustSearch(const StoryWorld& world, const RobustPlanCosts& costs) + explicit RobustWorldModel(const StoryWorld& world) : m_world(world) - , m_costs(costs) {} - std::optional> run(Spread start, const std::function& goal){ - normalize(start); - m_start = start; - m_nodes[start] = Node{0, {}, {}}; - m_queue.emplace(0, start); - size_t searched = 0; - while (!m_queue.empty()){ - const auto [cost, spread] = m_queue.top(); - m_queue.pop(); - Node& node = m_nodes[spread]; - if (node.done || node.cost != cost){ - continue; - } - node.done = true; - if (++searched > m_costs.max_searched){ - return std::nullopt; - } - if (std::all_of(spread.begin(), spread.end(), goal)){ - return legs_to(spread); - } - expand(spread, cost); - } - return std::nullopt; + std::optional step(const State& pos, Direction direction) const{ + return PokemonBDSP::step(m_world, pos, direction); } - -private: - struct Node{ - long long cost = 0; - Spread parent; - PlannedLeg leg; - bool done = false; - }; - using Entry = std::pair; - struct EntryGreater{ - bool operator()(const Entry& a, const Entry& b) const{ return a.first > b.first; } - }; - - void expand(const Spread& spread, long long cost){ - for (Direction direction : Pokemon::ALL_DIRECTIONS){ - if (std::optional wall = to_wall_leg(m_world, spread, direction, m_costs)){ - relax(spread, cost, std::move(*wall)); - } - for (int tiles = 1; tiles <= m_costs.max_open_tiles; tiles++){ - std::optional open = open_leg(m_world, spread, direction, tiles, m_costs); - if (!open){ - break; - } - relax(spread, cost, std::move(*open)); - } - } + size_t step_tiles(const State& from, const State& to) const{ + return distance(from, to); } - - // Only the start may be wider than costs.max_spread: every leg must - // bring the player within it. - void relax(const Spread& spread, long long cost, Expansion expansion){ - normalize(expansion.next); - if (expansion.next.size() > m_costs.max_spread || expansion.next == spread){ - return; - } - if (spread != m_start){ - const TileLeg& prev = m_nodes.at(spread).leg.leg; - if (expansion.leg.direction == prev.direction && !prev.ends_at_wall){ - expansion.cost -= m_costs.per_leg; - } - } - const long long total = cost + expansion.cost; - auto iter = m_nodes.find(expansion.next); - if (iter != m_nodes.end() && iter->second.cost <= total){ - return; - } - m_nodes[expansion.next] = Node{total, spread, PlannedLeg{expansion.leg, expansion.next}}; - m_queue.emplace(total, std::move(expansion.next)); + bool held_at(const State& pos, Direction direction) const{ + return at_wall(m_world, pos, direction); } - - std::vector legs_to(const Spread& end) const{ - std::vector legs; - for (Spread at = end; at != m_start; ){ - const Node& step = m_nodes.at(at); - legs.push_back(step.leg); - at = step.parent; - } - std::reverse(legs.begin(), legs.end()); - std::vector consolidated; - for (const PlannedLeg& planned : legs){ - if (!consolidated.empty() && - consolidated.back().leg.direction == planned.leg.direction && - !consolidated.back().leg.ends_at_wall - ){ - consolidated.back().leg.tiles += planned.leg.tiles; - consolidated.back().leg.ends_at_wall = planned.leg.ends_at_wall; - consolidated.back().after = planned.after; - }else{ - consolidated.push_back(planned); - } - } - return consolidated; + bool wild(const State& pos) const{ + return tall_grass(m_world, pos); + } + bool wander(const State& pos) const{ + return wandering_hazard(m_world, pos); } +private: const StoryWorld& m_world; - const RobustPlanCosts& m_costs; - Spread m_start; - std::map m_nodes; - std::priority_queue, EntryGreater> m_queue; }; +// Names every field of Pokemon::RobustLegCosts, in order, so it stops +// compiling when the shared costs gain or lose one: add the new field to +// robust_leg_costs() below (and to RobustPlanCosts if BDSP sets it), so it +// can't silently keep the shared default. +constexpr bool robust_leg_costs_fields_copied(){ + [[maybe_unused]] const auto& [ + per_tile, per_wild_tile, per_wander_tile, per_leg, leg_not_at_wall, + open_error, open_error_per, exact_open_tiles, per_open_tile, + max_open_tiles, max_spread, max_searched + ] = Pokemon::RobustLegCosts{}; + return true; +} +static_assert(robust_leg_costs_fields_copied()); + +// BDSP's costs as the shared planner's, field by field. per_wander_tile is +// BDSP's own (town_plan_costs() may raise it), never the shared default. +Pokemon::RobustLegCosts robust_leg_costs(const RobustPlanCosts& costs){ + Pokemon::RobustLegCosts ret; + ret.per_tile = costs.per_tile; + ret.per_wild_tile = costs.per_grass_tile; + ret.per_wander_tile = costs.per_wander_tile; + ret.per_leg = costs.per_leg; + ret.leg_not_at_wall = costs.leg_not_at_wall; + ret.open_error = costs.open_error; + ret.open_error_per = costs.open_error_per; + ret.exact_open_tiles = costs.exact_open_tiles; + ret.per_open_tile = costs.per_open_tile; + ret.max_open_tiles = costs.max_open_tiles; + ret.max_spread = costs.max_spread; + ret.max_searched = costs.max_searched; + return ret; +} + } // namespace std::optional> plan_robust_route( @@ -469,7 +305,15 @@ std::optional> plan_robust_route( throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Route starts must be standable: " + Pokemon::to_string(pos) + "."); } } - return RobustSearch(world, costs).run(from, goal); + const auto legs = Pokemon::plan_robust_legs(RobustWorldModel(world), from, goal, robust_leg_costs(costs)); + if (!legs){ + return std::nullopt; + } + std::vector ret; + for (const Pokemon::RobustLeg& leg : *legs){ + ret.push_back(PlannedLeg{TileLeg{leg.direction, leg.tiles, leg.to_wall}, leg.after}); + } + return ret; } long long robust_route_cost( @@ -477,31 +321,11 @@ long long robust_route_cost( const std::vector& from, const std::vector& legs, const RobustPlanCosts& costs ){ - long long total = 0; - Spread spread = from; - normalize(spread); - const TileLeg* previous = nullptr; + std::vector> robust; 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 = ⋚ + robust.push_back(Pokemon::RobustLeg{planned.leg.direction, planned.leg.tiles, planned.leg.ends_at_wall, planned.after}); } - return total; + return Pokemon::robust_legs_cost(RobustWorldModel(world), from, robust, robust_leg_costs(costs)); } diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 3c73bdeefa..cafbb18a51 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1484,6 +1484,9 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_LegPlanner.h Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.h + Source/Pokemon/Navigation/Pokemon_RobustLegPlanner.h + Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.cpp + Source/Pokemon/Navigation/Pokemon_RobustLegPlanner_Tests.h Source/Pokemon/Navigation/Pokemon_LegWalker.cpp Source/Pokemon/Navigation/Pokemon_LegWalker.h Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp