diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index c3e8fdc685..15aaea005b 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -35,9 +35,11 @@ #include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" #include "PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h" +#include "Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h" #include "Pokemon/Navigation/Pokemon_LegPlanner_Tests.h" #include "Pokemon/Navigation/Pokemon_LegWalker_Tests.h" #include "Pokemon/Navigation/Pokemon_MapData_Tests.h" +#include "Pokemon/Navigation/Pokemon_MoveMechanics_Tests.h" #include "Pokemon/Navigation/Pokemon_RouteLog_Tests.h" #include "Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h" #include "Pokemon/Navigation/Pokemon_WallRecovery_Tests.h" @@ -83,6 +85,8 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_LegWalker(ret); Pokemon::add_tests_WallRecovery(ret); Pokemon::add_tests_MapData(ret); + Pokemon::add_tests_ConnectedMaps(ret); + Pokemon::add_tests_MoveMechanics(ret); Pokemon::add_tests_RuntimeMap(ret); Pokemon::add_tests_RouteLog(ret); Pokemon::add_tests_AutoStory(ret); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index fdc17bd01a..0e51776983 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -23,8 +23,11 @@ #include "Pokemon_Interrupts_Tests.h" #include "Pokemon_SceneJudges_Tests.h" #include "Pokemon_ScreenEvents_Tests.h" +#include "Pokemon_StoryActions_Tests.h" #include "Pokemon_StoryEvents_Tests.h" +#include "Pokemon_StoryInterrupts_Tests.h" #include "Pokemon_StoryLog_Tests.h" +#include "Pokemon_StoryRun_Tests.h" #include "Pokemon_StorySavePolicy_Tests.h" #include "Pokemon_StorySegments_Tests.h" #include "Pokemon_StoryStepExecutor_Tests.h" @@ -38,6 +41,7 @@ namespace Pokemon{ // Registers every shared AutoStory suite, for the unit test runner. inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_AutoStorySelect(database); + add_tests_StoryRun(database); add_tests_AutoStoryStats(database); add_tests_StoryLog(database); add_tests_StoryRangeOptions(database); @@ -55,6 +59,8 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_SceneJudges(database); add_tests_Interrupts(database); add_tests_Transitions(database); + add_tests_StoryActions(database); + add_tests_StoryInterrupts(database); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h new file mode 100644 index 0000000000..ffe9602115 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h @@ -0,0 +1,96 @@ +/* Interrupt Handlers + * + * From: https://github.com/PokemonAutomation/ + * + * The table of a game's interrupt handlers and the screen look they read. + * Pokemon_StoryInterrupts.h builds on it. + * + */ + +#ifndef PokemonAutomation_Pokemon_InterruptHandlers_H +#define PokemonAutomation_Pokemon_InterruptHandlers_H + +#include +#include +#include +#include +#include +#include +#include "Pokemon_Interrupts.h" +#include "Pokemon_ScreenEvents.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_StoryStepExecutor.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What a game saw of the screen between two steps: its timed events, and +// the span of them the classifier judges. +struct ScreenLook{ + ScreenEventLog log{}; + InterruptWindow window = {}; +}; + +// Looks at the screen. `fresh` starts a new look; otherwise the look goes +// on from the last one, to see how an unsettled screen ends. +using ScreenLookFunction = std::function; + +// Clears an interrupt a look found: flees or fights the battle, closes +// the dialog, waits out the warp. +using InterruptAction = std::function; + +// A row of an InterruptHandlerTable. +struct InterruptHandler{ + InterruptAction handle = {}; + // What clearing it did to where the player is. + InterruptPose pose = InterruptPose::UNCHANGED; +}; + + +// A game's handlers by kind of interrupt, and the steps that start on one. +class InterruptHandlerTable{ +public: + // The handler for `kind`: one of WILD_ENCOUNTER, TRAINER_SIGHT, + // DIALOG or WARP. Another kind, or a second handler for one, throws + // InternalProgramError. + void add(InterruptKind kind, InterruptHandler handler); + // The handler for `kind`; nullptr if there is none. + const InterruptHandler* find(InterruptKind kind) const; + + // Steps of `step` start on `kind` showing: before one, it is the + // step's to clear, not an interrupt. A step that starts on + // WILD_ENCOUNTER or TRAINER_SIGHT starts on UNSETTLED too. + void starts_on(StoryStepKind step, InterruptKind kind); + bool step_starts_on(StoryStepKind step, InterruptKind kind) const; + +private: + std::map m_handlers; + std::set> m_starts_on; +}; + + +// A game's interrupts between steps: how it looks, how it judges what it +// saw, and what it does about each kind. +struct StoryInterrupts{ + ScreenLookFunction look = {}; + InterruptKnobs knobs = {}; + InterruptHandlerTable handlers = {}; + // Looks at a screen that stays UNSETTLED (a fade with no battle yet) + // before it fails the step as "interrupt_unsettled". A step that + // starts on it gets it on the first look. + size_t max_looks = 3; + // The same, for a screen that may be a battle's opening: enough looks + // for its battle to show. BDSP's 300 ms looks cover 12 s, past its + // battle_after_fade (8 s), after which a fade with no battle settles. + size_t max_opening_looks = 40; + // Interrupts cleared for one step before it fails as + // "too_many_interrupts". + size_t max_per_step = 3; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp new file mode 100644 index 0000000000..2e7376990e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp @@ -0,0 +1,182 @@ +/* Story Actions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_StoryActions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +const StoryAction* find_in(const std::map>& actions, std::string_view name){ + const auto iter = actions.find(name); + return iter == actions.end() ? nullptr : &iter->second; +} + +} // namespace + + +void StoryActionTable::add(StoryStepKind kind, std::string name, StoryAction action){ + const std::string key = std::format("{} '{}'", story_step_kind_name(kind), name); + if (!m_by_kind[kind].emplace(std::move(name), std::move(action)).second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("A second story action for {}", key)); + } +} + +void StoryActionTable::add_any_kind(std::string name, StoryAction action){ + if (name.empty()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "A story action for any kind needs a name."); + } + const std::string key = name; + if (!m_any_kind.emplace(std::move(name), std::move(action)).second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("A second story action for any kind named {}", key)); + } +} + +const StoryAction* StoryActionTable::find(StoryStepKind kind, std::string_view name) const{ + const auto kind_iter = m_by_kind.find(kind); + if (kind_iter != m_by_kind.end()){ + if (const StoryAction* exact = find_in(kind_iter->second, name)){ + return exact; + } + } + if (const StoryAction* any_kind = find_in(m_any_kind, name)){ + return any_kind; + } + if (kind_iter != m_by_kind.end()){ + return find_in(kind_iter->second, ""); + } + return nullptr; +} + +const StoryAction* StoryActionTable::find(const StoryStep& step) const{ + return find(step.kind, step.action); +} + + +std::vector lint_story_checkpoint(const StoryCheckpoint& data, const StoryActionTable& table){ + std::vector problems; + for (size_t c = 0; c < data.steps.size(); c++){ + const StoryStep& step = data.steps[c]; + const StoryAction* action = table.find(step); + const std::vector errors = action == nullptr + ? std::vector{"no action"} + : story_args_errors(StoryActionSpec{.kind = step.kind, .name = step.action, .args = action->args}, step.args); + for (const std::string& error : errors){ + problems.emplace_back(std::format( + "{} step {} {}: {} for {} '{}'", + data.id, c + 1, step.name, error, story_step_kind_name(step.kind), step.action + )); + } + } + return problems; +} + + +void StepGuard::before_step(const StoryStep&){} + +bool StepGuard::stops_on_failure(const StoryStep&) const{ + return false; +} + +void StepGuard::on_failure(const StoryStep&, const OperationFailedException&){} + +void StepGuard::on_interrupt(const StoryStep&, const InterruptCheck&){} + +void StepGuard::on_screen(const StoryStep&, const ScreenSettle&){} + + +TableExecutor::TableExecutor(const StoryActionTable& table, StepGuard& guard) + : m_table(table) + , m_guard(guard) +{} + +Outcome TableExecutor::run(const StoryStep& step, RunState& state){ + m_guard.before_step(step); + size_t cleared = 0; + while (true){ + if (std::optional failed = clear_interrupts(step, state, cleared)){ + return *failed; + } + try{ + Outcome outcome = run_action(step, state); + if (outcome.succeeded()){ + return outcome; + } + switch (look_after_failure(step, state, cleared)){ + case AfterFailure::RETRY: + continue; + case AfterFailure::GAME_NOT_RUNNING: + return outcome_game_not_running(); + case AfterFailure::KEEP: + return outcome; + } + }catch (OperationFailedException& e){ + const AfterFailure after = look_after_failure(step, state, cleared); + if (after == AfterFailure::RETRY){ + continue; + } + if (after == AfterFailure::GAME_NOT_RUNNING){ + return outcome_game_not_running(); + } + if (m_guard.stops_on_failure(step)){ + throw; + } + m_guard.on_failure(step, e); + return outcome_failed("operation_failed", e.message()); + } + } +} + +Outcome TableExecutor::run_action(const StoryStep& step, RunState& state){ + if (const StoryAction* action = m_table.find(step)){ + return action->act(step, state); + } + return unsupported_step(step); +} + +// Clears what interrupted the player before `step`, counting it in +// `cleared`. Nothing when there was nothing or it is cleared; else the +// step's failure. +std::optional TableExecutor::clear_interrupts(const StoryStep& step, RunState& state, size_t& cleared){ + if (m_interrupts == nullptr){ + return std::nullopt; + } + InterruptCheck check = clear_story_interrupt(*m_interrupts, step, state); + m_guard.on_screen(step, check.screen); + if (check.verdict.kind == InterruptKind::NONE){ + // Nothing interrupted; failed only when the game is not running. + return check.outcome.succeeded() ? std::nullopt : std::optional(check.outcome); + } + if (check.outcome.succeeded() && ++cleared > m_interrupts->max_per_step){ + check.outcome = outcome_failed("too_many_interrupts", step.name); + } + m_guard.on_interrupt(step, check); + if (!check.outcome.succeeded()){ + return check.outcome; + } + return std::nullopt; +} + +// What explains the failure of `step`, if anything: an interrupt that +// showed after it failed and is cleared, or the game not running. +AfterFailure TableExecutor::look_after_failure(const StoryStep& step, RunState& state, size_t& cleared){ + const size_t before = cleared; + const std::optional failed = clear_interrupts(step, state, cleared); + if (failed){ + return failed->failure == GAME_NOT_RUNNING ? AfterFailure::GAME_NOT_RUNNING : AfterFailure::KEEP; + } + return cleared > before ? AfterFailure::RETRY : AfterFailure::KEEP; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h new file mode 100644 index 0000000000..23711eb83c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h @@ -0,0 +1,162 @@ +/* Story Actions + * + * From: https://github.com/PokemonAutomation/ + * + * A game's story steps as a table of actions instead of one virtual per + * kind. An action is keyed by the step's kind and its action's name + * (StoryStep::action), so one table holds a game's + * usual way of doing a kind, its other ways, and the steps only it has. + * The console and a simulation bind the same rows to different actions. + * + * TableExecutor runs a step through the table, inside the game's + * StepGuard: the log line, and a failed console step turned into a failed + * Outcome. Today each game writes that guard itself (BDSP's + * StoryExecutor::run(), FRLG's guarded(), PLZA's Executor::run()). + * With the game's interrupts set, it also clears what stopped the player + * between steps (Pokemon_StoryInterrupts.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActions_H +#define PokemonAutomation_Pokemon_StoryActions_H + +#include +#include +#include +#include +#include +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_StoryInterrupts.h" +#include "Pokemon_StoryStepExecutor.h" +#include "Types/Pokemon_StoryActionSpec.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Does `step`, from the run so far. +using StoryActionFunction = std::function; + +// A row of a StoryActionTable: what does a step, and what it needs. +struct StoryAction{ + StoryActionFunction act = {}; + // Moves or reads the console. A binding without one (a simulation) + // can't run it. + bool needs_console = false; + // The screen event the action ends on ("fade", "dialog"). Declared for + // the event-driven waits to come; nothing reads it yet. + std::string waits_for = {}; + // The args its steps may carry (StoryStep::args); a step with any + // other, or without a required one, fails lint_story_checkpoint(). + std::vector args = {}; +}; + + +// A game's actions by step kind and action name. +class StoryActionTable{ +public: + // The action for steps of `kind` whose action is named `name`. An + // empty `name` is the kind's default. A second action for the same + // key throws InternalProgramError. + void add(StoryStepKind kind, std::string name, StoryAction action); + // The action for steps of any kind whose action is named `name`, + // which must not be empty. + void add_any_kind(std::string name, StoryAction action); + + // The action for a step of `kind` with an action named `name`: the + // one added for both, else the one for `name` of any kind, else the + // kind's default. nullptr if there is none. + const StoryAction* find(StoryStepKind kind, std::string_view name) const; + // find() for the step's kind and its action's name. + const StoryAction* find(const StoryStep& step) const; + +private: + using ByName = std::map>; + std::map m_by_kind; + ByName m_any_kind; +}; + +// The steps of `data` that `table` has no action for, as +// " step : no action for GAME 'bill'", or whose args +// don't fit their action's, as "... missing argument \"budget\" for GAME 'mart'". +std::vector lint_story_checkpoint(const StoryCheckpoint& data, const StoryActionTable& table); + + +// What a game does around every step a TableExecutor runs. Does nothing +// by default, and a failed step fails the step. +class StepGuard{ +public: + virtual ~StepGuard() = default; + + // Before the step runs: e.g. the step's log line. + virtual void before_step(const StoryStep& step); + // Whether a failed step stops the program, leaving the console on the + // failure, instead of failing the step for the segment to reload: the + // rows a developer is fixing. + virtual bool stops_on_failure(const StoryStep& step) const; + // The step threw `error` and fails: e.g. log it and save a screenshot. + virtual void on_failure(const StoryStep& step, const OperationFailedException& error); + // A look before the step, or after it failed, found an interrupt and + // cleared it or failed to (`check`): e.g. log it. + virtual void on_interrupt(const StoryStep& step, const InterruptCheck& check); + // How the screen looked when the look before the step (or after it + // failed) ended, interrupt or not: e.g. log it, so a run log shows + // whether the scene before had ended before the step's first input. + virtual void on_screen(const StoryStep& step, const ScreenSettle& screen); +}; + + +// What a look at the screen after a step failed found. +enum class AfterFailure{ + // Nothing explains the failure: it is the step's own. + KEEP, + // An interrupt explains it and is cleared: the step runs again. + RETRY, + // The game is not running (the Switch's HOME menu): the failure is + // that, and the step is not run again. + GAME_NOT_RUNNING, +}; + +// Runs each step with the table's action for it, inside `guard`. +class TableExecutor : public StoryStepExecutor{ +public: + // `table` and `guard` must outlive the executor. + TableExecutor(const StoryActionTable& table, StepGuard& guard); + + // The table's action for the step (run_action()); with none, the + // step is unsupported (unsupported_step()). An OperationFailedException + // from the action is the failed Outcome "operation_failed", unless the + // guard stops on it. + // With interrupts set, each step first clears what stopped the player + // since the step before, and a failed step that an interrupt explains + // runs again once it is cleared. + virtual Outcome run(const StoryStep& step, RunState& state) override; + + // The game's interrupts between steps, which must outlive the + // executor; none (the default) looks for none. + void set_interrupts(const StoryInterrupts* interrupts){ + m_interrupts = interrupts; + } + +protected: + // The table's action for the step, or unsupported_step() with none: + // what run() runs once the screen is clear. A binding may wrap it, or + // do the kinds its table does not have yet. + virtual Outcome run_action(const StoryStep& step, RunState& state); + +private: + std::optional clear_interrupts(const StoryStep& step, RunState& state, size_t& cleared); + AfterFailure look_after_failure(const StoryStep& step, RunState& state, size_t& cleared); + + const StoryActionTable& m_table; + StepGuard& m_guard; + const StoryInterrupts* m_interrupts = nullptr; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp new file mode 100644 index 0000000000..a4e8020210 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp @@ -0,0 +1,323 @@ +/* Story Actions Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryActions.h" +#include "Pokemon_StoryActions_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +StoryStep make(StoryStepKind kind, std::string name, std::string action = ""){ + StoryStep step; + step.kind = kind; + step.name = std::move(name); + step.action = std::move(action); + return step; +} + +// An action that fails with `name`, so a test sees which one ran. +StoryAction named(std::string name){ + return StoryAction{ + .act = [name](const StoryStep&, RunState&){ + return outcome_failed(name); + }, + }; +} + +// The name of the action the table finds for `kind` and `action`; "none" +// without one. +std::string found(const StoryActionTable& table, StoryStepKind kind, std::string name){ + const StoryAction* action = table.find(make(kind, "step", std::move(name))); + if (action == nullptr){ + return "none"; + } + RunState state; + return action->act(make(kind, "step"), state).failure; +} + + +UnitTestResult test_lookup_order(){ + StoryActionTable table; + table.add(StoryStepKind::TALK, "", named("talk default")); + table.add(StoryStepKind::TALK, "bill", named("talk bill")); + table.add_any_kind("bill", named("any bill")); + table.add_any_kind("nurse", named("any nurse")); + const std::pair checks[] = { + {found(table, StoryStepKind::TALK, "bill"), "talk bill"}, + {found(table, StoryStepKind::MASH, "bill"), "any bill"}, + {found(table, StoryStepKind::TALK, "nurse"), "any nurse"}, + {found(table, StoryStepKind::TALK, "oak"), "talk default"}, + {found(table, StoryStepKind::TALK, ""), "talk default"}, + {found(table, StoryStepKind::MASH, "oak"), "none"}, + {found(table, StoryStepKind::MASH, ""), "none"}, + }; + for (const auto& [actual, expected] : checks){ + if (actual != expected){ + return std::format("Expected {}, got {}", expected, actual); + } + } + return true; +} + +UnitTestResult test_duplicate_actions_throw(){ + StoryActionTable table; + table.add(StoryStepKind::TALK, "bill", named("first")); + table.add_any_kind("bill", named("any")); + const auto throws = [](auto add){ + try{ + add(); + }catch (InternalProgramError&){ + return true; + } + return false; + }; + if (!throws([&]{ table.add(StoryStepKind::TALK, "bill", named("second")); })){ + return "Expected a second TALK 'bill' to throw."; + } + if (!throws([&]{ table.add_any_kind("bill", named("second")); })){ + return "Expected a second any-kind 'bill' to throw."; + } + if (!throws([&]{ table.add_any_kind("", named("nameless")); })){ + return "Expected an any-kind action without a name to throw."; + } + return found(table, StoryStepKind::TALK, "bill") == "first" ? UnitTestResult(true) : UnitTestResult("Expected the first action kept."); +} + +// The args a test Mart takes. +const std::vector MART_ARGS = { + {.key = "map", .type = StoryArgType::WORD, .required = true, .fallback = std::nullopt, .why = ""}, + {.key = "budget", .type = StoryArgType::INTEGER, .required = true, .fallback = std::nullopt, .why = ""}, +}; + +// `step` with `args`. +StoryStep with_args(StoryStep step, StoryActionArgs args){ + step.args = std::move(args); + return step; +} + +UnitTestResult test_lint_names_steps_without_actions(){ + StoryActionTable table; + table.add(StoryStepKind::ROUTE, "", named("route")); + table.add_any_kind("bill", named("bill")); + StoryAction mart = named("mart"); + mart.args = MART_ARGS; + table.add(StoryStepKind::GAME, "mart", std::move(mart)); + const StoryCheckpoint data{ + .id = "00.05", + .title = "", + .start = std::nullopt, + .steps = { + make(StoryStepKind::ROUTE, "to the cape", "route"), + make(StoryStepKind::GAME, "meet Bill", "bill"), + make(StoryStepKind::GAME, "teleporter", "cell_separator"), + make(StoryStepKind::TALK, "talk"), + with_args(make(StoryStepKind::GAME, "buy", "mart"), {{"map", std::string("M")}, {"budget", int64_t(1500)}}), + with_args(make(StoryStepKind::GAME, "buy more", "mart"), {{"map", std::string("M")}}), + with_args(make(StoryStepKind::GAME, "meet Bill again", "bill"), {{"slot", int64_t(1)}}), + }, + }; + const std::vector problems = lint_story_checkpoint(data, table); + const std::vector expected = { + "00.05 step 3 teleporter: no action for GAME 'cell_separator'", + "00.05 step 4 talk: no action for TALK ''", + "00.05 step 6 buy more: missing argument \"budget\" for GAME 'mart'", + "00.05 step 7 meet Bill again: unknown argument \"slot\" for GAME 'bill'", + }; + if (problems != expected){ + std::string got; + for (const std::string& problem : problems){ + got += std::format("\n{}", problem); + } + return std::format("Expected two steps without actions and two with bad args, got:{}", got); + } + return true; +} + + +// A binding that does TALK itself when its table has no action for it. +class FakeTableExecutor : public TableExecutor{ +public: + using TableExecutor::TableExecutor; + +protected: + virtual Outcome run_action(const StoryStep& step, RunState& state) override{ + const Outcome outcome = TableExecutor::run_action(step, state); + if (step.kind == StoryStepKind::TALK && outcome.failure == "unsupported_step"){ + return outcome_failed("talk binding"); + } + return outcome; + } +}; + +// Writes down what the executor asked of it. +class FakeGuard : public StepGuard{ +public: + std::vector trace; + bool stops = false; + + virtual void before_step(const StoryStep& step) override{ + trace.push_back(std::format("before {}", step.name)); + } + virtual bool stops_on_failure(const StoryStep&) const override{ + return stops; + } + virtual void on_failure(const StoryStep& step, const OperationFailedException& error) override{ + trace.push_back(std::format("failed {}: {}", step.name, error.message())); + } +}; + +StoryAction throwing(){ + return StoryAction{ + .act = [](const StoryStep&, RunState&) -> Outcome{ + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, "no dialog"); + }, + .needs_console = true, + }; +} + +UnitTestResult test_executor_uses_table_then_binding(){ + StoryActionTable table; + table.add(StoryStepKind::GAME, "bill", named("bill action")); + FakeGuard guard; + FakeTableExecutor executor(table, guard); + RunState state; + const std::string bill = executor.run(make(StoryStepKind::GAME, "bill", "bill"), state).failure; + const std::string talk = executor.run(make(StoryStepKind::TALK, "talk"), state).failure; + const std::string mash = executor.run(make(StoryStepKind::MASH, "mash"), state).failure; + if (bill != "bill action" || talk != "talk binding" || mash != "unsupported_step"){ + return std::format("Expected table, binding, unsupported; got {}, {}, {}", bill, talk, mash); + } + if (guard.trace != std::vector{"before bill", "before talk", "before mash"}){ + return "Expected the guard before every step."; + } + return true; +} + +UnitTestResult test_guard_turns_failures_into_outcomes(){ + StoryActionTable table; + table.add(StoryStepKind::TALK, "", throwing()); + FakeGuard guard; + TableExecutor executor(table, guard); + RunState state; + const Outcome outcome = executor.run(make(StoryStepKind::TALK, "oak"), state); + if (outcome.failure != "operation_failed" || outcome.detail != "no dialog"){ + return std::format("Expected operation_failed: no dialog, got {}", to_string(outcome)); + } + if (guard.trace != std::vector{"before oak", "failed oak: no dialog"}){ + return "Expected the guard told of the failure."; + } + return true; +} + +UnitTestResult test_guard_stop_rethrows(){ + StoryActionTable table; + table.add(StoryStepKind::TALK, "", throwing()); + table.add(StoryStepKind::MASH, "", StoryAction{ + .act = [](const StoryStep&, RunState&) -> Outcome{ + throw std::runtime_error("not a console failure"); + }, + }); + FakeGuard guard; + guard.stops = true; + TableExecutor executor(table, guard); + RunState state; + try{ + executor.run(make(StoryStepKind::TALK, "oak"), state); + return "Expected a stop row's failure rethrown."; + }catch (OperationFailedException&){} + guard.stops = false; + try{ + executor.run(make(StoryStepKind::MASH, "scene"), state); + return "Expected other exceptions passed through."; + }catch (std::runtime_error&){} + if (guard.trace != std::vector{"before oak", "before scene"}){ + return "Expected no failure reported for a stop or another exception."; + } + return true; +} + + +struct StoryActionsCase{ + struct Input{ + std::string_view name; + UnitTestResult (*test)(); + }; + + struct Expectation{ + std::string_view description; + }; + + Input input; + Expectation expectation; +}; + +class Test_StoryActions : public UnitTest{ +public: + explicit Test_StoryActions(StoryActionsCase scenario) + : UnitTest(std::format("Pokemon::StoryActions - {}", scenario.input.name)) + , m_scenario(scenario) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.input.test(); + } + +private: + StoryActionsCase m_scenario; +}; + +const StoryActionsCase STORY_ACTIONS_CASES[] = { + { + .input = {.name = "table: exact, then any kind, then the kind's default", .test = test_lookup_order}, + .expectation = {.description = "finds the most specific action, or none"}, + }, + { + .input = {.name = "table: a second action for a key throws", .test = test_duplicate_actions_throw}, + .expectation = {.description = "keeps the first action and rejects nameless any-kind actions"}, + }, + { + .input = {.name = "lint: steps without an action", .test = test_lint_names_steps_without_actions}, + .expectation = {.description = "names each step the table has no action for"}, + }, + { + .input = {.name = "executor: the table, then the binding", .test = test_executor_uses_table_then_binding}, + .expectation = {.description = "a step without a table action is the binding's or unsupported, guarded before every step"}, + }, + { + .input = {.name = "executor: a console failure fails the step", .test = test_guard_turns_failures_into_outcomes}, + .expectation = {.description = "turns OperationFailedException into operation_failed and tells the guard"}, + }, + { + .input = {.name = "executor: a stop row rethrows", .test = test_guard_stop_rethrows}, + .expectation = {.description = "rethrows on a stop row and passes other exceptions through"}, + }, +}; + +} // namespace + + +void add_tests_StoryActions(UnitTestDatabase& database){ + for (const StoryActionsCase& scenario : STORY_ACTIONS_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h new file mode 100644 index 0000000000..6f6f908d18 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h @@ -0,0 +1,23 @@ +/* Story Actions Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActions_Tests_H +#define PokemonAutomation_Pokemon_StoryActions_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for story action tables, checkpoint lint and the table executor. +void add_tests_StoryActions(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp new file mode 100644 index 0000000000..8c50b18d37 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp @@ -0,0 +1,198 @@ +/* Story Interrupts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryInterrupts.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +void InterruptHandlerTable::add(InterruptKind kind, InterruptHandler handler){ + if (kind == InterruptKind::NONE || kind == InterruptKind::UNSETTLED){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + std::format("No handler can clear {}.", interrupt_kind_name(kind)) + ); + } + if (!m_handlers.emplace(kind, std::move(handler)).second){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + std::format("A second interrupt handler for {}", interrupt_kind_name(kind)) + ); + } +} + +const InterruptHandler* InterruptHandlerTable::find(InterruptKind kind) const{ + const auto iter = m_handlers.find(kind); + return iter == m_handlers.end() ? nullptr : &iter->second; +} + +void InterruptHandlerTable::starts_on(StoryStepKind step, InterruptKind kind){ + m_starts_on.emplace(step, kind); +} + +bool InterruptHandlerTable::step_starts_on(StoryStepKind step, InterruptKind kind) const{ + if (m_starts_on.contains({step, kind})){ + return true; + } + return kind == InterruptKind::UNSETTLED && ( + m_starts_on.contains({step, InterruptKind::WILD_ENCOUNTER}) || + m_starts_on.contains({step, InterruptKind::TRAINER_SIGHT}) + ); +} + + +namespace{ + +// Whether an UNSETTLED verdict on `look` may be a battle's opening: its +// fade is white (an encounter's flash), still down (a battle's fade ends +// on the battle), or came after a dialog box (a trainer's lines). +bool may_open_a_battle(const ScreenLook& look, const InterruptVerdict& verdict){ + const auto fade = std::find_if(verdict.evidence.begin(), verdict.evidence.end(), [](const ScreenEventChange& change){ + return change.edge == ScreenEventEdge::ROSE && + (change.event == ScreenEvent::FADE_WHITE || change.event == ScreenEvent::FADE_BLACK); + }); + if (fade == verdict.evidence.end()){ + return false; + } + const bool still_down = std::none_of(verdict.evidence.begin(), verdict.evidence.end(), [](const ScreenEventChange& change){ + return change.edge == ScreenEventEdge::FELL; + }); + if (fade->event == ScreenEvent::FADE_WHITE || still_down){ + return true; + } + return std::any_of(look.log.changes().begin(), look.log.changes().end(), [&](const ScreenEventChange& change){ + return change.event == ScreenEvent::DIALOG_BOX && change.edge == ScreenEventEdge::ROSE && + look.window.start <= change.time && change.time < fade->time; + }); +} + +// The look's verdict, looked at again while it is unsettled, up to +// max_looks looks in all, or max_opening_looks while it may be a battle's +// opening; not again before a step that starts on it. `screen` is how the +// last look ended. +InterruptVerdict settled_verdict(const StoryInterrupts& interrupts, StoryStepKind step, ScreenSettle& screen){ + ScreenLook look = interrupts.look(true); + InterruptVerdict verdict = classify_interrupt(look.log, look.window, interrupts.knobs); + const bool home = look.log.showing().has(ScreenEvent::SWITCH_HOME_MENU); + if (!home && !interrupts.handlers.step_starts_on(step, InterruptKind::UNSETTLED)){ + for (size_t looks = 1; verdict.kind == InterruptKind::UNSETTLED; looks++){ + const size_t limit = may_open_a_battle(look, verdict) ? interrupts.max_opening_looks : interrupts.max_looks; + if (looks >= limit){ + break; + } + look = interrupts.look(false); + verdict = classify_interrupt(look.log, look.window, interrupts.knobs); + } + } + screen = judge_settle(look); + return verdict; +} + +} // namespace + + +ScreenSettle judge_settle(const ScreenLook& look){ + ScreenSettle out; + const std::optional last = look.log.last_frame(); + if (!last || *last < look.window.start){ + return out; + } + out.seen = true; + out.showing = look.log.showing(); + WallClock since = look.window.start; + for (const ScreenEventChange& change : look.log.changes()){ + if (change.time <= look.window.end){ + since = std::max(since, change.time); + } + } + const WallClock end = std::max(look.window.end, since); + out.quiet = std::chrono::duration_cast(end - since); + return out; +} + +bool on_home_menu(const ScreenSettle& settle){ + return settle.seen && settle.showing.has(ScreenEvent::SWITCH_HOME_MENU); +} + +bool is_settled(const ScreenSettle& settle){ + return settle.seen && !on_home_menu(settle) && + settle.showing.has(ScreenEvent::PLAYER_CAN_MOVE) && + !settle.showing.any_of({ScreenEvent::DIALOG_BOX, ScreenEvent::BATTLE_STARTED}) && + fade_in(settle.showing) == WarpFade::NONE; +} + +std::string describe(const ScreenSettle& settle){ + if (!settle.seen){ + return "no frame seen"; + } + const std::string quiet = std::format("quiet {:.1f} s", settle.quiet.count() / 1000.0); + if (on_home_menu(settle)){ + return std::format("Switch HOME menu ({})", quiet); + } + if (is_settled(settle)){ + return std::format("settled overworld ({})", quiet); + } + return std::format("{} showing ({})", describe(settle.showing), quiet); +} + + +// The handler's outcome. A handler drives the console, which it can lose: +// that is a failed outcome too, not an exception for the executor's caller. +Outcome run_handler(const InterruptHandler& handler, const InterruptVerdict& verdict, RunState& state){ + try{ + return handler.handle(verdict, state); + }catch (OperationFailedException& e){ + return outcome_failed("operation_failed", e.message()); + } +} + + +InterruptCheck clear_story_interrupt(const StoryInterrupts& interrupts, const StoryStep& step, RunState& state){ + InterruptCheck out; + out.verdict = settled_verdict(interrupts, step.kind, out.screen); + if (on_home_menu(out.screen)){ + out.verdict = {}; + out.outcome = outcome_game_not_running(); + return out; + } + const InterruptKind kind = out.verdict.kind; + if (kind == InterruptKind::NONE){ + return out; + } + if (interrupts.handlers.step_starts_on(step.kind, kind)){ + out.verdict = {}; + return out; + } + if (kind == InterruptKind::UNSETTLED){ + out.outcome = outcome_failed("interrupt_unsettled", step.name); + return out; + } + const InterruptHandler* handler = interrupts.handlers.find(kind); + if (handler == nullptr || !handler->handle){ + out.outcome = outcome_failed("unhandled_interrupt", std::format("{} before {}", interrupt_kind_name(kind), step.name)); + return out; + } + const Outcome handled = run_handler(*handler, out.verdict, state); + if (!handled.succeeded()){ + out.outcome = outcome_failed("interrupt_failed", std::format("{}: {}", interrupt_kind_name(kind), to_string(handled))); + return out; + } + apply_interrupt_pose(handler->pose, state.pose); + return out; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h new file mode 100644 index 0000000000..61945b8459 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h @@ -0,0 +1,91 @@ +/* Story Interrupts + * + * From: https://github.com/PokemonAutomation/ + * + * What stops the story between two of its steps: someone walks up and + * talks, a trainer sees us as a step ends, a wild battle starts on the + * last tile of a walk, a door takes us somewhere. A walk's own walker + * clears what happens part-way through it (Pokemon_LegWalker.h, BDSP's + * walks); this is what is left once a step has settled. + * + * Before each step, and after a step fails, the TableExecutor looks at + * the screen through the game's eyes (ScreenLookFunction), judges the + * look with the shared classifier (classify_interrupt()) and clears what + * it found with the game's handler for that kind of interrupt. The + * handlers are a table, like the story's actions: data a game binds to + * its console or its simulation, not a type per game. + * + * A step that starts on what the look found (a MASH on its scene's box, + * a BATTLE on its trainer's lines) is not interrupted by it: the table + * says which (InterruptHandlerTable::starts_on()). A step that starts on + * a battle also starts on an UNSETTLED screen, a fade with no battle yet: + * that is its battle's opening, still playing (BDSP's Starly battle right + * after the starter is picked), and the step waits for it itself. + * + * Before another step, an unsettled screen that may be a battle's opening + * (a white flash, a fade still down, a fade after a dialog box) is looked + * at until its battle shows, up to max_opening_looks looks: the walk + * before the step ended in grass or in a trainer's sight. The battle is + * then cleared as any other. A fade that came back up with no box before + * it (a door's) is looked at max_looks times only. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryInterrupts_H +#define PokemonAutomation_Pokemon_StoryInterrupts_H + +#include +#include "Pokemon_InterruptHandlers.h" +#include "Pokemon_Interrupts.h" +#include "Pokemon_ScreenEvents.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_StoryStepExecutor.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How the screen looked at the end of a look: the line a run log needs to +// answer "had the scene ended before the step's first input?". +struct ScreenSettle{ + // Whether the look saw a frame at all. + bool seen = false; + // The events its last frame showed. + ScreenEvents showing = {}; + // How long the screen had shown them unchanged when the look ended. + Milliseconds quiet = Milliseconds(0); +}; +// The end of `look`: its last frame's events, and how long they held. +ScreenSettle judge_settle(const ScreenLook& look); +// Whether it ended on the HOME menu: the game is not running. +bool on_home_menu(const ScreenSettle& settle); +// Whether it ended on the overworld with no box, no fade and no battle. +bool is_settled(const ScreenSettle& settle); +// "settled overworld (quiet 0.3 s)", "black fade showing (quiet 0.1 s)", +// "Switch HOME menu (quiet 0.3 s)", "no frame seen". +std::string describe(const ScreenSettle& settle); + + +// What a look between steps found, and what clearing it came to. +struct InterruptCheck{ + // How the screen looked when the look ended, judged or not. + ScreenSettle screen = {}; + // NONE when nothing interrupted, or when the step starts on it. + InterruptVerdict verdict = {}; + // Failed when the look stayed unsettled, the kind had no handler, or + // the handler failed; GAME_NOT_RUNNING, with no verdict, when the + // look ended on the Switch's HOME menu. + Outcome outcome = {}; +}; + +// Looks at the screen before `step` (or after it failed) and clears what +// interrupted the player, if anything, writing the handler's effect on +// the pose into `state`. On the HOME menu it fails as GAME_NOT_RUNNING +// and clears nothing, whatever the step starts on. +InterruptCheck clear_story_interrupt(const StoryInterrupts& interrupts, const StoryStep& step, RunState& state); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp new file mode 100644 index 0000000000..e994e11745 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -0,0 +1,817 @@ +/* Story Interrupts Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The table executor's looks between steps, against a fake game: a + * scripted screen and handlers that note what they cleared. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryActions.h" +#include "Pokemon_StoryInterrupts.h" +#include "Pokemon_StoryInterrupts_Tests.h" +#include "Pokemon_StorySegments.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +const WallClock T0 = WallClock() + std::chrono::hours(1); + +// One frame of a scripted screen: its events, at `ms` after T0. +struct Frame{ + int ms; + ScreenEvents events; +}; + +const ScreenEvents WALK{ScreenEvent::PLAYER_CAN_MOVE}; +const ScreenEvents BOX{ScreenEvent::DIALOG_BOX, ScreenEvent::PLAYER_CAN_MOVE}; +const ScreenEvents WHITE{ScreenEvent::FADE_WHITE}; +const ScreenEvents BLACK{ScreenEvent::FADE_BLACK}; +const ScreenEvents BATTLE{ScreenEvent::BATTLE_STARTED}; +const ScreenEvents BANNER{ScreenEvent::LOCATION_BANNER, ScreenEvent::PLAYER_CAN_MOVE}; +// The Switch's HOME menu: the game is not running. +const ScreenEvents HOME{ScreenEvent::SWITCH_HOME_MENU}; + +// A look at `frames`, judged up to `until_ms`. +ScreenLook look_of(const std::vector& frames, int until_ms){ + ScreenLook look; + for (const Frame& frame : frames){ + look.log.record(frame.events, T0 + Milliseconds(frame.ms)); + } + look.window = {T0, T0 + Milliseconds(until_ms)}; + return look; +} + +ScreenLook quiet(){ + return look_of({{0, WALK}, {300, WALK}}, 300); +} +ScreenLook dialog(){ + return look_of({{0, WALK}, {100, BOX}}, 300); +} +ScreenLook wild(){ + return look_of({{0, WALK}, {100, WHITE}, {400, WALK}, {1500, BATTLE}}, 2000); +} +ScreenLook trainer(){ + return look_of({{0, WALK}, {100, BOX}, {2000, BLACK}, {2500, BATTLE}}, 3000); +} +ScreenLook warp(){ + return look_of({{0, WALK}, {100, BLACK}, {600, WALK}, {900, BANNER}}, 1200); +} +// A white fade with no battle yet: an encounter's flash or a cave exit. +ScreenLook white_unsettled(){ + return look_of({{0, WALK}, {100, WHITE}, {700, WALK}}, 1000); +} +// A trainer's lines, then the battle's black, still down: no battle yet. +ScreenLook trainer_opening(){ + return look_of({{0, WALK}, {100, BOX}, {2000, BLACK}}, 2100); +} +// A door's black, back up with no box before it: a warp, not yet settled. +ScreenLook black_unsettled(){ + return look_of({{0, WALK}, {100, BLACK}, {700, WALK}}, 1000); +} +// The same white, looked at for long enough after it: a cave exit. +ScreenLook white_settled(){ + return look_of({{0, WALK}, {100, WHITE}, {700, WALK}, {10000, WALK}}, 10000); +} +// The HOME menu, still: the program started with the game closed. +ScreenLook home_menu(){ + return look_of({{0, HOME}, {300, HOME}}, 300); +} +// The same, with a game's detectors reading it as the overworld too. +ScreenLook home_read_as_overworld(){ + ScreenEvents both = HOME; + both.set(ScreenEvent::PLAYER_CAN_MOVE, true); + return look_of({{0, both}}, 300); +} + + +// The fake game: the screen its looks show, one per look and then the +// last again, and a trace of what was looked at, cleared and run. +struct FakeGame{ + std::vector screens; + size_t looks = 0; + std::vector trace; + + ScreenLook look(bool fresh){ + trace.push_back(fresh ? "look" : "look again"); + const ScreenLook& out = screens.empty() ? quiet() : screens[std::min(looks, screens.size() - 1)]; + looks++; + return out; + } +}; + +// A handler that notes its kind; fails with `failure` if set. +InterruptHandler noting(std::string name, InterruptPose pose, std::string failure, FakeGame& game){ + return InterruptHandler{ + .handle = [&game, name, failure](const InterruptVerdict&, RunState&){ + game.trace.push_back(std::format("clear {}", name)); + return failure.empty() ? outcome_ok() : outcome_failed(failure); + }, + .pose = pose, + }; +} + +// All four handlers, a warp losing the pose; MASH starts on a dialog. +StoryInterrupts fake_interrupts(FakeGame& game){ + StoryInterrupts interrupts; + interrupts.look = [&game](bool fresh){ + return game.look(fresh); + }; + interrupts.handlers.add(InterruptKind::WILD_ENCOUNTER, noting("wild", InterruptPose::UNCHANGED, "", game)); + interrupts.handlers.add(InterruptKind::TRAINER_SIGHT, noting("trainer", InterruptPose::UNCHANGED, "", game)); + interrupts.handlers.add(InterruptKind::DIALOG, noting("dialog", InterruptPose::UNCHANGED, "", game)); + interrupts.handlers.add(InterruptKind::WARP, noting("warp", InterruptPose::LOST, "", game)); + interrupts.handlers.starts_on(StoryStepKind::MASH, InterruptKind::DIALOG); + return interrupts; +} + +StoryStep make(StoryStepKind kind, std::string name){ + StoryStep step; + step.kind = kind; + step.name = std::move(name); + return step; +} + +// The step's action: notes it ran, and fails its first `failures` runs, +// returning a failed Outcome or, with `throws`, throwing. +struct FakeAction{ + size_t failures = 0; + bool throws = false; +}; +StoryActionTable table_of(FakeAction action, FakeGame& game){ + StoryActionTable table; + auto runs = std::make_shared(0); + table.add_any_kind("act", StoryAction{ + .act = [&game, action, runs](const StoryStep& step, RunState&) -> Outcome{ + game.trace.push_back(std::format("run {}", step.name)); + if ((*runs)++ >= action.failures){ + return outcome_ok(); + } + if (action.throws){ + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, "stopped by a dialog"); + } + return outcome_failed("dialog", "stopped by a dialog"); + }, + }); + return table; +} + +// A guard that notes the interrupts it was told of. +class NotingGuard : public StepGuard{ +public: + explicit NotingGuard(FakeGame& game) + : m_game(game) + {} + virtual void on_interrupt(const StoryStep&, const InterruptCheck& check) override{ + m_game.trace.push_back(std::format("told {} {}", interrupt_kind_name(check.verdict.kind), to_string(check.outcome))); + } + +private: + FakeGame& m_game; +}; + +// `step` (action "act") run once by a TableExecutor with the fake +// game's interrupts, from a known pose. +struct FakeRun{ + Outcome outcome; + RunState state; +}; +FakeRun run_step(FakeGame& game, StoryInterrupts& interrupts, StoryStep step, FakeAction action = {}){ + const StoryActionTable table = table_of(action, game); + NotingGuard guard(game); + TableExecutor executor(table, guard); + executor.set_interrupts(&interrupts); + FakeRun out; + out.state.pose.map = "Town"; + out.state.pose.certainty = PoseCertainty::TILE; + step.action = "act"; + out.outcome = executor.run(step, out.state); + return out; +} + +UnitTestResult expect_trace(const FakeGame& game, const std::vector& expected){ + if (game.trace == expected){ + return true; + } + std::string out = "Expected the trace:"; + for (const std::string& line : expected){ + out += std::format("\n {}", line); + } + out += "\ngot:"; + for (const std::string& line : game.trace){ + out += std::format("\n {}", line); + } + return out; +} + + +UnitTestResult test_no_interrupts_set(){ + FakeGame game; + const StoryActionTable table = table_of({}, game); + StepGuard guard; + TableExecutor executor(table, guard); + RunState state; + StoryStep step = make(StoryStepKind::ROUTE, "walk"); + step.action = "act"; + const Outcome outcome = executor.run(step, state); + if (!outcome.succeeded()){ + return std::format("Expected the step to succeed, got {}", to_string(outcome)); + } + return expect_trace(game, {"run walk"}); +} + +UnitTestResult test_quiet_screen(){ + FakeGame game; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (!run.outcome.succeeded() || run.state.pose.certainty != PoseCertainty::TILE){ + return std::format("Expected the step to succeed where it stood, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "run walk"}); +} + +// A look showing `screen` before a ROUTE step: cleared by `handler`, then +// the step runs. +UnitTestResult test_cleared(ScreenLook screen, const std::string& kind, const std::string& handler, PoseCertainty pose){ + FakeGame game; + game.screens = {std::move(screen), quiet()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (!run.outcome.succeeded()){ + return std::format("Expected the step to succeed, got {}", to_string(run.outcome)); + } + if (run.state.pose.certainty != pose){ + return std::format("Expected the pose {}, got {}", certainty_name(pose), certainty_name(run.state.pose.certainty)); + } + return expect_trace(game, {"look", std::format("clear {}", handler), std::format("told {} ", kind), "run walk"}); +} + +UnitTestResult test_wild_encounter(){ + return test_cleared(wild(), "wild encounter", "wild", PoseCertainty::TILE); +} +UnitTestResult test_trainer_sight(){ + return test_cleared(trainer(), "trainer sight", "trainer", PoseCertainty::TILE); +} +UnitTestResult test_dialog(){ + return test_cleared(dialog(), "dialog", "dialog", PoseCertainty::TILE); +} +UnitTestResult test_warp(){ + return test_cleared(warp(), "warp", "warp", PoseCertainty::UNKNOWN); +} + +UnitTestResult test_step_starts_on_it(){ + FakeGame game; + game.screens = {dialog()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::MASH, "scene")); + if (!run.outcome.succeeded()){ + return std::format("Expected the step to succeed, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "run scene"}); +} + +UnitTestResult test_handler_fails_the_step(){ + FakeGame game; + game.screens = {dialog()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers = InterruptHandlerTable(); + interrupts.handlers.add(InterruptKind::DIALOG, noting("dialog", InterruptPose::UNCHANGED, "still_up", game)); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (run.outcome.failure != "interrupt_failed" || run.outcome.detail != "dialog: still_up"){ + return std::format("Expected interrupt_failed: dialog: still_up, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "clear dialog", "told dialog interrupt_failed: dialog: still_up"}); +} + +UnitTestResult test_unhandled_kind(){ + FakeGame game; + game.screens = {trainer()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers = InterruptHandlerTable(); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (run.outcome.failure != "unhandled_interrupt"){ + return std::format("Expected unhandled_interrupt, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "told trainer sight unhandled_interrupt: trainer sight before walk"}); +} + +UnitTestResult test_unsettled_looks_again(){ + FakeGame game; + game.screens = {white_unsettled(), white_settled(), quiet()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (!run.outcome.succeeded()){ + return std::format("Expected the step to succeed, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "look again", "clear warp", "told warp ", "run walk"}); +} + +// A door's fade is no battle's opening: three looks, as before. +UnitTestResult test_unsettled_is_bounded(){ + FakeGame game; + game.screens = {black_unsettled()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (run.outcome.failure != "interrupt_unsettled"){ + return std::format("Expected interrupt_unsettled, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "look again", "look again", "told unsettled interrupt_unsettled: walk"}); +} + +// A battle's opening still playing when a step that starts on a battle +// begins (BDSP's Starly battle, right after the starter is picked): the +// step's, on the first look, not interrupt_unsettled. +UnitTestResult test_unsettled_before_a_battle(){ + FakeGame game; + game.screens = {white_unsettled()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers.starts_on(StoryStepKind::BATTLE, InterruptKind::WILD_ENCOUNTER); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::BATTLE, "starly")); + if (!run.outcome.succeeded()){ + return std::format("Expected the battle step to run, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "run starly"}); +} + +// A battle's opening still playing when a walk step begins: the walk +// before it ended in grass or in a trainer's sight. The looks wait for the +// battle, past max_looks, +// and its handler clears it before the step. +UnitTestResult test_opening_before_a_walk(ScreenLook opening, ScreenLook battle, const std::string& kind, const std::string& handler){ + FakeGame game; + game.screens = {opening, opening, opening, opening, std::move(battle), quiet()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (!run.outcome.succeeded()){ + return std::format("Expected the walk to run after the battle, got {}", to_string(run.outcome)); + } + return expect_trace(game, { + "look", "look again", "look again", "look again", "look again", + std::format("clear {}", handler), std::format("told {} ", kind), "run walk", + }); +} +UnitTestResult test_wild_opening_before_a_walk(){ + return test_opening_before_a_walk(white_unsettled(), wild(), "wild encounter", "wild"); +} +UnitTestResult test_trainer_opening_before_a_walk(){ + return test_opening_before_a_walk(trainer_opening(), trainer(), "trainer sight", "trainer"); +} + +// A white that shows no battle and does not settle: max_opening_looks. +UnitTestResult test_opening_is_bounded(){ + FakeGame game; + game.screens = {white_unsettled()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.max_opening_looks = 5; + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (run.outcome.failure != "interrupt_unsettled"){ + return std::format("Expected interrupt_unsettled, got {}", to_string(run.outcome)); + } + return expect_trace(game, { + "look", "look again", "look again", "look again", "look again", + "told unsettled interrupt_unsettled: walk", + }); +} + +UnitTestResult test_failure_explained(bool throws){ + FakeGame game; + // Before the step, after its failure, before its second run. + game.screens = {quiet(), dialog(), quiet()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk"), {.failures = 1, .throws = throws}); + if (!run.outcome.succeeded()){ + return std::format("Expected the step run again and succeed, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "run walk", "look", "clear dialog", "told dialog ", "look", "run walk"}); +} +UnitTestResult test_failed_outcome_explained(){ + return test_failure_explained(false); +} +UnitTestResult test_thrown_failure_explained(){ + return test_failure_explained(true); +} + +UnitTestResult test_failure_not_explained(){ + FakeGame game; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk"), {.failures = 1}); + if (run.outcome.failure != "dialog"){ + return std::format("Expected the step's own failure, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "run walk", "look"}); +} + +// A step that keeps failing with a dialog that keeps coming back: run +// again while the dialogs are cleared, until there have been too many. +UnitTestResult test_too_many_interrupts(){ + FakeGame game; + game.screens = {dialog()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk"), {.failures = 10}); + if (run.outcome.failure != "dialog" || game.looks != interrupts.max_per_step + 1){ + return std::format("Expected the step's own failure after {} looks, got {} after {}", + interrupts.max_per_step + 1, to_string(run.outcome), game.looks); + } + if (game.trace.back() != "told dialog too_many_interrupts: walk"){ + return std::format("Expected the guard told of too many interrupts, got {}", game.trace.back()); + } + return true; +} + +UnitTestResult test_table_rejects(){ + InterruptHandlerTable table; + table.add(InterruptKind::DIALOG, {}); + for (InterruptKind kind : {InterruptKind::NONE, InterruptKind::UNSETTLED, InterruptKind::DIALOG}){ + try{ + table.add(kind, {}); + return std::format("Expected a handler for {} rejected.", interrupt_kind_name(kind)); + }catch (InternalProgramError&){} + } + if (table.find(InterruptKind::DIALOG) == nullptr || table.find(InterruptKind::WARP) != nullptr){ + return "Expected the dialog's handler found and no warp's."; + } + return true; +} + +// A guard that notes how the screen looked before each step. +class ScreenGuard : public StepGuard{ +public: + explicit ScreenGuard(FakeGame& game) + : m_game(game) + {} + virtual void on_screen(const StoryStep& step, const ScreenSettle& screen) override{ + m_game.trace.push_back(std::format("before {}: {}", step.name, describe(screen))); + } + +private: + FakeGame& m_game; +}; + +// The guard hears how the screen looked before every step, interrupt or +// not: the run log's answer to "had the scene ended before the input?". +UnitTestResult test_screen_before_each_step(){ + FakeGame game; + // A scene's closing fade still down: no battle comes, so the step + // fails unsettled, and the guard hears the fade was showing. + game.screens = {look_of({{0, WALK}, {100, BLACK}}, 300)}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.max_opening_looks = 2; + const StoryActionTable table = table_of({}, game); + ScreenGuard guard(game); + TableExecutor executor(table, guard); + executor.set_interrupts(&interrupts); + RunState state; + StoryStep step = make(StoryStepKind::ROUTE, "by_the_counter"); + step.action = "act"; + const Outcome faded = executor.run(step, state); + if (faded.succeeded()){ + return std::format("Expected a step in a fade to fail unsettled, got {}", to_string(faded)); + } + game.screens = {quiet()}; + game.looks = 0; + const Outcome settled = executor.run(step, state); + if (!settled.succeeded()){ + return std::format("Expected the step on a quiet screen to run, got {}", to_string(settled)); + } + return expect_trace(game, { + "look", "look again", "before by_the_counter: black fade showing (quiet 0.2 s)", + "look", "before by_the_counter: settled overworld (quiet 0.3 s)", "run by_the_counter", + }); +} + +// The program started with the game closed and the HOME menu showing. The +// screen is told as HOME and the step fails at once, before any input, +// and before a step that starts on a battle's opening too. +UnitTestResult test_home_menu_before_a_step(){ + for (StoryStepKind kind : {StoryStepKind::SAVE, StoryStepKind::ROUTE, StoryStepKind::BATTLE}){ + FakeGame game; + game.screens = {home_menu()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers.starts_on(StoryStepKind::BATTLE, InterruptKind::TRAINER_SIGHT); + const StoryActionTable table = table_of({}, game); + ScreenGuard guard(game); + TableExecutor executor(table, guard); + executor.set_interrupts(&interrupts); + RunState state; + StoryStep step = make(kind, "save"); + step.action = "act"; + const Outcome outcome = executor.run(step, state); + if (to_string(outcome) != "game_not_running: the game is not running: the Switch HOME menu is showing"){ + return std::format("Expected the step on HOME to fail as game_not_running, got {}", to_string(outcome)); + } + if (UnitTestResult trace = expect_trace(game, {"look", "before save: Switch HOME menu (quiet 0.3 s)"}); trace.result != UnitTestResult::PASSED){ + return trace; + } + } + return true; +} + +// A checkpoint that fails on the HOME menu is neither recovered in place +// nor reloaded: every press would go to the console's menus. +UnitTestResult test_home_menu_stops_the_segment(){ + std::vector trace; + CheckpointSpec spec; + spec.id = "00.03"; + spec.build = [&trace]{ + Checkpoint checkpoint; + checkpoint.id = "00.03"; + Event save; + save.name = "save"; + save.act = [&trace](RunState&){ + trace.push_back("save"); + return outcome_failed("game_not_running", "the game is not running: the Switch HOME menu is showing"); + }; + Recovery wait; + wait.kind = RecoveryKind::WAIT; + wait.prepare = [&trace](RunState&){ + trace.push_back("recover"); + return outcome_ok(); + }; + save.recoveries.push_back(std::move(wait)); + checkpoint.events.push_back(std::move(save)); + return checkpoint; + }; + Segment segment; + segment.id = "00"; + segment.checkpoints.push_back(std::move(spec)); + SegmentHooks hooks; + hooks.reload = [&trace](RunState&){ + trace.push_back("reload"); + return outcome_ok(); + }; + RunState state; + const SegmentReport report = run_segment(SegmentRange{}, SegmentPolicy{}, segment, hooks, state); + if (report.completed || report.failure.failure != "game_not_running" || report.reloads != 0){ + return std::format("Expected the segment to stop on game_not_running with no reload, got {}", to_string(report.failure)); + } + if (trace != std::vector{"save"}){ + std::string got; + for (const std::string& line : trace){ + got += std::format(" {}", line); + } + return std::format("Expected the save tried once and nothing else, got:{}", got); + } + return true; +} + +// A handler that drives the console can lose it. That fails the step as +// interrupt_failed, like a handler that returns a failure: it must not +// escape the executor, and the step is not run. +UnitTestResult test_handler_throws(){ + FakeGame game; + game.screens = {dialog()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers = InterruptHandlerTable(); + interrupts.handlers.add(InterruptKind::DIALOG, InterruptHandler{ + .handle = [&game](const InterruptVerdict&, RunState&) -> Outcome{ + game.trace.push_back("clear dialog"); + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, "the console is gone"); + }, + .pose = InterruptPose::UNCHANGED, + }); + try{ + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (run.outcome.failure != "interrupt_failed"){ + return std::format("Expected interrupt_failed, got {}", to_string(run.outcome)); + } + }catch (OperationFailedException& e){ + return std::format("The handler's failure escaped the executor: {}", e.message()); + } + return expect_trace(game, {"look", "clear dialog", "told dialog interrupt_failed: dialog: operation_failed: the console is gone"}); +} + +// The same loss after a step failed, while the executor looks for what +// explains the failure: the step's own failure is kept. +UnitTestResult test_handler_throws_after_a_failure(){ + FakeGame game; + game.screens = {quiet(), dialog()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers = InterruptHandlerTable(); + interrupts.handlers.add(InterruptKind::DIALOG, InterruptHandler{ + .handle = [&game](const InterruptVerdict&, RunState&) -> Outcome{ + game.trace.push_back("clear dialog"); + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, "the console is gone"); + }, + .pose = InterruptPose::UNCHANGED, + }); + try{ + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk"), FakeAction{.failures = 1}); + if (run.outcome.failure != "dialog"){ + return std::format("Expected the step's own failure, got {}", to_string(run.outcome)); + } + }catch (OperationFailedException& e){ + return std::format("The handler's failure escaped the executor: {}", e.message()); + } + return true; +} + +// A step that fails and then shows the HOME menu did not fail on its own: +// the game is not running, so the segment must stop instead of recovering +// or reloading with the game closed. +UnitTestResult test_home_menu_after_a_failed_step(){ + for (bool throws : {false, true}){ + FakeGame game; + game.screens = {quiet(), home_menu()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk"), FakeAction{.failures = 1, .throws = throws}); + if (run.outcome.failure != "game_not_running"){ + return std::format("Expected game_not_running after a step that {} and then showed HOME, got {}", + throws ? "threw" : "failed", to_string(run.outcome)); + } + const size_t runs = static_cast(std::count(game.trace.begin(), game.trace.end(), "run walk")); + if (runs != 1){ + return std::format("Expected the step run once, got {} runs", runs); + } + } + return true; +} + +UnitTestResult test_settle_of_a_look(){ + struct Row{ + std::string name; + ScreenLook look; + std::string expected; + }; + const std::vector rows = { + {"no frame", ScreenLook{}, "no frame seen"}, + {"a quiet overworld", quiet(), "settled overworld (quiet 0.3 s)"}, + {"a box", dialog(), "dialog box, player can move showing (quiet 0.2 s)"}, + {"a door's fade back up", black_unsettled(), "settled overworld (quiet 0.3 s)"}, + {"the HOME menu", home_menu(), "Switch HOME menu (quiet 0.3 s)"}, + {"HOME read as a quiet overworld too", home_read_as_overworld(), "Switch HOME menu (quiet 0.3 s)"}, + }; + for (const Row& row : rows){ + const std::string got = describe(judge_settle(row.look)); + if (got != row.expected){ + return std::format("{}: expected \"{}\", got \"{}\"", row.name, row.expected, got); + } + } + return true; +} + + +struct StoryInterruptsCase{ + struct Input{ + std::string_view name; + UnitTestResult (*test)(); + }; + + struct Expectation{ + std::string_view description; + }; + + Input input; + Expectation expectation; +}; + +class Test_StoryInterrupts : public UnitTest{ +public: + explicit Test_StoryInterrupts(StoryInterruptsCase scenario) + : UnitTest(std::format("Pokemon::StoryInterrupts - {}", scenario.input.name)) + , m_scenario(scenario) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.input.test(); + } + +private: + StoryInterruptsCase m_scenario; +}; + +const StoryInterruptsCase STORY_INTERRUPTS_CASES[] = { + { + .input = {.name = "no interrupts set: no look", .test = test_no_interrupts_set}, + .expectation = {.description = "the executor runs the step as before"}, + }, + { + .input = {.name = "a quiet screen: one look, then the step", .test = test_quiet_screen}, + .expectation = {.description = "nothing cleared, the pose kept"}, + }, + { + .input = {.name = "a wild encounter before a step", .test = test_wild_encounter}, + .expectation = {.description = "the wild handler, then the step"}, + }, + { + .input = {.name = "a trainer's sight before a step", .test = test_trainer_sight}, + .expectation = {.description = "the trainer handler, then the step"}, + }, + { + .input = {.name = "a dialog before a step", .test = test_dialog}, + .expectation = {.description = "the dialog handler, then the step"}, + }, + { + .input = {.name = "a warp before a step", .test = test_warp}, + .expectation = {.description = "the warp handler, the pose lost, then the step"}, + }, + { + .input = {.name = "a step that starts on it", .test = test_step_starts_on_it}, + .expectation = {.description = "a MASH's box is the step's, not an interrupt"}, + }, + { + .input = {.name = "a handler that fails fails the step", .test = test_handler_fails_the_step}, + .expectation = {.description = "interrupt_failed, the step not run"}, + }, + { + .input = {.name = "a kind with no handler fails the step", .test = test_unhandled_kind}, + .expectation = {.description = "unhandled_interrupt, the step not run"}, + }, + { + .input = {.name = "unsettled: look again until it settles", .test = test_unsettled_looks_again}, + .expectation = {.description = "a white with no battle after it is a warp"}, + }, + { + .input = {.name = "unsettled: at most max_looks looks", .test = test_unsettled_is_bounded}, + .expectation = {.description = "a door's fade: interrupt_unsettled after three looks"}, + }, + { + .input = {.name = "unsettled: a battle's opening before a battle step", .test = test_unsettled_before_a_battle}, + .expectation = {.description = "the step's, after one look"}, + }, + { + .input = {.name = "unsettled: a wild battle's opening before a walk", .test = test_wild_opening_before_a_walk}, + .expectation = {.description = "waits for the battle, clears it, then the walk"}, + }, + { + .input = {.name = "unsettled: a trainer battle's opening before a walk", .test = test_trainer_opening_before_a_walk}, + .expectation = {.description = "waits for the battle, fights it, then the walk"}, + }, + { + .input = {.name = "unsettled: at most max_opening_looks for an opening", .test = test_opening_is_bounded}, + .expectation = {.description = "a white with no battle: interrupt_unsettled"}, + }, + { + .input = {.name = "a failed step an interrupt explains runs again", .test = test_failed_outcome_explained}, + .expectation = {.description = "cleared after the failure, then the step again"}, + }, + { + .input = {.name = "a thrown step an interrupt explains runs again", .test = test_thrown_failure_explained}, + .expectation = {.description = "the console's failure too"}, + }, + { + .input = {.name = "a failed step with nothing on screen fails", .test = test_failure_not_explained}, + .expectation = {.description = "the step's own failure, run once"}, + }, + { + .input = {.name = "too many interrupts fail the step", .test = test_too_many_interrupts}, + .expectation = {.description = "the step's failure once max_per_step are cleared"}, + }, + { + .input = {.name = "table: one handler a kind that can be cleared", .test = test_table_rejects}, + .expectation = {.description = "rejects NONE, UNSETTLED and a second handler"}, + }, + { + .input = {.name = "the screen before each step, for the log", .test = test_screen_before_each_step}, + .expectation = {.description = "a fade still down is told, and fails unsettled; a quiet overworld is settled"}, + }, + { + .input = {.name = "how a look ended", .test = test_settle_of_a_look}, + .expectation = {.description = "the last frame's events and how long they held"}, + }, + { + .input = {.name = "the HOME menu before a step", .test = test_home_menu_before_a_step}, + .expectation = {.description = "told as HOME; game_not_running before any input"}, + }, + { + .input = {.name = "the HOME menu stops the segment", .test = test_home_menu_stops_the_segment}, + .expectation = {.description = "no recovery in place, no reload"}, + }, + { + .input = {.name = "a handler that throws fails the step", .test = test_handler_throws}, + .expectation = {.description = "interrupt_failed, the step not run, nothing escapes"}, + }, + { + .input = {.name = "a handler that throws after a failed step", .test = test_handler_throws_after_a_failure}, + .expectation = {.description = "the step's own failure, nothing escapes"}, + }, + { + .input = {.name = "the HOME menu after a failed step", .test = test_home_menu_after_a_failed_step}, + .expectation = {.description = "game_not_running instead of the step's failure, run once"}, + }, +}; + +} // namespace + + +void add_tests_StoryInterrupts(UnitTestDatabase& database){ + for (const StoryInterruptsCase& scenario : STORY_INTERRUPTS_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.h new file mode 100644 index 0000000000..4ba110b077 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.h @@ -0,0 +1,23 @@ +/* Story Interrupts Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryInterrupts_Tests_H +#define PokemonAutomation_Pokemon_StoryInterrupts_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the table executor's looks for interrupts between steps. +void add_tests_StoryInterrupts(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp new file mode 100644 index 0000000000..5266a751e7 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp @@ -0,0 +1,108 @@ +/* AutoStory Story Preflight + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTools/FloatPixel.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" +#include "Pokemon_StoryPreflight.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +using namespace std::chrono_literals; + + +namespace{ + +// Color bars are seven flat vertical stripes of different colors. +constexpr size_t BAR_COUNT = 7; +// Each stripe is sampled in its middle, away from its edges: inset by this +// fraction of its width on each side, and from the top for this fraction of +// the frame's height. +constexpr double BAR_INSET = 0.25; +constexpr double BAR_TOP = 0.1; +constexpr double BAR_HEIGHT = 0.5; +// A stripe flatter than this (stddev sum) is one solid color. +constexpr double BAR_MAX_STDDEV = 30; +// Two stripes this far apart (RGB distance) are different bars. +constexpr double BAR_MIN_DISTANCE = 60; +// A frame older than this is a stalled feed. +constexpr auto FRAME_MAX_AGE = 2000ms; + +bool shows_color_bars(const ImageViewRGB32& frame){ + std::array bars; + for (size_t c = 0; c < BAR_COUNT; c++){ + const double width = 1.0 / BAR_COUNT; + const ImageFloatBox stripe(c * width + width * BAR_INSET, BAR_TOP, width * (1 - 2 * BAR_INSET), BAR_HEIGHT); + const ImageStats stats = image_stats(extract_box_reference(frame, stripe)); + if (stats.stddev.sum() > BAR_MAX_STDDEV){ + return false; + } + bars[c] = stats.average; + } + for (size_t c = 1; c < BAR_COUNT; c++){ + if (euclidean_distance(bars[c - 1], bars[c]) < BAR_MIN_DISTANCE){ + return false; + } + } + return true; +} + +bool frame_shows_picture(const ImageViewRGB32& frame){ + if (!frame){ + return false; + } + if (is_black(frame)){ + return false; + } + return !shows_color_bars(frame); +} + +} // namespace + +StoryPreflight StoryPreflight::read(NintendoSwitch::ConsoleHandle& console, NintendoSwitch::ProControllerContext& context){ + StoryPreflight preflight; + preflight.controller_ready = context.controller().is_ready(); + const VideoSnapshot snapshot = console.video().snapshot(); + const bool fresh = snapshot && current_time() - snapshot.timestamp < FRAME_MAX_AGE; + preflight.video_alive = fresh && frame_shows_picture(snapshot); + preflight.game_running = preflight.video_alive + && !NintendoSwitch::HomeMenuDetector(console, COLOR_RED).detect(snapshot); + return preflight; +} + + +Outcome StoryPreflight::check() const{ + std::string failed; + auto add = [&failed](bool ok, std::string_view what){ + if (ok){ + return; + } + if (!failed.empty()){ + failed += "; "; + } + failed += what; + }; + add(video_alive, "no live video"); + add(controller_ready, "the controller is not ready"); + add(game_running, "the game is not running"); + if (failed.empty()){ + return outcome_ok(); + } + return outcome_failed(std::string(FAILURE), failed); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.h new file mode 100644 index 0000000000..d9aa65f158 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.h @@ -0,0 +1,50 @@ +/* AutoStory Story Preflight + * + * From: https://github.com/PokemonAutomation/ + * + * What the story run's preflight hook (StoryGameHooks::preflight) reads + * off the console before anything is pressed, and its verdict. The same + * for every game, so BDSP and FRLG lend the same reader. The start + * sequence that runs it is in Pokemon_StoryRun.h. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryPreflight_H +#define PokemonAutomation_Pokemon_StoryPreflight_H + +#include +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "Pokemon_StoryOutcome.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What a game reads off the console before a run presses anything. +struct StoryPreflight{ + // The failure of a preflight that failed: the console or its setup, + // not the story. Nothing answers it with a reload or a recovery. + static constexpr std::string_view FAILURE = "precondition_failed"; + + // Frames are arriving and show a picture (not black, not color bars). + bool video_alive = false; + bool controller_ready = false; + // The game is on screen, not the Switch's HOME menu. + bool game_running = false; + + // outcome_ok() when every check passed, else FAILURE naming each + // check that failed. + Outcome check() const; + + // Reads the console: a frame newer than two seconds that shows a + // picture (not black, not the capture card's color bars), the + // controller ready, and that frame not the HOME menu. Presses nothing. + static StoryPreflight read(NintendoSwitch::ConsoleHandle& console, NintendoSwitch::ProControllerContext& context); +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp new file mode 100644 index 0000000000..01f939df17 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp @@ -0,0 +1,160 @@ +/* AutoStory Story Run + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryRun.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// "its save", "a new game", "the game as it is": for the start line. +std::string_view story_start_name(StoryStart start){ + switch (start){ + case StoryStart::NEW_GAME: + return "a new game"; + case StoryStart::LIVE: + return "the game as it is"; + case StoryStart::FROM_SAVE: + return "its save"; + } + return "?"; +} + +void log_line(const std::string& line, StoryGameHooks& game){ + if (game.log){ + game.log(line); + } +} + +std::string story_stop_message(const SegmentReport& report){ + if (report.completed){ + return ""; + } + return std::format( + "AutoStory stopped at {} {}: {}", + report.failed_checkpoint, report.failed_event, to_string(report.failure) + ); +} + +std::string story_verify_summary(std::string_view checkpoint, const VerifyPolicy& policy, const VerifyReport& report){ + return std::format( + "AutoStory verify: {} {}/{} passed, {} needed.", checkpoint, report.passes, policy.runs, policy.passes_needed + ); +} + +Outcome run_story_preflight(StoryGameHooks& game){ + if (!game.preflight){ + log_line("[Story] preflight: not checked: the game has no preflight", game); + return outcome_ok(); + } + const Outcome outcome = game.preflight().check(); + if (!outcome.succeeded()){ + log_line(std::format("[Story] preflight failed, nothing pressed: {}", outcome.detail), game); + } + return outcome; +} + +Outcome load_story_save(std::string_view reason, StoryGameHooks& game, RunState& state){ + log_line(std::format("[Story] {}: loading the save", reason), game); + Outcome outcome = game.load_save(state); + if (outcome.succeeded() && game.check_save_place){ + const std::string error = game.check_save_place(); + if (!error.empty()){ + outcome = outcome_failed("wrong_save", error); + } + } + if (outcome.succeeded() && game.after_load){ + outcome = game.after_load(state); + } + if (!outcome.succeeded()){ + log_line(std::format("[Story] {}", to_string(outcome)), game); + } + return outcome; +} + +} // namespace + +Outcome prepare_story_start(std::string_view checkpoint, StoryStart start, StoryGameHooks& game, RunState& state){ + log_line(std::format("[Story] start: checkpoint {}, from {}", checkpoint, story_start_name(start)), game); + const Outcome preflight = run_story_preflight(game); + if (!preflight.succeeded()){ + return preflight; + } + switch (start){ + case StoryStart::NEW_GAME: + log_line(std::format("[Story] {}: starts a new game, no save to load", checkpoint), game); + return outcome_ok(); + case StoryStart::LIVE: + log_line(std::format("[Story] {}: starts from the game as it is, no save to load", checkpoint), game); + return outcome_ok(); + case StoryStart::FROM_SAVE: + break; + } + Outcome outcome = load_story_save(checkpoint, game, state); + if (outcome.succeeded()){ + state.flags.insert("save_loaded"); + } + return outcome; +} + +SegmentHooks story_segment_hooks(StoryGameHooks& game){ + SegmentHooks hooks; + hooks.reload = [&game](RunState& state){ + return load_story_save("retry", game, state); + }; + hooks.save = [&game](RunState& state){ + if (!game.save){ + return outcome_failed("no_save_hook", "this game's rows save at their start"); + } + return game.save(state); + }; + hooks.log = [&game](const std::string& line){ + log_line(line, game); + }; + hooks.status = [&game](const std::string& line){ + if (game.status){ + game.status(line); + } + }; + return hooks; +} + +void log_story_failure(StoryGameHooks& game){ + log_line(std::string(STORY_LEFT_WHERE_FAILED), game); +} + +std::string finish_story_run(const SegmentReport& report, std::string_view last, AutoStoryStats& stats, StoryGameHooks& game){ + record_story_counts(report.story_counts(), stats); + if (!report.completed){ + log_story_failure(game); + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, story_stop_message(report)); + } + std::string done = std::format("AutoStory: done through {}.", last); + log_line(done, game); + return done; +} + +std::string finish_story_verify( + std::string_view checkpoint, const VerifyPolicy& policy, const VerifyReport& report, StoryGameHooks& game +){ + std::string summary = story_verify_summary(checkpoint, policy, report); + if (!report.verified){ + log_story_failure(game); + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, summary); + } + log_line(summary, game); + return summary; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h new file mode 100644 index 0000000000..d888b9f73d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h @@ -0,0 +1,100 @@ +/* AutoStory Story Run + * + * From: https://github.com/PokemonAutomation/ + * + * The start and finish of a story run: get the + * game to the start checkpoint, lend the segment runner its reload, and + * finish a run or a verify run with the same log lines, stats and errors. + * A game lends only what really differs: how it loads its save (BDSP + * resets from HOME, FRLG soft-resets) and how it checks where the save is. + * + * These rules hold for every game: + * - Before anything is pressed, the game's preflight must see the video + * alive, the controller ready and the game running (not HOME). One + * that fails is the setup's failure, not the story's: nothing is + * touched. + * - A run that starts at a checkpoint with a save loads that save first, + * so it never walks from wherever the game was left. There is no + * "just loaded" shortcut: a load or place check that fails stops the + * run before anything is saved. + * - The first checkpoint's own save at its start runs only for a new + * game: after a load the save is already there, and from the game as + * it is the place is unconfirmed (the game may be on the HOME + * menu). + * - A failure leaves the game where it failed. Nothing here closes the + * game; the user (or the next run from the save) resumes from there. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRun_H +#define PokemonAutomation_Pokemon_StoryRun_H + +#include +#include +#include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_AutoStoryStats.h" +#include "Pokemon_StoryCheckpointTypes.h" +#include "Pokemon_StoryOutcome.h" +#include "Pokemon_StorySegments.h" +#include "Pokemon_StoryPreflight.h" +#include "Types/Pokemon_StoryStart.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What a game lends the story run. +struct StoryGameHooks{ + // Reads the console before anything else (see StoryPreflight). Without + // it the run logs that nothing was checked. + MoveOnlyFunction preflight; + // Loads the last save: the game reset (from HOME or soft) and back in + // the overworld. A failed Outcome says why. + Act load_save; + // Optional: after a load, "" when the save is where the checkpoint + // about to run starts, else why not. + MoveOnlyFunction check_save_place; + // Optional: after a load and its place check, rereads what the save + // holds (FRLG: the bag's supplies). + Act after_load; + // Optional: saves the game (rows that save at their end). + Act save; + EventLogger log; + // Optional: the step under way, for the video overlay. + EventLogger status; +}; + +// The line logged after any failure. +inline constexpr std::string_view STORY_LEFT_WHERE_FAILED = "AutoStory failed: the game stays where it failed."; + +// Gets the game to where checkpoint `checkpoint` starts, as `start` says. +// First logs the checkpoint starting ("[Story] start: checkpoint 00.04b, +// from its save") and runs the game's preflight; one that fails returns +// StoryPreflight::FAILURE with nothing pressed. FROM_SAVE then always +// loads the save (logging "[Story] 00.04b: loading the save"), checks its +// place and rereads it, and sets the "save_loaded" flag. +Outcome prepare_story_start(std::string_view checkpoint, StoryStart start, StoryGameHooks& game, RunState& state); + +// The runner's hooks: reload is load_story_save(); save, log and status +// are the game's. `game` must outlive them. +SegmentHooks story_segment_hooks(StoryGameHooks& game); + +// Ends a run: its counts into `stats`, then the failure line and an +// OperationFailedException if it stopped short, else "AutoStory: done +// through ." Returns that line, for the finish notification. +std::string finish_story_run(const SegmentReport& report, std::string_view last, AutoStoryStats& stats, StoryGameHooks& game); + +// Ends a verify run: the summary, and the failure line and an +// OperationFailedException unless verified. Returns the summary. +std::string finish_story_verify( + std::string_view checkpoint, const VerifyPolicy& policy, const VerifyReport& report, StoryGameHooks& game +); + +// The failure line, for a game whose run threw before the story run saw it. +void log_story_failure(StoryGameHooks& game); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp new file mode 100644 index 0000000000..b1c187331b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp @@ -0,0 +1,497 @@ +/* AutoStory Story Run Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryRun.h" +#include "Pokemon_StoryRun_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +// A game that records what the story run asked of it. +struct FakeGame{ + StoryPreflight preflight{.video_alive = true, .controller_ready = true, .game_running = true}; + std::string place_error; + size_t loads = 0; + size_t rereads = 0; + size_t saves = 0; + std::vector lines; + + StoryGameHooks hooks(){ + StoryGameHooks game; + game.preflight = [this]{ + return preflight; + }; + game.load_save = [this](RunState&){ + loads++; + return outcome_ok(); + }; + game.check_save_place = [this]{ + return place_error; + }; + game.after_load = [this](RunState&){ + rereads++; + return outcome_ok(); + }; + game.save = [this](RunState&){ + saves++; + return outcome_ok(); + }; + game.log = [this](const std::string& line){ + lines.push_back(line); + }; + return game; + } + bool logged(std::string_view line) const{ + for (const std::string& logged_line : lines){ + if (logged_line == line){ + return true; + } + } + return false; + } +}; + +// A start as the program asks for it, and what the game must have done. +struct StartCase{ + struct Input{ + std::string name; + StoryStart start; + std::string place_error; + StoryPreflight preflight; + }; + struct Expectation{ + bool succeeds; + size_t loads; + size_t rereads; + bool save_loaded; + }; + Input input; + Expectation expectation; +}; + +constexpr StoryPreflight READY{.video_alive = true, .controller_ready = true, .game_running = true}; +constexpr StoryPreflight ON_HOME{.video_alive = true, .controller_ready = true, .game_running = false}; +constexpr StoryPreflight NO_VIDEO{.video_alive = false, .controller_ready = true, .game_running = true}; +constexpr StoryPreflight NO_CONTROLLER{.video_alive = true, .controller_ready = false, .game_running = true}; + +std::string_view start_name(StoryStart start){ + switch (start){ + case StoryStart::NEW_GAME: + return "a new game"; + case StoryStart::LIVE: + return "the game as it is"; + case StoryStart::FROM_SAVE: + return "its save"; + } + return "?"; +} + +class Test_StoryStart : public UnitTest{ +public: + Test_StoryStart(StartCase test_case) + : UnitTest(std::format("Pokemon::StoryRun - start: {}", test_case.input.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + FakeGame fake; + fake.place_error = m_case.input.place_error; + fake.preflight = m_case.input.preflight; + StoryGameHooks game = fake.hooks(); + RunState state; + const Outcome outcome = prepare_story_start("00.04b", m_case.input.start, game, state); + const bool save_loaded = state.flags.contains("save_loaded"); + if (outcome.succeeded() != m_case.expectation.succeeds || fake.loads != m_case.expectation.loads + || fake.rereads != m_case.expectation.rereads || save_loaded != m_case.expectation.save_loaded + ){ + return std::format( + "Expected ok={} loads={} rereads={} save_loaded={}, got {} {} {} {} ({})", + m_case.expectation.succeeds, m_case.expectation.loads, m_case.expectation.rereads, m_case.expectation.save_loaded, + outcome.succeeded(), fake.loads, fake.rereads, save_loaded, to_string(outcome) + ); + } + if (!fake.logged(std::format("[Story] start: checkpoint 00.04b, from {}", start_name(m_case.input.start)))){ + return "Expected the line naming the checkpoint that starts"; + } + if (!m_case.input.preflight.game_running && outcome.failure != StoryPreflight::FAILURE){ + return std::format("Expected {}, got {}", StoryPreflight::FAILURE, to_string(outcome)); + } + return true; + } + +private: + const StartCase m_case; +}; + +const StartCase START_CASES[] = { + // A game left at a later checkpoint must not be walked from: a + // checkpoint with a save loads that save first. + { + .input = {.name = "a checkpoint with a save loads it first", .start = StoryStart::FROM_SAVE, .place_error = "", .preflight = READY}, + .expectation = {.succeeds = true, .loads = 1, .rereads = 1, .save_loaded = true}, + }, + { + .input = {.name = "a save in the wrong place fails before rereading it", .start = StoryStart::FROM_SAVE, .place_error = "The save is in Pewter City.", .preflight = READY}, + .expectation = {.succeeds = false, .loads = 1, .rereads = 0, .save_loaded = false}, + }, + { + .input = {.name = "a new game loads nothing", .start = StoryStart::NEW_GAME, .place_error = "", .preflight = READY}, + .expectation = {.succeeds = true, .loads = 0, .rereads = 0, .save_loaded = false}, + }, + { + .input = {.name = "a live start loads nothing", .start = StoryStart::LIVE, .place_error = "", .preflight = READY}, + .expectation = {.succeeds = true, .loads = 0, .rereads = 0, .save_loaded = false}, + }, + // The game is on the HOME menu: every press would go to the console's + // menus, so the preflight stops the run before any press. + { + .input = {.name = "the HOME menu stops the run before the load", .start = StoryStart::FROM_SAVE, .place_error = "", .preflight = ON_HOME}, + .expectation = {.succeeds = false, .loads = 0, .rereads = 0, .save_loaded = false}, + }, + { + .input = {.name = "the HOME menu stops a live start", .start = StoryStart::LIVE, .place_error = "", .preflight = ON_HOME}, + .expectation = {.succeeds = false, .loads = 0, .rereads = 0, .save_loaded = false}, + }, + { + .input = {.name = "dead video stops the run before the load", .start = StoryStart::FROM_SAVE, .place_error = "", .preflight = NO_VIDEO}, + .expectation = {.succeeds = false, .loads = 0, .rereads = 0, .save_loaded = false}, + }, + { + .input = {.name = "a controller not ready stops the run before the load", .start = StoryStart::FROM_SAVE, .place_error = "", .preflight = NO_CONTROLLER}, + .expectation = {.succeeds = false, .loads = 0, .rereads = 0, .save_loaded = false}, + }, +}; + + +// A preflight's checks, and the failure it reads as: the setup's, not +// the story's, naming every check that failed. +struct PreflightCase{ + struct Input{ + std::string name; + StoryPreflight preflight; + }; + struct Expectation{ + std::string outcome; + }; + Input input; + Expectation expectation; +}; + +class Test_StoryPreflight : public UnitTest{ +public: + Test_StoryPreflight(PreflightCase test_case) + : UnitTest(std::format("Pokemon::StoryRun - preflight: {}", test_case.input.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string got = to_string(m_case.input.preflight.check()); + if (got != m_case.expectation.outcome){ + return std::format("Expected \"{}\", got \"{}\"", m_case.expectation.outcome, got); + } + return true; + } + +private: + const PreflightCase m_case; +}; + +const PreflightCase PREFLIGHT_CASES[] = { + {.input = {.name = "a ready console passes", .preflight = READY}, .expectation = {.outcome = ""}}, + { + .input = {.name = "the HOME menu", .preflight = ON_HOME}, + .expectation = {.outcome = "precondition_failed: the game is not running"}, + }, + { + .input = {.name = "every check failed", .preflight = StoryPreflight{}}, + .expectation = {.outcome = "precondition_failed: no live video; the controller is not ready; the game is not running"}, + }, +}; + + +// Whether the first checkpoint saves at its start: only a new game's. After +// a load the save is already there; from the game as it is the place is +// unconfirmed (the game may be on the HOME menu). +struct FirstSaveCase{ + struct Input{ + StoryStart start; + }; + struct Expectation{ + bool saves; + }; + Input input; + Expectation expectation; +}; + +class Test_StoryFirstSave : public UnitTest{ +public: + Test_StoryFirstSave(FirstSaveCase test_case) + : UnitTest(std::format("Pokemon::StoryRun - first save: {}", start_name(test_case.input.start))) + , m_case(test_case) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + if (story_first_save_allowed(m_case.input.start) != m_case.expectation.saves){ + return std::format("Expected saves={} from {}", m_case.expectation.saves, start_name(m_case.input.start)); + } + return true; + } + +private: + const FirstSaveCase m_case; +}; + +const FirstSaveCase FIRST_SAVE_CASES[] = { + {.input = {.start = StoryStart::NEW_GAME}, .expectation = {.saves = true}}, + {.input = {.start = StoryStart::FROM_SAVE}, .expectation = {.saves = false}}, + {.input = {.start = StoryStart::LIVE}, .expectation = {.saves = false}}, +}; + + +// A failed attempt's reload loads the save through the game. +struct ReloadCase{ + struct Input{ + std::string name; + }; + struct Expectation{ + size_t loads; + size_t rereads; + std::string log_line; + }; + Input input; + Expectation expectation; +}; + +class Test_StoryReload : public UnitTest{ +public: + Test_StoryReload(const ReloadCase& test_case) + : UnitTest(std::format("Pokemon::StoryRun - {}", test_case.input.name)) + , m_case(test_case) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + FakeGame fake; + StoryGameHooks game = fake.hooks(); + SegmentHooks hooks = story_segment_hooks(game); + RunState state; + const Outcome outcome = hooks.reload(state); + const ReloadCase::Expectation& expected = m_case.expectation; + if (!outcome.succeeded() || fake.loads != expected.loads || fake.rereads != expected.rereads || !fake.logged(expected.log_line)){ + return std::format("Expected {} load and {} reread, got {} and {} ({})", expected.loads, expected.rereads, fake.loads, fake.rereads, to_string(outcome)); + } + return true; + } + +private: + const ReloadCase m_case; +}; + +const ReloadCase RELOAD_CASES[] = { + { + .input = {.name = "a retry reloads the save"}, + .expectation = {.loads = 1, .rereads = 1, .log_line = "[Story] retry: loading the save"}, + }, +}; + + +// A run that stopped short throws, logs the failure line and touches +// nothing in the game: no reload, no save, no reset to HOME. +struct FailureCase{ + struct Input{ + std::string name; + std::string checkpoint; + std::string event; + std::string stopped_after; + }; + struct Expectation{ + std::string message; + }; + Input input; + Expectation expectation; +}; + +class Test_StoryFailureLeavesGame : public UnitTest{ +public: + Test_StoryFailureLeavesGame(const FailureCase& test_case) + : UnitTest(std::format("Pokemon::StoryRun - {}", test_case.input.name)) + , m_case(test_case) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + FakeGame fake; + StoryGameHooks game = fake.hooks(); + SegmentReport report; + report.completed = false; + report.failed_checkpoint = m_case.input.checkpoint; + report.failed_event = m_case.input.event; + report.failure = outcome_failed("expect_failed", "dialogue opened"); + AutoStoryStats stats; + std::string message; + try{ + finish_story_run(report, m_case.input.stopped_after, stats, game); + return "Expected an OperationFailedException"; + }catch (OperationFailedException& e){ + message = e.message(); + } + if (message != m_case.expectation.message){ + return std::format("Unexpected message: {}", message); + } + if (!fake.logged(STORY_LEFT_WHERE_FAILED)){ + return "Expected the failure line"; + } + if (fake.loads != 0 || fake.saves != 0){ + return std::format("Expected the game untouched, got {} loads and {} saves", fake.loads, fake.saves); + } + return true; + } + +private: + const FailureCase m_case; +}; + +const FailureCase FAILURE_CASES[] = { + { + .input = {.name = "a failed run leaves the game where it failed", .checkpoint = "00.04b", .event = "talk_mom", .stopped_after = "00.05"}, + .expectation = {.message = "AutoStory stopped at 00.04b talk_mom: expect_failed: dialogue opened"}, + }, +}; + + +// A completed run logs and returns the line the finish notification sends. +struct FinishedCase{ + struct Input{ + std::string name; + std::string last_checkpoint; + }; + struct Expectation{ + std::string line; + }; + Input input; + Expectation expectation; +}; + +class Test_StoryFinished : public UnitTest{ +public: + Test_StoryFinished(const FinishedCase& test_case) + : UnitTest(std::format("Pokemon::StoryRun - {}", test_case.input.name)) + , m_case(test_case) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + FakeGame fake; + StoryGameHooks game = fake.hooks(); + SegmentReport report; + report.completed = true; + AutoStoryStats stats; + const std::string done = finish_story_run(report, m_case.input.last_checkpoint, stats, game); + if (done != m_case.expectation.line || !fake.logged(done)){ + return std::format("Unexpected finish line: {}", done); + } + return true; + } + +private: + const FinishedCase m_case; +}; + +const FinishedCase FINISHED_CASES[] = { + { + .input = {.name = "a completed run is done through its last checkpoint", .last_checkpoint = "00.05"}, + .expectation = {.line = "AutoStory: done through 00.05."}, + }, +}; + + +// A verify run short of its passes throws with the summary. +struct VerifyCase{ + struct Input{ + std::string name; + std::string checkpoint; + size_t passes; + }; + struct Expectation{ + std::string message; + }; + Input input; + Expectation expectation; +}; + +class Test_StoryVerifyFailed : public UnitTest{ +public: + Test_StoryVerifyFailed(const VerifyCase& test_case) + : UnitTest(std::format("Pokemon::StoryRun - {}", test_case.input.name)) + , m_case(test_case) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + FakeGame fake; + StoryGameHooks game = fake.hooks(); + VerifyPolicy policy; + VerifyReport report; + report.passes = m_case.input.passes; + report.verified = false; + std::string message; + try{ + finish_story_verify(m_case.input.checkpoint, policy, report, game); + return "Expected an OperationFailedException"; + }catch (OperationFailedException& e){ + message = e.message(); + } + if (message != m_case.expectation.message || !fake.logged(STORY_LEFT_WHERE_FAILED)){ + return std::format("Unexpected message: {}", message); + } + return true; + } + +private: + const VerifyCase m_case; +}; + +const VerifyCase VERIFY_CASES[] = { + { + .input = {.name = "an unverified checkpoint fails with its summary", .checkpoint = "00.15b", .passes = 1}, + .expectation = {.message = "AutoStory verify: 00.15b 1/3 passed, 2 needed."}, + }, +}; + +} // namespace + + +void add_tests_StoryRun(UnitTestDatabase& database){ + for (const StartCase& test_case : START_CASES){ + database.add(test_case); + } + for (const PreflightCase& test_case : PREFLIGHT_CASES){ + database.add(test_case); + } + for (const FirstSaveCase& test_case : FIRST_SAVE_CASES){ + database.add(test_case); + } + for (const ReloadCase& test_case : RELOAD_CASES){ + database.add(test_case); + } + for (const FailureCase& test_case : FAILURE_CASES){ + database.add(test_case); + } + for (const FinishedCase& test_case : FINISHED_CASES){ + database.add(test_case); + } + for (const VerifyCase& test_case : VERIFY_CASES){ + database.add(test_case); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.h new file mode 100644 index 0000000000..d1ac79aa1a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.h @@ -0,0 +1,23 @@ +/* AutoStory Story Run Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRun_Tests_H +#define PokemonAutomation_Pokemon_StoryRun_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the AutoStory story run's start, reload and finish. +void add_tests_StoryRun(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStart.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStart.h new file mode 100644 index 0000000000..33ba6d9489 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStart.h @@ -0,0 +1,38 @@ +/* AutoStory Story Start + * + * From: https://github.com/PokemonAutomation/ + * + * How a story run reaches its start checkpoint, and what that allows. + * The start sequence itself is prepare_story_start() in Pokemon_StoryRun.h. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStart_H +#define PokemonAutomation_Pokemon_StoryStart_H + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How the game reaches the start checkpoint. +enum class StoryStart{ + // A new game from the title screen: there is no save. + NEW_GAME, + // The game as another program left it: nothing is loaded. + LIVE, + // The checkpoint's save, loaded first. + FROM_SAVE, +}; + +// Whether the first checkpoint's own save at its start may run: only a +// new game's. After a load the save is already there, and from the game +// as it is the place is unconfirmed. +inline bool story_first_save_allowed(StoryStart start){ + return start == StoryStart::NEW_GAME; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp new file mode 100644 index 0000000000..1bd697a03e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp @@ -0,0 +1,153 @@ +/* Connected Maps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_ConnectedMaps.h" + +namespace PokemonAutomation{ +namespace Pokemon{ +namespace{ + +// The tile of `to` that `connection` on `side` leads onto from `here`: +// the edge row or column, shifted by the connection's offset. +TilePos edge_entry(const TilePos& here, Direction side, const MapConnection& connection, const Grid& to){ + TilePos point{here.x - connection.offset, here.y - connection.offset}; + switch (side){ + case Direction::NORTH: + point.y = to.height - 1; + break; + case Direction::SOUTH: + point.y = 0; + break; + case Direction::WEST: + point.x = to.width - 1; + break; + case Direction::EAST: + point.x = 0; + break; + } + return point; +} + +} // namespace + + +const MapData& ConnectedMaps::map(size_t index) const{ + if (index >= m_maps->size()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, + std::format("Map index {} is past the {} connected maps.", index, m_maps->size())); + } + return (*m_maps)[index]; +} + +std::optional ConnectedMaps::find(std::string_view name) const{ + for (size_t index = 0; index < m_maps->size(); index++){ + if ((*m_maps)[index].name == name){ + return index; + } + } + return std::nullopt; +} + +std::optional ConnectedMaps::warp_arrival(const MapWarp& warp) const{ + if (!warp.to){ + return std::nullopt; + } + const std::optional destination = find(warp.to->map); + if (!destination){ + return std::nullopt; + } + const MapData& to = map(*destination); + const auto arrival = to.points.find(warp.to->point); + if (arrival == to.points.end()){ + return std::nullopt; + } + return MapPlace{*destination, arrival->second}; +} + +std::optional ConnectedMaps::across_edge(const MapPlace& from, Direction side) const{ + for (const MapConnection& connection : map(from.map).connections){ + if (connection.side != side){ + continue; + } + const std::optional destination = find(connection.to_map); + if (!destination){ + continue; + } + const Grid& to = map(*destination).tiles; + const TilePos point = edge_entry(from.tile, side, connection, to); + if (to.contains(point)){ + return MapPlace{*destination, point}; + } + } + return std::nullopt; +} + +std::optional ConnectedMaps::neighbour(const MapPlace& from, Direction direction) const{ + const TilePos ahead = from.tile.next(direction); + if (map(from.map).tiles.contains(ahead)){ + return MapPlace{from.map, ahead}; + } + return across_edge(from, direction); +} + + +namespace{ + +// The side of `a` that `b` touches, and the offset of `b`'s tiles along it, +// if their rectangles on the world grid meet along a side. +std::optional touching(const MapData& a, const MapData& b){ + const TilePos pa = a.world->offset; + const TilePos pb = b.world->offset; + const int aw = a.tiles.width; + const int ah = a.tiles.height; + const int bw = b.tiles.width; + const int bh = b.tiles.height; + const bool columns_overlap = pa.x < pb.x + bw && pb.x < pa.x + aw; + const bool rows_overlap = pa.y < pb.y + bh && pb.y < pa.y + ah; + if (columns_overlap && pb.y + bh == pa.y){ + return MapConnection{Direction::NORTH, b.name, pb.x - pa.x}; + } + if (columns_overlap && pb.y == pa.y + ah){ + return MapConnection{Direction::SOUTH, b.name, pb.x - pa.x}; + } + if (rows_overlap && pb.x + bw == pa.x){ + return MapConnection{Direction::WEST, b.name, pb.y - pa.y}; + } + if (rows_overlap && pb.x == pa.x + aw){ + return MapConnection{Direction::EAST, b.name, pb.y - pa.y}; + } + return std::nullopt; +} + +} // namespace + +void connect_by_world(std::vector& maps){ + for (MapData& a : maps){ + for (const MapData& b : maps){ + if (&a == &b || !a.world || !b.world || a.world->name != b.world->name){ + continue; + } + const std::optional connection = touching(a, b); + if (!connection){ + continue; + } + const bool joined = std::ranges::any_of(a.connections, [&](const MapConnection& existing){ + return existing.to_map == b.name; + }); + if (!joined){ + a.connections.push_back(*connection); + } + } + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h new file mode 100644 index 0000000000..5fef2d16a6 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h @@ -0,0 +1,99 @@ +/* Connected Maps + * + * From: https://github.com/PokemonAutomation/ + * + * The one world the tile games (BDSP, FRLG) plan and walk on: maps joined by + * their warps and their edges (MapData::connections). The player's place in + * it is a map and a tile of that map, in the map's own coordinates. Where a + * warp or an edge leads is the same in both games; whether a step is + * allowed, and what the game does on arrival (FRLG walks the player out of + * a door), is each game's. + * + */ + +#ifndef PokemonAutomation_Pokemon_ConnectedMaps_H +#define PokemonAutomation_Pokemon_ConnectedMaps_H + +#include +#include +#include +#include +#include "Pokemon_Grid.h" +#include "Pokemon_MapData.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A tile of one of the connected maps: the map's index and the tile in that +// map's own coordinates. +struct MapPlace{ + size_t map = 0; + TilePos tile; + + bool operator==(const MapPlace& other) const = default; + // Map, then tile: an order for sets and maps of places. + auto operator<=>(const MapPlace& other) const = default; +}; + + +// A view of loaded maps as one connected world. It does not own the maps, +// which must outlive it and keep their order: MapPlace::map indexes them. +class ConnectedMaps{ +public: + explicit ConnectedMaps(const std::vector& maps) + : m_maps(&maps) + {} + // A temporary list would be gone by the first call. + explicit ConnectedMaps(std::vector&& maps) = delete; + + // How many maps are loaded: MapPlace::map runs from 0 to size() - 1. + size_t size() const{ + return m_maps->size(); + } + // The map at `index`; throws InternalProgramError past the last map, + // as from a MapPlace of another world. + const MapData& map(size_t index) const; + // The loaded map named `name`, or nothing. + std::optional find(std::string_view name) const; + + // Where taking `warp` puts the player: its destination point. Nothing + // if it leads to a map that isn't loaded or names a point that map + // doesn't have. + std::optional warp_arrival(const MapWarp& warp) const; + + // The tile past `side` of `from`'s map that carries on `from`'s row or + // column: on the first loaded map connected on that side that has it. + // Nothing if no loaded map there has it. + std::optional across_edge(const MapPlace& from, Direction side) const; + + // The tile next to `from` in `direction`: on the same map, or across + // its edge. Nothing past an edge that leads nowhere loaded. + std::optional neighbour(const MapPlace& from, Direction direction) const; + +private: + const std::vector* m_maps; +}; + + +// Joins the maps that lie on the same world grid (MapData::world) where +// they meet: each map gets a connection on each side to every map whose +// rectangle touches that side, unless it has one to that map already. +// Maps without a world are left alone. +void connect_by_world(std::vector& maps); + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +// A hash of MapPlace, for planners that keep places in unordered sets. +template <> +struct std::hash{ + size_t operator()(const PokemonAutomation::Pokemon::MapPlace& place) const{ + return std::hash()(place.tile) * 31 + place.map; + } +}; + +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp new file mode 100644 index 0000000000..788bfe9b84 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp @@ -0,0 +1,272 @@ +/* Connected Maps Tests + * + * From: https://github.com/PokemonAutomation/ + * + * A town with a route north of it and a lake east of it, joined by their + * places on one world grid (connect_by_world()), and a house the town's + * door warps into: + * + * world x: -1 0 1 2 3 4 5 + * y 0..2: [ Route (6 wide) ] + * y 3..5: [ Town (4) ][Lake] + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_ConnectedMaps.h" +#include "Pokemon_ConnectedMaps_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ +namespace{ + + +MapData open_map(std::string name, int width, int height){ + MapData map; + map.name = std::move(name); + map.tiles = Grid{width, height, std::vector((size_t)width * height, TileKind::OPEN)}; + return map; +} + +MapData on_world(MapData map, const TilePos& offset){ + map.world = MapWorld{"Test", offset}; + return map; +} + +const std::vector& test_maps(){ + static const std::vector maps = []{ + std::vector ret{ + on_world(open_map("Town", 4, 3), {0, 3}), + on_world(open_map("Route", 6, 3), {-1, 0}), + on_world(open_map("Lake", 2, 3), {4, 3}), + open_map("House", 2, 2), + }; + ret[3].points["door"] = {0, 1}; + connect_by_world(ret); + return ret; + }(); + return maps; +} + +// A tile named by its map. +struct NamedPlace{ + std::string_view map; + TilePos tile; +}; + +std::string describe(const ConnectedMaps& world, const std::optional& place){ + if (!place){ + return "nowhere"; + } + return std::format("{} {}", world.map(place->map).name, to_string(place->tile)); +} + +// Why `actual` is not `expected`, if it is not. +std::optional mismatch(const ConnectedMaps& world, const std::optional& actual, const std::optional& expected){ + std::optional wanted; + if (expected){ + wanted = MapPlace{*world.find(expected->map), expected->tile}; + } + if (actual == wanted){ + return std::nullopt; + } + return std::format("Got {}, expected {}.", describe(world, actual), describe(world, wanted)); +} + + +struct StepCase{ + struct Input{ + std::string_view name; + NamedPlace from; + Direction direction; + }; + // Where the step should put the player, or nothing for nowhere. + struct Expectation{ + std::optional place; + }; + Input input; + Expectation expectation; +}; + +class Test_ConnectedMaps_Step : public UnitTest{ +public: + explicit Test_ConnectedMaps_Step(StepCase scenario) + : UnitTest(std::format("Pokemon::ConnectedMaps - {}", scenario.input.name)), m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const ConnectedMaps world(test_maps()); + const StepCase::Input& input = m_scenario.input; + const MapPlace from{*world.find(input.from.map), input.from.tile}; + if (std::optional error = mismatch(world, world.neighbour(from, input.direction), m_scenario.expectation.place)){ + return *error; + } + return true; + } +private: + StepCase m_scenario; +}; + +const StepCase STEP_CASES[] = { + { + .input = {.name = "a step on the same map", .from = {"Town", {1, 1}}, .direction = Direction::EAST}, + .expectation = {.place = NamedPlace{"Town", {2, 1}}}, + }, + { + .input = {.name = "north onto the route, shifted by its offset", .from = {"Town", {0, 0}}, .direction = Direction::NORTH}, + .expectation = {.place = NamedPlace{"Route", {1, 2}}}, + }, + { + .input = {.name = "south off the route into the town", .from = {"Route", {1, 2}}, .direction = Direction::SOUTH}, + .expectation = {.place = NamedPlace{"Town", {0, 0}}}, + }, + { + .input = {.name = "east into the lake", .from = {"Town", {3, 2}}, .direction = Direction::EAST}, + .expectation = {.place = NamedPlace{"Lake", {0, 2}}}, + }, + { + .input = {.name = "west into the town", .from = {"Lake", {0, 1}}, .direction = Direction::WEST}, + .expectation = {.place = NamedPlace{"Town", {3, 1}}}, + }, + { + .input = {.name = "north out of the lake onto the route's last column", .from = {"Lake", {0, 0}}, .direction = Direction::NORTH}, + .expectation = {.place = NamedPlace{"Route", {5, 2}}}, + }, + { + .input = {.name = "north out of the lake past the route's span", .from = {"Lake", {1, 0}}, .direction = Direction::NORTH}, + .expectation = {.place = std::nullopt}, + }, + { + .input = {.name = "an edge no map joins", .from = {"Town", {0, 1}}, .direction = Direction::WEST}, + .expectation = {.place = std::nullopt}, + }, + { + .input = {.name = "past the joined map's span", .from = {"Route", {0, 2}}, .direction = Direction::SOUTH}, + .expectation = {.place = std::nullopt}, + }, + { + .input = {.name = "a map off the world grid joins nothing", .from = {"House", {1, 0}}, .direction = Direction::NORTH}, + .expectation = {.place = std::nullopt}, + }, +}; + + +struct WarpCase{ + struct Input{ + std::string_view name; + MapWarp warp; + }; + // Where the warp should put the player, or nothing for nowhere. + struct Expectation{ + std::optional place; + }; + Input input; + Expectation expectation; +}; + +class Test_ConnectedMaps_Warp : public UnitTest{ +public: + explicit Test_ConnectedMaps_Warp(WarpCase scenario) + : UnitTest(std::format("Pokemon::ConnectedMaps - {}", scenario.input.name)), m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const ConnectedMaps world(test_maps()); + if (std::optional error = mismatch(world, world.warp_arrival(m_scenario.input.warp), m_scenario.expectation.place)){ + return *error; + } + return true; + } +private: + WarpCase m_scenario; +}; + +const WarpCase WARP_CASES[] = { + { + .input = {.name = "a warp to a loaded map's point", .warp = {.to = WarpDestination{"House", "door"}}}, + .expectation = {.place = NamedPlace{"House", {0, 1}}}, + }, + { + .input = {.name = "a warp to a map that isn't loaded", .warp = {.to = WarpDestination{"Cave", "door"}}}, + .expectation = {.place = std::nullopt}, + }, + { + .input = {.name = "a warp to a point the map lacks", .warp = {.to = WarpDestination{"House", "stairs"}}}, + .expectation = {.place = std::nullopt}, + }, + { + .input = {.name = "a warp that leads nowhere", .warp = {}}, + .expectation = {.place = std::nullopt}, + }, +}; + + +struct StalePlaceCase{ + struct Input{ + std::string_view name; + size_t map; + }; + struct Expectation{ + // Whether reading the place throws InternalProgramError. + bool rejected = false; + }; + Input input; + Expectation expectation; +}; + +// A place whose map index is past the loaded maps (from another world, or +// one that has since shrunk) is an InternalProgramError, not a read past +// the end. +class Test_ConnectedMaps_StalePlace : public UnitTest{ +public: + explicit Test_ConnectedMaps_StalePlace(StalePlaceCase scenario) + : UnitTest(std::format("Pokemon::ConnectedMaps - {}", scenario.input.name)), m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const ConnectedMaps world(test_maps()); + const MapPlace stale{m_scenario.input.map, {0, 0}}; + bool rejected = false; + try{ + world.neighbour(stale, Direction::NORTH); + }catch (const InternalProgramError&){ + rejected = true; + } + if (rejected != m_scenario.expectation.rejected){ + return std::format("Map {} of {} was {}, expected it {}.", stale.map, world.size(), + rejected ? "rejected" : "read", m_scenario.expectation.rejected ? "rejected" : "read"); + } + return true; + } +private: + StalePlaceCase m_scenario; +}; + +const StalePlaceCase STALE_PLACE_CASES[] = { + {.input = {.name = "the last map index is read", .map = 3}, .expectation = {.rejected = false}}, + {.input = {.name = "a map index one past the last is rejected", .map = 4}, .expectation = {.rejected = true}}, + {.input = {.name = "a map index far past the last is rejected", .map = 1000}, .expectation = {.rejected = true}}, +}; + + +} // namespace + +void add_tests_ConnectedMaps(UnitTestDatabase& database){ + for (const StepCase& scenario : STEP_CASES){ + database.add(scenario); + } + for (const WarpCase& scenario : WARP_CASES){ + database.add(scenario); + } + for (const StalePlaceCase& scenario : STALE_PLACE_CASES){ + database.add(scenario); + } +} + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h new file mode 100644 index 0000000000..a3d6a6c26b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h @@ -0,0 +1,22 @@ +/* Connected Maps Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_ConnectedMaps_Tests_H +#define PokemonAutomation_Pokemon_ConnectedMaps_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers the checks on stepping and warping between connected maps. +void add_tests_ConnectedMaps(UnitTestDatabase& database); + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h new file mode 100644 index 0000000000..2b7d734b88 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h @@ -0,0 +1,119 @@ +/* Move Mechanics + * + * From: https://github.com/PokemonAutomation/ + * + * How each game moves the player for a press, as measured on the console: + * one entry per game, read by that game's walker and by its sim. + * + */ + +#ifndef PokemonAutomation_Pokemon_MoveMechanics_H +#define PokemonAutomation_Pokemon_MoveMechanics_H + +#include +#include "Common/Cpp/Time.h" +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How the walker presses an open leg, one that ends short of a wall. +enum class OpenLegPress{ + STEP_TAPS, // a step tap a tile: the count is exact + TIMED_HOLD, // one hold, timed by the tile time +}; + +// Time per tile along each axis of the screen. +struct TileTime{ + Milliseconds across{}; // east or west + Milliseconds up_down{}; // north or south + + constexpr Milliseconds along(Direction direction) const{ + return direction == Direction::EAST || direction == Direction::WEST ? across : up_down; + } +}; + +// A tap that takes one step: the press, and the release before the next +// press. Their sum is the time per tapped tile. +struct StepTap{ + Milliseconds hold{}; + Milliseconds release{}; +}; + +// One way of moving: walking, running or riding. +struct Gait{ + TileTime tile; + // The step tap in this gait; a game's taps differ by gait (FRLG's + // Bicycle taps far faster than its walk). + StepTap tap; + OpenLegPress open_legs = OpenLegPress::STEP_TAPS; +}; + +// How one game moves the player: its turn tap, and a tile time and step +// tap per gait. +struct MoveMechanics{ + // A tap that turns a player facing another way, without a step. + Milliseconds turn_tap{}; + // From pressing, standing still, to the first step under way. + Milliseconds start_delay{}; + Gait walk; + // B held, once the player has the Running Shoes. + Gait run; + // None where the walker does not ride yet. + std::optional bike; +}; + + +// Brilliant Diamond and Shining Pearl, measured on console B. The camera +// tilts, so a row takes longer than a column. D-pad taps move exactly a +// tile each, while a held run overshoots about 3 tiles in 10 (2026-11-09, +// Jubilife), so open legs are tapped. Taps: PokemonBDSP_AutoStory_RouteInput.h; +// tile times: PokemonBDSP_AutoStory_RouteTiming.h. +inline constexpr MoveMechanics BDSP_MOVE_MECHANICS{ + .turn_tap = Milliseconds(50), + .start_delay = Milliseconds(250), + .walk = { + .tile = {.across = Milliseconds(160), .up_down = Milliseconds(240)}, + .tap = {.hold = Milliseconds(160), .release = Milliseconds(640)}, + .open_legs = OpenLegPress::STEP_TAPS, + }, + .run = { + .tile = {.across = Milliseconds(100), .up_down = Milliseconds(150)}, + .tap = {.hold = Milliseconds(160), .release = Milliseconds(640)}, + .open_legs = OpenLegPress::STEP_TAPS, + }, + .bike = std::nullopt, +}; + +// FireRed and LeafGreen, measured on console B: a walking tile is 16 +// frames, running 8, and a held leg stops where its time says, so open +// legs on foot are timed holds; on the Bicycle they are counted in taps, +// 40 ms at one per 100 ms (BIKE_TAP_PERIOD_WORKED; at a 60 ms period one +// tap in 12 drops). The walker's holds count no start delay. +// Measurements: PokemonFRLG_MovementMechanics.h and +// PokemonFRLG_BikeSpinMechanics.h. +inline constexpr MoveMechanics FRLG_MOVE_MECHANICS{ + .turn_tap = Milliseconds(40), + .start_delay = Milliseconds(0), + .walk = { + .tile = {.across = Milliseconds(267), .up_down = Milliseconds(267)}, + .tap = {.hold = Milliseconds(66), .release = Milliseconds(700)}, + .open_legs = OpenLegPress::TIMED_HOLD, + }, + .run = { + .tile = {.across = Milliseconds(133), .up_down = Milliseconds(133)}, + .tap = {.hold = Milliseconds(66), .release = Milliseconds(700)}, + .open_legs = OpenLegPress::TIMED_HOLD, + }, + .bike = Gait{ + .tile = {.across = Milliseconds(100), .up_down = Milliseconds(100)}, + .tap = {.hold = Milliseconds(40), .release = Milliseconds(60)}, + .open_legs = OpenLegPress::STEP_TAPS, + }, +}; + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp new file mode 100644 index 0000000000..fced1d74eb --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp @@ -0,0 +1,130 @@ +/* Move Mechanics Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_MoveMechanics.h" +#include "Pokemon_MoveMechanics_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ +namespace{ + + +struct MoveMechanicsCase{ + struct Input{ + std::string_view game; + MoveMechanics mechanics; + }; + struct Expectation{ + // How the walker presses an open leg on foot (BDSP taps, FRLG + // timed holds). + OpenLegPress open_legs_on_foot; + }; + Input input; + Expectation expectation; +}; + +// Why `faster` is not faster than `slower` on both axes, if it is not. +std::optional not_faster(std::string_view faster_name, const Gait& faster, std::string_view slower_name, const Gait& slower){ + if (faster.tile.across >= slower.tile.across || faster.tile.up_down >= slower.tile.up_down){ + return std::format("{} ({}/{} ms) is not faster than {} ({}/{} ms).", + faster_name, faster.tile.across.count(), faster.tile.up_down.count(), + slower_name, slower.tile.across.count(), slower.tile.up_down.count()); + } + return std::nullopt; +} + +// Why the turn tap would step on foot in `gait`, if it would: a turn tap +// must be shorter than the gait's step tap. +std::optional turn_steps(std::string_view gait_name, const Gait& gait, Milliseconds turn_tap){ + if (turn_tap >= gait.tap.hold){ + return std::format("The turn tap ({} ms) is not shorter than the {} step tap ({} ms).", + turn_tap.count(), gait_name, gait.tap.hold.count()); + } + return std::nullopt; +} + +// Why a gait's step tap is unusable, if it is: both its press and its +// release must take time. +std::optional empty_tap(std::string_view gait_name, const Gait& gait){ + if (gait.tap.hold <= Milliseconds(0) || gait.tap.release <= Milliseconds(0)){ + return std::format("The {} step tap is {} ms pressed, {} ms released; both must be over 0.", + gait_name, gait.tap.hold.count(), gait.tap.release.count()); + } + return std::nullopt; +} + +std::string_view open_leg_press_name(OpenLegPress press){ + return press == OpenLegPress::STEP_TAPS ? "step taps" : "a timed hold"; +} + +// Why `gait` presses its open legs other than `expected`, if it does. +std::optional wrong_open_legs(std::string_view gait_name, const Gait& gait, OpenLegPress expected){ + if (gait.open_legs != expected){ + return std::format("Open legs {} are pressed as {}, expected {}.", + gait_name, open_leg_press_name(gait.open_legs), open_leg_press_name(expected)); + } + return std::nullopt; +} + +class Test_MoveMechanics : public UnitTest{ +public: + explicit Test_MoveMechanics(MoveMechanicsCase scenario) + : UnitTest(std::format("Pokemon::MoveMechanics - {}", scenario.input.game)), m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const MoveMechanics& game = m_scenario.input.mechanics; + const OpenLegPress expected = m_scenario.expectation.open_legs_on_foot; + const std::optional failures[] = { + empty_tap("walking", game.walk), + empty_tap("running", game.run), + game.bike ? empty_tap("bike", *game.bike) : std::nullopt, + turn_steps("walking", game.walk, game.turn_tap), + turn_steps("running", game.run, game.turn_tap), + not_faster("running", game.run, "walking", game.walk), + game.bike ? not_faster("the bike", *game.bike, "running", game.run) : std::nullopt, + wrong_open_legs("walking", game.walk, expected), + wrong_open_legs("running", game.run, expected), + }; + for (const std::optional& failure : failures){ + if (failure){ + return *failure; + } + } + return true; + } +private: + MoveMechanicsCase m_scenario; +}; + +const MoveMechanicsCase MOVE_MECHANICS_CASES[] = { + { + .input = {.game = "BDSP", .mechanics = BDSP_MOVE_MECHANICS}, + .expectation = {.open_legs_on_foot = OpenLegPress::STEP_TAPS}, + }, + { + .input = {.game = "FRLG", .mechanics = FRLG_MOVE_MECHANICS}, + .expectation = {.open_legs_on_foot = OpenLegPress::TIMED_HOLD}, + }, +}; + + +} // namespace + +void add_tests_MoveMechanics(UnitTestDatabase& database){ + for (const MoveMechanicsCase& scenario : MOVE_MECHANICS_CASES){ + database.add(scenario); + } +} + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.h new file mode 100644 index 0000000000..a545eae699 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.h @@ -0,0 +1,22 @@ +/* Move Mechanics Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_MoveMechanics_Tests_H +#define PokemonAutomation_Pokemon_MoveMechanics_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers the checks on each game's movement table. +void add_tests_MoveMechanics(UnitTestDatabase& database); + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 94dc41dd85..f2fad841a4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -27,6 +27,7 @@ #include "Inference/PokemonFRLG_StatsReader.h" #include "Inference/PokemonFRLG_TrainerIdReader.h" #include "Inference/PokemonFRLG_WildEncounterReader.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h" #include "Programs/BoxOrganization/PokemonFRLG_BoxSorter_Tests.h" #include "Tests/TestUtils.h" @@ -61,6 +62,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_ShinySymbolDetector(database); add_tests_TrainerIdReader(database); add_tests_WildEncounterReader(database); + add_tests_AutoStoryScreenEvents(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp new file mode 100644 index 0000000000..85edb74b36 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp @@ -0,0 +1,52 @@ +/* FRLG AutoStory - Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonFRLG_AutoStoryScreenEvents.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::ScreenEvent; +using Pokemon::ScreenEvents; + + +FrlgScreenObserver::FrlgScreenObserver() + : m_dialog(COLOR_RED) + , m_choice(COLOR_RED) + , m_battle_menu(COLOR_RED) + , m_battle_dialog(COLOR_RED) +{} + +ScreenEvents FrlgScreenObserver::observe(const VideoSnapshot& frame, WallClock){ + if (!frame){ + return {}; + } + const ImageViewRGB32& screen = *frame.frame; + ScreenEvents out = Pokemon::fade_events(Pokemon::fade_of_screen(screen)); + if (Pokemon::fade_in(out) != Pokemon::WarpFade::NONE){ + // A uniform screen has no box or menu to read. + return out; + } + const bool battle = m_battle_menu.detect(screen) || m_battle_dialog.detect(screen); + out.set(ScreenEvent::BATTLE_STARTED, battle); + out.set(ScreenEvent::DIALOG_BOX, !battle && m_dialog.detect(screen)); + out.set(ScreenEvent::CHOICE_BOX, !battle && m_choice.detect(screen)); + return out; +} + +void FrlgScreenObserver::make_overlays(VideoOverlaySet& items) const{ + m_dialog.make_overlays(items); + m_choice.make_overlays(items); + m_battle_menu.make_overlays(items); + m_battle_dialog.make_overlays(items); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h new file mode 100644 index 0000000000..8de3ed926a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h @@ -0,0 +1,49 @@ +/* FRLG AutoStory - Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + * FRLG's detectors as the shared screen events (Pokemon_ScreenEvents.h), + * so the shared judgements (Pokemon_SceneJudges.h) read FRLG frames too. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryScreenEvents_H +#define PokemonAutomation_PokemonFRLG_AutoStoryScreenEvents_H + +#include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" +#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_BattleDialogs.h" +#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_DialogDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The shared events from FRLG's detectors: +// - DIALOG_BOX: the overworld's white text box (WhiteDialogDetector); +// - CHOICE_BOX: a Yes/No or answer box beside it (SelectionDialogDetector); +// - BATTLE_STARTED: the battle menu or a battle's text box; +// - FADE_BLACK / FADE_WHITE: fade_of_screen(). +// Not reported yet, as FRLG has no detector for them here: the map-name +// popup (LOCATION_BANNER), PLAYER_CAN_MOVE, SCREEN_STILL, the interact +// prompt (FRLG has none) and a battle's end. +class FrlgScreenObserver : public Pokemon::ScreenEventObserver{ +public: + FrlgScreenObserver(); + + virtual Pokemon::ScreenEvents observe(const VideoSnapshot& frame, WallClock now) override; + virtual void make_overlays(VideoOverlaySet& items) const override; + +private: + WhiteDialogDetector m_dialog; + SelectionDialogDetector m_choice; + BattleMenuDetector m_battle_menu; + BattleDialogDetector m_battle_dialog; +}; + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp new file mode 100644 index 0000000000..d2a2d5d332 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp @@ -0,0 +1,99 @@ +/* FRLG AutoStory - Screen Events Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The adapter on synthetic frames: a uniform screen is a fade and nothing + * else, and no frame shows nothing. Frames of real boxes and battles are + * the detectors' own image tests (CommandLineTests); a flat grey frame is + * not one of those (the battle text box reads it as a box). + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "PokemonFRLG_AutoStoryScreenEvents.h" +#include "PokemonFRLG_AutoStoryScreenEvents_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::ScreenEvent; +using Pokemon::ScreenEvents; + +namespace{ + +struct ScreenEventsCase{ + struct Input{ + std::string name; + // The frame's colour; none for no frame. + std::optional color; + }; + + struct Expectation{ + ScreenEvents events; + }; + + Input input; + Expectation expectation; +}; + +class Test_AutoStoryScreenEvents : public UnitTest{ +public: + explicit Test_AutoStoryScreenEvents(ScreenEventsCase test_case) + : UnitTest(std::format("PokemonFRLG::AutoStoryScreenEvents - {}", test_case.input.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + VideoSnapshot frame; + if (m_case.input.color.has_value()){ + ImageRGB32 image(1920, 1080); + image.fill(*m_case.input.color); + frame = VideoSnapshot(std::move(image), WallClock()); + } + FrlgScreenObserver observer; + const ScreenEvents got = observer.observe(frame, WallClock()); + if (got != m_case.expectation.events){ + return std::format("expected {}, got {}", describe(m_case.expectation.events), describe(got)); + } + return true; + } + +private: + ScreenEventsCase m_case; +}; + +} // namespace + + +const ScreenEventsCase SCREEN_EVENTS_CASES[] = { + { + .input = {"no frame shows nothing", std::nullopt}, + .expectation = {{}}, + }, + { + .input = {"a black screen is a black fade only", 0xff000000}, + .expectation = {{ScreenEvent::FADE_BLACK}}, + }, + { + .input = {"a white screen is a white fade only", 0xffffffff}, + .expectation = {{ScreenEvent::FADE_WHITE}}, + }, +}; + +void add_tests_AutoStoryScreenEvents(UnitTestDatabase& database){ + for (const auto& item : SCREEN_EVENTS_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h new file mode 100644 index 0000000000..39b267b4d7 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h @@ -0,0 +1,25 @@ +/* FRLG AutoStory - Screen Events Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryScreenEvents_Tests_H +#define PokemonAutomation_PokemonFRLG_AutoStoryScreenEvents_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Registers the screen-event adapter's unit tests (synthetic frames). +void add_tests_AutoStoryScreenEvents(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index b96f9e31c0..e515e638d0 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1468,6 +1468,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Inference/Pokemon_TrainPokemonOCR.h Source/Pokemon/Inference/Pokemon_TypeReader.cpp Source/Pokemon/Inference/Pokemon_TypeReader.h + Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp + Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h + Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp + Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h Source/Pokemon/Navigation/Pokemon_Direction.cpp Source/Pokemon/Navigation/Pokemon_Direction.h Source/Pokemon/Navigation/Pokemon_Grid.cpp @@ -1491,6 +1495,9 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_MapData.h Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp Source/Pokemon/Navigation/Pokemon_MapData_Tests.h + Source/Pokemon/Navigation/Pokemon_MoveMechanics.h + Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp + Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.h Source/Pokemon/Navigation/Pokemon_RuntimeMap.cpp Source/Pokemon/Navigation/Pokemon_RuntimeMap.h Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp @@ -1559,6 +1566,12 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_AutoStorySelect.h Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.cpp Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp + Source/Pokemon/AutoStory/Pokemon_StoryRun.h + Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp + Source/Pokemon/AutoStory/Pokemon_StoryPreflight.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.cpp Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp @@ -1567,6 +1580,7 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.cpp Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h + Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp Source/Pokemon/AutoStory/Pokemon_Interrupts.h Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp @@ -1583,12 +1597,20 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.h Source/Pokemon/AutoStory/Pokemon_ScreenFades.h + Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp + Source/Pokemon/AutoStory/Pokemon_StoryActions.h + Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h Source/Pokemon/AutoStory/Pokemon_StoryCheckpointTypes.h Source/Pokemon/AutoStory/Pokemon_StoryEvent.h Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp Source/Pokemon/AutoStory/Pokemon_StoryEvents.h Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp + Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h + Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.h Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp Source/Pokemon/AutoStory/Pokemon_StoryLog.h Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp @@ -1633,6 +1655,7 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.cpp Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryStart.h Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h @@ -1952,6 +1975,10 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_NuggetBridgeFarmer.h Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_PickupFarmer.cpp Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_PickupFarmer.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_BattleMenuNavigation.cpp Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_BattleMenuNavigation.h Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_SafariOptimalAction.cpp