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 a0ce88ea19..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,6 +81,10 @@ 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); 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 63cce48b7a..e70da3dd48 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp @@ -14,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()){ @@ -25,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){ @@ -53,12 +53,13 @@ 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)); 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 86% rename from SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson_Tests.cpp rename to SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp index d01a4fe633..befc884cec 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp @@ -12,7 +12,7 @@ #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{ @@ -23,7 +23,7 @@ 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"}})"; // How a case fails, if it does. @@ -73,9 +73,23 @@ const AuthoredCase CASES[] = { }; +// 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 AuthoredCheckpoint& actual, const AuthoredCase& test){ +std::string check_loaded(const Loaded& actual, const AuthoredCase& test){ if (test.expectation.failure != Failure::NONE){ return "Expected rejection, read accepted authored checkpoint."; } @@ -93,7 +107,8 @@ 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."; } @@ -104,9 +119,10 @@ std::string check_loaded(const AuthoredCheckpoint& actual, const AuthoredCase& t 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(); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp similarity index 56% rename from SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp rename to SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp index a1483a3505..f81ecc7ef2 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp @@ -4,6 +4,7 @@ * */ +#include #include #include #include @@ -12,11 +13,10 @@ #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_TilePose.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" #include "Pokemon_StoryStepJson.h" namespace PokemonAutomation{ @@ -45,15 +45,6 @@ constexpr std::array, 15> KINDS{{ {StoryStepKind::GAME, "game_action"}, }}; -// The wire names of the pose certainties. -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"}, @@ -79,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; @@ -178,109 +169,138 @@ std::vector read_items(const JsonValue& value, std::string_view sourc return result; } -JsonObject args_json(const StoryArgs& args){ - JsonObject result; - for (const auto& [key, value] : args){ - std::visit([&](const auto& held){ result[key] = held; }, value); +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)); } return result; } -// A step's args: flags, whole numbers and words; any other value fails. -StoryArgs read_args(const JsonValue& value, std::string_view source){ - StoryArgs result; - for (const auto& [key, item] : value.to_object_throw(std::string(source))){ - if (item.is_boolean()){ - result[key] = item.to_boolean_throw(); - }else if (item.is_integer()){ - result[key] = item.to_integer_throw(); - }else if (item.is_string()){ - result[key] = item.to_string_throw(); - }else{ - throw ParseException(std::format("{}: argument {} is not a flag, whole number or word", source, key)); +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)}); } return result; } -// `result` with the step's yes/no and count fields read from `root`. -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(); +// 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)); } - if (const JsonValue* field = root.get_value("yes")){ - result.yes = field->to_boolean_throw(); + 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)); } - if (const JsonValue* field = root.get_value("may_lose")){ - result.may_lose = field->to_boolean_throw(); + 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; - } - if (kind != "tiles"){ - throw ParseException("Unsupported story position kind."); + 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); } - 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; } @@ -291,48 +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.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.action.empty()){ + result["action"] = step.action; } if (!step.args.empty()){ - result["args"] = args_json(step.args); + 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", "args", "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()){ @@ -342,30 +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("args")){ - result.args = read_args(*field, source); + 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; } @@ -375,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){ @@ -385,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"); @@ -394,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."); } 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/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp similarity index 51% rename from SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp rename to SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp index 60178eae1f..2b885a66a0 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp @@ -11,12 +11,13 @@ #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_Tests.h" +#include "Pokemon/AutoStory/Pokemon_AutoStory_Tests.h" #endif namespace PokemonAutomation{ @@ -52,37 +53,62 @@ struct WireCase{ }; 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 = "args", .json = R"({"id":"buy","kind":"game_action","variant":"mart","args":{"map":"CeruleanCity_Mart","budget":3000,"if_present":true}})"}, .expectation = {.canonical = R"({"id":"buy","kind":"game_action","variant":"mart","args":{"budget":3000,"if_present":true,"map":"CeruleanCity_Mart"}})"}}, - {.input = {.name = "empty args are omitted", .json = R"({"id":"buy","kind":"game_action","variant":"mart","args":{}})"}, .expectation = {.canonical = R"({"id":"buy","kind":"game_action","variant":"mart"})"}}, - {.input = {.name = "fractional arg", .json = R"({"id":"a","kind":"game_action","variant":"mart","args":{"budget":1.5}})"}, .expectation = {.rejected = true}}, - {.input = {.name = "nested arg", .json = R"({"id":"a","kind":"game_action","variant":"mart","args":{"items":[1]}})"}, .expectation = {.rejected = true}}, - {.input = {.name = "args not an object", .json = R"({"id":"a","kind":"game_action","variant":"mart","args":["map"]})"}, .expectation = {.rejected = true}}, + {.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 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 = "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 story_pose_json(read_story_pose(value, input.name)); + return grid_pose_json(read_grid_pose(value, input.name)); case Record::STEP: - return story_step_json(read_story_step(value, input.name)); + return story_step_json(read_story_step(value, input.name, actions)); case Record::CHECKPOINT: - return story_checkpoint_json(read_story_checkpoint(value, input.name)); + return story_checkpoint_json(read_story_checkpoint(value, input.name, actions)); } throw ParseException("Unknown test record."); } @@ -108,7 +134,7 @@ std::string check_case(const WireCase& test){ #ifdef PA_STORY_DATA_STANDALONE // A shared case file's record kind. -Record record_kind(const std::string& name){ +Record record_kind(std::string_view name){ if (name == "pose"){ return Record::POSE; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.h deleted file mode 100644 index 5bcbc181a2..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.h +++ /dev/null @@ -1,56 +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 "Types/Pokemon_StoryCheckpoint.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_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 6686331ee6..80205a98f2 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -10,48 +10,32 @@ #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); // Registers unit tests for the lossless shared story-data wire contract. void add_tests_StoryStepJson(UnitTestDatabase& database); -// Registers unit tests for step args: action specs and reading old variant strings. -void add_tests_StoryArgs(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 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); -// Registers every suite above, for the unit test runner. +// 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_StoryEvents(database); - add_tests_StorySegments(database); - add_tests_StorySteps(database); + add_tests_StoryStepExecutor(database); add_tests_StoryStepJson(database); - add_tests_StoryArgs(database); + add_tests_StoryActionArg(database); add_tests_AuthoredCheckpointJson(database); - add_tests_StoryLog(database); - add_tests_StoryRangeOptions(database); } 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_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 b58a85cd9a..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"; @@ -30,7 +30,7 @@ const char* screen_event_name(ScreenEvent event){ 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"; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h index 800351a306..ee3080235d 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h @@ -30,165 +30,12 @@ #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. - 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. -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. diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp index 6620fd0204..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; @@ -129,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; 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 fb95a779f8..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); } @@ -67,11 +66,13 @@ std::vector lint_story_checkpoint(const StoryCheckpoint& data, cons for (size_t c = 0; c < data.steps.size(); c++){ const StoryStep& step = data.steps[c]; const StoryAction* action = table.find(step); - const std::string error = action == nullptr ? "no action" : story_args_error(step.args, action->args); - if (!error.empty()){ + const std::vector errors = action == nullptr + ? std::vector{"no action"} + : story_args_errors(StoryActionSpec{.kind = step.kind, .name = step.action, .args = action->args}, step.args); + for (const std::string& error : errors){ problems.emplace_back(std::format( "{} step {} {}: {} for {} '{}'", - data.id, c + 1, step.name, error, story_step_kind_name(step.kind), variant_name(step.variant) + data.id, c + 1, step.name, error, story_step_kind_name(step.kind), step.action )); } } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h index 3f778729ee..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. * @@ -30,7 +30,8 @@ #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{ @@ -50,26 +51,26 @@ struct StoryAction{ 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::span args = {}; + 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: diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp index c29ac429e3..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"}, }; @@ -169,13 +99,13 @@ UnitTestResult test_duplicate_actions_throw(){ } // The args a test Mart takes. -constexpr StoryArgSpec MART_ARGS[] = { - {.key = "map", .type = StoryArgType::TEXT, .required = true}, - {.key = "budget", .type = StoryArgType::NUMBER, .required = true}, +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, StoryArgs args){ +StoryStep with_args(StoryStep step, StoryActionArgs args){ step.args = std::move(args); return step; } @@ -192,9 +122,9 @@ UnitTestResult test_lint_names_steps_without_actions(){ .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")}}), @@ -351,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"}, diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryArgs_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryArgs_Tests.cpp deleted file mode 100644 index 889639d650..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryArgs_Tests.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/* Story Args Tests - * - * From: https://github.com/PokemonAutomation/ - * - * Checking a step's args against an action's specs, and reading an old - * "name key=value" variant into a name and args. Built standalone - * (PA_STORY_DATA_STANDALONE), it runs without the application. - * - */ - -#include -#include -#include -#include -#include "Pokemon_StoryVariant.h" -#include "Types/Pokemon_StoryArgs.h" -#ifndef PA_STORY_DATA_STANDALONE -#include "Pokemon_AutoStory_Tests.h" -#endif - -namespace PokemonAutomation{ -namespace Pokemon{ - - -namespace{ - - -// The args a Mart step takes, as an action declares them. -constexpr StoryArgSpec MART_SPECS[] = { - {.key = "map", .type = StoryArgType::TEXT, .required = true}, - {.key = "budget", .type = StoryArgType::NUMBER, .required = true}, - {.key = "floor", .type = StoryArgType::NUMBER}, - {.key = "if_present", .type = StoryArgType::FLAG}, -}; - -constexpr std::string_view MART_POSITIONAL[] = {"map"}; - - -// An old variant, read with an action's positional keys and checked -// against its specs. -struct ArgsInput{ - std::string_view name; - std::string_view variant; - std::span specs = MART_SPECS; - std::span positional = MART_POSITIONAL; -}; - -// The action name and args it gives, and the first error: the split's, -// else the specs'. -struct ArgsExpectation{ - std::string_view action; - StoryArgs args = {}; - std::string_view error = {}; -}; - -struct ArgsCase{ - ArgsInput input; - ArgsExpectation expectation; -}; - -const ArgsCase CASES[] = { - {.input = {.name = "mart", .variant = "mart CeruleanCity_Mart budget=1500 floor=1500 if_present"}, - .expectation = {.action = "mart", .args = {{"map", std::string("CeruleanCity_Mart")}, {"budget", int64_t(1500)}, {"floor", int64_t(1500)}, {"if_present", true}}}}, - {.input = {.name = "plain name", .variant = "run", .specs = {}, .positional = {}}, .expectation = {.action = "run"}}, - {.input = {.name = "words stay words", .variant = "teach tutor forget=tail-whip", .specs = {}, .positional = {}}, - .expectation = {.action = "teach", .args = {{"tutor", true}, {"forget", std::string("tail-whip")}}, .error = "unknown argument \"forget\""}}, - {.input = {.name = "unknown key", .variant = "mart M budget=1 budgte=1"}, - .expectation = {.action = "mart", .args = {{"map", std::string("M")}, {"budget", int64_t(1)}, {"budgte", int64_t(1)}}, .error = "unknown argument \"budgte\""}}, - {.input = {.name = "wrong type", .variant = "mart M budget=lots"}, - .expectation = {.action = "mart", .args = {{"map", std::string("M")}, {"budget", std::string("lots")}}, .error = "argument \"budget\" has the wrong type"}}, - {.input = {.name = "missing required", .variant = "mart M"}, - .expectation = {.action = "mart", .args = {{"map", std::string("M")}}, .error = "missing argument \"budget\""}}, - {.input = {.name = "repeated key", .variant = "mart M budget=1 budget=2"}, - .expectation = {.action = "mart", .args = {{"map", std::string("M")}, {"budget", int64_t(1)}}, .error = "\"budget=2\" repeats an argument"}}, -}; - - -// "" when `test` reads as expected, else what differs. -std::string check_case(const ArgsCase& test){ - const LegacyVariant read = split_legacy_variant(test.input.variant, test.input.positional); - const std::string error = read.error.empty() ? story_args_error(read.args, test.input.specs) : read.error; - if (read.name != test.expectation.action || read.args != test.expectation.args){ - return "read \"" + read.name + "\" with other args"; - } - if (error != test.expectation.error){ - return "expected error \"" + std::string(test.expectation.error) + "\", got \"" + error + "\""; - } - return ""; -} - - -#ifndef PA_STORY_DATA_STANDALONE - -class StoryArgsTest : public UnitTest{ -public: - explicit StoryArgsTest(ArgsCase test) - : UnitTest("Pokemon::StoryArgs - " + 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_StoryArgs(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/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 f9a87c6778..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,10 +60,7 @@ 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; @@ -86,7 +83,7 @@ std::string to_string(const Outcome& outcome){ } Outcome outcome_game_not_running(){ - return outcome_failed(GAME_NOT_RUNNING, "the game is not running: the Switch HOME menu is showing"); + 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){ @@ -100,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"; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h index 582518b9c3..3e94a6996f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h @@ -32,212 +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); - -// 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. -constexpr const char* 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; -// 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; - - // 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.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h index 15b024134e..b9f5abe2a9 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h @@ -43,77 +43,13 @@ #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. 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; -}; - - // 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{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp index f9b4b9d079..764352933d 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -183,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; @@ -197,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; } @@ -225,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); @@ -475,7 +475,7 @@ UnitTestResult test_screen_before_each_step(){ executor.set_interrupts(&interrupts); RunState state; StoryStep step = make(StoryStepKind::ROUTE, "by_the_counter"); - step.variant = "act"; + 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); @@ -508,7 +508,7 @@ UnitTestResult test_home_menu_before_a_step(){ executor.set_interrupts(&interrupts); RunState state; StoryStep step = make(kind, "save"); - step.variant = "act"; + 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); @@ -553,12 +553,8 @@ UnitTestResult test_home_menu_stops_the_segment(){ trace.push_back("reload"); return outcome_ok(); }; - hooks.recover = [&trace](RunState&, const std::string&){ - trace.push_back("recover in place"); - return outcome_ok(); - }; RunState state; - const SegmentReport report = run_segment(state, segment, SegmentRange{}, SegmentPolicy{.recoveries_per_event = 2}, hooks); + 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); } @@ -574,9 +570,9 @@ UnitTestResult test_home_menu_stops_the_segment(){ UnitTestResult test_settle_of_a_look(){ struct Row{ - const char* name; + std::string name; ScreenLook look; - const char* expected; + std::string expected; }; const std::vector rows = { {"no frame", ScreenLook{}, "no frame seen"}, diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp index 8b5b3e0dca..0a9262d2c0 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp @@ -27,20 +27,18 @@ std::string event_log_line(std::string_view checkpoint, size_t number, std::stri return std::format("[Event] {}/{} {}: {}", checkpoint, number, event, status); } -std::string checkpoint_start_line(std::string_view checkpoint){ - return std::format("[Checkpoint] {}: start", checkpoint); -} - -std::string checkpoint_start_line(std::string_view checkpoint, size_t events){ - return std::format("[Checkpoint] {}: start, {} events", checkpoint, events); -} - -std::string checkpoint_attempt_line(std::string_view checkpoint, size_t attempt){ - return std::format("[Checkpoint] {}: attempt {}", checkpoint, attempt); +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, size_t attempts){ - return std::format("[Checkpoint] {}: attempt {}/{}", checkpoint, attempt, attempts); +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){ @@ -55,7 +53,7 @@ std::string checkpoint_reset_line(std::string_view checkpoint, size_t next_attem return std::format("[Checkpoint] {}: failed, resetting for attempt {}", checkpoint, next_attempt); } -std::string checkpoint_reset_line(std::string_view segment, std::string_view checkpoint, size_t next_attempt, size_t attempts){ +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 diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h index 5b5df714a9..f9576e1e69 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h @@ -15,6 +15,7 @@ #define PokemonAutomation_Pokemon_StoryLog_H #include +#include #include #include #include "Pokemon_AutoStoryStats.h" @@ -28,19 +29,18 @@ namespace Pokemon{ // [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: +// A checkpoint starts; the story engine also says it has `events` events: // [Checkpoint] 00.04: start -std::string checkpoint_start_line(std::string_view checkpoint); -// The story engine starts a checkpoint of `events` events: // [Checkpoint] 00.04: start, 3 events -std::string checkpoint_start_line(std::string_view checkpoint, size_t events); +std::string checkpoint_start_line(std::string_view checkpoint, std::optional events = std::nullopt); -// An attempt at a checkpoint starts, counting from 1: +// 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 -std::string checkpoint_attempt_line(std::string_view checkpoint, size_t attempt); -// The same, out of the program's limit of `attempts`: // [Checkpoint] 00.04: attempt 2/3 -std::string checkpoint_attempt_line(std::string_view checkpoint, size_t attempt, size_t attempts); +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: @@ -54,7 +54,7 @@ std::string checkpoint_pass_line(std::string_view checkpoint, size_t attempt, si 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 checkpoint_reset_line(std::string_view segment, std::string_view checkpoint, size_t next_attempt, size_t attempts); +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. diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp index 7737d2cb41..86b1e59b86 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp @@ -9,7 +9,7 @@ #include #include #include "Common/Cpp/TestRunners/UnitTest.h" -#include "Pokemon_AutoStory_Tests.h" +#include "Pokemon_StoryRun_Tests.h" #include "Pokemon_StoryLog.h" namespace PokemonAutomation{ @@ -90,7 +90,7 @@ const StoryLogCase STORY_LOG_CASES[] = { .expectation = {.line = "[Checkpoint] 00.04: failed, resetting for attempt 2"}, }, { - .input = {.name = "reload within a segment", .line = checkpoint_reset_line("00", "00.02", 2, 3)}, + .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"}, }, }; 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 358f606dc6..64becf2b68 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp @@ -103,28 +103,9 @@ Outcome reload(RunState& state, SegmentHooks& hooks){ return outcome_ok(); } -// 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)); - } -} - // 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 @@ -137,27 +118,21 @@ 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, checkpoint_pass_line(spec.id, attempt, run.recoveries)); + say(hooks, checkpoint_pass_line(spec.id, attempt)); return result; } - const bool not_running = result.failure.failure == GAME_NOT_RUNNING; - if (not_running || policy.stop_at_first_failure){ - say(hooks, std::format("[Segment] {}: {} failed; {}", segment.id, spec.id, not_running - ? "the game is not running, so no reload" - : "stopping at the first failure, the game stays where it failed" - )); - report.stopped_at_first_failure = !not_running; + 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, checkpoint_reset_line(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()){ @@ -182,19 +157,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 8e2426aee8..da96488d14 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, @@ -62,58 +59,6 @@ struct SegmentHooks{ EventLogger status; }; -// 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 @@ -122,7 +67,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 4575d6d396..6f04df6548 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp @@ -412,7 +412,7 @@ struct StorySegmentInput{ }; struct StorySegmentExpectation{ - const char* description; + std::string_view description; }; struct StorySegmentTestCase{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp similarity index 54% rename from SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp rename to SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp index 07cf478f66..f28e3016f2 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp @@ -1,20 +1,23 @@ -/* Story Steps +/* Story Step Executor * * From: https://github.com/PokemonAutomation/ * */ #include -#include #include #include -#include "Pokemon_StoryLog.h" -#include "Pokemon_StorySteps.h" +#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)); } @@ -22,8 +25,8 @@ Outcome unsupported_step(const StoryStep& step){ void StoryStepExecutor::begin_attempt(const StoryCheckpoint&){} -bool StoryStepExecutor::holds(const std::string& condition, RunState& state){ - return state.flags.contains(condition); +bool StoryStepExecutor::holds(std::string_view condition, RunState& state){ + return state.flags.contains(std::string(condition)); } @@ -39,7 +42,9 @@ Event story_event(const StoryStep& step, StoryStepExecutor& executor){ event.act = [&executor, &step](RunState& state){ return executor.run(state, step); }; - event.pose_learned = step.pose_after; + if (step.pose_after){ + event.pose_learned = pose_of(*step.pose_after); + } return event; } @@ -58,19 +63,6 @@ Event from_save_event(const Pose& start){ } // 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 @@ -91,13 +83,17 @@ void run_once_per_save(Event& event, std::string key, PreparedSteps& prepared){ } // 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); +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; @@ -106,31 +102,29 @@ Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor 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"; - } +// 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 ""; - 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 ""; } + return problems; } } // namespace @@ -149,9 +143,8 @@ std::vector lint_story_checkpoint(const StoryCheckpoint& data){ }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)); + 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()){ @@ -162,32 +155,6 @@ std::vector lint_story_checkpoint(const StoryCheckpoint& data){ } -void record_story_stats(AutoStoryStats& stats, const SegmentReport& report){ - StoryRunCounts counts{.segments = 1, .checkpoints = 0, .resets = report.reloads}; - for (const CheckpointRun& run : report.runs){ - if (run.passed){ - counts.checkpoints++; - } - } - record_story_counts(stats, counts); -} - - -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_StoryStepExecutor.h similarity index 70% rename from SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h rename to SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h index 7b76155d63..0d8c595bfa 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h @@ -1,4 +1,4 @@ -/* Story Steps +/* Story Step Executor * * From: https://github.com/PokemonAutomation/ * @@ -29,19 +29,16 @@ * */ -#ifndef PokemonAutomation_Pokemon_StorySteps_H -#define PokemonAutomation_Pokemon_StorySteps_H +#ifndef PokemonAutomation_Pokemon_StoryStepExecutor_H +#define PokemonAutomation_Pokemon_StoryStepExecutor_H -#include #include #include +#include #include -#include "Pokemon/Navigation/Pokemon_Grid.h" -#include "Pokemon_AutoStoryStats.h" #include "Pokemon_StoryEvents.h" -#include "Pokemon_StorySegments.h" #include "Pokemon_TilePose.h" -#include "Types/Pokemon_StoryChecks.h" +#include "Types/Pokemon_GridPose.h" #include "Types/Pokemon_StoryCheckpoint.h" #include "Types/Pokemon_StoryStep.h" #include "Types/Pokemon_StoryStepKind.h" @@ -68,9 +65,12 @@ class StoryStepExecutor{ // 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); + 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); @@ -79,41 +79,28 @@ Outcome unsupported_step(const StoryStep& step); // 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); +// 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 route or READY without a target, empty legs, a GAME -// step without a variant, TRAIN without battles, SHOP without items. +// 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); -// 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 diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp similarity index 83% rename from SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp rename to SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp index a61a345ee2..4aab90ad2a 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp @@ -19,10 +19,13 @@ #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" @@ -38,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. @@ -68,7 +71,7 @@ class FakeExecutor : public StoryStepExecutor{ 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); } @@ -77,7 +80,7 @@ class FakeExecutor : public StoryStepExecutor{ Outcome run_kind(RunState& state, const StoryStep& step){ switch (step.kind){ case StoryStepKind::ROUTE: - return outcome_ok(*step.target); + return outcome_ok(pose_of(story_arg(step.args, "target"))); case StoryStepKind::STEP: return step_one_tile(state, step); case StoryStepKind::TALK: @@ -85,7 +88,7 @@ class FakeExecutor : public StoryStepExecutor{ return outcome_ok(); case StoryStepKind::BATTLE: // The first battle is lost; a step that may lose goes on. - return step.may_lose ? outcome_ok() : outcome_failed("blackout"); + return story_arg(step.args, "may_lose") ? outcome_ok() : outcome_failed("blackout"); case StoryStepKind::SHOP: return shop(step); case StoryStepKind::GAME: @@ -100,20 +103,21 @@ class FakeExecutor : public StoryStepExecutor{ 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)); + const Direction direction = story_arg(step.args, "direction"); + return outcome_ok(tile_pose(state.pose.map, {tiles[0].next(direction)}, direction)); } Outcome shop(const StoryStep& step){ - for (const StoryItem& item : step.items){ + 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. + // A game step sets a run flag named for its action. Outcome game(RunState& state, const StoryStep& step){ - trace.push_back(" game " + step.variant); - state.flags.insert(step.variant); + trace.push_back(" game " + step.action); + state.flags.insert(step.action); return unchanged.contains(step.name) ? outcome_unchanged() : outcome_ok(); } }; @@ -122,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; @@ -147,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, @@ -294,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"){ @@ -346,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")}, }, }; @@ -369,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 @@ -384,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")}, }, }; @@ -416,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); } }; @@ -449,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`. @@ -488,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; @@ -497,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; } @@ -509,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; } @@ -527,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); } }; @@ -538,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(); @@ -561,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(); @@ -601,7 +587,13 @@ const std::vector& two_sections(){ } 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; } @@ -626,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."; } @@ -643,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."; } @@ -658,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. @@ -681,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."; } @@ -706,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){ @@ -734,7 +726,7 @@ struct StoryStepInput{ }; struct StoryStepExpectation{ - const char* description; + std::string_view description; }; struct StoryStepTestCase{ @@ -742,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{ @@ -806,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}, @@ -826,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 b50caadc58..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.h +++ /dev/null @@ -1,48 +0,0 @@ -/* 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. - * - */ - -#ifndef PokemonAutomation_StoryStepJson_H -#define PokemonAutomation_StoryStepJson_H - -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" -#include "Types/Pokemon_StoryCheckpoint.h" -#include "Types/Pokemon_StoryStep.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_StoryVariant.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.cpp deleted file mode 100644 index a10163f584..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.cpp +++ /dev/null @@ -1,98 +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; -} - -LegacyVariant split_legacy_variant(std::string_view variant, std::span positional){ - LegacyVariant result; - const std::vector words = variant_words(variant); - result.name = variant_name(variant); - size_t next = 0; - for (size_t c = result.name.empty() ? 0 : 1; c < words.size(); c++){ - std::string key; - StoryArgValue value = true; - if (const std::optional pair = variant_pair(words[c])){ - key = pair->key; - const std::optional number = variant_number(pair->value, 18); - value = number ? StoryArgValue(int64_t(*number)) : StoryArgValue(std::string(pair->value)); - }else if (next < positional.size()){ - key = positional[next++]; - value = std::string(words[c]); - }else{ - key = words[c]; - } - if (!result.args.emplace(std::move(key), std::move(value)).second){ - result.error = "\"" + std::string(words[c]) + "\" repeats an argument"; - return result; - } - } - return result; -} - - - -} // 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 bd8c02343a..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.h +++ /dev/null @@ -1,75 +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. - * - * Deprecated: a step's variant is now a plain action name and its - * arguments are structured (StoryStep::args, Types/Pokemon_StoryArgs.h). - * split_legacy_variant() reads an old variant into that form while plans - * and callers move over; the word helpers go once none reads them. - * - */ - -#ifndef PokemonAutomation_Pokemon_StoryVariant_H -#define PokemonAutomation_Pokemon_StoryVariant_H - -#include -#include -#include -#include -#include -#include -#include "Types/Pokemon_StoryArgs.h" - -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); - - -// An old variant as an action name and its args, or why it can't be read. -struct LegacyVariant{ - std::string name; - StoryArgs args; - std::string error; -}; - -// `variant` written the old way ("mart CeruleanCity_Mart budget=3000 -// if_present"): its first word is the name; the next plain words take the -// keys in `positional`, in order, and plain words after those are flags; -// "key=value" words are numbers when all digits, else words. It reads no -// action's specs: check the args against them (story_args_error()). -LegacyVariant split_legacy_variant(std::string_view variant, std::span positional = {}); - - - -} // 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_StoryArgs.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryArgs.cpp deleted file mode 100644 index c4da5548fd..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryArgs.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* Story Args - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Pokemon_StoryArgs.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -namespace{ - - -template -const Type* find_arg(const StoryArgs& args, std::string_view key){ - const auto iter = args.find(key); - return iter == args.end() ? nullptr : std::get_if(&iter->second); -} - -bool has_type(const StoryArgValue& value, StoryArgType type){ - switch (type){ - case StoryArgType::FLAG: - return std::holds_alternative(value); - case StoryArgType::NUMBER: - return std::holds_alternative(value); - case StoryArgType::TEXT: - return std::holds_alternative(value); - } - return false; -} - -const StoryArgSpec* find_spec(std::span specs, std::string_view key){ - for (const StoryArgSpec& spec : specs){ - if (spec.key == key){ - return &spec; - } - } - return nullptr; -} - - -} // namespace - - -std::optional story_arg_number(const StoryArgs& args, std::string_view key){ - const int64_t* value = find_arg(args, key); - return value ? std::optional(*value) : std::nullopt; -} - -std::optional story_arg_text(const StoryArgs& args, std::string_view key){ - const std::string* value = find_arg(args, key); - return value ? std::optional(*value) : std::nullopt; -} - -bool story_arg_flag(const StoryArgs& args, std::string_view key){ - const bool* value = find_arg(args, key); - return value != nullptr && *value; -} - -std::string story_args_error(const StoryArgs& args, std::span specs){ - for (const auto& [key, value] : args){ - const StoryArgSpec* spec = find_spec(specs, key); - if (spec == nullptr){ - return std::format("unknown argument \"{}\"", key); - } - if (!has_type(value, spec->type)){ - return std::format("argument \"{}\" has the wrong type", key); - } - } - for (const StoryArgSpec& spec : specs){ - if (spec.required && args.find(spec.key) == args.end()){ - return std::format("missing argument \"{}\"", spec.key); - } - } - return ""; -} - - - -} // namespace Pokemon -} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryArgs.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryArgs.h deleted file mode 100644 index 96214deed7..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryArgs.h +++ /dev/null @@ -1,68 +0,0 @@ -/* Story Args - * - * From: https://github.com/PokemonAutomation/ - * - * A step's arguments (StoryStep::args): named flags, whole numbers and - * words that its action reads, e.g. a Mart step's {"map": - * "CeruleanCity_Mart", "budget": 3000}. Each action declares the ones it - * takes (StoryArgSpec); a game checks a step's args against them when it - * loads the step, so a typo fails at load instead of mid-run. - * - */ - -#ifndef PokemonAutomation_Pokemon_StoryArgs_H -#define PokemonAutomation_Pokemon_StoryArgs_H - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace PokemonAutomation{ -namespace Pokemon{ - - -// One argument's value: a flag, a whole number or a word. -using StoryArgValue = std::variant; - -// A step's arguments by name. -using StoryArgs = std::map>; - - -// The number `key` holds; nothing if absent or not a number. -std::optional story_arg_number(const StoryArgs& args, std::string_view key); - -// The word `key` holds; nothing if absent or not a word. -std::optional story_arg_text(const StoryArgs& args, std::string_view key); - -// Whether flag `key` is set; absent is unset. -bool story_arg_flag(const StoryArgs& args, std::string_view key); - - -// The type an action declares for an argument. -enum class StoryArgType{ - FLAG, - NUMBER, - TEXT, -}; - -// An argument an action takes. -struct StoryArgSpec{ - std::string_view key; - StoryArgType type = StoryArgType::TEXT; - bool required = false; -}; - -// Why `args` don't fit `specs`: a key no spec names, a value of another -// type, or a required one missing. Empty when they fit. -std::string story_args_error(const StoryArgs& args, std::span specs); - - - -} // 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 index 7071035402..9374862ecb 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h @@ -4,7 +4,7 @@ * * 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_StorySteps.h) turns it into engine events. + * (Pokemon_StoryStepExecutor.h) turns it into engine events. * */ @@ -14,7 +14,7 @@ #include #include #include -#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "Pokemon_GridPose.h" #include "Pokemon_StoryStep.h" namespace PokemonAutomation{ @@ -26,7 +26,7 @@ struct StoryCheckpoint{ std::string id; std::string title; // Where its starting save leaves the player; none for a new game. - std::optional start; + std::optional start; std::vector steps; }; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.cpp deleted file mode 100644 index 1ea9bbb92a..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* Story Checks - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon_StoryChecks.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -const char* story_checks_name(StoryChecks checks){ - switch (checks){ - case StoryChecks::THOROUGH: - return "thorough"; - case StoryChecks::FAST: - return "fast"; - } - return "?"; -} - - - -} // namespace Pokemon -} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.h deleted file mode 100644 index 3dba180603..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.h +++ /dev/null @@ -1,33 +0,0 @@ -/* Story Checks - * - * 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_StoryChecks_H -#define PokemonAutomation_Pokemon_StoryChecks_H - -namespace PokemonAutomation{ -namespace Pokemon{ - - -// How much a step reads the screen to confirm what it did. -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); - - - -} // 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 index 8255c60e3f..26cd129bce 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h @@ -2,72 +2,40 @@ * * From: https://github.com/PokemonAutomation/ * - * One step of a tile game's story (FRLG, BDSP) as plain data: its kind - * and the fields that kind reads. A game's executor does it - * (Pokemon_StorySteps.h); the shared JSON reads and writes it - * (Pokemon_StoryStepJson.h). + * 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 -#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" -#include "Pokemon/Navigation/Pokemon_Grid.h" -#include "Pokemon_StoryArgs.h" +#include "Pokemon_GridPose.h" +#include "Pokemon_StoryActionArg.h" #include "Pokemon_StoryStepKind.h" namespace PokemonAutomation{ namespace Pokemon{ -// 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. A plain name; what the action needs beyond - // it goes in `args`. - std::string variant; - // The arguments the variant's action reads (a Mart's map and budget), - // checked against the ones it declares when the game loads the step. - StoryArgs args; + // 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 @@ -82,7 +50,7 @@ struct StoryStep{ 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; + std::optional pose_after; }; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp index 8491db4f90..28b755779b 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp @@ -10,7 +10,7 @@ namespace PokemonAutomation{ namespace Pokemon{ -const char* story_step_kind_name(StoryStepKind kind){ +std::string story_step_kind_name(StoryStepKind kind){ switch (kind){ case StoryStepKind::NEW_GAME: return "NEW_GAME"; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h index a62d40e7d6..2e43aa8118 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h @@ -3,13 +3,15 @@ * 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_StorySteps.h). + * 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{ @@ -34,7 +36,7 @@ enum class StoryStepKind{ }; // Returns the readable string representation of a story step kind. -const char* story_step_kind_name(StoryStepKind kind); +std::string story_step_kind_name(StoryStepKind kind); 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 1e0b488e6a..24bf93b039 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp @@ -45,7 +45,7 @@ constexpr std::pair GLYPHS[] = { {'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 bb860467c0..6b4d923fbf 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h @@ -46,148 +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' - 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, -}; - -// 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 e745d28bd8..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; } @@ -215,9 +215,9 @@ UnitTestResult test_spin_hole_and_button_glyphs_parse(){ } 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. @@ -262,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; }; @@ -348,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({ @@ -427,7 +427,7 @@ struct MapDataTestInput{ }; struct MapDataTestExpectation{ - const char* description; + std::string_view description; }; struct MapDataTestCase{ 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); - - -// "