diff --git a/.github/workflows/cpp-ci-serial-programs-base.yml b/.github/workflows/cpp-ci-serial-programs-base.yml index 1601ddaa9a..48e45d1d1c 100644 --- a/.github/workflows/cpp-ci-serial-programs-base.yml +++ b/.github/workflows/cpp-ci-serial-programs-base.yml @@ -106,7 +106,7 @@ jobs: uses: actions/checkout@v7 with: repository: dayfine/PokemonSimulation - ref: 9cb12c52f5f055299e32c2a7cf43e7103c101e3e + ref: bdca47c5045797be1d2a1f0931ad6a8f15ab3225 path: StoryReplaySource - name: Verify replay preview bytes and independently regenerate its route input diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index eb78e63e6a..ddb921e11b 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -234,7 +234,7 @@ pa_embed_text_files(SerialProgramsLib "${FRLG_MAP_RESOURCES}" pa_embed_text_files(SerialProgramsLib Source/VideoGames/PokemonFRLG/Programs/AutoStory/BattleData VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.h PokemonAutomation::NintendoSwitch::PokemonFRLG autostory_battle_json) pa_embed_text_files(SerialProgramsLib Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData - VideoGames/PokemonFRLG/Programs/AutoStory/Data/JsonParser.h PokemonAutomation::NintendoSwitch::PokemonFRLG autostory_checkpoint_json) + VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h PokemonAutomation::NintendoSwitch::PokemonFRLG autostory_checkpoint_json) pa_embed_text_files(SerialProgramsLib Source/VideoGames/PokemonFRLG/Programs/AutoStory/ReplayData VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay.h PokemonAutomation::NintendoSwitch::PokemonFRLG story_replay_fixture_json) diff --git a/SerialPrograms/Source/CommonTools/ScreenMachine/StepTrace.cpp b/SerialPrograms/Source/CommonTools/ScreenMachine/StepTrace.cpp index 4e7a69b911..97503bb1a2 100644 --- a/SerialPrograms/Source/CommonTools/ScreenMachine/StepTrace.cpp +++ b/SerialPrograms/Source/CommonTools/ScreenMachine/StepTrace.cpp @@ -36,9 +36,7 @@ void StepTrace::screen(const std::string& name){ } m_count++; const double seconds = std::chrono::duration(current_time() - m_start).count(); - char prefix[16]; - std::snprintf(prefix, sizeof(prefix), "%03zu-", m_count); - std::string path = m_folder + prefix + name + ".png"; + std::string path = m_folder + std::format("{:03}-", m_count) + name + ".png"; VideoSnapshot screen = m_stream.video().snapshot(); if (screen){ screen.frame->save(path); diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index b4f5041241..feeda0774e 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -15,6 +15,7 @@ #include "Common/Qt/QtThreadPool_Tests.h" #include "Kernels/Kernels_Tests.h" #include "Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h" +#include "Pokemon/AutoStory/Pokemon_StoryRun_Tests.h" #include "CommonFramework/AudioPipeline/AudioInfo_Tests.h" #include "CommonFramework/AudioPipeline/Tools/ChannelMixer.h" #include "CommonFramework/AudioPipeline/SinkPipeline_Tests.h" @@ -80,16 +81,16 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_MapData(ret); Pokemon::add_tests_RuntimeMap(ret); Pokemon::add_tests_RouteLog(ret); + Pokemon::add_tests_StoryEvents(ret); + Pokemon::add_tests_StorySegments(ret); + Pokemon::add_tests_StoryLog(ret); + Pokemon::add_tests_StoryRangeOptions(ret); Pokemon::add_tests_ScreenEvents(ret); Pokemon::add_tests_Interrupts(ret); Pokemon::add_tests_Transitions(ret); Pokemon::add_tests_StoryActions(ret); Pokemon::add_tests_StoryInterrupts(ret); - Pokemon::add_tests_StoryEvents(ret); - Pokemon::add_tests_StorySegments(ret); - Pokemon::add_tests_StorySteps(ret); - Pokemon::add_tests_StoryStepJson(ret); - Pokemon::add_tests_AuthoredCheckpointJson(ret); + Pokemon::add_tests_AutoStory(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); NintendoSwitch::add_tests_UpdatePopupDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp similarity index 60% rename from SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.cpp rename to SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp index 699ece6df1..e70da3dd48 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp @@ -1,5 +1,7 @@ /* Shared Authored Checkpoint JSON + * * From: https://github.com/PokemonAutomation/ + * */ #include @@ -12,7 +14,7 @@ namespace PokemonAutomation{ namespace Pokemon{ -void require_story_json_fields( +void validate_json_fields( const JsonObject& object, std::initializer_list fields, std::string_view source ){ if (object.size() != fields.size()){ @@ -23,20 +25,20 @@ void require_story_json_fields( } } -AuthoredCheckpoint read_authored_checkpoint( - const JsonValue& value, std::string_view expected_game, std::string_view source +StoryCheckpoint read_authored_checkpoint( + const JsonValue& value, std::string_view game, std::string_view source, + const ExecutionReader& read_execution, std::span actions ){ const JsonObject& root = value.to_object_throw(std::string(source)); - require_story_json_fields(root, {"format", "game", "checkpoint", "execution"}, source); - if (expected_game.empty() || root.get_string_throw("format") != "pokesim-authored-checkpoint/1" - || root.get_string_throw("game") != expected_game + validate_json_fields(root, {"format", "game", "checkpoint", "execution"}, source); + if (game.empty() || root.get_string_throw("format") != "pokesim-authored-checkpoint/1" + || root.get_string_throw("game") != game ){ throw ParseException(std::format("{}: unsupported authored checkpoint format/game.", source)); } - return { - .checkpoint = read_story_checkpoint(root.get_value_throw("checkpoint"), source), - .execution = root.get_object_throw("execution", std::string(source)).clone(), - }; + StoryCheckpoint checkpoint = read_story_checkpoint(root.get_value_throw("checkpoint"), source, actions); + read_execution(root.get_object_throw("execution", std::string(source)), source); + return checkpoint; } JsonValue authored_checkpoint_json(const StoryCheckpoint& checkpoint, std::string_view game, JsonObject execution){ @@ -51,17 +53,19 @@ JsonValue authored_checkpoint_json(const StoryCheckpoint& checkpoint, std::strin return result; } -AuthoredCheckpoint load_authored_checkpoint( - std::span> files, std::string_view file, std::string_view expected_game +StoryCheckpoint load_authored_checkpoint( + std::span files, std::string_view file, std::string_view game, + const ExecutionReader& read_execution, std::span actions ){ for (const auto& [name, text] : files){ if (name == file){ - return read_authored_checkpoint(parse_json(text), expected_game, file); + return read_authored_checkpoint(parse_json(text), game, file, read_execution, actions); } } throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Authored checkpoint is not embedded: " + std::string(file)); } + } // namespace Pokemon } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h new file mode 100644 index 0000000000..9e20f7a252 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h @@ -0,0 +1,72 @@ +/* Shared Authored Checkpoint JSON + * + * From: https://github.com/PokemonAutomation/ + * + * Reading and writing an authored checkpoint file: the shared + * StoryCheckpoint (Pokemon_StoryStepJson.h) in an envelope that names the + * game, plus the game's own execution object, which the game parses into + * its own type through a reader it passes in. Only parsing and encoding: + * nothing here binds or runs a step, and nothing read keeps JSON. + * + */ + +#ifndef PokemonAutomation_AuthoredCheckpointJson_H +#define PokemonAutomation_AuthoredCheckpointJson_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The game's reader of an envelope's execution object: it parses the +// object into the game's own type and throws ParseException when it is +// malformed. +using ExecutionReader = std::function; + +// Require exactly these fields, including fields whose value is null/zero/false. +// Missing/unknown fields throw ParseException with the document source. +void validate_json_fields( + const JsonObject& object, std::initializer_list fields, std::string_view source +); + +// The checkpoint of `game`'s strict authored envelope, its steps read +// against `actions` (read_story_checkpoint()); its execution object goes +// to `read_execution`. +StoryCheckpoint read_authored_checkpoint( + const JsonValue& value, std::string_view game, std::string_view source, + const ExecutionReader& read_execution, + std::span actions = builtin_story_actions() +); + +// Encode the authored envelope; execution is supplied by the game adapter. +// This does not encode game bookkeeping or the legacy native-export envelope. +JsonValue authored_checkpoint_json(const StoryCheckpoint& checkpoint, std::string_view game, JsonObject execution); + +// A JSON file built into the program: its name without ".json", and its +// text. +using EmbeddedJsonFile = std::pair; + +// Find embedded file `file` among `files` and parse it as +// read_authored_checkpoint() does. Missing resources throw +// InternalProgramError; malformed documents throw ParseException. +StoryCheckpoint load_authored_checkpoint( + std::span files, std::string_view file, std::string_view game, + const ExecutionReader& read_execution, + std::span actions = builtin_story_actions() +); + + + +} // namespace Pokemon +} // namespace PokemonAutomation + +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp similarity index 81% rename from SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson_Tests.cpp rename to SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp index 7aba0e12f4..befc884cec 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp @@ -1,25 +1,37 @@ /* Shared Authored Checkpoint JSON Tests + * * From: https://github.com/PokemonAutomation/ + * */ #include +#include +#include #include #include "Common/Cpp/Exceptions.h" #include "Pokemon_AuthoredCheckpointJson.h" #include "Pokemon_StoryStepJson.h" #ifndef PA_STORY_DATA_STANDALONE -#include "Pokemon_AutoStory_Tests.h" +#include "Pokemon/AutoStory/Pokemon_AutoStory_Tests.h" #endif namespace PokemonAutomation{ namespace Pokemon{ + + namespace{ + // Documents intentionally contain no game headers or native bookkeeping. -const std::string FRLG = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{"id":"00.05","title":"Parcel","events":[{"id":"first","kind":"route"},{"id":"second","kind":"scene"}]},"execution":{"menu":"before_pokedex"}})"; +const std::string FRLG = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{"id":"00.05","title":"Parcel","events":[{"id":"first","kind":"talk"},{"id":"second","kind":"scene"}]},"execution":{"menu":"before_pokedex"}})"; const std::string BDSP = R"({"format":"pokesim-authored-checkpoint/1","game":"bdsp","checkpoint":{"id":"01.03","title":"Mine","events":[{"id":"roark","kind":"talk"}]},"execution":{"on_failure":"reload_and_retry","saves_in":"Oreburgh City"}})"; -enum class Failure{ NONE, PARSE, MISSING_RESOURCE }; +// How a case fails, if it does. +enum class Failure{ + NONE, + PARSE, + MISSING_RESOURCE, +}; struct AuthoredInput{ std::string name; @@ -60,7 +72,24 @@ const AuthoredCase CASES[] = { .checkpoint = "x", .execution = R"({"zero":0,"false":false,"null":null})", .events = {}}}, }; -std::string check_loaded(const AuthoredCheckpoint& actual, const AuthoredCase& test){ + +// What a test reads: the checkpoint, and the execution object its reader +// kept. +struct Loaded{ + StoryCheckpoint checkpoint; + JsonObject execution; +}; + +// A reader that keeps the execution object in `kept`. +ExecutionReader keep_execution(JsonObject& kept){ + return [&kept](const JsonObject& execution, std::string_view){ + kept = execution.clone(); + }; +} + +// "" when `actual` is what `test` expects and survives a write and a +// read, else what was expected and what was read. +std::string check_loaded(const Loaded& actual, const AuthoredCase& test){ if (test.expectation.failure != Failure::NONE){ return "Expected rejection, read accepted authored checkpoint."; } @@ -78,19 +107,22 @@ std::string check_loaded(const AuthoredCheckpoint& actual, const AuthoredCase& t return "Expected authored event IDs in their original order."; } const JsonValue encoded = authored_checkpoint_json(actual.checkpoint, test.input.game, actual.execution.clone()); - const AuthoredCheckpoint reread = read_authored_checkpoint(encoded, test.input.game, test.input.name); + Loaded reread; + reread.checkpoint = read_authored_checkpoint(encoded, test.input.game, test.input.name, keep_execution(reread.execution)); if (!(story_checkpoint_json(actual.checkpoint) == story_checkpoint_json(reread.checkpoint)) || actual.execution != reread.execution){ return "Expected checkpoint and execution to survive the shared writer/reader round trip."; } return ""; } +// "" when `test` reads or fails as expected. std::string check_case(const AuthoredCase& test){ try{ const std::vector> files = {{"plan", test.input.json}}; - const AuthoredCheckpoint actual = test.input.resource - ? load_authored_checkpoint(files, test.input.file, test.input.game) - : read_authored_checkpoint(parse_json(test.input.json), test.input.game, test.input.name); + Loaded actual; + actual.checkpoint = test.input.resource + ? load_authored_checkpoint(files, test.input.file, test.input.game, keep_execution(actual.execution)) + : read_authored_checkpoint(parse_json(test.input.json), test.input.game, test.input.name, keep_execution(actual.execution)); return check_loaded(actual, test); }catch (const ParseException& error){ return test.expectation.failure == Failure::PARSE ? "" : "Unexpected parse failure: " + error.message(); @@ -99,34 +131,49 @@ std::string check_case(const AuthoredCase& test){ } } + #ifndef PA_STORY_DATA_STANDALONE + class AuthoredJsonTest : public UnitTest{ public: explicit AuthoredJsonTest(AuthoredCase test) - : UnitTest("Pokemon::AuthoredCheckpointJson - " + test.input.name), m_case(std::move(test)){} + : UnitTest("Pokemon::AuthoredCheckpointJson - " + test.input.name) + , m_case(std::move(test)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ const std::string error = check_case(m_case); return error.empty() ? UnitTestResult(true) : UnitTestResult(error); } + private: AuthoredCase m_case; }; + #endif + } // namespace + #ifndef PA_STORY_DATA_STANDALONE + void add_tests_AuthoredCheckpointJson(UnitTestDatabase& database){ for (const AuthoredCase& test : CASES){ database.add(test); } } + #endif + + } // namespace Pokemon } // namespace PokemonAutomation + #ifdef PA_STORY_DATA_STANDALONE + int main(){ int failed = 0; for (const auto& test : PokemonAutomation::Pokemon::CASES){ @@ -136,4 +183,5 @@ int main(){ } return failed != 0; } + #endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp similarity index 53% rename from SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp rename to SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp index 3ee2f51f6d..f81ecc7ef2 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp @@ -1,19 +1,32 @@ /* Story Step JSON + * * From: https://github.com/PokemonAutomation/ + * */ + +#include #include #include #include #include +#include #include +#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Json/JsonArray.h" #include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" #include "Pokemon_StoryStepJson.h" + namespace PokemonAutomation{ namespace Pokemon{ + + namespace{ + + +// The wire names of the step kinds. constexpr std::array, 15> KINDS{{ {StoryStepKind::NEW_GAME, "new_game"}, {StoryStepKind::OPTIONS, "options"}, @@ -31,13 +44,8 @@ constexpr std::array, 15> KINDS{{ {StoryStepKind::READY, "ready"}, {StoryStepKind::GAME, "game_action"}, }}; -constexpr std::array, 5> CERTAINTIES{{ - {PoseCertainty::TILE, "tile"}, - {PoseCertainty::COLUMN, "column"}, - {PoseCertainty::ROW, "row"}, - {PoseCertainty::SET, "set"}, - {PoseCertainty::UNKNOWN, "unknown"}, -}}; + +// The wire names of the directions. constexpr std::array, 4> DIRECTIONS{{ {Direction::NORTH, "north"}, {Direction::EAST, "east"}, @@ -45,6 +53,8 @@ constexpr std::array, 4> DIRECTIONS{{ {Direction::WEST, "west"}, }}; + +// `value` as an object with no field outside `keys`. const JsonObject& fields(const JsonValue& value, std::initializer_list keys, std::string_view source){ const JsonObject& object = value.to_object_throw(std::string(source)); for (const auto& [key, unused] : object){ @@ -60,7 +70,7 @@ const JsonObject& fields(const JsonValue& value, std::initializer_list -Enum read_enum(const std::array, N>& names, const std::string& name, std::string_view source){ +Enum read_enum(const std::array, N>& names, std::string_view name, std::string_view source){ for (const auto& [value, label] : names){ if (label == name){ return value; @@ -102,7 +112,7 @@ JsonValue count_json(size_t value){ return (uint64_t)value; } -JsonArray strings_json(const std::vector& strings){ +JsonArray strings_json(std::span strings){ JsonArray result; for (const std::string& value : strings){ result.push_back(value); @@ -118,7 +128,7 @@ std::vector read_strings(const JsonValue& value, std::string_view s return result; } -JsonArray legs_json(const std::vector& legs){ +JsonArray legs_json(std::span legs){ JsonArray result; for (const StoryLeg& leg : legs){ JsonObject item; @@ -139,7 +149,7 @@ std::vector read_legs(const JsonValue& value, std::string_view source) return result; } -JsonArray items_json(const std::vector& items){ +JsonArray items_json(std::span items){ JsonArray result; for (const StoryItem& item : items){ JsonObject row; @@ -158,80 +168,139 @@ std::vector read_items(const JsonValue& value, std::string_view sourc } return result; } -StoryStep read_step_options(StoryStep result, const JsonObject& root, std::string_view source){ - if (const JsonValue* field = root.get_value("fight_wild")){ - result.fight_wild = field->to_boolean_throw(); + +JsonArray tiles_json(std::span tiles){ + JsonArray result; + for (const TilePos& tile : tiles){ + JsonArray pair; + pair.push_back(tile.x); + pair.push_back(tile.y); + result.push_back(std::move(pair)); } - if (const JsonValue* field = root.get_value("yes")){ - result.yes = field->to_boolean_throw(); + return result; +} + +std::vector read_tiles(const JsonValue& value, std::string_view source){ + std::vector result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + const JsonArray& pair = item.to_array_throw(std::string(source)); + if (pair.size() != 2){ + throw ParseException(std::format("{}: a tile needs two coordinates", source)); + } + result.push_back({integer(pair[0], source), integer(pair[1], source)}); } - if (const JsonValue* field = root.get_value("may_lose")){ - result.may_lose = field->to_boolean_throw(); + return result; +} + +// One arg's value as JSON. +JsonValue arg_json(const StoryArgValue& value){ + switch (story_arg_type(value)){ + case StoryArgType::BOOLEAN: + return std::get(value); + case StoryArgType::INTEGER: + return std::get(value); + case StoryArgType::WORD: + return std::get(value); + case StoryArgType::DIRECTION: + return enum_name(DIRECTIONS, std::get(value)); + case StoryArgType::GRID_POSE: + return grid_pose_json(std::get(value)); + case StoryArgType::LEGS: + return legs_json(std::get>(value)); + case StoryArgType::WORDS: + return strings_json(std::get>(value)); + case StoryArgType::ITEMS: + return items_json(std::get>(value)); + } + throw ParseException("Unsupported story arg type."); +} + +// One arg's value read as `type`. +StoryArgValue read_arg(const JsonValue& value, StoryArgType type, std::string_view source){ + switch (type){ + case StoryArgType::BOOLEAN: + return value.to_boolean_throw(std::string(source)); + case StoryArgType::INTEGER: + return value.to_integer_throw(std::string(source)); + case StoryArgType::WORD: + return value.to_string_throw(std::string(source)); + case StoryArgType::DIRECTION: + return read_enum(DIRECTIONS, value.to_string_throw(std::string(source)), source); + case StoryArgType::GRID_POSE: + return read_grid_pose(value, source); + case StoryArgType::LEGS: + return read_legs(value, source); + case StoryArgType::WORDS: + return read_strings(value, source); + case StoryArgType::ITEMS: + return read_items(value, source); + } + throw ParseException(std::format("{}: unsupported story arg type", source)); +} + +// The step's action among `actions`: the named one, or the kind's default. +// Null for a kind with no action that names none. +const StoryActionSpec* step_action( + const StoryStep& step, std::span actions, std::string_view source +){ + if (step.kind == StoryStepKind::GAME && step.action.empty()){ + throw ParseException(std::format("{}: game_action step {} names no action", source, step.name)); + } + const StoryActionSpec* spec = find_story_action(actions, step.kind, step.action); + if (spec == nullptr && !step.action.empty()){ + throw ParseException(std::format("{}: step {}: unknown action {}", source, step.name, step.action)); + } + return spec; +} + +// The step's args, read against its action's spec, with the fallbacks +// filled in. +StoryActionArgs read_args( + const JsonValue* value, const StoryActionSpec* spec, const StoryStep& step, std::string_view source +){ + const StoryActionSpec none{.kind = step.kind, .name = "", .args = {}}; + const StoryActionSpec& action = spec ? *spec : none; + StoryActionArgs result; + if (value != nullptr){ + for (const auto& [key, item] : value->to_object_throw(std::string(source))){ + const auto arg = std::find_if(action.args.begin(), action.args.end(), [&](const StoryArgSpec& candidate){ + return candidate.key == key; + }); + if (arg == action.args.end()){ + throw ParseException(std::format("{}: step {}: unknown argument \"{}\"", source, step.name, key)); + } + result[key] = read_arg(item, arg->type, source); + } } - if (const JsonValue* field = root.get_value("battles")){ - result.battles = count(*field, source); + const std::vector errors = story_args_errors(action, result); + if (!errors.empty()){ + throw ParseException(std::format("{}: step {}: {}", source, step.name, errors.front())); } - return result; + return with_fallbacks(action, std::move(result)); } + } // namespace -JsonValue story_pose_json(const Pose& pose){ + +JsonValue grid_pose_json(const GridPose& pose){ JsonObject result; result["map"] = pose.map; - result["certainty"] = enum_name(CERTAINTIES, pose.certainty); - JsonObject where; - where["kind"] = "unknown"; - if (pose.where){ - const auto* tiles = dynamic_cast(pose.where.get()); - if (!tiles){ - throw ParseException("Unsupported story Position subtype."); - } - where["kind"] = "tiles"; - JsonArray positions; - for (const TilePos& tile : tiles->tiles){ - JsonArray pair; - pair.push_back(tile.x); pair.push_back(tile.y); - positions.push_back(std::move(pair)); - } - where["tiles"] = std::move(positions); - if (tiles->facing){ - where["facing"] = enum_name(DIRECTIONS, *tiles->facing); - } + result["tiles"] = tiles_json(pose.tiles); + if (pose.facing){ + result["facing"] = enum_name(DIRECTIONS, *pose.facing); } - result["where"] = std::move(where); return result; } -Pose read_story_pose(const JsonValue& value, std::string_view source){ - const JsonObject& root = fields(value, {"map", "certainty", "where"}, source); - Pose result; +GridPose read_grid_pose(const JsonValue& value, std::string_view source){ + const JsonObject& root = fields(value, {"map", "tiles", "facing"}, source); + GridPose result; result.map = root.get_string_throw("map"); - result.certainty = read_enum(CERTAINTIES, root.get_string_throw("certainty"), source); - const JsonObject& where = fields(root.get_value_throw("where"), {"kind", "tiles", "facing"}, source); - const std::string& kind = where.get_string_throw("kind"); - if (kind == "unknown"){ - if (where.size() != 1){ - throw ParseException("Unknown story position has extra fields."); - } - return result; + result.tiles = read_tiles(root.get_value_throw("tiles"), source); + if (const JsonValue* field = root.get_value("facing")){ + result.facing = read_enum(DIRECTIONS, field->to_string_throw(), source); } - if (kind != "tiles"){ - throw ParseException("Unsupported story position kind."); - } - std::vector tiles; - for (const JsonValue& item : where.get_array_throw("tiles")){ - const JsonArray& pair = item.to_array_throw(std::string(source)); - if (pair.size() != 2){ - throw ParseException("Story tile needs two coordinates."); - } - tiles.push_back({integer(pair[0], source), integer(pair[1], source)}); - } - std::optional facing; - if (const JsonValue* field = where.get_value("facing")){ - facing = read_enum(DIRECTIONS, field->to_string_throw(), source); - } - result.where = std::make_shared(std::move(tiles), facing); return result; } @@ -242,45 +311,27 @@ JsonValue story_step_json(const StoryStep& step){ if (!step.why.empty()){ result["why"] = step.why; } - if (step.target){ - result["target"] = story_pose_json(*step.target); - } - if (step.direction != Direction::NORTH){ - result["direction"] = enum_name(DIRECTIONS, step.direction); + if (!step.action.empty()){ + result["action"] = step.action; } - if (!step.legs.empty()){ - result["legs"] = legs_json(step.legs); - } - if (step.fight_wild){ - result["fight_wild"] = true; - } - if (!step.yes){ - result["yes"] = false; - } - if (step.may_lose){ - result["may_lose"] = true; - } - if (step.battles){ - result["battles"] = count_json(step.battles); - } - if (!step.items.empty()){ - result["items"] = items_json(step.items); - } - if (!step.variant.empty()){ - result["variant"] = step.variant; + if (!step.args.empty()){ + JsonObject args; + for (const auto& [key, value] : step.args){ + args[key] = arg_json(value); + } + result["args"] = std::move(args); } if (!step.skip_if.empty()){ result["skip_if"] = strings_json(step.skip_if); } if (step.pose_after){ - result["declared_after"] = story_pose_json(*step.pose_after); + result["declared_after"] = grid_pose_json(*step.pose_after); } return result; } -StoryStep read_story_step(const JsonValue& value, std::string_view source){ - const JsonObject& root = fields(value, {"id", "kind", "why", "target", "direction", "legs", "fight_wild", "yes", - "may_lose", "battles", "items", "variant", "skip_if", "declared_after"}, source); +StoryStep read_story_step(const JsonValue& value, std::string_view source, std::span actions){ + const JsonObject& root = fields(value, {"id", "kind", "why", "action", "args", "skip_if", "declared_after"}, source); StoryStep result; result.name = root.get_string_throw("id"); if (result.name.empty()){ @@ -290,27 +341,15 @@ StoryStep read_story_step(const JsonValue& value, std::string_view source){ if (const JsonValue* field = root.get_value("why")){ result.why = field->to_string_throw(); } - if (const JsonValue* field = root.get_value("target")){ - result.target = read_story_pose(*field, source); - } - if (const JsonValue* field = root.get_value("direction")){ - result.direction = read_enum(DIRECTIONS, field->to_string_throw(), source); - } - if (const JsonValue* field = root.get_value("legs")){ - result.legs = read_legs(*field, source); - } - result = read_step_options(std::move(result), root, source); - if (const JsonValue* field = root.get_value("items")){ - result.items = read_items(*field, source); - } - if (const JsonValue* field = root.get_value("variant")){ - result.variant = field->to_string_throw(); + if (const JsonValue* field = root.get_value("action")){ + result.action = field->to_string_throw(); } + result.args = read_args(root.get_value("args"), step_action(result, actions, source), result, source); if (const JsonValue* field = root.get_value("skip_if")){ result.skip_if = read_strings(*field, source); } if (const JsonValue* field = root.get_value("declared_after")){ - result.pose_after = read_story_pose(*field, source); + result.pose_after = read_grid_pose(*field, source); } return result; } @@ -320,7 +359,7 @@ JsonValue story_checkpoint_json(const StoryCheckpoint& checkpoint){ result["id"] = checkpoint.id; result["title"] = checkpoint.title; if (checkpoint.start){ - result["start"] = story_pose_json(*checkpoint.start); + result["start"] = grid_pose_json(*checkpoint.start); } JsonArray events; for (const StoryStep& step : checkpoint.steps){ @@ -330,7 +369,7 @@ JsonValue story_checkpoint_json(const StoryCheckpoint& checkpoint){ return result; } -StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view source){ +StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view source, std::span actions){ const JsonObject& root = fields(value, {"id", "title", "start", "events"}, source); StoryCheckpoint result; result.id = root.get_string_throw("id"); @@ -339,11 +378,11 @@ StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view s } result.title = root.get_string_throw("title"); if (const JsonValue* start = root.get_value("start")){ - result.start = read_story_pose(*start, source); + result.start = read_grid_pose(*start, source); } std::set names; for (const JsonValue& event : root.get_array_throw("events")){ - StoryStep step = read_story_step(event, source); + StoryStep step = read_story_step(event, source, actions); if (step.name.empty() || !names.insert(step.name).second){ throw ParseException("Empty or duplicate story event id."); } @@ -351,5 +390,8 @@ StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view s } return result; } + + + } // namespace Pokemon } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h new file mode 100644 index 0000000000..f45f8dd77f --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h @@ -0,0 +1,59 @@ +/* Story Step JSON + * + * From: https://github.com/PokemonAutomation/ + * + * The shared JSON wire form of the story data types (Types/): poses, + * steps and checkpoints, read strictly and written losslessly. This is + * the only layer that reads story JSON: a step comes out with its args + * typed and checked, and nothing after it parses. + * + */ + +#ifndef PokemonAutomation_StoryStepJson_H +#define PokemonAutomation_StoryStepJson_H + +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A grid pose: {"map": "PalletTown", "tiles": [[3, 4]], "facing": "north"}. +JsonValue grid_pose_json(const GridPose& pose); + +// Read a grid pose; malformed and unknown fields fail. +GridPose read_grid_pose(const JsonValue& value, std::string_view source); + + +// Encode a step: its kind, action and args. This does not run it. +JsonValue story_step_json(const StoryStep& step); + +// Read a step, its args parsed against its action among `actions` (by +// default the built-in ones; a game passes them with its own) and their +// fallbacks filled in. Unknown fields, kinds, actions and args, mistyped +// values and missing required args fail. +StoryStep read_story_step( + const JsonValue& value, std::string_view source, + std::span actions = builtin_story_actions() +); + + +// Encode the common checkpoint; game adapters supply the shared policy/state envelope. +JsonValue story_checkpoint_json(const StoryCheckpoint& checkpoint); + +// Read the common checkpoint, its steps read as read_story_step() does. +StoryCheckpoint read_story_checkpoint( + const JsonValue& value, std::string_view source, + std::span actions = builtin_story_actions() +); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp new file mode 100644 index 0000000000..2b885a66a0 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp @@ -0,0 +1,238 @@ +/* Story Step JSON Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Each case reads a record from JSON and writes it back: the canonical + * form, or a rejection. Built standalone (PA_STORY_DATA_STANDALONE), it + * also checks the shared case file the Python reader checks. + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Pokemon_StoryStepJson.h" +#ifndef PA_STORY_DATA_STANDALONE +#include "Pokemon/AutoStory/Pokemon_AutoStory_Tests.h" +#endif + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// Which record a case reads. +enum class Record{ + POSE, + STEP, + CHECKPOINT, +}; + +// A record to read, and which kind it is. +struct WireInput{ + std::string_view name; + Record record = Record::STEP; + std::string_view json; +}; + +// What reading it gives: the canonical record, or a rejection. +struct WireExpectation{ + std::string_view canonical = {}; + bool rejected = false; +}; + +struct WireCase{ + WireInput input; + WireExpectation expectation; +}; + +const WireCase CASES[] = { + {.input = {.name = "no args", .json = R"({"id":"talk","kind":"talk"})"}, .expectation = {.canonical = R"({"id":"talk","kind":"talk"})"}}, + {.input = {.name = "all shared fields", .json = R"({"id":"all","kind":"game_action","why":"source reason","action":"profile","skip_if":["flag"],"declared_after":{"map":"B","tiles":[[0,0],[1,0]],"facing":"east"}})"}, .expectation = {.canonical = R"({"id":"all","kind":"game_action","why":"source reason","action":"profile","skip_if":["flag"],"declared_after":{"map":"B","tiles":[[0,0],[1,0]],"facing":"east"}})"}}, + {.input = {.name = "route fills its fallback", .json = R"({"id":"r","kind":"route","args":{"target":{"map":"A","tiles":[[1,2]]}}})"}, .expectation = {.canonical = R"({"id":"r","kind":"route","args":{"fight_wild":false,"target":{"map":"A","tiles":[[1,2]]}}})"}}, + {.input = {.name = "legs", .json = R"({"id":"l","kind":"legs","action":"legs","args":{"legs":[{"direction":"south","tiles":2}],"fight_wild":true}})"}, .expectation = {.canonical = R"({"id":"l","kind":"legs","action":"legs","args":{"fight_wild":true,"legs":[{"direction":"south","tiles":2}]}})"}}, + {.input = {.name = "direction", .json = R"({"id":"s","kind":"step","args":{"direction":"west"}})"}, .expectation = {.canonical = R"({"id":"s","kind":"step","args":{"direction":"west"}})"}}, + {.input = {.name = "items", .json = R"({"id":"s","kind":"shop","args":{"items":[{"item":"potion","quantity":5}]}})"}, .expectation = {.canonical = R"({"id":"s","kind":"shop","args":{"items":[{"item":"potion","quantity":5}]}})"}}, + {.input = {.name = "game args", .json = R"({"id":"buy","kind":"game_action","action":"mart","args":{"map":"CeruleanCity_Mart","budget":3000,"if_present":true}})"}, .expectation = {.canonical = R"({"id":"buy","kind":"game_action","action":"mart","args":{"budget":3000,"if_present":true,"map":"CeruleanCity_Mart"}})"}}, + {.input = {.name = "game words", .json = R"({"id":"buy","kind":"game_action","action":"mart","args":{"map":"M","budget":1,"skip":["a","b"]}})"}, .expectation = {.canonical = R"({"id":"buy","kind":"game_action","action":"mart","args":{"budget":1,"if_present":false,"map":"M","skip":["a","b"]}})"}}, + {.input = {.name = "unknown arg", .json = R"({"id":"a","kind":"game_action","action":"mart","args":{"map":"M","budget":1,"budgte":1}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "missing required arg", .json = R"({"id":"a","kind":"game_action","action":"mart","args":{"map":"M"}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "route without target", .json = R"({"id":"a","kind":"route"})"}, .expectation = {.rejected = true}}, + {.input = {.name = "args on a kind with none", .json = R"({"id":"a","kind":"talk","args":{"yes":true}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "game step without action", .json = R"({"id":"a","kind":"game_action"})"}, .expectation = {.rejected = true}}, + {.input = {.name = "unknown action name", .json = R"({"id":"a","kind":"game_action","action":"dance"})"}, .expectation = {.rejected = true}}, + {.input = {.name = "fractional arg", .json = R"({"id":"a","kind":"game_action","action":"mart","args":{"map":"M","budget":1.5}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "args not an object", .json = R"({"id":"a","kind":"game_action","action":"mart","args":["map"]})"}, .expectation = {.rejected = true}}, + {.input = {.name = "old field", .json = R"({"id":"a","kind":"battle","may_lose":true})"}, .expectation = {.rejected = true}}, + {.input = {.name = "old variant", .json = R"({"id":"a","kind":"game_action","variant":"mart"})"}, .expectation = {.rejected = true}}, + {.input = {.name = "unknown field", .json = R"({"id":"a","kind":"talk","mystery":0})"}, .expectation = {.rejected = true}}, + {.input = {.name = "unknown kind", .json = R"({"id":"a","kind":"magic"})"}, .expectation = {.rejected = true}}, + {.input = {.name = "boolean count", .json = R"({"id":"a","kind":"train","args":{"battles":false}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "wrong bool", .json = R"({"id":"a","kind":"answer","args":{"yes":0}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "unknown facing stays absent", .record = Record::POSE, .json = R"({"map":"M","tiles":[[0,0]]})"}, .expectation = {.canonical = R"({"map":"M","tiles":[[0,0]]})"}}, + {.input = {.name = "no tiles", .record = Record::POSE, .json = R"({"map":"M","tiles":[]})"}, .expectation = {.canonical = R"({"map":"M","tiles":[]})"}}, + {.input = {.name = "old pose", .record = Record::POSE, .json = R"({"map":"M","certainty":"unknown","where":{"kind":"unknown"}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "bad coordinate", .record = Record::POSE, .json = R"({"map":"M","tiles":[[0,true]]})"}, .expectation = {.rejected = true}}, + {.input = {.name = "ordered checkpoint", .record = Record::CHECKPOINT, .json = R"({"id":"00.05","title":"Parcel","events":[{"id":"first","kind":"talk"},{"id":"second","kind":"scene"}]})"}, .expectation = {.canonical = R"({"id":"00.05","title":"Parcel","events":[{"id":"first","kind":"talk"},{"id":"second","kind":"scene"}]})"}}, + {.input = {.name = "duplicate events", .record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[{"id":"a","kind":"talk"},{"id":"a","kind":"talk"}]})"}, .expectation = {.rejected = true}}, +}; + +// The built-in actions and a game's: a Mart step (GAME "mart") and a +// profile check that takes no args. +std::vector test_actions(){ + std::vector actions(builtin_story_actions().begin(), builtin_story_actions().end()); + actions.push_back({.kind = StoryStepKind::GAME, .name = "mart", .args = { + {.key = "map", .type = StoryArgType::WORD, .required = true, .fallback = std::nullopt, .why = "the Mart's map"}, + {.key = "budget", .type = StoryArgType::INTEGER, .required = true, .fallback = std::nullopt, .why = "money to spend"}, + {.key = "if_present", .type = StoryArgType::BOOLEAN, .required = false, .fallback = false, .why = ""}, + {.key = "skip", .type = StoryArgType::WORDS, .required = false, .fallback = std::nullopt, .why = ""}, + }}); + actions.push_back({.kind = StoryStepKind::GAME, .name = "profile", .args = {}}); + return actions; +} + + +// `input` read and written back. +JsonValue round_trip(const WireInput& input){ + static const std::vector actions = test_actions(); + const JsonValue value = parse_json(std::string(input.json)); + switch (input.record){ + case Record::POSE: + return grid_pose_json(read_grid_pose(value, input.name)); + case Record::STEP: + return story_step_json(read_story_step(value, input.name, actions)); + case Record::CHECKPOINT: + return story_checkpoint_json(read_story_checkpoint(value, input.name, actions)); + } + throw ParseException("Unknown test record."); +} + +// "" when `test` reads as expected, else what was expected and what was read. +std::string check_case(const WireCase& test){ + try{ + const JsonValue actual = round_trip(test.input); + if (test.expectation.rejected){ + return "Expected rejection, read accepted record."; + } + const JsonValue expected = parse_json(std::string(test.expectation.canonical)); + if (!(actual == expected)){ + return "Expected " + expected.dump() + ", read " + actual.dump(); + } + }catch (const ParseException& error){ + return test.expectation.rejected ? "" : "Unexpected parse failure: " + error.message(); + } + return ""; +} + + +#ifdef PA_STORY_DATA_STANDALONE + +// A shared case file's record kind. +Record record_kind(std::string_view name){ + if (name == "pose"){ + return Record::POSE; + } + if (name == "step"){ + return Record::STEP; + } + if (name == "checkpoint"){ + return Record::CHECKPOINT; + } + throw ParseException("Unsupported shared case record kind."); +} + +// Checks every case of the shared file `filename`; nonzero if any failed. +int check_shared_file(const std::string& filename){ + const JsonValue document = load_json_file(filename); + const JsonObject& root = document.to_object_throw(filename); + if (root.get_string_throw("format") != "pokesim-story-wire-cases/1"){ + throw ParseException("Unsupported story wire case format."); + } + int failed = 0; + for (const JsonValue& value : root.get_array_throw("cases")){ + const JsonObject& row = value.to_object_throw(filename); + const JsonObject& input = row.get_object_throw("input"); + const JsonObject& expected = row.get_object_throw("expectation"); + const std::string source = input.get_value_throw("value").dump(); + const JsonValue* normalized = expected.get_value("canonical"); + const std::string canonical = normalized ? normalized->dump() : ""; + const JsonValue* rejected = expected.get_value("rejected"); + const WireCase test{ + .input = {.name = input.get_string_throw("name"), .record = record_kind(input.get_string_throw("record")), .json = source}, + .expectation = {.canonical = canonical, .rejected = rejected && rejected->to_boolean_throw()}, + }; + const std::string error = check_case(test); + if (!error.empty()){ + std::cerr << test.input.name << ": " << error << '\n'; + failed++; + } + } + std::cout << "Checked " << root.get_array_throw("cases").size() << " shared story records.\n"; + return failed != 0; +} + +#endif + + +#ifndef PA_STORY_DATA_STANDALONE + +class StoryJsonTest : public UnitTest{ +public: + explicit StoryJsonTest(WireCase test) + : UnitTest("Pokemon::StoryStepJson - " + std::string(test.input.name)) + , m_case(test) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string error = check_case(m_case); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } + +private: + WireCase m_case; +}; + +#endif + + +} // namespace + + +#ifndef PA_STORY_DATA_STANDALONE + +void add_tests_StoryStepJson(UnitTestDatabase& database){ + for (const WireCase& test : CASES){ + database.add(test); + } +} + +#endif + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +#ifdef PA_STORY_DATA_STANDALONE + +int main(int argc, char** argv){ + if (argc == 2){ + return PokemonAutomation::Pokemon::check_shared_file(argv[1]); + } + int failed = 0; + for (const auto& test : PokemonAutomation::Pokemon::CASES){ + const std::string error = PokemonAutomation::Pokemon::check_case(test); + std::cout << test.input.name << ": " << (error.empty() ? "PASS" : error) << '\n'; + failed += !error.empty(); + } + return failed != 0; +} + +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.h deleted file mode 100644 index 1b1be213dd..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.h +++ /dev/null @@ -1,53 +0,0 @@ -/* Shared Authored Checkpoint JSON - * From: https://github.com/PokemonAutomation/ - */ - -#ifndef PokemonAutomation_AuthoredCheckpointJson_H -#define PokemonAutomation_AuthoredCheckpointJson_H - -#include -#include -#include -#include -#include -#include "Common/Cpp/Json/JsonObject.h" -#include "Pokemon_StorySteps.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -// Common story data and an owned execution object for the game adapter to validate. -// Parsing this document does not validate game policies or bind/execute actions. -struct AuthoredCheckpoint{ - StoryCheckpoint checkpoint; - JsonObject execution; -}; - -// Require exactly these fields, including fields whose value is null/zero/false. -// Missing/unknown fields throw ParseException with the document source. -void require_story_json_fields( - const JsonObject& object, std::initializer_list fields, std::string_view source -); - -// Read the strict authored envelope and common checkpoint for expected_game. -// The game adapter must still validate execution fields and values before use. -AuthoredCheckpoint read_authored_checkpoint( - const JsonValue& value, std::string_view expected_game, std::string_view source -); - -// Encode the authored envelope; execution is supplied by the game adapter. -// This does not encode game bookkeeping or the legacy native-export envelope. -JsonValue authored_checkpoint_json(const StoryCheckpoint& checkpoint, std::string_view game, JsonObject execution); - -// Find and parse an embedded (filename without .json, text) resource for this game. -// Missing resources throw InternalProgramError; malformed documents throw ParseException. -AuthoredCheckpoint load_authored_checkpoint( - std::span> files, std::string_view file, std::string_view expected_game -); - - -} // namespace Pokemon -} // namespace PokemonAutomation - -#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryFailureCapture_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryFailureCapture_Tests.cpp index 5f11f3e523..6d538e825d 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryFailureCapture_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryFailureCapture_Tests.cpp @@ -8,6 +8,7 @@ */ #include +#include #include #include "Common/Cpp/Json/JsonArray.h" #include "Common/Cpp/Json/JsonValue.h" @@ -69,10 +70,10 @@ UnitTestResult test_step_of_status(){ if (step.checkpoint != "00.03" || step.event != "below_oaks_trigger"){ return "Expected 00.03 below_oaks_trigger, got \"" + step.checkpoint + "\" \"" + step.event + "\""; } - for (const char* line : {"00: start, 3 checkpoints", "00.02: passed on attempt 1 (one-shot)", "", "a/b"}){ + for (std::string_view line : {"00: start, 3 checkpoints", "00.02: passed on attempt 1 (one-shot)", "", "a/b"}){ step = step_of_status(line); if (!step.checkpoint.empty() || !step.event.empty()){ - return std::string("Expected no step in \"") + line + "\""; + return "Expected no step in \"" + std::string(line) + "\""; } } return true; @@ -84,7 +85,7 @@ struct FailureCaptureInput{ }; struct FailureCaptureExpectation{ - const char* description; + std::string_view description; }; struct FailureCaptureTestCase{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 41b82680c3..85bb5eee87 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -10,38 +10,38 @@ #define PokemonAutomation_Pokemon_AutoStory_Tests_H #include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon_ScreenStory_Tests.h" namespace PokemonAutomation{ namespace Pokemon{ -// Registers unit tests for the shared screen events and the judgements over them. -void add_tests_ScreenEvents(UnitTestDatabase& database); -// The timed screen-event log, the warp judge and the interrupt classifier. -void add_tests_Interrupts(UnitTestDatabase& database); -// The transition tracker and the games' fade profiles. -void add_tests_Transitions(UnitTestDatabase& database); -// Story action tables, the variant parser and the table executor. -void add_tests_StoryActions(UnitTestDatabase& database); -// The table executor's looks for interrupts between steps. -void add_tests_StoryInterrupts(UnitTestDatabase& database); // Registers unit tests for story event sequencing and execution. void add_tests_StoryEvents(UnitTestDatabase& database); // Registers unit tests for story segment running, verification, and branching. void add_tests_StorySegments(UnitTestDatabase& database); // Registers unit tests for high-level story step dispatching and table conversion. -void add_tests_StorySteps(UnitTestDatabase& database); +void add_tests_StoryStepExecutor(UnitTestDatabase& database); // The failure capture's folder names, its JSON and the step a status line // names. Registered by add_tests_StorySegments(). void add_tests_AutoStoryFailureCapture(UnitTestDatabase& database); +// Registers unit tests for the lossless shared story-data wire contract. +void add_tests_StoryStepJson(UnitTestDatabase& database); +// Registers unit tests for step args: checking them against an action's spec. +void add_tests_StoryActionArg(UnitTestDatabase& database); +// Registers unit tests for the shared authored envelope, game identity and embedded-resource loading. +void add_tests_AuthoredCheckpointJson(UnitTestDatabase& database); +// Registers the story engine's suites above (StoryEvents and StorySegments are +// registered on their own), for the unit test runner. +inline void add_tests_AutoStory(UnitTestDatabase& database){ + add_tests_StoryStepExecutor(database); + add_tests_StoryStepJson(database); + add_tests_StoryActionArg(database); + add_tests_AuthoredCheckpointJson(database); +} -// Lossless shared story-data wire contract. -void add_tests_StoryStepJson(UnitTestDatabase& database); - -// Shared authored envelope, game identity and embedded-resource loading. -void add_tests_AuthoredCheckpointJson(UnitTestDatabase& database); } // namespace Pokemon } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.cpp new file mode 100644 index 0000000000..898504d384 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.cpp @@ -0,0 +1,79 @@ +/* Builtin Story Actions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon_BuiltinStoryActions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +StoryArgSpec required(std::string key, StoryArgType type, std::string why){ + return StoryArgSpec{.key = std::move(key), .type = type, .required = true, .fallback = std::nullopt, .why = std::move(why)}; +} + +StoryArgSpec optional(std::string key, StoryArgType type, StoryArgValue fallback, std::string why){ + return StoryArgSpec{.key = std::move(key), .type = type, .required = false, .fallback = std::move(fallback), .why = std::move(why)}; +} + +std::vector make_builtin_actions(){ + const StoryArgSpec fight_wild = optional("fight_wild", StoryArgType::BOOLEAN, false, "fight wild battles on the way instead of running"); + return { + {.kind = StoryStepKind::ROUTE, .name = "route", .args = { + required("target", StoryArgType::GRID_POSE, "where to go; with several tiles, any of them"), + fight_wild, + }}, + {.kind = StoryStepKind::READY, .name = "ready", .args = { + required("target", StoryArgType::GRID_POSE, "the nurse"), + }}, + {.kind = StoryStepKind::LEGS, .name = "legs", .args = { + required("legs", StoryArgType::LEGS, "the straight legs to walk"), + fight_wild, + }}, + {.kind = StoryStepKind::STEP, .name = "face", .args = { + required("direction", StoryArgType::DIRECTION, "the way to step or face"), + }}, + {.kind = StoryStepKind::ANSWER, .name = "answer", .args = { + optional("yes", StoryArgType::BOOLEAN, true, "the answer"), + }}, + {.kind = StoryStepKind::BATTLE, .name = "fight", .args = { + optional("may_lose", StoryArgType::BOOLEAN, false, "losing goes on (a rival's first battle)"), + }}, + {.kind = StoryStepKind::TRAIN, .name = "train", .args = { + required("battles", StoryArgType::INTEGER, "the battles to fight"), + }}, + {.kind = StoryStepKind::SHOP, .name = "shop", .args = { + required("items", StoryArgType::ITEMS, "the items and how many of each"), + }}, + }; +} + + +} // namespace + + +std::span builtin_story_actions(){ + static const std::vector actions = make_builtin_actions(); + return actions; +} + +const StoryActionSpec* find_story_action(std::span actions, StoryStepKind kind, std::string_view name){ + for (const StoryActionSpec& action : actions){ + if (action.kind == kind && (name.empty() || action.name == name)){ + return &action; + } + } + return nullptr; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h new file mode 100644 index 0000000000..46b2d989e6 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h @@ -0,0 +1,65 @@ +/* Builtin Story Actions + * + * From: https://github.com/PokemonAutomation/ + * + * The shared engine's built-in actions (a route, fixed legs, a battle, a + * shop...) with the args each takes, and reading a step's args. A game + * adds its own actions (GAME steps and its other ways of doing a kind) to + * these when it loads its tables. + * + */ + +#ifndef PokemonAutomation_Pokemon_BuiltinStoryActions_H +#define PokemonAutomation_Pokemon_BuiltinStoryActions_H + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_MapUtil.h" +#include "Types/Pokemon_StoryActionArg.h" +#include "Types/Pokemon_StoryActionSpec.h" +#include "Types/Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The built-in actions: each kind's usual way. A kind's first one is its +// default, the action of a step that names none. +// route ROUTE target GRID_POSE (required), fight_wild BOOLEAN (false) +// ready READY target GRID_POSE (required): the nurse +// legs LEGS legs LEGS (required), fight_wild BOOLEAN (false) +// face STEP direction DIRECTION (required) +// answer ANSWER yes BOOLEAN (true) +// fight BATTLE may_lose BOOLEAN (false) +// train TRAIN battles INTEGER (required) +// shop SHOP items ITEMS (required) +// Other kinds (TALK, MASH, HEAL, SAVE, ...) take no args. +std::span builtin_story_actions(); + +// The action of `kind` named `name` among `actions`; for an empty name, +// the kind's first. Null when there is none. +const StoryActionSpec* find_story_action(std::span actions, StoryStepKind kind, std::string_view name); + +// The value of arg `key`, which the step's action requires or gives a +// fallback, so the loaded step has it. Throws InternalProgramError when it +// is missing or of another type: a step built without its action's spec. +template +const Type& story_arg(const StoryActionArgs& args, std::string_view key); + + +template +const Type& story_arg(const StoryActionArgs& args, std::string_view key){ + const Type* value = value_if_at_it(args, args.find(key)); + if (value == nullptr){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Missing or mistyped story arg: " + std::string(key)); + } + return *value; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h new file mode 100644 index 0000000000..a4dd2ac915 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h @@ -0,0 +1,94 @@ +/* Fade Profiles + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_Transitions.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_FadeProfiles_H +#define PokemonAutomation_Pokemon_FadeProfiles_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Whether the screen differs after a transition from before it. The +// tracker has only frame statistics; the caller compares the frames, or +// says it did not. +enum class SceneChange{ + UNKNOWN, + SAME, + DIFFERENT, +}; + + +// A game's fades, as data. Two tiers of the same test: a frame is uniform +// (the fade's hold) when its middle's stddev sum is at most +// `uniform_max_stddev_sum`, and partial (on the way down or up) when it is +// at most `partial_max_stddev_sum`. Either way it is dark or white by its +// rgb sum. +struct FadeProfile{ + double uniform_max_stddev_sum = 10; + double partial_max_stddev_sum = 60; + // Dark at or below this rgb sum; a partial frame up to `partial_dark_max_sum`. + double dark_max_sum = 225; + double partial_dark_max_sum = 300; + // White at or above this rgb sum; a partial frame from `partial_white_min_sum`. + double white_min_sum = 500; + double partial_white_min_sum = 450; + + // Partial frames for longer than this, with no hold, are the scene's + // own look (a dim cave floor, a street at night), not a fade. + Milliseconds max_fall = Milliseconds(1000); + // A transition still dark or white after this has timed out: the + // screen did not come back. + Milliseconds max_hold = Milliseconds(8000); + + // Whether the game fades to white between maps (BDSP's cave exits). + // Without, every white is an encounter's flash. + bool has_white_fade = true; + // A white held this long or less, back on the same scene, is a flash. + Milliseconds flash_max_hold = Milliseconds(150); + // A white held this long or more, not back on the same scene, is a + // white fade. Between the two the white is unsure. + Milliseconds white_fade_min_hold = Milliseconds(400); +}; + +// BDSP. The uniform tier is the shared walk's (FADE_MAX_STDDEV_SUM, the +// Oreburgh Gate's textured floor is no fade, lab-B 2026-11-08); the partial +// tier is run_into_door()'s 60, which caught the doorway's dim fade frames. +// A cave mouth's fade is dim (45 to 64 a channel), hence the dark sum of 225. +// The flash and white-fade holds are provisional: no console frames of an +// encounter flash and a cave exit have been timed side by side yet, so the +// band between them is wide and reports WHITE_UNSURE. +extern const FadeProfile BDSP_FADE_PROFILE; +// FRLG. The GBA fades to true black, so the dark tiers are the shared +// BlackScreenDetector's 100 and a little above; it has no white fade between +// maps, so every white is an encounter's flash. +extern const FadeProfile FRLG_FADE_PROFILE; + + +// What a transition was. +enum class TransitionKind : uint8_t{ + FADE_BLACK, // A door, a cave mouth, a scene cut, a battle's own fade. + FADE_WHITE, // A cave exit: a long white onto another scene. + FLASH, // An encounter's flash: a short white, back on the scene. + WHITE_UNSURE, // A white that may be either: wait for a battle. +}; +// "black fade", for the log. +std::string transition_kind_name(TransitionKind kind); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h new file mode 100644 index 0000000000..c63b14124c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h @@ -0,0 +1,95 @@ +/* Interrupt Handlers + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_StoryInterrupts.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_InterruptHandlers_H +#define PokemonAutomation_Pokemon_InterruptHandlers_H + +#include +#include +#include +#include +#include +#include +#include "Pokemon_Interrupts.h" +#include "Pokemon_ScreenEvents.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_StoryStepExecutor.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What a game saw of the screen between two steps: its timed events, and +// the span of them the classifier judges. +struct ScreenLook{ + ScreenEventLog log{}; + InterruptWindow window = {}; +}; + +// Looks at the screen. `fresh` starts a new look; otherwise the look goes +// on from the last one, to see how an unsettled screen ends. +using ScreenLookFunction = std::function; + +// Clears an interrupt a look found: flees or fights the battle, closes +// the dialog, waits out the warp. +using InterruptAction = std::function; + +// A row of an InterruptHandlerTable. +struct InterruptHandler{ + InterruptAction handle = {}; + // What clearing it did to where the player is. + InterruptPose pose = InterruptPose::UNCHANGED; +}; + + +// A game's handlers by kind of interrupt, and the steps that start on one. +class InterruptHandlerTable{ +public: + // The handler for `kind`: one of WILD_ENCOUNTER, TRAINER_SIGHT, + // DIALOG or WARP. Another kind, or a second handler for one, throws + // InternalProgramError. + void add(InterruptKind kind, InterruptHandler handler); + // The handler for `kind`; nullptr if there is none. + const InterruptHandler* find(InterruptKind kind) const; + + // Steps of `step` start on `kind` showing: before one, it is the + // step's to clear, not an interrupt. A step that starts on + // WILD_ENCOUNTER or TRAINER_SIGHT starts on UNSETTLED too. + void starts_on(StoryStepKind step, InterruptKind kind); + bool step_starts_on(StoryStepKind step, InterruptKind kind) const; + +private: + std::map m_handlers; + std::set> m_starts_on; +}; + + +// A game's interrupts between steps: how it looks, how it judges what it +// saw, and what it does about each kind. +struct StoryInterrupts{ + ScreenLookFunction look = {}; + InterruptKnobs knobs = {}; + InterruptHandlerTable handlers = {}; + // Looks at a screen that stays UNSETTLED (a fade with no battle yet) + // before it fails the step as "interrupt_unsettled". A step that + // starts on it gets it on the first look. + size_t max_looks = 3; + // The same, for a screen that may be a battle's opening: enough looks + // for its battle to show. BDSP's 300 ms looks cover 12 s, past its + // battle_after_fade (8 s), after which a fade with no battle settles. + size_t max_opening_looks = 40; + // Interrupts cleared for one step before it fails as + // "too_many_interrupts". + size_t max_per_step = 3; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp index e93ce9f5c9..ebee346629 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp @@ -12,7 +12,7 @@ namespace PokemonAutomation{ namespace Pokemon{ -const char* warp_judgement_name(WarpJudgement judgement){ +std::string warp_judgement_name(WarpJudgement judgement){ switch (judgement){ case WarpJudgement::NO_FADE: return "no fade"; case WarpJudgement::FADE_SHOWING: return "fade still showing"; @@ -25,7 +25,7 @@ const char* warp_judgement_name(WarpJudgement judgement){ return "?"; } -const char* interrupt_kind_name(InterruptKind kind){ +std::string interrupt_kind_name(InterruptKind kind){ switch (kind){ case InterruptKind::NONE: return "none"; case InterruptKind::WILD_ENCOUNTER: return "wild encounter"; @@ -222,7 +222,7 @@ WarpVerdict judge_warp(const Transition& transition, const InterruptKnobs& knobs std::string describe(const InterruptVerdict& verdict, WallClock origin){ std::string out = interrupt_kind_name(verdict.kind); - const char* separator = ": "; + std::string_view separator = ": "; for (const ScreenEventChange& change : verdict.evidence){ out += std::format( "{}{:+} ms {} {}", diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.h index 52d23c811c..b7637ad044 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.h @@ -24,80 +24,12 @@ #include "Common/Cpp/Time.h" #include "Pokemon_ScreenEvents.h" #include "Pokemon_Transitions.h" +#include "Pokemon_WarpJudge.h" namespace PokemonAutomation{ namespace Pokemon{ -// A game's timing, as data. -struct InterruptKnobs{ - // A fade must hold this long to be a warp's. One uniform frame is enough - // by default: a 50 ms fade can show on one frame only. - Milliseconds min_fade_hold = Milliseconds(0); - // A battle that shows this soon after a fade ends is that fade's - // encounter, and a fade is no warp before this has passed with no - // battle. BDSP's encounter flash shows its battle within 8 s - // (WHITE_FLASH_BATTLE_WAIT in its walk). - Milliseconds battle_after_fade = Milliseconds(8000); - // A dialog box that rose this long or less before a battle's fade is a - // trainer's lines. A trainer's lines can pause more than 4 s before the - // battle (BDSP r210d), and a trainer may say several boxes. - Milliseconds sight_lines_lead = Milliseconds(20000); -}; - -// The span of the log to judge: changes at `start` or later, and no later -// than `end`. -struct InterruptWindow{ - WallClock start = {}; - WallClock end = {}; -}; - - -// How a fade looked, for the warp judge. -struct FadeSpan{ - WarpFade fade = WarpFade::NONE; - WallClock down = {}; - // When the screen came back; none while it still shows the fade. - std::optional up = {}; -}; - -// What the warp judge made of a fade. -enum class WarpJudgement{ - NO_FADE, // No fade went down in the window. - FADE_SHOWING, // It went down and has not come back up. - TOO_SHORT, // It came back up before min_fade_hold. - SAME_SCENE, // It came back up on the scene it left. - WARPED, // Down, held, back up; not on the same scene. - FLASH, // An encounter's flash (a tracked transition only). - WHITE_UNSURE, // A white that may be a flash or a cave exit (a - // tracked transition only): wait for a battle. -}; -// "fade too short", for the log. -const char* warp_judgement_name(WarpJudgement judgement); - -// The warp judge's verdict and the fade it judged. -struct WarpVerdict{ - WarpJudgement judgement = WarpJudgement::NO_FADE; - // The last fade that went down in the window, if any. - std::optional fade = {}; -}; - -// A warp is a fade going down, holding uniform, and coming back up on -// another scene. The last fade that went down in `window` is judged; a -// LOCATION_BANNER does not count here (WarpSeen does). `change` is what -// the caller saw of the scene before and after: UNKNOWN does not rule the -// warp out. This judges the fade only: a battle after it is -// classify_interrupt()'s question. -WarpVerdict judge_warp( - const ScreenEventLog& log, InterruptWindow window, - const InterruptKnobs& knobs, SceneChange change -); -// The same judge over a TransitionTracker's transition, which has its own -// scene comparison. A transition whose hold went unseen onto another scene -// is a warp whatever min_fade_hold says: the scene change is the evidence. -WarpVerdict judge_warp(const Transition& transition, const InterruptKnobs& knobs); - - // What stopped the player. enum class InterruptKind{ NONE, @@ -108,7 +40,7 @@ enum class InterruptKind{ UNSETTLED, // A fade, too recent to know if a battle follows. }; // "trainer sight", for the log. -const char* interrupt_kind_name(InterruptKind kind); +std::string interrupt_kind_name(InterruptKind kind); // What stopped the player, and the evidence for it. struct InterruptVerdict{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp index aecc5cbbd8..37f03590a0 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp @@ -124,7 +124,7 @@ UnitTestResult test_empty_log(){ UnitTestResult test_judge_warp(){ struct Row{ - const char* name; + std::string name; std::vector frames; SceneChange change; WarpJudgement expected; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_MapUtil.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_MapUtil.h new file mode 100644 index 0000000000..f9be88108b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_MapUtil.h @@ -0,0 +1,44 @@ +/* Map Util + * + * From: https://github.com/PokemonAutomation/ + * + * Lookups in a map through the iterator find() returned, so a call site + * says which lookup it does and never copies the value by accident: + * const int64_t* budget = value_if_at_it(args, args.find("budget")); + * + */ + +#ifndef PokemonAutomation_Pokemon_MapUtil_H +#define PokemonAutomation_Pokemon_MapUtil_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The value at `it`, or null when `it` is `map`'s end. +template +const typename Map::mapped_type* value_at_it(const Map& map, typename Map::const_iterator it); + +// The `Type` alternative of the variant at `it`, or null when `it` is +// `map`'s end or the variant holds another type. +template +const Type* value_if_at_it(const Map& map, typename Map::const_iterator it); + + +template +const typename Map::mapped_type* value_at_it(const Map& map, typename Map::const_iterator it){ + return it == map.end() ? nullptr : &it->second; +} + +template +const Type* value_if_at_it(const Map& map, typename Map::const_iterator it){ + return it == map.end() ? nullptr : std::get_if(&it->second); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp index 628be668dc..b92a63e2a9 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp @@ -38,12 +38,17 @@ SceneMove TalkOver::look(const ScreenEvents& look, WallClock now){ m_calm_since = WallClock::max(); return SceneMove::BATTLE; } - if (fade_in(look) != WarpFade::NONE){ - m_fade = fade_in(look); + m_fade_showing = fade_in(look); + if (m_fade_showing != WarpFade::NONE){ + m_fade = m_fade_showing; } m_banner |= look.has(ScreenEvent::LOCATION_BANNER); const bool box = look.has(ScreenEvent::DIALOG_BOX); - const bool calm = !box && look.has(ScreenEvent::PLAYER_CAN_MOVE) && warped(); + // A fade is never calm: BDSP's overworld reads a black frame as no + // box, and black stays still, so a closing fade counted as quiet and + // ended Mom's scene as it went down (lab-B 2026-11-09 14:33). + const bool calm = !box && m_fade_showing == WarpFade::NONE && + look.has(ScreenEvent::PLAYER_CAN_MOVE) && warped(); const bool quiet = calm && look.has(ScreenEvent::SCREEN_STILL); if (!calm){ m_calm_since = WallClock::max(); @@ -73,6 +78,9 @@ std::string TalkOver::describe() const{ return "no fade or banner"; } std::string out = m_fade == WarpFade::NONE ? "" : warp_fade_name(m_fade); + if (m_fade != WarpFade::NONE){ + out += m_fade_showing == WarpFade::NONE ? " back up" : " still down"; + } if (m_banner){ out += out.empty() ? "banner read" : ", banner read"; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h index 704ecf9a86..908dcaa39c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h @@ -71,6 +71,9 @@ constexpr Milliseconds TALK_OVER_CALM = Milliseconds(15000); // When a talk or a scene is over, from looks alone. A look is a frame's // events: DIALOG_BOX, PLAYER_CAN_MOVE, SCREEN_STILL, a fade, // LOCATION_BANNER (the expected map's) and BATTLE_STARTED are read. +// It is over only once every fade has come back up, no box shows, and +// the overworld has been quiet (or calm) since: a look that shows a fade +// starts the quiet over, however still it is. class TalkOver{ public: explicit TalkOver(TalkOverRule rule = {}) @@ -86,7 +89,9 @@ class TalkOver{ private: TalkOverRule m_rule; + // The first fade seen, and the one the last look showed. WarpFade m_fade = WarpFade::NONE; + WarpFade m_fade_showing = WarpFade::NONE; bool m_banner = false; WallClock m_quiet_since = WallClock::max(); WallClock m_calm_since = WallClock::max(); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEventLog.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEventLog.h new file mode 100644 index 0000000000..62f34e2f6b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEventLog.h @@ -0,0 +1,100 @@ +/* Screen Event Log + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_ScreenEvents.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_ScreenEventLog_H +#define PokemonAutomation_Pokemon_ScreenEventLog_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Concurrency/Mutex.h" +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" +#include "Pokemon_ScreenFades.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Whether an event started or stopped showing. +enum class ScreenEventEdge : uint8_t{ + ROSE, + FELL, +}; + +// One event starting or stopping to show, at the frame that showed it. +struct ScreenEventChange{ + WallClock time; + ScreenEvent event; + ScreenEventEdge edge; + + bool operator==(const ScreenEventChange& other) const = default; +}; + +// How many changes a log keeps. A walk's events change a few times a +// second at most (a fade's black, a box, the screen going still), so this +// is a minute or more of a busy scene. +constexpr size_t SCREEN_EVENT_LOG_CAPACITY = 256; + +// The events of a stream of frames, in order and timed: what rose and fell +// when, not only what was seen (ScreenEventWatcher::seen()). The judges that +// care about order read it (Pokemon_Interrupts.h): a flash then a battle is +// an encounter, a box then a battle a trainer's sight. +// +// It keeps the newest `capacity` changes and counts the ones it dropped. +// Not thread-safe; ScreenEventWatcher guards its own. +class ScreenEventLog{ +public: + explicit ScreenEventLog(size_t capacity = SCREEN_EVENT_LOG_CAPACITY); + + // Adds a frame: a change for each event that rose or fell since the + // frame before (the first frame's events all rise). `now` must not go + // back in time. + void record(const ScreenEvents& frame, WallClock now); + + // The changes kept, oldest first. + const std::deque& changes() const{ + return m_changes; + } + // How many changes were dropped, oldest first, to keep the capacity. + size_t dropped() const{ + return m_dropped; + } + // The events of the last frame recorded. + ScreenEvents showing() const{ + return m_showing; + } + // When the last frame was recorded; none before the first. + std::optional last_frame() const{ + return m_last_frame; + } + void clear(); + +private: + size_t m_capacity; + std::deque m_changes; + size_t m_dropped = 0; + ScreenEvents m_showing; + std::optional m_last_frame; +}; +// "+1200 ms dialog box rose", times from `origin`, one change per line. +std::string describe(const ScreenEventLog& log, WallClock origin); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEventTypes.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEventTypes.h new file mode 100644 index 0000000000..45988abc4e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEventTypes.h @@ -0,0 +1,100 @@ +/* Screen Event Types + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_ScreenEvents.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_ScreenEventTypes_H +#define PokemonAutomation_Pokemon_ScreenEventTypes_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Concurrency/Mutex.h" +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// One thing a frame shows. A game reports the ones its detectors can see. +enum class ScreenEvent : uint8_t{ + FADE_BLACK, // A uniform dark screen: a door, a cave mouth, a scene cut. + FADE_WHITE, // A uniform white screen: a cave exit. + LOCATION_BANNER, // A location banner. An observer given an expected + // map reports only that map's. + DIALOG_BOX, // A dialogue box. + CHOICE_BOX, // A choice (Yes/No, a menu of answers). + INTERACT_PROMPT, // A button prompt to interact ("A Talk"). + BATTLE_STARTED, // A battle shows (its menu, its HUD or its opening). + BATTLE_ENDED, // A battle's closing screen. + PLAYER_CAN_MOVE, // The overworld with the player in control. + SCREEN_STILL, // The screen barely changed since the frame before. + SWITCH_HOME_MENU, // The Switch's HOME menu: the game is not on the screen. +}; +// How many ScreenEvent values there are. +constexpr size_t SCREEN_EVENT_COUNT = 11; +// "dialog box", for the log. +std::string screen_event_name(ScreenEvent event); + + +// How a screen's fade looks: the kind of FADE_BLACK / FADE_WHITE. +enum class WarpFade{ + NONE, + BLACK, // a door's black, or a cave mouth's dim fade + WHITE, // a cave exit's white, with no battle after it +}; +// "black fade", for the log. +std::string warp_fade_name(WarpFade fade); + + +// The events of one frame, or of all the frames a watcher saw. +class ScreenEvents{ +public: + ScreenEvents() = default; + ScreenEvents(std::initializer_list events); + + bool has(ScreenEvent event) const{ + return (m_bits & bit(event)) != 0; + } + // Whether any of `events` is in this set. + bool any_of(const ScreenEvents& events) const{ + return (m_bits & events.m_bits) != 0; + } + // Adds `event`, or removes it when `on` is false (as std::bitset::set). + void set(ScreenEvent event, bool on); + void merge(const ScreenEvents& events){ + m_bits |= events.m_bits; + } + + uint32_t bits() const{ + return m_bits; + } + static ScreenEvents from_bits(uint32_t bits); + + bool operator==(const ScreenEvents& other) const = default; + +private: + static uint32_t bit(ScreenEvent event){ + return uint32_t(1) << (uint32_t)event; + } + + uint32_t m_bits = 0; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp index e80ed6161f..db2e5fbfa7 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp @@ -13,7 +13,7 @@ namespace PokemonAutomation{ namespace Pokemon{ -const char* screen_event_name(ScreenEvent event){ +std::string screen_event_name(ScreenEvent event){ switch (event){ case ScreenEvent::FADE_BLACK: return "black fade"; case ScreenEvent::FADE_WHITE: return "white fade"; @@ -25,11 +25,12 @@ const char* screen_event_name(ScreenEvent event){ case ScreenEvent::BATTLE_ENDED: return "battle ended"; case ScreenEvent::PLAYER_CAN_MOVE: return "player can move"; case ScreenEvent::SCREEN_STILL: return "screen still"; + case ScreenEvent::SWITCH_HOME_MENU: return "Switch HOME menu"; } return "?"; } -const char* warp_fade_name(WarpFade fade){ +std::string warp_fade_name(WarpFade fade){ switch (fade){ case WarpFade::NONE: return "no fade"; case WarpFade::BLACK: return "black fade"; @@ -147,6 +148,23 @@ std::string describe(const ScreenEventLog& log, WallClock origin){ } +SwitchHomeObserver::SwitchHomeObserver(NintendoSwitch::ConsoleHandle& console, ScreenEventObserver& game) + : m_game(game) + , m_home(console, COLOR_RED) +{} + +ScreenEvents SwitchHomeObserver::observe(const VideoSnapshot& frame, WallClock now){ + if (frame && m_home.detect_only(*frame.frame)){ + return {ScreenEvent::SWITCH_HOME_MENU}; + } + return m_game.observe(frame, now); +} + +void SwitchHomeObserver::make_overlays(VideoOverlaySet& items) const{ + m_game.make_overlays(items); +} + + ScreenEventWatcher::ScreenEventWatcher(ScreenEventObserver& observer, ScreenEvents stop_on) : VisualInferenceCallback("ScreenEventWatcher") , m_observer(observer) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h index cd633e0f60..ee3080235d 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h @@ -28,164 +28,14 @@ #include "CommonFramework/ImageTypes/ImageViewRGB32.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" #include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" +#include "Pokemon_ScreenEventLog.h" namespace PokemonAutomation{ namespace Pokemon{ -// One thing a frame shows. A game reports the ones its detectors can see. -enum class ScreenEvent : uint8_t{ - FADE_BLACK, // A uniform dark screen: a door, a cave mouth, a scene cut. - FADE_WHITE, // A uniform white screen: a cave exit. - LOCATION_BANNER, // A location banner. An observer given an expected - // map reports only that map's. - DIALOG_BOX, // A dialogue box. - CHOICE_BOX, // A choice (Yes/No, a menu of answers). - INTERACT_PROMPT, // A button prompt to interact ("A Talk"). - BATTLE_STARTED, // A battle shows (its menu, its HUD or its opening). - BATTLE_ENDED, // A battle's closing screen. - PLAYER_CAN_MOVE, // The overworld with the player in control. - SCREEN_STILL, // The screen barely changed since the frame before. -}; -// How many ScreenEvent values there are. -constexpr size_t SCREEN_EVENT_COUNT = 10; -// "dialog box", for the log. -const char* screen_event_name(ScreenEvent event); - - -// How a screen's fade looks: the kind of FADE_BLACK / FADE_WHITE. -enum class WarpFade{ - NONE, - BLACK, // a door's black, or a cave mouth's dim fade - WHITE, // a cave exit's white, with no battle after it -}; -// "black fade", for the log. -const char* warp_fade_name(WarpFade fade); - - -// The events of one frame, or of all the frames a watcher saw. -class ScreenEvents{ -public: - ScreenEvents() = default; - ScreenEvents(std::initializer_list events); - - bool has(ScreenEvent event) const{ - return (m_bits & bit(event)) != 0; - } - // Whether any of `events` is in this set. - bool any_of(const ScreenEvents& events) const{ - return (m_bits & events.m_bits) != 0; - } - // Adds `event`, or removes it when `on` is false (as std::bitset::set). - void set(ScreenEvent event, bool on); - void merge(const ScreenEvents& events){ - m_bits |= events.m_bits; - } - - uint32_t bits() const{ - return m_bits; - } - static ScreenEvents from_bits(uint32_t bits); - - bool operator==(const ScreenEvents& other) const = default; - -private: - static uint32_t bit(ScreenEvent event){ - return uint32_t(1) << (uint32_t)event; - } - - uint32_t m_bits = 0; -}; -// The event of a fade: FADE_BLACK, FADE_WHITE, or none for WarpFade::NONE. -ScreenEvents fade_events(WarpFade fade); -// The fade `events` show: BLACK before WHITE if they have both. -WarpFade fade_in(const ScreenEvents& events); -// "dialog box, player can move"; "nothing" when empty. -std::string describe(const ScreenEvents& events); - - -// A fade is uniform over the middle 80% of the screen, the shared -// Black/WhiteScreenWatcher's stddev test (upstream #1717): a dim cave floor -// is textured, so it is no fade (BDSP's Oreburgh Gate, mean 46, lab-B -// 2026-11-08). Check against the Gate's frames on the console before -// tightening. -constexpr double FADE_MAX_STDDEV_SUM = 10; -// Dark goes to an rgb sum of 225, as a cave mouth's fade is dim, 45 to 64 -// a channel, not black. -constexpr double FADE_MAX_DARK_SUM = 225; -// White from an rgb sum of 500, as the shared WhiteScreenWatcher's. -constexpr double FADE_MIN_WHITE_SUM = 500; -// The fade `middle` (the stats of the screen's middle 80%) shows, if any. -WarpFade fade_of(const ImageStats& middle); -// fade_of() for a screen. -WarpFade fade_of_screen(const ImageViewRGB32& screen); - - -// Whether an event started or stopped showing. -enum class ScreenEventEdge : uint8_t{ - ROSE, - FELL, -}; - -// One event starting or stopping to show, at the frame that showed it. -struct ScreenEventChange{ - WallClock time; - ScreenEvent event; - ScreenEventEdge edge; - - bool operator==(const ScreenEventChange& other) const = default; -}; - -// How many changes a log keeps. A walk's events change a few times a -// second at most (a fade's black, a box, the screen going still), so this -// is a minute or more of a busy scene. -constexpr size_t SCREEN_EVENT_LOG_CAPACITY = 256; - -// The events of a stream of frames, in order and timed: what rose and fell -// when, not only what was seen (ScreenEventWatcher::seen()). The judges that -// care about order read it (Pokemon_Interrupts.h): a flash then a battle is -// an encounter, a box then a battle a trainer's sight. -// -// It keeps the newest `capacity` changes and counts the ones it dropped. -// Not thread-safe; ScreenEventWatcher guards its own. -class ScreenEventLog{ -public: - explicit ScreenEventLog(size_t capacity = SCREEN_EVENT_LOG_CAPACITY); - - // Adds a frame: a change for each event that rose or fell since the - // frame before (the first frame's events all rise). `now` must not go - // back in time. - void record(const ScreenEvents& frame, WallClock now); - - // The changes kept, oldest first. - const std::deque& changes() const{ - return m_changes; - } - // How many changes were dropped, oldest first, to keep the capacity. - size_t dropped() const{ - return m_dropped; - } - // The events of the last frame recorded. - ScreenEvents showing() const{ - return m_showing; - } - // When the last frame was recorded; none before the first. - std::optional last_frame() const{ - return m_last_frame; - } - void clear(); - -private: - size_t m_capacity; - std::deque m_changes; - size_t m_dropped = 0; - ScreenEvents m_showing; - std::optional m_last_frame; -}; -// "+1200 ms dialog box rose", times from `origin`, one change per line. -std::string describe(const ScreenEventLog& log, WallClock origin); - - // A game's detectors, as events. Observers may keep state between frames // (the frame before, for SCREEN_STILL; when a banner was last read, to // gate OCR), so one observer watches one stream at a time. @@ -202,6 +52,23 @@ class ScreenEventObserver{ }; +// A game's observer behind a look at the Switch itself: a frame showing +// the HOME menu shows SWITCH_HOME_MENU and nothing else, as a game's +// detectors may read HOME's plain screen as a quiet overworld (BDSP, +// lab-B 2026-11-09). Every other frame is the game's to read. +class SwitchHomeObserver : public ScreenEventObserver{ +public: + SwitchHomeObserver(NintendoSwitch::ConsoleHandle& console, ScreenEventObserver& game); + + virtual ScreenEvents observe(const VideoSnapshot& frame, WallClock now) override; + virtual void make_overlays(VideoOverlaySet& items) const override; + +private: + ScreenEventObserver& m_game; + NintendoSwitch::HomeMenuDetector m_home; +}; + + // An observer as a run_until callback: it records every event it sees, in // order in a log, and stops the action on any of `stop_on` (none: it only // records). diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp index 2d0db31cfd..ef57a2e747 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp @@ -66,7 +66,7 @@ ImageRGB32 screen_of(uint32_t a, uint32_t b){ UnitTestResult test_fade_of_screen(){ struct Row{ - const char* name; + std::string name; uint32_t a; uint32_t b; WarpFade fade; @@ -115,6 +115,9 @@ int first_beat(TalkOver& judge, const std::vector& beats, SceneMov const ScreenEvents QUIET{ScreenEvent::PLAYER_CAN_MOVE, ScreenEvent::SCREEN_STILL}; const ScreenEvents CALM{ScreenEvent::PLAYER_CAN_MOVE}; const ScreenEvents BOX{ScreenEvent::DIALOG_BOX, ScreenEvent::PLAYER_CAN_MOVE, ScreenEvent::SCREEN_STILL}; +// A black frame as BDSP's eyes see it: no box, so "overworld", and still. +const ScreenEvents FADED{ScreenEvent::FADE_BLACK, ScreenEvent::PLAYER_CAN_MOVE, ScreenEvent::SCREEN_STILL}; +const ScreenEvents CALM_FADED{ScreenEvent::FADE_BLACK, ScreenEvent::PLAYER_CAN_MOVE}; std::vector repeat(const ScreenEvents& look, size_t count){ return std::vector(count, look); @@ -126,7 +129,7 @@ std::vector concat(std::vector a, const std::vector< UnitTestResult test_talk_over(){ struct Row{ - const char* name; + std::string name; TalkOverRule rule; std::vector beats; SceneMove want; @@ -146,6 +149,14 @@ UnitTestResult test_talk_over(){ SceneMove::DONE, 6}, {"no quiet ends a talk before a battle", {.end_on_quiet = false}, repeat(QUIET, 30), SceneMove::DONE, -1}, {"a battle", {.end_on_quiet = false}, concat(repeat(QUIET, 6), {ScreenEvents{ScreenEvent::BATTLE_STARTED}}), SceneMove::BATTLE, 6}, + // Mom's Running Shoes scene (lab-B 2026-11-09 14:33): quiet, then + // the scene's closing fade. It ended at the fade's start and the + // next step's input landed in the fade. + {"a closing fade starts the quiet over", {}, + concat(concat(repeat(QUIET, 4), repeat(FADED, 3)), repeat(QUIET, 8)), + SceneMove::DONE, 12}, + {"a fade still down never ends it", {}, concat(repeat(QUIET, 3), repeat(FADED, 20)), SceneMove::DONE, -1}, + {"a fade is never calm", {}, concat(repeat(CALM, 10), repeat(CALM_FADED, 10)), SceneMove::DONE, -1}, }; for (const Row& row : rows){ TalkOver judge(row.rule); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenFades.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenFades.h new file mode 100644 index 0000000000..57de9f6a3d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenFades.h @@ -0,0 +1,60 @@ +/* Screen Fades + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_ScreenEvents.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_ScreenFades_H +#define PokemonAutomation_Pokemon_ScreenFades_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Concurrency/Mutex.h" +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" +#include "Pokemon_ScreenEventTypes.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The event of a fade: FADE_BLACK, FADE_WHITE, or none for WarpFade::NONE. +ScreenEvents fade_events(WarpFade fade); +// The fade `events` show: BLACK before WHITE if they have both. +WarpFade fade_in(const ScreenEvents& events); +// "dialog box, player can move"; "nothing" when empty. +std::string describe(const ScreenEvents& events); + + +// A fade is uniform over the middle 80% of the screen, the shared +// Black/WhiteScreenWatcher's stddev test (upstream #1717): a dim cave floor +// is textured, so it is no fade (BDSP's Oreburgh Gate, mean 46, lab-B +// 2026-11-08). Check against the Gate's frames on the console before +// tightening. +constexpr double FADE_MAX_STDDEV_SUM = 10; +// Dark goes to an rgb sum of 225, as a cave mouth's fade is dim, 45 to 64 +// a channel, not black. +constexpr double FADE_MAX_DARK_SUM = 225; +// White from an rgb sum of 500, as the shared WhiteScreenWatcher's. +constexpr double FADE_MIN_WHITE_SUM = 500; +// The fade `middle` (the stats of the screen's middle 80%) shows, if any. +WarpFade fade_of(const ImageStats& middle); +// fade_of() for a screen. +WarpFade fade_of_screen(const ImageViewRGB32& screen); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenStory_Tests.h new file mode 100644 index 0000000000..7760c923eb --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenStory_Tests.h @@ -0,0 +1,33 @@ +/* Screen Story Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_AutoStory_Tests.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_ScreenStory_Tests_H +#define PokemonAutomation_Pokemon_ScreenStory_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the shared screen events and the judgements over them. +void add_tests_ScreenEvents(UnitTestDatabase& database); +// The timed screen-event log, the warp judge and the interrupt classifier. +void add_tests_Interrupts(UnitTestDatabase& database); +// The transition tracker and the games' fade profiles. +void add_tests_Transitions(UnitTestDatabase& database); +// Story action tables, the variant parser and the table executor. +void add_tests_StoryActions(UnitTestDatabase& database); +// The table executor's looks for interrupts between steps. +void add_tests_StoryInterrupts(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp index 349aa3e530..9dd748b015 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp @@ -7,7 +7,6 @@ #include #include #include "Common/Cpp/Exceptions.h" -#include "Pokemon_StoryVariant.h" #include "Pokemon_StoryActions.h" namespace PokemonAutomation{ @@ -58,7 +57,7 @@ const StoryAction* StoryActionTable::find(StoryStepKind kind, std::string_view n } const StoryAction* StoryActionTable::find(const StoryStep& step) const{ - return find(step.kind, variant_name(step.variant)); + return find(step.kind, step.action); } @@ -66,10 +65,14 @@ std::vector lint_story_checkpoint(const StoryCheckpoint& data, cons std::vector problems; for (size_t c = 0; c < data.steps.size(); c++){ const StoryStep& step = data.steps[c]; - if (table.find(step) == nullptr){ + const StoryAction* action = table.find(step); + const std::vector errors = action == nullptr + ? std::vector{"no action"} + : story_args_errors(StoryActionSpec{.kind = step.kind, .name = step.action, .args = action->args}, step.args); + for (const std::string& error : errors){ problems.emplace_back(std::format( - "{} step {} {}: no action for {} '{}'", - data.id, c + 1, step.name, story_step_kind_name(step.kind), variant_name(step.variant) + "{} step {} {}: {} for {} '{}'", + data.id, c + 1, step.name, error, story_step_kind_name(step.kind), step.action )); } } @@ -87,6 +90,8 @@ void StepGuard::on_failure(const StoryStep&, const OperationFailedException&){} void StepGuard::on_interrupt(const StoryStep&, const InterruptCheck&){} +void StepGuard::on_screen(const StoryStep&, const ScreenSettle&){} + TableExecutor::TableExecutor(const StoryActionTable& table, StepGuard& guard) : m_table(table) @@ -122,7 +127,7 @@ Outcome TableExecutor::run_action(RunState& state, const StoryStep& step){ if (const StoryAction* action = m_table.find(step)){ return action->act(state, step); } - return StoryStepExecutor::run(state, step); + return unsupported_step(step); } // Clears what interrupted the player before `step`, counting it in @@ -133,8 +138,10 @@ std::optional TableExecutor::clear_interrupts(RunState& state, const St return std::nullopt; } InterruptCheck check = clear_story_interrupt(*m_interrupts, state, step); + m_guard.on_screen(step, check.screen); if (check.verdict.kind == InterruptKind::NONE){ - return std::nullopt; + // Nothing interrupted; failed only when the game is not running. + return check.outcome.succeeded() ? std::nullopt : std::optional(check.outcome); } if (check.outcome.succeeded() && ++cleared > m_interrupts->max_per_step){ check.outcome = outcome_failed("too_many_interrupts", step.name); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h index 9f66529814..36009acf73 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h @@ -3,8 +3,8 @@ * From: https://github.com/PokemonAutomation/ * * A game's story steps as a table of actions instead of one virtual per - * kind. An action is keyed by the step's kind and its variant's name - * (variant_name(), Pokemon_StoryVariant.h), so one table holds a game's + * kind. An action is keyed by the step's kind and its action's name + * (StoryStep::action), so one table holds a game's * usual way of doing a kind, its other ways, and the steps only it has. * The console and a simulation bind the same rows to different actions. * @@ -23,13 +23,15 @@ #include #include #include +#include #include #include #include #include "CommonFramework/Exceptions/OperationFailedException.h" #include "Pokemon_StoryEvents.h" #include "Pokemon_StoryInterrupts.h" -#include "Pokemon_StorySteps.h" +#include "Pokemon_StoryStepExecutor.h" +#include "Types/Pokemon_StoryActionSpec.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -47,25 +49,28 @@ struct StoryAction{ // The screen event the action ends on ("fade", "dialog"). Declared for // the event-driven waits to come; nothing reads it yet. std::string waits_for = {}; + // The args its steps may carry (StoryStep::args); a step with any + // other, or without a required one, fails lint_story_checkpoint(). + std::vector args = {}; }; -// A game's actions by step kind and variant name. +// A game's actions by step kind and action name. class StoryActionTable{ public: - // The action for steps of `kind` whose variant is named `name`. An + // The action for steps of `kind` whose action is named `name`. An // empty `name` is the kind's default. A second action for the same // key throws InternalProgramError. void add(StoryStepKind kind, std::string name, StoryAction action); - // The action for steps of any kind whose variant is named `name`, + // The action for steps of any kind whose action is named `name`, // which must not be empty. void add_any_kind(std::string name, StoryAction action); - // The action for a step of `kind` with a variant named `name`: the + // The action for a step of `kind` with an action named `name`: the // one added for both, else the one for `name` of any kind, else the // kind's default. nullptr if there is none. const StoryAction* find(StoryStepKind kind, std::string_view name) const; - // find() for the step's kind and its variant's name. + // find() for the step's kind and its action's name. const StoryAction* find(const StoryStep& step) const; private: @@ -75,7 +80,8 @@ class StoryActionTable{ }; // The steps of `data` that `table` has no action for, as -// " step : no action for GAME 'bill'". +// " step : no action for GAME 'bill'", or whose args +// don't fit their action's, as "... missing argument \"budget\" for GAME 'mart'". std::vector lint_story_checkpoint(const StoryCheckpoint& data, const StoryActionTable& table); @@ -96,6 +102,10 @@ class StepGuard{ // A look before the step, or after it failed, found an interrupt and // cleared it or failed to (`check`): e.g. log it. virtual void on_interrupt(const StoryStep& step, const InterruptCheck& check); + // How the screen looked when the look before the step (or after it + // failed) ended, interrupt or not: e.g. log it, so a run log shows + // whether the scene before had ended before the step's first input. + virtual void on_screen(const StoryStep& step, const ScreenSettle& screen); }; @@ -105,10 +115,10 @@ class TableExecutor : public StoryStepExecutor{ // `table` and `guard` must outlive the executor. TableExecutor(const StoryActionTable& table, StepGuard& guard); - // The table's action for the step; with none, the kind's virtual - // (StoryStepExecutor::run()), so a game can move to the table one - // kind at a time. An OperationFailedException from either is the - // failed Outcome "operation_failed", unless the guard stops on it. + // The table's action for the step (run_action()); with none, the + // step is unsupported (unsupported_step()). An OperationFailedException + // from the action is the failed Outcome "operation_failed", unless the + // guard stops on it. // With interrupts set, each step first clears what stopped the player // since the step before, and a failed step that an interrupt explains // runs again once it is cleared. @@ -121,8 +131,9 @@ class TableExecutor : public StoryStepExecutor{ } protected: - // The table's action for the step, or the kind's virtual: what run() - // runs once the screen is clear. A binding may wrap it. + // The table's action for the step, or unsupported_step() with none: + // what run() runs once the screen is clear. A binding may wrap it, or + // do the kinds its table does not have yet. virtual Outcome run_action(RunState& state, const StoryStep& step); private: diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp index 851a6ecd03..49f835cac7 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp @@ -14,7 +14,6 @@ #include "Common/Cpp/TestRunners/UnitTest.h" #include "CommonFramework/Exceptions/OperationFailedException.h" #include "Pokemon_StoryActions.h" -#include "Pokemon_StoryVariant.h" #include "Pokemon_AutoStory_Tests.h" namespace PokemonAutomation{ @@ -23,21 +22,11 @@ namespace Pokemon{ namespace{ -std::string joined(const std::vector& words){ - std::string out; - for (std::string_view word : words){ - out += "["; - out += word; - out += "]"; - } - return out; -} - -StoryStep make(StoryStepKind kind, std::string name, std::string variant = ""){ +StoryStep make(StoryStepKind kind, std::string name, std::string action = ""){ StoryStep step; step.kind = kind; step.name = std::move(name); - step.variant = std::move(variant); + step.action = std::move(action); return step; } @@ -50,10 +39,10 @@ StoryAction named(std::string name){ }; } -// The name of the action the table finds for `kind` and `variant`; "none" +// The name of the action the table finds for `kind` and `action`; "none" // without one. -std::string found(const StoryActionTable& table, StoryStepKind kind, std::string variant){ - const StoryAction* action = table.find(make(kind, "step", std::move(variant))); +std::string found(const StoryActionTable& table, StoryStepKind kind, std::string name){ + const StoryAction* action = table.find(make(kind, "step", std::move(name))); if (action == nullptr){ return "none"; } @@ -62,64 +51,6 @@ std::string found(const StoryActionTable& table, StoryStepKind kind, std::string } -UnitTestResult test_variant_words(){ - const std::string words = joined(variant_words(" mart PewterCity_Mart budget=2000 ")); - if (words != "[mart][PewterCity_Mart][budget=2000]"){ - return "Expected three words, got " + words; - } - if (!variant_words("").empty() || !variant_words(" ").empty()){ - return "Expected no words in an empty variant."; - } - return true; -} - -UnitTestResult test_variant_pairs(){ - const std::optional pair = variant_pair("budget=2000"); - if (!pair || pair->key != "budget" || pair->value != "2000"){ - return "Expected budget=2000 as a pair."; - } - const std::optional empty_value = variant_pair("door="); - if (!empty_value || empty_value->key != "door" || !empty_value->value.empty()){ - return "Expected door= as a pair with an empty value."; - } - const std::optional two = variant_pair("a=b=c"); - if (!two || two->key != "a" || two->value != "b=c"){ - return "Expected a=b=c split at the first '='."; - } - if (variant_pair("=2000") || variant_pair("mart")){ - return "Expected no pair without a key or an '='."; - } - return true; -} - -UnitTestResult test_variant_name_and_values(){ - if (variant_name(" bill shot=1") != "bill" || !variant_name("shot=1 bill").empty() || !variant_name("").empty()){ - return "Expected the name to be the first word unless it is a pair."; - } - const std::string_view variant = "mart potion=5 budget=2000 potion=9"; - if (variant_value(variant, "potion") != std::optional("5")){ - return "Expected the first potion= value."; - } - if (variant_value(variant, "mart") || variant_value(variant, "repel")){ - return "Expected no value for a plain word or a missing key."; - } - return true; -} - -UnitTestResult test_variant_numbers(){ - if (variant_number("2000") != 2000u || variant_number("0") != 0u || variant_number("999999") != 999999u){ - return "Expected decimal numbers read."; - } - if (variant_number("") || variant_number("12a") || variant_number("-1") || variant_number("1234567")){ - return "Expected no number from empty, non-digit or too long text."; - } - if (variant_number("123", 2) || variant_number("12", 2) != 12u){ - return "Expected max_digits respected."; - } - return true; -} - - UnitTestResult test_lookup_order(){ StoryActionTable table; table.add(StoryStepKind::TALK, "", named("talk default")); @@ -127,12 +58,11 @@ UnitTestResult test_lookup_order(){ table.add_any_kind("bill", named("any bill")); table.add_any_kind("nurse", named("any nurse")); const std::pair checks[] = { - {found(table, StoryStepKind::TALK, "bill x=1"), "talk bill"}, + {found(table, StoryStepKind::TALK, "bill"), "talk bill"}, {found(table, StoryStepKind::MASH, "bill"), "any bill"}, {found(table, StoryStepKind::TALK, "nurse"), "any nurse"}, {found(table, StoryStepKind::TALK, "oak"), "talk default"}, {found(table, StoryStepKind::TALK, ""), "talk default"}, - {found(table, StoryStepKind::TALK, "x=1"), "talk default"}, {found(table, StoryStepKind::MASH, "oak"), "none"}, {found(table, StoryStepKind::MASH, ""), "none"}, }; @@ -168,45 +98,69 @@ UnitTestResult test_duplicate_actions_throw(){ return found(table, StoryStepKind::TALK, "bill") == "first" ? UnitTestResult(true) : UnitTestResult("Expected the first action kept."); } +// The args a test Mart takes. +const std::vector MART_ARGS = { + {.key = "map", .type = StoryArgType::WORD, .required = true, .fallback = std::nullopt, .why = ""}, + {.key = "budget", .type = StoryArgType::INTEGER, .required = true, .fallback = std::nullopt, .why = ""}, +}; + +// `step` with `args`. +StoryStep with_args(StoryStep step, StoryActionArgs args){ + step.args = std::move(args); + return step; +} + UnitTestResult test_lint_names_steps_without_actions(){ StoryActionTable table; table.add(StoryStepKind::ROUTE, "", named("route")); table.add_any_kind("bill", named("bill")); + StoryAction mart = named("mart"); + mart.args = MART_ARGS; + table.add(StoryStepKind::GAME, "mart", std::move(mart)); const StoryCheckpoint data{ .id = "00.05", .title = "", .start = std::nullopt, .steps = { - make(StoryStepKind::ROUTE, "to the cape", "costs=grass"), + make(StoryStepKind::ROUTE, "to the cape", "route"), make(StoryStepKind::GAME, "meet Bill", "bill"), - make(StoryStepKind::GAME, "teleporter", "cell_separator x=1"), + make(StoryStepKind::GAME, "teleporter", "cell_separator"), make(StoryStepKind::TALK, "talk"), + with_args(make(StoryStepKind::GAME, "buy", "mart"), {{"map", std::string("M")}, {"budget", int64_t(1500)}}), + with_args(make(StoryStepKind::GAME, "buy more", "mart"), {{"map", std::string("M")}}), + with_args(make(StoryStepKind::GAME, "meet Bill again", "bill"), {{"slot", int64_t(1)}}), }, }; const std::vector problems = lint_story_checkpoint(data, table); const std::vector expected = { "00.05 step 3 teleporter: no action for GAME 'cell_separator'", "00.05 step 4 talk: no action for TALK ''", + "00.05 step 6 buy more: missing argument \"budget\" for GAME 'mart'", + "00.05 step 7 meet Bill again: unknown argument \"slot\" for GAME 'bill'", }; if (problems != expected){ std::string got; for (const std::string& problem : problems){ got += "\n" + problem; } - return "Expected two steps without actions, got:" + got; + return "Expected two steps without actions and two with bad args, got:" + got; } return true; } -// Steps without an action of their own go to this TALK. +// A binding that does TALK itself when its table has no action for it. class FakeTableExecutor : public TableExecutor{ public: using TableExecutor::TableExecutor; protected: - virtual Outcome talk(RunState&, const StoryStep&) override{ - return outcome_failed("talk virtual"); + virtual Outcome run_action(RunState& state, const StoryStep& step) override{ + const Outcome outcome = TableExecutor::run_action(state, step); + if (step.kind == StoryStepKind::TALK && outcome.failure == "unsupported_step"){ + return outcome_failed("talk binding"); + } + return outcome; } }; @@ -236,7 +190,7 @@ StoryAction throwing(){ }; } -UnitTestResult test_executor_uses_table_then_virtuals(){ +UnitTestResult test_executor_uses_table_then_binding(){ StoryActionTable table; table.add(StoryStepKind::GAME, "bill", named("bill action")); FakeGuard guard; @@ -245,8 +199,8 @@ UnitTestResult test_executor_uses_table_then_virtuals(){ const std::string bill = executor.run(state, make(StoryStepKind::GAME, "bill", "bill")).failure; const std::string talk = executor.run(state, make(StoryStepKind::TALK, "talk")).failure; const std::string mash = executor.run(state, make(StoryStepKind::MASH, "mash")).failure; - if (bill != "bill action" || talk != "talk virtual" || mash != "unsupported_step"){ - return "Expected table, virtual, unsupported; got " + bill + ", " + talk + ", " + mash; + if (bill != "bill action" || talk != "talk binding" || mash != "unsupported_step"){ + return "Expected table, binding, unsupported; got " + bill + ", " + talk + ", " + mash; } if (guard.trace != std::vector{"before bill", "before talk", "before mash"}){ return "Expected the guard before every step."; @@ -327,22 +281,6 @@ class Test_StoryActions : public UnitTest{ }; const StoryActionsCase STORY_ACTIONS_CASES[] = { - { - .input = {.name = "variant: words split on spaces", .test = test_variant_words}, - .expectation = {.description = "drops empty words between, before and after spaces"}, - }, - { - .input = {.name = "variant: key=value pairs", .test = test_variant_pairs}, - .expectation = {.description = "splits at the first '=', needs a key, allows an empty value"}, - }, - { - .input = {.name = "variant: name and values", .test = test_variant_name_and_values}, - .expectation = {.description = "names the first plain word and reads the first value of a key"}, - }, - { - .input = {.name = "variant: numbers", .test = test_variant_numbers}, - .expectation = {.description = "reads decimal digits only, up to max_digits"}, - }, { .input = {.name = "table: exact, then any kind, then the kind's default", .test = test_lookup_order}, .expectation = {.description = "finds the most specific action, or none"}, @@ -356,8 +294,8 @@ const StoryActionsCase STORY_ACTIONS_CASES[] = { .expectation = {.description = "names each step the table has no action for"}, }, { - .input = {.name = "executor: the table, then the kind's virtual", .test = test_executor_uses_table_then_virtuals}, - .expectation = {.description = "falls back to the per-kind virtuals, guarded before every step"}, + .input = {.name = "executor: the table, then the binding", .test = test_executor_uses_table_then_binding}, + .expectation = {.description = "a step without a table action is the binding's or unsupported, guarded before every step"}, }, { .input = {.name = "executor: a console failure fails the step", .test = test_guard_turns_failures_into_outcomes}, diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryCheckpointTypes.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryCheckpointTypes.h new file mode 100644 index 0000000000..c977326857 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryCheckpointTypes.h @@ -0,0 +1,86 @@ +/* Story Checkpoint Types + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_StoryEvents.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryCheckpointTypes_H +#define PokemonAutomation_Pokemon_StoryCheckpointTypes_H + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_StoryLog.h" +#include "Pokemon_StoryEvent.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Pose confidence adjustment following an event interruption. +enum class InterruptPose{ + UNCHANGED, // Cleared where we stood (a talk-only trainer). + WITHIN_SET, // Moved an unknown part of a leg: still within the position we had, no longer exactly where. + LOST, // Anywhere. +}; +// Policy defining how an interrupted event should be resumed. +enum class ResumePolicy{ + RETRY_EVENT, // Run the event again, from its skip_if. + RECHECK_EXPECT, // The action may have finished: done if its expects hold, else retry. + STOP, // Stop the checkpoint. +}; + +// Something that can stop an action part-way. +struct Interrupt{ + std::string name; + Check detect; + Act handle; + InterruptPose pose = InterruptPose::UNCHANGED; + ResumePolicy resume = ResumePolicy::RETRY_EVENT; +}; +// Writes what an interrupt did (`effect`) into `pose`. +void apply_interrupt_pose(Pose& pose, InterruptPose effect); + + +// Story milestone containing pre/post conditions and a series of events. +struct Checkpoint{ + std::string id; + // Must hold before the first event (the save it starts from). + std::vector start; + std::vector interrupts; + std::vector events; + // Must hold after the last event. + std::vector end; + // Saves the game after the end check, if set. + Act save; + size_t max_interrupts_per_event = 5; +}; + + +// Result report from executing a checkpoint. +struct CheckpointReport{ + bool completed = false; + // 1-based number of the event that failed; 0 for the start or end check + // or the save, or when nothing failed. + size_t failed_event = 0; + std::string failed_name; + Outcome failure; + size_t events_run = 0; + size_t events_skipped = 0; +}; + +// Callback receiver for story event execution log messages. +using EventLogger = MoveOnlyFunction; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h new file mode 100644 index 0000000000..48f20e317e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h @@ -0,0 +1,86 @@ +/* Story Event + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_StoryEvents.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryEvent_H +#define PokemonAutomation_Pokemon_StoryEvent_H + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_StoryLog.h" +#include "Pokemon_StoryOutcome.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Predicate callable evaluating current run state. +using Check = MoveOnlyFunction; + +// A question the screen (or the run state) answers, named for the log. +struct Condition{ + std::string name; + Check check; +}; +// Constructs a named Condition from a predicate check. +Condition condition(std::string name, Check check); + +// Holds while the pose is on `map` (any map if empty) and at least as +// certain as `need`. +Condition pose_known(std::string map, PoseCertainty need); + + +// Strategy for recovering from a failed event. +enum class RecoveryKind{ + WAIT, // Something transient (a wanderer, a slow scene): wait, try again. + REANCHOR, // The pose is in doubt: confirm it on a landmark, try again. + STOP, // Nothing to do: stop the checkpoint. +}; +// Returns the readable name of a recovery strategy. +std::string recovery_name(RecoveryKind kind); + +// Answers a failure named `on` (any failure if empty): runs `prepare`, if +// any, and tries the event again, up to `attempts` times. +struct Recovery{ + std::string on; + RecoveryKind kind = RecoveryKind::STOP; + Act prepare; + size_t attempts = 1; + std::string why; +}; + + +// Single executable story action with preconditions, recovery steps, and postconditions. +struct Event{ + std::string name; + std::string why; + // Skipped when all of these hold (and there is at least one). + std::vector skip_if; + // Must hold before `act`; a failure is "require_failed". + std::vector require; + Act act; + // Must hold after `act`; a failure is "expect_failed". + std::vector expect; + // Written to the run's pose once the event succeeds. An action that + // learns its pose as it goes (the row that answered) returns it in + // its Outcome instead. + std::optional pose_learned; + // In order of escalation. + std::vector recoveries; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp index 79a095fb9f..882627e411 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp @@ -14,7 +14,7 @@ namespace PokemonAutomation{ namespace Pokemon{ -const char* certainty_name(PoseCertainty certainty){ +std::string certainty_name(PoseCertainty certainty){ switch (certainty){ case PoseCertainty::TILE: return "tile"; @@ -60,19 +60,18 @@ std::string to_string(const Pose& pose){ bool Outcome::succeeded() const{ return failure.empty(); } -Outcome outcome_ok(){ - return Outcome{}; -} -Outcome outcome_ok(Pose pose){ +Outcome outcome_ok(std::optional pose){ Outcome outcome; outcome.pose = std::move(pose); return outcome; } + Outcome outcome_unchanged(){ Outcome outcome; outcome.changed_nothing = true; return outcome; } + Outcome outcome_failed(std::string failure, std::string detail){ Outcome outcome; outcome.failure = std::move(failure); @@ -83,6 +82,10 @@ std::string to_string(const Outcome& outcome){ return outcome.detail.empty() ? outcome.failure : outcome.failure + ": " + outcome.detail; } +Outcome outcome_game_not_running(){ + return outcome_failed(std::string(GAME_NOT_RUNNING), "the game is not running: the Switch HOME menu is showing"); +} + Condition condition(std::string name, Check check){ return Condition{std::move(name), std::move(check)}; } @@ -94,7 +97,7 @@ Condition pose_known(std::string map, PoseCertainty need){ }); } -const char* recovery_name(RecoveryKind kind){ +std::string recovery_name(RecoveryKind kind){ switch (kind){ case RecoveryKind::WAIT: return "wait"; @@ -107,11 +110,6 @@ const char* recovery_name(RecoveryKind kind){ } -std::string event_log_line(const std::string& checkpoint, size_t number, const std::string& event, const std::string& status){ - return std::format("[Event] {}/{} {}: {}", checkpoint, number, event, status); -} - - namespace{ // Runs an action; if it succeeded knowing where it left the player, that @@ -266,6 +264,9 @@ Recovery* next_recovery(EventRun& run, const std::string& failure){ // is answered in turn, so escalation goes on from there. std::optional recover(EventRun& run, Outcome failure){ while (true){ + if (failure.failure == GAME_NOT_RUNNING){ + return failure; + } Recovery* recovery = next_recovery(run, failure.failure); if (recovery == nullptr){ return failure; @@ -401,7 +402,7 @@ Outcome finish_checkpoint(RunState& state, Checkpoint& checkpoint){ CheckpointReport run_checkpoint(RunState& state, Checkpoint& checkpoint, EventLogger& log){ CheckpointReport report; const std::string& id = checkpoint.id; - log(std::format("[Checkpoint] {}: start, {} events", id, checkpoint.events.size())); + log(checkpoint_start_line(id, checkpoint.events.size())); std::optional failing = first_failing(checkpoint.start, state); if (failing){ return stop_checkpoint(report, log, id, outcome_failed("start_failed", *failing)); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h index 10e96b6bc4..3e94a6996f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h @@ -32,209 +32,16 @@ #include #include #include +#include #include #include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_StoryLog.h" +#include "Pokemon_StoryCheckpointTypes.h" namespace PokemonAutomation{ namespace Pokemon{ -// How much of the pose is known. COLUMN and ROW pin one axis (a wall, a -// door); SET means one of the positions the pose holds. -enum class PoseCertainty{ - TILE, - COLUMN, - ROW, - SET, - UNKNOWN, -}; -// Returns the string label for a pose certainty level. -const char* certainty_name(PoseCertainty certainty); - -// Whether a pose known to `have` is good enough for an event that needs `need`. -bool certainty_covers(PoseCertainty have, PoseCertainty need); - -// Where on a map the player is, in the game's own terms: tiles and a -// facing in a 2D game (Pokemon_TilePose.h), a map point or a fly point in -// an open-world one. The engine only carries and prints it; the game's -// actions read it back. -struct Position{ - virtual ~Position() = default; - // The text after the map in a log line, e.g. "(10, 20) facing north"; - // none for a game that has nothing to say beyond the map. - virtual std::string describe() const{ - return ""; - } -}; - -// Where the player is believed to be. The screen is read; the pose is -// tracked, and only an anchor (a wall, a door, an NPC who answered) makes -// it certain. `where` is null until the game learns a position and after -// the pose is lost; it is shared because poses are copied (an event's -// learned pose into the run) and never changed in place. -struct Pose{ - std::string map; - PoseCertainty certainty = PoseCertainty::UNKNOWN; - std::shared_ptr where; -}; -// Formats a Pose as a human-readable string. -std::string to_string(const Pose& pose); - - -// What a run knows. Flags are set only by confirmed effects and are lost -// on a reload. -struct RunState{ - Pose pose; - std::set flags; -}; - - -// How an action or a check ended: empty `failure` is success; otherwise a -// name that recoveries match (e.g. "probe_exhausted"). A succeeded action -// that knows where it left the player sets `pose`; the runner writes it -// into the run before the event's expects are checked. -struct Outcome{ - std::string failure; - std::string detail; - std::optional pose; - // A succeeded action that left the game as it found it: a read, a - // check, a TM the lead already knows. A reload of the same save undoes - // nothing it did. - bool changed_nothing = false; - - bool succeeded() const; -}; -// Constructs a successful event outcome without changing pose. -Outcome outcome_ok(); -// Constructs a successful event outcome updating the run pose. -Outcome outcome_ok(Pose pose); -// outcome_ok() with `changed_nothing`. -Outcome outcome_unchanged(); -// Constructs a failed event outcome with reason and optional diagnostic detail. -Outcome outcome_failed(std::string failure, std::string detail = ""); -// "probe_exhausted: 4 rows": the failure and its detail, if any. -std::string to_string(const Outcome& outcome); - - -// Callable action executed for a story event. -using Act = MoveOnlyFunction; -// Predicate callable evaluating current run state. -using Check = MoveOnlyFunction; - -// A question the screen (or the run state) answers, named for the log. -struct Condition{ - std::string name; - Check check; -}; -// Constructs a named Condition from a predicate check. -Condition condition(std::string name, Check check); - -// Holds while the pose is on `map` (any map if empty) and at least as -// certain as `need`. -Condition pose_known(std::string map, PoseCertainty need); - - -// Strategy for recovering from a failed event. -enum class RecoveryKind{ - WAIT, // Something transient (a wanderer, a slow scene): wait, try again. - REANCHOR, // The pose is in doubt: confirm it on a landmark, try again. - STOP, // Nothing to do: stop the checkpoint. -}; -// Returns the readable name of a recovery strategy. -const char* recovery_name(RecoveryKind kind); - -// Answers a failure named `on` (any failure if empty): runs `prepare`, if -// any, and tries the event again, up to `attempts` times. -struct Recovery{ - std::string on; - RecoveryKind kind = RecoveryKind::STOP; - Act prepare; - size_t attempts = 1; - std::string why; -}; - - -// Single executable story action with preconditions, recovery steps, and postconditions. -struct Event{ - std::string name; - std::string why; - // Skipped when all of these hold (and there is at least one). - std::vector skip_if; - // Must hold before `act`; a failure is "require_failed". - std::vector require; - Act act; - // Must hold after `act`; a failure is "expect_failed". - std::vector expect; - // Written to the run's pose once the event succeeds. An action that - // learns its pose as it goes (the row that answered) returns it in - // its Outcome instead. - std::optional pose_learned; - // In order of escalation. - std::vector recoveries; -}; - - -// Pose confidence adjustment following an event interruption. -enum class InterruptPose{ - UNCHANGED, // Cleared where we stood (a talk-only trainer). - WITHIN_SET, // Moved an unknown part of a leg: still within the position we had, no longer exactly where. - LOST, // Anywhere. -}; -// Policy defining how an interrupted event should be resumed. -enum class ResumePolicy{ - RETRY_EVENT, // Run the event again, from its skip_if. - RECHECK_EXPECT, // The action may have finished: done if its expects hold, else retry. - STOP, // Stop the checkpoint. -}; - -// Something that can stop an action part-way. -struct Interrupt{ - std::string name; - Check detect; - Act handle; - InterruptPose pose = InterruptPose::UNCHANGED; - ResumePolicy resume = ResumePolicy::RETRY_EVENT; -}; -// Writes what an interrupt did (`effect`) into `pose`. -void apply_interrupt_pose(Pose& pose, InterruptPose effect); - - -// Story milestone containing pre/post conditions and a series of events. -struct Checkpoint{ - std::string id; - // Must hold before the first event (the save it starts from). - std::vector start; - std::vector interrupts; - std::vector events; - // Must hold after the last event. - std::vector end; - // Saves the game after the end check, if set. - Act save; - size_t max_interrupts_per_event = 5; -}; - - -// Result report from executing a checkpoint. -struct CheckpointReport{ - bool completed = false; - // 1-based number of the event that failed; 0 for the start or end check - // or the save, or when nothing failed. - size_t failed_event = 0; - std::string failed_name; - Outcome failure; - size_t events_run = 0; - size_t events_skipped = 0; -}; - -// Callback receiver for story event execution log messages. -using EventLogger = MoveOnlyFunction; - - -// One log line, in a format the lab watcher parses: -// [Event] 00.04/3 talk_mom: start -// [Event] 00.04/3 talk_mom: failed: expect_failed: has_parcel -std::string event_log_line(const std::string& checkpoint, size_t number, const std::string& event, const std::string& status); - // Problems an author should fix before running: unnamed or empty events, // missing actions, recoveries out of escalation order. std::vector lint_checkpoint(const Checkpoint& checkpoint); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp index 418355a696..cc00052362 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp @@ -617,7 +617,7 @@ struct StoryEventInput{ }; struct StoryEventExpectation{ - const char* description; + std::string_view description; }; struct StoryEventTestCase{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp index 258d334ba2..f431425718 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp @@ -4,6 +4,10 @@ * */ +#include +#include +#include +#include #include #include "Common/Cpp/Exceptions.h" #include "Pokemon_StoryInterrupts.h" @@ -37,33 +41,119 @@ void InterruptHandlerTable::starts_on(StoryStepKind step, InterruptKind kind){ } bool InterruptHandlerTable::step_starts_on(StoryStepKind step, InterruptKind kind) const{ - return m_starts_on.contains({step, kind}); + if (m_starts_on.contains({step, kind})){ + return true; + } + return kind == InterruptKind::UNSETTLED && ( + m_starts_on.contains({step, InterruptKind::WILD_ENCOUNTER}) || + m_starts_on.contains({step, InterruptKind::TRAINER_SIGHT}) + ); } namespace{ -InterruptVerdict judge(const StoryInterrupts& interrupts, bool fresh){ - const ScreenLook look = interrupts.look(fresh); - return classify_interrupt(look.log, look.window, interrupts.knobs); +// Whether an UNSETTLED verdict on `look` may be a battle's opening: its +// fade is white (an encounter's flash), still down (a battle's fade ends +// on the battle), or came after a dialog box (a trainer's lines). +bool may_open_a_battle(const ScreenLook& look, const InterruptVerdict& verdict){ + const auto fade = std::find_if(verdict.evidence.begin(), verdict.evidence.end(), [](const ScreenEventChange& change){ + return change.edge == ScreenEventEdge::ROSE && + (change.event == ScreenEvent::FADE_WHITE || change.event == ScreenEvent::FADE_BLACK); + }); + if (fade == verdict.evidence.end()){ + return false; + } + const bool still_down = std::none_of(verdict.evidence.begin(), verdict.evidence.end(), [](const ScreenEventChange& change){ + return change.edge == ScreenEventEdge::FELL; + }); + if (fade->event == ScreenEvent::FADE_WHITE || still_down){ + return true; + } + return std::any_of(look.log.changes().begin(), look.log.changes().end(), [&](const ScreenEventChange& change){ + return change.event == ScreenEvent::DIALOG_BOX && change.edge == ScreenEventEdge::ROSE && + look.window.start <= change.time && change.time < fade->time; + }); } // The look's verdict, looked at again while it is unsettled, up to -// max_looks looks in all. -InterruptVerdict settled_verdict(const StoryInterrupts& interrupts){ - InterruptVerdict verdict = judge(interrupts, true); - for (size_t looks = 1; verdict.kind == InterruptKind::UNSETTLED && looks < interrupts.max_looks; looks++){ - verdict = judge(interrupts, false); +// max_looks looks in all, or max_opening_looks while it may be a battle's +// opening; not again before a step that starts on it. `screen` is how the +// last look ended. +InterruptVerdict settled_verdict(const StoryInterrupts& interrupts, StoryStepKind step, ScreenSettle& screen){ + ScreenLook look = interrupts.look(true); + InterruptVerdict verdict = classify_interrupt(look.log, look.window, interrupts.knobs); + const bool home = look.log.showing().has(ScreenEvent::SWITCH_HOME_MENU); + if (!home && !interrupts.handlers.step_starts_on(step, InterruptKind::UNSETTLED)){ + for (size_t looks = 1; verdict.kind == InterruptKind::UNSETTLED; looks++){ + const size_t limit = may_open_a_battle(look, verdict) ? interrupts.max_opening_looks : interrupts.max_looks; + if (looks >= limit){ + break; + } + look = interrupts.look(false); + verdict = classify_interrupt(look.log, look.window, interrupts.knobs); + } } + screen = judge_settle(look); return verdict; } } // namespace +ScreenSettle judge_settle(const ScreenLook& look){ + ScreenSettle out; + const std::optional last = look.log.last_frame(); + if (!last || *last < look.window.start){ + return out; + } + out.seen = true; + out.showing = look.log.showing(); + WallClock since = look.window.start; + for (const ScreenEventChange& change : look.log.changes()){ + if (change.time <= look.window.end){ + since = std::max(since, change.time); + } + } + const WallClock end = std::max(look.window.end, since); + out.quiet = std::chrono::duration_cast(end - since); + return out; +} + +bool on_home_menu(const ScreenSettle& settle){ + return settle.seen && settle.showing.has(ScreenEvent::SWITCH_HOME_MENU); +} + +bool is_settled(const ScreenSettle& settle){ + return settle.seen && !on_home_menu(settle) && + settle.showing.has(ScreenEvent::PLAYER_CAN_MOVE) && + !settle.showing.any_of({ScreenEvent::DIALOG_BOX, ScreenEvent::BATTLE_STARTED}) && + fade_in(settle.showing) == WarpFade::NONE; +} + +std::string describe(const ScreenSettle& settle){ + if (!settle.seen){ + return "no frame seen"; + } + const std::string quiet = std::format("quiet {:.1f} s", settle.quiet.count() / 1000.0); + if (on_home_menu(settle)){ + return "Switch HOME menu (" + quiet + ")"; + } + if (is_settled(settle)){ + return "settled overworld (" + quiet + ")"; + } + return describe(settle.showing) + " showing (" + quiet + ")"; +} + + InterruptCheck clear_story_interrupt(const StoryInterrupts& interrupts, RunState& state, const StoryStep& step){ InterruptCheck out; - out.verdict = settled_verdict(interrupts); + out.verdict = settled_verdict(interrupts, step.kind, out.screen); + if (on_home_menu(out.screen)){ + out.verdict = {}; + out.outcome = outcome_game_not_running(); + return out; + } const InterruptKind kind = out.verdict.kind; if (kind == InterruptKind::NONE){ return out; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h index 048aa8538f..b9f5abe2a9 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h @@ -17,7 +17,17 @@ * * A step that starts on what the look found (a MASH on its scene's box, * a BATTLE on its trainer's lines) is not interrupted by it: the table - * says which (InterruptHandlerTable::starts_on()). + * says which (InterruptHandlerTable::starts_on()). A step that starts on + * a battle also starts on an UNSETTLED screen, a fade with no battle yet: + * that is its battle's opening, still playing (BDSP's Starly battle right + * after the starter is picked), and the step waits for it itself. + * + * Before another step, an unsettled screen that may be a battle's opening + * (a white flash, a fade still down, a fade after a dialog box) is looked + * at until its battle shows, up to max_opening_looks looks: the walk + * before the step ended in grass or in a trainer's sight. The battle is + * then cleared as any other. A fade that came back up with no box before + * it (a door's) is looked at max_looks times only. * */ @@ -28,87 +38,55 @@ #include #include #include +#include #include #include "Pokemon_Interrupts.h" #include "Pokemon_ScreenEvents.h" #include "Pokemon_StoryEvents.h" -#include "Pokemon_StorySteps.h" +#include "Pokemon_StoryStepExecutor.h" +#include "Pokemon_InterruptHandlers.h" namespace PokemonAutomation{ namespace Pokemon{ -// What a game saw of the screen between two steps: its timed events, and -// the span of them the classifier judges. -struct ScreenLook{ - ScreenEventLog log{}; - InterruptWindow window = {}; -}; - -// Looks at the screen. `fresh` starts a new look; otherwise the look goes -// on from the last one, to see how an unsettled screen ends. -using ScreenLookFunction = std::function; - -// Clears an interrupt a look found: flees or fights the battle, closes -// the dialog, waits out the warp. -using InterruptAction = std::function; - -// A row of an InterruptHandlerTable. -struct InterruptHandler{ - InterruptAction handle = {}; - // What clearing it did to where the player is. - InterruptPose pose = InterruptPose::UNCHANGED; -}; - - -// A game's handlers by kind of interrupt, and the steps that start on one. -class InterruptHandlerTable{ -public: - // The handler for `kind`: one of WILD_ENCOUNTER, TRAINER_SIGHT, - // DIALOG or WARP. Another kind, or a second handler for one, throws - // InternalProgramError. - void add(InterruptKind kind, InterruptHandler handler); - // The handler for `kind`; nullptr if there is none. - const InterruptHandler* find(InterruptKind kind) const; - - // Steps of `step` start on `kind` showing: before one, it is the - // step's to clear, not an interrupt. - void starts_on(StoryStepKind step, InterruptKind kind); - bool step_starts_on(StoryStepKind step, InterruptKind kind) const; - -private: - std::map m_handlers; - std::set> m_starts_on; -}; - - -// A game's interrupts between steps: how it looks, how it judges what it -// saw, and what it does about each kind. -struct StoryInterrupts{ - ScreenLookFunction look = {}; - InterruptKnobs knobs = {}; - InterruptHandlerTable handlers = {}; - // Looks at a screen that stays UNSETTLED (a fade with no battle yet) - // before it fails the step as "interrupt_unsettled". - size_t max_looks = 3; - // Interrupts cleared for one step before it fails as - // "too_many_interrupts". - size_t max_per_step = 3; +// How the screen looked at the end of a look: the line a run log needs to +// answer "had the scene ended before the step's first input?". +struct ScreenSettle{ + // Whether the look saw a frame at all. + bool seen = false; + // The events its last frame showed. + ScreenEvents showing = {}; + // How long the screen had shown them unchanged when the look ended. + Milliseconds quiet = Milliseconds(0); }; +// The end of `look`: its last frame's events, and how long they held. +ScreenSettle judge_settle(const ScreenLook& look); +// Whether it ended on the HOME menu: the game is not running. +bool on_home_menu(const ScreenSettle& settle); +// Whether it ended on the overworld with no box, no fade and no battle. +bool is_settled(const ScreenSettle& settle); +// "settled overworld (quiet 0.3 s)", "black fade showing (quiet 0.1 s)", +// "Switch HOME menu (quiet 0.3 s)", "no frame seen". +std::string describe(const ScreenSettle& settle); // What a look between steps found, and what clearing it came to. struct InterruptCheck{ + // How the screen looked when the look ended, judged or not. + ScreenSettle screen = {}; // NONE when nothing interrupted, or when the step starts on it. InterruptVerdict verdict = {}; // Failed when the look stayed unsettled, the kind had no handler, or - // the handler failed. + // the handler failed; GAME_NOT_RUNNING, with no verdict, when the + // look ended on the Switch's HOME menu. Outcome outcome = {}; }; // Looks at the screen before `step` (or after it failed) and clears what // interrupted the player, if anything, writing the handler's effect on -// the pose into `state`. +// the pose into `state`. On the HOME menu it fails as GAME_NOT_RUNNING +// and clears nothing, whatever the step starts on. InterruptCheck clear_story_interrupt(const StoryInterrupts& interrupts, RunState& state, const StoryStep& step); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp index 2dedf86142..764352933d 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -19,6 +19,7 @@ #include "CommonFramework/Exceptions/OperationFailedException.h" #include "Pokemon_StoryActions.h" #include "Pokemon_StoryInterrupts.h" +#include "Pokemon_StorySegments.h" #include "Pokemon_AutoStory_Tests.h" namespace PokemonAutomation{ @@ -41,6 +42,8 @@ const ScreenEvents WHITE{ScreenEvent::FADE_WHITE}; const ScreenEvents BLACK{ScreenEvent::FADE_BLACK}; const ScreenEvents BATTLE{ScreenEvent::BATTLE_STARTED}; const ScreenEvents BANNER{ScreenEvent::LOCATION_BANNER, ScreenEvent::PLAYER_CAN_MOVE}; +// The Switch's HOME menu: the game is not running. +const ScreenEvents HOME{ScreenEvent::SWITCH_HOME_MENU}; // A look at `frames`, judged up to `until_ms`. ScreenLook look_of(const std::vector& frames, int until_ms){ @@ -71,10 +74,28 @@ ScreenLook warp(){ ScreenLook white_unsettled(){ return look_of({{0, WALK}, {100, WHITE}, {700, WALK}}, 1000); } +// A trainer's lines, then the battle's black, still down: no battle yet. +ScreenLook trainer_opening(){ + return look_of({{0, WALK}, {100, BOX}, {2000, BLACK}}, 2100); +} +// A door's black, back up with no box before it: a warp, not yet settled. +ScreenLook black_unsettled(){ + return look_of({{0, WALK}, {100, BLACK}, {700, WALK}}, 1000); +} // The same white, looked at for long enough after it: a cave exit. ScreenLook white_settled(){ return look_of({{0, WALK}, {100, WHITE}, {700, WALK}, {10000, WALK}}, 10000); } +// The HOME menu, still: the program started with the game closed. +ScreenLook home_menu(){ + return look_of({{0, HOME}, {300, HOME}}, 300); +} +// The same, with a game's detectors reading it as the overworld too. +ScreenLook home_read_as_overworld(){ + ScreenEvents both = HOME; + both.set(ScreenEvent::PLAYER_CAN_MOVE, true); + return look_of({{0, both}}, 300); +} // The fake game: the screen its looks show, one per look and then the @@ -162,7 +183,7 @@ class NotingGuard : public StepGuard{ FakeGame& m_game; }; -// `step` (variant "act") run once by a TableExecutor with the fake +// `step` (action "act") run once by a TableExecutor with the fake // game's interrupts, from a known pose. struct FakeRun{ Outcome outcome; @@ -176,7 +197,7 @@ FakeRun run_step(FakeGame& game, StoryInterrupts& interrupts, StoryStep step, Fa FakeRun out; out.state.pose.map = "Town"; out.state.pose.certainty = PoseCertainty::TILE; - step.variant = "act"; + step.action = "act"; out.outcome = executor.run(out.state, step); return out; } @@ -204,7 +225,7 @@ UnitTestResult test_no_interrupts_set(){ TableExecutor executor(table, guard); RunState state; StoryStep step = make(StoryStepKind::ROUTE, "walk"); - step.variant = "act"; + step.action = "act"; const Outcome outcome = executor.run(state, step); if (!outcome.succeeded()){ return "Expected the step to succeed, got " + to_string(outcome); @@ -298,9 +319,10 @@ UnitTestResult test_unsettled_looks_again(){ return expect_trace(game, {"look", "look again", "clear warp", "told warp ", "run walk"}); } +// A door's fade is no battle's opening: three looks, as before. UnitTestResult test_unsettled_is_bounded(){ FakeGame game; - game.screens = {white_unsettled()}; + game.screens = {black_unsettled()}; StoryInterrupts interrupts = fake_interrupts(game); const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); if (run.outcome.failure != "interrupt_unsettled"){ @@ -309,6 +331,61 @@ UnitTestResult test_unsettled_is_bounded(){ return expect_trace(game, {"look", "look again", "look again", "told unsettled interrupt_unsettled: walk"}); } +// A battle's opening still playing when a step that starts on a battle +// begins (BDSP's Starly battle, right after the starter is picked): the +// step's, on the first look, not interrupt_unsettled. +UnitTestResult test_unsettled_before_a_battle(){ + FakeGame game; + game.screens = {white_unsettled()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers.starts_on(StoryStepKind::BATTLE, InterruptKind::WILD_ENCOUNTER); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::BATTLE, "starly")); + if (!run.outcome.succeeded()){ + return "Expected the battle step to run, got " + to_string(run.outcome); + } + return expect_trace(game, {"look", "run starly"}); +} + +// A battle's opening still playing when a walk step begins: the walk +// before it ended in grass or in a trainer's sight (BDSP fault sweep, 51 +// steps of 00.01-01.11). The looks wait for the battle, past max_looks, +// and its handler clears it before the step. +UnitTestResult test_opening_before_a_walk(ScreenLook opening, ScreenLook battle, const std::string& kind, const std::string& handler){ + FakeGame game; + game.screens = {opening, opening, opening, opening, std::move(battle), quiet()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (!run.outcome.succeeded()){ + return "Expected the walk to run after the battle, got " + to_string(run.outcome); + } + return expect_trace(game, { + "look", "look again", "look again", "look again", "look again", + "clear " + handler, "told " + kind + " ", "run walk", + }); +} +UnitTestResult test_wild_opening_before_a_walk(){ + return test_opening_before_a_walk(white_unsettled(), wild(), "wild encounter", "wild"); +} +UnitTestResult test_trainer_opening_before_a_walk(){ + return test_opening_before_a_walk(trainer_opening(), trainer(), "trainer sight", "trainer"); +} + +// A white that shows no battle and does not settle: max_opening_looks. +UnitTestResult test_opening_is_bounded(){ + FakeGame game; + game.screens = {white_unsettled()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.max_opening_looks = 5; + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (run.outcome.failure != "interrupt_unsettled"){ + return "Expected interrupt_unsettled, got " + to_string(run.outcome); + } + return expect_trace(game, { + "look", "look again", "look again", "look again", "look again", + "told unsettled interrupt_unsettled: walk", + }); +} + UnitTestResult test_failure_explained(bool throws){ FakeGame game; // Before the step, after its failure, before its second run. @@ -369,6 +446,151 @@ UnitTestResult test_table_rejects(){ return true; } +// A guard that notes how the screen looked before each step. +class ScreenGuard : public StepGuard{ +public: + explicit ScreenGuard(FakeGame& game) + : m_game(game) + {} + virtual void on_screen(const StoryStep& step, const ScreenSettle& screen) override{ + m_game.trace.push_back("before " + step.name + ": " + describe(screen)); + } + +private: + FakeGame& m_game; +}; + +// The guard hears how the screen looked before every step, interrupt or +// not: the run log's answer to "had the scene ended before the input?". +UnitTestResult test_screen_before_each_step(){ + FakeGame game; + // A scene's closing fade still down: no battle comes, so the step + // fails unsettled, and the guard hears the fade was showing. + game.screens = {look_of({{0, WALK}, {100, BLACK}}, 300)}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.max_opening_looks = 2; + const StoryActionTable table = table_of(game, {}); + ScreenGuard guard(game); + TableExecutor executor(table, guard); + executor.set_interrupts(&interrupts); + RunState state; + StoryStep step = make(StoryStepKind::ROUTE, "by_the_counter"); + step.action = "act"; + const Outcome faded = executor.run(state, step); + if (faded.succeeded()){ + return "Expected a step in a fade to fail unsettled, got " + to_string(faded); + } + game.screens = {quiet()}; + game.looks = 0; + const Outcome settled = executor.run(state, step); + if (!settled.succeeded()){ + return "Expected the step on a quiet screen to run, got " + to_string(settled); + } + return expect_trace(game, { + "look", "look again", "before by_the_counter: black fade showing (quiet 0.2 s)", + "look", "before by_the_counter: settled overworld (quiet 0.3 s)", "run by_the_counter", + }); +} + +// The program started on the HOME menu (lab-B 2026-11-09 15:31: "before +// save: settled overworld", then X on HOME and a 22-tile walk on it). The +// screen is told as HOME and the step fails at once, before any input, +// and before a step that starts on a battle's opening too. +UnitTestResult test_home_menu_before_a_step(){ + for (StoryStepKind kind : {StoryStepKind::SAVE, StoryStepKind::ROUTE, StoryStepKind::BATTLE}){ + FakeGame game; + game.screens = {home_menu()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers.starts_on(StoryStepKind::BATTLE, InterruptKind::TRAINER_SIGHT); + const StoryActionTable table = table_of(game, {}); + ScreenGuard guard(game); + TableExecutor executor(table, guard); + executor.set_interrupts(&interrupts); + RunState state; + StoryStep step = make(kind, "save"); + step.action = "act"; + const Outcome outcome = executor.run(state, step); + if (to_string(outcome) != "game_not_running: the game is not running: the Switch HOME menu is showing"){ + return "Expected the step on HOME to fail as game_not_running, got " + to_string(outcome); + } + if (UnitTestResult trace = expect_trace(game, {"look", "before save: Switch HOME menu (quiet 0.3 s)"}); trace.result != UnitTestResult::PASSED){ + return trace; + } + } + return true; +} + +// A checkpoint that fails on the HOME menu is neither recovered in place +// nor reloaded: every press would go to the console's menus. +UnitTestResult test_home_menu_stops_the_segment(){ + std::vector trace; + CheckpointSpec spec; + spec.id = "00.03"; + spec.build = [&trace]{ + Checkpoint checkpoint; + checkpoint.id = "00.03"; + Event save; + save.name = "save"; + save.act = [&trace](RunState&){ + trace.push_back("save"); + return outcome_failed("game_not_running", "the game is not running: the Switch HOME menu is showing"); + }; + Recovery wait; + wait.kind = RecoveryKind::WAIT; + wait.prepare = [&trace](RunState&){ + trace.push_back("recover"); + return outcome_ok(); + }; + save.recoveries.push_back(std::move(wait)); + checkpoint.events.push_back(std::move(save)); + return checkpoint; + }; + Segment segment; + segment.id = "00"; + segment.checkpoints.push_back(std::move(spec)); + SegmentHooks hooks; + hooks.reload = [&trace](RunState&){ + trace.push_back("reload"); + return outcome_ok(); + }; + RunState state; + const SegmentReport report = run_segment(state, segment, SegmentRange{}, SegmentPolicy{}, hooks); + if (report.completed || report.failure.failure != "game_not_running" || report.reloads != 0){ + return "Expected the segment to stop on game_not_running with no reload, got " + to_string(report.failure); + } + if (trace != std::vector{"save"}){ + std::string got; + for (const std::string& line : trace){ + got += " " + line; + } + return "Expected the save tried once and nothing else, got:" + got; + } + return true; +} + +UnitTestResult test_settle_of_a_look(){ + struct Row{ + std::string name; + ScreenLook look; + std::string expected; + }; + const std::vector rows = { + {"no frame", ScreenLook{}, "no frame seen"}, + {"a quiet overworld", quiet(), "settled overworld (quiet 0.3 s)"}, + {"a box", dialog(), "dialog box, player can move showing (quiet 0.2 s)"}, + {"a door's fade back up", black_unsettled(), "settled overworld (quiet 0.3 s)"}, + {"the HOME menu", home_menu(), "Switch HOME menu (quiet 0.3 s)"}, + {"HOME read as a quiet overworld too", home_read_as_overworld(), "Switch HOME menu (quiet 0.3 s)"}, + }; + for (const Row& row : rows){ + const std::string got = describe(judge_settle(row.look)); + if (got != row.expected){ + return std::format("{}: expected \"{}\", got \"{}\"", row.name, row.expected, got); + } + } + return true; +} + struct StoryInterruptsInput{ std::string_view name; @@ -441,7 +663,23 @@ const StoryInterruptsCase STORY_INTERRUPTS_CASES[] = { }, { .input = {.name = "unsettled: at most max_looks looks", .test = test_unsettled_is_bounded}, - .expectation = {.description = "interrupt_unsettled after three looks"}, + .expectation = {.description = "a door's fade: interrupt_unsettled after three looks"}, + }, + { + .input = {.name = "unsettled: a battle's opening before a battle step", .test = test_unsettled_before_a_battle}, + .expectation = {.description = "the step's, after one look"}, + }, + { + .input = {.name = "unsettled: a wild battle's opening before a walk", .test = test_wild_opening_before_a_walk}, + .expectation = {.description = "waits for the battle, clears it, then the walk"}, + }, + { + .input = {.name = "unsettled: a trainer battle's opening before a walk", .test = test_trainer_opening_before_a_walk}, + .expectation = {.description = "waits for the battle, fights it, then the walk"}, + }, + { + .input = {.name = "unsettled: at most max_opening_looks for an opening", .test = test_opening_is_bounded}, + .expectation = {.description = "a white with no battle: interrupt_unsettled"}, }, { .input = {.name = "a failed step an interrupt explains runs again", .test = test_failed_outcome_explained}, @@ -463,6 +701,22 @@ const StoryInterruptsCase STORY_INTERRUPTS_CASES[] = { .input = {.name = "table: one handler a kind that can be cleared", .test = test_table_rejects}, .expectation = {.description = "rejects NONE, UNSETTLED and a second handler"}, }, + { + .input = {.name = "the screen before each step, for the log", .test = test_screen_before_each_step}, + .expectation = {.description = "a fade still down is told, and fails unsettled; a quiet overworld is settled"}, + }, + { + .input = {.name = "how a look ended", .test = test_settle_of_a_look}, + .expectation = {.description = "the last frame's events and how long they held"}, + }, + { + .input = {.name = "the HOME menu before a step", .test = test_home_menu_before_a_step}, + .expectation = {.description = "told as HOME; game_not_running before any input"}, + }, + { + .input = {.name = "the HOME menu stops the segment", .test = test_home_menu_stops_the_segment}, + .expectation = {.description = "no recovery in place, no reload"}, + }, }; } // namespace diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp new file mode 100644 index 0000000000..0a9262d2c0 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp @@ -0,0 +1,73 @@ +/* Story Log + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryLog.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +std::string resets_text(size_t attempt){ + if (attempt <= 1){ + return "one-shot"; + } + return std::format("{} reset{}", attempt - 1, attempt == 2 ? "" : "s"); +} + +} // namespace + + +std::string event_log_line(std::string_view checkpoint, size_t number, std::string_view event, std::string_view status){ + return std::format("[Event] {}/{} {}: {}", checkpoint, number, event, status); +} + +std::string checkpoint_start_line(std::string_view checkpoint, std::optional events){ + if (!events){ + return std::format("[Checkpoint] {}: start", checkpoint); + } + return std::format("[Checkpoint] {}: start, {} events", checkpoint, *events); +} + +std::string checkpoint_attempt_line(std::string_view checkpoint, size_t attempt, std::optional attempts){ + if (!attempts){ + return std::format("[Checkpoint] {}: attempt {}", checkpoint, attempt); + } + return std::format("[Checkpoint] {}: attempt {}/{}", checkpoint, attempt, *attempts); +} + +std::string checkpoint_pass_line(std::string_view checkpoint, size_t attempt, size_t in_place){ + return std::format( + "[Checkpoint] {}: passed on attempt {} ({}){}", + checkpoint, attempt, resets_text(attempt), + in_place == 0 ? "" : std::format(", {} in place", in_place) + ); +} + +std::string checkpoint_reset_line(std::string_view checkpoint, size_t next_attempt){ + return std::format("[Checkpoint] {}: failed, resetting for attempt {}", checkpoint, next_attempt); +} + +std::string segment_reload_line(std::string_view segment, std::string_view checkpoint, size_t next_attempt, size_t attempts){ + return std::format( + "[Segment] {}: {} failed, reloading for attempt {}/{}", + segment, checkpoint, next_attempt, attempts + ); +} + + +void record_story_counts(AutoStoryStats& stats, const StoryRunCounts& counts){ + stats.m_segment += counts.segments; + stats.m_checkpoint += counts.checkpoints; + stats.m_reset += counts.resets; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h new file mode 100644 index 0000000000..f9576e1e69 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h @@ -0,0 +1,76 @@ +/* Story Log + * + * From: https://github.com/PokemonAutomation/ + * + * The log lines an AutoStory program writes around its checkpoints, in + * one format for every game: the story engine (Pokemon_StoryEvents.h, + * Pokemon_StorySegments.h) writes them, and a game with its own checkpoint + * loop (SV's) writes the same lines, so the lab watcher and whoever reads + * a log find each checkpoint's start, attempts, resets and pass the same + * way. Also the program's stats counts. Nothing here runs a story. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryLog_H +#define PokemonAutomation_Pokemon_StoryLog_H + +#include +#include +#include +#include +#include "Pokemon_AutoStoryStats.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// One event's line: +// [Event] 00.04/3 talk_mom: start +// [Event] 00.04/3 talk_mom: failed: expect_failed: has_parcel +std::string event_log_line(std::string_view checkpoint, size_t number, std::string_view event, std::string_view status); + +// A checkpoint starts; the story engine also says it has `events` events: +// [Checkpoint] 00.04: start +// [Checkpoint] 00.04: start, 3 events +std::string checkpoint_start_line(std::string_view checkpoint, std::optional events = std::nullopt); + +// An attempt at a checkpoint starts, counting from 1, out of the +// program's limit of `attempts` if it has one: +// [Checkpoint] 00.04: attempt 2 +// [Checkpoint] 00.04: attempt 2/3 +std::string checkpoint_attempt_line( + std::string_view checkpoint, size_t attempt, std::optional attempts = std::nullopt +); + +// A checkpoint passed on attempt `attempt`, after `in_place` recoveries in +// place: +// [Checkpoint] 00.03: passed on attempt 1 (one-shot) +// [Checkpoint] 00.04: passed on attempt 3 (2 resets), 1 in place +std::string checkpoint_pass_line(std::string_view checkpoint, size_t attempt, size_t in_place = 0); + +// An attempt failed and the game resets to the checkpoint's save for +// attempt `next_attempt`: +// [Checkpoint] 00.04: failed, resetting for attempt 2 +std::string checkpoint_reset_line(std::string_view checkpoint, size_t next_attempt); +// The story engine reloads within segment `segment`, out of `attempts`: +// [Segment] 00: 00.02 failed, reloading for attempt 2/3 +std::string segment_reload_line(std::string_view segment, std::string_view checkpoint, size_t next_attempt, size_t attempts); + + +// What a story run adds to the program's stats. +struct StoryRunCounts{ + size_t segments = 0; + // Checkpoints passed (and saved at). + size_t checkpoints = 0; + // Game resets or reloads after failed attempts. + size_t resets = 0; +}; + +// Adds `counts` to the shared AutoStory stats. +void record_story_counts(AutoStoryStats& stats, const StoryRunCounts& counts); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp new file mode 100644 index 0000000000..86b1e59b86 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp @@ -0,0 +1,173 @@ +/* Story Log Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_StoryRun_Tests.h" +#include "Pokemon_StoryLog.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +// A formatter's line, made when the table is built. +struct StoryLogInput{ + std::string name; + std::string line; +}; + +// The exact line: the lab watcher and the engine tests read these. +struct StoryLogExpectation{ + std::string line; +}; + +// One formatter call and the line it must make. +struct StoryLogCase{ + StoryLogInput input; + StoryLogExpectation expectation; +}; + +class Test_StoryLog : public UnitTest{ +public: + Test_StoryLog(StoryLogCase test_case) + : UnitTest("Pokemon::StoryLog - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + if (m_case.input.line != m_case.expectation.line){ + return "Expected \"" + m_case.expectation.line + "\", got \"" + m_case.input.line + "\""; + } + return true; + } + +private: + const StoryLogCase m_case; +}; + +const StoryLogCase STORY_LOG_CASES[] = { + { + .input = {.name = "event", .line = event_log_line("00.04", 3, "talk_mom", "start")}, + .expectation = {.line = "[Event] 00.04/3 talk_mom: start"}, + }, + { + .input = {.name = "checkpoint start", .line = checkpoint_start_line("00.04")}, + .expectation = {.line = "[Checkpoint] 00.04: start"}, + }, + { + .input = {.name = "checkpoint start with its events", .line = checkpoint_start_line("00.04", 3)}, + .expectation = {.line = "[Checkpoint] 00.04: start, 3 events"}, + }, + { + .input = {.name = "attempt", .line = checkpoint_attempt_line("00.04", 2)}, + .expectation = {.line = "[Checkpoint] 00.04: attempt 2"}, + }, + { + .input = {.name = "attempt out of a limit", .line = checkpoint_attempt_line("00.04", 2, 3)}, + .expectation = {.line = "[Checkpoint] 00.04: attempt 2/3"}, + }, + { + .input = {.name = "one-shot pass", .line = checkpoint_pass_line("00.03", 1)}, + .expectation = {.line = "[Checkpoint] 00.03: passed on attempt 1 (one-shot)"}, + }, + { + .input = {.name = "pass after one reset", .line = checkpoint_pass_line("00.04", 2)}, + .expectation = {.line = "[Checkpoint] 00.04: passed on attempt 2 (1 reset)"}, + }, + { + .input = {.name = "pass after resets and recoveries in place", .line = checkpoint_pass_line("00.04", 3, 1)}, + .expectation = {.line = "[Checkpoint] 00.04: passed on attempt 3 (2 resets), 1 in place"}, + }, + { + .input = {.name = "reset", .line = checkpoint_reset_line("00.04", 2)}, + .expectation = {.line = "[Checkpoint] 00.04: failed, resetting for attempt 2"}, + }, + { + .input = {.name = "reload within a segment", .line = segment_reload_line("00", "00.02", 2, 3)}, + .expectation = {.line = "[Segment] 00: 00.02 failed, reloading for attempt 2/3"}, + }, +}; + + +// Counts added to fresh stats, in order. +struct StoryCountsInput{ + std::string name; + std::vector added; +}; + +// The stats after them: counts add up rather than replace. +struct StoryCountsExpectation{ + uint64_t segments; + uint64_t checkpoints; + uint64_t resets; +}; + +// Counts recorded into the AutoStory stats and the totals they must reach. +struct StoryCountsCase{ + StoryCountsInput input; + StoryCountsExpectation expectation; +}; + +class Test_StoryCounts : public UnitTest{ +public: + Test_StoryCounts(StoryCountsCase test_case) + : UnitTest("Pokemon::StoryLog - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + AutoStoryStats stats; + for (const StoryRunCounts& counts : m_case.input.added){ + record_story_counts(stats, counts); + } + const StoryCountsExpectation& expected = m_case.expectation; + if (stats.m_segment != expected.segments || stats.m_checkpoint != expected.checkpoints || stats.m_reset != expected.resets){ + return "Expected " + std::to_string(expected.segments) + " segments, " + std::to_string(expected.checkpoints) + + " checkpoints and " + std::to_string(expected.resets) + " resets, got " + + std::to_string(stats.m_segment) + ", " + std::to_string(stats.m_checkpoint) + + " and " + std::to_string(stats.m_reset); + } + return true; + } + +private: + const StoryCountsCase m_case; +}; + +const StoryCountsCase STORY_COUNTS_CASES[] = { + { + .input = {.name = "a segment's counts in the stats", .added = {{.segments = 1, .checkpoints = 2, .resets = 3}}}, + .expectation = {.segments = 1, .checkpoints = 2, .resets = 3}, + }, + { + .input = { + .name = "a checkpoint loop's counts add up", + .added = {{.segments = 0, .checkpoints = 1, .resets = 0}, {.segments = 0, .checkpoints = 0, .resets = 1}, {.segments = 0, .checkpoints = 1, .resets = 0}}, + }, + .expectation = {.segments = 0, .checkpoints = 2, .resets = 1}, + }, +}; + +} // namespace + + +void add_tests_StoryLog(UnitTestDatabase& database){ + for (const StoryLogCase& test_case : STORY_LOG_CASES){ + database.add(test_case); + } + for (const StoryCountsCase& test_case : STORY_COUNTS_CASES){ + database.add(test_case); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcome.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcome.h new file mode 100644 index 0000000000..a752df6972 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcome.h @@ -0,0 +1,66 @@ +/* Story Outcome + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_StoryEvents.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryOutcome_H +#define PokemonAutomation_Pokemon_StoryOutcome_H + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_StoryLog.h" +#include "Pokemon_StoryPose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How an action or a check ended: empty `failure` is success; otherwise a +// name that recoveries match (e.g. "probe_exhausted"). A succeeded action +// that knows where it left the player sets `pose`; the runner writes it +// into the run before the event's expects are checked. +struct Outcome{ + std::string failure; + std::string detail; + std::optional pose; + // A succeeded action that left the game as it found it: a read, a + // check, a TM the lead already knows. A reload of the same save undoes + // nothing it did. + bool changed_nothing = false; + + bool succeeded() const; +}; +// Constructs a successful event outcome, updating the run pose when given one. +Outcome outcome_ok(std::optional pose = std::nullopt); +// outcome_ok() with `changed_nothing`. +Outcome outcome_unchanged(); +// Constructs a failed event outcome with reason and optional diagnostic detail. +Outcome outcome_failed(std::string failure, std::string detail = ""); +// "probe_exhausted: 4 rows": the failure and its detail, if any. +std::string to_string(const Outcome& outcome); + +// The failure of a step that found the Switch's HOME menu instead of the +// game. Nothing in the story can answer it, as every press goes to the +// console's menus: no recovery runs and no reload, the run stops. +inline constexpr std::string_view GAME_NOT_RUNNING = "game_not_running"; +// GAME_NOT_RUNNING, saying so for the run log. +Outcome outcome_game_not_running(); + + +// Callable action executed for a story event. +using Act = MoveOnlyFunction; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h new file mode 100644 index 0000000000..b9c0eb53db --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h @@ -0,0 +1,79 @@ +/* Story Pose + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_StoryEvents.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryPose_H +#define PokemonAutomation_Pokemon_StoryPose_H + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_StoryLog.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How much of the pose is known. COLUMN and ROW pin one axis (a wall, a +// door); SET means one of the positions the pose holds. +enum class PoseCertainty{ + TILE, + COLUMN, + ROW, + SET, + UNKNOWN, +}; +// Returns the string label for a pose certainty level. +std::string certainty_name(PoseCertainty certainty); + +// Whether a pose known to `have` is good enough for an event that needs `need`. +bool certainty_covers(PoseCertainty have, PoseCertainty need); + +// Where on a map the player is, in the game's own terms: tiles and a +// facing in a 2D game (Pokemon_TilePose.h), a map point or a fly point in +// an open-world one. The engine only carries and prints it; the game's +// actions read it back. +struct Position{ + virtual ~Position() = default; + // The text after the map in a log line, e.g. "(10, 20) facing north"; + // none for a game that has nothing to say beyond the map. + virtual std::string describe() const{ + return ""; + } +}; + +// Where the player is believed to be. The screen is read; the pose is +// tracked, and only an anchor (a wall, a door, an NPC who answered) makes +// it certain. `where` is null until the game learns a position and after +// the pose is lost; it is shared because poses are copied (an event's +// learned pose into the run) and never changed in place. +struct Pose{ + std::string map; + PoseCertainty certainty = PoseCertainty::UNKNOWN; + std::shared_ptr where; +}; +// Formats a Pose as a human-readable string. +std::string to_string(const Pose& pose); + + +// What a run knows. Flags are set only by confirmed effects and are lost +// on a reload. +struct RunState{ + Pose pose; + std::set flags; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.h new file mode 100644 index 0000000000..faa1fcaa0a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.h @@ -0,0 +1,28 @@ +/* Story Run Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The unit tests of the pieces every AutoStory program shares, story + * engine or not: the checkpoint log lines and the range options. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRun_Tests_H +#define PokemonAutomation_Pokemon_StoryRun_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the shared checkpoint log lines and stats counts. +void add_tests_StoryLog(UnitTestDatabase& database); +// 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/AutoStory/Pokemon_StorySegments.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp index ea28de777d..5bd4ded188 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp @@ -6,6 +6,7 @@ #include #include +#include "Pokemon_StoryLog.h" #include "Pokemon_StorySegments.h" namespace PokemonAutomation{ @@ -108,35 +109,9 @@ void tell_failed(SegmentHooks& hooks, const std::string& checkpoint, const Check } } -// The policy's in-place recovery, after each event's own: the game's -// recover hook, if any, then the event again. Counts into `used`. -void add_policy_recoveries(Checkpoint& checkpoint, const SegmentPolicy& policy, SegmentHooks& hooks, size_t& used){ - if (policy.recoveries_per_event == 0){ - return; - } - for (Event& event : checkpoint.events){ - Recovery recovery; - recovery.kind = RecoveryKind::REANCHOR; - recovery.attempts = policy.recoveries_per_event; - recovery.why = "the segment's policy: recover in place before reloading"; - recovery.prepare = [&hooks, &used, name = event.name](RunState& state){ - used++; - return hooks.recover ? hooks.recover(state, name) : outcome_ok(); - }; - event.recoveries.push_back(std::move(recovery)); - } -} - -std::string resets_text(size_t attempts){ - if (attempts == 1){ - return "one-shot"; - } - return std::format("{} reset{}", attempts - 1, attempts == 2 ? "" : "s"); -} - // One row to success, reloading and rebuilding after each failed attempt. // Returns the last attempt's report, or the reload's failure; `run` says -// how many attempts and recoveries it took. +// how many attempts it took. CheckpointReport run_row( RunState& state, const Segment& segment, CheckpointSpec& spec, const SegmentPolicy& policy, SegmentHooks& hooks, SegmentReport& report, CheckpointRun& run @@ -149,34 +124,22 @@ CheckpointReport run_row( return hooks.save ? hooks.save(state) : outcome_failed("no_save_hook"); }; } - add_policy_recoveries(checkpoint, policy, hooks, run.recoveries); EventLogger log = [&hooks](const std::string& line){ say(hooks, line); }; CheckpointReport result = run_checkpoint(state, checkpoint, log); if (result.completed){ run.passed = true; - say(hooks, std::format( - "[Checkpoint] {}: passed on attempt {} ({}){}", - spec.id, attempt, resets_text(attempt), - run.recoveries == 0 ? "" : std::format(", {} in place", run.recoveries) - )); + say(hooks, checkpoint_pass_line(spec.id, attempt)); return result; } tell_failed(hooks, spec.id, result); - if (policy.stop_at_first_failure){ - say(hooks, std::format( - "[Segment] {}: {} failed; stopping at the first failure, the game stays where it failed", - segment.id, spec.id - )); - report.stopped_at_first_failure = true; + if (result.failure.failure == GAME_NOT_RUNNING){ + say(hooks, std::format("[Segment] {}: {} failed; the game is not running, so no reload", segment.id, spec.id)); return result; } if (attempt >= policy.attempts_per_checkpoint){ return result; } - say(hooks, std::format( - "[Segment] {}: {} failed, reloading for attempt {}/{}", - segment.id, spec.id, attempt + 1, policy.attempts_per_checkpoint - )); + say(hooks, segment_reload_line(segment.id, spec.id, attempt + 1, policy.attempts_per_checkpoint)); report.reloads++; Outcome reloaded = reload(state, hooks); if (!reloaded.succeeded()){ @@ -201,19 +164,6 @@ SegmentReport stop_segment(SegmentReport& report, SegmentHooks& hooks, const std } // namespace -bool CheckpointRun::one_shot() const{ - return passed && attempts == 1 && recoveries == 0; -} - -size_t SegmentReport::one_shot_passes() const{ - size_t count = 0; - for (const CheckpointRun& run : runs){ - count += run.one_shot() ? 1 : 0; - } - return count; -} - - SegmentReport run_segment( RunState& state, Segment& segment, const SegmentRange& range, const SegmentPolicy& policy, SegmentHooks& hooks diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h index 95b14bb4a3..b1b1859514 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h @@ -17,11 +17,12 @@ #define PokemonAutomation_Pokemon_StorySegments_H #include -#include #include #include #include "Common/Cpp/MoveOnlyFunction.h" #include "Pokemon_StoryEvents.h" +#include "Pokemon_StoryLog.h" +#include "Types/Pokemon_StorySegmentTypes.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -47,14 +48,10 @@ struct Segment{ // What the game lends the runner: how to save, how to reload the last save // (the run state is emptied first; the reload's Outcome says where the // player stands), and where to log. -// `recover`, if set, is the game's way of recovering in place from a failed -// event (re-anchor on a landmark, close a stray dialogue) before the event -// is tried again; see SegmentPolicy::recoveries_per_event. struct SegmentHooks{ Act save; Act reload; EventLogger log; - MoveOnlyFunction recover; // Optional: each [Segment], [Checkpoint] and [Event] line again, // without its tag ("00.03/2 below_oaks_trigger: start"), for the video // overlay, so whoever watches the stream sees the step under way; and, @@ -67,58 +64,6 @@ struct SegmentHooks{ MoveOnlyFunction failed; }; -// Retry and timeout configuration for story segment execution. -struct SegmentPolicy{ - // Runs of one checkpoint, reloading its save between them, before the - // segment stops. - size_t attempts_per_checkpoint = 3; - // Lab: stop at the first failed attempt without reloading, leaving the - // game where it failed for a look. - bool stop_at_first_failure = false; - // Times each event may recover in place (SegmentHooks::recover, then - // the event again) once its own recoveries are used up, before its - // checkpoint fails and is reloaded. 0 keeps a failure a reload. - size_t recoveries_per_event = 0; -}; - -// The checkpoints to run, by id, both inclusive. An unset end is the -// segment's first or last checkpoint. -struct SegmentRange{ - std::optional from; - std::optional to; -}; - - -// Summary of checkpoint attempts, recoveries, and pass status. -struct CheckpointRun{ - std::string id; - bool passed = false; - size_t attempts = 0; - // In-place recoveries (SegmentPolicy::recoveries_per_event) used, in all attempts. - size_t recoveries = 0; - - bool one_shot() const; -}; - -// Execution results and failure diagnostics for a story segment run. -struct SegmentReport{ - bool completed = false; - // The run stopped at its first failure (SegmentPolicy::stop_at_first_failure). - bool stopped_at_first_failure = false; - // Both empty when nothing failed; the event is empty when a start - // check, an end check, a save or a reload failed. - std::string failed_checkpoint; - std::string failed_event; - Outcome failure; - size_t checkpoints_run = 0; - // Reloads after failed attempts. - size_t reloads = 0; - // Each checkpoint run, in order, the failed one last. - std::vector runs; - - size_t one_shot_passes() const; -}; - // Runs the checkpoints in `range`, in order. Logs through `hooks.log`, // around the checkpoint lines: // [Segment] 00: start, 3 checkpoints @@ -127,7 +72,6 @@ struct SegmentReport{ // [Checkpoint] 00.03: passed on attempt 1 (one-shot) // [Segment] 00: 2 of 3 checkpoints one-shot // [Segment] 00: done, 3 checkpoints -// [Segment] 00: 00.02 failed; stopping at the first failure, the game stays where it failed // [Segment] 00: failed at 00.02 talk_mom: expect_failed: dialogue opened SegmentReport run_segment( RunState& state, Segment& segment, const SegmentRange& range, diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp index 9520afb2d8..c0b28fb38c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp @@ -441,7 +441,7 @@ struct StorySegmentInput{ }; struct StorySegmentExpectation{ - const char* description; + std::string_view description; }; struct StorySegmentTestCase{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp new file mode 100644 index 0000000000..f28e3016f2 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp @@ -0,0 +1,160 @@ +/* Story Step Executor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Pokemon_BuiltinStoryActions.h" +#include "Pokemon_StoryStepExecutor.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +Pose pose_of(const GridPose& pose){ + return tile_pose(pose.map, pose.tiles, pose.facing); +} + +Outcome unsupported_step(const StoryStep& step){ + return outcome_failed("unsupported_step", std::format("{} {}", story_step_kind_name(step.kind), step.name)); +} + + +void StoryStepExecutor::begin_attempt(const StoryCheckpoint&){} + +bool StoryStepExecutor::holds(std::string_view condition, RunState& state){ + return state.flags.contains(std::string(condition)); +} + + +Event story_event(const StoryStep& step, StoryStepExecutor& executor){ + Event event; + event.name = step.name; + event.why = step.why; + for (const std::string& name : step.skip_if){ + event.skip_if.push_back(condition(name, [&executor, name](RunState& state){ + return executor.holds(name, state); + })); + } + event.act = [&executor, &step](RunState& state){ + return executor.run(state, step); + }; + if (step.pose_after){ + event.pose_learned = pose_of(*step.pose_after); + } + return event; +} + +namespace{ + +// The first event of a checkpoint that starts from a save: where the save +// leaves the player, for a run that reloaded it. +Event from_save_event(const Pose& start){ + Event event; + event.name = "from_save"; + event.why = "where the checkpoint's save leaves the player"; + event.act = [](RunState&){ return outcome_ok(); }; + event.pose_learned = start; + return event; +} + +} // namespace + +namespace{ + +// `event`, for a once_per_save step known in `prepared` as `key`: skipped +// while `prepared` has it, and added to it when it succeeds changing +// nothing. +void run_once_per_save(Event& event, std::string key, PreparedSteps& prepared){ + event.skip_if.push_back(condition("done_from_this_save", [&prepared, key](RunState&){ + return prepared.contains(key); + })); + event.act = [act = std::move(event.act), &prepared, key](RunState& state) mutable{ + Outcome outcome = act(state); + if (outcome.succeeded() && outcome.changed_nothing){ + prepared.insert(key); + } + return outcome; + }; +} + +} // namespace + +Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor& executor, PreparedSteps* prepared){ + executor.begin_attempt(data); + Checkpoint checkpoint; + checkpoint.id = data.id; + if (data.start){ + checkpoint.events.push_back(from_save_event(pose_of(*data.start))); + } + for (const StoryStep& step : data.steps){ + checkpoint.events.push_back(story_event(step, executor)); + if (prepared != nullptr && step.once_per_save){ + run_once_per_save(checkpoint.events.back(), data.id + "/" + step.name, *prepared); + } + } + return checkpoint; +} + + +namespace{ + +// What is wrong with a step's action and args, each as a line: a GAME +// step without an action, args that don't fit a built-in action's spec, +// an empty leg. +std::vector action_problems(const StoryStep& step){ + if (step.kind == StoryStepKind::GAME){ + return step.action.empty() ? std::vector{"no action"} : std::vector{}; + } + const StoryActionSpec* spec = find_story_action(builtin_story_actions(), step.kind, step.action); + if (spec == nullptr){ + // A game's own action: the game checks it when it loads the step. + return {}; + } + std::vector problems = story_args_errors(*spec, step.args); + const std::vector* legs = value_if_at_it>(step.args, step.args.find("legs")); + if (legs != nullptr && legs->empty()){ + problems.emplace_back("no legs"); + } + for (const StoryLeg& leg : legs ? *legs : std::vector{}){ + if (leg.tiles <= 0){ + problems.emplace_back("a leg of no tiles"); + } + } + return problems; +} + +} // namespace + +std::vector lint_story_checkpoint(const StoryCheckpoint& data){ + std::vector problems; + if (data.id.empty()){ + problems.emplace_back("a checkpoint has no id"); + } + std::set names; + for (size_t c = 0; c < data.steps.size(); c++){ + const StoryStep& step = data.steps[c]; + const std::string where = std::format("{} step {}", data.id, c + 1); + if (step.name.empty()){ + problems.emplace_back(where + ": no name"); + }else if (!names.insert(step.name).second){ + problems.emplace_back(std::format("{}: a second step named {}", where, step.name)); + } + for (const std::string& problem : action_problems(step)){ + problems.emplace_back(std::format("{} {}: {} {}", where, step.name, story_step_kind_name(step.kind), problem)); + } + // skip_if's conditions must all hold; once per save is one more. + if (step.once_per_save && !step.skip_if.empty()){ + problems.emplace_back(std::format("{} {}: once per save with skip_if", where, step.name)); + } + } + return problems; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h new file mode 100644 index 0000000000..0d8c595bfa --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h @@ -0,0 +1,107 @@ +/* Story Step Executor + * + * From: https://github.com/PokemonAutomation/ + * + * One vocabulary of story steps for the tile games (FRLG, BDSP): a route, + * a fixed walk, a step onto a trigger, a talk, a YES/NO, a scene, a + * battle, the nurse, a shop, a save, and so on. A checkpoint is a list of + * such steps, plain data (Types/), so a game's story is a table its unit + * tests can plan without a console. + * + * build_story_checkpoint() turns a table row into engine events + * (Pokemon_StoryEvents.h). Each event's action asks the game's + * StoryStepExecutor to do its step; a game implements the kinds it uses, + * and a step it has no way of doing fails by name (unsupported_step()) + * instead of doing something else. + * + * Steps never match dialogue or menu text: they look for screen state (a + * dialogue box, an arrow, a fade, a battle menu, colours, positions). The + * few reads that need text (item names in a shop or the Bag) take the + * game's language from the program's options (StoryRunOptions), and with + * no reader for it fall back to checks that need none (a row's position, + * digits, a changed screen), so a run never fails because its language + * is not supported. + * + * Poses are the game's own (Pose, with a TilePose for these games): a + * checkpoint's start, a scene's end and a route's target are poses, and + * an executor that knows where a step left the player says so in its + * Outcome, which the engine writes into the run. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepExecutor_H +#define PokemonAutomation_Pokemon_StoryStepExecutor_H + +#include +#include +#include +#include +#include "Pokemon_StoryEvents.h" +#include "Pokemon_TilePose.h" +#include "Types/Pokemon_GridPose.h" +#include "Types/Pokemon_StoryCheckpoint.h" +#include "Types/Pokemon_StoryStep.h" +#include "Types/Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How a game does its story steps: an interface with no data. run() is the +// game's: it does the step's kind its own way (FRLG and BDSP bind kinds and +// variants to actions in a table), and returns unsupported_step() for a +// kind it has no way of doing. +class StoryStepExecutor{ +public: + virtual ~StoryStepExecutor() = default; + + // A checkpoint is being built for a new attempt: build_story_checkpoint() + // calls this first, so a game can start the attempt afresh (trainers + // who can see us again, the row's own settings). Does nothing by default. + virtual void begin_attempt(const StoryCheckpoint& data); + + // Does `step`, from the run so far. + virtual Outcome run(RunState& state, const StoryStep& step) = 0; + + // Whether the condition named in a step's skip_if holds: by default, + // whether the run has the flag (set by an earlier step's action). + virtual bool holds(std::string_view condition, RunState& state); +}; + +// `pose` as the engine's Pose: a TilePose, TILE for one tile, SET for several. +Pose pose_of(const GridPose& pose); + +// "unsupported_step: TRAIN train_in_grass": what an executor without the kind returns. +Outcome unsupported_step(const StoryStep& step); + + +// The step as an event that runs it with `executor`. Both must outlive +// the event. +Event story_event(const StoryStep& step, StoryStepExecutor& executor); + +// The once_per_save steps done from the save the game is on that changed +// nothing, as "/". The game keeps it across reloads and +// empties it when it saves or loads another save. +using PreparedSteps = std::set; + +// The checkpoint `data` as events: "from_save" first when it has a start +// (the start pose, for a run that reloaded its save), then one event per +// step. `data` and `executor` must outlive the checkpoint. Saving is the +// game's: it sets the checkpoint's save, or adds a SAVE step. +// With `prepared`, each once_per_save step is skipped while `prepared` has +// it, and added to it when it succeeds changing nothing; `prepared` must +// then outlive the checkpoint. Without, once_per_save steps run every time. +Checkpoint build_story_checkpoint( + const StoryCheckpoint& data, StoryStepExecutor& executor, PreparedSteps* prepared = nullptr +); + +// Problems an author should fix before running: an empty id, unnamed or +// repeated steps, a GAME step without an action, a built-in action's args +// that don't fit its spec (a route without a target), empty legs. +std::vector lint_story_checkpoint(const StoryCheckpoint& data); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp similarity index 78% rename from SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp rename to SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp index e61a1eeb95..4aab90ad2a 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp @@ -14,14 +14,18 @@ #include #include #include +#include #include #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_StoryEvents.h" +#include "Pokemon_BuiltinStoryActions.h" #include "Pokemon_StorySegments.h" -#include "Pokemon_StorySteps.h" +#include "Pokemon_StoryStepExecutor.h" #include "Pokemon_TilePose.h" #include "Pokemon_AutoStory_Tests.h" @@ -37,7 +41,7 @@ namespace{ class FakeExecutor : public StoryStepExecutor{ public: std::vector trace; - std::set conditions; + std::set> conditions; // Steps by name that always fail, and how. std::set failing; // Steps by name that fail this many more times, then pass. @@ -64,43 +68,56 @@ class FakeExecutor : public StoryStepExecutor{ left--; return outcome_failed("blocked", step.name + " was blocked"); } - return StoryStepExecutor::run(state, step); + return run_kind(state, step); } - virtual bool holds(const std::string& condition, RunState& state) override{ + + virtual bool holds(std::string_view condition, RunState& state) override{ return conditions.contains(condition) || StoryStepExecutor::holds(condition, state); } -protected: - virtual Outcome route(RunState&, const StoryStep& step) override{ - return outcome_ok(*step.target); +private: + // The kinds this world has; any other is unsupported. + Outcome run_kind(RunState& state, const StoryStep& step){ + switch (step.kind){ + case StoryStepKind::ROUTE: + return outcome_ok(pose_of(story_arg(step.args, "target"))); + case StoryStepKind::STEP: + return step_one_tile(state, step); + case StoryStepKind::TALK: + case StoryStepKind::MASH: + return outcome_ok(); + case StoryStepKind::BATTLE: + // The first battle is lost; a step that may lose goes on. + return story_arg(step.args, "may_lose") ? outcome_ok() : outcome_failed("blackout"); + case StoryStepKind::SHOP: + return shop(step); + case StoryStepKind::GAME: + return game(state, step); + default: + return unsupported_step(step); + } } - virtual Outcome step(RunState& state, const StoryStep& step) override{ + + Outcome step_one_tile(RunState& state, const StoryStep& step){ const std::vector tiles = tiles_of(state.pose); if (tiles.size() != 1){ return outcome_failed("no_pose", to_string(state.pose)); } - return outcome_ok(tile_pose(state.pose.map, {tiles[0].next(step.direction)}, step.direction)); - } - virtual Outcome talk(RunState&, const StoryStep&) override{ - return outcome_ok(); - } - virtual Outcome mash(RunState&, const StoryStep&) override{ - return outcome_ok(); - } - virtual Outcome battle(RunState&, const StoryStep& step) override{ - // The first battle is lost; a step that may lose goes on. - return step.may_lose ? outcome_ok() : outcome_failed("blackout"); + const Direction direction = story_arg(step.args, "direction"); + return outcome_ok(tile_pose(state.pose.map, {tiles[0].next(direction)}, direction)); } - virtual Outcome shop(RunState&, const StoryStep& step) override{ - for (const StoryItem& item : step.items){ + + Outcome shop(const StoryStep& step){ + for (const StoryItem& item : story_arg>(step.args, "items")){ trace.push_back(" bought " + std::to_string(item.quantity) + " " + item.item); } return outcome_ok(); } - // A game step sets a run flag named for its variant. - virtual Outcome game(RunState& state, const StoryStep& step) override{ - trace.push_back(" game " + step.variant); - state.flags.insert(step.variant); + + // A game step sets a run flag named for its action. + Outcome game(RunState& state, const StoryStep& step){ + trace.push_back(" game " + step.action); + state.flags.insert(step.action); return unchanged.contains(step.name) ? outcome_unchanged() : outcome_ok(); } }; @@ -109,22 +126,31 @@ StoryStep make(StoryStepKind kind, std::string name){ StoryStep step; step.kind = kind; step.name = std::move(name); + // As loading it would: the kind's built-in action's fallbacks. + if (const StoryActionSpec* spec = find_story_action(builtin_story_actions(), kind, "")){ + step.args = with_fallbacks(*spec, {}); + } return step; } -StoryStep route_to(std::string name, Pose target){ +// A grid pose on one tile. +GridPose grid(std::string map, TilePos tile, Direction facing){ + return GridPose{.map = std::move(map), .tiles = {tile}, .facing = facing}; +} + +StoryStep route_to(std::string name, GridPose target){ StoryStep step = make(StoryStepKind::ROUTE, std::move(name)); - step.target = std::move(target); + step.args = {{"target", std::move(target)}, {"fight_wild", false}}; return step; } StoryStep step_into(std::string name, Direction direction){ StoryStep step = make(StoryStepKind::STEP, std::move(name)); - step.direction = direction; + step.args = {{"direction", direction}}; return step; } -StoryStep scene(std::string name, std::optional pose_after){ +StoryStep scene(std::string name, std::optional pose_after){ StoryStep step = make(StoryStepKind::MASH, std::move(name)); step.pose_after = std::move(pose_after); return step; @@ -134,17 +160,17 @@ StoryStep scene(std::string name, std::optional pose_after){ // talk, a shop, a game step. StoryCheckpoint lab_checkpoint(){ StoryStep shop = make(StoryStepKind::SHOP, "potions"); - shop.items = {{.item = "potion", .quantity = 5}, {.item = "antidote", .quantity = 3}}; + shop.args = {{"items", std::vector{{.item = "potion", .quantity = 5}, {.item = "antidote", .quantity = 3}}}}; StoryStep game = make(StoryStepKind::GAME, "dance"); - game.variant = "dance"; + game.action = "dance"; return StoryCheckpoint{ .id = "00.03", .title = "to the lab", - .start = tile_pose("Town", {{6, 8}}, Direction::SOUTH), + .start = grid("Town", {6, 8}, Direction::SOUTH), .steps = { - route_to("below_trigger", tile_pose("Town", {{12, 2}}, Direction::NORTH)), + route_to("below_trigger", grid("Town", {12, 2}, Direction::NORTH)), step_into("trigger", Direction::NORTH), - scene("to_the_lab", tile_pose("Lab", {{6, 4}}, Direction::NORTH)), + scene("to_the_lab", grid("Lab", {6, 4}, Direction::NORTH)), make(StoryStepKind::TALK, "talk_oak"), shop, game, @@ -166,7 +192,7 @@ Run run(const StoryCheckpoint& data, StoryStepExecutor& executor){ return ret; } -std::string joined(const std::vector& lines){ +std::string joined(std::span lines){ std::string text; for (const std::string& line : lines){ text += "\n " + line; @@ -281,14 +307,14 @@ UnitTestResult test_failure_names_the_step(){ UnitTestResult test_unsupported_and_lost_battles(){ // The fake has no TRAIN, and loses battles a step may not lose. StoryStep train = make(StoryStepKind::TRAIN, "train"); - train.battles = 3; + train.args = {{"battles", int64_t(3)}}; FakeExecutor executor; Run result = run(StoryCheckpoint{.id = "01", .title = "", .start = std::nullopt, .steps = {train}}, executor); if (result.report.completed || result.report.failure.failure != "unsupported_step" || result.report.failure.detail != "TRAIN train"){ return "Expected TRAIN unsupported:" + joined(result.lines); } StoryStep rival = make(StoryStepKind::BATTLE, "rival"); - rival.may_lose = true; + rival.args = {{"may_lose", true}}; StoryStep brock = make(StoryStepKind::BATTLE, "brock"); result = run(StoryCheckpoint{.id = "02", .title = "", .start = std::nullopt, .steps = {rival, brock}}, executor); if (result.report.completed || result.report.failed_name != "brock" || result.report.failure.failure != "blackout"){ @@ -300,7 +326,7 @@ UnitTestResult test_unsupported_and_lost_battles(){ // Runs `tables` as one segment whose saves and reloads go into the // executor's trace and whose log lines go into `lines`. Whatever blocked a // step has gone by the reload. -SegmentReport run_tables(const std::vector& tables, FakeExecutor& executor, std::vector& lines){ +SegmentReport run_tables(std::span tables, FakeExecutor& executor, std::vector& lines){ Segment segment; segment.id = "00"; for (const StoryCheckpoint& data : tables){ @@ -333,7 +359,7 @@ UnitTestResult test_segment_of_tables(){ StoryCheckpoint{ .id = "00.04", .title = "the parcel", - .start = tile_pose("Lab", {{6, 4}}, Direction::NORTH), + .start = grid("Lab", {6, 4}, Direction::NORTH), .steps = {make(StoryStepKind::TALK, "give_parcel")}, }, }; @@ -356,7 +382,7 @@ UnitTestResult test_segment_of_tables(){ && report.runs[0].one_shot() && report.runs[0].attempts == 1 && !report.runs[1].one_shot() && report.runs[1].attempts == 2 && report.runs[1].passed && report.one_shot_passes() == 1; - const auto has = [&lines](const std::string& line){ + const auto has = [&lines](std::string_view line){ return std::find(lines.begin(), lines.end(), line) != lines.end(); }; if (!runs_ok @@ -371,14 +397,14 @@ UnitTestResult test_segment_of_tables(){ // The two tables of test_segment_of_tables() as a segment run by `executor`, -// with hooks that write saves, reloads and recoveries into its trace. +// with hooks that write saves and reloads into its trace. struct PolicyLab{ std::vector tables{ lab_checkpoint(), StoryCheckpoint{ .id = "00.04", .title = "the parcel", - .start = tile_pose("Lab", {{6, 4}}, Direction::NORTH), + .start = grid("Lab", {6, 4}, Direction::NORTH), .steps = {make(StoryStepKind::TALK, "give_parcel")}, }, }; @@ -403,18 +429,14 @@ struct PolicyLab{ executor.trace.push_back("reload"); return outcome_ok(); }; - hooks.recover = [this](RunState&, const std::string& event){ - executor.trace.push_back("recover " + event); - return outcome_ok(); - }; hooks.log = [this](const std::string& line){ lines.push_back(line); }; RunState state; return run_segment(state, segment, SegmentRange{}, policy, hooks); } - bool has(const std::string& line) const{ + bool has(std::string_view line) const{ return std::find(lines.begin(), lines.end(), line) != lines.end(); } - size_t count(const std::string& item) const{ + size_t count(std::string_view item) const{ return (size_t)std::count(executor.trace.begin(), executor.trace.end(), item); } }; @@ -436,38 +458,15 @@ UnitTestResult test_policy_attempts_then_fail(){ UnitTestResult test_policy_stop_at_first_failure(){ PolicyLab lab; lab.executor.failing = {"give_parcel"}; - const SegmentReport report = lab.run(SegmentPolicy{.stop_at_first_failure = true}); - if (report.completed || !report.stopped_at_first_failure || report.reloads != 0 || lab.count("reload") != 0 + const SegmentReport report = lab.run(SegmentPolicy{.attempts_per_checkpoint = 1}); + if (report.completed || report.reloads != 0 || lab.count("reload") != 0 || lab.count("TALK give_parcel") != 1 - || !lab.has("[Segment] 00: 00.04 failed; stopping at the first failure, the game stays where it failed") ){ return "Expected a stop at the first failure, with no reload:" + joined(lab.executor.trace) + joined(lab.lines); } return true; } -UnitTestResult test_policy_recovers_in_place(){ - // The talk fails twice; two recoveries in place get it through - // without a reload, but not one-shot. - PolicyLab lab; - lab.executor.failures_left = {{"give_parcel", 2}}; - const SegmentReport report = lab.run(SegmentPolicy{.recoveries_per_event = 2}); - if (!report.completed || report.reloads != 0 || lab.count("recover give_parcel") != 2 - || report.runs.size() != 2 || report.runs[1].recoveries != 2 || report.runs[1].one_shot() - || !lab.has("[Checkpoint] 00.04: passed on attempt 1 (one-shot), 2 in place") - ){ - return "Expected 00.04 recovered in place twice:" + joined(lab.executor.trace) + joined(lab.lines); - } - // Past the budget, the checkpoint is reloaded as before. - PolicyLab reloaded; - reloaded.executor.failures_left = {{"give_parcel", 2}}; - const SegmentReport second = reloaded.run(SegmentPolicy{.recoveries_per_event = 1}); - if (!second.completed || second.reloads != 1 || second.runs[1].attempts != 2){ - return "Expected a reload once the in-place budget was used:" + joined(reloaded.executor.trace) + joined(reloaded.lines); - } - return true; -} - // A boss's checkpoint: a TEACH of a move the lead knows (changes // nothing), a TEACH that teaches, both once per save, then the battle, // lost on the first attempt. The segment's saves empty `prepared`. @@ -475,7 +474,7 @@ struct BossLab{ StoryCheckpoint table{ .id = "00.15b", .title = "the rival", - .start = tile_pose("Cerulean", {{23, 7}}, Direction::NORTH), + .start = grid("Cerulean", {23, 7}, Direction::NORTH), .steps = {once("teach_known"), once("teach_new"), make(StoryStepKind::BATTLE, "rival")}, }; FakeExecutor executor; @@ -484,7 +483,7 @@ struct BossLab{ static StoryStep once(std::string name){ StoryStep step = make(StoryStepKind::GAME, name); - step.variant = name; + step.action = name; step.once_per_save = true; return step; } @@ -496,7 +495,7 @@ struct BossLab{ segment.id = "00"; segment.checkpoints.push_back(CheckpointSpec{ .id = table.id, .title = table.title, .saves = true, - .build = [this]{ return build_story_checkpoint(table, executor, prepared); }, + .build = [this]{ return build_story_checkpoint(table, executor, &prepared); }, }); return segment; } @@ -514,7 +513,7 @@ struct BossLab{ hooks.log = [this](const std::string& line){ lines.push_back(line); }; return hooks; } - size_t count(const std::string& item) const{ + size_t count(std::string_view item) const{ return (size_t)std::count(executor.trace.begin(), executor.trace.end(), item); } }; @@ -525,7 +524,7 @@ struct BossLab{ UnitTestResult test_once_per_save_retry(){ BossLab lab; StoryStep battle = make(StoryStepKind::BATTLE, "rival"); - battle.may_lose = true; + battle.args = {{"may_lose", true}}; lab.table.steps.back() = battle; lab.executor.failures_left = {{"rival", 1}}; Segment segment = lab.segment(); @@ -548,7 +547,7 @@ UnitTestResult test_once_per_save_retry(){ UnitTestResult test_once_per_save_verify(){ BossLab lab; StoryStep battle = make(StoryStepKind::BATTLE, "rival"); - battle.may_lose = true; + battle.args = {{"may_lose", true}}; lab.table.steps.back() = battle; Segment segment = lab.segment(); SegmentHooks hooks = lab.hooks(); @@ -577,32 +576,6 @@ UnitTestResult test_once_per_save_verify(){ } -// The checks level: THOROUGH by default, and what the program sets is -// what a step reads. -UnitTestResult test_checks_level(){ - class CheckingExecutor : public FakeExecutor{ - public: - std::vector seen; - virtual Outcome talk(RunState&, const StoryStep& step) override{ - seen.push_back(step.name + " " + story_checks_name(checks())); - return outcome_ok(); - } - }; - StoryCheckpoint data = lab_checkpoint(); - CheckingExecutor executor; - run(data, executor); - executor.set_checks(StoryChecks::FAST); - executor.set_language(Language::Korean); - run(data, executor); - if (executor.language() != Language::Korean){ - return "Expected the language set on the executor."; - } - if (executor.seen != std::vector{"talk_oak thorough", "talk_oak fast"}){ - return "Expected the talk to read thorough, then fast:" + joined(executor.seen); - } - return true; -} - // Two sections of a story, as BDSP has segments 00 and 01. const std::vector& two_sections(){ static const std::vector rows{ @@ -612,8 +585,15 @@ const std::vector& two_sections(){ }; return rows; } + const StringSelectDatabase& two_sections_database(){ - static const StringSelectDatabase database = story_checkpoint_database(two_sections()); + 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; } @@ -638,7 +618,7 @@ UnitTestResult test_checkpoint_dropdowns(){ ){ return "Unexpected label."; } - StoryRunOptions options(database); + 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."; } @@ -655,12 +635,12 @@ UnitTestResult test_story_stats(){ SegmentReport report; report.reloads = 2; report.runs = { - CheckpointRun{.id = "00.03", .passed = true, .attempts = 1, .recoveries = 0}, - CheckpointRun{.id = "00.04", .passed = true, .attempts = 3, .recoveries = 0}, - CheckpointRun{.id = "00.05", .passed = false, .attempts = 1, .recoveries = 0}, + CheckpointRun{.id = "00.03", .passed = true, .attempts = 1}, + CheckpointRun{.id = "00.04", .passed = true, .attempts = 3}, + CheckpointRun{.id = "00.05", .passed = false, .attempts = 1}, }; AutoStoryStats stats; - record_story_stats(stats, report); + record_story_counts(stats, report.story_counts()); if (stats.m_segment != 1 || stats.m_checkpoint != 2 || stats.m_reset != 2){ return "Expected 1 segment, 2 checkpoints and 2 resets."; } @@ -670,13 +650,13 @@ UnitTestResult test_story_stats(){ // The program's option group: 3 attempts, no stop, Thorough, by default; // Fast when chosen. UnitTestResult test_run_options(){ - StoryRunOptions options(two_sections_database()); + StoryRunOptions options(two_sections_database(), Gen8ToGen9Languages_Database()); const SegmentPolicy policy = options.policy(); - if (policy.attempts_per_checkpoint != 3 || policy.stop_at_first_failure || options.checks() != StoryChecks::THOROUGH){ + 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(StoryChecks::FAST); - if (options.checks() != StoryChecks::FAST){ + 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. @@ -693,7 +673,7 @@ UnitTestResult test_run_options(){ // 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()); + StoryRunOptions options(two_sections_database(), Gen8ToGen9Languages_Database()); if (options.VERIFY.policy()){ return "Expected verify mode off by default."; } @@ -718,16 +698,16 @@ UnitTestResult test_lint(){ StoryStep no_target = make(StoryStepKind::ROUTE, "walk"); StoryStep again = make(StoryStepKind::TALK, "walk"); StoryStep bad_legs = make(StoryStepKind::LEGS, "legs"); - bad_legs.legs = {{.direction = Direction::NORTH, .tiles = 0}}; + bad_legs.args = {{"legs", std::vector{{.direction = Direction::NORTH, .tiles = 0}}}, {"fight_wild", false}}; StoryStep no_variant = make(StoryStepKind::GAME, ""); const StoryCheckpoint data{.id = "", .title = "", .start = std::nullopt, .steps = {no_target, again, bad_legs, no_variant}}; const std::vector expected{ "a checkpoint has no id", - " step 1 walk: ROUTE no target", + " step 1 walk: ROUTE missing argument \"target\" (where to go; with several tiles, any of them)", " step 2: a second step named walk", " step 3 legs: LEGS a leg of no tiles", " step 4: no name", - " step 4 : GAME no variant", + " step 4 : GAME no action", }; const std::vector problems = lint_story_checkpoint(data); if (problems != expected){ @@ -746,7 +726,7 @@ struct StoryStepInput{ }; struct StoryStepExpectation{ - const char* description; + std::string_view description; }; struct StoryStepTestCase{ @@ -754,10 +734,10 @@ struct StoryStepTestCase{ StoryStepExpectation expectation; }; -class Test_StorySteps : public UnitTest{ +class Test_StoryStepExecutor : public UnitTest{ public: - explicit Test_StorySteps(StoryStepTestCase scenario) - : UnitTest("Pokemon::StorySteps - " + scenario.input.name) + explicit Test_StoryStepExecutor(StoryStepTestCase scenario) + : UnitTest("Pokemon::StoryStepExecutor - " + scenario.input.name) , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -797,10 +777,6 @@ const StoryStepTestCase STORY_STEP_CASES[] = { .input = {.name = "lint", .test = test_lint}, .expectation = {.description = "verifies lint validation rules on story checkpoints"}, }, - { - .input = {.name = "the checks level reaches the steps", .test = test_checks_level}, - .expectation = {.description = "transfers checks granularity option to step execution"}, - }, { .input = {.name = "the run options' defaults", .test = test_run_options}, .expectation = {.description = "validates initial default story run option values"}, @@ -822,12 +798,8 @@ const StoryStepTestCase STORY_STEP_CASES[] = { .expectation = {.description = "enforces max checkpoint attempt policy before terminal failure"}, }, { - .input = {.name = "policy: stop at the first failure", .test = test_policy_stop_at_first_failure}, - .expectation = {.description = "halts execution immediately when stop_at_first_failure is enabled"}, - }, - { - .input = {.name = "policy: recover in place before reloading", .test = test_policy_recovers_in_place}, - .expectation = {.description = "applies in-place recovery handler prior to reloading save"}, + .input = {.name = "policy: one attempt stops at the first failure", .test = test_policy_stop_at_first_failure}, + .expectation = {.description = "halts without a reload when a checkpoint has one attempt"}, }, { .input = {.name = "once per save: a retry skips what changed nothing", .test = test_once_per_save_retry}, @@ -842,9 +814,9 @@ const StoryStepTestCase STORY_STEP_CASES[] = { } // namespace -void add_tests_StorySteps(UnitTestDatabase& database){ +void add_tests_StoryStepExecutor(UnitTestDatabase& database){ for (const auto& scenario : STORY_STEP_CASES){ - database.add(scenario); + database.add(scenario); } } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.h deleted file mode 100644 index d58fd9828c..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.h +++ /dev/null @@ -1,26 +0,0 @@ -/* Story Step JSON - * From: https://github.com/PokemonAutomation/ - */ -#ifndef PokemonAutomation_StoryStepJson_H -#define PokemonAutomation_StoryStepJson_H -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "Pokemon_StorySteps.h" -namespace PokemonAutomation{ -namespace Pokemon{ -// Lossless tile-game pose data, including uncertainty and absent position/facing. -// An unsupported Position subtype fails instead of being converted to unknown. -JsonValue story_pose_json(const Pose& pose); -// Read a tile-game pose; malformed fields and unsupported position tags fail. -Pose read_story_pose(const JsonValue& value, std::string_view source); -// Encode every shared step field. This does not bind or execute an action. -JsonValue story_step_json(const StoryStep& step); -// Read the shared step record; unknown fields/kinds and invalid values fail. -StoryStep read_story_step(const JsonValue& value, std::string_view source); -// Encode the common checkpoint; game adapters supply the shared policy/state envelope. -JsonValue story_checkpoint_json(const StoryCheckpoint& checkpoint); -// Read only the common checkpoint record, retaining ordered steps and start belief. -StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view source); -} // namespace Pokemon -} // namespace PokemonAutomation -#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp deleted file mode 100644 index 021b18f508..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/* Story Step JSON Tests - * From: https://github.com/PokemonAutomation/ - */ -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Pokemon_StoryStepJson.h" -#ifndef PA_STORY_DATA_STANDALONE -#include "Pokemon_AutoStory_Tests.h" -#endif -namespace PokemonAutomation{ -namespace Pokemon{ -namespace{ -enum class Record{ POSE, STEP, CHECKPOINT }; -struct WireInput{ - std::string_view name; - Record record = Record::STEP; - std::string_view json; -}; -struct WireExpectation{ - std::string_view canonical = {}; - bool rejected = false; -}; -struct WireCase{ - WireInput input; - WireExpectation expectation; -}; -const WireCase CASES[] = { - {.input = {.name = "default fields", .json = R"({"id":"talk","kind":"talk"})"}, .expectation = {.canonical = R"({"id":"talk","kind":"talk"})"}}, - {.input = {.name = "all shared fields", .json = R"({"id":"all","kind":"game_action","why":"source reason","direction":"west","legs":[{"direction":"south","tiles":0}],"fight_wild":true,"yes":false,"may_lose":true,"battles":3,"items":[{"item":"potion","quantity":0}],"variant":"profile","skip_if":["flag"],"target":{"map":"A","certainty":"unknown","where":{"kind":"unknown"}},"declared_after":{"map":"B","certainty":"set","where":{"kind":"tiles","tiles":[[0,0],[1,0]],"facing":"east"}}})"}, .expectation = {.canonical = R"({"id":"all","kind":"game_action","why":"source reason","direction":"west","legs":[{"direction":"south","tiles":0}],"fight_wild":true,"yes":false,"may_lose":true,"battles":3,"items":[{"item":"potion","quantity":0}],"variant":"profile","skip_if":["flag"],"target":{"map":"A","certainty":"unknown","where":{"kind":"unknown"}},"declared_after":{"map":"B","certainty":"set","where":{"kind":"tiles","tiles":[[0,0],[1,0]],"facing":"east"}}})"}}, - {.input = {.name = "unknown facing stays absent", .record = Record::POSE, .json = R"({"map":"M","certainty":"tile","where":{"kind":"tiles","tiles":[[0,0]]}})"}, .expectation = {.canonical = R"({"map":"M","certainty":"tile","where":{"kind":"tiles","tiles":[[0,0]]}})"}}, - {.input = {.name = "empty position differs from no position", .record = Record::POSE, .json = R"({"map":"M","certainty":"unknown","where":{"kind":"tiles","tiles":[]}})"}, .expectation = {.canonical = R"({"map":"M","certainty":"unknown","where":{"kind":"tiles","tiles":[]}})"}}, - {.input = {.name = "ordered checkpoint", .record = Record::CHECKPOINT, .json = R"({"id":"00.05","title":"Parcel","events":[{"id":"first","kind":"route"},{"id":"second","kind":"scene"}]})"}, .expectation = {.canonical = R"({"id":"00.05","title":"Parcel","events":[{"id":"first","kind":"route"},{"id":"second","kind":"scene"}]})"}}, - {.input = {.name = "unknown field", .json = R"({"id":"a","kind":"talk","mystery":0})"}, .expectation = {.rejected = true}}, - {.input = {.name = "unknown action", .json = R"({"id":"a","kind":"magic"})"}, .expectation = {.rejected = true}}, - {.input = {.name = "negative count", .json = R"({"id":"a","kind":"train","battles":-1})"}, .expectation = {.rejected = true}}, - {.input = {.name = "boolean count", .json = R"({"id":"a","kind":"train","battles":false})"}, .expectation = {.rejected = true}}, - {.input = {.name = "wrong bool", .json = R"({"id":"a","kind":"answer","yes":0})"}, .expectation = {.rejected = true}}, - {.input = {.name = "unknown position", .record = Record::POSE, .json = R"({"map":"M","certainty":"unknown","where":{"kind":"gps"}})"}, .expectation = {.rejected = true}}, - {.input = {.name = "bad coordinate", .record = Record::POSE, .json = R"({"map":"M","certainty":"tile","where":{"kind":"tiles","tiles":[[0,true]]}})"}, .expectation = {.rejected = true}}, - {.input = {.name = "duplicate events", .record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[{"id":"a","kind":"talk"},{"id":"a","kind":"talk"}]})"}, .expectation = {.rejected = true}}, -}; - -JsonValue round_trip(const WireInput& input){ - const JsonValue value = parse_json(std::string(input.json)); - switch (input.record){ - case Record::POSE: return story_pose_json(read_story_pose(value, input.name)); - case Record::STEP: return story_step_json(read_story_step(value, input.name)); - case Record::CHECKPOINT: return story_checkpoint_json(read_story_checkpoint(value, input.name)); - } - throw ParseException("Unknown test record."); -} - -std::string check_case(const WireCase& test){ - try{ - const JsonValue actual = round_trip(test.input); - if (test.expectation.rejected){ - return "Expected rejection, read accepted record."; - } - const JsonValue expected = parse_json(std::string(test.expectation.canonical)); - if (!(actual == expected)){ - return "Expected " + expected.dump() + ", read " + actual.dump(); - } - }catch (const ParseException& error){ - return test.expectation.rejected ? "" : "Unexpected parse failure: " + error.message(); - } - return ""; -} -#ifdef PA_STORY_DATA_STANDALONE -Record record_kind(const std::string& name){ - if (name == "pose"){ - return Record::POSE; - } - if (name == "step"){ - return Record::STEP; - } - if (name == "checkpoint"){ - return Record::CHECKPOINT; - } - throw ParseException("Unsupported shared case record kind."); -} - -int check_shared_file(const std::string& filename){ - const JsonValue document = load_json_file(filename); - const JsonObject& root = document.to_object_throw(filename); - if (root.get_string_throw("format") != "pokesim-story-wire-cases/1"){ - throw ParseException("Unsupported story wire case format."); - } - int failed = 0; - for (const JsonValue& value : root.get_array_throw("cases")){ - const JsonObject& row = value.to_object_throw(filename); - const JsonObject& input = row.get_object_throw("input"); - const JsonObject& expected = row.get_object_throw("expectation"); - const std::string source = input.get_value_throw("value").dump(); - const JsonValue* normalized = expected.get_value("canonical"); - const std::string canonical = normalized ? normalized->dump() : ""; - const JsonValue* rejected = expected.get_value("rejected"); - const WireCase test{ - .input = {.name = input.get_string_throw("name"), .record = record_kind(input.get_string_throw("record")), .json = source}, - .expectation = {.canonical = canonical, .rejected = rejected && rejected->to_boolean_throw()}, - }; - const std::string error = check_case(test); - if (!error.empty()){ - std::cerr << test.input.name << ": " << error << '\n'; - failed++; - } - } - std::cout << "Checked " << root.get_array_throw("cases").size() << " shared story records.\n"; - return failed != 0; -} -#endif - -#ifndef PA_STORY_DATA_STANDALONE -class StoryJsonTest : public UnitTest{ -public: - explicit StoryJsonTest(WireCase test) - : UnitTest("Pokemon::StoryStepJson - " + std::string(test.input.name)), m_case(test){} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const std::string error = check_case(m_case); - return error.empty() ? UnitTestResult(true) : UnitTestResult(error); - } -private: - WireCase m_case; -}; -#endif -} // namespace -#ifndef PA_STORY_DATA_STANDALONE -void add_tests_StoryStepJson(UnitTestDatabase& database){ - for (const WireCase& test : CASES){ - database.add(test); - } -} -#endif -} // namespace Pokemon -} // namespace PokemonAutomation -#ifdef PA_STORY_DATA_STANDALONE -int main(int argc, char** argv){ - if (argc == 2){ - return PokemonAutomation::Pokemon::check_shared_file(argv[1]); - } - int failed = 0; - for (const auto& test : PokemonAutomation::Pokemon::CASES){ - const std::string error = PokemonAutomation::Pokemon::check_case(test); - std::cout << test.input.name << ": " << (error.empty() ? "PASS" : error) << '\n'; - failed += !error.empty(); - } - return failed != 0; -} -#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp deleted file mode 100644 index 3004ba6013..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp +++ /dev/null @@ -1,325 +0,0 @@ -/* Story Steps - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Pokemon_StorySteps.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -const char* story_step_kind_name(StoryStepKind kind){ - switch (kind){ - case StoryStepKind::NEW_GAME: - return "NEW_GAME"; - case StoryStepKind::OPTIONS: - return "OPTIONS"; - case StoryStepKind::ROUTE: - return "ROUTE"; - case StoryStepKind::LEGS: - return "LEGS"; - case StoryStepKind::STEP: - return "STEP"; - case StoryStepKind::TALK: - return "TALK"; - case StoryStepKind::ANSWER: - return "ANSWER"; - case StoryStepKind::MASH: - return "MASH"; - case StoryStepKind::BATTLE: - return "BATTLE"; - case StoryStepKind::TRAIN: - return "TRAIN"; - case StoryStepKind::HEAL: - return "HEAL"; - case StoryStepKind::SHOP: - return "SHOP"; - case StoryStepKind::SAVE: - return "SAVE"; - case StoryStepKind::READY: - return "READY"; - case StoryStepKind::GAME: - return "GAME"; - } - return "?"; -} - - -const char* story_checks_name(StoryChecks checks){ - switch (checks){ - case StoryChecks::THOROUGH: - return "thorough"; - case StoryChecks::FAST: - return "fast"; - } - return "?"; -} - - -Outcome unsupported_step(const StoryStep& step){ - return outcome_failed("unsupported_step", std::format("{} {}", story_step_kind_name(step.kind), step.name)); -} - -Outcome StoryStepExecutor::run(RunState& state, const StoryStep& step){ - return dispatch_story_step(*this, state, step); -} - -void StoryStepExecutor::begin_attempt(const StoryCheckpoint&){} - -bool StoryStepExecutor::holds(const std::string& condition, RunState& state){ - return state.flags.contains(condition); -} - -Outcome StoryStepExecutor::new_game(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::options(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::route(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::legs(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::step(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::talk(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::answer(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::mash(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::battle(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::train(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::heal(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::shop(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::save(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::ready(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::game(RunState&, const StoryStep& step){ - return unsupported_step(step); -} - -Outcome dispatch_story_step(StoryStepExecutor& executor, RunState& state, const StoryStep& step){ - switch (step.kind){ - case StoryStepKind::NEW_GAME: - return executor.new_game(state, step); - case StoryStepKind::OPTIONS: - return executor.options(state, step); - case StoryStepKind::ROUTE: - return executor.route(state, step); - case StoryStepKind::LEGS: - return executor.legs(state, step); - case StoryStepKind::STEP: - return executor.step(state, step); - case StoryStepKind::TALK: - return executor.talk(state, step); - case StoryStepKind::ANSWER: - return executor.answer(state, step); - case StoryStepKind::MASH: - return executor.mash(state, step); - case StoryStepKind::BATTLE: - return executor.battle(state, step); - case StoryStepKind::TRAIN: - return executor.train(state, step); - case StoryStepKind::HEAL: - return executor.heal(state, step); - case StoryStepKind::SHOP: - return executor.shop(state, step); - case StoryStepKind::SAVE: - return executor.save(state, step); - case StoryStepKind::READY: - return executor.ready(state, step); - case StoryStepKind::GAME: - return executor.game(state, step); - } - return unsupported_step(step); -} - - -Event story_event(const StoryStep& step, StoryStepExecutor& executor){ - Event event; - event.name = step.name; - event.why = step.why; - for (const std::string& name : step.skip_if){ - event.skip_if.push_back(condition(name, [&executor, name](RunState& state){ - return executor.holds(name, state); - })); - } - event.act = [&executor, &step](RunState& state){ - return executor.run(state, step); - }; - event.pose_learned = step.pose_after; - return event; -} - -namespace{ - -// The first event of a checkpoint that starts from a save: where the save -// leaves the player, for a run that reloaded it. -Event from_save_event(const Pose& start){ - Event event; - event.name = "from_save"; - event.why = "where the checkpoint's save leaves the player"; - event.act = [](RunState&){ return outcome_ok(); }; - event.pose_learned = start; - return event; -} - -} // namespace - -Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor& executor){ - executor.begin_attempt(data); - Checkpoint checkpoint; - checkpoint.id = data.id; - if (data.start){ - checkpoint.events.push_back(from_save_event(*data.start)); - } - for (const StoryStep& step : data.steps){ - checkpoint.events.push_back(story_event(step, executor)); - } - return checkpoint; -} - -namespace{ - -// `event`, for a once_per_save step known in `prepared` as `key`: skipped -// while `prepared` has it, and added to it when it succeeds changing -// nothing. -void run_once_per_save(Event& event, std::string key, PreparedSteps& prepared){ - event.skip_if.push_back(condition("done_from_this_save", [&prepared, key](RunState&){ - return prepared.contains(key); - })); - event.act = [act = std::move(event.act), &prepared, key](RunState& state) mutable{ - Outcome outcome = act(state); - if (outcome.succeeded() && outcome.changed_nothing){ - prepared.insert(key); - } - return outcome; - }; -} - -} // namespace - -Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor& executor, PreparedSteps& prepared){ - Checkpoint checkpoint = build_story_checkpoint(data, executor); - // After "from_save", the events are the steps in order. - const size_t first = data.start ? 1 : 0; - for (size_t c = 0; c < data.steps.size(); c++){ - if (data.steps[c].once_per_save){ - run_once_per_save(checkpoint.events[first + c], data.id + "/" + data.steps[c].name, prepared); - } - } - return checkpoint; -} - - -namespace{ - -// What a step of its kind must have, or "" if it has it. -std::string missing_field(const StoryStep& step){ - switch (step.kind){ - case StoryStepKind::ROUTE: - case StoryStepKind::READY: - return step.target ? "" : "no target"; - case StoryStepKind::LEGS: - if (step.legs.empty()){ - return "no legs"; - } - for (const StoryLeg& leg : step.legs){ - if (leg.tiles <= 0){ - return "a leg of no tiles"; - } - } - return ""; - case StoryStepKind::TRAIN: - return step.battles > 0 ? "" : "no battles"; - case StoryStepKind::SHOP: - return step.items.empty() ? "no items" : ""; - case StoryStepKind::GAME: - return step.variant.empty() ? "no variant" : ""; - default: - return ""; - } -} - -} // namespace - -std::vector lint_story_checkpoint(const StoryCheckpoint& data){ - std::vector problems; - if (data.id.empty()){ - problems.emplace_back("a checkpoint has no id"); - } - std::set names; - for (size_t c = 0; c < data.steps.size(); c++){ - const StoryStep& step = data.steps[c]; - const std::string where = std::format("{} step {}", data.id, c + 1); - if (step.name.empty()){ - problems.emplace_back(where + ": no name"); - }else if (!names.insert(step.name).second){ - problems.emplace_back(std::format("{}: a second step named {}", where, step.name)); - } - const std::string missing = missing_field(step); - if (!missing.empty()){ - problems.emplace_back(std::format("{} {}: {} {}", where, step.name, story_step_kind_name(step.kind), missing)); - } - // skip_if's conditions must all hold; once per save is one more. - if (step.once_per_save && !step.skip_if.empty()){ - problems.emplace_back(std::format("{} {}: once per save with skip_if", where, step.name)); - } - } - return problems; -} - - -void record_story_stats(AutoStoryStats& stats, const SegmentReport& report){ - stats.m_segment++; - for (const CheckpointRun& run : report.runs){ - if (run.passed){ - stats.m_checkpoint++; - } - } - stats.m_reset += report.reloads; -} - - -Pose tile_pose(std::string map, std::vector tiles, std::optional facing){ - Pose pose; - pose.map = std::move(map); - pose.certainty = tiles.empty() ? PoseCertainty::UNKNOWN - : tiles.size() == 1 ? PoseCertainty::TILE : PoseCertainty::SET; - pose.where = std::make_shared(std::move(tiles), facing); - return pose; -} - -std::optional facing_of(const Pose& pose){ - const TilePose* tile_pose = dynamic_cast(pose.where.get()); - return tile_pose ? tile_pose->facing : std::nullopt; -} - - - -} // namespace Pokemon -} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h deleted file mode 100644 index 27aaabad8a..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h +++ /dev/null @@ -1,261 +0,0 @@ -/* Story Steps - * - * From: https://github.com/PokemonAutomation/ - * - * One vocabulary of story steps for the tile games (FRLG, BDSP): a route, - * a fixed walk, a step onto a trigger, a talk, a YES/NO, a scene, a - * battle, the nurse, a shop, a save, and so on. A checkpoint is a list of - * such steps, plain data, so a game's story is a table its unit tests can - * plan without a console. - * - * build_story_checkpoint() turns a table row into engine events - * (Pokemon_StoryEvents.h). Each event's action asks the game's - * StoryStepExecutor to do its step: one virtual per kind, so a game - * implements the kinds it uses, and a step the game has no way of doing - * fails by name instead of doing something else. - * - * Steps never match dialogue or menu text: they look for screen state (a - * dialogue box, an arrow, a fade, a battle menu, colours, positions). The - * few reads that need text (item names in a shop or the Bag) take the - * game's language from the executor, and with no reader for it fall back - * to checks that need none (a row's position, digits, a changed screen), - * so a run never fails because its language is not supported. - * - * Poses are the game's own (Pose, with a TilePose for these games): a - * checkpoint's start, a scene's end and a route's target are poses, and - * an executor that knows where a step left the player says so in its - * Outcome, which the engine writes into the run. - * - */ - -#ifndef PokemonAutomation_Pokemon_StorySteps_H -#define PokemonAutomation_Pokemon_StorySteps_H - -#include -#include -#include -#include -#include -#include "CommonFramework/Language.h" -#include "Pokemon/Navigation/Pokemon_Grid.h" -#include "Pokemon_AutoStoryStats.h" -#include "Pokemon_StoryEvents.h" -#include "Pokemon_StorySegments.h" -#include "Pokemon_TilePose.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -// Action category classification for individual story steps. -enum class StoryStepKind{ - NEW_GAME, // title screen (no save) to the first room - OPTIONS, // the game's options as the story needs them - ROUTE, // plan and walk to `target` - LEGS, // walk `legs` as given - STEP, // one step `direction`: onto a trigger, into a door - TALK, // A at what the player faces - ANSWER, // text to a YES/NO, then `yes` - MASH, // text until the overworld is back: a scene - BATTLE, // text into a battle, fight it, text to the overworld - TRAIN, // fight `battles` wild battles where the player stands - HEAL, // the nurse, from in front of her or of the Center's door - SHOP, // `items` from a shop - SAVE, // save the game where the player stands - READY, // before a big battle: items, and the nurse at `target` if they can't - GAME, // a step only this game has, named by `variant` -}; -// Returns the readable string representation of a story step kind. -const char* story_step_kind_name(StoryStepKind kind); - -// How much a step reads the screen to confirm what it did. Each game -// decides what its steps check at each level. -enum class StoryChecks{ - // Confirm on screen: purchases, the Bag, status after battles, position. - THOROUGH, - // In a rush: trust counts and timings. - FAST, -}; -// Returns the readable string representation of a story check level. -const char* story_checks_name(StoryChecks checks); - - -// A straight leg of a fixed walk. -struct StoryLeg{ - Direction direction = Direction::NORTH; - int tiles = 0; -}; - -// An item and how many to get. -struct StoryItem{ - std::string item; - size_t quantity = 0; -}; - -// Specification of an atomic story task with actions and postconditions. -struct StoryStep{ - StoryStepKind kind = StoryStepKind::TALK; - std::string name; - std::string why; - - // ROUTE: where to go; with several tiles, any of them. READY: the nurse. - std::optional target; - // STEP - Direction direction = Direction::NORTH; - // LEGS - std::vector legs; - // ROUTE, LEGS: fight wild battles on the way instead of running. - bool fight_wild = false; - // ANSWER - bool yes = true; - // BATTLE: losing goes on (a rival's first battle). - bool may_lose = false; - // TRAIN - size_t battles = 0; - // SHOP - std::vector items; - // How this game does the kind, when it has more than one way: a - // route's plan costs, a door lined up by sight, the Mart lady instead - // of the clerk. Empty is the game's usual way. GAME: the step's name - // in the game's executor. - std::string variant; - - // Skipped when all of these hold (and there is at least one): names - // the game's executor answers (StoryStepExecutor::holds()), run flags - // unless the game reads them off the screen. - std::vector skip_if; - // Preparation for what follows, done once per save: a TEACH, a check, - // a read. Once it has succeeded and changed nothing - // (Outcome::changed_nothing), the attempts after a reload of the same - // save skip it, so a retry goes from the reload straight to the - // battle. One that changed the game (a TM taught) runs again, as the - // reload undid it. Only with build_story_checkpoint()'s PreparedSteps. - bool once_per_save = false; - // Where the step leaves the player, when its action does not say: the - // end of a scene that moves the player. - std::optional pose_after; -}; - -// Milestone row in the story table grouping related steps and starting pose. -struct StoryCheckpoint{ - std::string id; - std::string title; - // Where its starting save leaves the player; none for a new game. - std::optional start; - std::vector steps; -}; - - -// How a game does each kind of step. Every kind fails as unsupported -// unless the game overrides it. -class StoryStepExecutor{ -public: - virtual ~StoryStepExecutor() = default; - - // A checkpoint is being built for a new attempt: build_story_checkpoint() - // calls this first, so a game can start the attempt afresh (trainers - // who can see us again, the row's own settings). Does nothing by default. - virtual void begin_attempt(const StoryCheckpoint& data); - - // The checks level the program's options chose (StoryRunOptions); - // THOROUGH unless set. Steps read it to decide what to confirm. - StoryChecks checks() const{ - return m_checks; - } - void set_checks(StoryChecks checks){ - m_checks = checks; - } - // The game's language (StoryRunOptions), for the reads that need text; - // English unless set. A game with no reader for it uses language-free - // checks instead. - Language language() const{ - return m_language; - } - void set_language(Language language){ - m_language = language; - } - - // Runs `step`: dispatch_story_step() by default. A game overrides it - // to wrap every step, e.g. to turn a failed console step into a failed - // Outcome. - virtual Outcome run(RunState& state, const StoryStep& step); - - // Whether the condition named in a step's skip_if holds: by default, - // whether the run has the flag (set by an earlier step's action). - virtual bool holds(const std::string& condition, RunState& state); - -protected: - // One per step kind, called by dispatch_story_step(); each fails as - // unsupported unless the game overrides it. - friend Outcome dispatch_story_step(StoryStepExecutor& executor, RunState& state, const StoryStep& step); - virtual Outcome new_game(RunState& state, const StoryStep& step); - virtual Outcome options(RunState& state, const StoryStep& step); - virtual Outcome route(RunState& state, const StoryStep& step); - virtual Outcome legs(RunState& state, const StoryStep& step); - virtual Outcome step(RunState& state, const StoryStep& step); - virtual Outcome talk(RunState& state, const StoryStep& step); - virtual Outcome answer(RunState& state, const StoryStep& step); - virtual Outcome mash(RunState& state, const StoryStep& step); - virtual Outcome battle(RunState& state, const StoryStep& step); - virtual Outcome train(RunState& state, const StoryStep& step); - virtual Outcome heal(RunState& state, const StoryStep& step); - virtual Outcome shop(RunState& state, const StoryStep& step); - virtual Outcome save(RunState& state, const StoryStep& step); - virtual Outcome ready(RunState& state, const StoryStep& step); - virtual Outcome game(RunState& state, const StoryStep& step); - -private: - StoryChecks m_checks = StoryChecks::THOROUGH; - Language m_language = Language::English; -}; - -// Calls the executor's method for the step's kind. -Outcome dispatch_story_step(StoryStepExecutor& executor, RunState& state, const StoryStep& step); - -// "unsupported_step: TRAIN train_in_grass": what an executor without the kind returns. -Outcome unsupported_step(const StoryStep& step); - - -// The step as an event that runs it with `executor`. Both must outlive -// the event. -Event story_event(const StoryStep& step, StoryStepExecutor& executor); - -// The checkpoint `data` as events: "from_save" first when it has a start -// (the start pose, for a run that reloaded its save), then one event per -// step. `data` and `executor` must outlive the checkpoint. Saving is the -// game's: it sets the checkpoint's save, or adds a SAVE step. -Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor& executor); - -// The once_per_save steps done from the save the game is on that changed -// nothing, as "/". The game keeps it across reloads and -// empties it when it saves or loads another save. -using PreparedSteps = std::set; - -// As above, and each once_per_save step is skipped while `prepared` has -// it, and added to it when it succeeds changing nothing. `prepared` must -// outlive the checkpoint. -Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor& executor, PreparedSteps& prepared); - -// Problems an author should fix before running: an empty id, unnamed or -// repeated steps, a route or READY without a target, empty legs, a GAME -// step without a variant, TRAIN without battles, SHOP without items. -std::vector lint_story_checkpoint(const StoryCheckpoint& data); - - -// Adds a segment's run to the program's stats: the segment, each checkpoint -// that passed, each reload. -void record_story_stats(AutoStoryStats& stats, const SegmentReport& report); - - -// A pose on one of `tiles` of `map`, facing `facing` if set: TILE for one -// tile, SET for several, UNKNOWN for none. -Pose tile_pose(std::string map, std::vector tiles, std::optional facing = std::nullopt); - -// The facing of a tile pose; nothing for another pose or none. -std::optional facing_of(const Pose& pose); - - - -} // namespace Pokemon -} // namespace PokemonAutomation -#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.cpp deleted file mode 100644 index 6df0e9df31..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* Story Variant - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon_StoryVariant.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -std::vector variant_words(std::string_view text){ - std::vector words; - while (!text.empty()){ - const size_t space = text.find(' '); - const std::string_view word = text.substr(0, space); - if (!word.empty()){ - words.push_back(word); - } - if (space == std::string_view::npos){ - break; - } - text.remove_prefix(space + 1); - } - return words; -} - -std::optional variant_pair(std::string_view word){ - const size_t equals = word.find('='); - if (equals == std::string_view::npos || equals == 0){ - return std::nullopt; - } - return VariantPair{word.substr(0, equals), word.substr(equals + 1)}; -} - -std::string_view variant_name(std::string_view variant){ - const std::vector words = variant_words(variant); - if (words.empty() || variant_pair(words[0])){ - return {}; - } - return words[0]; -} - -std::optional variant_value(std::string_view variant, std::string_view key){ - for (std::string_view word : variant_words(variant)){ - const std::optional pair = variant_pair(word); - if (pair && pair->key == key){ - return pair->value; - } - } - return std::nullopt; -} - -std::optional variant_number(std::string_view text, size_t max_digits){ - if (text.empty() || text.size() > max_digits){ - return std::nullopt; - } - size_t value = 0; - for (char c : text){ - if (c < '0' || c > '9'){ - return std::nullopt; - } - value = value * 10 + size_t(c - '0'); - } - return value; -} - - - -} // namespace Pokemon -} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.h deleted file mode 100644 index f136fa147b..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.h +++ /dev/null @@ -1,51 +0,0 @@ -/* Story Variant - * - * From: https://github.com/PokemonAutomation/ - * - * Reading a step's variant (StoryStep::variant): a name, then words split - * on spaces, some of them "key=value" pairs and small numbers. A table - * writes "mart PewterCity_Mart budget=2000 potion=5"; the name ("mart") - * picks the step's action (Pokemon_StoryActions.h) and the action reads - * the rest. - * - */ - -#ifndef PokemonAutomation_Pokemon_StoryVariant_H -#define PokemonAutomation_Pokemon_StoryVariant_H - -#include -#include -#include -#include - -namespace PokemonAutomation{ -namespace Pokemon{ - - -// `text`'s words, split on spaces, empty words dropped. -std::vector variant_words(std::string_view text); - -// A word "key=value" as its two halves. -struct VariantPair{ - std::string_view key; - std::string_view value; -}; -// `word` split at its first '='; nothing without one or with an empty key. -std::optional variant_pair(std::string_view word); - -// The variant's name: its first word, unless that is a "key=value" pair. -// Empty for an empty variant or one of pairs only. -std::string_view variant_name(std::string_view variant); - -// The value of the first "key=value" word with `key`; nothing if none. -std::optional variant_value(std::string_view variant, std::string_view key); - -// `text` as a number of up to `max_digits` decimal digits; nothing if it -// isn't one. -std::optional variant_number(std::string_view text, size_t max_digits = 6); - - - -} // namespace Pokemon -} // namespace PokemonAutomation -#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.cpp index 510e94d7e8..51ad94a30c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.cpp @@ -4,6 +4,7 @@ * */ +#include #include #include "Pokemon_TilePose.h" @@ -28,8 +29,22 @@ std::string TilePose::describe() const{ } std::vector tiles_of(const Pose& pose){ - const TilePose* tile_pose = dynamic_cast(pose.where.get()); - return tile_pose ? tile_pose->tiles : std::vector{}; + const TilePose* position = dynamic_cast(pose.where.get()); + return position ? position->tiles : std::vector{}; +} + +std::optional facing_of(const Pose& pose){ + const TilePose* position = dynamic_cast(pose.where.get()); + return position ? position->facing : std::nullopt; +} + +Pose tile_pose(std::string map, std::vector tiles, std::optional facing){ + Pose pose; + pose.map = std::move(map); + pose.certainty = tiles.empty() ? PoseCertainty::UNKNOWN + : tiles.size() == 1 ? PoseCertainty::TILE : PoseCertainty::SET; + pose.where = std::make_shared(std::move(tiles), facing); + return pose; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.h index a5e786ef72..bf937c3912 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.h @@ -35,6 +35,13 @@ struct TilePose : public Position{ // is not a tile pose. std::vector tiles_of(const Pose& pose); +// The facing of a tile pose; nothing for another pose or none. +std::optional facing_of(const Pose& pose); + +// A pose on one of `tiles` of `map`, facing `facing` if set: TILE for one +// tile, SET for several, UNKNOWN for none. +Pose tile_pose(std::string map, std::vector tiles, std::optional facing = std::nullopt); + } // namespace Pokemon diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.cpp index 715869aa27..7b58c05649 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.cpp @@ -41,7 +41,7 @@ const FadeProfile FRLG_FADE_PROFILE{ }; -const char* transition_kind_name(TransitionKind kind){ +std::string transition_kind_name(TransitionKind kind){ switch (kind){ case TransitionKind::FADE_BLACK: return "black fade"; case TransitionKind::FADE_WHITE: return "white fade"; @@ -76,7 +76,7 @@ std::string offset(std::optional time, WallClock origin){ } return std::format("{:+} ms", std::chrono::duration_cast(*time - origin).count()); } -const char* scene_change_name(SceneChange change){ +std::string scene_change_name(SceneChange change){ switch (change){ case SceneChange::UNKNOWN: return "scene unknown"; case SceneChange::SAME: return "same scene"; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.h index 5764247571..9cae9bbe35 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.h @@ -24,77 +24,12 @@ #include "Common/Cpp/Time.h" #include "CommonFramework/ImageTools/ImageStats.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "Pokemon_FadeProfiles.h" namespace PokemonAutomation{ namespace Pokemon{ -// Whether the screen differs after a transition from before it. The -// tracker has only frame statistics; the caller compares the frames, or -// says it did not. -enum class SceneChange{ - UNKNOWN, - SAME, - DIFFERENT, -}; - - -// A game's fades, as data. Two tiers of the same test: a frame is uniform -// (the fade's hold) when its middle's stddev sum is at most -// `uniform_max_stddev_sum`, and partial (on the way down or up) when it is -// at most `partial_max_stddev_sum`. Either way it is dark or white by its -// rgb sum. -struct FadeProfile{ - double uniform_max_stddev_sum = 10; - double partial_max_stddev_sum = 60; - // Dark at or below this rgb sum; a partial frame up to `partial_dark_max_sum`. - double dark_max_sum = 225; - double partial_dark_max_sum = 300; - // White at or above this rgb sum; a partial frame from `partial_white_min_sum`. - double white_min_sum = 500; - double partial_white_min_sum = 450; - - // Partial frames for longer than this, with no hold, are the scene's - // own look (a dim cave floor, a street at night), not a fade. - Milliseconds max_fall = Milliseconds(1000); - // A transition still dark or white after this has timed out: the - // screen did not come back. - Milliseconds max_hold = Milliseconds(8000); - - // Whether the game fades to white between maps (BDSP's cave exits). - // Without, every white is an encounter's flash. - bool has_white_fade = true; - // A white held this long or less, back on the same scene, is a flash. - Milliseconds flash_max_hold = Milliseconds(150); - // A white held this long or more, not back on the same scene, is a - // white fade. Between the two the white is unsure. - Milliseconds white_fade_min_hold = Milliseconds(400); -}; - -// BDSP. The uniform tier is the shared walk's (FADE_MAX_STDDEV_SUM, the -// Oreburgh Gate's textured floor is no fade, lab-B 2026-11-08); the partial -// tier is run_into_door()'s 60, which caught the doorway's dim fade frames. -// A cave mouth's fade is dim (45 to 64 a channel), hence the dark sum of 225. -// The flash and white-fade holds are provisional: no console frames of an -// encounter flash and a cave exit have been timed side by side yet, so the -// band between them is wide and reports WHITE_UNSURE. -extern const FadeProfile BDSP_FADE_PROFILE; -// FRLG. The GBA fades to true black, so the dark tiers are the shared -// BlackScreenDetector's 100 and a little above; it has no white fade between -// maps, so every white is an encounter's flash. -extern const FadeProfile FRLG_FADE_PROFILE; - - -// What a transition was. -enum class TransitionKind : uint8_t{ - FADE_BLACK, // A door, a cave mouth, a scene cut, a battle's own fade. - FADE_WHITE, // A cave exit: a long white onto another scene. - FLASH, // An encounter's flash: a short white, back on the scene. - WHITE_UNSURE, // A white that may be either: wait for a battle. -}; -// "black fade", for the log. -const char* transition_kind_name(TransitionKind kind); - // Where the tracker is in a transition. enum class TransitionPhase : uint8_t{ SCENE, // No transition: the screen shows a scene. diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_WarpJudge.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_WarpJudge.h new file mode 100644 index 0000000000..ab112a4362 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_WarpJudge.h @@ -0,0 +1,95 @@ +/* Warp Judge + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_Interrupts.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_WarpJudge_H +#define PokemonAutomation_Pokemon_WarpJudge_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Pokemon_ScreenEvents.h" +#include "Pokemon_Transitions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A game's timing, as data. +struct InterruptKnobs{ + // A fade must hold this long to be a warp's. One uniform frame is enough + // by default: a 50 ms fade can show on one frame only. + Milliseconds min_fade_hold = Milliseconds(0); + // A battle that shows this soon after a fade ends is that fade's + // encounter, and a fade is no warp before this has passed with no + // battle. BDSP's encounter flash shows its battle within 8 s + // (WHITE_FLASH_BATTLE_WAIT in its walk). + Milliseconds battle_after_fade = Milliseconds(8000); + // A dialog box that rose this long or less before a battle's fade is a + // trainer's lines. A trainer's lines can pause more than 4 s before the + // battle (BDSP r210d), and a trainer may say several boxes. + Milliseconds sight_lines_lead = Milliseconds(20000); +}; + +// The span of the log to judge: changes at `start` or later, and no later +// than `end`. +struct InterruptWindow{ + WallClock start = {}; + WallClock end = {}; +}; + + +// How a fade looked, for the warp judge. +struct FadeSpan{ + WarpFade fade = WarpFade::NONE; + WallClock down = {}; + // When the screen came back; none while it still shows the fade. + std::optional up = {}; +}; + +// What the warp judge made of a fade. +enum class WarpJudgement{ + NO_FADE, // No fade went down in the window. + FADE_SHOWING, // It went down and has not come back up. + TOO_SHORT, // It came back up before min_fade_hold. + SAME_SCENE, // It came back up on the scene it left. + WARPED, // Down, held, back up; not on the same scene. + FLASH, // An encounter's flash (a tracked transition only). + WHITE_UNSURE, // A white that may be a flash or a cave exit (a + // tracked transition only): wait for a battle. +}; +// "fade too short", for the log. +std::string warp_judgement_name(WarpJudgement judgement); + +// The warp judge's verdict and the fade it judged. +struct WarpVerdict{ + WarpJudgement judgement = WarpJudgement::NO_FADE; + // The last fade that went down in the window, if any. + std::optional fade = {}; +}; + +// A warp is a fade going down, holding uniform, and coming back up on +// another scene. The last fade that went down in `window` is judged; a +// LOCATION_BANNER does not count here (WarpSeen does). `change` is what +// the caller saw of the scene before and after: UNKNOWN does not rule the +// warp out. This judges the fade only: a battle after it is +// classify_interrupt()'s question. +WarpVerdict judge_warp( + const ScreenEventLog& log, InterruptWindow window, + const InterruptKnobs& knobs, SceneChange change +); +// The same judge over a TransitionTracker's transition, which has its own +// scene comparison. A transition whose hold went unseen onto another scene +// is a warp whatever min_fade_hold says: the scene change is the evidence. +WarpVerdict judge_warp(const Transition& transition, const InterruptKnobs& knobs); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_GridPose.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_GridPose.h new file mode 100644 index 0000000000..3280715da5 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_GridPose.h @@ -0,0 +1,37 @@ +/* Grid Pose + * + * From: https://github.com/PokemonAutomation/ + * + * Where a player stands on a 2D tile grid (FRLG, BDSP): a map, the tiles + * they may be on and the way they face. Games that move on a surface or + * in 3D (PLZA) need their own type. + * + */ + +#ifndef PokemonAutomation_Pokemon_GridPose_H +#define PokemonAutomation_Pokemon_GridPose_H + +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// One of `tiles` of `map`, facing `facing` if set. As a target, any of the +// tiles will do. +struct GridPose{ + std::string map; + std::vector tiles; + std::optional facing; + + bool operator==(const GridPose& other) const = default; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp new file mode 100644 index 0000000000..4adc5dd7d6 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp @@ -0,0 +1,20 @@ +/* Story Action Arg + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryActionArg.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +StoryArgType story_arg_type(const StoryArgValue& value){ + return (StoryArgType)value.index(); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h new file mode 100644 index 0000000000..417d228a9f --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h @@ -0,0 +1,79 @@ +/* Story Action Arg + * + * From: https://github.com/PokemonAutomation/ + * + * A step's action and its arguments (StoryStep::action, StoryStep::args), + * e.g. a Mart step's {"map": "CeruleanCity_Mart", "budget": 3000}. Each + * action declares the arguments it takes (Pokemon_StoryActionSpec.h), with their + * types and defaults; the JSON reader (Data/Pokemon_StoryStepJson.h) + * parses a step's args against them and fills in the defaults, so a typo + * fails at load instead of mid-run and nothing after it reads JSON. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActionArg_H +#define PokemonAutomation_Pokemon_StoryActionArg_H + +#include +#include +#include +#include +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "Pokemon_GridPose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A straight leg of a fixed walk. +struct StoryLeg{ + Direction direction = Direction::NORTH; + int tiles = 0; + + bool operator==(const StoryLeg& other) const = default; +}; + +// An item and how many to get. +struct StoryItem{ + std::string item; + size_t quantity = 0; + + bool operator==(const StoryItem& other) const = default; +}; + + +// The type an action declares for an argument, in StoryArgValue's order. +enum class StoryArgType{ + BOOLEAN, + INTEGER, + WORD, + DIRECTION, + GRID_POSE, + LEGS, + WORDS, + ITEMS, +}; + +// One argument's value; the index is its StoryArgType. +using StoryArgValue = std::variant< + bool, int64_t, std::string, // BOOLEAN, INTEGER, WORD + Direction, GridPose, // DIRECTION, GRID_POSE + std::vector, // LEGS + std::vector, // WORDS + std::vector // ITEMS +>; + +// A step's arguments by key. +using StoryActionArgs = std::map>; + +// The type `value` holds. +StoryArgType story_arg_type(const StoryArgValue& value); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp new file mode 100644 index 0000000000..9cf751d2ac --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp @@ -0,0 +1,142 @@ +/* Story Action Arg Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Checking a step's args against an action's spec and filling in its + * fallbacks. Built standalone (PA_STORY_DATA_STANDALONE), it runs without + * the application. + * + */ + +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon_StoryActionArg.h" +#ifndef PA_STORY_DATA_STANDALONE +#include "Pokemon/AutoStory/Pokemon_AutoStory_Tests.h" +#endif + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// The args a Mart step takes, as a game declares them. +const StoryActionSpec& mart_spec(){ + static const StoryActionSpec spec{.kind = StoryStepKind::GAME, .name = "mart", .args = { + {.key = "map", .type = StoryArgType::WORD, .required = true, .fallback = std::nullopt, .why = "the Mart's map"}, + {.key = "budget", .type = StoryArgType::INTEGER, .required = true, .fallback = std::nullopt, .why = ""}, + {.key = "floor", .type = StoryArgType::INTEGER, .required = false, .fallback = int64_t(0), .why = ""}, + {.key = "if_present", .type = StoryArgType::BOOLEAN, .required = false, .fallback = std::nullopt, .why = ""}, + }}; + return spec; +} + +// Args checked against the Mart's spec, then filled in. +struct ArgsInput{ + std::string_view name; + StoryActionArgs args; +}; + +// The errors joined by "; ", and the args with their fallbacks. +struct ArgsExpectation{ + std::string_view error = {}; + StoryActionArgs filled = {}; +}; + +struct ArgsCase{ + ArgsInput input; + ArgsExpectation expectation; +}; + +const ArgsCase CASES[] = { + {.input = {.name = "mart", .args = {{"map", std::string("M")}, {"budget", int64_t(1500)}, {"if_present", true}}}, + .expectation = {.filled = {{"map", std::string("M")}, {"budget", int64_t(1500)}, {"floor", int64_t(0)}, {"if_present", true}}}}, + {.input = {.name = "fallback does not override", .args = {{"map", std::string("M")}, {"budget", int64_t(1)}, {"floor", int64_t(2)}}}, + .expectation = {.filled = {{"map", std::string("M")}, {"budget", int64_t(1)}, {"floor", int64_t(2)}}}}, + {.input = {.name = "unknown key", .args = {{"map", std::string("M")}, {"budget", int64_t(1)}, {"budgte", int64_t(1)}}}, + .expectation = {.error = "unknown argument \"budgte\"", .filled = {{"map", std::string("M")}, {"budget", int64_t(1)}, {"budgte", int64_t(1)}, {"floor", int64_t(0)}}}}, + {.input = {.name = "wrong type", .args = {{"map", std::string("M")}, {"budget", std::string("lots")}}}, + .expectation = {.error = "argument \"budget\" has the wrong type", .filled = {{"map", std::string("M")}, {"budget", std::string("lots")}, {"floor", int64_t(0)}}}}, + {.input = {.name = "missing required", .args = {{"budget", int64_t(1)}}}, + .expectation = {.error = "missing argument \"map\" (the Mart's map)", .filled = {{"budget", int64_t(1)}, {"floor", int64_t(0)}}}}, +}; + + +// "" when `test` reads as expected, else what differs. +std::string check_case(const ArgsCase& test){ + std::string error; + for (const std::string& each : story_args_errors(mart_spec(), test.input.args)){ + error += (error.empty() ? "" : "; ") + each; + } + if (error != test.expectation.error){ + return "expected error \"" + std::string(test.expectation.error) + "\", got \"" + error + "\""; + } + if (with_fallbacks(mart_spec(), test.input.args) != test.expectation.filled){ + return "filled in other args"; + } + const StoryActionArgs& args = test.expectation.filled; + const int64_t* floor = value_if_at_it(args, args.find("floor")); + if (floor == nullptr || *floor != story_arg(args, "floor")){ + return "reads floor otherwise"; + } + return ""; +} + + +#ifndef PA_STORY_DATA_STANDALONE + +class StoryActionArgTest : public UnitTest{ +public: + explicit StoryActionArgTest(ArgsCase test) + : UnitTest("Pokemon::StoryActionArg - " + std::string(test.input.name)) + , m_case(test) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string error = check_case(m_case); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } + +private: + ArgsCase m_case; +}; + +#endif + + +} // namespace + + +#ifndef PA_STORY_DATA_STANDALONE + +void add_tests_StoryActionArg(UnitTestDatabase& database){ + for (const ArgsCase& test : CASES){ + database.add(test); + } +} + +#endif + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +#ifdef PA_STORY_DATA_STANDALONE + +int main(){ + int failed = 0; + for (const auto& test : PokemonAutomation::Pokemon::CASES){ + const std::string error = PokemonAutomation::Pokemon::check_case(test); + std::cout << test.input.name << ": " << (error.empty() ? "PASS" : error) << '\n'; + failed += !error.empty(); + } + return failed != 0; +} + +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp new file mode 100644 index 0000000000..50ac67e2b2 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp @@ -0,0 +1,62 @@ +/* Story Action Spec + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Pokemon_StoryActionSpec.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +const StoryArgSpec* find_spec(const StoryActionSpec& action, std::string_view key){ + for (const StoryArgSpec& spec : action.args){ + if (spec.key == key){ + return &spec; + } + } + return nullptr; +} + + +} // namespace + + +std::vector story_args_errors(const StoryActionSpec& spec, const StoryActionArgs& args){ + std::vector errors; + for (const auto& [key, value] : args){ + const StoryArgSpec* arg = find_spec(spec, key); + if (arg == nullptr){ + errors.emplace_back(std::format("unknown argument \"{}\"", key)); + }else if (story_arg_type(value) != arg->type){ + errors.emplace_back(std::format("argument \"{}\" has the wrong type", key)); + } + } + for (const StoryArgSpec& arg : spec.args){ + if (arg.required && args.find(arg.key) == args.end()){ + errors.emplace_back(std::format("missing argument \"{}\"{}", arg.key, arg.why.empty() ? "" : " (" + arg.why + ")")); + } + } + return errors; +} + +StoryActionArgs with_fallbacks(const StoryActionSpec& spec, StoryActionArgs args){ + for (const StoryArgSpec& arg : spec.args){ + if (arg.fallback){ + args.try_emplace(arg.key, *arg.fallback); + } + } + return args; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h new file mode 100644 index 0000000000..729cb7799f --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h @@ -0,0 +1,52 @@ +/* Story Action Spec + * + * From: https://github.com/PokemonAutomation/ + * + * What an action declares: the kind of step it does, its name and the + * args it takes, with their types and fallbacks (Pokemon_StoryActionArg.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActionSpec_H +#define PokemonAutomation_Pokemon_StoryActionSpec_H + +#include +#include +#include +#include "Pokemon_StoryActionArg.h" +#include "Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// One argument an action takes. A missing optional one reads as `fallback` +// when it has one. +struct StoryArgSpec{ + std::string key; + StoryArgType type = StoryArgType::WORD; + bool required = false; + std::optional fallback; + // What it is for, shown in lint errors. + std::string why; +}; + +// An action: the kind of step it does, its name and the args it takes. +struct StoryActionSpec{ + StoryStepKind kind = StoryStepKind::GAME; + std::string name; + std::vector args; +}; + +// Each way `args` don't fit `spec`: a key it doesn't name, a value of +// another type, a required one missing. Empty when they fit. +std::vector story_args_errors(const StoryActionSpec& spec, const StoryActionArgs& args); + +// `args` with each missing optional arg of `spec` set to its fallback. +StoryActionArgs with_fallbacks(const StoryActionSpec& spec, StoryActionArgs args); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.cpp new file mode 100644 index 0000000000..aade2b3809 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.cpp @@ -0,0 +1,32 @@ +/* Story Checks + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryCheckLevel.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string story_check_level_name(StoryCheckLevel level){ + switch (level){ + case StoryCheckLevel::TESTING: + return "testing"; + case StoryCheckLevel::THOROUGH: + return "thorough"; + case StoryCheckLevel::DEFAULT: + return "default"; + case StoryCheckLevel::FAST: + return "fast"; + case StoryCheckLevel::SPEEDRUN: + return "speedrun"; + } + return "?"; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h new file mode 100644 index 0000000000..86de9f8c76 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h @@ -0,0 +1,43 @@ +/* Story Check Level + * + * From: https://github.com/PokemonAutomation/ + * + * How much a story step reads the screen to confirm what it did. The + * program's options choose it (StoryRunOptions); each game decides what + * its steps check at each level. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryCheckLevel_H +#define PokemonAutomation_Pokemon_StoryCheckLevel_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How much a step reads the screen to confirm what it did. +enum class StoryCheckLevel{ + // Everything THOROUGH checks, each checkpoint run 3 times by default to + // make sure it really passes. + TESTING, + // Check everything for the user: Bag items, Pokemon stats, + // preconditions. + THOROUGH, + // Assume most things are fine; check the most important ones. + DEFAULT, + // Minimal checks. + FAST, + // Almost no checks, to be as fast as possible. + SPEEDRUN, +}; + +// Returns the readable string representation of a story check level. +std::string story_check_level_name(StoryCheckLevel level); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h new file mode 100644 index 0000000000..9374862ecb --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h @@ -0,0 +1,37 @@ +/* Story Checkpoint + * + * From: https://github.com/PokemonAutomation/ + * + * A checkpoint of a tile game's story table as plain data: where its save + * leaves the player and its steps in order. build_story_checkpoint() + * (Pokemon_StoryStepExecutor.h) turns it into engine events. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryCheckpoint_H +#define PokemonAutomation_Pokemon_StoryCheckpoint_H + +#include +#include +#include +#include "Pokemon_GridPose.h" +#include "Pokemon_StoryStep.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Milestone row in the story table grouping related steps and starting pose. +struct StoryCheckpoint{ + std::string id; + std::string title; + // Where its starting save leaves the player; none for a new game. + std::optional start; + std::vector steps; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.cpp new file mode 100644 index 0000000000..2908ffd8d5 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.cpp @@ -0,0 +1,38 @@ +/* Story Segment Types + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StorySegmentTypes.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +bool CheckpointRun::one_shot() const{ + return passed && attempts == 1; +} + +size_t SegmentReport::one_shot_passes() const{ + size_t count = 0; + for (const CheckpointRun& run : runs){ + count += run.one_shot() ? 1 : 0; + } + return count; +} + +StoryRunCounts SegmentReport::story_counts() const{ + StoryRunCounts counts{.segments = 1, .checkpoints = 0, .resets = reloads}; + for (const CheckpointRun& run : runs){ + if (run.passed){ + counts.checkpoints++; + } + } + return counts; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h new file mode 100644 index 0000000000..d245deacf1 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h @@ -0,0 +1,73 @@ +/* Story Segment Types + * + * From: https://github.com/PokemonAutomation/ + * + * The plain data of a segment run (Pokemon_StorySegments.h): its policy, + * the range of checkpoints to run and the report of what happened. + * + */ + +#ifndef PokemonAutomation_Pokemon_StorySegmentTypes_H +#define PokemonAutomation_Pokemon_StorySegmentTypes_H + +#include +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "Pokemon/AutoStory/Pokemon_StoryLog.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Retry and timeout configuration for story segment execution. +struct SegmentPolicy{ + // Runs of one checkpoint, reloading its save between them, before the + // segment stops. 1 stops at the first failure without reloading, leaving + // the game where it failed for a look. + size_t attempts_per_checkpoint = 3; +}; + +// The checkpoints to run, by id, both inclusive. An unset end is the +// segment's first or last checkpoint. +struct SegmentRange{ + std::optional from; + std::optional to; +}; + + +// Summary of checkpoint attempts and pass status. +struct CheckpointRun{ + std::string id; + bool passed = false; + size_t attempts = 0; + + bool one_shot() const; +}; + +// Execution results and failure diagnostics for a story segment run. +struct SegmentReport{ + bool completed = false; + // Both empty when nothing failed; the event is empty when a start + // check, an end check, a save or a reload failed. + std::string failed_checkpoint; + std::string failed_event; + Outcome failure; + size_t checkpoints_run = 0; + // Reloads after failed attempts. + size_t reloads = 0; + // Each checkpoint run, in order, the failed one last. + std::vector runs; + + size_t one_shot_passes() const; + // What the run adds to the program's stats (record_story_counts()): + // the segment, each checkpoint that passed, each reload. + StoryRunCounts story_counts() const; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h new file mode 100644 index 0000000000..26cd129bce --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h @@ -0,0 +1,60 @@ +/* Story Step + * + * From: https://github.com/PokemonAutomation/ + * + * One step of a tile game's story (FRLG, BDSP) as plain data: its kind, + * the action that does it and the action's args. A game's executor does it + * (Pokemon_StoryStepExecutor.h); the shared JSON reads and writes it + * (Data/Pokemon_StoryStepJson.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStep_H +#define PokemonAutomation_Pokemon_StoryStep_H + +#include +#include +#include +#include "Pokemon_GridPose.h" +#include "Pokemon_StoryActionArg.h" +#include "Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Specification of an atomic story task with actions and postconditions. +struct StoryStep{ + StoryStepKind kind = StoryStepKind::TALK; + std::string name; + std::string why; + + // How the step does its kind: one of the built-in actions + // (Pokemon_BuiltinStoryActions.h) or the game's own; for a GAME step, the + // game's action. Empty is the kind's default action. + std::string action; + // The arguments the action reads, parsed against its spec when the + // game loads the step, with the spec's fallbacks filled in. + StoryActionArgs args; + + // Skipped when all of these hold (and there is at least one): names + // the game's executor answers (StoryStepExecutor::holds()), run flags + // unless the game reads them off the screen. + std::vector skip_if; + // Preparation for what follows, done once per save: a TEACH, a check, + // a read. Once it has succeeded and changed nothing + // (Outcome::changed_nothing), the attempts after a reload of the same + // save skip it, so a retry goes from the reload straight to the + // battle. One that changed the game (a TM taught) runs again, as the + // reload undid it. Only with build_story_checkpoint()'s PreparedSteps. + bool once_per_save = false; + // Where the step leaves the player, when its action does not say: the + // end of a scene that moves the player. + std::optional pose_after; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp new file mode 100644 index 0000000000..28b755779b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp @@ -0,0 +1,52 @@ +/* Story Step Kind + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string story_step_kind_name(StoryStepKind kind){ + switch (kind){ + case StoryStepKind::NEW_GAME: + return "NEW_GAME"; + case StoryStepKind::OPTIONS: + return "OPTIONS"; + case StoryStepKind::ROUTE: + return "ROUTE"; + case StoryStepKind::LEGS: + return "LEGS"; + case StoryStepKind::STEP: + return "STEP"; + case StoryStepKind::TALK: + return "TALK"; + case StoryStepKind::ANSWER: + return "ANSWER"; + case StoryStepKind::MASH: + return "MASH"; + case StoryStepKind::BATTLE: + return "BATTLE"; + case StoryStepKind::TRAIN: + return "TRAIN"; + case StoryStepKind::HEAL: + return "HEAL"; + case StoryStepKind::SHOP: + return "SHOP"; + case StoryStepKind::SAVE: + return "SAVE"; + case StoryStepKind::READY: + return "READY"; + case StoryStepKind::GAME: + return "GAME"; + } + return "?"; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h new file mode 100644 index 0000000000..2e43aa8118 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h @@ -0,0 +1,45 @@ +/* Story Step Kind + * + * From: https://github.com/PokemonAutomation/ + * + * The kinds of story step the tile games (FRLG, BDSP) share. A game's + * executor does each kind its own way (Pokemon_StoryStepExecutor.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepKind_H +#define PokemonAutomation_Pokemon_StoryStepKind_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Action category classification for individual story steps. +enum class StoryStepKind{ + NEW_GAME, // title screen (no save) to the first room + OPTIONS, // the game's options as the story needs them + ROUTE, // plan and walk to `target` + LEGS, // walk `legs` as given + STEP, // one step `direction`: onto a trigger, into a door + TALK, // A at what the player faces + ANSWER, // text to a YES/NO, then `yes` + MASH, // text until the overworld is back: a scene + BATTLE, // text into a battle, fight it, text to the overworld + TRAIN, // fight `battles` wild battles where the player stands + HEAL, // the nurse, from in front of her or of the Center's door + SHOP, // `items` from a shop + SAVE, // save the game where the player stands + READY, // before a big battle: items, and the nurse at `target` if they can't + GAME, // a step only this game has, named by `variant` +}; + +// Returns the readable string representation of a story step kind. +std::string story_step_kind_name(StoryStepKind kind); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.cpp index 340719dce7..62ec864f74 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.cpp @@ -11,7 +11,7 @@ namespace PokemonAutomation{ namespace Pokemon{ -const char* direction_name(Direction direction){ +std::string direction_name(Direction direction){ switch (direction){ case Direction::NORTH: return "north"; diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.h index e455710855..0b9d3eeb03 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.h @@ -31,7 +31,7 @@ constexpr Direction ALL_DIRECTIONS[] = { Direction::NORTH, Direction::EAST, Direction::SOUTH, Direction::WEST, }; // Returns the lowercase name string of a cardinal direction. -const char* direction_name(Direction direction); +std::string direction_name(Direction direction); // Grid coordinate with integer x and y components. diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp index 12fd84286e..28c97d9210 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp @@ -335,7 +335,7 @@ struct LegPlannerInput{ }; struct LegPlannerExpectation{ - const char* description; + std::string_view description; }; struct LegPlannerTestCase{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h new file mode 100644 index 0000000000..c1a7401c3b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h @@ -0,0 +1,117 @@ +/* Leg Types + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_LegWalker.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_LegTypes_H +#define PokemonAutomation_Pokemon_LegTypes_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Something that stops the player part-way through a leg. +template +class LegInterrupt{ +public: + virtual ~LegInterrupt() = default; + + virtual std::string name() const = 0; + + // A new watcher for the screen the interruption brings up. + virtual std::unique_ptr make_watcher() const = 0; + + // How long after the step that set it off the watcher fires. The games + // only interrupt between steps, so from this the walker works out how + // many tiles of an open leg were walked. + virtual Milliseconds detection_delay() const = 0; + + // Clears it, leaving the player standing on the overworld, on the same + // tile and facing the same way. + virtual void clear(Console& console, Context& context) const = 0; +}; + +// Collection of interrupt detectors active during leg movement. +template +using LegInterrupts = std::vector>>; + + +// How the game moves the player: holds `direction` for `duration`, then +// lets go. +template +using LegMover = std::function; + + +// A straight leg, for a player standing still and facing its way. +struct LegSpec{ + Direction direction = Direction::NORTH; + int tiles = 0; + // A wall stops the player after the last tile. + bool to_wall = false; + // How long one tile takes, for this leg's direction and way of moving. + Milliseconds tile_time{0}; + // An open leg stops at its first interrupt, once cleared, instead of + // walking on from an estimate; the caller finds the player again. + bool stop_on_interrupt = false; + // A leg to a wall stops when, held again after an interrupt, it is + // interrupted again right away: something on the way, like a sign, + // interrupts every hold, so the wall is never reached. + bool stop_if_blocked = false; + // The steps (from 1) the game holds the player up a tile before, as + // FireRed does on a step onto a connected map: each makes a hold over + // it a tile longer. + std::vector stalled_steps = {}; +}; +// Formats a LegSpec into a descriptive string. +std::string to_string(const LegSpec& leg); + +// Execution summary of a completed or stopped leg movement. +struct LegResult{ + // Tiles walked, which is `tiles` unless the leg gave up. + int tiles = 0; + // Whether `tiles` is certain: an interrupted open leg is an estimate. + bool exact = true; + size_t interruptions = 0; + // The leg stopped at an interrupt (stop_on_interrupt, stop_if_blocked): + // the player is somewhere along it. For an open leg `tiles` is then how + // many the interrupt's timing says were walked (tiles_before_interrupt()), + // for the caller to look around; for a leg to a wall it is 0. + bool stopped = false; +}; + + +// How long to hold for `tiles` tiles: an open leg lets go half a tile before +// the last step would end, so the step under way finishes and no other +// starts; a leg to a wall is held two tiles longer than it takes. The last +// `tiles` of the leg are held for, a tile more for each of its stalled +// steps among them. +Milliseconds leg_hold(const LegSpec& leg, int tiles); + +// How many tiles an open leg had walked when an interrupt was seen +// `elapsed` into its hold, given the interrupt's detection delay. Steps end +// a whole number of tiles into the hold, so this rounds to the nearest. +int tiles_before_interrupt(const LegSpec& leg, Milliseconds elapsed, Milliseconds detection_delay, int remaining); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h index dcdb704058..f02618031c 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h @@ -34,94 +34,12 @@ #include "CommonTools/Async/InferenceRoutines.h" #include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" #include "Pokemon_Grid.h" +#include "Pokemon_LegTypes.h" namespace PokemonAutomation{ namespace Pokemon{ -// Something that stops the player part-way through a leg. -template -class LegInterrupt{ -public: - virtual ~LegInterrupt() = default; - - virtual std::string name() const = 0; - - // A new watcher for the screen the interruption brings up. - virtual std::unique_ptr make_watcher() const = 0; - - // How long after the step that set it off the watcher fires. The games - // only interrupt between steps, so from this the walker works out how - // many tiles of an open leg were walked. - virtual Milliseconds detection_delay() const = 0; - - // Clears it, leaving the player standing on the overworld, on the same - // tile and facing the same way. - virtual void clear(Console& console, Context& context) const = 0; -}; - -// Collection of interrupt detectors active during leg movement. -template -using LegInterrupts = std::vector>>; - - -// How the game moves the player: holds `direction` for `duration`, then -// lets go. -template -using LegMover = std::function; - - -// A straight leg, for a player standing still and facing its way. -struct LegSpec{ - Direction direction = Direction::NORTH; - int tiles = 0; - // A wall stops the player after the last tile. - bool to_wall = false; - // How long one tile takes, for this leg's direction and way of moving. - Milliseconds tile_time{0}; - // An open leg stops at its first interrupt, once cleared, instead of - // walking on from an estimate; the caller finds the player again. - bool stop_on_interrupt = false; - // A leg to a wall stops when, held again after an interrupt, it is - // interrupted again right away: something on the way, like a sign, - // interrupts every hold, so the wall is never reached. - bool stop_if_blocked = false; - // The steps (from 1) the game holds the player up a tile before, as - // FireRed does on a step onto a connected map: each makes a hold over - // it a tile longer. - std::vector stalled_steps = {}; -}; -// Formats a LegSpec into a descriptive string. -std::string to_string(const LegSpec& leg); - -// Execution summary of a completed or stopped leg movement. -struct LegResult{ - // Tiles walked, which is `tiles` unless the leg gave up. - int tiles = 0; - // Whether `tiles` is certain: an interrupted open leg is an estimate. - bool exact = true; - size_t interruptions = 0; - // The leg stopped at an interrupt (stop_on_interrupt, stop_if_blocked): - // the player is somewhere along it. For an open leg `tiles` is then how - // many the interrupt's timing says were walked (tiles_before_interrupt()), - // for the caller to look around; for a leg to a wall it is 0. - bool stopped = false; -}; - - -// How long to hold for `tiles` tiles: an open leg lets go half a tile before -// the last step would end, so the step under way finishes and no other -// starts; a leg to a wall is held two tiles longer than it takes. The last -// `tiles` of the leg are held for, a tile more for each of its stalled -// steps among them. -Milliseconds leg_hold(const LegSpec& leg, int tiles); - -// How many tiles an open leg had walked when an interrupt was seen -// `elapsed` into its hold, given the interrupt's detection delay. Steps end -// a whole number of tiles into the hold, so this rounds to the nearest. -int tiles_before_interrupt(const LegSpec& leg, Milliseconds elapsed, Milliseconds detection_delay, int remaining); - - // What one hold reported: nothing if it ran out, or which interrupt showed // and how long into the hold. struct HoldOutcome{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp index 984b282070..f4438a4fa5 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp @@ -230,7 +230,7 @@ struct LegWalkerInput{ }; struct LegWalkerExpectation{ - const char* description; + std::string_view description; }; struct LegWalkerTestCase{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp index 087680cb09..24bf93b039 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp @@ -36,9 +36,16 @@ constexpr std::pair GLYPHS[] = { {'2', TileKind::CLOSED_SOUTH}, {'4', TileKind::CLOSED_WEST}, {'6', TileKind::CLOSED_EAST}, + {'u', TileKind::SPIN_NORTH}, + {'d', TileKind::SPIN_SOUTH}, + {'l', TileKind::SPIN_WEST}, + {'r', TileKind::SPIN_EAST}, + {'o', TileKind::STOP_SPIN}, + {'H', TileKind::FALL_HOLE}, + {'B', TileKind::STRENGTH_BUTTON}, }; -constexpr std::pair WARP_ENTRIES[] = { +constexpr std::pair WARP_ENTRIES[] = { {"walk_into", WarpEntry::WALK_INTO}, {"step_on", WarpEntry::STEP_ON}, {"cave_entrance", WarpEntry::CAVE_ENTRANCE}, diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h index a5adcea1b9..6b4d923fbf 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h @@ -46,141 +46,12 @@ #include #include "Common/Cpp/Json/JsonValue.h" #include "Pokemon_Grid.h" +#include "Pokemon_MapFeatures.h" namespace PokemonAutomation{ namespace Pokemon{ -// What a tile is, for walking. The map files write each as one glyph. -enum class TileKind : uint8_t{ - WALL, // '#' - OPEN, // '.' - TALL_GRASS, // '~' open, with wild encounters - WATER, // 'w' - LEDGE_NORTH, // '^' a wall, except that walking into it the arrow's - LEDGE_SOUTH, // 'v' way hops the player over it - LEDGE_WEST, // '<' - LEDGE_EAST, // '>' - DOOR, // 'D' a door or warp tile walked into - SIGN, // 'S' a sign, read by facing it - OUTSIDE, // ' ' no map of the game's here (a map's rectangle - // reaching past the game's own) - CLOSED_NORTH, // '8' open, but not crossed through its named side: - CLOSED_SOUTH, // '2' not entered from it, nor left through it (the - CLOSED_WEST, // '4' number pad's arrows) - CLOSED_EAST, // '6' -}; -// The tile a glyph stands for, or nothing if it isn't one. -std::optional tile_from_glyph(char glyph); -// Returns the character glyph representing a TileKind. -char glyph_of(TileKind tile); - - -// Where the tiles came from: the decompilation file, at which revision, -// read when. -struct MapSource{ - std::string decomp_file; - std::string revision; - std::string date; -}; - -// Where the map lies on a world grid that several maps share (a BDSP map -// matrix): its tile (0, 0) is tile `offset` of world `name`. Maps on the -// same world join where they meet. -struct MapWorld{ - std::string name; - TilePos offset; -}; - -// Where a warp puts the player: point `point` of map `map`. -struct WarpDestination{ - std::string map; - std::string point; -}; - -// How the player takes a warp, as the map file writes it. -enum class WarpEntry{ - WALK_INTO, // "walk_into": a door or cave mouth, walked into - STEP_ON, // "step_on": stepping onto the tile (ladders, - // escalators, BDSP's warp tiles) - CAVE_ENTRANCE, // "cave_entrance": stepping onto the tile; the game - // walks a player arriving on it a tile south - WALK_NORTH, // "walk_north" ...: standing on the tile and walking - WALK_SOUTH, // that way (exit mats, stairs at the side of a room) - WALK_WEST, - WALK_EAST, -}; - -// A warp from (x, y), taken as `enter` says. `to` is left out for a warp -// to a map that is not loaded: the warp is still there, for routes to keep -// off. -struct MapWarp{ - int x = 0; - int y = 0; - WarpEntry enter = WarpEntry::WALK_INTO; - std::optional to; -}; - -// Type classification for interactive map objects. -enum class ObjectKind{ - NPC, - ITEM, - SIGN, -}; - -// A box of tiles, both corners inclusive. -struct TileBox{ - int x0 = 0; - int y0 = 0; - int x1 = 0; - int y1 = 0; -}; - -// A trainer sees `sight` tiles ahead in each direction of `looks` (their -// facing, unless the map says otherwise). -struct MapTrainer{ - int sight = 0; - std::vector looks; -}; - -// Something standing on a tile, which blocks it. A person who wanders may -// stand anywhere in `wander`. The game hides the object while `hide_flag` -// is set (an event flag, or a story state the game's code sets). -struct MapObject{ - std::string name; - ObjectKind kind = ObjectKind::NPC; - int x = 0; - int y = 0; - std::optional facing; - std::optional wander; - std::optional trainer; - std::optional hide_flag; -}; - -// A scene that starts when the player steps into `box` while the story is -// in `when` (any time, if left out): the decompilation's coord events. -struct MapTrigger{ - std::string name; - TileBox box; - std::optional when; -}; - -// Walking off the map's `side` continues on `to_map`, whose tiles are -// shifted by `offset` along that side. -struct MapConnection{ - Direction side = Direction::NORTH; - std::string to_map; - int offset = 0; -}; - -// A tile measured on the console that differs from the decompilation's. -struct MapPatch{ - int x = 0; - int y = 0; - TileKind glyph = TileKind::WALL; - std::string measured_by; -}; - // Complete map dataset including dimensions, collision tiles, warps, and objects. struct MapData{ std::string name; diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp index 554ec84c3e..9597502b70 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp @@ -27,7 +27,7 @@ namespace Pokemon{ namespace{ -const char* const VALID_MAP = R"({ +const std::string VALID_MAP = R"({ "name": "TestTown", "source": {"decomp_file": "data/maps/TestTown/map.json", "revision": "abc123", "date": "2026-10-31"}, "tiles": ["####", "#..~", "#D.S", "w^v#"], @@ -44,7 +44,7 @@ const char* const VALID_MAP = R"({ // A map shaped like BDSP's: on a world grid, with tiles off the game's // map, a region, a warp tile stood on, trainers, a person the story hides // and scene triggers. -const char* const BDSP_MAP = R"({ +const std::string BDSP_MAP = R"({ "name": "Route 201", "source": {"decomp_file": "pret/pokediamond: land_data narc_0000.bin", "revision": "default branch", "date": "2026-11-01"}, "world": {"name": "Sinnoh", "x": 96, "y": 839}, @@ -66,7 +66,7 @@ const char* const BDSP_MAP = R"({ // A map shaped like FRLG's: elevations, one-sided walls, warps of every // entry to per-warp points (one to a map not loaded), a person hidden by // an event flag, and a flag set. -const char* const FRLG_MAP = R"({ +const std::string FRLG_MAP = R"({ "name": "CeruleanCave_1F", "source": {"decomp_file": "data/maps/CeruleanCave_1F/map.json", "revision": "ce6406d8c2ea", "date": "2026-11-01"}, "allow_running": false, @@ -91,7 +91,7 @@ const char* const FRLG_MAP = R"({ // `base` with `find` replaced by `replacement`; empty when `find` is not // in it. -std::string edited(const char* base, const std::string& find, const std::string& replacement){ +std::string edited(const std::string& base, const std::string& find, const std::string& replacement){ std::string json = base; const size_t at = json.find(find); if (at == std::string::npos){ @@ -114,8 +114,8 @@ std::string parse_error(const std::string& json){ } // Whether `text` contains every one of `parts`. -bool mentions(const std::string& text, const std::vector& parts){ - for (const char* part : parts){ +bool mentions(const std::string& text, const std::vector& parts){ + for (const std::string& part : parts){ if (text.find(part) == std::string::npos){ return false; } @@ -181,7 +181,7 @@ UnitTestResult test_lists_may_be_left_out(){ } UnitTestResult test_glyphs_round_trip(){ - for (char glyph : std::string("#.~wv^<>DS 8246")){ + for (char glyph : std::string("#.~wv^<>DS 8246udlroHB")){ const std::optional tile = tile_from_glyph(glyph); if (!tile || glyph_of(*tile) != glyph){ return std::string("Glyph '") + glyph + "' does not round-trip."; @@ -193,10 +193,31 @@ UnitTestResult test_glyphs_round_trip(){ return true; } +// PokemonSimulation's tile-legend.json glyphs for forced movement, holes and +// boulder switches, in a map's rows. +UnitTestResult test_spin_hole_and_button_glyphs_parse(){ + const std::string json = R"({ + "name": "SpinRoom", + "source": {"decomp_file": "f", "revision": "r", "date": "d"}, + "tiles": ["udlroHB"] +})"; + const MapData map = parse_map(parse_json(json), "SpinRoom.json"); + constexpr TileKind EXPECTED[] = { + TileKind::SPIN_NORTH, TileKind::SPIN_SOUTH, TileKind::SPIN_WEST, TileKind::SPIN_EAST, + TileKind::STOP_SPIN, TileKind::FALL_HOLE, TileKind::STRENGTH_BUTTON, + }; + for (int x = 0; x < (int)std::size(EXPECTED); x++){ + if (map.tiles.at({x, 0}) != EXPECTED[x]){ + return std::format("Tile ({}, 0) read '{}'.", x, glyph_of(map.tiles.at({x, 0}))); + } + } + return true; +} + struct BadMap{ - const char* name; + std::string name; std::string json; - std::vector mentions; + std::vector mentions; }; // The first row whose map doesn't fail as it says, or true. @@ -241,7 +262,7 @@ UnitTestResult test_each_error_class(){ // One value read from a parsed map, and what it should be, both as text. struct Expected{ - const char* what; + std::string what; std::string expected; std::string read; }; @@ -327,7 +348,7 @@ UnitTestResult test_frlg_shaped_map(){ const auto elevation = [&](const TilePos& pos){ return std::to_string(map.elevation->at(pos)); }; - const auto warp = [&](WarpEntry enter, const TilePos& pos, const char* to){ + const auto warp = [&](WarpEntry enter, const TilePos& pos, std::string_view to){ return std::format("{} {} -> {}", to_string(pos), (int)enter, to); }; return first_wrong({ @@ -406,7 +427,7 @@ struct MapDataTestInput{ }; struct MapDataTestExpectation{ - const char* description; + std::string_view description; }; struct MapDataTestCase{ @@ -484,6 +505,10 @@ const MapDataTestCase MAP_DATA_CASES[] = { .input = {.name = "glyphs round-trip", .test = test_glyphs_round_trip}, .expectation = {.description = "converts between tile characters and enum kinds"}, }, + { + .input = {.name = "spin, hole and button glyphs", .test = test_spin_hole_and_button_glyphs_parse}, + .expectation = {.description = "parses u d l r o H B as the tile legend's spin, stop, hole and switch tiles"}, + }, { .input = {.name = "each error class", .test = test_each_error_class}, .expectation = {.description = "rejects invalid JSON syntax and malformed map schemas"}, diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h new file mode 100644 index 0000000000..e7af9fd8be --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h @@ -0,0 +1,100 @@ +/* Map Features + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_MapData.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_MapFeatures_H +#define PokemonAutomation_Pokemon_MapFeatures_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon_Grid.h" +#include "Pokemon_MapTiles.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A warp from (x, y), taken as `enter` says. `to` is left out for a warp +// to a map that is not loaded: the warp is still there, for routes to keep +// off. +struct MapWarp{ + int x = 0; + int y = 0; + WarpEntry enter = WarpEntry::WALK_INTO; + std::optional to; +}; + +// Type classification for interactive map objects. +enum class ObjectKind{ + NPC, + ITEM, + SIGN, +}; + +// A box of tiles, both corners inclusive. +struct TileBox{ + int x0 = 0; + int y0 = 0; + int x1 = 0; + int y1 = 0; +}; + +// A trainer sees `sight` tiles ahead in each direction of `looks` (their +// facing, unless the map says otherwise). +struct MapTrainer{ + int sight = 0; + std::vector looks; +}; + +// Something standing on a tile, which blocks it. A person who wanders may +// stand anywhere in `wander`. The game hides the object while `hide_flag` +// is set (an event flag, or a story state the game's code sets). +struct MapObject{ + std::string name; + ObjectKind kind = ObjectKind::NPC; + int x = 0; + int y = 0; + std::optional facing; + std::optional wander; + std::optional trainer; + std::optional hide_flag; +}; + +// A scene that starts when the player steps into `box` while the story is +// in `when` (any time, if left out): the decompilation's coord events. +struct MapTrigger{ + std::string name; + TileBox box; + std::optional when; +}; + +// Walking off the map's `side` continues on `to_map`, whose tiles are +// shifted by `offset` along that side. +struct MapConnection{ + Direction side = Direction::NORTH; + std::string to_map; + int offset = 0; +}; + +// A tile measured on the console that differs from the decompilation's. +struct MapPatch{ + int x = 0; + int y = 0; + TileKind glyph = TileKind::WALL; + std::string measured_by; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h new file mode 100644 index 0000000000..2184680cdf --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h @@ -0,0 +1,96 @@ +/* Map Tiles + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_MapData.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_MapTiles_H +#define PokemonAutomation_Pokemon_MapTiles_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What a tile is, for walking. The map files write each as one glyph. +enum class TileKind : uint8_t{ + WALL, // '#' + OPEN, // '.' + TALL_GRASS, // '~' open, with wild encounters + WATER, // 'w' + LEDGE_NORTH, // '^' a wall, except that walking into it the arrow's + LEDGE_SOUTH, // 'v' way hops the player over it + LEDGE_WEST, // '<' + LEDGE_EAST, // '>' + DOOR, // 'D' a door or warp tile walked into + SIGN, // 'S' a sign, read by facing it + OUTSIDE, // ' ' no map of the game's here (a map's rectangle + // reaching past the game's own) + CLOSED_NORTH, // '8' open, but not crossed through its named side: + CLOSED_SOUTH, // '2' not entered from it, nor left through it (the + CLOSED_WEST, // '4' number pad's arrows) + CLOSED_EAST, // '6' + SPIN_NORTH, // 'u' open; stepping on it slides the player north + SPIN_SOUTH, // 'd' (Rocket Hideout and Viridian Gym spin tiles) + SPIN_WEST, // 'l' + SPIN_EAST, // 'r' + STOP_SPIN, // 'o' open; where a spin's slide stops + FALL_HOLE, // 'H' open; a hole that drops the player a floor + STRENGTH_BUTTON,// 'B' open; Victory Road's switch for a boulder +}; +// The tile a glyph stands for, or nothing if it isn't one. +std::optional tile_from_glyph(char glyph); +// Returns the character glyph representing a TileKind. +char glyph_of(TileKind tile); + + +// Where the tiles came from: the decompilation file, at which revision, +// read when. +struct MapSource{ + std::string decomp_file; + std::string revision; + std::string date; +}; + +// Where the map lies on a world grid that several maps share (a BDSP map +// matrix): its tile (0, 0) is tile `offset` of world `name`. Maps on the +// same world join where they meet. +struct MapWorld{ + std::string name; + TilePos offset; +}; + +// Where a warp puts the player: point `point` of map `map`. +struct WarpDestination{ + std::string map; + std::string point; +}; + +// How the player takes a warp, as the map file writes it. +enum class WarpEntry{ + WALK_INTO, // "walk_into": a door or cave mouth, walked into + STEP_ON, // "step_on": stepping onto the tile (ladders, + // escalators, BDSP's warp tiles) + CAVE_ENTRANCE, // "cave_entrance": stepping onto the tile; the game + // walks a player arriving on it a tile south + WALK_NORTH, // "walk_north" ...: standing on the tile and walking + WALK_SOUTH, // that way (exit mats, stairs at the side of a room) + WALK_WEST, + WALK_EAST, +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp index 29a51c94ea..55ba9c14b0 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp @@ -36,11 +36,11 @@ std::string to_string(const RouteLogLeg& leg){ case RouteLegAction::WALK: break; } - const char* end = leg.end == RouteLegEnd::WALL ? " (to wall)" : leg.end == RouteLegEnd::WARP ? " (warp)" : " (open)"; - return direction + " " + std::to_string(leg.tiles) + end; + const std::string_view end = leg.end == RouteLegEnd::WALL ? " (to wall)" : leg.end == RouteLegEnd::WARP ? " (warp)" : " (open)"; + return direction + " " + std::to_string(leg.tiles) + std::string(end); } -const char* basis_name(EndBasis basis){ +std::string basis_name(EndBasis basis){ switch (basis){ case EndBasis::WALKED: return "walked"; @@ -53,16 +53,21 @@ const char* basis_name(EndBasis basis){ } +// " to ", as the plan and the leg lines both write a leg. +static std::string planned_leg_text(const PlannedRouteLeg& leg){ + return to_string(leg.leg) + " to " + describe(leg.after); +} + std::string route_plan_line(const std::string& label, const std::vector& from, const std::vector& legs){ std::string text = label + ": plan from " + describe(from) + ":"; - for (const PlannedRouteLeg& leg : legs){ - text += "\n " + to_string(leg.leg) + " to " + describe(leg.after); + for (size_t i = 0; i < legs.size(); i++){ + text += (i == 0 ? " " : "; ") + planned_leg_text(legs[i]); } return text; } std::string route_leg_line(size_t number, size_t count, const PlannedRouteLeg& leg){ - return std::format("Leg {}/{}: {} to {}", number, count, to_string(leg.leg), describe(leg.after)); + return std::format("Leg {}/{}: {}", number, count, planned_leg_text(leg)); } std::string route_leg_end_line( diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h index 07eb571f20..17cdaef020 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h @@ -7,9 +7,7 @@ * routes from it. These are BDSP AutoStory's route lines, lifted from * PokemonBDSP_AutoStory_RouteWalk.cpp, with what the other games need: * - * [Route] To the grass: plan from Route 202 (15, 25), Route 202 (16, 25): - * east 15 (to wall) to Route 202 (23, 25), Route 202 (30, 26) - * north 5 (to wall) to Route 202 (23, 24) + * [Route] To the grass: plan from Route 202 (15, 25), Route 202 (16, 25): east 15 (to wall) to Route 202 (23, 25), Route 202 (30, 26); north 5 (to wall) to Route 202 (23, 24) * [Route] Leg 1/2: east 15 (to wall) to Route 202 (23, 25), Route 202 (30, 26) * [Route] To the grass: east 15 (to wall): ended at Route 202 (23, 25) (walked). * [Route] To the grass: north 5 (to wall): stopped early after about 2 tiles, at Route 202 (23, 23); planning again. @@ -31,69 +29,18 @@ #include #include +#include #include #include "Pokemon_Grid.h" +#include "Pokemon_RouteLogLegs.h" namespace PokemonAutomation{ namespace Pokemon{ -// Prefix tag prepended to route navigation log messages. -inline constexpr const char* ROUTE_LOG_TAG = "[Route] "; - -// A tile of a named map. -struct RouteTile{ - std::string map; - TilePos pos; -}; -// "Route 202 (23, 25)". -std::string to_string(const RouteTile& tile); -// The tiles, comma-separated; "an unknown tile" for none. -std::string describe(const std::vector& tiles); - - -// Action type performed during a route leg. -enum class RouteLegAction{ - WALK, - SURF, - FACE, -}; - -// How a leg ends: at a wall, on a warp, or where it is timed to. -enum class RouteLegEnd{ - OPEN, - WALL, - WARP, -}; - -// Description of a single route movement segment. -struct RouteLogLeg{ - RouteLegAction action = RouteLegAction::WALK; - Direction direction = Direction::NORTH; - size_t tiles = 0; - RouteLegEnd end = RouteLegEnd::OPEN; -}; -// "east 15 (to wall)", "south 4 (open)", "north 1 (warp)", "surf east", -// "face west". -std::string to_string(const RouteLogLeg& leg); - -// A planned leg and the tiles it may end on. -struct PlannedRouteLeg{ - RouteLogLeg leg; - std::vector after; -}; - -// How the end of a walked leg is known. -enum class EndBasis{ - WALKED, // walked as planned, or seen - ASSUMED, // taken to have ended as planned after an interrupt - UNKNOWN, // stopped somewhere on the way -}; -// Returns the readable string representation of an end basis. -const char* basis_name(EndBasis basis); - - -// "