diff --git a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEventTypes.h b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEventTypes.h new file mode 100644 index 0000000000..e9d05d5052 --- /dev/null +++ b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEventTypes.h @@ -0,0 +1,94 @@ +/* Screen Event Types + * + * From: https://github.com/PokemonAutomation/ + * + * The words a program uses for what the screen shows: a fade, a dialogue + * box, a battle starting. ScreenEvents.h watches a stream for them. + * + */ + +#ifndef PokemonAutomation_CommonTools_ScreenEvents_ScreenEventTypes_H +#define PokemonAutomation_CommonTools_ScreenEvents_ScreenEventTypes_H + +#include +#include +#include +#include +#include + +namespace PokemonAutomation{ + + +// One thing a frame shows. A game reports the ones its detectors can see. +enum class ScreenEvent : uint8_t{ + FADE_BLACK, // A uniform dark screen: a door, a cave mouth, a scene cut. + FADE_WHITE, // A uniform white screen: a cave exit. + LOCATION_BANNER, // A location banner. An observer given an expected + // map reports only that map's. + DIALOG_BOX, // A dialogue box. + CHOICE_BOX, // A choice (Yes/No, a menu of answers). + INTERACT_PROMPT, // A button prompt to interact ("A Talk"). + BATTLE_STARTED, // A battle shows (its menu, its HUD or its opening). + BATTLE_ENDED, // A battle's closing screen. + PLAYER_CAN_MOVE, // The overworld with the player in control. + SCREEN_STILL, // The screen barely changed since the frame before. + SWITCH_HOME_MENU, // The Switch's HOME menu: the game is not on the screen. +}; +// How many ScreenEvent values there are. +constexpr size_t SCREEN_EVENT_COUNT = 11; +static_assert((size_t)ScreenEvent::SWITCH_HOME_MENU + 1 == SCREEN_EVENT_COUNT, "SWITCH_HOME_MENU is the last ScreenEvent"); +// "dialog box", for the log. +std::string screen_event_name(ScreenEvent event); + + +// How a screen's fade looks: the kind of FADE_BLACK / FADE_WHITE. +enum class WarpFade{ + NONE, + BLACK, // a door's black, or a cave mouth's dim fade + WHITE, // a cave exit's white, with no battle after it +}; +// "black fade", for the log. +std::string warp_fade_name(WarpFade fade); + + +// The events of one frame, or of all the frames a watcher saw. +class ScreenEvents{ +public: + ScreenEvents() = default; + ScreenEvents(std::initializer_list events); + + bool has(ScreenEvent event) const{ + return (m_bits & bit(event)) != 0; + } + // Whether any of `events` is in this set. + bool any_of(const ScreenEvents& events) const{ + return (m_bits & events.m_bits) != 0; + } + // Adds `event`, or removes it when `on` is false (as std::bitset::set). + void set(ScreenEvent event, bool on); + void merge(const ScreenEvents& events){ + m_bits |= events.m_bits; + } + + uint32_t bits() const{ + return m_bits; + } + static ScreenEvents from_bits(uint32_t bits); + + bool operator==(const ScreenEvents& other) const = default; + +private: + static uint32_t bit(ScreenEvent event){ + return uint32_t(1) << (uint32_t)event; + } + + uint32_t m_bits = 0; +}; +// "dialog box, player can move" (joined by `separator`); "nothing" when +// empty. +std::string describe(const ScreenEvents& events, std::string_view separator = ", "); + + + +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents.cpp b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents.cpp new file mode 100644 index 0000000000..4234cc658b --- /dev/null +++ b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents.cpp @@ -0,0 +1,125 @@ +/* Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "ScreenEventTypes.h" +#include "ScreenFades.h" +#include "ScreenEvents.h" + +namespace PokemonAutomation{ + + +std::string screen_event_name(ScreenEvent event){ + switch (event){ + case ScreenEvent::FADE_BLACK: return "black fade"; + case ScreenEvent::FADE_WHITE: return "white fade"; + case ScreenEvent::LOCATION_BANNER: return "location banner"; + case ScreenEvent::DIALOG_BOX: return "dialog box"; + case ScreenEvent::CHOICE_BOX: return "choice box"; + case ScreenEvent::INTERACT_PROMPT: return "interact prompt"; + case ScreenEvent::BATTLE_STARTED: return "battle started"; + case ScreenEvent::BATTLE_ENDED: return "battle ended"; + case ScreenEvent::PLAYER_CAN_MOVE: return "player can move"; + case ScreenEvent::SCREEN_STILL: return "screen still"; + case ScreenEvent::SWITCH_HOME_MENU: return "Switch HOME menu"; + } + return "?"; +} + +std::string warp_fade_name(WarpFade fade){ + switch (fade){ + case WarpFade::NONE: return "no fade"; + case WarpFade::BLACK: return "black fade"; + case WarpFade::WHITE: return "white fade"; + } + return "?"; +} + + +ScreenEvents::ScreenEvents(std::initializer_list events){ + for (ScreenEvent event : events){ + set(event, true); + } +} +void ScreenEvents::set(ScreenEvent event, bool on){ + if (on){ + m_bits |= bit(event); + }else{ + m_bits &= ~bit(event); + } +} +ScreenEvents ScreenEvents::from_bits(uint32_t bits){ + ScreenEvents out; + out.m_bits = bits & ((uint32_t(1) << SCREEN_EVENT_COUNT) - 1); + return out; +} + +ScreenEvents fade_events(WarpFade fade){ + switch (fade){ + case WarpFade::NONE: + return {}; + case WarpFade::BLACK: + return {ScreenEvent::FADE_BLACK}; + case WarpFade::WHITE: + return {ScreenEvent::FADE_WHITE}; + } + return {}; +} +WarpFade fade_in(const ScreenEvents& events){ + if (events.has(ScreenEvent::FADE_BLACK)){ + return WarpFade::BLACK; + } + if (events.has(ScreenEvent::FADE_WHITE)){ + return WarpFade::WHITE; + } + return WarpFade::NONE; +} +std::string describe(const ScreenEvents& events, std::string_view separator){ + std::string out; + for (size_t c = 0; c < SCREEN_EVENT_COUNT; c++){ + const ScreenEvent event = (ScreenEvent)c; + if (!events.has(event)){ + continue; + } + if (!out.empty()){ + out += separator; + } + out += screen_event_name(event); + } + return out.empty() ? "nothing" : out; +} + + +// Black is is_black() (SolidColorTest, BlackScreenDetector's test) with +// the fade's thresholds. +// White is not is_white(): that also wants an even grey, and a fade to +// white can be tinted. +WarpFade fade_of(const ImageStats& middle){ + if (is_black(middle, FADE_MAX_DARK_SUM, FADE_MAX_STDDEV_SUM)){ + return WarpFade::BLACK; + } + if (middle.stddev.sum() > FADE_MAX_STDDEV_SUM){ + return WarpFade::NONE; + } + return middle.average.sum() >= FADE_MIN_WHITE_SUM ? WarpFade::WHITE : WarpFade::NONE; +} +WarpFade fade_of_screen(const ImageViewRGB32& screen){ + return fade_of(image_stats(extract_box_reference(screen, ImageFloatBox(0.1, 0.1, 0.8, 0.8)))); +} + + +bool same_screen(const VideoSnapshot& a, const VideoSnapshot& b){ + if (!a || !b || a->width() != b->width() || a->height() != b->height()){ + return false; + } + return ImageMatch::pixel_RMSD(a, b) < 2.0; +} + + +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents.h b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents.h new file mode 100644 index 0000000000..832838b419 --- /dev/null +++ b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents.h @@ -0,0 +1,49 @@ +/* Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + * What an autonomous program can see on the screen, in words every game + * shares: a fade, a location banner, a dialogue box, a battle starting. + * Each game implements ScreenEventObserver with its own detectors; the + * judgements built on these events are then the same for all of them. + * + * An observer is asked frame by frame. + * + */ + +#ifndef PokemonAutomation_CommonTools_ScreenEvents_ScreenEvents_H +#define PokemonAutomation_CommonTools_ScreenEvents_ScreenEvents_H + +#include "Common/Cpp/Time.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "ScreenEventTypes.h" + +namespace PokemonAutomation{ + + +// A game's detectors, as events. Observers may keep state between frames +// (the frame before, for SCREEN_STILL; when a banner was last read, to +// gate OCR), so one observer watches one stream at a time. +class ScreenEventObserver{ +public: + virtual ~ScreenEventObserver() = default; + + // What `frame` shows. `now` is the caller's clock, for observers that + // rate-limit expensive reads. A null frame shows nothing. + virtual ScreenEvents observe(const VideoSnapshot& frame, WallClock now) = 0; + + // The boxes the detectors read, for the video overlay. + virtual void make_overlays(VideoOverlaySet& items) const = 0; +}; + + +// Whether `a` and `b` both have a frame of the same size within the +// still-screen RMSD threshold (2.0): the screen barely changed +// (ScreenEvent::SCREEN_STILL). +bool same_screen(const VideoSnapshot& a, const VideoSnapshot& b); + + + +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.cpp b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.cpp new file mode 100644 index 0000000000..de98615d40 --- /dev/null +++ b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.cpp @@ -0,0 +1,167 @@ +/* Screen Events Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The shared event vocabulary, fades and the still-screen test. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "ScreenEventTypes.h" +#include "ScreenFades.h" +#include "ScreenEvents.h" +#include "ScreenEvents_Tests.h" + +namespace PokemonAutomation{ + +namespace{ + +UnitTestResult expect_equal(const std::string& what, const std::string& got, const std::string& expected){ + if (got == expected){ + return true; + } + return std::format("{}: expected \"{}\", got \"{}\"", what, expected, got); +} + + +UnitTestResult test_set_and_describe(){ + ScreenEvents events{ScreenEvent::DIALOG_BOX, ScreenEvent::PLAYER_CAN_MOVE}; + if (!events.has(ScreenEvent::DIALOG_BOX) || events.has(ScreenEvent::CHOICE_BOX)){ + return "has() disagrees with the constructor's events"; + } + events.set(ScreenEvent::DIALOG_BOX, false); + events.merge(fade_events(WarpFade::WHITE)); + events.merge(fade_events(WarpFade::NONE)); + if (fade_in(events) != WarpFade::WHITE){ + return "fade_events(WHITE) did not give a white fade"; + } + if (ScreenEvents::from_bits(events.bits()) != events){ + return "from_bits(bits()) is not the same set"; + } + if (describe(ScreenEvents()) != "nothing"){ + return "an empty set does not describe as nothing"; + } + return expect_equal("describe()", describe(events), "white fade, player can move"); +} + +// A screen filled with one colour, or a checkerboard of two. +ImageRGB32 screen_of(uint32_t a, uint32_t b){ + ImageRGB32 out(64, 36); + for (size_t y = 0; y < out.height(); y++){ + for (size_t x = 0; x < out.width(); x++){ + out.pixel(x, y) = (x + y) % 2 == 0 ? a : b; + } + } + return out; +} + +UnitTestResult test_fade_of_screen(){ + struct Row{ + std::string name; + uint32_t a; + uint32_t b; + WarpFade fade; + }; + const std::vector rows = { + {"black", 0xff000000, 0xff000000, WarpFade::BLACK}, + {"a cave mouth's dim fade (60 a channel)", 0xff3c3c3c, 0xff3c3c3c, WarpFade::BLACK}, + {"white", 0xffffffff, 0xffffffff, WarpFade::WHITE}, + {"grey, neither", 0xff787878, 0xff787878, WarpFade::NONE}, + {"a dark textured floor", 0xff101010, 0xff505050, WarpFade::NONE}, + }; + for (const Row& row : rows){ + const WarpFade got = fade_of_screen(screen_of(row.a, row.b)); + if (got != row.fade){ + return std::format("{}: expected {}, got {}", row.name, warp_fade_name(row.fade), warp_fade_name(got)); + } + } + return true; +} + +UnitTestResult test_same_screen(){ + const WallClock now = WallClock::min(); + const VideoSnapshot black(screen_of(0xff000000, 0xff000000), now); + const VideoSnapshot black_again(screen_of(0xff000000, 0xff000000), now); + const VideoSnapshot white(screen_of(0xffffffff, 0xffffffff), now); + ImageRGB32 small(32, 18); + small.fill(0xff000000); + const VideoSnapshot black_small(std::move(small), now); + if (!same_screen(black, black_again)){ + return "two black frames are not the same screen"; + } + if (same_screen(black, white)){ + return "black and white frames are the same screen"; + } + if (same_screen(black, black_small)){ + return "frames of different sizes are the same screen"; + } + if (same_screen(black, VideoSnapshot())){ + return "a missing frame is the same screen"; + } + return true; +} + + +struct ScreenEventsCase{ + struct Input{ + std::function body; + }; + struct Expectation{ + }; + + std::string name; + Input input; + Expectation expectation; +}; + +class Test_ScreenEvents : public UnitTest{ +public: + explicit Test_ScreenEvents(ScreenEventsCase test_case) + : UnitTest(std::format("CommonTools::ScreenEvents - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_case.input.body(); + } + +private: + ScreenEventsCase m_case; +}; + +} // namespace + + +const ScreenEventsCase SCREEN_EVENTS_CASES[] = { + { + .name = "a set of events, its fade and its log text", + .input = {.body = test_set_and_describe}, + .expectation = {}, + }, + { + .name = "a fade is uniform, dark or white; a textured floor is none", + .input = {.body = test_fade_of_screen}, + .expectation = {}, + }, + { + .name = "the same screen: equal frames of one size", + .input = {.body = test_same_screen}, + .expectation = {}, + }, +}; + +void add_tests_ScreenEvents(UnitTestDatabase& database){ + for (const auto& item : SCREEN_EVENTS_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.h b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.h new file mode 100644 index 0000000000..3d1c84b44f --- /dev/null +++ b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.h @@ -0,0 +1,21 @@ +/* Screen Events Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ScreenEvents_ScreenEvents_Tests_H +#define PokemonAutomation_CommonTools_ScreenEvents_ScreenEvents_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ + + +// Registers unit tests for the shared screen events. +void add_tests_ScreenEvents(UnitTestDatabase& database); + + + +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenFades.h b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenFades.h new file mode 100644 index 0000000000..a153f49246 --- /dev/null +++ b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenFades.h @@ -0,0 +1,43 @@ +/* Screen Fades + * + * From: https://github.com/PokemonAutomation/ + * + * A fade to black or white, read from a screen and as screen events. + * + */ + +#ifndef PokemonAutomation_CommonTools_ScreenEvents_ScreenFades_H +#define PokemonAutomation_CommonTools_ScreenEvents_ScreenFades_H + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "ScreenEventTypes.h" + +namespace PokemonAutomation{ + + +// The event of a fade: FADE_BLACK, FADE_WHITE, or none for WarpFade::NONE. +ScreenEvents fade_events(WarpFade fade); +// The fade `events` show: BLACK before WHITE if they have both. +WarpFade fade_in(const ScreenEvents& events); + + +// A fade is uniform over the middle 80% of the screen, the same stddev +// test as the shared Black/WhiteScreenWatcher: a dim cave floor (mean +// about 46 a channel) is textured, so it is no fade. A tighter bound +// needs checking against such dim floors first. +constexpr double FADE_MAX_STDDEV_SUM = 10; +// Dark goes to an rgb sum of 225, as a cave mouth's fade is dim, 45 to 64 +// a channel, not black. +constexpr double FADE_MAX_DARK_SUM = 225; +// White from an rgb sum of 500, as the shared WhiteScreenWatcher's. +constexpr double FADE_MIN_WHITE_SUM = 500; +// The fade `middle` (the stats of the screen's middle 80%) shows, if any. +WarpFade fade_of(const ImageStats& middle); +// fade_of() for a screen. +WarpFade fade_of_screen(const ImageViewRGB32& screen); + + + +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/CommonTools/ScreenMachine/ScreenObservation.h b/SerialPrograms/Source/CommonTools/ScreenMachine/ScreenObservation.h new file mode 100644 index 0000000000..737b074d77 --- /dev/null +++ b/SerialPrograms/Source/CommonTools/ScreenMachine/ScreenObservation.h @@ -0,0 +1,44 @@ +/* Screen Observation + * + * From: https://github.com/PokemonAutomation/ + * + * What one look at the game showed, as facts rather than pixels: the + * events on screen (a fade, a dialog box, a battle) and named readings. A + * console fills it from a frame with the game's detectors; a simulation + * fills it from its model and has no frame. Code that decides on an + * observation alone therefore runs in both. + * + */ + +#ifndef PokemonAutomation_CommonTools_ScreenObservation_H +#define PokemonAutomation_CommonTools_ScreenObservation_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/ScreenEvents/ScreenEventTypes.h" + +namespace PokemonAutomation{ + + +// One look at the game. +struct ScreenObservation{ + // When the look was taken. Only a default; no reader treats min() as + // "not set". + WallClock when = WallClock::min(); + ScreenEvents events = {}; + // Named numbers the game's readers found, by names the game chooses; + // "heading" is degrees clockwise from north, [0, 360). + std::map> readings = {}; + // The frame looked at; none in a simulation. A state that needs it + // can only run on a console. + std::optional frame = std::nullopt; +}; + + + +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index f83b4ef374..721c9a5f72 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -25,6 +25,7 @@ #include "CommonFramework/Tools/GlobalThreadPools.h" #include "CommonTools/VisualDetectors/BlackBorderDetector.h" #include "CommonTools/OCR/OCR_Tests.h" +#include "CommonTools/ScreenEvents/ScreenEvents_Tests.h" #include "NintendoSwitch/Inference/NintendoSwitch_CheckOnlineDetector.h" #include "NintendoSwitch/Inference/NintendoSwitch_FailedToConnectDetector.h" @@ -72,6 +73,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ OCR::add_tests(ret); Kernels::add_tests(ret); Pokemon::add_tests_AutoStory(ret); + add_tests_ScreenEvents(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); NintendoSwitch::add_tests_UpdatePopupDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.cpp new file mode 100644 index 0000000000..212d51a1b8 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.cpp @@ -0,0 +1,40 @@ +/* Screen Observation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_ScreenObservation.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +ScreenObservation screen_observation(const ScreenEvents& events){ + // The events the story engine reads; the rest are left out. + constexpr ScreenEvent ENGINE_EVENTS[] = { + ScreenEvent::FADE_BLACK, + ScreenEvent::FADE_WHITE, + ScreenEvent::DIALOG_BOX, + ScreenEvent::BATTLE_STARTED, + ScreenEvent::PLAYER_CAN_MOVE, + ScreenEvent::SCREEN_STILL, + ScreenEvent::CHOICE_BOX, + ScreenEvent::INTERACT_PROMPT, + }; + ScreenObservation look; + for (ScreenEvent event : ENGINE_EVENTS){ + if (events.has(event)){ + look.events.set(event, true); + } + } + if (events.has(ScreenEvent::CHOICE_BOX)){ + look.events.set(ScreenEvent::DIALOG_BOX, true); + } + return look; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.h new file mode 100644 index 0000000000..2c1b7d8dd5 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.h @@ -0,0 +1,28 @@ +/* Screen Observation + * + * From: https://github.com/PokemonAutomation/ + * + * Bridges a ScreenEventObserver (ScreenEvents) to the story + * engine's look (ScreenObservation). + * + */ + +#ifndef PokemonAutomation_Pokemon_ScreenObservation_H +#define PokemonAutomation_Pokemon_ScreenObservation_H + +#include "CommonTools/ScreenMachine/ScreenObservation.h" +#include "CommonTools/ScreenEvents/ScreenEventTypes.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A ScreenEventObserver's events as one look for the story engine: the +// events the engine reads (not LOCATION_BANNER, BATTLE_ENDED or +// SWITCH_HOME_MENU), and CHOICE_BOX adds DIALOG_BOX. No time and no frame. +ScreenObservation screen_observation(const ScreenEvents& events); + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.cpp new file mode 100644 index 0000000000..00dc48e141 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.cpp @@ -0,0 +1,89 @@ +/* Story Action Registry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon_StoryActionRegistry.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +template +StoryActionRegistry::StoryActionRegistry(const StoryGame& game) + : m_game(game) +{ + for (const StoryAction& action : game.actions){ + m_specs.push_back(action.spec); + } +} + +template +const StoryAction* StoryActionRegistry::find(StoryStepKind kind, std::string_view name) const{ + for (const StoryAction& action : m_game.actions){ + if (action.spec.kind == kind && (name.empty() || action.spec.name == name)){ + return &action; + } + } + return nullptr; +} + +template +std::vector StoryActionRegistry::check(const StoryStep& step) const{ + if (step.kind == StoryStepKind::GAME && step.action.empty()){ + return {"no action"}; + } + const StoryAction* action = find(step.kind, step.action); + if (action == nullptr){ + return {std::format("unknown action \"{}\" for {}", step.action, story_step_kind_name(step.kind))}; + } + return story_args_errors(action->spec, step.args); +} + +template +std::vector StoryActionRegistry::lint(const StoryCheckpoint& checkpoint) const{ + std::vector problems; + if (checkpoint.id.empty()){ + problems.emplace_back("a checkpoint has no id"); + } + std::set names; + for (size_t c = 0; c < checkpoint.steps.size(); c++){ + const StoryStep& step = checkpoint.steps[c]; + const std::string where = std::format("{} step {} {}", checkpoint.id, c + 1, step.name); + if (step.name.empty() || !names.insert(step.name).second){ + problems.push_back(std::format("{}: empty or repeated name", where)); + } + for (const std::string& problem : check(step)){ + problems.push_back(std::format("{}: {}", where, problem)); + } + } + return problems; +} + +template +Outcome StoryActionRegistry::dispatch(StoryBackend& backend, const StoryStep& step, RunState& state) const{ + const StoryAction* action = find(step.kind, step.action); + if (action == nullptr || !action->handler){ + return outcome_failed(std::string(UNSUPPORTED_STEP), std::format( + "{} {}: the game has no action for it", story_step_kind_name(step.kind), step.action.empty() ? "default" : step.action + )); + } + if (action->spec.console_only && backend.kind() != StoryBackendKind::CONSOLE){ + return outcome_failed(std::string(CONSOLE_ONLY), std::format( + "{} runs only on a console, not on a {} backend", action->spec.name, story_backend_kind_name(backend.kind()) + )); + } + const StoryActionArgs args = with_fallbacks(action->spec, step.args); + return action->handler(backend, StoryActionCall{.step = step, .args = args}, state); +} + + +template class StoryActionRegistry; + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h new file mode 100644 index 0000000000..1e3d5b208e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h @@ -0,0 +1,77 @@ +/* Story Action Registry + * + * From: https://github.com/PokemonAutomation/ + * + * A game's actions, looked up by a step's kind and action name. It checks + * a step against its action's spec before anything runs, and runs a + * step's action with the spec's fallbacks filled in. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActionRegistry_H +#define PokemonAutomation_Pokemon_StoryActionRegistry_H + +#include +#include +#include +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" +#include "Pokemon_StoryGame.h" +#include "Pokemon_ZonePose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The failure of a console_only action (StoryActionSpec) on a backend that +// is not a console. Every attempt would fail the same way, so the engine +// does not reload for it. +inline constexpr std::string_view CONSOLE_ONLY = "console_only"; + +// The failure of a step whose action the game does not have. +inline constexpr std::string_view UNSUPPORTED_STEP = "unsupported_step"; + +// `game`'s actions. `game` must outlive the registry. +template +class StoryActionRegistry{ +public: + explicit StoryActionRegistry(const StoryGame& game); + StoryActionRegistry(const StoryActionRegistry&) = delete; + StoryActionRegistry& operator=(const StoryActionRegistry&) = delete; + + // Every action's spec, for the JSON reader (read_story_checkpoint()). + const std::vector& specs() const{ + return m_specs; + } + + // What is wrong with `step` before it runs: an action that is not + // registered, args that don't fit its spec. + std::vector check(const StoryStep& step) const; + + // check() for each step of `checkpoint`, and its step names (none + // empty, none repeated). + std::vector lint(const StoryCheckpoint& checkpoint) const; + + // Runs `step`'s action with its args' fallbacks filled in; a step with + // no registered action fails as UNSUPPORTED_STEP, a console_only + // action on another backend as CONSOLE_ONLY, before any input. + Outcome dispatch(StoryBackend& backend, const StoryStep& step, RunState& state) const; + +private: + // The action of `kind` named `name`; for an empty name, the kind's + // first. Null when there is none. + const StoryAction* find(StoryStepKind kind, std::string_view name) const; + + const StoryGame& m_game; + std::vector m_specs; +}; + +// Instantiated for ZonePose (Pokemon_ZonePose.h), in +// Pokemon_StoryActionRegistry.cpp. +extern template class StoryActionRegistry; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend.cpp new file mode 100644 index 0000000000..320b2789d2 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend.cpp @@ -0,0 +1,42 @@ +/* Story Backend + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryBackend.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string_view story_backend_kind_name(StoryBackendKind kind){ + switch (kind){ + case StoryBackendKind::CONSOLE: + return "console"; + case StoryBackendKind::SIMULATION: + return "simulation"; + case StoryBackendKind::SCRIPT: + return "script"; + } + return "unknown"; +} + +double direction_degrees(Direction direction){ + switch (direction){ + case Direction::NORTH: + return 0; + case Direction::EAST: + return 90; + case Direction::SOUTH: + return 180; + case Direction::WEST: + return -90; + } + return 0; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend.h new file mode 100644 index 0000000000..5d27359cf7 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend.h @@ -0,0 +1,89 @@ +/* Story Backend + * + * From: https://github.com/PokemonAutomation/ + * + * Input and observation, nothing else: what the story engine drives. One + * per run. A console backend wraps the console's controller and video and + * builds each observation with the game's detectors; a simulation backend + * wraps a model of the game. The engine and every action run the same on + * both. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryBackend_H +#define PokemonAutomation_Pokemon_StoryBackend_H + +#include +#include +#include "Common/Cpp/CancellableScope.h" +#include "Common/Cpp/Time.h" +#include "CommonTools/ScreenMachine/ScreenObservation.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h" +#include "Pokemon/AutoStory/Pokemon_StoryOutcome.h" +#include "Pokemon/Navigation/Pokemon_Direction.h" +#include "Pokemon_StoryPoseConcept.h" +#include "Pokemon_ZonePose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How fast a held direction moves the player. +enum class StoryPace{ + WALK, + RUN, +}; + +// What a backend plays on. An action declared console_only +// (StoryActionSpec) runs only on CONSOLE: it reads or presses through +// screens nothing else models (menus, a keyboard, a battle AI). +enum class StoryBackendKind{ + CONSOLE, + SIMULATION, + SCRIPT, // a scripted fake, for unit tests +}; + +// "console", "simulation", "script". +std::string_view story_backend_kind_name(StoryBackendKind kind); + +// `direction` as degrees clockwise of straight on (0, 90, 180, -90): a +// game with no tiles moves a direction's taps and holds as stick(). +double direction_degrees(Direction direction); + +// One look at the game, with where the player is when a reader knows it +// (StoryGame::readers fill `pose` and the readings). +template +struct Observation : public ScreenObservation{ + std::optional pose = std::nullopt; +}; + +// The engine's only way to the game. +// code-health: allow public_methods -- the agreed backend boundary is these low-level calls; splitting them would make every action take two objects +template +class StoryBackend{ +public: + virtual ~StoryBackend() = default; + + virtual StoryBackendKind kind() const = 0; + + virtual void press(NintendoSwitch::Button button, Milliseconds hold, Milliseconds release) = 0; + // One tile in `direction`, or a turn to face it. + virtual void tap(Direction direction) = 0; + virtual void hold(Direction direction, Milliseconds duration, StoryPace pace) = 0; + // The move stick held at `degrees` clockwise from north (straight on, + // for a camera-relative game) for `duration`, then let go for `release` + // (a turn's time to finish) like press(): the free-moving games' walk + // and turn. A tile game's hold() is this at a multiple of 90. + virtual void stick(double degrees, Milliseconds duration, Milliseconds release, StoryPace pace) = 0; + virtual void wait(Milliseconds duration) = 0; + // The game now, once every input sent so far has been done. + virtual Observation observe() = 0; + virtual void log(std::string_view line) = 0; + virtual CancellableScope& scope() = 0; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend_Tests.cpp new file mode 100644 index 0000000000..5c779c0f7b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend_Tests.cpp @@ -0,0 +1,163 @@ +/* Story Backend Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_ScreenObservation.h" +#include "Pokemon_StoryBackend.h" +#include "Pokemon_StoryFakeBackend.h" +#include "Pokemon_ZonePose.h" +#include "Pokemon_StoryBackend_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +using namespace std::chrono_literals; + + +// A look at one piece: what it gives as text. +struct BackendCase{ + std::string name; + struct Input{ + std::function read; + }; + Input input; + struct Expectation{ + std::string text; + }; + Expectation expectation; +}; + +std::string degrees_text(){ + return std::format( + "{} {} {} {}", + direction_degrees(Direction::NORTH), direction_degrees(Direction::EAST), + direction_degrees(Direction::SOUTH), direction_degrees(Direction::WEST) + ); +} + +std::string observation_text(ScreenEvents events){ + return describe(screen_observation(events).events); +} + +std::string matches_text(){ + const ZonePose city{.zone = "LumioseCity"}; + const ZonePose hotel{.zone = "HotelZ"}; + const ZonePose any{}; + return std::format( + "{} {} {} {}", + pose_matches(city, city), pose_matches(city, hotel), pose_matches(hotel, any), pose_matches(any, city) + ); +} + +// The scripted backend's inputs and looks. +std::string fake_text(CancellableScope& scope){ + Observation fade; + fade.events = {ScreenEvent::FADE_WHITE}; + FakeStoryBackend backend({.looks = {Observation{}, fade}}, scope); + backend.press(NintendoSwitch::BUTTON_A, 80ms, 80ms); + backend.tap(Direction::EAST); + backend.hold(Direction::NORTH, 400ms, StoryPace::RUN); + backend.stick(90, 150ms, 300ms, StoryPace::WALK); + backend.wait(100ms); + std::string looks; + for (size_t c = 0; c < 3; c++){ + looks += std::format("{}{}", looks.empty() ? "" : " / ", describe(backend.observe().events)); + } + std::string text; + for (const std::string& input : backend.inputs()){ + text += input + ", "; + } + return text + looks; +} + +const BackendCase CASES[] = { + { + .name = "directions as stick degrees", + .input = {.read = [](CancellableScope&){ return degrees_text(); }}, + .expectation = {.text = "0 90 180 -90"}, + }, + { + .name = "backend kinds by name", + .input = {.read = [](CancellableScope&){ + return std::format( + "{} {} {}", story_backend_kind_name(StoryBackendKind::CONSOLE), + story_backend_kind_name(StoryBackendKind::SIMULATION), story_backend_kind_name(StoryBackendKind::SCRIPT) + ); + }}, + .expectation = {.text = "console simulation script"}, + }, + { + .name = "a look keeps the engine's events", + .input = {.read = [](CancellableScope&){ + return observation_text({ScreenEvent::FADE_WHITE, ScreenEvent::LOCATION_BANNER, ScreenEvent::SWITCH_HOME_MENU}); + }}, + .expectation = {.text = "white fade"}, + }, + { + .name = "a choice box in a look is also a dialog box", + .input = {.read = [](CancellableScope&){ return observation_text({ScreenEvent::CHOICE_BOX}); }}, + .expectation = {.text = "dialog box, choice box"}, + }, + { + .name = "a zone pose matches its zone, or any zone when the target names none", + .input = {.read = [](CancellableScope&){ return matches_text(); }}, + .expectation = {.text = "true false true false"}, + }, + { + .name = "a zone pose as text", + .input = {.read = [](CancellableScope&){ + return std::format("{} / {}", pose_text(ZonePose{.zone = "HotelZ"}), pose_text(ZonePose{})); + }}, + .expectation = {.text = "zone HotelZ / zone unknown"}, + }, + { + .name = "the scripted backend records inputs and repeats its last look", + .input = {.read = fake_text}, + .expectation = {.text = "press A, tap east, hold north 400ms run, stick 90deg 150ms walk, release 300ms, wait 100ms, " + "nothing / white fade / white fade"}, + }, +}; + + +class StoryBackendTest : public UnitTest{ +public: + explicit StoryBackendTest(BackendCase test_case) + : UnitTest(std::format("Pokemon::StoryBackend - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope& scope) const override{ + const std::string got = m_case.input.read(scope); + if (got != m_case.expectation.text){ + return std::format("expected \"{}\", got \"{}\"", m_case.expectation.text, got); + } + return true; + } + +private: + BackendCase m_case; +}; + +} // namespace + + +void add_tests_StoryBackend(UnitTestDatabase& database){ + for (const BackendCase& test : CASES){ + database.add(test); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend_Tests.h new file mode 100644 index 0000000000..01cdff62ca --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend_Tests.h @@ -0,0 +1,23 @@ +/* Story Backend Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryBackend_Tests_H +#define PokemonAutomation_Pokemon_StoryBackend_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the backend's pieces: directions, a look from screen events, zone poses and the scripted backend. +void add_tests_StoryBackend(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp new file mode 100644 index 0000000000..2d2db38d19 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp @@ -0,0 +1,175 @@ +/* Story Engine + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_CheckpointAttempts.h" +#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "Pokemon_StoryEngine.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// A failure every attempt would repeat: no reload for it. +bool repeats_on_reload(const Outcome& failure){ + return failure.failure == GAME_NOT_RUNNING || failure.failure == CONSOLE_ONLY || failure.failure == "lint_failed"; +} + +} // namespace + + +template +StoryEngine::StoryEngine(const StoryGame& game, StoryBackend& backend) + : m_game(game) + , m_backend(backend) + , m_registry(game) + , m_runner(m_registry, backend) +{} + +template +StoryEngineReport StoryEngine::run_checkpoint(const StoryCheckpoint& checkpoint, RunState& state){ + StoryEngineReport report; + const std::vector problems = m_registry.lint(checkpoint); + if (!problems.empty()){ + for (const std::string& problem : problems){ + m_backend.log(std::format("[Lint] {}", problem)); + } + report.run.failure = outcome_failed("lint_failed", problems.front()); + return report; + } + report.run = run_steps(checkpoint, state); + if (!report.run.completed){ + m_backend.log(std::format("[Save] {}: run failed: not saved", checkpoint.id)); + return report; + } + report.passed = true; + save_if_passed(checkpoint, report); + return report; +} + +template +Outcome StoryEngine::reload(RunState& state){ + state = RunState{}; + if (!m_game.reload){ + return outcome_failed("reload_failed", "the game has no reload"); + } + const Outcome reloaded = m_game.reload(m_backend); + if (!reloaded.succeeded()){ + return outcome_failed("reload_failed", to_string(reloaded)); + } + if (reloaded.pose){ + state.pose = *reloaded.pose; + } + return outcome_ok(); +} + +template +StoryEngineReport StoryEngine::run_with_retries( + const StoryCheckpoint& checkpoint, size_t attempts, RunState& state, CheckpointRun& run +){ + StoryEngineReport report; + const CheckpointAttempts loop{ + .max_attempts = attempts, + .run = [&](size_t attempt){ + run.attempts = attempt; + report = run_checkpoint(checkpoint, state); + if (report.passed){ + return AttemptResult::PASSED; + } + return repeats_on_reload(report.run.failure) ? AttemptResult::FINAL : AttemptResult::FAILED; + }, + .reset = [&](size_t next_attempt){ + m_backend.log(checkpoint_reset_line(checkpoint.id, next_attempt, attempts)); + const Outcome reloaded = reload(state); + if (!reloaded.succeeded()){ + report.run.completed = false; + report.run.failed_name.clear(); + report.run.failure = reloaded; + return false; + } + return true; + }, + .log = [this](const std::string& line){ + m_backend.log(line); + }, + }; + run.passed = run_checkpoint_attempts(checkpoint.id, loop).passed; + return report; +} + +template +SegmentReport StoryEngine::run_segment( + std::string_view id, std::span checkpoints, size_t attempts_per_checkpoint, + RunState& state +){ + SegmentReport report; + m_backend.log(std::format("[Segment] {}: start, {} checkpoints", id, checkpoints.size())); + // Whether a reload returns to the save the next checkpoint starts from. + bool start_saved = true; + for (const StoryCheckpoint& checkpoint : checkpoints){ + const size_t attempts = start_saved ? attempts_per_checkpoint : 1; + if (!start_saved && attempts_per_checkpoint > 1){ + m_backend.log(std::format("[Segment] {}: {}: no save at its start, so no reload if it fails", id, checkpoint.id)); + } + report.checkpoints_run++; + report.runs.push_back(CheckpointRun{.id = checkpoint.id}); + const StoryEngineReport result = run_with_retries(checkpoint, attempts, state, report.runs.back()); + report.reloads += report.runs.back().attempts - 1; + if (!result.passed){ + report.failed_checkpoint = checkpoint.id; + report.failed_event = result.run.failed_name; + report.failure = result.run.failure; + m_backend.log(std::format("[Segment] {}: failed at {}: {}", id, checkpoint.id, to_string(report.failure))); + return report; + } + start_saved = result.saved; + } + report.completed = true; + m_backend.log(std::format("[Segment] {}: done, {} checkpoints", id, report.checkpoints_run)); + return report; +} + +template +CheckpointReport StoryEngine::run_steps(const StoryCheckpoint& checkpoint, RunState& state){ + Checkpoint events{.id = checkpoint.id, .events = {}}; + for (const StoryStep& step : checkpoint.steps){ + events.events.push_back(Event{ + .name = step.name, + .why = step.why, + .act = [this, &step](RunState& run_state){ + return m_runner.act(step, run_state); + }, + }); + } + EventLogger log = [this](const std::string& line){ + m_backend.log(line); + }; + return Pokemon::run_checkpoint(state, events, log); +} + +template +void StoryEngine::save_if_passed(const StoryCheckpoint& checkpoint, StoryEngineReport& report){ + if (!m_game.save){ + m_backend.log(std::format("[Save] {}: not saved: the game has no save", checkpoint.id)); + return; + } + const Outcome saved = m_game.save(m_backend, checkpoint); + report.saved = saved.succeeded(); + m_backend.log(std::format("[Save] {}: {}", checkpoint.id, report.saved ? "saved" : std::format("save failed: {}", to_string(saved)))); +} + + +template class StoryEngine; + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.h new file mode 100644 index 0000000000..fa4b5b1141 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.h @@ -0,0 +1,94 @@ +/* Story Engine + * + * From: https://github.com/PokemonAutomation/ + * + * The one story executor, for every game and both backends. A run of a + * checkpoint lints its steps against the game's actions (a problem fails + * the run before any input), runs them through the event layer + * (Pokemon_StoryEvents.h) with the step runner, and saves at the end of + * each checkpoint that passed (StoryGame::save: the game knows whether + * the row autosaved). A failed checkpoint is retried after the game's + * reload, when the reload returns to the save it started from. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryEngine_H +#define PokemonAutomation_Pokemon_StoryEngine_H + +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_StoryCheckpointTypes.h" +#include "Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h" +#include "Pokemon_StoryActionRegistry.h" +#include "Pokemon_StoryStepRunner.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// An engine run of one checkpoint. +struct StoryEngineReport{ + // The steps' run. A checkpoint that failed its lint has none. + CheckpointReport run = {}; + // The steps all completed. + bool passed = false; + // The game saved at the checkpoint's end. + bool saved = false; +}; + +// Runs `game`'s checkpoints on `backend`. Both must outlive it. +template +class StoryEngine{ +public: + StoryEngine(const StoryGame& game, StoryBackend& backend); + StoryEngine(const StoryEngine&) = delete; + StoryEngine& operator=(const StoryEngine&) = delete; + + const StoryActionRegistry& registry() const{ + return m_registry; + } + + // Runs `checkpoint` from `state` and, when it passed, saves + // (StoryGame::save). + StoryEngineReport run_checkpoint(const StoryCheckpoint& checkpoint, RunState& state); + + // `checkpoints` in order from the save the game is on, each run with + // run_checkpoint(), until one does not pass. One that fails is run + // again after a reload (StoryGame::reload), up to + // `attempts_per_checkpoint` runs, only when a reload returns to the + // save it started from: the first checkpoint's, or one the checkpoint + // before it saved at its end. No reload for a failure every attempt + // would repeat: a lint, a console_only action, the game not running. + // Logs "[Segment] : ..." lines. + SegmentReport run_segment( + std::string_view id, std::span checkpoints, size_t attempts_per_checkpoint, + RunState& state + ); + +private: + CheckpointReport run_steps(const StoryCheckpoint& checkpoint, RunState& state); + void save_if_passed(const StoryCheckpoint& checkpoint, StoryEngineReport& report); + // Empties `state` and reloads the last save; the reload's pose, if it + // says one, goes into `state`. + Outcome reload(RunState& state); + // One checkpoint of a segment until it passes or runs out of attempts. + StoryEngineReport run_with_retries( + const StoryCheckpoint& checkpoint, size_t attempts, RunState& state, CheckpointRun& run + ); + + const StoryGame& m_game; + StoryBackend& m_backend; + StoryActionRegistry m_registry; + StoryStepRunner m_runner; +}; + +// Instantiated for ZonePose (Pokemon_ZonePose.h), in +// Pokemon_StoryEngine.cpp. +extern template class StoryEngine; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp new file mode 100644 index 0000000000..603407ba56 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp @@ -0,0 +1,275 @@ +/* Story Engine Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The engine on a FakeStoryBackend: a test game whose actions answer as + * scripted (pass, fail, fail once, press, wait for a white fade in the + * scripted looks), so a run's report, inputs and retries are checked with + * no console. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_StoryEngine.h" +#include "Pokemon_StoryFakeBackend.h" +#include "Pokemon_StoryEngine_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +using namespace std::chrono_literals; + + +// What the test game's actions share across a run. +struct TestWorld{ + // How many times "fail_once" ran. + size_t fail_once_calls = 0; +}; + +StoryAction game_action(std::string name, StoryActionHandler handler){ + return StoryAction{ + .spec = {.kind = StoryStepKind::GAME, .name = std::move(name), .args = {}, .console_only = false}, + .handler = std::move(handler), + }; +} + +// The test game. Its save saves the checkpoints of `autosaves`; its +// reload works unless `reload_fails`. +StoryGame test_game(TestWorld& world, std::set autosaves, bool reload_fails){ + StoryGame game; + game.id = "test"; + game.actions.push_back(game_action("ok", [](StoryBackend&, const StoryActionCall&, RunState&){ + return outcome_ok(); + })); + game.actions.push_back(game_action("fail", [](StoryBackend&, const StoryActionCall&, RunState&){ + return outcome_failed("scripted_failure"); + })); + game.actions.push_back(game_action("fail_once", [&world](StoryBackend&, const StoryActionCall&, RunState&){ + return world.fail_once_calls++ == 0 ? outcome_failed("scripted_failure") : outcome_ok(); + })); + game.actions.push_back(game_action("not_running", [](StoryBackend&, const StoryActionCall&, RunState&){ + return outcome_game_not_running(); + })); + game.actions.push_back(game_action("press_a", [](StoryBackend& backend, const StoryActionCall&, RunState&){ + backend.press(NintendoSwitch::BUTTON_A, 80ms, 80ms); + return outcome_ok(); + })); + StoryAction console = game_action("console", [](StoryBackend&, const StoryActionCall&, RunState&){ + return outcome_ok(); + }); + console.spec.console_only = true; + game.actions.push_back(std::move(console)); + // Walks north until a look shows a white fade, at most 3 slices. + game.actions.push_back(game_action("walk_to_fade", [](StoryBackend& backend, const StoryActionCall&, RunState&){ + for (size_t slice = 0; slice < 3; slice++){ + backend.hold(Direction::NORTH, 500ms, StoryPace::WALK); + if (backend.observe().events.has(ScreenEvent::FADE_WHITE)){ + return outcome_ok(); + } + } + return outcome_failed("no_fade", "no white fade in 3 slices"); + })); + game.save = [autosaves = std::move(autosaves)](StoryBackend&, const StoryCheckpoint& checkpoint){ + return autosaves.contains(checkpoint.id) ? outcome_ok() : outcome_failed("no_autosave"); + }; + game.reload = [reload_fails](StoryBackend& backend){ + backend.press(NintendoSwitch::BUTTON_HOME, 80ms, 80ms); + return reload_fails ? outcome_failed("no_game") : outcome_ok(); + }; + return game; +} + +// A checkpoint of GAME steps, each named for its action. +StoryCheckpoint checkpoint_of(std::string id, std::vector actions){ + StoryCheckpoint checkpoint; + checkpoint.id = std::move(id); + checkpoint.title = "Test"; + for (std::string& action : actions){ + checkpoint.steps.push_back(StoryStep{.kind = StoryStepKind::GAME, .name = action, .why = "", .action = action, .args = {}}); + } + return checkpoint; +} + +// A look that shows `events`. +Observation look(ScreenEvents events){ + Observation observation; + observation.events = events; + return observation; +} + +// "a b": the strings, space-separated. +std::string joined(const std::vector& texts, std::string_view separator = " "){ + std::string text; + for (const std::string& part : texts){ + text += (text.empty() ? "" : std::string(separator)) + part; + } + return text; +} + +// "done | runs 01.00:pass/1 | reloads 0" or +// "failed at 01.01 fail: scripted_failure | runs ... | reloads 1". +std::string summary(const SegmentReport& report){ + std::vector runs; + for (const CheckpointRun& run : report.runs){ + runs.push_back(std::format("{}:{}/{}", run.id, run.passed ? "pass" : "fail", run.attempts)); + } + const std::string verdict = report.completed + ? "done" + : std::format("failed at {} {}: {}", report.failed_checkpoint, report.failed_event, report.failure.failure); + return std::format("{} | runs {} | reloads {}", verdict, joined(runs), report.reloads); +} + + +struct SegmentCase{ + std::string name; + struct Input{ + std::vector checkpoints; + size_t attempts = 1; + std::set autosaves = {}; + bool reload_fails = false; + std::vector> looks = {}; + StoryBackendKind kind = StoryBackendKind::SCRIPT; + }; + Input input; + struct Expectation{ + // summary() of the segment's report. + std::string summary; + // The backend's inputs, joined by ", ". + std::string inputs = {}; + // A log line the run wrote, if any is checked. + std::string line = {}; + }; + Expectation expectation; +}; + +const SegmentCase SEGMENT_CASES[] = { + { + .name = "two checkpoints pass and save", + .input = {.checkpoints = {checkpoint_of("01.00", {"ok", "press_a"}), checkpoint_of("01.01", {"ok"})}, .autosaves = {"01.00", "01.01"}}, + .expectation = {.summary = "done | runs 01.00:pass/1 01.01:pass/1 | reloads 0", .inputs = "press A", .line = "[Save] 01.00: saved"}, + }, + { + .name = "a failed step stops the segment with its event", + .input = {.checkpoints = {checkpoint_of("01.00", {"ok", "fail", "press_a"})}}, + .expectation = {.summary = "failed at 01.00 fail: scripted_failure | runs 01.00:fail/1 | reloads 0", .inputs = "", .line = "[Checkpoint] 01.00: failed at 2 fail: scripted_failure"}, + }, + { + .name = "a failed checkpoint passes after a reload", + .input = {.checkpoints = {checkpoint_of("01.01", {"fail_once"})}, .attempts = 3}, + .expectation = {.summary = "done | runs 01.01:pass/2 | reloads 1", .inputs = "press HOME", .line = "[Checkpoint] 01.01: failed, resetting for attempt 2/3"}, + }, + { + .name = "no reload after a checkpoint that did not save", + .input = {.checkpoints = {checkpoint_of("01.00", {"ok"}), checkpoint_of("01.01", {"fail"})}, .attempts = 3}, + .expectation = {.summary = "failed at 01.01 fail: scripted_failure | runs 01.00:pass/1 01.01:fail/1 | reloads 0", .inputs = "", .line = "[Segment] test: 01.01: no save at its start, so no reload if it fails"}, + }, + { + .name = "a reload after a checkpoint that saved", + .input = {.checkpoints = {checkpoint_of("01.00", {"ok"}), checkpoint_of("01.01", {"fail"})}, .attempts = 2, .autosaves = {"01.00"}}, + .expectation = {.summary = "failed at 01.01 fail: scripted_failure | runs 01.00:pass/1 01.01:fail/2 | reloads 1", .inputs = "press HOME"}, + }, + { + .name = "a failed reload ends the segment", + .input = {.checkpoints = {checkpoint_of("01.01", {"fail"})}, .attempts = 3, .reload_fails = true}, + .expectation = {.summary = "failed at 01.01 : reload_failed | runs 01.01:fail/1 | reloads 0", .inputs = "press HOME"}, + }, + { + .name = "the game not running is not retried", + .input = {.checkpoints = {checkpoint_of("01.01", {"not_running"})}, .attempts = 3}, + .expectation = {.summary = "failed at 01.01 not_running: game_not_running | runs 01.01:fail/1 | reloads 0"}, + }, + { + .name = "an unknown action fails the lint before any input", + .input = {.checkpoints = {checkpoint_of("01.00", {"press_a", "dance"})}, .attempts = 3}, + .expectation = {.summary = "failed at 01.00 : lint_failed | runs 01.00:fail/1 | reloads 0", .inputs = "", .line = "[Lint] 01.00 step 2 dance: unknown action \"dance\" for GAME"}, + }, + { + .name = "a console_only action fails off a console", + .input = {.checkpoints = {checkpoint_of("01.00", {"console"})}, .attempts = 3}, + .expectation = {.summary = "failed at 01.00 console: console_only | runs 01.00:fail/1 | reloads 0"}, + }, + { + .name = "a console_only action runs on a console", + .input = {.checkpoints = {checkpoint_of("01.00", {"console"})}, .kind = StoryBackendKind::CONSOLE}, + .expectation = {.summary = "done | runs 01.00:pass/1 | reloads 0"}, + }, + { + .name = "a walk ends on the scripted white fade", + .input = {.checkpoints = {checkpoint_of("01.01", {"walk_to_fade"})}, .looks = {look({}), look({ScreenEvent::FADE_WHITE})}}, + .expectation = {.summary = "done | runs 01.01:pass/1 | reloads 0", .inputs = "hold north 500ms walk, hold north 500ms walk"}, + }, + { + .name = "a walk whose fade never shows fails", + .input = {.checkpoints = {checkpoint_of("01.01", {"walk_to_fade"})}, .looks = {look({ScreenEvent::DIALOG_BOX})}}, + .expectation = { + .summary = "failed at 01.01 walk_to_fade: no_fade | runs 01.01:fail/1 | reloads 0", + .inputs = "hold north 500ms walk, hold north 500ms walk, hold north 500ms walk", + .line = "[Step] walk_to_fade GAME/walk_to_fade: failed: no_fade: no white fade in 3 slices", + }, + }, +}; + +UnitTestResult check_segment(const SegmentCase& test, CancellableScope& scope){ + TestWorld world; + const StoryGame game = test_game(world, test.input.autosaves, test.input.reload_fails); + FakeStoryBackend backend({.looks = test.input.looks, .kind = test.input.kind}, scope); + StoryEngine engine(game, backend); + RunState state; + const SegmentReport report = engine.run_segment("test", test.input.checkpoints, test.input.attempts, state); + const std::string got = summary(report); + if (got != test.expectation.summary){ + return std::format("expected \"{}\", got \"{}\"", test.expectation.summary, got); + } + const std::string inputs = joined(backend.inputs(), ", "); + if (inputs != test.expectation.inputs){ + return std::format("expected inputs \"{}\", got \"{}\"", test.expectation.inputs, inputs); + } + if (test.expectation.line.empty()){ + return true; + } + for (const std::string& line : backend.lines()){ + if (line == test.expectation.line){ + return true; + } + } + return std::format("expected the line \"{}\" in:\n{}", test.expectation.line, joined(backend.lines(), "\n")); +} + + +class StoryEngineTest : public UnitTest{ +public: + explicit StoryEngineTest(SegmentCase test_case) + : UnitTest(std::format("Pokemon::StoryEngine - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope& scope) const override{ + return check_segment(m_case, scope); + } + +private: + SegmentCase m_case; +}; + +} // namespace + + +void add_tests_StoryEngine(UnitTestDatabase& database){ + for (const SegmentCase& test : SEGMENT_CASES){ + database.add(test); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.h new file mode 100644 index 0000000000..0f5713f2df --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.h @@ -0,0 +1,23 @@ +/* Story Engine Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryEngine_Tests_H +#define PokemonAutomation_Pokemon_StoryEngine_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the story engine on a scripted backend: runs, lint, retries and saves. +void add_tests_StoryEngine(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.cpp new file mode 100644 index 0000000000..e6008b2118 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.cpp @@ -0,0 +1,92 @@ +/* Story Fake Backend + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon_StoryFakeBackend.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// "walk" or "run". +std::string_view pace_name(StoryPace pace){ + return pace == StoryPace::RUN ? "run" : "walk"; +} + + +} // namespace + + +template +FakeStoryBackend::FakeStoryBackend(FakeStoryScript script, CancellableScope& scope) + : m_script(std::move(script)) + , m_scope(scope) +{} + +template +StoryBackendKind FakeStoryBackend::kind() const{ + return m_script.kind; +} + +template +void FakeStoryBackend::press(NintendoSwitch::Button button, Milliseconds, Milliseconds){ + m_inputs.push_back(std::format("press {}", NintendoSwitch::button_to_string(button))); +} + +template +void FakeStoryBackend::tap(Direction direction){ + m_inputs.push_back(std::format("tap {}", direction_name(direction))); +} + +template +void FakeStoryBackend::hold(Direction direction, Milliseconds duration, StoryPace pace){ + m_inputs.push_back(std::format("hold {} {}ms {}", direction_name(direction), duration.count(), pace_name(pace))); +} + +template +void FakeStoryBackend::stick(double degrees, Milliseconds duration, Milliseconds release, StoryPace pace){ + std::string input = std::format("stick {}deg {}ms {}", degrees, duration.count(), pace_name(pace)); + if (release > Milliseconds::zero()){ + input += std::format(", release {}ms", release.count()); + } + m_inputs.push_back(std::move(input)); +} + +template +void FakeStoryBackend::wait(Milliseconds duration){ + m_inputs.push_back(std::format("wait {}ms", duration.count())); +} + +template +Observation FakeStoryBackend::observe(){ + if (m_script.looks.empty()){ + return {}; + } + const size_t look = m_next_look < m_script.looks.size() ? m_next_look++ : m_script.looks.size() - 1; + return m_script.looks[look]; +} + +template +void FakeStoryBackend::log(std::string_view line){ + m_lines.emplace_back(line); +} + +template +CancellableScope& FakeStoryBackend::scope(){ + return m_scope; +} + + +template class FakeStoryBackend; + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.h new file mode 100644 index 0000000000..2d27bc1c2e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.h @@ -0,0 +1,82 @@ +/* Story Fake Backend + * + * From: https://github.com/PokemonAutomation/ + * + * A scripted game for engine tests, with no console and no model: each + * observe() returns the script's next look (the last one repeats), every + * input and log line is recorded. A fault is a script: a walk whose fade + * never comes. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryFakeBackend_H +#define PokemonAutomation_Pokemon_StoryFakeBackend_H + +#include +#include +#include +#include +#include "Pokemon_StoryBackend.h" +#include "Pokemon_ZonePose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What a FakeStoryBackend shows and does. +template +struct FakeStoryScript{ + // observe()'s answers in order; the last repeats. None: an empty look. + std::vector> looks = {}; + // What it says it plays on: SCRIPT, or CONSOLE to run a console_only + // action's code in a test. + StoryBackendKind kind = StoryBackendKind::SCRIPT; +}; + +// The backend of the engine's unit tests and of a game's scripted tests, +// for any pose type. +// code-health: allow public_methods -- the backend calls it fakes plus the two recordings tests read; nothing to split +template +class FakeStoryBackend : public StoryBackend{ +public: + FakeStoryBackend(FakeStoryScript script, CancellableScope& scope); + + // Each input, in order: "press A", "press +" (by button_to_string()), + // "tap north", "hold east 400ms walk", "stick 90deg 150ms walk", + // "stick 90deg 150ms walk, release 300ms" (a release only when not + // zero), "wait 100ms". + const std::vector& inputs() const{ + return m_inputs; + } + // Each log line, in order. + const std::vector& lines() const{ + return m_lines; + } + + virtual StoryBackendKind kind() const override; + virtual void press(NintendoSwitch::Button button, Milliseconds hold, Milliseconds release) override; + virtual void tap(Direction direction) override; + virtual void hold(Direction direction, Milliseconds duration, StoryPace pace) override; + virtual void stick(double degrees, Milliseconds duration, Milliseconds release, StoryPace pace) override; + virtual void wait(Milliseconds duration) override; + virtual Observation observe() override; + virtual void log(std::string_view line) override; + virtual CancellableScope& scope() override; + +private: + FakeStoryScript m_script; + CancellableScope& m_scope; + size_t m_next_look = 0; + std::vector m_inputs; + std::vector m_lines; +}; + +// Instantiated for ZonePose (Pokemon_ZonePose.h), in +// Pokemon_StoryFakeBackend.cpp. +extern template class FakeStoryBackend; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryGame.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryGame.h new file mode 100644 index 0000000000..2f4393ba46 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryGame.h @@ -0,0 +1,69 @@ +/* Story Game + * + * From: https://github.com/PokemonAutomation/ + * + * What a game hands the story engine: its actions, its save and its + * reload, as data plus functions. No subclassing. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryGame_H +#define PokemonAutomation_Pokemon_StoryGame_H + +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_StoryOutcome.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" +#include "Pokemon_StoryBackend.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What an action is asked to do: the step it runs (its name and why, for +// the log and for what an action tunes by step) and the step's args with +// their fallbacks filled in. Both live for the call only. +struct StoryActionCall{ + const StoryStep& step; + const StoryActionArgs& args; +}; + +// An action's code: reads its call's args and drives the backend. A +// succeeded action that knows where it left the player returns that pose +// in its Outcome. +template +using StoryActionHandler = std::function& backend, const StoryActionCall& call, RunState& state)>; + +// An action: its spec (kind, name, args) and its code. +template +struct StoryAction{ + StoryActionSpec spec = {}; + StoryActionHandler handler = {}; +}; + +// A game, for the engine. +template +struct StoryGame{ + // "frlg", "bdsp", "plza". + std::string id = {}; + // The game's actions. A kind's first is its default, the action of a + // step that names none. + std::vector> actions = {}; + // The game's save (a wait for an autosave) at the end of `checkpoint`. + // Optional: with none, nothing saves. + std::function& backend, const StoryCheckpoint& checkpoint)> save = {}; + // Back to the last save. A succeeded reload that knows where it left + // the player returns that pose in its Outcome. Optional: with none, a + // failed checkpoint is not retried. + std::function& backend)> reload = {}; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryPoseConcept.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryPoseConcept.h new file mode 100644 index 0000000000..62e8b1dffd --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryPoseConcept.h @@ -0,0 +1,34 @@ +/* Story Pose Concept + * + * From: https://github.com/PokemonAutomation/ + * + * What the story engine needs of a game's pose type: whether a pose read + * off the game is a target, and a line of text for the log. A game that + * moves freely brings its own type (PLZA: ZonePose, a zone until it has a + * position reader). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryPoseConcept_H +#define PokemonAutomation_Pokemon_StoryPoseConcept_H + +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A pose the engine can carry: pose_matches(actual, target) and +// pose_text(pose), found by argument-dependent lookup. +template +concept StoryPose = std::copyable && requires(const PoseType& actual, const PoseType& target){ + { pose_matches(actual, target) } -> std::convertible_to; + { pose_text(actual) } -> std::convertible_to; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.cpp new file mode 100644 index 0000000000..fa85fb34e2 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.cpp @@ -0,0 +1,48 @@ +/* Story Step Runner + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon_StoryStepRunner.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// "GAME/walk" or "TALK/default": the step's kind and action. +std::string step_label(const StoryStep& step){ + return std::format("{}/{}", story_step_kind_name(step.kind), step.action.empty() ? "default" : step.action); +} + +} // namespace + + +template +StoryStepRunner::StoryStepRunner(const StoryActionRegistry& registry, StoryBackend& backend) + : m_registry(registry) + , m_backend(backend) +{} + +template +Outcome StoryStepRunner::act(const StoryStep& step, RunState& state){ + m_backend.scope().throw_if_cancelled(); + Outcome outcome = m_registry.dispatch(m_backend, step, state); + m_backend.log(std::format( + "[Step] {} {}: {}", step.name, step_label(step), + outcome.succeeded() ? "ok" : std::format("failed: {}", to_string(outcome)) + )); + return outcome; +} + + +template class StoryStepRunner; + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.h new file mode 100644 index 0000000000..916cb89420 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.h @@ -0,0 +1,46 @@ +/* Story Step Runner + * + * From: https://github.com/PokemonAutomation/ + * + * Runs one story step on a backend: runs its action through the registry + * and logs a "[Step]" line. One step executor for every game that has a + * StoryBackend, on a console or in a simulation. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepRunner_H +#define PokemonAutomation_Pokemon_StoryStepRunner_H + +#include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" +#include "Pokemon_StoryActionRegistry.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Runs steps with `registry`'s actions on `backend`. Both must outlive it. +template +class StoryStepRunner{ +public: + StoryStepRunner(const StoryActionRegistry& registry, StoryBackend& backend); + StoryStepRunner(const StoryStepRunner&) = delete; + StoryStepRunner& operator=(const StoryStepRunner&) = delete; + + // `step`'s action, once the run is not cancelled, then the "[Step]" + // line. + Outcome act(const StoryStep& step, RunState& state); + +private: + const StoryActionRegistry& m_registry; + StoryBackend& m_backend; +}; + +// Instantiated for ZonePose (Pokemon_ZonePose.h), in +// Pokemon_StoryStepRunner.cpp. +extern template class StoryStepRunner; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 294fca3723..9546633e20 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -15,8 +15,12 @@ #include "Data/Pokemon_AuthoredCheckpointJson_Tests.h" #include "Data/Pokemon_StoryFiles_Tests.h" #include "Data/Pokemon_StoryStepJson_Tests.h" +#include "Engine/Pokemon_StoryBackend_Tests.h" +#include "Engine/Pokemon_StoryEngine_Tests.h" #include "Options/Pokemon_StoryRangeOptions_Tests.h" #include "Pokemon_AutoStorySelect_Tests.h" +#include "Pokemon_CheckpointAttempts_Tests.h" +#include "Pokemon_StoryEvents_Tests.h" #include "Pokemon_StoryLog_Tests.h" #include "Types/Pokemon_StoryActionArg_Tests.h" @@ -33,6 +37,10 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_StoryStepJson(database); add_tests_AuthoredCheckpointJson(database); add_tests_StoryFiles(database); + add_tests_StoryBackend(database); + add_tests_CheckpointAttempts(database); + add_tests_StoryEvents(database); + add_tests_StoryEngine(database); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.cpp new file mode 100644 index 0000000000..44edd9ff0c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.cpp @@ -0,0 +1,36 @@ +/* Checkpoint Attempts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryLog.h" +#include "Pokemon_CheckpointAttempts.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +CheckpointAttemptsResult run_checkpoint_attempts(std::string_view checkpoint, const CheckpointAttempts& attempts){ + CheckpointAttemptsResult result; + for (size_t attempt = 1;; attempt++){ + result.attempts = attempt; + const AttemptResult outcome = attempts.run(attempt); + if (outcome == AttemptResult::PASSED){ + result.passed = true; + attempts.log(checkpoint_pass_line(checkpoint, attempt, attempts.prefix_kind)); + return result; + } + if (outcome == AttemptResult::FINAL || attempt >= attempts.max_attempts){ + return result; + } + if (!attempts.reset(attempt + 1)){ + return result; + } + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.h new file mode 100644 index 0000000000..88121f2a25 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.h @@ -0,0 +1,75 @@ +/* Checkpoint Attempts + * + * From: https://github.com/PokemonAutomation/ + * + * The retry loop every AutoStory runs a checkpoint in: run an attempt, and + * when it fails go back to the checkpoint's start save and try again, + * until an attempt passes, fails in a way another attempt would repeat, + * the last attempt fails, or a reset fails. The story segments and the + * story engine run their checkpoints through it, so each writes the same + * pass line (Pokemon_StoryLog.h) and counts attempts the same way. The + * game supplies the attempt and the reset. + * + */ + +#ifndef PokemonAutomation_Pokemon_CheckpointAttempts_H +#define PokemonAutomation_Pokemon_CheckpointAttempts_H + +#include +#include +#include +#include +#include "Pokemon_StoryLog.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How one attempt at a checkpoint ended. +enum class AttemptResult{ + PASSED, + // Failed; another attempt from the start save may pass. + FAILED, + // Failed in a way another attempt would repeat (the game is not + // running): no more attempts. + FINAL, +}; + +// Writes one log line. +using CheckpointLogger = std::function; + +// What the game does at each step of the retry loop. +struct CheckpointAttempts{ + // Attempts before the loop gives up. The first attempt always runs, + // so 0 runs one, as 1 does. + size_t max_attempts = 1; + // Runs attempt `attempt`, counting from 1. + std::function run; + // Goes back to the checkpoint's start save before attempt + // `next_attempt`, writing its own log line. Returns false when it could + // not, which ends the loop. + std::function reset; + CheckpointLogger log; + // AS_GIVEN when `checkpoint` is the game's own text that already says + // it is a checkpoint, so the pass line leaves out "[Checkpoint] " + // (checkpoint_start_line()). + CheckpointPrefix prefix_kind = CheckpointPrefix::ADD; +}; + +// What the loop came to. +struct CheckpointAttemptsResult{ + bool passed = false; + // Attempts run, counting the last one. + size_t attempts = 0; +}; + +// Runs `checkpoint` until an attempt passes, an attempt is FINAL, +// `max_attempts` attempts failed, or a reset failed. Writes the pass line. +// Exceptions from `run` and `reset` pass through. +CheckpointAttemptsResult run_checkpoint_attempts(std::string_view checkpoint, const CheckpointAttempts& attempts); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts_Tests.cpp new file mode 100644 index 0000000000..e36119f1c1 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts_Tests.cpp @@ -0,0 +1,135 @@ +/* Checkpoint Attempts Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_CheckpointAttempts.h" +#include "Pokemon_CheckpointAttempts_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +struct AttemptsCase{ + std::string name; + struct Input{ + size_t max_attempts = 1; + // Each attempt's result in order; past the end, FAILED. + std::vector results; + bool reset_fails = false; + }; + Input input; + struct Expectation{ + bool passed = false; + size_t attempts = 0; + // The resets asked for, by next attempt: "2 3". + std::string resets = {}; + // The log, joined by " | ". + std::string log = {}; + }; + Expectation expectation; +}; + +const AttemptsCase CASES[] = { + { + .name = "the first attempt passes", + .input = {.max_attempts = 3, .results = {AttemptResult::PASSED}}, + .expectation = {.passed = true, .attempts = 1, .resets = "", .log = "[Checkpoint] 01.01: passed on attempt 1 (one-shot)"}, + }, + { + .name = "the third attempt passes after two resets", + .input = {.max_attempts = 3, .results = {AttemptResult::FAILED, AttemptResult::FAILED, AttemptResult::PASSED}}, + .expectation = {.passed = true, .attempts = 3, .resets = "2 3", .log = "[Checkpoint] 01.01: passed on attempt 3 (2 resets)"}, + }, + { + .name = "every attempt fails", + .input = {.max_attempts = 2, .results = {}}, + .expectation = {.passed = false, .attempts = 2, .resets = "2"}, + }, + { + .name = "zero attempts runs one", + .input = {.max_attempts = 0, .results = {}}, + .expectation = {.passed = false, .attempts = 1}, + }, + { + .name = "a final failure ends the loop", + .input = {.max_attempts = 3, .results = {AttemptResult::FINAL}}, + .expectation = {.passed = false, .attempts = 1}, + }, + { + .name = "a failed reset ends the loop", + .input = {.max_attempts = 3, .results = {}, .reset_fails = true}, + .expectation = {.passed = false, .attempts = 1, .resets = "2"}, + }, +}; + +UnitTestResult check_case(const AttemptsCase& test){ + std::string resets; + std::string log; + const CheckpointAttempts attempts{ + .max_attempts = test.input.max_attempts, + .run = [&](size_t attempt){ + return attempt <= test.input.results.size() ? test.input.results[attempt - 1] : AttemptResult::FAILED; + }, + .reset = [&](size_t next_attempt){ + resets += std::format("{}{}", resets.empty() ? "" : " ", next_attempt); + return !test.input.reset_fails; + }, + .log = [&](const std::string& line){ + log += (log.empty() ? "" : " | ") + line; + }, + }; + const CheckpointAttemptsResult result = run_checkpoint_attempts("01.01", attempts); + if (result.passed != test.expectation.passed || result.attempts != test.expectation.attempts){ + return std::format( + "expected passed {} after {}, got passed {} after {}", + test.expectation.passed, test.expectation.attempts, result.passed, result.attempts + ); + } + if (resets != test.expectation.resets){ + return std::format("expected resets \"{}\", got \"{}\"", test.expectation.resets, resets); + } + if (log != test.expectation.log){ + return std::format("expected the log \"{}\", got \"{}\"", test.expectation.log, log); + } + return true; +} + + +class CheckpointAttemptsTest : public UnitTest{ +public: + explicit CheckpointAttemptsTest(AttemptsCase test_case) + : UnitTest(std::format("Pokemon::CheckpointAttempts - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return check_case(m_case); + } + +private: + AttemptsCase m_case; +}; + +} // namespace + + +void add_tests_CheckpointAttempts(UnitTestDatabase& database){ + for (const AttemptsCase& test : CASES){ + database.add(test); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts_Tests.h new file mode 100644 index 0000000000..2fbdf7683e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts_Tests.h @@ -0,0 +1,23 @@ +/* Checkpoint Attempts Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_CheckpointAttempts_Tests_H +#define PokemonAutomation_Pokemon_CheckpointAttempts_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the checkpoint retry loop. +void add_tests_CheckpointAttempts(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryCheckpointTypes.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryCheckpointTypes.h new file mode 100644 index 0000000000..c237236255 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryCheckpointTypes.h @@ -0,0 +1,46 @@ +/* Story Checkpoint Types + * + * From: https://github.com/PokemonAutomation/ + * + * A checkpoint as the event runner sees it: its events, and the report of + * a run of it. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryCheckpointTypes_H +#define PokemonAutomation_Pokemon_StoryCheckpointTypes_H + +#include +#include +#include +#include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_StoryEvent.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The stretch of story between two saves, as events. +struct Checkpoint{ + std::string id; + std::vector events; +}; + +// Result report from executing a checkpoint. +struct CheckpointReport{ + bool completed = false; + // 1-based number of the event that failed; 0 when nothing failed. + size_t failed_event = 0; + std::string failed_name; + Outcome failure; + size_t events_run = 0; +}; + +// Where the runner writes its log lines. +using EventLogger = MoveOnlyFunction; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h new file mode 100644 index 0000000000..d497989b12 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h @@ -0,0 +1,31 @@ +/* Story Event + * + * From: https://github.com/PokemonAutomation/ + * + * One step of a checkpoint as the event runner sees it: its name, why it + * is there, and its action. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryEvent_H +#define PokemonAutomation_Pokemon_StoryEvent_H + +#include +#include "Pokemon_StoryOutcome.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// One step of a checkpoint: an action, named for the log. +struct Event{ + std::string name; + std::string why; + Act act; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp new file mode 100644 index 0000000000..ca0fbfb39c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp @@ -0,0 +1,96 @@ +/* Story Events + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_StoryLog.h" +#include "Pokemon_StoryEvents.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string event_log_line(std::string_view checkpoint, size_t number, std::string_view event, std::string_view status){ + return std::format("[Event] {}/{} {}: {}", checkpoint, number, event, status); +} + +std::string checkpoint_log_line(std::string_view checkpoint, std::string_view text){ + return std::format("[Checkpoint] {}: {}", checkpoint, text); +} + + +namespace{ + + +// The text of the exception being handled. +std::string current_exception_text(){ + try{ + throw; + }catch (const Exception& e){ + return e.message(); + }catch (std::exception& e){ + return e.what(); + }catch (...){ + return "unknown exception"; + } +} + +// Runs event `number` of `checkpoint`; if it succeeded knowing where it +// left the player, that becomes the run's pose. Logs its start and end, +// and a throw as its and the checkpoint's failure before it goes on. +Outcome run_event(Checkpoint& checkpoint, size_t number, RunState& state, EventLogger& log){ + Event& event = checkpoint.events[number - 1]; + log(event_log_line(checkpoint.id, number, event.name, "start")); + Outcome outcome; + try{ + outcome = event.act(state); + }catch (...){ + const std::string what = current_exception_text(); + log(event_log_line(checkpoint.id, number, event.name, std::format("failed: {}", what))); + log(checkpoint_log_line(checkpoint.id, std::format("failed at {} {}: {}", number, event.name, what))); + throw; + } + if (!outcome.succeeded()){ + log(event_log_line(checkpoint.id, number, event.name, std::format("failed: {}", to_string(outcome)))); + return outcome; + } + if (outcome.pose){ + state.pose = *outcome.pose; + } + log(event_log_line(checkpoint.id, number, event.name, "done")); + return outcome; +} + + +} // namespace + + +CheckpointReport run_checkpoint(RunState& state, Checkpoint& checkpoint, EventLogger& log){ + CheckpointReport report; + const std::string& id = checkpoint.id; + log(checkpoint_start_line(id, checkpoint.events.size())); + for (size_t c = 0; c < checkpoint.events.size(); c++){ + report.events_run++; + Outcome outcome = run_event(checkpoint, c + 1, state, log); + if (!outcome.succeeded()){ + report.failed_event = c + 1; + report.failed_name = checkpoint.events[c].name; + log(checkpoint_log_line(id, std::format("failed at {} {}: {}", c + 1, report.failed_name, to_string(outcome)))); + report.failure = std::move(outcome); + return report; + } + } + report.completed = true; + log(checkpoint_log_line(id, std::format("done, {} run", report.events_run))); + return report; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h new file mode 100644 index 0000000000..395d3fdc3b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h @@ -0,0 +1,47 @@ +/* Story Events + * + * From: https://github.com/PokemonAutomation/ + * + * A story checkpoint as a list of events, run straight through: each + * event's action in order, until one fails, which stops the checkpoint + * with the event and the reason. + * + * The run state is the runner's to change. An action that knows where it + * left the player says so in its Outcome, and the runner writes that into + * the pose once the action has succeeded. + * + * Actuation is a callable the game supplies, so this file knows nothing + * of any one game or console, and the runner can be tested against a + * scripted world. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryEvents_H +#define PokemonAutomation_Pokemon_StoryEvents_H + +#include +#include +#include +#include "Pokemon_StoryCheckpointTypes.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// "[Event] 00.04/2 to_lab: start": event `number` (from 1) of +// `checkpoint`, named `event`, and its status. +std::string event_log_line(std::string_view checkpoint, size_t number, std::string_view event, std::string_view status); + +// "[Checkpoint] 00.04: done, 3 run". +std::string checkpoint_log_line(std::string_view checkpoint, std::string_view text); + +// Runs `checkpoint`'s events in order from `state`, logging each one's +// start and end, until one fails. An exception from an action is logged +// as the event's failure and goes on: the game decides what it means. +CheckpointReport run_checkpoint(RunState& state, Checkpoint& checkpoint, EventLogger& log); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp new file mode 100644 index 0000000000..e250c0ff8f --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp @@ -0,0 +1,155 @@ +/* Story Events Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_StoryEvents_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// How a scripted event's action ends. +enum class ScriptedAct{ + PASS, + PASS_AT_LOBBY, // succeeds knowing the player is in "Lobby" + FAIL, + THROW, +}; + +struct EventsCase{ + std::string name; + struct Input{ + std::vector events; + }; + Input input; + struct Expectation{ + // "completed 2 run, pose Lobby" or "failed at 2 e2: scripted, 2 run". + std::string report; + // The log, one line each, joined by " | "; "throws" when it throws. + std::string log; + }; + Expectation expectation; +}; + +const EventsCase CASES[] = { + { + .name = "every event runs in order", + .input = {.events = {ScriptedAct::PASS, ScriptedAct::PASS}}, + .expectation = { + .report = "completed, 2 run, pose ?", + .log = "[Checkpoint] 01.01: start, 2 events | [Event] 01.01/1 e1: start | [Event] 01.01/1 e1: done" + " | [Event] 01.01/2 e2: start | [Event] 01.01/2 e2: done | [Checkpoint] 01.01: done, 2 run", + }, + }, + { + .name = "a failed event stops the checkpoint", + .input = {.events = {ScriptedAct::PASS, ScriptedAct::FAIL, ScriptedAct::PASS}}, + .expectation = { + .report = "failed at 2 e2: scripted, 2 run", + .log = "[Checkpoint] 01.01: start, 3 events | [Event] 01.01/1 e1: start | [Event] 01.01/1 e1: done" + " | [Event] 01.01/2 e2: start | [Event] 01.01/2 e2: failed: scripted: as scripted" + " | [Checkpoint] 01.01: failed at 2 e2: scripted: as scripted", + }, + }, + { + .name = "an action's pose becomes the run's", + .input = {.events = {ScriptedAct::PASS_AT_LOBBY}}, + .expectation = { + .report = "completed, 1 run, pose Lobby", + .log = "[Checkpoint] 01.01: start, 1 events | [Event] 01.01/1 e1: start | [Event] 01.01/1 e1: done | [Checkpoint] 01.01: done, 1 run", + }, + }, + { + .name = "a throw is logged as the event's failure and goes on", + .input = {.events = {ScriptedAct::THROW}}, + .expectation = { + .report = "throws", + .log = "[Checkpoint] 01.01: start, 1 events | [Event] 01.01/1 e1: start | [Event] 01.01/1 e1: failed: boom" + " | [Checkpoint] 01.01: failed at 1 e1: boom", + }, + }, +}; + +Act act_of(ScriptedAct kind){ + return [kind](RunState&) -> Outcome{ + switch (kind){ + case ScriptedAct::PASS: + return outcome_ok(); + case ScriptedAct::PASS_AT_LOBBY: + return outcome_ok(Pose{.map = "Lobby", .certainty = PoseCertainty::SET, .where = nullptr}); + case ScriptedAct::FAIL: + return outcome_failed("scripted", "as scripted"); + case ScriptedAct::THROW: + throw std::runtime_error("boom"); + } + return outcome_ok(); + }; +} + +UnitTestResult check_case(const EventsCase& test){ + Checkpoint checkpoint{.id = "01.01", .events = {}}; + for (size_t c = 0; c < test.input.events.size(); c++){ + checkpoint.events.push_back(Event{.name = std::format("e{}", c + 1), .why = "", .act = act_of(test.input.events[c])}); + } + std::string log; + EventLogger logger = [&log](const std::string& line){ + log += (log.empty() ? "" : " | ") + line; + }; + RunState state; + std::string report = "throws"; + try{ + const CheckpointReport run = run_checkpoint(state, checkpoint, logger); + report = run.completed + ? std::format("completed, {} run, pose {}", run.events_run, state.pose.map.empty() ? "?" : state.pose.map) + : std::format("failed at {} {}: {}, {} run", run.failed_event, run.failed_name, run.failure.failure, run.events_run); + }catch (const std::runtime_error&){} + if (report != test.expectation.report){ + return std::format("expected \"{}\", got \"{}\"", test.expectation.report, report); + } + if (log != test.expectation.log){ + return std::format("expected the log \"{}\", got \"{}\"", test.expectation.log, log); + } + return true; +} + + +class StoryEventsTest : public UnitTest{ +public: + explicit StoryEventsTest(EventsCase test_case) + : UnitTest(std::format("Pokemon::StoryEvents - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return check_case(m_case); + } + +private: + EventsCase m_case; +}; + +} // namespace + + +void add_tests_StoryEvents(UnitTestDatabase& database){ + for (const EventsCase& test : CASES){ + database.add(test); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.h new file mode 100644 index 0000000000..1ed6eacf52 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.h @@ -0,0 +1,23 @@ +/* Story Events Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryEvents_Tests_H +#define PokemonAutomation_Pokemon_StoryEvents_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the straight-line event runner. +void add_tests_StoryEvents(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h new file mode 100644 index 0000000000..cdcb9d3eb4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h @@ -0,0 +1,48 @@ +/* Story Segment Types + * + * From: https://github.com/PokemonAutomation/ + * + * The plain data of a segment run (Engine/Pokemon_StoryEngine.h): the + * report of what happened. + * + */ + +#ifndef PokemonAutomation_Pokemon_StorySegmentTypes_H +#define PokemonAutomation_Pokemon_StorySegmentTypes_H + +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_StoryOutcome.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Summary of checkpoint attempts and pass status. +struct CheckpointRun{ + std::string id; + bool passed = false; + size_t attempts = 0; +}; + +// Execution results and failure diagnostics for a story segment run. +struct SegmentReport{ + bool completed = false; + // Both empty when nothing failed; the event is empty when a save or a + // reload failed. + std::string failed_checkpoint; + std::string failed_event; + Outcome failure; + size_t checkpoints_run = 0; + // Reloads after failed attempts. + size_t reloads = 0; + // Each checkpoint run, in order, the failed one last. + std::vector runs; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.cpp new file mode 100644 index 0000000000..0663f79588 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.cpp @@ -0,0 +1,30 @@ +/* Direction + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_Direction.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string direction_name(Direction direction){ + switch (direction){ + case Direction::NORTH: + return "north"; + case Direction::EAST: + return "east"; + case Direction::SOUTH: + return "south"; + case Direction::WEST: + return "west"; + } + return "?"; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.h new file mode 100644 index 0000000000..5024b3ec69 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.h @@ -0,0 +1,36 @@ +/* Direction + * + * From: https://github.com/PokemonAutomation/ + * + * The four cardinal directions the player can face or move in. + * + */ + +#ifndef PokemonAutomation_Pokemon_Direction_H +#define PokemonAutomation_Pokemon_Direction_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Row 0 is the top of a map, so SOUTH increases y. +enum class Direction{ + NORTH, + EAST, + SOUTH, + WEST, +}; +// Array containing all four cardinal directions. +constexpr Direction ALL_DIRECTIONS[] = { + Direction::NORTH, Direction::EAST, Direction::SOUTH, Direction::WEST, +}; +// Returns the lowercase name string of a cardinal direction. +std::string direction_name(Direction direction); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 17ba84a741..4a6d734a58 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -908,6 +908,13 @@ file(GLOB LIBRARY_SOURCES Source/CommonTools/Options/TrainOCRModeOption.h Source/CommonTools/Resources/SpriteDatabase.cpp Source/CommonTools/Resources/SpriteDatabase.h + Source/CommonTools/ScreenEvents/ScreenEventTypes.h + Source/CommonTools/ScreenEvents/ScreenEvents.cpp + Source/CommonTools/ScreenEvents/ScreenEvents.h + Source/CommonTools/ScreenEvents/ScreenEvents_Tests.cpp + Source/CommonTools/ScreenEvents/ScreenEvents_Tests.h + Source/CommonTools/ScreenEvents/ScreenFades.h + Source/CommonTools/ScreenMachine/ScreenObservation.h Source/CommonTools/StartupChecks/StartProgramChecks.cpp Source/CommonTools/StartupChecks/StartProgramChecks.h Source/CommonTools/StartupChecks/VideoResolutionCheck.cpp @@ -1498,9 +1505,37 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h + Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.h + Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h + Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend.h + Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend_Tests.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend_Tests.h + Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.h + Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.h + Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.h + Source/Pokemon/AutoStory/Engine/Pokemon_StoryGame.h + Source/Pokemon/AutoStory/Engine/Pokemon_StoryPoseConcept.h + Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.h Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.cpp Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.h + Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.cpp + Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.h + Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts_Tests.h Source/Pokemon/AutoStory/Pokemon_MapUtil.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_StoryLog.cpp Source/Pokemon/AutoStory/Pokemon_StoryLog.h Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp @@ -1519,9 +1554,12 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.cpp Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h + Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h + Source/Pokemon/Navigation/Pokemon_Direction.cpp + Source/Pokemon/Navigation/Pokemon_Direction.h Source/Pokemon/Pokemon_AdvRng.cpp Source/Pokemon/Pokemon_AdvRng.h Source/Pokemon/Pokemon_BdspRng.cpp