From 00c6ceb847ba1030e8c20eaeb686ebf629f1f24f Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 14 Nov 2026 23:47:19 -0800 Subject: [PATCH] AutoStory: operate on a console The shared run options (start and end checkpoint, attempts, checks level, language, verify mode, save mode, reload at start, postconditions only), the checkpoint dropdown database, launch and reload from HOME with the HOME tile reader, and the Switch prompts a launch answers. From plza/fault-sweep without the lab's BREAKPOINTS option. Fork CI reads CommandLineTests from dayfine/CommandLineTests for the HomeTileReader frames, pinned as on plza/fault-sweep. --- .../workflows/cpp-ci-serial-programs-base.yml | 4 +- .../ComputerPrograms_UnitTestRunner.cpp | 2 + .../NintendoSwitch_HomeTileReader.cpp | 249 ++++++++++++ .../Inference/NintendoSwitch_HomeTileReader.h | 55 +++ .../AutoStory/Engine/Pokemon_StoryLaunch.cpp | 313 ++++++++++++++ .../AutoStory/Engine/Pokemon_StoryLaunch.h | 176 ++++++++ .../Engine/Pokemon_StoryLaunch_Tests.cpp | 381 ++++++++++++++++++ .../Engine/Pokemon_StoryLaunch_Tests.h | 23 ++ .../AutoStory/Pokemon_AutoStorySelect.h | 17 + .../Pokemon_AutoStorySelect_Tests.cpp | 66 +++ .../AutoStory/Pokemon_AutoStory_Tests.h | 6 + .../Pokemon_StoryStepExecutor_Tests.cpp | 116 ++++++ .../AutoStory/Pokemon_StorySwitchPrompts.cpp | 53 +++ .../AutoStory/Pokemon_StorySwitchPrompts.h | 33 ++ .../Pokemon/Options/Pokemon_GameLanguages.cpp | 43 ++ .../Pokemon/Options/Pokemon_GameLanguages.h | 45 +++ .../Options/Pokemon_StoryRangeOptions.cpp | 51 +++ .../Options/Pokemon_StoryRangeOptions.h | 53 +++ .../Pokemon_StoryRangeOptions_Tests.cpp | 142 +++++++ .../Options/Pokemon_StoryRangeOptions_Tests.h | 23 ++ .../Options/Pokemon_StoryRunOptions.cpp | 179 ++++++++ .../Pokemon/Options/Pokemon_StoryRunOptions.h | 113 ++++++ .../Options/Pokemon_StoryRunOptions_Tests.cpp | 99 +++++ .../Options/Pokemon_StoryRunOptions_Tests.h | 23 ++ SerialPrograms/cmake/SourceFiles.cmake | 18 + 25 files changed, 2282 insertions(+), 1 deletion(-) create mode 100644 SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeTileReader.cpp create mode 100644 SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeTileReader.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySwitchPrompts.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySwitchPrompts.h create mode 100644 SerialPrograms/Source/Pokemon/Options/Pokemon_GameLanguages.cpp create mode 100644 SerialPrograms/Source/Pokemon/Options/Pokemon_GameLanguages.h create mode 100644 SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.cpp create mode 100644 SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.h create mode 100644 SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp create mode 100644 SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h create mode 100644 SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions_Tests.h diff --git a/.github/workflows/cpp-ci-serial-programs-base.yml b/.github/workflows/cpp-ci-serial-programs-base.yml index efb3c80a04..e321d2dc90 100644 --- a/.github/workflows/cpp-ci-serial-programs-base.yml +++ b/.github/workflows/cpp-ci-serial-programs-base.yml @@ -245,7 +245,9 @@ jobs: uses: actions/checkout@v7 if: inputs.run-tests with: - repository: 'PokemonAutomation/CommandLineTests' + # The fork's fixtures: upstream's plus the HomeTileReader frames (fork only until they land upstream). + repository: 'dayfine/CommandLineTests' + ref: '0195f3b0c6ffb15bf6df176cfd3a64d781346fcf' path: 'CommandLineTests' # The unit tests assume the downloadable resources they need are already downloaded diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 6cc20db2fc..7106155ace 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -34,6 +34,7 @@ #include "NintendoSwitch/Inference/NintendoSwitch_CheckOnlineDetector.h" #include "NintendoSwitch/Inference/NintendoSwitch_FailedToConnectDetector.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeTileReader.h" #include "NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h" #include "NintendoSwitch/Programs/Typewriter/NintendoSwitch_Typewriter_Tests.h" #include "NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.h" @@ -86,6 +87,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_AutoStory(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); + NintendoSwitch::add_tests_HomeTileReader(ret); NintendoSwitch::add_tests_UpdatePopupDetector(ret); NintendoSwitch::Typewriter::add_tests_TypewriterTextMapping(ret); NintendoSwitch::PokemonBDSP::add_tests_DialogDetector(ret); diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeTileReader.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeTileReader.cpp new file mode 100644 index 0000000000..b8913f5001 --- /dev/null +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeTileReader.cpp @@ -0,0 +1,249 @@ +/* Home Tile Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/OCR/OCR_Routines.h" +#include "CommonTools/OCR/OCR_StringNormalization.h" +#include "Tests/ImageUnitTest.h" +#include "NintendoSwitch_HomeTileReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +namespace{ + +// The selected tile's frame lines, about 0.008 of the screen tall, just +// outside the tile art: strips across the screen that the art of the +// other tiles stays out of. +const ImageFloatBox FRAME_TOP_STRIP{0.0, 0.252, 1.0, 0.014}; +const ImageFloatBox FRAME_BOTTOM_STRIP{0.0, 0.627, 1.0, 0.014}; +constexpr double FRAME_TOP = 0.256; +constexpr double FRAME_BOTTOM = 0.637; +// A column crosses a frame line when this many of its pixels in the strip +// are the frame's cyan. +constexpr size_t MIN_LINE_PIXELS = 3; +// A tile frame is 0.214 of the screen wide. +constexpr double MIN_FRAME_WIDTH = 0.18; +constexpr double MAX_FRAME_WIDTH = 0.25; + +// The band above the row where HOME writes the selected game's name. The +// name starts 0.005 to 0.01 left of the frame, right of a game card icon +// that ends 0.017 or more left of it. +constexpr double NAME_TOP = 0.19; +constexpr double NAME_HEIGHT = 0.06; +constexpr double NAME_LEAD = 0.015; +constexpr double NAME_RIGHT = 0.98; +// The name's cyan (ARGB), dark text on HOME's light background once +// filtered: red low, green and blue high. +constexpr uint32_t NAME_MINS = 0xff000096; +constexpr uint32_t NAME_MAXS = 0xff96ffff; + +// The frame's cyan, which pulses between about (0, 187, 229) and +// (52, 249, 229), with lighter anti-aliased edges. +bool is_frame_cyan(uint32_t pixel){ + const int red = (pixel >> 16) & 0xff; + const int green = (pixel >> 8) & 0xff; + const int blue = pixel & 0xff; + return green >= 160 && blue >= 160 && green - red >= 60 && blue - red >= 60; +} + +// Per column of `strip`, whether it crosses a frame line. +std::vector frame_line_columns(const ImageViewRGB32& strip){ + std::vector columns(strip.width(), false); + for (size_t x = 0; x < strip.width(); x++){ + size_t cyan = 0; + for (size_t y = 0; y < strip.height(); y++){ + cyan += is_frame_cyan(strip.pixel(x, y)) ? 1 : 0; + } + columns[x] = cyan >= MIN_LINE_PIXELS; + } + return columns; +} + +// The longest run of columns that cross both frame lines, as [begin, end). +std::pair longest_framed_run(const std::vector& top, const std::vector& bottom){ + std::pair best{0, 0}; + size_t begin = 0; + for (size_t x = 0; x <= top.size(); x++){ + const bool framed = x < top.size() && x < bottom.size() && top[x] && bottom[x]; + if (framed){ + continue; + } + if (x - begin > best.second - best.first){ + best = {begin, x}; + } + begin = x + 1; + } + return best; +} + +} // namespace + + +std::optional find_selected_home_tile(const ImageViewRGB32& screen){ + if (screen.width() == 0 || screen.height() == 0){ + return std::nullopt; + } + const std::pair run = longest_framed_run( + frame_line_columns(extract_box_reference(screen, FRAME_TOP_STRIP)), + frame_line_columns(extract_box_reference(screen, FRAME_BOTTOM_STRIP)) + ); + const double width = (double)screen.width(); + const double frame_width = (double)(run.second - run.first) / width; + if (frame_width < MIN_FRAME_WIDTH || frame_width > MAX_FRAME_WIDTH){ + return std::nullopt; + } + return ImageFloatBox((double)run.first / width, FRAME_TOP, frame_width, FRAME_BOTTOM - FRAME_TOP); +} + +std::optional read_selected_home_tile_name(Language language, const ImageViewRGB32& screen){ + const std::optional frame = find_selected_home_tile(screen); + if (!frame){ + return std::nullopt; + } + const double left = std::max(0.0, frame->x - NAME_LEAD); + const ImageViewRGB32 band = extract_box_reference(screen, ImageFloatBox(left, NAME_TOP, NAME_RIGHT - left, NAME_HEIGHT)); + const ImageRGB32 text = to_blackwhite_rgb32_range(band, true, NAME_MINS, NAME_MAXS); + return OCR::ocr_read(language, text); +} + +bool selected_home_tile_is(Language language, const ImageViewRGB32& screen, std::string_view name){ + const std::optional read = read_selected_home_tile_name(language, screen); + if (!read){ + return false; + } + const std::u32string wanted = OCR::normalize_utf32(std::string(name)); + return !wanted.empty() && OCR::normalize_utf32(*read).find(wanted) != std::u32string::npos; +} + + + +namespace{ + +// The names HOME shows for the two games on console B's frames. +constexpr std::string_view FIRERED = "Pokémon FireRed Version"; +constexpr std::string_view LEGENDS_ZA = "Pokémon Legends: Z-A"; + +// Where the first tile's frame starts, and the step to the next tile, as +// parts of the screen's width, before the row scrolls. +constexpr double FIRST_TILE_LEFT = 0.076; +constexpr double TILE_STEP = 0.211; +constexpr double TILE_TOLERANCE = 0.02; + +struct HomeTileCase{ + struct Input{ + std::string_view image; + }; + struct Expectation{ + // The selected tile's place in the row, from 0; nothing: no tile + // is selected. + std::optional tile = std::nullopt; + // The name the selected tile shows: FIRERED or LEGENDS_ZA. + std::string_view game = {}; + }; + std::string_view name; + Input input; + Expectation expectation; +}; + +// Console B, 2026-11-14: HOME after the order changed (the game played +// last moves to the first tile), and the user select over HOME. +const std::vector HOME_TILE_CASES = { + {.name = "FireRed on the first tile 1", + .input = {.image = "NintendoSwitch/HomeTileReader/FireRedFirstTile_1.png"}, + .expectation = {.tile = 0, .game = FIRERED}}, + {.name = "FireRed on the first tile 2", + .input = {.image = "NintendoSwitch/HomeTileReader/FireRedFirstTile_2.png"}, + .expectation = {.tile = 0, .game = FIRERED}}, + {.name = "FireRed on the first tile 3", + .input = {.image = "NintendoSwitch/HomeTileReader/FireRedFirstTile_3.png"}, + .expectation = {.tile = 0, .game = FIRERED}}, + {.name = "Legends Z-A on the first tile", + .input = {.image = "NintendoSwitch/HomeTileReader/LegendsZAFirstTile.png"}, + .expectation = {.tile = 0, .game = LEGENDS_ZA}}, + {.name = "Legends Z-A on the second tile", + .input = {.image = "NintendoSwitch/HomeTileReader/LegendsZASecondTile.png"}, + .expectation = {.tile = 1, .game = LEGENDS_ZA}}, + {.name = "user select over HOME", + .input = {.image = "NintendoSwitch/HomeTileReader/UserSelectOverHome.png"}, + .expectation = {}}, +}; + +// What went wrong with the frame on `screen`; empty when it is where `test` expects. +std::string check_frame(const HomeTileCase& test, const ImageViewRGB32& screen){ + const std::optional frame = find_selected_home_tile(screen); + if (!test.expectation.tile){ + return frame ? std::format("Expected no selected tile, found a frame at x={:.3f}.", frame->x) : ""; + } + if (!frame){ + return std::format("Expected a frame on tile {}, found none.", *test.expectation.tile); + } + const double expected_left = FIRST_TILE_LEFT + TILE_STEP * (double)*test.expectation.tile; + if (std::abs(frame->x - expected_left) > TILE_TOLERANCE){ + return std::format("Expected the frame on tile {} (x={:.3f}), found it at x={:.3f}.", *test.expectation.tile, expected_left, frame->x); + } + return ""; +} + +// What went wrong with the names on `screen`: it must be the game `test` +// expects and not the other one. +std::string check_names(const HomeTileCase& test, const ImageViewRGB32& screen){ + const std::string read = read_selected_home_tile_name(Language::English, screen).value_or(""); + for (std::string_view game : {FIRERED, LEGENDS_ZA}){ + const bool expected = game == test.expectation.game; + if (selected_home_tile_is(Language::English, screen, game) != expected){ + return std::format("Expected the tile {} \"{}\", read \"{}\".", expected ? "to be" : "not to be", game, read); + } + } + return ""; +} + +class Test_HomeTileReader : public ImageUnitTest{ +public: + explicit Test_HomeTileReader(const HomeTileCase& test) + : ImageUnitTest(std::format("NintendoSwitch::HomeTileReader - {}", test.name), {std::string(test.input.image)}) + , m_case(test) + { + // Plus the PaddleOCR (ONNX) recognition session and its working set. + m_memory += PADDLE_OCR_SINGLE_LINE_MEMORY_ESTIMATE; + } + + virtual UnitTestResult run_on_images( + Logger&, CancellableScope&, + const std::vector& images + ) const override{ + std::string error = check_frame(m_case, images[0]); + if (error.empty()){ + error = check_names(m_case, images[0]); + } + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } + +private: + HomeTileCase m_case; +}; + +} // namespace + + +void add_tests_HomeTileReader(UnitTestDatabase& database){ + for (const HomeTileCase& test : HOME_TILE_CASES){ + database.add(test); + } +} + + + +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeTileReader.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeTileReader.h new file mode 100644 index 0000000000..c0c57f1052 --- /dev/null +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeTileReader.h @@ -0,0 +1,55 @@ +/* Home Tile Reader + * + * From: https://github.com/PokemonAutomation/ + * + * Which game tile the HOME menu's cursor is on. HOME draws a cyan frame + * around the selected tile of the game row and writes that game's name + * above the row, also in cyan. The frame says that a tile is selected and + * where; the name says which game it is. Neither depends on the order of + * the row, which changes as games are played (the last one played moves + * to the first tile). + * + * Measured on the Switch 1 HOME menu at 1920x1080; positions are parts of + * the screen, so other capture sizes read the same. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_HomeTileReader_H +#define PokemonAutomation_NintendoSwitch_HomeTileReader_H + +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +// The selected tile's cyan frame on `screen`; nothing when no tile of the +// game row is selected (the cursor on the icons below it, a dialog or the +// user select over HOME). +std::optional find_selected_home_tile(const ImageViewRGB32& screen); + +// The name HOME writes above the selected tile, as OCR reads it in +// `language` (the console's, not the game's); nothing when no tile is +// selected. +std::optional read_selected_home_tile_name(Language language, const ImageViewRGB32& screen); + +// Whether a tile is selected and its name contains `name` ("Pokémon +// Legends: Z-A", or a distinctive part of it), compared as OCR text: +// case, accents, spaces and punctuation ignored. +bool selected_home_tile_is(Language language, const ImageViewRGB32& screen, std::string_view name); + + +// The screenshot tests in CommandLineTests/NintendoSwitch/HomeTileReader/. +void add_tests_HomeTileReader(UnitTestDatabase& database); + + + +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch.cpp new file mode 100644 index 0000000000..e72453540a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch.cpp @@ -0,0 +1,313 @@ +/* Story Launch + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "NintendoSwitch/Inference/NintendoSwitch_HomeTileReader.h" +#include "Pokemon_StoryLaunch.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +using namespace NintendoSwitch; + + +namespace{ + + +// What a look shows, as far as a launch cares. +enum class LaunchScreen{ + HOME, + NEW_GAME, + PROMPT, + TITLE, + OVERWORLD, + OTHER, +}; + +struct LaunchLook{ + LaunchScreen screen = LaunchScreen::OTHER; + // The prompt on screen, for PROMPT. + const StoryLaunchPrompt* prompt = nullptr; +}; + +// Which of the policy's loose checks a look may pass. +struct LaunchReadable{ + // The launch launched or closed the game: the checks read only after. + bool launched = false; + // No title press's fade holds the title check off, and a title read + // only after the launch (title_after_launch) waits for the A on the + // game's tile: right after the close, before HOME, a screen passes + // PLZA's loose title check (console B, 2026-11-14). + bool title = true; +}; + +// `look` as `policy` reads it. HOME first: a game's detectors may read +// HOME's plain screen as a quiet overworld. +LaunchLook read_launch_look(const StoryLaunchPolicy& policy, const ScreenObservation& look, LaunchReadable readable){ + const bool launched = readable.launched; + if (look.events.has(ScreenEvent::SWITCH_HOME_MENU)){ + return {.screen = LaunchScreen::HOME}; + } + if (policy.new_game && policy.new_game(look)){ + return {.screen = LaunchScreen::NEW_GAME}; + } + for (const StoryLaunchPrompt& prompt : policy.prompts){ + if ((launched || !prompt.after_launch) && prompt.matches && prompt.matches(look)){ + return {.screen = LaunchScreen::PROMPT, .prompt = &prompt}; + } + } + if (readable.title && (launched || !policy.title_after_launch) && policy.title(look)){ + return {.screen = LaunchScreen::TITLE}; + } + const bool overworld = policy.overworld ? policy.overworld(look) : look.events.has(ScreenEvent::PLAYER_CAN_MOVE); + return {.screen = overworld ? LaunchScreen::OVERWORLD : LaunchScreen::OTHER}; +} + +Outcome launch_failed(std::string detail){ + return outcome_failed(std::string(STORY_LAUNCH_FAILED), std::move(detail)); +} + +// Why `policy` cannot launch `request`, before any press; nothing when it +// can. +std::optional launch_problem(const StoryLaunchPolicy& policy, StoryLaunchRequest request){ + if (!policy.tile_selected || !policy.title){ + return launch_failed(std::format("{}: the launch policy has no tile or title check", policy.game)); + } + if (request.save == StoryLaunchRequest::Save::BACKUP && policy.backup_save.empty()){ + return launch_failed(std::format("{}: the game has no backup save", policy.game)); + } + return std::nullopt; +} + + +// One launch: a look, one thing done about it, until the overworld has +// settled or a screen took too many presses. +template +class LaunchDriver{ +public: + LaunchDriver(StoryBackend& backend, const StoryLaunchPolicy& policy, StoryLaunchRequest request) + : m_backend(backend) + , m_policy(policy) + , m_request(request) + {} + + // One look and its answer; the launch's end when this look ended it. + std::optional step(){ + const Observation observation = m_backend.observe(); + const LaunchLook look = read_launch_look(m_policy, observation, {.launched = m_launched || m_loading, .title = m_title_held_looks == 0 && (m_launched || !m_policy.title_after_launch)}); + count_title_hold(observation); + if (look.screen != LaunchScreen::OVERWORLD){ + m_settled = 0; + } + switch (look.screen){ + case LaunchScreen::HOME: + return on_home(observation); + case LaunchScreen::NEW_GAME: + return launch_failed(std::format("{}: the game shows a new game: no save to load, and a launch never starts one", m_policy.game)); + case LaunchScreen::PROMPT: + return on_prompt(*look.prompt); + case LaunchScreen::TITLE: + return on_title(observation); + case LaunchScreen::OVERWORLD: + return on_overworld(); + case LaunchScreen::OTHER: + break; + } + return on_other(); + } + +private: + // Whether an overworld up now is not yet the save asked for. + bool needs_load() const{ + return !m_loading && (m_request.running == StoryLaunchRequest::Running::RESTART || m_request.save == StoryLaunchRequest::Save::BACKUP); + } + + // The cursor to the game's tile, then the game closed if it must + // load again, then A on the tile. + std::optional on_home(const ScreenObservation& observation){ + if (m_launch_pressed && m_home_waited < m_policy.launch_wait){ + if (m_home_waited == Milliseconds(0)){ + log("home", "waiting for the game to start"); + } + m_home_waited += m_policy.poll; + m_backend.wait(m_policy.poll); + return std::nullopt; + } + if (!m_policy.tile_selected(observation)){ + return move_to_tile(); + } + if (needs_load()){ + m_loading = true; + return press("home", {.button = BUTTON_X}, m_policy.presses_per_screen, "close the game"); + } + m_launched = true; + m_launch_pressed = true; + m_home_waited = Milliseconds(0); + return press("home", {.button = BUTTON_A}, m_policy.presses_per_screen, "launch the game"); + } + + std::optional move_to_tile(){ + const size_t left = m_policy.tile_search; + if (m_tile_moves >= 3 * left){ + return launch_failed(std::format("{}: the game's tile is not on HOME: {} tiles searched", m_policy.game, m_tile_moves)); + } + const Button button = m_tile_moves < left ? BUTTON_LEFT : BUTTON_RIGHT; + m_tile_moves++; + log("home", std::format("not on the game's tile: {}", button_to_string(button))); + m_backend.press(button, Milliseconds(80), Milliseconds(400)); + return std::nullopt; + } + + // The prompt's lead-in presses, then its press. + std::optional on_prompt(const StoryLaunchPrompt& prompt){ + if (m_presses[prompt.name] < prompt.max_presses){ + for (const StoryLaunchPress& each : prompt.before){ + m_backend.press(each.button, each.hold, each.release); + } + } + return press(prompt.name, prompt.press, prompt.max_presses); + } + + std::optional on_title(const ScreenObservation& observation){ + m_loading = true; + m_launched = true; + const bool backup = m_request.save == StoryLaunchRequest::Save::BACKUP && !m_backup_sent; + if (backup && m_policy.backup_title && !m_policy.backup_title(observation)){ + m_backend.wait(m_policy.poll); + return std::nullopt; + } + if (backup){ + m_backup_sent = true; + log("title", "the backup save"); + for (const StoryLaunchPress& each : m_policy.backup_save){ + m_backend.press(each.button, each.hold, each.release); + } + } + m_title_pressed = true; + return press("title", m_policy.title_press, m_policy.presses_per_screen); + } + + // A black fade after a title press starts the title's hold; each + // other look shortens it. + void count_title_hold(const ScreenObservation& observation){ + if (m_title_pressed && observation.events.has(ScreenEvent::FADE_BLACK)){ + m_title_pressed = false; + m_title_held_looks = m_policy.title_load_looks; + }else if (m_title_held_looks > 0){ + m_title_held_looks--; + } + } + + std::optional on_overworld(){ + if (needs_load()){ + return press("overworld", {.button = BUTTON_HOME}, m_policy.presses_per_screen, "HOME, to load the save"); + } + if (++m_settled >= m_policy.settled_looks){ + log("overworld", std::format("settled for {} looks", m_settled)); + return outcome_ok(); + } + m_backend.wait(m_policy.poll); + return std::nullopt; + } + + // A screen the policy doesn't know: the game's boot or a load once + // launched; before that the game was in front already, left with HOME + // to load the save, or B toward its overworld. + std::optional on_other(){ + if (m_launched || m_loading){ + m_backend.wait(m_policy.poll); + return std::nullopt; + } + if (needs_load()){ + return press("unknown screen", {.button = BUTTON_HOME}, m_policy.presses_per_screen, "HOME, to load the save"); + } + return press("unknown screen", {.button = BUTTON_B}, m_policy.presses_per_screen, "B, toward the overworld"); + } + + // `what` on `screen`, unless `screen` already took `max` presses. + std::optional press(std::string_view screen, const StoryLaunchPress& what, size_t max, std::string_view why = {}){ + size_t& count = m_presses[std::string(screen)]; + if (count >= max){ + return launch_failed(std::format("{}: stuck on {}: {} presses changed nothing", m_policy.game, screen, count)); + } + count++; + log(screen, why.empty() ? button_to_string(what.button) : std::string(why)); + m_backend.press(what.button, what.hold, what.release); + return std::nullopt; + } + + void log(std::string_view screen, std::string_view what){ + m_backend.log(std::format("[Launch] {}: {}: {}", m_policy.game, screen, what)); + } + + StoryBackend& m_backend; + const StoryLaunchPolicy& m_policy; + StoryLaunchRequest m_request; + std::map> m_presses; + size_t m_tile_moves = 0; + size_t m_settled = 0; + // The game was closed from HOME, or showed its title: what comes up + // next is a save loading. + bool m_loading = false; + // A on the game's tile, or the title: until the overworld, a screen + // the policy doesn't know is the game booting or loading. + bool m_launched = false; + // A was pressed on the game's tile, and HOME has shown for + // `m_home_waited` since. + bool m_launch_pressed = false; + Milliseconds m_home_waited = Milliseconds(0); + bool m_backup_sent = false; + // A title press with no black fade since. + bool m_title_pressed = false; + // Looks left on which the title is not read (title_load_looks). + size_t m_title_held_looks = 0; +}; + + +} // namespace + + +std::function switch_home_tile_named(Language language, std::string name){ + return [language, name = std::move(name)](const ScreenObservation& look){ + return look.frame && look.frame->frame && selected_home_tile_is(language, *look.frame->frame, name); + }; +} + + +template +Outcome launch_story_game(StoryBackend& backend, const StoryLaunchPolicy& policy, StoryLaunchRequest request){ + if (std::optional problem = launch_problem(policy, request)){ + backend.log(std::format("[Launch] {}", problem->detail)); + return std::move(*problem); + } + LaunchDriver driver(backend, policy, request); + for (size_t looks = 0; looks < policy.max_looks; looks++){ + backend.scope().throw_if_cancelled(); + if (std::optional end = driver.step()){ + if (!end->succeeded()){ + backend.log(std::format("[Launch] {}", end->detail)); + } + return std::move(*end); + } + } + const Outcome failed = launch_failed(std::format("{}: no overworld after {} looks", policy.game, policy.max_looks)); + backend.log(std::format("[Launch] {}", failed.detail)); + return failed; +} + +template Outcome launch_story_game(StoryBackend&, const StoryLaunchPolicy&, StoryLaunchRequest); +template Outcome launch_story_game(StoryBackend&, const StoryLaunchPolicy&, StoryLaunchRequest); + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch.h new file mode 100644 index 0000000000..df04f47a6f --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch.h @@ -0,0 +1,176 @@ +/* Story Launch + * + * From: https://github.com/PokemonAutomation/ + * + * A run's first event: from wherever the console is (the Switch's HOME + * menu with the game closed or suspended, the game's title, the + * overworld) to the overworld on a save. One driver for every game; the + * game's StoryLaunchPolicy says how its screens look and which press + * answers each. It runs before the first checkpoint, on its own, never + * inside a new game's language or intro steps, and it never starts a new + * game. + * + * The driver looks, does one thing, and looks again. It does not need to + * know every screen: one it doesn't know is waited out (a boot, a fade) + * or, before the game was launched, left with HOME or B. Each screen's + * presses are counted, so a screen that ignores its press fails the + * launch instead of looping, and the launch ends only once the overworld + * shows for several looks in a row. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryLaunch_H +#define PokemonAutomation_Pokemon_StoryLaunch_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/Language.h" +#include "CommonTools/ScreenMachine/ScreenObservation.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h" +#include "Pokemon/AutoStory/Pokemon_StoryOutcome.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "Pokemon_StoryBackend.h" +#include "Pokemon_ZonePose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What a launch loads. +struct StoryLaunchRequest{ + enum class Save{ + LATEST, // the title's plain load + BACKUP, // the policy's backup_save presses on the title first + // (PLZA: Up, then B + X, the save before the latest) + }; + enum class Running{ + // A game already on the overworld is the start: it is resumed + // from HOME, not reloaded. + KEEP, + // A game already running is closed from HOME, then launched, so + // the save loads; a title on screen already counts as launched. + RESTART, + }; + Save save = Save::LATEST; + Running running = Running::RESTART; +}; + +// One press: `button` (several pressed together when or-ed), held for +// `hold`, then let go for `release`. +struct StoryLaunchPress{ + NintendoSwitch::Button button = NintendoSwitch::BUTTON_A; + Milliseconds hold = Milliseconds(80); + Milliseconds release = Milliseconds(400); +}; + +// A screen on the way that one press answers: the user select, an online +// license check, HOME's close-software dialog, the load menu's Continue, +// a recap of the story so far. +struct StoryLaunchPrompt{ + std::string name = {}; + std::function matches = {}; + StoryLaunchPress press = {}; + // Pressed in order before `press`, each time: the cursor moves to the + // choice `press` picks (the update prompt's last choice). + std::vector before = {}; + // Read only once this launch launched or closed the game: a screen + // the game also shows in play (a dialog box, a choice), where a press + // before the launch would answer the story instead. + bool after_launch = false; + // Presses it may take before the launch is stuck on it. + size_t max_presses = 6; +}; + +// How one game's screens look on the way from HOME to its overworld. +struct StoryLaunchPolicy{ + // "frlg", "bdsp", "plza", for the log. + std::string game = {}; + // On HOME: whether the cursor is on this game's tile. The launch + // presses A on HOME only then, as A launches whatever tile is + // selected. Required; on a Switch, switch_home_tile_named() with the + // name HOME shows for the game. + std::function tile_selected = {}; + // How far the tile search moves each way: Left `tile_search` times + // (the most recently played games are leftmost), then Right twice as + // many. + size_t tile_search = 6; + // The title screen, which leads to the save. Required. + std::function title = {}; + StoryLaunchPress title_press = {}; + // `title` is read only once this launch launched or closed the game: + // a loose check (any quiet screen after the boot) that a game in play + // would pass too. + bool title_after_launch = false; + // Pressed once on the title before `title_press` for Save::BACKUP. + // Empty: the game has no backup save, and a BACKUP launch fails + // before it presses anything. + std::vector backup_save = {}; + // Where `backup_save` goes: the title proper. A loose `title` passes + // the boot's logos too, where those presses do nothing and the title's + // next press loads the latest save (console B, 2026-11-14). Until it + // shows, a BACKUP launch waits on title looks without a press. Empty: + // the first title look takes them. + std::function backup_title = {}; + // A screen that would start a new game: there is no save. The launch + // fails there without a press. Optional. + std::function new_game = {}; + // The game's other screens on the way, each answered by its press. + std::vector prompts = {}; + // The player in control. Unset: the look shows PLAYER_CAN_MOVE. + std::function overworld = {}; + // Looks after a title press's black fade (FADE_BLACK) on which + // `title` is not read: the screens there are the save loading or the + // boot, waited out. A loose title check passes a load's tips screen, + // and an A on a boot logo is followed by the boot's own fade, so the + // title is read again once these looks are over. 0: always read. + size_t title_load_looks = 0; + // Looks in a row the overworld must show before the launch is done. + size_t settled_looks = 3; + // The wait between looks at a screen with nothing to press. + Milliseconds poll = Milliseconds(500); + // After A on the game's tile, how long HOME may still show (its zoom + // into the game, a check or the user select in front of it) before + // the launch takes A again: until then each look at HOME waits, as + // another A there would launch the game again. + Milliseconds launch_wait = Milliseconds(30000); + // Presses HOME, the title, an overworld to leave or a screen the + // policy doesn't know may take before the launch is stuck there. + size_t presses_per_screen = 6; + // Looks before the launch gives up: about `poll` times this of + // loading at most. + size_t max_looks = 360; +}; + +// A `tile_selected` for a Switch game: HOME's cursor is on the tile whose +// name, above the game row, contains `name` ("Pokémon Legends: Z-A"), +// read in `language`, the console's (NintendoSwitch_HomeTileReader.h). +// False on a look without a frame, as in a simulation. +std::function switch_home_tile_named(Language language, std::string name); + +// The failure of a launch that did not reach the overworld; its detail +// says where it stopped. Nothing in the story answers it: no reload, no +// recovery. +inline constexpr std::string_view STORY_LAUNCH_FAILED = "launch_failed"; + +// Drives `backend` to the overworld on the save `request` asks for, by +// `policy`; logs each press as "[Launch] : : ". +// Succeeds once the overworld shows `policy.settled_looks` looks in a +// row; fails as STORY_LAUNCH_FAILED on a new game, a missing tile, a +// screen that took too many presses, or after `policy.max_looks` looks. +template +Outcome launch_story_game(StoryBackend& backend, const StoryLaunchPolicy& policy, StoryLaunchRequest request); + +// Instantiated once, in Pokemon_StoryLaunch.cpp. +extern template Outcome launch_story_game(StoryBackend&, const StoryLaunchPolicy&, StoryLaunchRequest); +// And for ZonePose (Pokemon_ZonePose.h). +extern template Outcome launch_story_game(StoryBackend&, const StoryLaunchPolicy&, StoryLaunchRequest); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch_Tests.cpp new file mode 100644 index 0000000000..92e1428b38 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch_Tests.cpp @@ -0,0 +1,381 @@ +/* Story Launch Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The launch on a scripted console: each case is the screens the console + * shows, look by look (the last repeats), and the presses the launch must + * make, or where it must fail. The test game's screens are readings its + * policy reads; HOME is the shared SWITCH_HOME_MENU event and the + * overworld the shared PLAYER_CAN_MOVE. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_StoryFakeBackend.h" +#include "Pokemon_StoryLaunch.h" +#include "Pokemon_StoryLaunch_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +using namespace NintendoSwitch; + + +namespace{ + + +// What the scripted console shows. +enum class Screen{ + HOME_ON_GAME, // HOME, the cursor on the game's tile + HOME_OFF_GAME, // HOME, the cursor on another tile + CLOSE_DIALOG, // HOME's "Close software?" + LICENSE_CHECK, // the online license check + BLACK, // a boot or a load + FADE, // a black fade (FADE_BLACK), as a boot or a load starts + TITLE, + NEW_GAME, // the title's menu without a save + BACKUP_CONFIRM, // "Load the backup save?" + LOAD_MENU, // Continue / New Game + UPDATE, // the update prompt: Up twice to its last choice, then A + GAME_DIALOG, // the game's dialog box, in play or on the way + LOGO, // a boot logo, which a loose title check passes + OVERWORLD, +}; + +inline constexpr std::string_view SCREEN = "screen"; +inline constexpr std::string_view TILE = "home.tile"; + +Observation look(Screen screen){ + Observation observation; + switch (screen){ + case Screen::HOME_ON_GAME: + case Screen::HOME_OFF_GAME: + observation.events = ScreenEvents{ScreenEvent::SWITCH_HOME_MENU}; + observation.readings[std::string(TILE)] = screen == Screen::HOME_ON_GAME ? 1 : 0; + return observation; + case Screen::OVERWORLD: + observation.events = ScreenEvents{ScreenEvent::PLAYER_CAN_MOVE}; + return observation; + case Screen::FADE: + observation.events = ScreenEvents{ScreenEvent::FADE_BLACK}; + return observation; + default: + observation.readings[std::string(SCREEN)] = (int)screen; + return observation; + } +} + +std::function shows(Screen screen){ + return [screen](const ScreenObservation& observation){ + const auto it = observation.readings.find(SCREEN); + return it != observation.readings.end() && it->second == (int)screen; + }; +} + +// Whether the test game has a backup save. +enum class Backup{ + PLZA, // Up, then B + X + NONE, +}; + +// How the test game finds its tile on HOME. +enum class TileCheck{ + READINGS, // the scripted "home.tile" reading + SWITCH_NAME, // switch_home_tile_named(), which reads the look's frame +}; + +// How loose the test game's title and dialog checks are. +enum class GameScreens{ + STRICT, // read whenever they show + AFTER_LAUNCH, // read only once the launch launched the game +}; + +// Which screens the test game's title check passes. +enum class TitleCheck{ + TITLE, // the title only + LOOSE, // the title and the boot's logos; the backup save only on the title +}; + +// The test game's bounds that a case may change. +struct Bounds{ + size_t title_load_looks = 0; + size_t max_looks = 12; +}; + +// The test game: A on the title, `backup` for the backup save, A on each +// prompt (Up, Up, A on the update prompt; B on the game's dialog), and +// small bounds so a failure takes few looks. +StoryLaunchPolicy test_policy(Backup backup, GameScreens game_screens, TileCheck tile_check, TitleCheck title_check, Bounds bounds){ + StoryLaunchPolicy policy; + policy.game = "test"; + policy.tile_selected = [](const ScreenObservation& observation){ + const auto it = observation.readings.find(TILE); + return it != observation.readings.end() && it->second == 1; + }; + if (tile_check == TileCheck::SWITCH_NAME){ + policy.tile_selected = switch_home_tile_named(Language::English, "Pokémon Legends: Z-A"); + } + policy.tile_search = 2; + policy.title = shows(Screen::TITLE); + if (title_check == TitleCheck::LOOSE){ + policy.title = [](const ScreenObservation& observation){ + return shows(Screen::TITLE)(observation) || shows(Screen::LOGO)(observation); + }; + policy.backup_title = shows(Screen::TITLE); + } + if (backup == Backup::PLZA){ + policy.backup_save = {{.button = BUTTON_UP}, {.button = BUTTON_B | BUTTON_X, .hold = Milliseconds(1000)}}; + } + policy.new_game = shows(Screen::NEW_GAME); + policy.prompts = { + {.name = "close software", .matches = shows(Screen::CLOSE_DIALOG)}, + {.name = "license check", .matches = shows(Screen::LICENSE_CHECK)}, + {.name = "backup confirm", .matches = shows(Screen::BACKUP_CONFIRM)}, + {.name = "load menu", .matches = shows(Screen::LOAD_MENU)}, + {.name = "update", .matches = shows(Screen::UPDATE), .before = {{.button = BUTTON_UP}, {.button = BUTTON_UP}}}, + {.name = "game dialog", .matches = shows(Screen::GAME_DIALOG), .press = {.button = BUTTON_B}, + .after_launch = game_screens == GameScreens::AFTER_LAUNCH}, + }; + policy.title_after_launch = game_screens == GameScreens::AFTER_LAUNCH; + policy.presses_per_screen = 3; + policy.title_load_looks = bounds.title_load_looks; + policy.launch_wait = Milliseconds(2000); + policy.max_looks = bounds.max_looks; + return policy; +} + +// `screens`, then the overworld for as many looks as it takes to settle. +std::vector then_settled(std::vector screens){ + screens.insert(screens.end(), {Screen::OVERWORLD, Screen::OVERWORLD, Screen::OVERWORLD}); + return screens; +} + +using Save = StoryLaunchRequest::Save; +using Running = StoryLaunchRequest::Running; + +// One launch. +struct LaunchCase{ + struct Input{ + std::vector screens; + StoryLaunchRequest request = {}; + Backup backup = Backup::PLZA; + GameScreens game_screens = GameScreens::STRICT; + TileCheck tile_check = TileCheck::READINGS; + TitleCheck title_check = TitleCheck::TITLE; + Bounds bounds = {}; + }; + struct Expectation{ + // Empty: the launch succeeds; else a part of its failure's detail. + std::string_view failure = {}; + // The inputs in order, by space: a button ("A", "HOME", "B+X") + // or "wait". + std::string_view inputs = {}; + }; + std::string_view name; + Input input; + Expectation expectation; +}; + +const std::vector LAUNCH_CASES = { + {.name = "game closed on HOME", + .input = {.screens = then_settled({Screen::HOME_ON_GAME, Screen::HOME_ON_GAME, Screen::BLACK, Screen::TITLE, Screen::BLACK})}, + .expectation = {.inputs = "X A wait A wait wait wait"}}, + {.name = "game open on its title", + .input = {.screens = then_settled({Screen::TITLE, Screen::BLACK})}, + .expectation = {.inputs = "A wait wait wait"}}, + {.name = "game on the overworld kept", + .input = {.screens = then_settled({}), .request = {.running = Running::KEEP}}, + .expectation = {.inputs = "wait wait"}}, + // RELOAD_AT_START off (Pokemon_StoryRunOptions.h) on PLZA's loose + // title check: a game already on the overworld, as console B's at + // the Pokemon Center counter on 2026-11-14, is started from with no press. + {.name = "game on the overworld kept with a loose title check", + .input = {.screens = then_settled({}), .request = {.running = Running::KEEP}, .game_screens = GameScreens::AFTER_LAUNCH}, + .expectation = {.inputs = "wait wait"}}, + {.name = "kept game resumed from HOME with a loose title check", + .input = {.screens = then_settled({Screen::HOME_ON_GAME}), .request = {.running = Running::KEEP}, + .game_screens = GameScreens::AFTER_LAUNCH}, + .expectation = {.inputs = "A wait wait"}}, + {.name = "game on the overworld restarted", + .input = {.screens = then_settled({Screen::OVERWORLD, Screen::HOME_ON_GAME, Screen::CLOSE_DIALOG, Screen::HOME_ON_GAME, + Screen::BLACK, Screen::TITLE})}, + .expectation = {.inputs = "HOME X A A wait A wait wait"}}, + {.name = "backup save from the overworld", + .input = {.screens = then_settled({Screen::OVERWORLD, Screen::HOME_ON_GAME, Screen::HOME_ON_GAME, Screen::TITLE, + Screen::BACKUP_CONFIRM, Screen::BLACK}), + .request = {.save = Save::BACKUP, .running = Running::KEEP}}, + .expectation = {.inputs = "HOME X A Up B+X A A wait wait wait"}}, + // Console B, 2026-11-14: after the close, a screen before HOME passed + // PLZA's loose title check; the backup's buttons went there and the + // real title took only A, so the latest save loaded. + {.name = "backup save waits for the title after the game's launch", + .input = {.screens = then_settled({Screen::OVERWORLD, Screen::HOME_ON_GAME, Screen::CLOSE_DIALOG, Screen::TITLE, + Screen::HOME_ON_GAME, Screen::BLACK, Screen::TITLE, Screen::BACKUP_CONFIRM, Screen::BLACK}), + .request = {.save = Save::BACKUP, .running = Running::KEEP}, .game_screens = GameScreens::AFTER_LAUNCH}, + .expectation = {.inputs = "HOME X A wait A wait Up B+X A A wait wait wait"}}, + // Console B, 2026-11-14: the backup's buttons went to a boot logo that + // passed the loose title check; the title took only A. + {.name = "backup save waits past the boot's logos for the title", + .input = {.screens = then_settled({Screen::OVERWORLD, Screen::HOME_ON_GAME, Screen::CLOSE_DIALOG, Screen::HOME_ON_GAME, + Screen::LOGO, Screen::LOGO, Screen::TITLE, Screen::BACKUP_CONFIRM, Screen::BLACK}), + .request = {.save = Save::BACKUP, .running = Running::KEEP}, .game_screens = GameScreens::AFTER_LAUNCH, + .title_check = TitleCheck::LOOSE}, + .expectation = {.inputs = "HOME X A A wait wait Up B+X A A wait wait wait"}}, + {.name = "backup save the game does not have", + .input = {.screens = then_settled({}), .request = {.save = Save::BACKUP}, .backup = Backup::NONE}, + .expectation = {.failure = "no backup save", .inputs = ""}}, + {.name = "license check back to HOME", + .input = {.screens = then_settled({Screen::HOME_ON_GAME, Screen::HOME_ON_GAME, Screen::LICENSE_CHECK, Screen::HOME_ON_GAME, + Screen::BLACK, Screen::TITLE, Screen::LOAD_MENU})}, + .expectation = {.inputs = "X A A wait wait A A wait wait"}}, + // Console B, 2026-11-14 02:41 (FRLG): HOME showed for about 1.5 s + // after the A on the tile, and each look there pressed A again. + {.name = "HOME after the launch press waits", + .input = {.screens = then_settled({Screen::HOME_ON_GAME, Screen::HOME_ON_GAME, Screen::HOME_ON_GAME, Screen::HOME_ON_GAME, + Screen::HOME_ON_GAME, Screen::BLACK, Screen::TITLE})}, + .expectation = {.inputs = "X A wait wait wait wait A wait wait"}}, + {.name = "HOME past the launch wait takes A again", + .input = {.screens = then_settled({Screen::HOME_ON_GAME, Screen::HOME_ON_GAME, Screen::HOME_ON_GAME, Screen::HOME_ON_GAME, + Screen::HOME_ON_GAME, Screen::HOME_ON_GAME, Screen::HOME_ON_GAME, Screen::TITLE})}, + .expectation = {.inputs = "X A wait wait wait wait A A wait wait"}}, + {.name = "cursor on another tile", + .input = {.screens = then_settled({Screen::HOME_OFF_GAME, Screen::HOME_OFF_GAME, Screen::HOME_ON_GAME}), + .request = {.running = Running::KEEP}}, + .expectation = {.inputs = "Left Left A wait wait"}}, + {.name = "game not on HOME", + .input = {.screens = {Screen::HOME_OFF_GAME}}, + .expectation = {.failure = "tile is not on HOME", .inputs = "Left Left Right Right Right Right"}}, + {.name = "Switch tile check never launches without a frame", + .input = {.screens = {Screen::HOME_ON_GAME}, .tile_check = TileCheck::SWITCH_NAME}, + .expectation = {.failure = "tile is not on HOME", .inputs = "Left Left Right Right Right Right"}}, + {.name = "title ignores A", + .input = {.screens = {Screen::TITLE}}, + .expectation = {.failure = "stuck on title", .inputs = "A A A"}}, + {.name = "no save never starts a new game", + .input = {.screens = {Screen::NEW_GAME}}, + .expectation = {.failure = "new game", .inputs = ""}}, + {.name = "black screen after launch times out", + .input = {.screens = {Screen::HOME_ON_GAME, Screen::HOME_ON_GAME, Screen::BLACK}}, + .expectation = {.failure = "no overworld after 12 looks", .inputs = "X A wait wait wait wait wait wait wait wait wait wait"}}, + {.name = "kept game off the overworld takes B", + .input = {.screens = then_settled({Screen::LOAD_MENU, Screen::BLACK}), .request = {.running = Running::KEEP}}, + .expectation = {.inputs = "A B wait wait"}}, + {.name = "update prompt takes its lead-in presses", + .input = {.screens = then_settled({Screen::HOME_ON_GAME, Screen::HOME_ON_GAME, Screen::UPDATE, Screen::BLACK, Screen::TITLE})}, + .expectation = {.inputs = "X A Up Up A wait A wait wait"}}, + {.name = "strict title in front is pressed", + .input = {.screens = then_settled({Screen::GAME_DIALOG, Screen::TITLE, Screen::BLACK})}, + .expectation = {.inputs = "B A wait wait wait"}}, + {.name = "loose title in front is left with HOME", + .input = {.screens = then_settled({Screen::GAME_DIALOG, Screen::TITLE, Screen::HOME_ON_GAME, Screen::HOME_ON_GAME, + Screen::BLACK, Screen::GAME_DIALOG, Screen::TITLE}), + .game_screens = GameScreens::AFTER_LAUNCH}, + .expectation = {.inputs = "HOME HOME X A wait B A wait wait"}}, + // Console B, PLZA, 2026-11-14 13:09: A twice on a boot logo the loose + // title check passes, the boot's black, the title (A works), the + // load's black, then its tips screen, which the title check passes + // too. Each fade after a title press holds the title check off for + // 6 looks: the boot's title waits 3 looks, the tips screen gets no A. + {.name = "title not read on the screens after its fade", + .input = {.screens = then_settled({Screen::HOME_ON_GAME, Screen::HOME_ON_GAME, Screen::FADE, + Screen::TITLE, Screen::TITLE, + Screen::FADE, Screen::FADE, Screen::FADE, Screen::FADE, + Screen::TITLE, Screen::TITLE, Screen::TITLE, Screen::TITLE, + Screen::FADE, Screen::FADE, + Screen::TITLE, Screen::TITLE, Screen::TITLE, Screen::TITLE}), + .game_screens = GameScreens::AFTER_LAUNCH, .bounds = {.title_load_looks = 6, .max_looks = 30}}, + .expectation = {.inputs = "X A wait A A wait wait wait wait wait wait wait A wait wait wait wait wait wait wait wait"}}, + {.name = "title read again once its fade's looks are over", + .input = {.screens = {Screen::HOME_ON_GAME, Screen::HOME_ON_GAME, Screen::TITLE, Screen::FADE, Screen::TITLE}, + .game_screens = GameScreens::AFTER_LAUNCH, .bounds = {.title_load_looks = 2}}, + .expectation = {.failure = "stuck on title", .inputs = "X A A wait wait wait A A"}}, +}; + +// The fake backend's record of `input` ("A" -> "press A"). +std::string recorded(std::string_view input){ + if (input == "wait"){ + return "wait 500ms"; + } + static const std::map BUTTONS = { + {"A", BUTTON_A}, {"B", BUTTON_B}, {"X", BUTTON_X}, {"HOME", BUTTON_HOME}, + {"Up", BUTTON_UP}, {"Left", BUTTON_LEFT}, {"Right", BUTTON_RIGHT}, {"B+X", BUTTON_B | BUTTON_X}, + }; + const auto it = BUTTONS.find(input); + return it == BUTTONS.end() ? std::format("unknown input {}", input) : std::format("press {}", button_to_string(it->second)); +} + +// `inputs` (by space) as the fake backend records them. +std::vector expected_inputs(std::string_view inputs){ + std::vector expected; + while (!inputs.empty()){ + const size_t space = inputs.find(' '); + expected.push_back(recorded(inputs.substr(0, space))); + inputs = space == std::string_view::npos ? std::string_view() : inputs.substr(space + 1); + } + return expected; +} + +std::string describe_inputs(const std::vector& inputs){ + std::string text; + for (const std::string& input : inputs){ + text += text.empty() ? input : std::format(", {}", input); + } + return std::format("[{}]", text); +} + +std::string check_launch(const LaunchCase& test, CancellableScope& scope){ + std::vector> looks; + for (Screen screen : test.input.screens){ + looks.push_back(look(screen)); + } + FakeStoryBackend backend({.looks = std::move(looks)}, scope); + const Outcome outcome = launch_story_game(backend, test_policy(test.input.backup, test.input.game_screens, test.input.tile_check, test.input.title_check, test.input.bounds), test.input.request); + if (test.expectation.failure.empty() && !outcome.succeeded()){ + return std::format("expected success, got {}", to_string(outcome)); + } + if (!test.expectation.failure.empty()){ + if (outcome.failure != STORY_LAUNCH_FAILED || outcome.detail.find(test.expectation.failure) == std::string::npos){ + return std::format("expected a launch failure with \"{}\", got {}", test.expectation.failure, to_string(outcome)); + } + } + const std::vector expected = expected_inputs(test.expectation.inputs); + if (backend.inputs() != expected){ + return std::format("expected inputs {}, got {}", describe_inputs(expected), describe_inputs(backend.inputs())); + } + return ""; +} + +class StoryLaunchTest : public UnitTest{ +public: + explicit StoryLaunchTest(LaunchCase test) + : UnitTest(std::format("Pokemon::StoryLaunch - {}", test.name)) + , m_case(std::move(test)) + {} + virtual UnitTestResult run(Logger&, CancellableScope& scope) const override{ + const std::string error = check_launch(m_case, scope); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } +private: + LaunchCase m_case; +}; + + +} // namespace + + +void add_tests_StoryLaunch(UnitTestDatabase& database){ + for (const LaunchCase& test : LAUNCH_CASES){ + database.add(test); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch_Tests.h new file mode 100644 index 0000000000..efba4cc847 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch_Tests.h @@ -0,0 +1,23 @@ +/* Story Launch Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryLaunch_Tests_H +#define PokemonAutomation_Pokemon_StoryLaunch_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the launch from HOME to the overworld on a scripted console. +void add_tests_StoryLaunch(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStorySelect.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStorySelect.h index 294dd5d21d..e711f8b1ab 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStorySelect.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStorySelect.h @@ -8,6 +8,7 @@ #define PokemonAutomation_Pokemon_AutoStorySelect_H #include +#include #include #include #include "CommonTools/Options/StringSelectOption.h" @@ -40,6 +41,22 @@ StringSelectDatabase make_story_select_database( } +// The start/end dropdown database of a story's checkpoints, given by their +// labels in order ("00.09 Pewter Gym: Camper Liam, then Brock"), slugged +// by their index, as make_story_select_database() slugs SV's. A game whose +// story is in sections (BDSP's segments 00 and 01) passes them joined: a +// section's entry i is then story_index(true, i, first of the section). +// The program keeps it in a function-local static: the options hold a +// reference. +inline StringSelectDatabase story_checkpoint_database(std::span labels){ + StringSelectDatabase database; + for (size_t c = 0; c < labels.size(); c++){ + database.add_entry(StringSelectEntry(std::to_string(c), labels[c])); + } + return database; +} + + // The index in the whole story list of entry `index_in_section` of the // tutorial or the main story, whose first entry is `first_main_story_index`. // NOTE: a section ends where the user must step in (e.g. level up the diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.cpp index efdd49bd8f..c9eae2f1ae 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.cpp @@ -4,6 +4,7 @@ * */ +#include #include #include #include @@ -103,6 +104,68 @@ class Test_AutoStorySelectDatabase : public UnitTest{ const AutoStorySelectScenario m_scenario; }; +// (slug, label) entries as [0 "label", ...]. +std::string describe_entries(const std::vector>& entries){ + std::string text; + for (const auto& [slug, label] : entries){ + text += std::format("{}{} \"{}\"", text.empty() ? "" : ", ", slug, label); + } + return std::format("[{}]", text); +} + +// A game's checkpoint labels, in story order. +struct StoryCheckpointDatabaseInput{ + std::vector labels; +}; + +// The (slug, label) entries: one per label, in order, slugged by its index. +struct StoryCheckpointDatabaseExpectation{ + std::vector> entries; +}; + +// story_checkpoint_database() over a game's labels and the entries it must make. +struct StoryCheckpointDatabaseCase{ + std::string name; + StoryCheckpointDatabaseInput input; + StoryCheckpointDatabaseExpectation expectation; +}; + +class Test_StoryCheckpointDatabase : public UnitTest{ +public: + Test_StoryCheckpointDatabase(StoryCheckpointDatabaseCase test_case) + : UnitTest(std::format("Pokemon::AutoStorySelectDatabase - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const StringSelectDatabase database = story_checkpoint_database(m_case.input.labels); + std::vector> got; + for (const StringSelectEntry& entry : database.case_list()){ + got.emplace_back(entry.slug, entry.display_name); + } + if (got != m_case.expectation.entries){ + return std::format("Expected {}, got {}", describe_entries(m_case.expectation.entries), describe_entries(got)); + } + return true; + } + +private: + const StoryCheckpointDatabaseCase m_case; +}; + +const StoryCheckpointDatabaseCase STORY_CHECKPOINT_DATABASE_CASES[] = { + { + .name = "checkpoint labels slugged by index", + .input = {.labels = {"00.01 Pallet Town", "00.02 Oak's lab"}}, + .expectation = {.entries = {{"0", "00.01 Pallet Town"}, {"1", "00.02 Oak's lab"}}}, + }, + { + .name = "no checkpoints, no entries", + .input = {.labels = {}}, + .expectation = {.entries = {}}, + }, +}; + void add_index_tests(UnitTestDatabase& database){ const AutoStoryIndexScenario scenarios[] = { { @@ -158,6 +221,9 @@ void add_select_database_tests(UnitTestDatabase& database){ for (const AutoStorySelectScenario& scenario : select_scenarios){ database.add(scenario); } + for (const StoryCheckpointDatabaseCase& test_case : STORY_CHECKPOINT_DATABASE_CASES){ + database.add(test_case); + } } } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 555e0ed0e9..692399895f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -21,6 +21,9 @@ #include "Engine/Pokemon_StoryEnginePolicy_Tests.h" #include "Engine/Pokemon_StoryEngineRuns_Tests.h" #include "Engine/Pokemon_StoryEngineSaveRetry_Tests.h" +#include "Engine/Pokemon_StoryLaunch_Tests.h" +#include "Pokemon/Options/Pokemon_StoryRangeOptions_Tests.h" +#include "Pokemon/Options/Pokemon_StoryRunOptions_Tests.h" #include "Pokemon_SceneJudges_Tests.h" #include "Pokemon_StoryEvents_Tests.h" #include "Pokemon_StoryFailureClasses_Tests.h" @@ -53,6 +56,9 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_StorySavePolicy(database); add_tests_SceneJudges(database); add_tests_StoryFiles(database); + add_tests_StoryRangeOptions(database); + add_tests_StoryRunOptions(database); + add_tests_StoryLaunch(database); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp index 8249895110..e8c7209afe 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp @@ -20,6 +20,9 @@ #include #include #include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/Options/Pokemon_GameLanguages.h" +#include "Pokemon/Options/Pokemon_StoryRunOptions.h" +#include "Pokemon_AutoStorySelect.h" #include "Pokemon_AutoStoryStats.h" #include "Pokemon_StoryEvents.h" #include "Pokemon_BuiltinStoryActions.h" @@ -606,6 +609,60 @@ UnitTestResult test_pause_points(){ } +// Two sections of a story, as BDSP has segments 00 and 01. +const std::vector& two_sections(){ + static const std::vector rows{ + StoryCheckpoint{.id = "00.01", .title = "Leave the house", .start = std::nullopt, .steps = {}}, + StoryCheckpoint{.id = "00.02", .title = "Walk to Sandgem Town", .start = std::nullopt, .steps = {}}, + StoryCheckpoint{.id = "01.01", .title = "Jubilife to Barry", .start = std::nullopt, .steps = {}}, + }; + return rows; +} + +const StringSelectDatabase& two_sections_database(){ + static const StringSelectDatabase database = []{ + std::vector labels; + for (const StoryCheckpoint& checkpoint : two_sections()){ + labels.push_back(story_checkpoint_label(checkpoint)); + } + return story_checkpoint_database(labels); + }(); + return database; +} + +// The dropdowns list the checkpoints as "id title", slugged by their index +// in the whole story, which is story_index() of a section's own index. +UnitTestResult test_checkpoint_dropdowns(){ + const StringSelectDatabase& database = two_sections_database(); + const std::vector expected{"00.01 Leave the house", "00.02 Walk to Sandgem Town", "01.01 Jubilife to Barry"}; + if (database.size() != expected.size()){ + return std::format("Expected 3 entries, got {}", database.size()); + } + for (size_t c = 0; c < expected.size(); c++){ + if (database[c].display_name != expected[c] || database[c].slug != std::to_string(c)){ + return std::format("Unexpected entry {}: {} {}", c, database[c].slug, database[c].display_name); + } + } + if (database[story_index(true, 0, 2)].display_name != "01.01 Jubilife to Barry"){ + return "Expected the second section's first entry at story_index(true, 0, 2)."; + } + if (story_checkpoint_label(StoryCheckpoint{.id = "00.09", .title = "Pewter Gym: Camper Liam, then Brock", .start = std::nullopt, .steps = {}}) + != "00.09 Pewter Gym: Camper Liam, then Brock" + ){ + return "Unexpected label."; + } + StoryRunOptions options(database, Gen8ToGen9Languages_Database()); + if (options.start_index() != 0 || options.end_index() != 2 || !options.check_validity().empty()){ + return "Expected the whole story by default."; + } + options.START_CHECKPOINT.set_by_index(2); + options.END_CHECKPOINT.set_by_index(1); + if (options.check_validity().empty()){ + return "Expected a start after the end to be refused."; + } + return true; +} + // A segment's report in the shared AutoStory stats. UnitTestResult test_story_stats(){ SegmentReport report; @@ -623,6 +680,53 @@ UnitTestResult test_story_stats(){ return true; } +// The program's option group: 3 attempts, no stop, Thorough, by default; +// Fast when chosen. +UnitTestResult test_run_options(){ + StoryRunOptions options(two_sections_database(), Gen8ToGen9Languages_Database()); + const SegmentPolicy policy = options.policy(); + if (policy.attempts_per_checkpoint != 3 || options.check_level() != StoryCheckLevel::DEFAULT){ + return "Expected 3 attempts, no stop at the first failure, and Thorough checks by default."; + } + options.CHECKS.set(StoryCheckLevel::FAST); + if (options.check_level() != StoryCheckLevel::FAST){ + return "Expected Fast checks once chosen."; + } + // Every game language can be chosen, read or not. + if (options.language() != Language::English){ + return "Expected English by default."; + } + options.LANGUAGE.set(Language::Japanese); + if (options.language() != Language::Japanese || !options.check_validity().empty()){ + return "Expected Japanese to be chosen and valid, reader or not."; + } + return true; +} + +// Verify mode: off by default; 3 runs and 2 passes when on, for one +// checkpoint only, never needing more passes than runs. +UnitTestResult test_verify_options(){ + StoryRunOptions options(two_sections_database(), Gen8ToGen9Languages_Database()); + if (options.VERIFY.policy()){ + return "Expected verify mode off by default."; + } + options.VERIFY.set_enabled(true); + if (options.check_validity().empty()){ + return "Expected verify mode refused over more than one checkpoint."; + } + options.END_CHECKPOINT.set_by_index(options.start_index()); + const std::optional policy = options.VERIFY.policy(); + if (!options.check_validity().empty() || !policy || policy->runs != 3 || policy->passes_needed != 2){ + return std::format("Expected 3 runs and 2 passes on one checkpoint: {}", options.check_validity()); + } + options.VERIFY.RUNS.set(2); + options.VERIFY.PASSES.set(3); + if (options.check_validity().empty()){ + return "Expected more passes than runs refused."; + } + return true; +} + UnitTestResult test_lint(){ StoryStep no_target = make(StoryStepKind::ROUTE, "walk"); StoryStep again = make(StoryStepKind::TALK, "walk"); @@ -710,6 +814,18 @@ const StoryStepTestCase STORY_STEP_CASES[] = { .name = "lint", .input = {.test = test_lint}, .expectation = {.description = "verifies lint validation rules on story checkpoints"}, }, + { + .name = "the run options' defaults", .input = {.test = test_run_options}, + .expectation = {.description = "validates initial default story run option values"}, + }, + { + .name = "the run options' verify mode", .input = {.test = test_verify_options}, + .expectation = {.description = "configures verification mode options and passes count"}, + }, + { + .name = "start and end checkpoint dropdowns", .input = {.test = test_checkpoint_dropdowns}, + .expectation = {.description = "populates start and end dropdown selections correctly"}, + }, { .name = "a segment's run in the AutoStory stats", .input = {.test = test_story_stats}, .expectation = {.description = "updates story run statistics following segment completion"}, diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySwitchPrompts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySwitchPrompts.cpp new file mode 100644 index 0000000000..3dcb5a4d94 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySwitchPrompts.cpp @@ -0,0 +1,53 @@ +/* AutoStory Switch Launch Prompts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/Inference/NintendoSwitch_CloseGameDetector.h" +#include "NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h" +#include "NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h" +#include "Pokemon_StorySwitchPrompts.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +using namespace std::chrono_literals; +using namespace NintendoSwitch; + + +namespace{ + +// Whether `detector` fires on the look's frame; false without one. +template +std::function frame_shows(std::shared_ptr detector){ + return [detector = std::move(detector)](const ScreenObservation& look){ + return look.frame && look.frame->frame && detector->detect(*look.frame->frame); + }; +} + +} // namespace + + +std::vector switch_launch_prompts(ConsoleHandle& console){ + const StoryLaunchPress scroll_up{.button = BUTTON_UP, .hold = 40ms, .release = 40ms}; + return { + {.name = "close software", .matches = frame_shows(std::make_shared(console)), + .press = {.button = BUTTON_A, .hold = 160ms, .release = ConsoleSettings::instance().CLOSE_GAME_DELAY}}, + {.name = "user select", .matches = frame_shows(std::make_shared(console)), + .press = {.button = BUTTON_A, .hold = 160ms}}, + {.name = "update prompt", .matches = frame_shows(std::make_shared(console)), + .press = {.button = BUTTON_A, .hold = 160ms}, .before = {scroll_up, scroll_up}}, + }; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySwitchPrompts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySwitchPrompts.h new file mode 100644 index 0000000000..5bfa8dba26 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySwitchPrompts.h @@ -0,0 +1,33 @@ +/* AutoStory Switch Launch Prompts + * + * From: https://github.com/PokemonAutomation/ + * + * The Switch's own screens between HOME and a game, each answered by one + * press: HOME's "Close software?", the user select and the update prompt. + * They are the same in every game, so each game's StoryLaunchPolicy + * (Engine/Pokemon_StoryLaunch.h) starts its prompts with these. + * + */ + +#ifndef PokemonAutomation_Pokemon_StorySwitchPrompts_H +#define PokemonAutomation_Pokemon_StorySwitchPrompts_H + +#include +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Engine/Pokemon_StoryLaunch.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// On `console`'s frames: "Close software?" takes A, then the console's +// close delay (Switch settings); the user select takes A on the user +// highlighted; the update prompt takes Up twice, to "Start Software", then +// A. A look without a frame (a simulation) shows none of them. +std::vector switch_launch_prompts(NintendoSwitch::ConsoleHandle& console); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_GameLanguages.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_GameLanguages.cpp new file mode 100644 index 0000000000..42f0dadf08 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_GameLanguages.cpp @@ -0,0 +1,43 @@ +/* Game Languages + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_GameLanguages.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const EnumDropdownDatabase& Gen8ToGen9Languages_Database(){ + static const EnumDropdownDatabase database({ + {Language::English, "en", "English"}, + {Language::Japanese, "ja", "Japanese"}, + {Language::Spanish, "es", "Spanish"}, + {Language::French, "fr", "French"}, + {Language::German, "de", "German"}, + {Language::Italian, "it", "Italian"}, + {Language::Korean, "ko", "Korean"}, + {Language::ChineseSimplified, "zh-Hans", "Chinese (Simplified)"}, + {Language::ChineseTraditional, "zh-Hant", "Chinese (Traditional)"}, + }); + return database; +} + +const EnumDropdownDatabase& FireRedLeafGreenLanguages_Database(){ + static const EnumDropdownDatabase database({ + {Language::English, "en", "English"}, + {Language::Japanese, "ja", "Japanese"}, + {Language::Spanish, "es", "Spanish"}, + {Language::French, "fr", "French"}, + {Language::German, "de", "German"}, + {Language::Italian, "it", "Italian"}, + }); + return database; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_GameLanguages.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_GameLanguages.h new file mode 100644 index 0000000000..003767c870 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_GameLanguages.h @@ -0,0 +1,45 @@ +/* Game Languages + * + * From: https://github.com/PokemonAutomation/ + * + * The languages each game can be played in, as dropdown databases for a + * program's language option. A program offers its game's set, so a user + * can't pick a language the game doesn't have. Every language a game ships + * in is listed, tested on console or not. Code that reads text takes this + * option and never assumes a language. With no reader for the chosen + * language, a name lookup throws InternalProgramError ("No data loaded for + * this language.") and a story step falls back to positions, digits and the + * screen. + * + */ + +#ifndef PokemonAutomation_Pokemon_GameLanguages_H +#define PokemonAutomation_Pokemon_GameLanguages_H + +#include "Common/Cpp/Options/EnumDropdownDatabase.h" +#include "CommonFramework/Language.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The nine languages of the Switch games of generations 8 and 9: Sword and +// Shield, Brilliant Diamond and Shining Pearl, Legends: Arceus, Scarlet and +// Violet, Legends: Z-A. Japanese, English, French, Italian, German, +// Spanish, Korean, Chinese (Simplified and Traditional). The games have one +// Spanish (Spain), hence one "es". +const EnumDropdownDatabase& Gen8ToGen9Languages_Database(); + +// The six languages of FireRed and LeafGreen, the Game Boy Advance +// releases the Switch versions reissue: Japanese, English, French, Italian, +// German, Spanish. On Switch each language is a separate version with no +// in-game language option (Nintendo of America sells English, French and +// Spanish, the latter two in their European form), so the user picks the +// version they own. +const EnumDropdownDatabase& FireRedLeafGreenLanguages_Database(); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.cpp new file mode 100644 index 0000000000..d294e5e386 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.cpp @@ -0,0 +1,51 @@ +/* Story Range Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryRangeOptions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +StoryRangeOptions::StoryRangeOptions(std::string label, const StringSelectDatabase& checkpoints, LockMode end_lock) + : GroupOption(std::move(label), LockMode::LOCK_WHILE_RUNNING) + , START_CHECKPOINT( + "Start checkpoint:
The program starts from this checkpoint's save.", + checkpoints, + LockMode::LOCK_WHILE_RUNNING, + 0 + ) + , END_CHECKPOINT( + "End checkpoint:
The program stops after this checkpoint.", + checkpoints, + end_lock, + checkpoints.size() == 0 ? 0 : checkpoints.size() - 1 + ) +{ + PA_ADD_OPTION(START_CHECKPOINT); + PA_ADD_OPTION(END_CHECKPOINT); +} + +size_t StoryRangeOptions::start_index() const{ + return START_CHECKPOINT.index(); +} + +size_t StoryRangeOptions::end_index() const{ + return END_CHECKPOINT.index(); +} + +std::string StoryRangeOptions::check_validity() const{ + if (start_index() > end_index()){ + return "The start checkpoint comes after the end checkpoint."; + } + return GroupOption::check_validity(); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.h new file mode 100644 index 0000000000..809f3324d2 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.h @@ -0,0 +1,53 @@ +/* Story Range Options + * + * From: https://github.com/PokemonAutomation/ + * + * The start and end checkpoint dropdowns of an AutoStory program, over one + * list of the story's checkpoints, and the check that the start does not + * come after the end. StoryRunOptions (Pokemon_StoryRunOptions.h) is this + * group plus the run policy. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRangeOptions_H +#define PokemonAutomation_Pokemon_StoryRangeOptions_H + +#include +#include "Common/Cpp/Options/GroupOption.h" +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A program shows the group, or adds START_CHECKPOINT and END_CHECKPOINT +// to its own options under its own keys (keeping the keys its saved +// settings already use) and calls check_validity() from its own. +class StoryRangeOptions : public GroupOption{ +public: + // `checkpoints`: the dropdown database (make_story_select_database() + // or story_checkpoint_database()), kept alive by the caller. The + // dropdowns start on its first and last entries. `end_lock`: + // UNLOCK_WHILE_RUNNING for a program that reads the end after each + // checkpoint, so the end can be moved during a run. + StoryRangeOptions( + std::string label, const StringSelectDatabase& checkpoints, + LockMode end_lock = LockMode::LOCK_WHILE_RUNNING + ); + + // The checkpoints chosen, by index in the database, both inclusive. + size_t start_index() const; + size_t end_index() const; + // "The start checkpoint comes after the end checkpoint." if it does. + virtual std::string check_validity() const override; + +public: + StringSelectOption START_CHECKPOINT; + StringSelectOption END_CHECKPOINT; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp new file mode 100644 index 0000000000..fce811e4c6 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp @@ -0,0 +1,142 @@ +/* Story Range Options Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Pokemon_AutoStorySelect.h" +#include "Pokemon_StoryRangeOptions.h" +#include "Pokemon_StoryRangeOptions_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +// A stand-in for a story checkpoint: only its name is read. +struct NamedCheckpoint{ + std::string label; + std::string name() const{ + return label; + } +}; + +// Two tutorial checkpoints, then three of the main story, as SV's list is +// laid out. +const std::vector>& story_list(){ + static const std::vector> list = []{ + std::vector> ret; + for (std::string_view label : {"tutorial 0", "tutorial 1", "main 0", "main 1", "main 2"}){ + ret.emplace_back(std::make_unique(NamedCheckpoint{.label = std::string(label)})); + } + return ret; + }(); + return list; +} + +// The main story's dropdowns: entries 2..4 of the list, slugged 2..4. +const StringSelectDatabase& main_story_database(){ + static const StringSelectDatabase database = make_story_select_database(story_list(), 2, story_list().size()); + return database; +} + +// A range chosen in the main story's dropdowns and what the group reads from it. +struct StoryRangeCase{ + // The start and end set by slug, as saved settings load them; empty + // leaves the default. + struct Input{ + std::string start_slug; + std::string end_slug; + }; + + // The indexes in the dropdown, and whether the range is valid. + struct Expectation{ + size_t start; + size_t end; + bool valid; + }; + + std::string name; + Input input; + Expectation expectation; +}; + +class Test_StoryRange : public UnitTest{ +public: + Test_StoryRange(StoryRangeCase test_case) + : UnitTest(std::format("Pokemon::StoryRangeOptions - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + StoryRangeOptions range("Checkpoints", main_story_database()); + if (!m_case.input.start_slug.empty()){ + range.START_CHECKPOINT.set_by_slug(m_case.input.start_slug); + } + if (!m_case.input.end_slug.empty()){ + range.END_CHECKPOINT.set_by_slug(m_case.input.end_slug); + } + const StoryRangeCase::Expectation& expected = m_case.expectation; + if (range.start_index() != expected.start || range.end_index() != expected.end){ + return std::format( + "Expected indexes {} to {}, got {} to {}", + expected.start, expected.end, range.start_index(), range.end_index() + ); + } + const std::string error = range.check_validity(); + if (error.empty() != expected.valid){ + return expected.valid ? std::format("Expected a valid range, got: {}", error) : "Expected the range refused."; + } + if (!expected.valid && error != "The start checkpoint comes after the end checkpoint."){ + return std::format("Unexpected message: {}", error); + } + return true; + } + +private: + const StoryRangeCase m_case; +}; + +const StoryRangeCase STORY_RANGE_CASES[] = { + { + .name = "the whole database by default", + .input = {.start_slug = "", .end_slug = ""}, + .expectation = {.start = 0, .end = 2, .valid = true}, + }, + { + .name = "slugs are whole-list indexes, indexes are the dropdown's", + .input = {.start_slug = "3", .end_slug = "4"}, + .expectation = {.start = 1, .end = 2, .valid = true}, + }, + { + .name = "one checkpoint", + .input = {.start_slug = "3", .end_slug = "3"}, + .expectation = {.start = 1, .end = 1, .valid = true}, + }, + { + .name = "a start after the end is refused", + .input = {.start_slug = "4", .end_slug = "2"}, + .expectation = {.start = 2, .end = 0, .valid = false}, + }, +}; + +} // namespace + + +void add_tests_StoryRangeOptions(UnitTestDatabase& database){ + for (const StoryRangeCase& test_case : STORY_RANGE_CASES){ + database.add(test_case); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.h new file mode 100644 index 0000000000..1d3e48e19d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.h @@ -0,0 +1,23 @@ +/* Story Range Options Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRangeOptions_Tests_H +#define PokemonAutomation_Pokemon_StoryRangeOptions_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the shared start/end checkpoint range options. +void add_tests_StoryRangeOptions(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp new file mode 100644 index 0000000000..ff601182f6 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp @@ -0,0 +1,179 @@ +/* Story Run Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon_StoryRunOptions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const EnumDropdownDatabase& StoryCheckLevel_Database(){ + static const EnumDropdownDatabase database({ + {StoryCheckLevel::TESTING, "testing", "Testing: run each checkpoint 3 times to be sure it really passes"}, + {StoryCheckLevel::THOROUGH, "thorough", "Thorough: check everything for the user (Bag items, Pok\u00e9mon stats, preconditions)"}, + {StoryCheckLevel::DEFAULT, "default", "Default: check the most important things, assume the rest is fine"}, + {StoryCheckLevel::FAST, "fast", "Fast: minimal checks"}, + {StoryCheckLevel::SPEEDRUN, "speedrun", "Speedrun: almost no checks, as fast as possible"}, + }); + return database; +} + + +const EnumDropdownDatabase& StorySaveMode_Database(){ + static const EnumDropdownDatabase database({ + {StorySaveMode::NONE, "none", "None: never save (testing a checkpoint; the start save stays)"}, + {StorySaveMode::AFTER_VERIFICATION, "after_verification", "After verification: save once, at the end of a run that passed"}, + {StorySaveMode::PER_CHECKPOINT, "per_checkpoint", "Each checkpoint: save after each checkpoint that passed (a playthrough)"}, + }); + return database; +} + + +namespace{ + +constexpr std::string_view SAVE_MODE_LABEL = + "Save:
When the run saves the game. A failed run never saves. " + "None keeps the save the run started from. After verification saves once, at the end of a run that passed " + "(in Verify Mode, at the end of the last run, when every run passed). Each checkpoint saves after each " + "checkpoint that passed, for a playthrough of verified checkpoints."; + +constexpr std::string_view RELOAD_AT_START_LABEL = + "Reload the Save at the Start:
Close the game and load the save before the first checkpoint. " + "Off: start from wherever the game is (resumed from HOME if need be), for a game already at the start checkpoint. " + "Later checkpoints reload as usual. Off needs Save set to None."; + +} // namespace + + +std::string story_checkpoint_label(const StoryCheckpoint& checkpoint){ + return checkpoint.title.empty() ? checkpoint.id : std::format("{} {}", checkpoint.id, checkpoint.title); +} + + + +StoryVerifyOptions::StoryVerifyOptions() + : GroupOption( + "Verify Mode: run the start checkpoint (also the end) from its save several times. " + "Only with Save set to After verification does the last run save at its end, when every run passed", + LockMode::LOCK_WHILE_RUNNING, + EnableMode::DEFAULT_DISABLED + ) + , RUNS( + "Runs:
Runs of the checkpoint, each from its save.", + LockMode::LOCK_WHILE_RUNNING, + 3, 1, 20 + ) + , PASSES( + "Passes needed:
Runs that must pass for the checkpoint to be verified.", + LockMode::LOCK_WHILE_RUNNING, + 2, 1, 20 + ) +{ + PA_ADD_OPTION(RUNS); + PA_ADD_OPTION(PASSES); +} + +std::optional StoryVerifyOptions::policy() const{ + if (!enabled()){ + return std::nullopt; + } + return VerifyPolicy{.runs = RUNS, .passes_needed = PASSES}; +} + +std::string StoryVerifyOptions::check_validity() const{ + if (enabled() && PASSES > RUNS){ + return "Verify mode can't need more passes than it has runs."; + } + return GroupOption::check_validity(); +} + + +StoryRunOptions::StoryRunOptions(const StringSelectDatabase& checkpoints, const EnumDropdownDatabase& languages) + : StoryRangeOptions("Story Run", checkpoints) + , ATTEMPTS_PER_CHECKPOINT( + "Attempts per checkpoint:
A failed checkpoint reloads its save and runs again, up to this many times in all. " + "1 stops at the first failure, leaving the game where it failed.", + LockMode::LOCK_WHILE_RUNNING, + 3, 1, 20 + ) + , CHECKS( + "Checks:
How much each step reads the screen to confirm what it did, from Testing (the most) to Speedrun (almost none).", + StoryCheckLevel_Database(), + LockMode::LOCK_WHILE_RUNNING, + StoryCheckLevel::DEFAULT + ) + , LANGUAGE( + "Game language:
For the few reads that need text (item names in a shop or the Bag). " + "Story steps never match dialogue text; with no reader for this language they check positions, digits and the screen instead.", + languages, + LockMode::LOCK_WHILE_RUNNING, + Language::English + ) + , SAVE_MODE(std::string(SAVE_MODE_LABEL), StorySaveMode_Database(), LockMode::LOCK_WHILE_RUNNING, StorySaveMode::NONE) + , RELOAD_AT_START(std::string(RELOAD_AT_START_LABEL), LockMode::LOCK_WHILE_RUNNING, true) + , POSTCONDITIONS_ONLY( + "Check postconditions only:
Run nothing: read where the game stands and check the end checkpoint's " + "position, items and flags. What the game can't read yet is reported as not checked.", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(ATTEMPTS_PER_CHECKPOINT); + PA_ADD_OPTION(CHECKS); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(VERIFY); + PA_ADD_OPTION(SAVE_MODE); + PA_ADD_OPTION(RELOAD_AT_START); + PA_ADD_OPTION(POSTCONDITIONS_ONLY); +} + +std::string StoryRunOptions::check_validity() const{ + std::string error = StoryRangeOptions::check_validity(); + if (!error.empty()){ + return error; + } + if (VERIFY.enabled() && start_index() != end_index()){ + return "Verify mode runs one checkpoint: set the end checkpoint to the start checkpoint."; + } + if (VERIFY.enabled() && POSTCONDITIONS_ONLY){ + return "Check postconditions only runs nothing: turn off Verify Mode."; + } + if (!RELOAD_AT_START && SAVE_MODE != StorySaveMode::NONE){ + return "Reload the Save at the Start is off: the run starts from wherever the game is, which nothing checked, " + "so it must not save. Set Save to None or turn the reload on."; + } + return error; +} + +SegmentPolicy StoryRunOptions::policy() const{ + SegmentPolicy policy; + policy.attempts_per_checkpoint = ATTEMPTS_PER_CHECKPOINT; + policy.save_mode = SAVE_MODE; + return policy; +} + +std::optional StoryRunOptions::verify_policy() const{ + std::optional policy = VERIFY.policy(); + if (policy){ + policy->save_mode = SAVE_MODE; + } + return policy; +} + +StoryCheckLevel StoryRunOptions::check_level() const{ + return CHECKS; +} + +Language StoryRunOptions::language() const{ + return LANGUAGE; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h new file mode 100644 index 0000000000..0029ea908c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h @@ -0,0 +1,113 @@ +/* Story Run Options + * + * From: https://github.com/PokemonAutomation/ + * + * The options every AutoStory program shows for where to start and end, how + * hard to try and how much to check: the shared range group + * (Pokemon_StoryRangeOptions.h) plus the run policy, read into the shared + * SegmentPolicy (Pokemon/AutoStory/Pokemon_StorySegments.h), the checks + * level (Types/Pokemon_StoryCheckLevel.h), the language the game's steps + * read text in, when the run saves (Types/Pokemon_StorySaveMode.h), + * whether it reloads the save before its first checkpoint and whether it + * only checks postconditions. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRunOptions_H +#define PokemonAutomation_Pokemon_StoryRunOptions_H + +#include +#include +#include +#include +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Language.h" +#include "CommonTools/Options/StringSelectOption.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" +#include "Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h" +#include "Pokemon_StoryRangeOptions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A checkpoint's label in the start and end dropdowns, as SV labels its +// segments: "00.09 Pewter Gym: Camper Liam, then Brock". The labels of a +// story's checkpoints, in order, make its dropdowns +// (story_checkpoint_database()). +std::string story_checkpoint_label(const StoryCheckpoint& checkpoint); + + +// Verify mode, off by default (verify_checkpoint()): the start checkpoint +// RUNS times from its save; verified when at least PASSES pass. Only the +// last run may save, at its end, when SAVE_MODE is After verification +// and every run passed. For a battle that has lost twice or more, given +// its own checkpoint saved right before it. +class StoryVerifyOptions : public GroupOption{ +public: + StoryVerifyOptions(); + + // The runs and passes, unset when verify mode is off. + std::optional policy() const; + virtual std::string check_validity() const override; + +public: + SimpleIntegerOption RUNS; + SimpleIntegerOption PASSES; +}; + + +// The range group (START_CHECKPOINT, END_CHECKPOINT, start_index(), +// end_index()) with the run policy added to the same group, so the saved +// settings keep one flat object. +class StoryRunOptions : public StoryRangeOptions{ +public: + // `checkpoints`: story_checkpoint_database() of the game's story, kept + // alive by the caller; the dropdowns start on its first and last. + // `languages`: the ones the game has (Pokemon_GameLanguages.h). + StoryRunOptions(const StringSelectDatabase& checkpoints, const EnumDropdownDatabase& languages); + + // The range's check, then verify mode's: one checkpoint only; then a + // run without the reload at the start must not save. + virtual std::string check_validity() const override; + + // The policy these options set, with the save mode. + SegmentPolicy policy() const; + // Verify mode's runs and passes with the save mode; unset when off. + std::optional verify_policy() const; + // The checks level, for the game's steps to read. + StoryCheckLevel check_level() const; + // The game's language, for the steps that read text. + Language language() const; + +public: + SimpleIntegerOption ATTEMPTS_PER_CHECKPOINT; + EnumDropdownOption CHECKS; + // Any language the game has, whether or not a reader supports it: + // steps without one use language-free checks, so none is refused. + EnumDropdownOption LANGUAGE; + // On, it runs one checkpoint: the start, which must also be the end. + StoryVerifyOptions VERIFY; + // When the run saves; NONE (testing) by default. + EnumDropdownOption SAVE_MODE; + // On (the default), the run loads the save before its first + // checkpoint (StoryLaunchRequest::Running::RESTART). Off, it starts + // from where the game is, resumed from HOME if need be (Running::KEEP); + // later checkpoints reload as before. Off needs SAVE_MODE NONE: the + // run must not save from a position nothing checked. + BooleanCheckBoxOption RELOAD_AT_START; + // On, nothing runs: the game reads where it stands and checks the end + // checkpoint's postconditions (Pokemon_StoryPostconditionCheck.h). + BooleanCheckBoxOption POSTCONDITIONS_ONLY; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions_Tests.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions_Tests.cpp new file mode 100644 index 0000000000..c9f62e050d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions_Tests.cpp @@ -0,0 +1,99 @@ +/* Story Run Options Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Pokemon_AutoStorySelect.h" +#include "Pokemon_GameLanguages.h" +#include "Pokemon_StoryRunOptions.h" +#include "Pokemon_StoryRunOptions_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +// Two checkpoints' dropdowns. +const StringSelectDatabase& two_checkpoints(){ + static const StringSelectDatabase database = story_checkpoint_database(std::vector{"01.01", "01.02"}); + return database; +} + +// The reload at the start and the save mode a user set, and whether the +// options let the run start. +struct ReloadAtStartCase{ + struct Input{ + bool reload_at_start; + StorySaveMode save_mode; + }; + struct Expectation{ + // Empty: the options are valid; else the refusal's message. + std::string_view error; + }; + std::string_view name; + Input input; + Expectation expectation; +}; + +constexpr std::string_view NO_RELOAD_SAVES = + "Reload the Save at the Start is off: the run starts from wherever the game is, which nothing checked, " + "so it must not save. Set Save to None or turn the reload on."; + +const ReloadAtStartCase RELOAD_AT_START_CASES[] = { + {.name = "reload at the start by default", .input = {.reload_at_start = true, .save_mode = StorySaveMode::NONE}, + .expectation = {.error = ""}}, + {.name = "a reloaded run may save", .input = {.reload_at_start = true, .save_mode = StorySaveMode::PER_CHECKPOINT}, + .expectation = {.error = ""}}, + {.name = "no reload without saves", .input = {.reload_at_start = false, .save_mode = StorySaveMode::NONE}, + .expectation = {.error = ""}}, + {.name = "no reload refuses saves after verification", .input = {.reload_at_start = false, .save_mode = StorySaveMode::AFTER_VERIFICATION}, + .expectation = {.error = NO_RELOAD_SAVES}}, + {.name = "no reload refuses saves per checkpoint", .input = {.reload_at_start = false, .save_mode = StorySaveMode::PER_CHECKPOINT}, + .expectation = {.error = NO_RELOAD_SAVES}}, +}; + +class Test_ReloadAtStart : public UnitTest{ +public: + explicit Test_ReloadAtStart(ReloadAtStartCase test_case) + : UnitTest(std::format("Pokemon::StoryRunOptions - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + StoryRunOptions run(two_checkpoints(), Gen8ToGen9Languages_Database()); + if (!run.RELOAD_AT_START){ + return "Expected the reload at the start on by default."; + } + run.RELOAD_AT_START = m_case.input.reload_at_start; + run.SAVE_MODE.set(m_case.input.save_mode); + const std::string error = run.check_validity(); + if (error != m_case.expectation.error){ + return std::format("Expected \"{}\", got \"{}\".", m_case.expectation.error, error); + } + return true; + } + +private: + const ReloadAtStartCase m_case; +}; + +} // namespace + + +void add_tests_StoryRunOptions(UnitTestDatabase& database){ + for (const ReloadAtStartCase& test_case : RELOAD_AT_START_CASES){ + database.add(test_case); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions_Tests.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions_Tests.h new file mode 100644 index 0000000000..1ebc703cd0 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions_Tests.h @@ -0,0 +1,23 @@ +/* Story Run Options Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRunOptions_Tests_H +#define PokemonAutomation_Pokemon_StoryRunOptions_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the shared run options' checks. +void add_tests_StoryRunOptions(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index ef854e0700..52e3972117 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1374,6 +1374,8 @@ file(GLOB LIBRARY_SOURCES Source/NintendoSwitch/Inference/NintendoSwitch_FailedToConnectDetector.h Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.cpp Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h + Source/NintendoSwitch/Inference/NintendoSwitch_HomeTileReader.cpp + Source/NintendoSwitch/Inference/NintendoSwitch_HomeTileReader.h Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.cpp Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.cpp @@ -1505,6 +1507,10 @@ file(GLOB LIBRARY_SOURCES 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_StoryLaunch.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch.h + Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch_Tests.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_StoryLaunch_Tests.h Source/Pokemon/AutoStory/Engine/Pokemon_StoryPoseConcept.cpp Source/Pokemon/AutoStory/Engine/Pokemon_StoryPoseConcept.h Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.cpp @@ -1551,6 +1557,8 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.h + Source/Pokemon/AutoStory/Pokemon_StorySwitchPrompts.cpp + Source/Pokemon/AutoStory/Pokemon_StorySwitchPrompts.h Source/Pokemon/AutoStory/Pokemon_TestExpect.h Source/Pokemon/AutoStory/Pokemon_TilePose.cpp Source/Pokemon/AutoStory/Pokemon_TilePose.h @@ -1606,6 +1614,8 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Options/Pokemon_BoxSortingTable.cpp Source/Pokemon/Options/Pokemon_BoxSortingTable.h Source/Pokemon/Options/Pokemon_EncounterBotOptions.h + Source/Pokemon/Options/Pokemon_GameLanguages.cpp + Source/Pokemon/Options/Pokemon_GameLanguages.h Source/Pokemon/Options/Pokemon_HomeSpriteSelectOption.cpp Source/Pokemon/Options/Pokemon_HomeSpriteSelectOption.h Source/Pokemon/Options/Pokemon_IvJudgeOption.cpp @@ -1626,6 +1636,14 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_CheckpointId.h Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h + Source/Pokemon/Options/Pokemon_StoryRangeOptions.cpp + Source/Pokemon/Options/Pokemon_StoryRangeOptions.h + Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp + Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.h + Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp + Source/Pokemon/Options/Pokemon_StoryRunOptions.h + Source/Pokemon/Options/Pokemon_StoryRunOptions_Tests.cpp + Source/Pokemon/Options/Pokemon_StoryRunOptions_Tests.h Source/Pokemon/Pokemon_AdvRng.cpp Source/Pokemon/Pokemon_AdvRng.h Source/Pokemon/Pokemon_BdspRng.cpp