diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleTextBoxDetector.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleTextBoxDetector.cpp new file mode 100644 index 0000000000..6e066afdc9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleTextBoxDetector.cpp @@ -0,0 +1,90 @@ +/* Battle Text Box Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Images/SolidColorTest.h" +#include "Tests/ImageUnitTest.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" +#include "PokemonFRLG_BattleTextBoxDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +// Measured on the console's captures (1920x1080): blue (34, 88, 121), +// white (236, 229, 235), gold (222, 176, 52). +const FloatPixel BOX_BLUE{0.176, 0.357, 0.467}; +const FloatPixel FRAME_GOLD{0.493, 0.391, 0.116}; + +} + + +BattleTextBoxDetector::BattleTextBoxDetector(Color color) + : m_color(color) + // As BattleDialogDetector's. + , m_blue_top(0.0372308, 0.750154, 0.925538, 0.00934615) + , m_blue_right(0.956615, 0.7595, 0.00615385, 0.185885) + , m_white_line(0.0385, 0.7337, 0.923, 0.0058) + , m_gold_band(0.0385, 0.7163, 0.923, 0.0087) +{} + +void BattleTextBoxDetector::make_overlays(VideoOverlaySet& items) const{ + const BoxOption& GAME_BOX = GameSettings::instance().GAME_BOX; + items.add(m_color, GAME_BOX.inner_to_outer(m_blue_top)); + items.add(m_color, GAME_BOX.inner_to_outer(m_blue_right)); + items.add(m_color, GAME_BOX.inner_to_outer(m_white_line)); + items.add(m_color, GAME_BOX.inner_to_outer(m_gold_band)); +} + +bool BattleTextBoxDetector::detect(const ImageViewRGB32& screen){ + const ImageViewRGB32 game_screen = extract_box_reference(screen, GameSettings::instance().GAME_BOX); + return is_solid(extract_box_reference(game_screen, m_blue_top), BOX_BLUE, 0.25, 20) + && is_solid(extract_box_reference(game_screen, m_blue_right), BOX_BLUE, 0.25, 20) + && is_white(extract_box_reference(game_screen, m_white_line), 500, 20) + && is_solid(extract_box_reference(game_screen, m_gold_band), FRAME_GOLD, 0.10, 40); +} + + + +class Test_BattleTextBoxDetector : public ImageUnitTest{ +public: + Test_BattleTextBoxDetector(const std::string& image, bool expected) + : ImageUnitTest("PokemonFRLG::BattleTextBoxDetector - " + image, {image}) + , m_expected(expected) + {} + + virtual UnitTestResult run_on_images( + Logger& logger, CancellableScope& scope, + const std::vector& images + ) const override{ + BattleTextBoxDetector detector(COLOR_RED); + return detector.detect(images[0]) == m_expected; + } + +private: + bool m_expected; +}; + +void add_tests_BattleTextBoxDetector(UnitTestDatabase& database){ + // Console B's captures: Mt. Moon B1F and Route 1, a battle's opening + // with the box still empty, after a leg's watch saw nothing; Viridian + // Forest, "Wild CATERPIE" with its HP box. + database.add("PokemonFRLG/BattleTextBoxDetector/MtMoonB1F_Opening_True.png", true); + database.add("PokemonFRLG/BattleTextBoxDetector/Route1_Opening_True.png", true); + database.add("PokemonFRLG/BattleTextBoxDetector/ViridianForest_WildCaterpie_True.png", true); + // The cave just before that battle, and black below Pewter's Pokemon + // Center, which BattleDialogDetector reads as the box. + database.add("PokemonFRLG/BattleTextBoxDetector/MtMoonB1F_Overworld_False.png", false); + database.add("PokemonFRLG/BattleTextBoxDetector/PewterPokemonCenter_BlackBelow_False.png", false); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleTextBoxDetector.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleTextBoxDetector.h new file mode 100644 index 0000000000..be72b867ea --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleTextBoxDetector.h @@ -0,0 +1,55 @@ +/* Battle Text Box Detector + * + * From: https://github.com/PokemonAutomation/ + * + * A battle's text box, by its frame: blue inside a white line and a gold + * band. It shows from the moment a battle's opening ends, before the HP + * boxes and the "Wild appeared!" that BattleScreenDetector needs: + * in Mt. Moon the HP boxes came over 5s after the step that set the battle + * off (console B, 2026-11-03). Black below a small room, which passes for + * the box's blue (BattleDialogDetector), has neither line. + * + * English layout only: the Japanese box sits a little lower and narrower + * (BattleDialogDetector) and wasn't checked. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_BattleTextBoxDetector_H +#define PokemonAutomation_PokemonFRLG_BattleTextBoxDetector_H + +#include "Common/Cpp/Color.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +class BattleTextBoxDetector : public StaticScreenDetector{ +public: + BattleTextBoxDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_blue_top; + ImageFloatBox m_blue_right; + ImageFloatBox m_white_line; + ImageFloatBox m_gold_band; +}; + + +void add_tests_BattleTextBoxDetector(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp index 1a907f7a06..c91375a8a6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp @@ -58,6 +58,46 @@ int sight_onto(const std::vector& maps, const MapPosition& tile){ return sight; } +// The tiles an open `step` from `start` may have ended on with nothing +// seen: its end, and up to OPEN_LEG_SHORTFALL tiles before it. +std::vector short_candidates(const std::vector& maps, const MapPosition& start, const RouteStep& step){ + const std::vector tiles = leg_tiles(maps, start, step); + std::vector candidates; + for (size_t c = 0; c <= (size_t)OPEN_LEG_SHORTFALL && c < tiles.size(); c++){ + candidates.push_back(StopCandidate{tiles[tiles.size() - 1 - c], std::nullopt}); + } + return candidates; +} + +// Whether `next` is a hold to a wall. +bool is_wall_hold(const RouteStep& next){ + return next.action == RouteAction::WALK && next.to_wall && !next.warps; +} + +// Whether `next`, a hold to a wall, ends on its planned tile from each of +// `candidates`: then it finds the player itself. +bool hold_finds(const std::vector& maps, const std::vector& candidates, const RouteStep& next){ + for (const StopCandidate& candidate : candidates){ + const std::optional hold = hold_to_wall(maps, candidate.player, false, next.direction); + if (!hold || !(hold->end == next.end)){ + return false; + } + } + return true; +} + +// How many tiles `anchor`'s holds and way back walk, as far as planned. +int anchor_tiles(const Reanchor& anchor){ + int tiles = 0; + for (const RouteStep& step : anchor.holds){ + tiles += step.tiles; + } + for (const RouteStep& step : anchor.back){ + tiles += step.tiles; + } + return tiles; +} + // The route's lines in the route log the games share, as BDSP's walker // writes them, under the caller's label. class RouteLogLines{ @@ -118,6 +158,9 @@ class CheckedSteps{ const std::string leg = to_string(step); m_reholds = m_last_late && leg == m_last ? m_reholds + 1 : 0; StepOutcome outcome = m_calls.walk(step, facing); + if (outcome.end == StepEnd::BATTLE_BEFORE){ + return outcome; + } if (outcome.end == StepEnd::DONE && crossing && m_calls.watch_for_trainer){ outcome = StepOutcome{.end = m_calls.watch_for_trainer(step, crossing->approach_tiles), .walked = std::nullopt}; } @@ -182,9 +225,12 @@ class RouteRun{ const std::optional crossing = m_next >= m_holds ? crossing_here(step) : std::nullopt; const StepOutcome outcome = m_steps.walk(step, m_facing, crossing); if (outcome.end == StepEnd::DONE){ + const std::optional start = m_next >= m_unchecked ? m_at : std::nullopt; + remember_walked(step); m_at = step.end; m_facing = step.facing_after; m_lines.done(step, ++m_next, m_holds); + check_open_leg(step, start); continue; } const std::optional start = m_next >= m_holds ? m_at : std::nullopt; @@ -193,6 +239,13 @@ class RouteRun{ m_calls.fail(std::format("walk_overworld_route(): stopped part-way {} times.", m_stops)); return; } + if (outcome.end == StepEnd::BATTLE_BEFORE){ + if (!after_battle_before(step)){ + return; + } + continue; + } + m_walked.reset(); if (!after_stop(step, outcome, start, crossing)){ return; } @@ -211,6 +264,44 @@ class RouteRun{ return trainer_crossing(*maps(), *m_at, step); } + // A walk the next step's battle check may find stopped part-way: + // where in the plan it is, and where it started from, if known. + struct Walked{ + RouteStep step; + size_t index = 0; + std::optional start; + }; + + // `step`, m_plan[m_next], walked to its end. Only a walk not onto a + // warp can have stopped part-way unseen. + void remember_walked(const RouteStep& step){ + m_walked.reset(); + if (step.action == RouteAction::WALK && !step.warps){ + m_walked = Walked{step, m_next, m_next >= m_holds ? m_at : std::nullopt}; + } + } + + // A wild battle set off before `step`, m_plan[m_next], showed before + // it started. The step walked before it may have been stopped by the + // battle anywhere: the player is found again on it, as after a battle + // seen after its hold, and never taken to be on `step`'s line (the + // next leg was held from where the battle left the player, and the + // route went on 6 tiles off: console B, 2026-11-03, Mt. Moon B2F). + // With nothing walked since the plan was made, the player is where + // `step` starts. False once the route has failed. + bool after_battle_before(const RouteStep& step){ + if (!m_walked){ + m_calls.log("Route: a wild battle before " + to_string(step) + ", with nothing walked since the plan: walking it from its start."); + return true; + } + const Walked walked = std::move(*m_walked); + m_walked.reset(); + m_calls.log("Route: a wild battle before " + to_string(step) + " was set off on " + to_string(walked.step) + ", which may have stopped part-way."); + m_next = walked.index; + m_at = walked.start; + return after_stop(walked.step, StepOutcome{.end = StepEnd::LATE, .walked = std::nullopt}, walked.start, std::nullopt); + } + // After a stop on `step`, from `start` if known. False once the route // has failed. bool after_stop( @@ -262,6 +353,56 @@ class RouteRun{ return true; } + // After `step`, an open leg from `start` (not known: not checked) that + // ended with nothing seen, while m_plan[m_next] is the step after it. + // A hold to a wall after a leg that ended short ends somewhere else + // with nothing to show it (r16), unless it ends on its tile from + // wherever the leg left the player. If it doesn't, finds the player at + // walls first; without such holds, or if they and the way back walk + // farther than the leg there and back, trusts the leg. Only there, and + // only that far, to keep the check cheap: in Viridian Forest (r16) it + // walks 10 tiles after "west 6", while after Route 1's "west 4" the + // only holds walk 30. An open leg after a short one walks on off the + // route, which isn't checked. + void check_open_leg(const RouteStep& step, const std::optional& start){ + if (maps() == nullptr || m_planning->open_leg_check != OpenLegCheck::REANCHOR || !start + || step.action != RouteAction::WALK || step.to_wall || step.warps + || m_next >= m_plan.size() || !is_wall_hold(m_plan[m_next]) + ){ + return; + } + const std::vector candidates = short_candidates(*maps(), *start, step); + if (candidates.size() < 2 || hold_finds(*maps(), candidates, m_plan[m_next])){ + return; + } + const std::optional anchor = plan_reanchor(*maps(), candidates, step, m_planning->costs); + if (!anchor || anchor->holds.empty() || anchor_tiles(*anchor) > 2 * step.tiles){ + m_calls.log("Route: no holds to walls within " + std::to_string(2 * step.tiles) + " tiles find the player if " + to_string(step) + " ended short; taken as walked."); + return; + } + m_calls.log(std::format( + "Route: position check: {} may have ended up to {} tiles short with nothing seen; finding the player at walls.", + to_string(step), OPEN_LEG_SHORTFALL + )); + replan(*anchor, m_next); + m_at = std::nullopt; + m_lines.plan(std::nullopt, m_plan); + } + + // The plan from here: `anchor`'s holds and way back, then the old + // plan's steps from `rest` on. Neither the holds nor the way back are + // checked as open legs again. + void replan(const Reanchor& anchor, size_t rest){ + std::vector plan = anchor.holds; + plan.insert(plan.end(), anchor.back.begin(), anchor.back.end()); + plan.insert(plan.end(), m_plan.begin() + rest, m_plan.end()); + m_plan = std::move(plan); + m_walked.reset(); + m_holds = anchor.holds.size(); + m_unchecked = m_holds + anchor.back.size(); + m_next = 0; + } + // Finds the player on one of `candidates`, plans the way back to the // end of `step` (m_plan[m_next]), and the rest of the route after it. bool rejoin(const RouteStep& step, const std::vector& candidates, WalkedTiles walked){ @@ -283,12 +424,7 @@ class RouteRun{ ); return false; } - std::vector plan = anchor->holds; - plan.insert(plan.end(), anchor->back.begin(), anchor->back.end()); - plan.insert(plan.end(), m_plan.begin() + m_next + 1, m_plan.end()); - m_plan = std::move(plan); - m_holds = anchor->holds.size(); - m_next = 0; + replan(*anchor, m_next + 1); if (m_holds > 0){ m_at = std::nullopt; m_lines.plan(std::nullopt, m_plan); @@ -318,11 +454,17 @@ class RouteRun{ size_t m_next = 0; size_t m_stops = 0; size_t m_holds = 0; // of the plan, holds to walls that find the player + size_t m_unchecked = 0; // of the plan, the holds and the way back after them + std::optional m_walked; // the step walked last, if it may have stopped part-way }; } +WalkedTiles walked_before_warp(const RouteStep& step){ + return WalkedTiles{.min = 1, .max = step.tiles - 1}; +} + std::optional trainer_crossing( const std::vector& maps, const MapPosition& start, const RouteStep& step ){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h index 3e15603f4d..475b2bc69a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h @@ -17,7 +17,14 @@ * the route is planned again from it. More: holds to walls that end on * one tile from all of them find the player (plan_reanchor()), and a * way back to the stopped leg's end rejoins the route. The rest of the - * route is then walked as planned. + * route is then walked as planned. A leg onto a warp whose fade was + * a wild battle's counts as stopped before its warp + * (walked_before_warp()), and the way back goes on through the warp; + * - an open leg that ended with nothing seen may still have ended up to + * OPEN_LEG_SHORTFALL tiles short. When the next step is a hold to a + * wall that doesn't end on its tile from each of those, the player is + * found at walls the same way and walked back to the leg's end first. + * When no holds find them, the leg is taken as walked, as before. * * Where the player is is never guessed: when no holds find them from every * tile they may be on, the route fails, and the caller stops without @@ -49,6 +56,10 @@ enum class StepEnd{ STOPPED, // stopped part-way: where the player is isn't known LATE, // something was seen after the hold, which may have // stopped the player before the end + // Not walked: a wild battle set off before the step showed before it + // started. The step before it may have stopped part-way: its + // battle was seen too late (console B, 2026-11-03, Mt. Moon B2F). + BATTLE_BEFORE, }; // How a step ended, and for an open leg STOPPED part-way, how many of its @@ -66,6 +77,25 @@ enum class WallCheck{ SKIP, }; +// The most tiles an open leg has been seen to end short with nothing on +// screen: "west 6" in Viridian Forest ended 2 short (r16, console B, +// 2026-11-01); on Route 1 a column was lost (cp0006-b). The cause isn't +// known (the forest drift), so this is what was seen, not a bound. +constexpr int OPEN_LEG_SHORTFALL = 2; + +// Where a leg onto a warp stopped when its fade was a wild battle's: the +// battle's wipe passes for the fade (console B, 2026-11-03, Mt. Moon 1F), +// so the stop isn't timed. The battle started on one of the leg's steps +// before the warp. The walker reports the leg STOPPED there. +WalkedTiles walked_before_warp(const RouteStep& step); + +// Whether, after an open leg that ended with nothing seen, the player is +// found again at walls when where they stand matters (see run_route()). +enum class OpenLegCheck{ + REANCHOR, + TRUST, // taken to have ended where planned +}; + // What the route was planned with, to plan the way back onto it: the maps // (with the event flags the caller set) and the costs; and, for the route // log (Pokemon_RouteLog.h), where it starts and what the caller calls it. @@ -75,6 +105,7 @@ struct RoutePlanning{ std::optional start; std::string label = "Route"; WallCheck wall_check = WallCheck::TAP; + OpenLegCheck open_leg_check = OpenLegCheck::REANCHOR; }; // The console side. `walk` walks one step from `facing` (unknown after a diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp index 9100f08d3f..4dba0fbe26 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp @@ -68,7 +68,10 @@ std::optional walk_step( if (step.warps){ wait_out_warp(console, context, step); static_assert(AFTER_WARP_BATTLE_WATCH >= AFTER_WARP); - check_warp_was_no_battle(console, context, step); + if (run_from_battle_after_warp(console, context)){ + console.log("Route: a wild battle, not the warp to " + step.end.map + "; the player is on " + to_string(step) + " before the warp.", COLOR_ORANGE); + return walked_before_warp(step); + } } break; } @@ -85,12 +88,21 @@ std::optional walk_step( // walk_step(), then a watch for what its last step set off. Not DONE if // the player may have stopped short of the step's end: an open leg // stopped, or something seen after the hold, which may have stopped it -// before the end (after a warp, it was checked for already). +// before the end (after a warp, it was checked for already). A battle +// on its way that the watch missed counts as seen (clear_unseen_battle()), +// also after a leg the maps see no wild tiles on. One on its way before +// the step starts was set off before it: the step isn't walked, and is +// BATTLE_BEFORE (clear_battle_before()). StepOutcome walk_and_watch( ConsoleHandle& console, ProControllerContext& context, const RouteStep& step, std::optional facing, const OverworldInterruptSet& interrupts, MoveSpeed speed ){ + if (clear_battle_before(console, context, interrupts.wild, step) > 0){ + return StepOutcome{.end = StepEnd::BATTLE_BEFORE, .walked = std::nullopt}; + } + clear_open_message(console, context, step.wild ? interrupts.wild : interrupts.other, step); + check_overworld(console, context, step); if (const std::optional walked = walk_step(console, context, step, facing, interrupts, speed)){ return StepOutcome{.end = StepEnd::STOPPED, .walked = walked}; } @@ -98,7 +110,11 @@ StepOutcome walk_and_watch( return StepOutcome{}; } const Milliseconds watch = step.wild ? AFTER_WILD_LEG_WATCH : AFTER_LEG_WATCH; - const size_t late = Pokemon::clear_late_interrupts(console, context, step.wild ? interrupts.wild : interrupts.other, watch, MAX_INTERRUPTIONS_PER_LEG); + const OverworldInterrupts& watched = step.wild ? interrupts.wild : interrupts.other; + size_t late = Pokemon::clear_late_interrupts(console, context, watched, watch, MAX_INTERRUPTIONS_PER_LEG); + if (late == 0){ + late = clear_unseen_battle(console, context, interrupts.wild, step); + } // After a warp it was checked for already. const bool done = late == 0 || step.warps || step.action != RouteAction::WALK; return StepOutcome{.end = done ? StepEnd::DONE : StepEnd::LATE, .walked = std::nullopt}; @@ -218,8 +234,6 @@ void walk_overworld_route_with_recovery( } RouteCalls calls; calls.walk = [&](const RouteStep& step, std::optional from_facing){ - clear_open_message(console, context, step.wild ? interrupts.wild : interrupts.other, step); - check_overworld(console, context, step); return walk_and_watch(console, context, step, from_facing, interrupts, speed); }; calls.hold_to_warp = [&](const RouteStep& step){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.h index aedadc9332..cad763c5b1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.h @@ -35,6 +35,8 @@ namespace PokemonFRLG{ // is isn't guessed: the stop's timing narrows it to a few tiles of the leg // (walked_near()), from which run_route() finds them again with // `planning`'s maps and costs, and walks the rest of the route as planned. +// A warp's fade that turns out to be a wild battle's stops its leg the +// same way, somewhere before the warp (walked_before_warp()). // // After a leg that crosses a trainer's sight it watches for the trainer, // long enough for them to walk up and speak, and hands what shows to @@ -48,10 +50,9 @@ namespace PokemonFRLG{ // A message open before a step is handed to `interrupts` once // (clear_open_message()). Throws OperationFailedException if a menu or // message is still open before a step, a warp's fade or the Surf prompt -// doesn't show, a warp's fade turns out to be a wild battle's, a leg is -// interrupted too many times, or the player can't be found again from -// every tile they may be on. A wild battle that starts as the last leg -// ends is cleared before it returns. +// doesn't show, a leg is interrupted too many times, or the player can't +// be found again from every tile they may be on. A wild battle that +// starts as the last leg ends is cleared before it returns. void walk_overworld_route_with_recovery( ConsoleHandle& console, ProControllerContext& context, const std::vector& route, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index 3e0f4f75f6..f350abf558 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -31,6 +31,10 @@ const char* sim_screen_name(SimScreen screen){ return "the START menu"; case SimScreen::BATTLE_FLASH: return "a battle's flashes"; + case SimScreen::BATTLE_WIPE: + return "a battle's wipe"; + case SimScreen::BATTLE_OPENING: + return "a battle's opening"; case SimScreen::BATTLE: return "a battle"; case SimScreen::FADE: @@ -144,11 +148,11 @@ bool OverworldSim::sees(SimWatcher watcher, SimScreen screen) const{ case SimWatcher::BATTLE_SCREEN: return screen == SimScreen::BATTLE; case SimWatcher::BATTLE_TEXT_BOX: - return screen == SimScreen::BATTLE || (screen == SimScreen::OVERWORLD && m_state.black_below); + return screen == SimScreen::BATTLE || screen == SimScreen::BATTLE_OPENING || (screen == SimScreen::OVERWORLD && m_state.black_below); case SimWatcher::MESSAGE: return screen == SimScreen::MESSAGE; case SimWatcher::FADE: - return screen == SimScreen::FADE; + return screen == SimScreen::FADE || screen == SimScreen::BATTLE_WIPE; } return false; } @@ -306,9 +310,10 @@ bool OverworldSim::after_step(const Step& step, Milliseconds pressed){ return wild_battle(pressed) || trainer_sees(pressed); } -// A wild battle the script starts on this step onto tall grass. +// A wild battle the script starts on this step onto tall grass, or onto a +// wild floor. bool OverworldSim::wild_battle(Milliseconds pressed){ - if (!is_tall_grass(map(), m_player.position)){ + if (!is_tall_grass(map(), m_player.position) && !m_script.wild_floor_maps.contains(map().name)){ return false; } m_grass_steps++; @@ -321,6 +326,12 @@ bool OverworldSim::wild_battle(Milliseconds pressed){ if (!encounter.seen_late){ schedule(pressed + m_script.timing.flash, SimScreen::BATTLE_FLASH, false); } + if (m_script.timing.battle_wipe){ + schedule(pressed + *m_script.timing.battle_wipe, SimScreen::BATTLE_WIPE, false); + } + if (m_script.timing.battle_opening){ + schedule(pressed + *m_script.timing.battle_opening, SimScreen::BATTLE_OPENING, false); + } schedule(pressed + m_script.timing.battle_screen, SimScreen::BATTLE, false); note(std::format("a wild battle on {}{}.", to_string(m_state.position), encounter.seen_late ? " (flashes missed)" : "")); return true; @@ -482,12 +493,11 @@ Milliseconds delay_of(const OverworldInterrupts& interrupts, size_t index){ } -OverworldSimWalker::OverworldSimWalker(OverworldSim& sim, SimWalkerRules rules) +OverworldSimWalker::OverworldSimWalker(OverworldSim& sim, SimWalkerRules rules, const OverworldInterruptSet& walker) : m_sim(sim) , m_rules(rules) { - // The walker's own interrupts, in its order: battles first. - const OverworldInterruptSet& walker = default_overworld_interrupts(); + // In the walker's order: battles first. m_wild = { {"a wild battle", SimWatcher::FLASH, delay_of(walker.wild, 0), true}, {"a wild battle (seen late)", SimWatcher::BATTLE_SCREEN, delay_of(walker.wild, 1), true}, @@ -556,18 +566,28 @@ std::optional OverworldSimWalker::hold_watching(const RouteStep& step, return m_sim.hold(step.direction, hold, STEP_RELEASE, hold + STEP_RELEASE + m_rules.watch_past_hold, watchers(interrupts)); } -// wait_out_warp(), then check_warp_was_no_battle(). -void OverworldSimWalker::after_warp(const RouteStep& step, int warps_before){ +// wait_out_warp(), then run_from_battle_after_warp(): false if the fade +// was a wild battle's, run from. wait_out_warp()'s watcher takes a wild +// battle's wipe for the fade (run 7; console B, 2026-11-03, Mt. Moon 1F): +// the battle screen stands in for the wipe. +bool OverworldSimWalker::after_warp(const RouteStep& step, int warps_before){ if (m_sim.state().warps == warps_before){ - m_sim.watch({}, WARP_TIMEOUT); - fail("walk_overworld_route(): no fade in and out after walking onto the warp to " + step.end.map + "."); + if (!m_sim.watch({SimWatcher::BATTLE_SCREEN}, WARP_TIMEOUT)){ + fail("walk_overworld_route(): no fade in and out after walking onto the warp to " + step.end.map + "."); + } + }else{ + m_sim.watch({SimWatcher::FADE}, WARP_TIMEOUT); } - m_sim.watch({SimWatcher::FADE}, WARP_TIMEOUT); m_sim.watch({}, AFTER_WARP); - if (m_sim.watch(watchers({m_wild[1]}), AFTER_WARP_BATTLE_WATCH - AFTER_WARP)){ - m_sim.handle_battle(SimBattleChoice::RUN); - fail("walk_overworld_route(): a wild battle, not the warp to " + step.end.map + ": the player is off the route."); + if (!m_sim.watch(watchers({m_wild[1]}), AFTER_WARP_BATTLE_WATCH - AFTER_WARP)){ + return true; } + m_sim.handle_battle(SimBattleChoice::RUN); + return false; +} + +void OverworldSimWalker::fail_off_route(const RouteStep& step){ + fail("walk_overworld_route(): a wild battle, not the warp to " + step.end.map + ": the player is off the route."); } std::optional OverworldSimWalker::walk_step(const RouteStep& step, std::optional facing){ @@ -604,14 +624,24 @@ std::optional OverworldSimWalker::walk_step(const RouteStep& step, if (result.stopped){ return walked_near(step, result.tiles, TILE_TIME); } - if (step.warps){ - after_warp(step, warps_before); + if (step.warps && !after_warp(step, warps_before)){ + if (!m_rules.find_player_after_warp_battle){ + fail_off_route(step); + } + m_log.push_back("Route: a wild battle, not the warp to " + step.end.map + "; the player is on " + to_string(step) + " before the warp."); + return walked_before_warp(step); } return std::nullopt; } -// walk_and_watch(), after clear_open_message() and check_overworld(). +// walk_and_watch(). StepOutcome OverworldSimWalker::walk(const RouteStep& step, std::optional facing){ + if (m_rules.battle_before_step && battle_on_its_way()){ + m_log.push_back("Route: " + std::string(sim_screen_name(m_sim.state().screen)) + " before " + to_string(step) + ": watching on for a wild battle set off before it."); + if (clear_late(m_wild, UNSEEN_BATTLE_WATCH, MAX_INTERRUPTIONS_PER_LEG) > 0){ + return StepOutcome{.end = StepEnd::BATTLE_BEFORE, .walked = std::nullopt}; + } + } if (m_sim.state().screen == SimScreen::MESSAGE){ m_log.push_back("Route: a message is open before " + to_string(step) + "; handing it to the leg's interrupts."); clear_late(interrupts(step), OPEN_MESSAGE_WATCH, 1); @@ -623,11 +653,32 @@ StepOutcome OverworldSimWalker::walk(const RouteStep& step, std::optional fade_first{SimWatcher::FADE}; for (const SimWatcher watcher : watchers(m_other)){ @@ -639,7 +690,9 @@ void OverworldSimWalker::hold_to_warp(const RouteStep& step){ const Milliseconds hold = TILE_TIME * (step.tiles + 2); const std::optional seen = m_sim.hold(step.direction, hold, STEP_RELEASE, hold + STEP_RELEASE, fade_first); if (seen && seen->watcher == 0){ - after_warp(step, warps_before); + if (!after_warp(step, warps_before)){ + fail_off_route(step); + } return; } if (!seen){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index b4b7aa3626..f7ff383c24 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -27,6 +27,7 @@ #include #include +#include #include #include #include "Common/Cpp/Time.h" @@ -46,6 +47,8 @@ enum class SimScreen{ MESSAGE, // a white message box: a sign, a trainer START_MENU, BATTLE_FLASH, // a wild battle's opening flashes + BATTLE_WIPE, // black, as a wild battle's wipe ends, before its text box + BATTLE_OPENING, // a battle's text box, empty, before the HP boxes BATTLE, // a battle's text box with the HP boxes FADE, // a warp's fade out and in }; @@ -63,7 +66,8 @@ enum class SimWatcher{ }; // A wild battle on the player's `grass_step`th step onto tall grass (from -// 1). Seen late: its flashes are missed, and only the battle screen shows. +// 1), or onto any tile of a map in SimScript::wild_floor_maps. Seen late: +// its flashes are missed, and only the battle screen shows. struct SimEncounter{ int grass_step = 1; bool seen_late = false; @@ -76,6 +80,12 @@ struct SimTiming{ Milliseconds tile{267}; Milliseconds flash{300}; Milliseconds battle_screen{3700}; + // A wild battle's text box, before the HP boxes (battle_screen). Not + // set: not modelled, the battle screen shows at once. + std::optional battle_opening; + // Black, from the end of a wild battle's wipe until its text box + // (battle_opening) or HP boxes. Not set: not modelled. + std::optional battle_wipe; Milliseconds message{400}; Milliseconds fade{1000}; // from the step's end to the new map Milliseconds trainer_notice{1000}; // "!" over the trainer, before they walk up @@ -90,6 +100,10 @@ struct SimScript{ // The hold numbered by the key (from 1) stops this many tiles short, // with nothing on screen (the forest drift, console B, 2026-11-01). std::map short_holds; + // Maps where every step can start a wild battle, also on tiles the maps + // don't mark as grass: Mt. Moon B2F's tiles closed on one side ('8') + // are cave floor too (console B, 2026-11-03). + std::set wild_floor_maps; SimTiming timing; }; @@ -240,6 +254,28 @@ struct SimWalkerRules{ // now; the tile-at-a-time build watched each step for 900 ms, and saw // the warp's fade on the step onto the forest's north gate as a battle. Milliseconds watch_past_hold{0}; + // A leg onto a warp whose fade was a wild battle's (its wipe passes for + // the fade) stops before the warp, and the player is found again on it. + // Without it the walker stopped as off the route (console B, + // 2026-11-03, Mt. Moon 1F, row 00.13). + bool find_player_after_warp_battle = true; + // After a leg's watch saw nothing, a battle's text box on screen (its + // HP boxes still to come) is watched on for, and the leg taken as + // stopped part-way. Without it the walker took "south 15 (to wall)" + // as walked and the next leg into the battle (console B, 2026-11-03, + // Mt. Moon B1F, row 00.13). + bool watch_on_for_unseen_battle = true; + // The same after a leg the maps see no wild tiles on (RouteStep::wild), + // which the leg and its watch don't watch for battles: on Mt. Moon + // B2F's tiles closed on one side, which the maps don't mark as wild, a + // battle on "east 7 (to wall)" left black after the leg, the leg was + // taken as walked and the next one held from where the battle was + // (console B, 2026-11-03, row 00.13). + bool watch_on_after_unmarked_leg = true; + // Before a step, a battle on its way (its text box or wipe) is watched + // on for, and the step before it taken as stopped part-way, not the + // step held from where the battle left the player. + bool battle_before_step = true; }; // The console side of run_route() on an OverworldSim, as @@ -248,7 +284,14 @@ struct SimWalkerRules{ // a message is closed and a trainer's battle after it fought. class OverworldSimWalker{ public: - OverworldSimWalker(OverworldSim& sim, SimWalkerRules rules = {}); + // `interrupts`: whose detection delays place a stopped leg, the + // walker's own or a caller's (story_interrupts()). Each set lists a + // wild battle, one seen late and a message for `wild`, and a message + // for `other`, in that order. + OverworldSimWalker( + OverworldSim& sim, SimWalkerRules rules = {}, + const OverworldInterruptSet& interrupts = default_overworld_interrupts() + ); // RouteCalls whose `fail` throws OperationFailedException, as the // console's does. @@ -271,9 +314,12 @@ class OverworldSimWalker{ }; StepOutcome walk(const RouteStep& step, std::optional facing); std::optional walk_step(const RouteStep& step, std::optional facing); - void after_warp(const RouteStep& step, int warps_before); + bool after_warp(const RouteStep& step, int warps_before); + [[noreturn]] void fail_off_route(const RouteStep& step); std::optional hold_watching(const RouteStep& step, Milliseconds hold, const std::vector& interrupts); size_t clear_late(const std::vector& interrupts, Milliseconds watch, size_t max); + size_t clear_unseen_battle(const RouteStep& step); + bool battle_on_its_way() const; void clear(const Interrupt& interrupt); void hold_to_warp(const RouteStep& step); StepEnd watch_for_trainer(const RouteStep& step, int approach_tiles); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp index 0c3b955630..4704fca85c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp @@ -89,6 +89,7 @@ struct SimCase{ SimWalkerRules rules = {}; std::optional> route = std::nullopt; WallCheck wall_check = WallCheck::TAP; + OpenLegCheck open_leg_check = OpenLegCheck::REANCHOR; }; struct SimRun{ @@ -116,7 +117,7 @@ SimRun run_case(const SimCase& c){ run.route = planned(c); OverworldSim sim(maps(), c.start, c.facing, c.script); OverworldSimWalker walker(sim, c.rules); - const RoutePlanning planning{.maps = &maps(), .costs = default_route_costs(), .start = c.start, .label = "Sim", .wall_check = c.wall_check}; + const RoutePlanning planning{.maps = &maps(), .costs = default_route_costs(), .start = c.start, .label = "Sim", .wall_check = c.wall_check, .open_leg_check = c.open_leg_check}; run.failure = walker.run(run.route, planning); run.state = sim.state(); run.log = walker.log(); @@ -211,6 +212,39 @@ std::optional longest_wild_leg(const std::vector& route){ } +// The first WALK of `route` onto a warp through grass. +std::optional wild_warp_leg(const std::vector& route){ + for (size_t c = 0; c < route.size(); c++){ + if (route[c].action == RouteAction::WALK && route[c].wild && route[c].warps){ + return c; + } + } + return std::nullopt; +} + +// A walk of `c` with a wild battle, its flashes missed, on step `tile` +// (from 1) of the route's first leg onto a warp through grass, which must +// be a grass step. Nothing if there is no such leg or step. +std::optional run_with_battle_on_warp_leg(SimCase c, size_t tile){ + const std::vector route = planned(c); + const std::optional warp = wild_warp_leg(route); + if (!warp){ + return std::nullopt; + } + const MapPosition from = *warp == 0 ? c.start : route[*warp - 1].end; + const std::vector tiles = leg_tiles(maps(), from, route[*warp]); + if (tile >= tiles.size() || !on_grass(tiles[tile])){ + return std::nullopt; + } + int grass_step = grass_steps(c.start, route, *warp).before; + for (size_t t = 1; t <= tile; t++){ + grass_step += on_grass(tiles[t]) ? 1 : 0; + } + c.script.encounters = {{.grass_step = grass_step, .seen_late = true}}; + return run_case(c); +} + + // cp0007 m6f and r15 (console B, 2026-11-01): out of Viridian Forest // through its north gate. The leg through the grass ends on the gate's // warp. Two rules keep it from failing on screens that aren't battles: @@ -240,6 +274,42 @@ UnitTestResult test_forest_north_gate(){ return true; } +// Console B, 2026-11-03, Mt. Moon 1F (row 00.13): a wild battle whose +// flashes were missed started on the leg south onto the ladder; its wipe +// passed for the ladder's fade, and the walker stopped as off the route, +// on the leg a tile short of the ladder. Here on the leg through the +// forest's grass onto its north gate: a battle on the leg's first or +// second step is run from, the player found again on the leg, and the +// gate reached through its warp. If the walk back onto the warp then +// ends short of it (hold 4: the leg, the hold that finds the player and +// its re-hold after the Bug Catcher), the route still stops on no fade. +// Without the rule it stops as off the route, as on the console. +UnitTestResult test_battle_on_warp_leg(){ + const SimCase c{.start = at("ViridianForest", 5, 20), .facing = Direction::NORTH, .goal = at("Route2_ViridianForest_NorthEntrance", 7, 9)}; + for (size_t tile : {1, 2}){ + const std::optional now = run_with_battle_on_warp_leg(c, tile); + if (!now){ + return std::format("Expected a leg onto the gate's warp with grass on its step {}:", tile) + describe(planned(c)); + } + if (!arrived(*now, c.goal) || now->state.warps != 1){ + return std::format("Expected the battle on step {} run from, then the gate reached:", tile) + describe(*now); + } + } + SimCase no_warp = c; + no_warp.script.short_holds[4] = 2; + const std::optional short_back = run_with_battle_on_warp_leg(no_warp, 1); + if (!short_back || !stopped_with(*short_back, "no fade in and out") || short_back->state.warps != 0){ + return "Expected a stop on no fade when the walk back ends short of the warp:" + (short_back ? describe(*short_back) : ""); + } + SimCase off = c; + off.rules.find_player_after_warp_battle = false; + const std::optional old = run_with_battle_on_warp_leg(off, 1); + if (!old || !stopped_with(*old, "a wild battle, not the warp to Route2_ViridianForest_NorthEntrance: the player is off the route.")){ + return "Expected a stop as off the route without the rule:" + (old ? describe(*old) : ""); + } + return true; +} + // cp0007-zy (console B, 2026-11-01): with the START menu still open, three // legs to walls in Viridian Forest "walked" without the player moving. // The walker now stops before the first. @@ -345,8 +415,10 @@ UnitTestResult test_no_hold_over_ledge(){ // r16 (console B, 2026-11-01), Viridian Forest: an open leg west ended 2 // tiles short with nothing on screen, and the next leg, south to a wall, // was held into the TRAINER TIPS sign on (9, 29) six times. The walker now -// stops at the second read, as off the route; it can't yet tell the leg -// ended short (follow-up). +// finds the player at walls after the open leg, since the hold south +// doesn't end on its tile from where a short leg leaves them. Without that +// check it stops at the sign's second read, as off the route; without the +// stop either, it reads the sign 6 times. UnitTestResult test_short_leg_then_sign(){ SimCase c{.start = at("ViridianForest", 13, 28), .facing = Direction::WEST, .goal = at("ViridianForest", 7, 33)}; c.route = std::vector{ @@ -355,10 +427,16 @@ UnitTestResult test_short_leg_then_sign(){ }; c.script.short_holds[1] = 2; const SimRun now = run_case(c); - if (!stopped_with(now, "interrupted right away, again") || now.state.signs_read > 2){ - return "Expected a stop at the sign's second read:" + describe(now); + if (!arrived(now, c.goal) || now.state.signs_read != 0){ + return "Expected the player found at walls after the short leg, and the route walked:" + describe(now); + } + SimCase trusted = c; + trusted.open_leg_check = OpenLegCheck::TRUST; + const SimRun blocked = run_case(trusted); + if (!stopped_with(blocked, "interrupted right away, again") || blocked.state.signs_read > 2){ + return "Expected a stop at the sign's second read without the check:" + describe(blocked); } - SimCase unbounded = c; + SimCase unbounded = trusted; unbounded.rules.stop_if_blocked = false; const SimRun old = run_case(unbounded); if (!stopped_with(old, "Interrupted 6 times") || old.state.signs_read != 6){ @@ -367,6 +445,31 @@ UnitTestResult test_short_leg_then_sign(){ return true; } +// r16 (console B, 2026-11-01), Viridian Forest, a tile short instead of 2: +// the hold south from (8, 28) misses the sign and stops at the wall a +// column east of the plan's, with nothing on screen, so the walk was +// claimed done off the route. The walker now finds the player at walls +// after the open leg; without that check it ends on (8, 33). +UnitTestResult test_short_leg_unseen(){ + SimCase c{.start = at("ViridianForest", 13, 28), .facing = Direction::WEST, .goal = at("ViridianForest", 7, 33)}; + c.route = std::vector{ + leg(Direction::WEST, 6, at("ViridianForest", 7, 28), false), + leg(Direction::SOUTH, 5, c.goal, true), + }; + c.script.short_holds[1] = 1; + const SimRun now = run_case(c); + if (!arrived(now, c.goal)){ + return "Expected the player found at walls after the short leg, and the route walked:" + describe(now); + } + SimCase trusted = c; + trusted.open_leg_check = OpenLegCheck::TRUST; + const SimRun old = run_case(trusted); + if (!old.failure.empty() || !(old.state.position == at("ViridianForest", 8, 33))){ + return "Expected the walk claimed done on (8, 33) without the check:" + describe(old); + } + return true; +} + // r18 (console B, 2026-11-01), Pewter Gym: after Brock, Camper Liam sees // the player on the walk south to the door, walks up and battles. The // route holds on south to the door's mat; finding the player again at @@ -405,12 +508,14 @@ UnitTestResult test_mart_exit(){ void add_tests_OverworldSim(UnitTestDatabase& database){ database.add("the forest's north gate: no fade or black read as a battle", test_forest_north_gate); + database.add("a battle on a leg onto a warp", test_battle_on_warp_leg); database.add("the START menu left open", test_start_menu_open); database.add("a battle at the end of a leg", test_battle_at_end_of_leg); database.add("a late battle stops an open leg", test_late_battle_mid_leg); database.add("a trainer's battle is fought, not fled", test_trainer_not_fled); database.add("no hold over a ledge", test_no_hold_over_ledge); database.add("a short leg, then a sign", test_short_leg_then_sign); + database.add("a short leg, nothing seen", test_short_leg_unseen); database.add("a trainer on the way out of Pewter Gym", test_trainer_on_way_out); database.add("out of Viridian Mart from the clerk's scene", test_mart_exit); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp index e9b9f55bba..59563a1c16 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp @@ -8,6 +8,7 @@ #include #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" #include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" #include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_BattleDialogs.h" @@ -15,6 +16,7 @@ #include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_StartMenuDetector.h" #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleFlashWatcher.h" #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleScreenDetector.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleTextBoxDetector.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" #include "PokemonFRLG_PlayerFacingReader.h" #include "PokemonFRLG_OverworldWalk.h" @@ -68,11 +70,8 @@ class LateWildBattleInterrupt : public WildBattleInterrupt{ virtual std::unique_ptr make_watcher() const override{ return std::make_unique(COLOR_RED); } - // The flashes, the wipe and the opening animation: 3.7s after the step's - // press, twice on Route 1 (console B, 2026-11-01). Other maps open - // battles with other wipes, so elsewhere this is a guess. virtual Milliseconds detection_delay() const override{ - return 3700ms; + return OverworldWalkSteps::LATE_WILD_BATTLE_DELAY; } }; @@ -266,18 +265,79 @@ void clear_open_message( Pokemon::clear_late_interrupts(console, context, interrupts, OPEN_MESSAGE_WATCH, 1); } +// A battle whose flashes were missed shows its HP boxes, which the leg's +// watch for a late battle needs, seconds after its text box: in Mt. Moon +// the watch after "south 15 (to wall)" ended on the box still empty, the +// leg was taken as walked to its wall, and the next leg was walked into +// the battle, 5 tiles short of where it was planned from (console B, +// 2026-11-03, row 00.13). +namespace{ + +// What on screen shows a wild battle on its way: its text box, or the +// black of its wipe. Nothing if neither shows. +const char* battle_on_its_way(ConsoleHandle& console, ProControllerContext& context){ + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + if (!screen){ + return nullptr; + } + if (BattleTextBoxDetector(COLOR_RED).detect(screen)){ + return "a battle's text box"; + } + if (BlackScreenDetector(COLOR_RED).detect(screen)){ + return "a black screen"; + } + return nullptr; +} + +} + +size_t clear_unseen_battle( + ConsoleHandle& console, ProControllerContext& context, + const OverworldInterrupts& wild, const RouteStep& step +){ + if (step.action != RouteAction::WALK || step.warps){ + return 0; + } + const char* seen = battle_on_its_way(console, context); + if (seen == nullptr){ + return 0; + } + console.log(std::format("Route: {} after {}, which nothing stopped: watching on for a wild battle.", seen, to_string(step)), COLOR_ORANGE); + return Pokemon::clear_late_interrupts(console, context, wild, UNSEEN_BATTLE_WATCH, MAX_INTERRUPTIONS_PER_LEG); +} + +size_t clear_battle_before( + ConsoleHandle& console, ProControllerContext& context, + const OverworldInterrupts& wild, const RouteStep& step +){ + const char* seen = battle_on_its_way(console, context); + if (seen == nullptr){ + return 0; + } + console.log(std::format("Route: {} before {}: watching on for a wild battle set off before it.", seen, to_string(step)), COLOR_ORANGE); + return Pokemon::clear_late_interrupts(console, context, wild, UNSEEN_BATTLE_WATCH, MAX_INTERRUPTIONS_PER_LEG); +} + // After a warp's fade: fails, once the battle is fled, if it was a wild // battle's. In run 7 (console B, 2026-11-01) the player had drifted onto // Route 1's grass, and the step meant for Oak's Lab's door set off a // battle; its flashes and wipe passed for the warp's fade, the route went // on as if inside, and the next screen was the battle's FIGHT menu. -void check_warp_was_no_battle(ConsoleHandle& console, ProControllerContext& context, const RouteStep& step){ +bool run_from_battle_after_warp(ConsoleHandle& console, ProControllerContext& context){ BattleScreenWatcher battle(COLOR_RED); context.wait_for_all_requests(); if (wait_until(console, context, AFTER_WARP_BATTLE_WATCH, {battle}) < 0){ - return; + return false; } flee_battle(console, context); + return true; +} + +void check_warp_was_no_battle(ConsoleHandle& console, ProControllerContext& context, const RouteStep& step){ + if (!run_from_battle_after_warp(console, context)){ + return; + } OperationFailedExceptionWithScreenshot::fire( ErrorReportMode::SEND_ERROR_REPORT, "walk_overworld_route(): a wild battle, not the warp to " + step.end.map + ": the player is off the route.", @@ -432,10 +492,10 @@ void walk_overworld_route( break; } if (step.action != RouteAction::FACE){ - Pokemon::clear_late_interrupts( - console, context, step.wild ? interrupts.wild : interrupts.other, - step.wild ? AFTER_WILD_LEG_WATCH : AFTER_LEG_WATCH, MAX_INTERRUPTIONS_PER_LEG - ); + const OverworldInterrupts& watched = step.wild ? interrupts.wild : interrupts.other; + if (Pokemon::clear_late_interrupts(console, context, watched, step.wild ? AFTER_WILD_LEG_WATCH : AFTER_LEG_WATCH, MAX_INTERRUPTIONS_PER_LEG) == 0){ + clear_unseen_battle(console, context, interrupts.wild, step); + } } facing = step.facing_after; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h index 6ea5c1542f..5e914bb7fe 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h @@ -109,12 +109,21 @@ inline constexpr Milliseconds AFTER_WARP_BATTLE_WATCH(5000); // A message set off by a leg's last step shows after the hold ends. Caught // here, before the next leg's turn tap, which the message would swallow. inline constexpr Milliseconds AFTER_LEG_WATCH(500); -// The same after a leg through grass. A battle whose flashes are missed is -// seen only by its "Wild appeared!", 3.7s after its step's press -// (twice on Route 1, console B, 2026-11-01, run 7). Unless the walker waits -// that long, the next leg is walked into the battle and lost: there, "east -// 4" and "west 4". +// A wild battle whose flashes are missed is seen only by its "Wild +// appeared!": the flashes, the wipe and the opening animation +// take 3.7s from its step's press, twice on Route 1 (console B, 2026-11-01, +// run 7). Other maps open battles with other wipes, so elsewhere this is a +// guess. Every interrupt for such a battle places the stop with this. +inline constexpr Milliseconds LATE_WILD_BATTLE_DELAY(3700); +// The same after a leg through grass, for a battle seen that late. Unless +// the walker waits that long, the next leg is walked into the battle and +// lost: on Route 1, "east 4" and "west 4". inline constexpr Milliseconds AFTER_WILD_LEG_WATCH(3500); +// After a leg's watch saw nothing, but the screen shows a battle on its +// way: how long to watch on for its HP boxes. In Mt. Moon they came over +// 5s after the step that set the battle off, after the watch had ended on +// the battle's empty text box (console B, 2026-11-03, row 00.13). +inline constexpr Milliseconds UNSEEN_BATTLE_WATCH(5000); // How long clear_open_message() watches for the message it saw. inline constexpr Milliseconds OPEN_MESSAGE_WATCH(1000); inline constexpr size_t MAX_INTERRUPTIONS_PER_LEG = 5; @@ -165,6 +174,34 @@ void clear_open_message( const OverworldInterrupts& interrupts, const RouteStep& step ); +// After `step`'s hold and the watch after it, which saw nothing: if the +// screen shows a wild battle on its way anyway (its text box before the HP +// boxes, or black), watches on for it with `wild` (the interrupts for a +// step where a wild battle can start) and clears what shows. Returns how +// many it cleared: the leg may have stopped part-way. After any walk not +// onto a warp, whose fade check_warp_was_no_battle() covers, also where +// the maps see no wild tiles (RouteStep::wild): they miss some. Mt. Moon +// B2F's tiles closed on one side are cave floor too, and a battle on +// "east 7 (to wall)" there left the screen black after the leg, which +// was taken as walked (console B, 2026-11-03, row 00.13). +size_t clear_unseen_battle( + ConsoleHandle& console, ProControllerContext& context, + const OverworldInterrupts& wild, const RouteStep& step +); + +// Before `step`: if the screen shows a wild battle on its way (as +// clear_unseen_battle()), set off before the step started, watches on for +// it with `wild` and clears what shows. Returns how many it cleared: the +// step before may have stopped part-way. +size_t clear_battle_before( + ConsoleHandle& console, ProControllerContext& context, + const OverworldInterrupts& wild, const RouteStep& step +); + +// After a warp's fade: if it was a wild battle's, runs from the battle and +// returns true. +bool run_from_battle_after_warp(ConsoleHandle& console, ProControllerContext& context); + // After `step`'s warp: fails, once the battle is fled, if its fade was a // wild battle's. void check_warp_was_no_battle(ConsoleHandle& console, ProControllerContext& context, const RouteStep& step); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 4f3cb35021..18dda426ef 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -29,6 +29,7 @@ #include "Inference/Menus/PokemonFRLG_TeachScreenReader.h" #include "Inference/PokemonFRLG_BattleLevelUpReader.h" #include "Inference/PokemonFRLG_BattleSelectionArrowDetector.h" +#include "Inference/PokemonFRLG_BattleTextBoxDetector.h" #include "Inference/PokemonFRLG_PartyLevelUpReader.h" #include "Inference/PokemonFRLG_ShinySymbolDetector.h" #include "Inference/PokemonFRLG_StatsReader.h" @@ -726,6 +727,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_EliteFourRoomDetector(database); add_tests_HallOfFameSavingDetector(database); add_tests_BattleMoveSelectionArrow(database); + add_tests_BattleTextBoxDetector(database); add_tests_BagDetector(database); add_tests_AutoStoryReaders(database); add_tests_ExitWildBattle(database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp index 8428706822..43702b6b96 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp @@ -745,7 +745,7 @@ class StoryWildBattle : public OverworldInterrupt{ } // As the walker's own wild battle interrupts. virtual Milliseconds detection_delay() const override{ - return m_late ? 2000ms : 300ms; + return m_late ? OverworldWalkSteps::LATE_WILD_BATTLE_DELAY : 300ms; } // Run from or fought by the battle loop, which returns only once START // opens on the overworld, so nothing of the battle is left before the diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp index 107e9fc670..0aea6c90a0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp @@ -2,14 +2,17 @@ * * From: https://github.com/PokemonAutomation/ * - * The Mart cursor's moves, and the bag's rows as the story counts them. + * The Mart cursor's moves, the bag's rows as the story counts them, and + * where the story's wild battle seen late places a stopped leg. * */ #include #include #include +#include #include +#include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Logging/AbstractLogger.h" #include "Common/Cpp/TestRunners/UnitTest.h" @@ -17,6 +20,8 @@ #include "CommonFramework/Language.h" #include "Tests/ImageUnitTest.h" #include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SaveCardReader.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" #include "PokemonFRLG_AutoStoryActions.h" #include "PokemonFRLG_AutoStoryBattle.h" #include "PokemonFRLG_AutoStoryBattleDecisions.h" @@ -215,6 +220,69 @@ UnitTestResult test_unread_language(Logger& logger){ return true; } +// The open leg through Route 1's grass on the way from Viridian Mart to +// Oak's Lab ("south 20"), and the tile it starts from. +struct GrassLeg{ + MapPosition start; + RouteStep step; +}; +std::optional route1_grass_leg(const std::vector& maps){ + const MapPosition mart{"ViridianCity_Mart", {4, 3}}; + const RouteGoal lab{MapPosition{"PalletTown_ProfessorOaksLab", {6, 11}}, std::nullopt}; + const std::optional> route = plan_overworld_route(maps, mart, lab, default_route_costs(), Direction::WEST); + if (!route){ + return std::nullopt; + } + MapPosition start = mart; + for (const RouteStep& step : *route){ + if (step.action == RouteAction::WALK && step.wild && !step.to_wall && !step.warps && step.tiles >= 16){ + return GrassLeg{start, step}; + } + start = step.end; + } + return std::nullopt; +} + +// How many tiles of `leg` the player walked to `at`, or -1 if `at` is off it. +int tiles_walked(const std::vector& maps, const GrassLeg& leg, const MapPosition& at){ + const std::vector tiles = leg_tiles(maps, leg.start, leg.step); + for (size_t c = 0; c < tiles.size(); c++){ + if (tiles[c] == at){ + return (int)c; + } + } + return -1; +} + +// r16 and r17 (console B, 2026-11-01), Route 1: a wild battle on the first +// grass step of "south 20" whose flashes were missed shows "Wild +// appeared!" 3.7 s after the step's press. The story's interrupt for it +// must place the stop where the battle stopped the player, as the walker's +// does: with 2 s it put them about 6 tiles further on. +UnitTestResult test_late_battle_placed(Logger&){ + const std::vector maps = overworld_maps(); + const std::optional leg = route1_grass_leg(maps); + if (!leg){ + return "Expected an open leg of 16 tiles or more through Route 1's grass from Viridian Mart to Oak's Lab."; + } + SimScript script; + script.encounters = {{.grass_step = 1, .seen_late = true}}; + OverworldSim sim(maps, leg->start, leg->step.direction, script); + Supplies supplies; + const OverworldInterruptSet story = story_interrupts(supplies, false, StoryChecks::FAST, Language::English); + OverworldSimWalker walker(sim, {}, story); + const StepOutcome outcome = walker.calls().walk(leg->step, leg->step.direction); + const int walked = tiles_walked(maps, *leg, sim.state().position); + if (outcome.end != StepEnd::STOPPED || !outcome.walked || walked < outcome.walked->min || outcome.walked->max < walked){ + return std::format( + "Expected \"{}\" from {} stopped and placed on tile {} ({}), where the battle stopped the player; placed on tiles {} to {}.", + to_string(leg->step), to_string(leg->start), walked, to_string(sim.state().position), + outcome.walked ? outcome.walked->min : -1, outcome.walked ? outcome.walked->max : -1 + ); + } + return true; +} + // battle_shows(), the battle loop's look at whether the battle is still on // screen, on console B's captures. @@ -280,6 +348,7 @@ void add_tests_AutoStoryItems(UnitTestDatabase& database){ database.add("an unread item name keeps its row", test_pocket_rows_unread); database.add("unread bag counts count as some", test_unread_counts); database.add("no item names read in a language without them", test_unread_language); + database.add("a wild battle seen late is placed where it stopped the leg", test_late_battle_placed); // "Wild CHANSEY appeared!" with its HP box, and Mt. Moon B2F's corridor // after "Got away safely!", whose black lower half reads as the battle's // text box (console B, 2026-11-03: 9 minutes of A and B there). diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index eda3053c7f..f8fadc0a6b 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1785,6 +1785,8 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleScreenDetector.h Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleSelectionArrowDetector.cpp Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleSelectionArrowDetector.h + Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleTextBoxDetector.cpp + Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleTextBoxDetector.h Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_DaycareManDetector.cpp Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_DaycareManDetector.h Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_DigitReader.cpp