diff --git a/.github/workflows/story-data.yml b/.github/workflows/story-data.yml new file mode 100644 index 0000000000..8576b19548 --- /dev/null +++ b/.github/workflows/story-data.yml @@ -0,0 +1,30 @@ +name: Story data codec +on: + pull_request: + workflow_dispatch: +jobs: + native-codec: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v7 + - uses: actions/checkout@v7 + with: + repository: dayfine/PokemonSimulation + # Synthetic contract cases, not an approved map/resource pin. + ref: 866613fa03e5c4a5eb7e57c91b59fafb44fc7ee3 + path: publisher + - uses: actions/setup-python@v6 + with: + python-version: '3.12' + - name: Check the Python reader against the same cases + working-directory: publisher + env: + PYTHONPATH: src + run: python -m unittest pokesim.story.test_checkpoint_wire + - run: cmake -S devtools/story-data-tests -B build-story-data -DCMAKE_BUILD_TYPE=Debug + - run: cmake --build build-story-data --config Debug -j4 + - run: ctest --test-dir build-story-data -C Debug --output-on-failure diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp new file mode 100644 index 0000000000..f021fe29b0 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp @@ -0,0 +1,71 @@ +/* Shared Authored Checkpoint JSON + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_StoryStepJson.h" +#include "Pokemon_AuthoredCheckpointJson.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +void validate_json_fields( + const JsonObject& object, std::initializer_list fields, std::string_view source +){ + if (object.size() != fields.size()){ + throw ParseException(std::format("{}: missing or extra authored checkpoint fields.", source)); + } + for (std::string_view field : fields){ + object.get_value_throw(std::string(field), std::string(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)); + 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)); + } + 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){ + if (game.empty()){ + throw ParseException("Authored checkpoint game must not be empty."); + } + JsonObject result; + result["format"] = "pokesim-authored-checkpoint/1"; + result["game"] = std::string(game); + result["checkpoint"] = story_checkpoint_json(checkpoint); + result["execution"] = std::move(execution); + return result; +} + +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), game, file, read_execution, actions); + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("Authored checkpoint is not embedded: {}", file)); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h new file mode 100644 index 0000000000..9e20f7a252 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h @@ -0,0 +1,72 @@ +/* Shared Authored Checkpoint JSON + * + * From: https://github.com/PokemonAutomation/ + * + * Reading and writing an authored checkpoint file: the shared + * StoryCheckpoint (Pokemon_StoryStepJson.h) in an envelope that names the + * game, plus the game's own execution object, which the game parses into + * its own type through a reader it passes in. Only parsing and encoding: + * nothing here binds or runs a step, and nothing read keeps JSON. + * + */ + +#ifndef PokemonAutomation_AuthoredCheckpointJson_H +#define PokemonAutomation_AuthoredCheckpointJson_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The game's reader of an envelope's execution object: it parses the +// object into the game's own type and throws ParseException when it is +// malformed. +using ExecutionReader = std::function; + +// Require exactly these fields, including fields whose value is null/zero/false. +// Missing/unknown fields throw ParseException with the document source. +void validate_json_fields( + const JsonObject& object, std::initializer_list fields, std::string_view source +); + +// The checkpoint of `game`'s strict authored envelope, its steps read +// against `actions` (read_story_checkpoint()); its execution object goes +// to `read_execution`. +StoryCheckpoint read_authored_checkpoint( + const JsonValue& value, std::string_view game, std::string_view source, + const ExecutionReader& read_execution, + std::span actions = builtin_story_actions() +); + +// Encode the authored envelope; execution is supplied by the game adapter. +// This does not encode game bookkeeping or the legacy native-export envelope. +JsonValue authored_checkpoint_json(const StoryCheckpoint& checkpoint, std::string_view game, JsonObject execution); + +// A JSON file built into the program: its name without ".json", and its +// text. +using EmbeddedJsonFile = std::pair; + +// Find embedded file `file` among `files` and parse it as +// read_authored_checkpoint() does. Missing resources throw +// InternalProgramError; malformed documents throw ParseException. +StoryCheckpoint load_authored_checkpoint( + std::span files, std::string_view file, std::string_view game, + const ExecutionReader& read_execution, + std::span actions = builtin_story_actions() +); + + + +} // namespace Pokemon +} // namespace PokemonAutomation + +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp new file mode 100644 index 0000000000..4291207e86 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp @@ -0,0 +1,188 @@ +/* Shared Authored Checkpoint JSON Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_AuthoredCheckpointJson.h" +#include "Pokemon_StoryStepJson.h" +#ifndef PA_STORY_DATA_STANDALONE +#include "Pokemon_AuthoredCheckpointJson_Tests.h" +#endif + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// Documents intentionally contain no game headers or native bookkeeping. +const std::string FRLG = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{"id":"00.05","title":"Parcel","events":[{"id":"first","kind":"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. +enum class Failure{ + NONE, + PARSE, + MISSING_RESOURCE, +}; + +struct AuthoredInput{ + std::string name; + std::string json; + std::string game = "frlg"; + bool resource = false; + std::string file = "plan"; +}; + +struct AuthoredExpectation{ + std::string checkpoint = "00.05"; + std::string execution = R"({"menu":"before_pokedex"})"; + std::vector events = {"first", "second"}; + Failure failure = Failure::NONE; +}; + +struct AuthoredCase{ + AuthoredInput input; + AuthoredExpectation expectation; +}; + +const AuthoredCase CASES[] = { + {.input = {.name = "FRLG envelope", .json = FRLG}, .expectation = {}}, + {.input = {.name = "BDSP embedded resource", .json = BDSP, .game = "bdsp", .resource = true}, .expectation = { + .checkpoint = "01.03", .execution = R"({"on_failure":"reload_and_retry","saves_in":"Oreburgh City"})", .events = {"roark"}}}, + {.input = {.name = "FRLG embedded resource", .json = FRLG, .resource = true}, .expectation = {}}, + {.input = {.name = "wrong game", .json = BDSP}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "empty expected game", .json = FRLG, .game = ""}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "missing resource", .json = FRLG, .resource = true, .file = "absent"}, .expectation = {.failure = Failure::MISSING_RESOURCE}}, + {.input = {.name = "invalid embedded JSON", .json = "{", .resource = true}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "wrong format", .json = R"({"format":"future","game":"frlg","checkpoint":{},"execution":{}})"}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "missing execution", .json = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{}})"}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "same count wrong field", .json = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{},"extra":{}})"}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "extra envelope field", .json = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{},"execution":{},"extra":0})"}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "execution must be object", .json = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{"id":"x","title":"X","events":[]},"execution":false})"}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "invalid common action", .json = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{"id":"x","title":"X","events":[{"id":"bad","kind":"magic"}]},"execution":{}})"}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "execution stays game owned", .json = R"({"format":"pokesim-authored-checkpoint/1","game":"future","checkpoint":{"id":"x","title":"X","events":[]},"execution":{"zero":0,"false":false,"null":null}})", .game = "future"}, .expectation = { + .checkpoint = "x", .execution = R"({"zero":0,"false":false,"null":null})", .events = {}}}, +}; + + +// What a test reads: the checkpoint, and the execution object its reader +// kept. +struct Loaded{ + StoryCheckpoint checkpoint; + JsonObject execution; +}; + +// A reader that keeps the execution object in `kept`. +ExecutionReader keep_execution(JsonObject& kept){ + return [&kept](const JsonObject& execution, std::string_view){ + kept = execution.clone(); + }; +} + +// "" when `actual` is what `test` expects and survives a write and a +// read, else what was expected and what was read. +std::string check_loaded(const Loaded& actual, const AuthoredCase& test){ + if (test.expectation.failure != Failure::NONE){ + return "Expected rejection, read accepted authored checkpoint."; + } + if (actual.checkpoint.id != test.expectation.checkpoint){ + return std::format("Expected checkpoint {}, read {}", test.expectation.checkpoint, actual.checkpoint.id); + } + if (!(JsonValue(actual.execution.clone()) == parse_json(test.expectation.execution))){ + return std::format("Expected execution {}, read {}", test.expectation.execution, actual.execution.dump()); + } + std::vector events; + for (const StoryStep& step : actual.checkpoint.steps){ + events.push_back(step.name); + } + if (events != test.expectation.events){ + return "Expected authored event IDs in their original order."; + } + const JsonValue encoded = authored_checkpoint_json(actual.checkpoint, test.input.game, actual.execution.clone()); + Loaded reread; + reread.checkpoint = read_authored_checkpoint(encoded, test.input.game, test.input.name, keep_execution(reread.execution)); + if (!(story_checkpoint_json(actual.checkpoint) == story_checkpoint_json(reread.checkpoint)) || actual.execution != reread.execution){ + return "Expected checkpoint and execution to survive the shared writer/reader round trip."; + } + return ""; +} + +// "" when `test` reads or fails as expected. +std::string check_case(const AuthoredCase& test){ + try{ + const std::vector> files = {{"plan", test.input.json}}; + 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 ? "" : std::format("Unexpected parse failure: {}", error.message()); + }catch (const InternalProgramError& error){ + return test.expectation.failure == Failure::MISSING_RESOURCE ? "" : std::format("Unexpected resource failure: {}", error.message()); + } +} + + +#ifndef PA_STORY_DATA_STANDALONE + +class AuthoredJsonTest : public UnitTest{ +public: + explicit AuthoredJsonTest(AuthoredCase test) + : UnitTest(std::format("Pokemon::AuthoredCheckpointJson - {}", test.input.name)) + , m_case(std::move(test)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string error = check_case(m_case); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } + +private: + AuthoredCase m_case; +}; + +#endif + + +} // namespace + + +#ifndef PA_STORY_DATA_STANDALONE + +void add_tests_AuthoredCheckpointJson(UnitTestDatabase& database){ + for (const AuthoredCase& test : CASES){ + database.add(test); + } +} + +#endif + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +#ifdef PA_STORY_DATA_STANDALONE + +int main(){ + int failed = 0; + for (const auto& test : PokemonAutomation::Pokemon::CASES){ + 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/Data/Pokemon_AuthoredCheckpointJson_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.h new file mode 100644 index 0000000000..ae88e442a4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.h @@ -0,0 +1,23 @@ +/* Authored Checkpoint JSON Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_AuthoredCheckpointJson_Tests_H +#define PokemonAutomation_Pokemon_AuthoredCheckpointJson_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the shared authored envelope, game identity and embedded-resource loading. +void add_tests_AuthoredCheckpointJson(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp new file mode 100644 index 0000000000..98f434c568 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp @@ -0,0 +1,433 @@ +/* Story Step JSON + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon_StoryStepJson.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// The wire names of the step kinds. +constexpr std::array, 15> KINDS{{ + {StoryStepKind::NEW_GAME, "new_game"}, + {StoryStepKind::OPTIONS, "options"}, + {StoryStepKind::ROUTE, "route"}, + {StoryStepKind::LEGS, "legs"}, + {StoryStepKind::STEP, "step"}, + {StoryStepKind::TALK, "talk"}, + {StoryStepKind::ANSWER, "answer"}, + {StoryStepKind::MASH, "scene"}, + {StoryStepKind::BATTLE, "battle"}, + {StoryStepKind::TRAIN, "train"}, + {StoryStepKind::HEAL, "heal"}, + {StoryStepKind::SHOP, "shop"}, + {StoryStepKind::SAVE, "save"}, + {StoryStepKind::READY, "ready"}, + {StoryStepKind::GAME, "game_action"}, +}}; + +// The wire names of the directions. +constexpr std::array, 4> DIRECTIONS{{ + {Direction::NORTH, "north"}, + {Direction::EAST, "east"}, + {Direction::SOUTH, "south"}, + {Direction::WEST, "west"}, +}}; + + +// `value` as an object with no field outside `keys`. +const JsonObject& fields(const JsonValue& value, std::initializer_list keys, std::string_view source){ + const JsonObject& object = value.to_object_throw(std::string(source)); + for (const auto& [key, unused] : object){ + bool known = false; + for (std::string_view allowed : keys){ + known |= key == allowed; + } + if (!known){ + throw ParseException(std::format("{}: unsupported field {}", source, key)); + } + } + return object; +} + +template +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; + } + } + throw ParseException(std::format("{}: unsupported value {}", source, name)); +} + +template +std::string enum_name(const std::array, N>& names, Enum value){ + for (const auto& [candidate, label] : names){ + if (candidate == value){ + return std::string(label); + } + } + throw ParseException("Unsupported story enum value."); +} + +int integer(const JsonValue& value, std::string_view source){ + const int64_t number = value.to_integer_throw(std::string(source)); + if (number < std::numeric_limits::min() || number > std::numeric_limits::max()){ + throw ParseException(std::format("{}: coordinate exceeds native int", source)); + } + return (int)number; +} + +size_t count(const JsonValue& value, std::string_view source){ + const int64_t number = value.to_integer_throw(std::string(source)); + if (number < 0 || (uint64_t)number > std::numeric_limits::max()){ + throw ParseException(std::format("{}: count is out of range", source)); + } + return (size_t)number; +} + +JsonValue count_json(size_t value){ + if ((uint64_t)value > (uint64_t)std::numeric_limits::max()){ + throw ParseException("Story count exceeds the wire integer range."); + } + return (uint64_t)value; +} + +JsonArray strings_json(std::span strings){ + JsonArray result; + for (const std::string& value : strings){ + result.push_back(value); + } + return result; +} + +std::vector read_strings(const JsonValue& value, std::string_view source){ + std::vector result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + result.push_back(item.to_string_throw(std::string(source))); + } + return result; +} + +JsonArray legs_json(std::span legs){ + JsonArray result; + for (const StoryLeg& leg : legs){ + JsonObject item; + item["direction"] = enum_name(DIRECTIONS, leg.direction); + item["tiles"] = leg.tiles; + result.push_back(std::move(item)); + } + return result; +} + +std::vector read_legs(const JsonValue& value, std::string_view source){ + std::vector result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + const JsonObject& row = fields(item, {"direction", "tiles"}, source); + result.push_back({.direction = read_enum(DIRECTIONS, row.get_string_throw("direction"), source), + .tiles = integer(row.get_value_throw("tiles"), source)}); + } + return result; +} + +JsonArray items_json(std::span items){ + JsonArray result; + for (const StoryItem& item : items){ + JsonObject row; + row["item"] = item.item; + row["quantity"] = count_json(item.quantity); + result.push_back(std::move(row)); + } + return result; +} + +std::vector read_items(const JsonValue& value, std::string_view source){ + std::vector result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + const JsonObject& row = fields(item, {"item", "quantity"}, source); + result.push_back({.item = row.get_string_throw("item"), .quantity = count(row.get_value_throw("quantity"), source)}); + } + return result; +} + +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; +} + +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; +} + +// One arg's value as JSON. +JsonValue arg_json(const StoryArgValue& value){ + switch (story_arg_type(value)){ + case StoryArgType::BOOLEAN: + return std::get(value); + case StoryArgType::INTEGER: + return std::get(value); + case StoryArgType::WORD: + return std::get(value); + case StoryArgType::DIRECTION: + return enum_name(DIRECTIONS, std::get(value)); + case StoryArgType::GRID_POSE: + return grid_pose_json(std::get(value)); + case StoryArgType::LEGS: + return legs_json(std::get>(value)); + case StoryArgType::WORDS: + return strings_json(std::get>(value)); + case StoryArgType::ITEMS: + return items_json(std::get>(value)); + } + throw ParseException("Unsupported story arg type."); +} + +// One arg's value read as `type`. +StoryArgValue read_arg(const JsonValue& value, StoryArgType type, std::string_view source){ + switch (type){ + case StoryArgType::BOOLEAN: + return value.to_boolean_throw(std::string(source)); + case StoryArgType::INTEGER: + return value.to_integer_throw(std::string(source)); + case StoryArgType::WORD: + return value.to_string_throw(std::string(source)); + case StoryArgType::DIRECTION: + return read_enum(DIRECTIONS, value.to_string_throw(std::string(source)), source); + case StoryArgType::GRID_POSE: + return read_grid_pose(value, source); + case StoryArgType::LEGS: + return read_legs(value, source); + case StoryArgType::WORDS: + return read_strings(value, source); + case StoryArgType::ITEMS: + return read_items(value, source); + } + throw ParseException(std::format("{}: unsupported story arg type", source)); +} + +// The step's action among `actions`: the named one, or the kind's default. +// Null for a kind with no action that names none. +const StoryActionSpec* step_action( + const StoryStep& step, std::span actions, std::string_view source +){ + if (step.kind == StoryStepKind::GAME && step.action.empty()){ + throw ParseException(std::format("{}: game_action step {} names no action", source, step.name)); + } + const StoryActionSpec* spec = find_story_action(actions, step.kind, step.action); + if (spec == nullptr && !step.action.empty()){ + throw ParseException(std::format("{}: step {}: unknown action {}", source, step.name, step.action)); + } + return spec; +} + +// The step's args, read against its action's spec, with the fallbacks +// filled in. +StoryActionArgs read_args( + const JsonValue* value, const StoryActionSpec* spec, const StoryStep& step, std::string_view source +){ + const StoryActionSpec none{.kind = step.kind, .name = "", .args = {}}; + const StoryActionSpec& action = spec ? *spec : none; + StoryActionArgs result; + if (value != nullptr){ + for (const auto& [key, item] : value->to_object_throw(std::string(source))){ + const auto arg = std::find_if(action.args.begin(), action.args.end(), [&](const StoryArgSpec& candidate){ + return candidate.key == key; + }); + if (arg == action.args.end()){ + throw ParseException(std::format("{}: step {}: unknown argument \"{}\"", source, step.name, key)); + } + result[key] = read_arg(item, arg->type, source); + } + } + const std::vector errors = story_args_errors(action, result); + if (!errors.empty()){ + throw ParseException(std::format("{}: step {}: {}", source, step.name, errors.front())); + } + return with_fallbacks(action, std::move(result)); +} + + +JsonValue postconditions_json(const StoryPostconditions& postconditions){ + JsonObject result; + if (postconditions.position){ + result["position"] = grid_pose_json(*postconditions.position); + } + if (!postconditions.items.empty()){ + result["items"] = items_json(postconditions.items); + } + if (!postconditions.flags.empty()){ + result["flags"] = strings_json(postconditions.flags); + } + return result; +} + +StoryPostconditions read_postconditions(const JsonValue& value, std::string_view source){ + const JsonObject& root = fields(value, {"position", "items", "flags"}, source); + StoryPostconditions result; + if (const JsonValue* field = root.get_value("position")){ + result.position = read_grid_pose(*field, source); + } + if (const JsonValue* field = root.get_value("items")){ + result.items = read_items(*field, source); + } + if (const JsonValue* field = root.get_value("flags")){ + result.flags = read_strings(*field, source); + } + return result; +} + + +} // namespace + + +JsonValue grid_pose_json(const GridPose& pose){ + JsonObject result; + result["map"] = pose.map; + result["tiles"] = tiles_json(pose.tiles); + if (pose.facing){ + result["facing"] = enum_name(DIRECTIONS, *pose.facing); + } + return 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.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); + } + return result; +} + +JsonValue story_step_json(const StoryStep& step){ + JsonObject result; + result["id"] = step.name; + result["kind"] = enum_name(KINDS, step.kind); + if (!step.why.empty()){ + result["why"] = step.why; + } + if (!step.action.empty()){ + result["action"] = step.action; + } + if (!step.args.empty()){ + JsonObject args; + for (const auto& [key, value] : step.args){ + args[key] = arg_json(value); + } + result["args"] = std::move(args); + } + if (!step.skip_if.empty()){ + result["skip_if"] = strings_json(step.skip_if); + } + if (step.pose_after){ + result["declared_after"] = grid_pose_json(*step.pose_after); + } + return result; +} + +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()){ + throw ParseException("Empty story step id."); + } + result.kind = read_enum(KINDS, root.get_string_throw("kind"), source); + if (const JsonValue* field = root.get_value("why")){ + result.why = field->to_string_throw(); + } + if (const JsonValue* field = root.get_value("action")){ + result.action = field->to_string_throw(); + } + result.args = read_args(root.get_value("args"), step_action(result, actions, source), result, source); + if (const JsonValue* field = root.get_value("skip_if")){ + result.skip_if = read_strings(*field, source); + } + if (const JsonValue* field = root.get_value("declared_after")){ + result.pose_after = read_grid_pose(*field, source); + } + return result; +} + +JsonValue story_checkpoint_json(const StoryCheckpoint& checkpoint){ + JsonObject result; + result["id"] = checkpoint.id; + result["title"] = checkpoint.title; + if (checkpoint.start){ + result["start"] = grid_pose_json(*checkpoint.start); + } + JsonArray events; + for (const StoryStep& step : checkpoint.steps){ + events.push_back(story_step_json(step)); + } + result["events"] = std::move(events); + if (checkpoint.postconditions != StoryPostconditions{}){ + result["postconditions"] = postconditions_json(checkpoint.postconditions); + } + return result; +} + +StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view source, std::span actions){ + const JsonObject& root = fields(value, {"id", "title", "start", "events", "postconditions"}, source); + StoryCheckpoint result; + result.id = root.get_string_throw("id"); + if (result.id.empty()){ + throw ParseException("Empty story checkpoint id."); + } + result.title = root.get_string_throw("title"); + if (const JsonValue* start = root.get_value("start")){ + 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, actions); + if (step.name.empty() || !names.insert(step.name).second){ + throw ParseException("Empty or duplicate story event id."); + } + result.steps.push_back(std::move(step)); + } + if (const JsonValue* postconditions = root.get_value("postconditions")){ + result.postconditions = read_postconditions(*postconditions, source); + } + return result; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h new file mode 100644 index 0000000000..f45f8dd77f --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h @@ -0,0 +1,59 @@ +/* Story Step JSON + * + * From: https://github.com/PokemonAutomation/ + * + * The shared JSON wire form of the story data types (Types/): poses, + * steps and checkpoints, read strictly and written losslessly. This is + * the only layer that reads story JSON: a step comes out with its args + * typed and checked, and nothing after it parses. + * + */ + +#ifndef PokemonAutomation_StoryStepJson_H +#define PokemonAutomation_StoryStepJson_H + +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A grid pose: {"map": "PalletTown", "tiles": [[3, 4]], "facing": "north"}. +JsonValue grid_pose_json(const GridPose& pose); + +// Read a grid pose; malformed and unknown fields fail. +GridPose read_grid_pose(const JsonValue& value, std::string_view source); + + +// Encode a step: its kind, action and args. This does not run it. +JsonValue story_step_json(const StoryStep& step); + +// Read a step, its args parsed against its action among `actions` (by +// default the built-in ones; a game passes them with its own) and their +// fallbacks filled in. Unknown fields, kinds, actions and args, mistyped +// values and missing required args fail. +StoryStep read_story_step( + const JsonValue& value, std::string_view source, + std::span actions = builtin_story_actions() +); + + +// Encode the common checkpoint; game adapters supply the shared policy/state envelope. +JsonValue story_checkpoint_json(const StoryCheckpoint& checkpoint); + +// Read the common checkpoint, its steps read as read_story_step() does. +StoryCheckpoint read_story_checkpoint( + const JsonValue& value, std::string_view source, + std::span actions = builtin_story_actions() +); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp new file mode 100644 index 0000000000..cd304de9c0 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp @@ -0,0 +1,239 @@ +/* Story Step JSON Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Each case reads a record from JSON and writes it back: the canonical + * form, or a rejection. Built standalone (PA_STORY_DATA_STANDALONE), it + * also checks the shared case file the Python reader checks. + * + */ + +#include +#include +#include +#include +#include +#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_StoryStepJson_Tests.h" +#endif + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// Which record a case reads. +enum class Record{ + POSE, + STEP, + CHECKPOINT, +}; + +// A record to read, and which kind it is. +struct WireInput{ + std::string_view name; + Record record = Record::STEP; + std::string_view json; +}; + +// What reading it gives: the canonical record, or a rejection. +struct WireExpectation{ + std::string_view canonical = {}; + bool rejected = false; +}; + +struct WireCase{ + WireInput input; + WireExpectation expectation; +}; + +const WireCase CASES[] = { + {.input = {.name = "no args", .json = R"({"id":"talk","kind":"talk"})"}, .expectation = {.canonical = R"({"id":"talk","kind":"talk"})"}}, + {.input = {.name = "all shared fields", .json = R"({"id":"all","kind":"game_action","why":"source reason","action":"profile","skip_if":["flag"],"declared_after":{"map":"B","tiles":[[0,0],[1,0]],"facing":"east"}})"}, .expectation = {.canonical = R"({"id":"all","kind":"game_action","why":"source reason","action":"profile","skip_if":["flag"],"declared_after":{"map":"B","tiles":[[0,0],[1,0]],"facing":"east"}})"}}, + {.input = {.name = "route fills its fallback", .json = R"({"id":"r","kind":"route","args":{"target":{"map":"A","tiles":[[1,2]]}}})"}, .expectation = {.canonical = R"({"id":"r","kind":"route","args":{"fight_wild":false,"target":{"map":"A","tiles":[[1,2]]}}})"}}, + {.input = {.name = "legs", .json = R"({"id":"l","kind":"legs","action":"legs","args":{"legs":[{"direction":"south","tiles":2}],"fight_wild":true}})"}, .expectation = {.canonical = R"({"id":"l","kind":"legs","action":"legs","args":{"fight_wild":true,"legs":[{"direction":"south","tiles":2}]}})"}}, + {.input = {.name = "direction", .json = R"({"id":"s","kind":"step","args":{"direction":"west"}})"}, .expectation = {.canonical = R"({"id":"s","kind":"step","args":{"direction":"west"}})"}}, + {.input = {.name = "items", .json = R"({"id":"s","kind":"shop","args":{"items":[{"item":"potion","quantity":5}]}})"}, .expectation = {.canonical = R"({"id":"s","kind":"shop","args":{"items":[{"item":"potion","quantity":5}]}})"}}, + {.input = {.name = "game args", .json = R"({"id":"buy","kind":"game_action","action":"mart","args":{"map":"CeruleanCity_Mart","budget":3000,"if_present":true}})"}, .expectation = {.canonical = R"({"id":"buy","kind":"game_action","action":"mart","args":{"budget":3000,"if_present":true,"map":"CeruleanCity_Mart"}})"}}, + {.input = {.name = "game words", .json = R"({"id":"buy","kind":"game_action","action":"mart","args":{"map":"M","budget":1,"skip":["a","b"]}})"}, .expectation = {.canonical = R"({"id":"buy","kind":"game_action","action":"mart","args":{"budget":1,"if_present":false,"map":"M","skip":["a","b"]}})"}}, + {.input = {.name = "unknown arg", .json = R"({"id":"a","kind":"game_action","action":"mart","args":{"map":"M","budget":1,"budgte":1}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "missing required arg", .json = R"({"id":"a","kind":"game_action","action":"mart","args":{"map":"M"}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "route without target", .json = R"({"id":"a","kind":"route"})"}, .expectation = {.rejected = true}}, + {.input = {.name = "args on a kind with none", .json = R"({"id":"a","kind":"talk","args":{"yes":true}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "game step without action", .json = R"({"id":"a","kind":"game_action"})"}, .expectation = {.rejected = true}}, + {.input = {.name = "unknown action name", .json = R"({"id":"a","kind":"game_action","action":"dance"})"}, .expectation = {.rejected = true}}, + {.input = {.name = "fractional arg", .json = R"({"id":"a","kind":"game_action","action":"mart","args":{"map":"M","budget":1.5}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "args not an object", .json = R"({"id":"a","kind":"game_action","action":"mart","args":["map"]})"}, .expectation = {.rejected = true}}, + {.input = {.name = "old field", .json = R"({"id":"a","kind":"battle","may_lose":true})"}, .expectation = {.rejected = true}}, + {.input = {.name = "old variant", .json = R"({"id":"a","kind":"game_action","variant":"mart"})"}, .expectation = {.rejected = true}}, + {.input = {.name = "unknown field", .json = R"({"id":"a","kind":"talk","mystery":0})"}, .expectation = {.rejected = true}}, + {.input = {.name = "unknown kind", .json = R"({"id":"a","kind":"magic"})"}, .expectation = {.rejected = true}}, + {.input = {.name = "boolean count", .json = R"({"id":"a","kind":"train","args":{"battles":false}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "wrong bool", .json = R"({"id":"a","kind":"answer","args":{"yes":0}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "unknown facing stays absent", .record = Record::POSE, .json = R"({"map":"M","tiles":[[0,0]]})"}, .expectation = {.canonical = R"({"map":"M","tiles":[[0,0]]})"}}, + {.input = {.name = "no tiles", .record = Record::POSE, .json = R"({"map":"M","tiles":[]})"}, .expectation = {.canonical = R"({"map":"M","tiles":[]})"}}, + {.input = {.name = "old pose", .record = Record::POSE, .json = R"({"map":"M","certainty":"unknown","where":{"kind":"unknown"}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "bad coordinate", .record = Record::POSE, .json = R"({"map":"M","tiles":[[0,true]]})"}, .expectation = {.rejected = true}}, + {.input = {.name = "ordered checkpoint", .record = Record::CHECKPOINT, .json = R"({"id":"00.05","title":"Parcel","events":[{"id":"first","kind":"talk"},{"id":"second","kind":"scene"}]})"}, .expectation = {.canonical = R"({"id":"00.05","title":"Parcel","events":[{"id":"first","kind":"talk"},{"id":"second","kind":"scene"}]})"}}, + {.input = {.name = "duplicate events", .record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[{"id":"a","kind":"talk"},{"id":"a","kind":"talk"}]})"}, .expectation = {.rejected = true}}, +}; + +// The built-in actions and a game's: a Mart step (GAME "mart") and a +// profile check that takes no args. +std::vector test_actions(){ + std::vector actions(builtin_story_actions().begin(), builtin_story_actions().end()); + actions.push_back({.kind = StoryStepKind::GAME, .name = "mart", .args = { + {.key = "map", .type = StoryArgType::WORD, .required = true, .fallback = std::nullopt, .why = "the Mart's map"}, + {.key = "budget", .type = StoryArgType::INTEGER, .required = true, .fallback = std::nullopt, .why = "money to spend"}, + {.key = "if_present", .type = StoryArgType::BOOLEAN, .required = false, .fallback = false, .why = ""}, + {.key = "skip", .type = StoryArgType::WORDS, .required = false, .fallback = std::nullopt, .why = ""}, + }}); + actions.push_back({.kind = StoryStepKind::GAME, .name = "profile", .args = {}}); + return actions; +} + + +// `input` read and written back. +JsonValue round_trip(const WireInput& input){ + static const std::vector actions = test_actions(); + const JsonValue value = parse_json(std::string(input.json)); + switch (input.record){ + case Record::POSE: + return grid_pose_json(read_grid_pose(value, input.name)); + case Record::STEP: + return story_step_json(read_story_step(value, input.name, actions)); + case Record::CHECKPOINT: + return story_checkpoint_json(read_story_checkpoint(value, input.name, actions)); + } + throw ParseException("Unknown test record."); +} + +// "" when `test` reads as expected, else what was expected and what was read. +std::string check_case(const WireCase& test){ + try{ + const JsonValue actual = round_trip(test.input); + if (test.expectation.rejected){ + return "Expected rejection, read accepted record."; + } + const JsonValue expected = parse_json(std::string(test.expectation.canonical)); + if (!(actual == expected)){ + return std::format("Expected {}, read {}", expected.dump(), actual.dump()); + } + }catch (const ParseException& error){ + return test.expectation.rejected ? "" : std::format("Unexpected parse failure: {}", error.message()); + } + return ""; +} + + +#ifdef PA_STORY_DATA_STANDALONE + +// A shared case file's record kind. +Record record_kind(std::string_view name){ + if (name == "pose"){ + return Record::POSE; + } + if (name == "step"){ + return Record::STEP; + } + if (name == "checkpoint"){ + return Record::CHECKPOINT; + } + throw ParseException("Unsupported shared case record kind."); +} + +// Checks every case of the shared file `filename`; nonzero if any failed. +int check_shared_file(const std::string& filename){ + const JsonValue document = load_json_file(filename); + const JsonObject& root = document.to_object_throw(filename); + if (root.get_string_throw("format") != "pokesim-story-wire-cases/1"){ + throw ParseException("Unsupported story wire case format."); + } + int failed = 0; + for (const JsonValue& value : root.get_array_throw("cases")){ + const JsonObject& row = value.to_object_throw(filename); + const JsonObject& input = row.get_object_throw("input"); + const JsonObject& expected = row.get_object_throw("expectation"); + const std::string source = input.get_value_throw("value").dump(); + const JsonValue* normalized = expected.get_value("canonical"); + const std::string canonical = normalized ? normalized->dump() : ""; + const JsonValue* rejected = expected.get_value("rejected"); + const WireCase test{ + .input = {.name = input.get_string_throw("name"), .record = record_kind(input.get_string_throw("record")), .json = source}, + .expectation = {.canonical = canonical, .rejected = rejected && rejected->to_boolean_throw()}, + }; + const std::string error = check_case(test); + if (!error.empty()){ + std::cerr << test.input.name << ": " << error << '\n'; + failed++; + } + } + std::cout << "Checked " << root.get_array_throw("cases").size() << " shared story records.\n"; + return failed != 0; +} + +#endif + + +#ifndef PA_STORY_DATA_STANDALONE + +class StoryJsonTest : public UnitTest{ +public: + explicit StoryJsonTest(WireCase test) + : UnitTest(std::format("Pokemon::StoryStepJson - {}", test.input.name)) + , m_case(test) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string error = check_case(m_case); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } + +private: + WireCase m_case; +}; + +#endif + + +} // namespace + + +#ifndef PA_STORY_DATA_STANDALONE + +void add_tests_StoryStepJson(UnitTestDatabase& database){ + for (const WireCase& test : CASES){ + database.add(test); + } +} + +#endif + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +#ifdef PA_STORY_DATA_STANDALONE + +int main(int argc, char** argv){ + if (argc == 2){ + return PokemonAutomation::Pokemon::check_shared_file(argv[1]); + } + int failed = 0; + for (const auto& test : PokemonAutomation::Pokemon::CASES){ + const std::string error = PokemonAutomation::Pokemon::check_case(test); + std::cout << test.input.name << ": " << (error.empty() ? "PASS" : error) << '\n'; + failed += !error.empty(); + } + return failed != 0; +} + +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h new file mode 100644 index 0000000000..9c4f9565ad --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h @@ -0,0 +1,23 @@ +/* Story Step JSON Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepJson_Tests_H +#define PokemonAutomation_Pokemon_StoryStepJson_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the lossless shared story-data wire contract. +void add_tests_StoryStepJson(UnitTestDatabase& database); + + + +} // 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 6c12b7b0cb..1fc89ec462 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -12,13 +12,18 @@ #define PokemonAutomation_Pokemon_AutoStory_Tests_H #include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/Pokemon_AuthoredCheckpointJson_Tests.h" +#include "Data/Pokemon_StoryStepJson_Tests.h" #include "Pokemon/Options/Pokemon_StoryRangeOptions_Tests.h" #include "Pokemon_AutoStorySelect_Tests.h" #include "Pokemon_CheckpointRetry_Tests.h" #include "Pokemon_StoryEvents_Tests.h" #include "Pokemon_StoryLog_Tests.h" #include "Pokemon_StoryRunCounts_Tests.h" +#include "Pokemon_StorySavePolicy_Tests.h" #include "Pokemon_StorySegments_Tests.h" +#include "Pokemon_StoryStepExecutor_Tests.h" +#include "Types/Pokemon_StoryActionArg_Tests.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -32,6 +37,11 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_StoryRangeOptions(database); add_tests_StoryEvents(database); add_tests_StorySegments(database); + add_tests_StoryStepExecutor(database); + add_tests_StoryStepJson(database); + add_tests_StoryActionArg(database); + add_tests_AuthoredCheckpointJson(database); + add_tests_StorySavePolicy(database); add_tests_StoryRunCounts(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..a13a29cfec --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h @@ -0,0 +1,66 @@ +/* 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 +#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, std::format("Missing or mistyped story arg: {}", key)); + } + return *value; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif 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_StoryPostconditionCheck.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPostconditionCheck.cpp new file mode 100644 index 0000000000..d4881de3bd --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPostconditionCheck.cpp @@ -0,0 +1,226 @@ +/* Story Postcondition Check + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Pokemon_StoryPostconditionCheck.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +std::string verdict_name(PostconditionVerdict verdict){ + switch (verdict){ + case PostconditionVerdict::PASSED: + return "passed"; + case PostconditionVerdict::FAILED: + return "failed"; + case PostconditionVerdict::NOT_CHECKED: + return "not checked"; + } + return "?"; +} + +PostconditionResult result(std::string what, PostconditionVerdict verdict, std::string detail){ + return PostconditionResult{.what = std::move(what), .verdict = verdict, .detail = std::move(detail)}; +} + +PostconditionResult not_read(std::string what){ + return result(std::move(what), PostconditionVerdict::NOT_CHECKED, "the game can't read it"); +} + +// The first pose among a step's args (a route's target). +std::optional pose_arg(const StoryStep& step){ + for (const auto& [unused, value] : step.args){ + if (const GridPose* pose = std::get_if(&value)){ + return *pose; + } + } + return std::nullopt; +} + +std::string tiles_text(const std::vector& tiles){ + std::string text; + for (const TilePos& tile : tiles){ + text += (text.empty() ? "" : " or ") + to_string(tile); + } + return text; +} + +void check_map(const GridPose& end, const ObservedState& observed, std::vector& out){ + if (!observed.map){ + out.push_back(not_read("map")); + return; + } + const bool same = *observed.map == end.map; + out.push_back(result( + "map", same ? PostconditionVerdict::PASSED : PostconditionVerdict::FAILED, + same ? end.map : std::format("expected {}, read {}", end.map, *observed.map) + )); +} + +// The tile and facing mean nothing on another map: not checked then. +void check_tile(const GridPose& end, const ObservedState& observed, bool map_failed, std::vector& out){ + if (end.tiles.empty()){ + return; + } + if (map_failed){ + out.push_back(result("tile", PostconditionVerdict::NOT_CHECKED, "on another map")); + return; + } + if (!observed.tile){ + out.push_back(not_read("tile")); + return; + } + const bool on = std::find(end.tiles.begin(), end.tiles.end(), *observed.tile) != end.tiles.end(); + out.push_back(result( + "tile", on ? PostconditionVerdict::PASSED : PostconditionVerdict::FAILED, + on ? to_string(*observed.tile) : std::format("expected {}, read {}", tiles_text(end.tiles), to_string(*observed.tile)) + )); +} + +void check_facing(const GridPose& end, const ObservedState& observed, bool map_failed, std::vector& out){ + if (!end.facing){ + return; + } + if (map_failed){ + out.push_back(result("facing", PostconditionVerdict::NOT_CHECKED, "on another map")); + return; + } + if (!observed.facing){ + out.push_back(not_read("facing")); + return; + } + const bool same = *observed.facing == *end.facing; + out.push_back(result( + "facing", same ? PostconditionVerdict::PASSED : PostconditionVerdict::FAILED, + same ? direction_name(*end.facing) + : std::format("expected {}, read {}", direction_name(*end.facing), direction_name(*observed.facing)) + )); +} + +void check_position(const StoryCheckpoint& checkpoint, const ObservedState& observed, std::vector& out){ + const std::optional end = checkpoint_end_pose(checkpoint); + if (!end){ + return; + } + check_map(*end, observed, out); + const bool map_failed = out.back().verdict == PostconditionVerdict::FAILED; + check_tile(*end, observed, map_failed, out); + check_facing(*end, observed, map_failed, out); +} + +void check_items(const StoryPostconditions& expected, const ObservedState& observed, std::vector& out){ + for (const StoryItem& item : expected.items){ + const std::string what = std::format("item {}", item.item); + const auto read = observed.items.find(item.item); + if (read == observed.items.end()){ + out.push_back(not_read(what)); + continue; + } + const bool same = read->second == item.quantity; + out.push_back(result( + what, same ? PostconditionVerdict::PASSED : PostconditionVerdict::FAILED, + same ? std::format("{}", item.quantity) : std::format("expected {}, read {}", item.quantity, read->second) + )); + } +} + +void check_flags(const StoryPostconditions& expected, const ObservedState& observed, std::vector& out){ + for (const std::string& flag : expected.flags){ + const std::string what = std::format("flag {}", flag); + const auto read = observed.flags.find(flag); + if (read == observed.flags.end()){ + out.push_back(not_read(what)); + continue; + } + out.push_back(result( + what, read->second ? PostconditionVerdict::PASSED : PostconditionVerdict::FAILED, + read->second ? "set" : "expected set, read clear" + )); + } +} + +std::string summary_verdict(const PostconditionReport& report){ + if (report.results.empty()){ + return "nothing to check"; + } + if (report.count(PostconditionVerdict::FAILED) > 0){ + return "failed"; + } + return report.all_passed() ? "passed" : "incomplete"; +} + +} // namespace + + +size_t PostconditionReport::count(PostconditionVerdict verdict) const{ + size_t total = 0; + for (const PostconditionResult& item : results){ + total += item.verdict == verdict ? 1 : 0; + } + return total; +} + +bool PostconditionReport::all_passed() const{ + return !results.empty() && count(PostconditionVerdict::PASSED) == results.size(); +} + + +std::optional checkpoint_end_pose(const StoryCheckpoint& checkpoint){ + if (checkpoint.postconditions.position){ + return checkpoint.postconditions.position; + } + for (auto step = checkpoint.steps.rbegin(); step != checkpoint.steps.rend(); ++step){ + if (step->pose_after){ + return step->pose_after; + } + if (std::optional target = pose_arg(*step)){ + return target; + } + // Taps and single steps move the player without saying where to. + if (step->kind == StoryStepKind::LEGS || step->kind == StoryStepKind::STEP){ + return std::nullopt; + } + } + return std::nullopt; +} + +PostconditionReport check_postconditions(const StoryCheckpoint& checkpoint, const ObservedState& observed){ + PostconditionReport report; + report.checkpoint = checkpoint.id; + check_position(checkpoint, observed, report.results); + check_items(checkpoint.postconditions, observed, report.results); + check_flags(checkpoint.postconditions, observed, report.results); + return report; +} + +std::vector postcondition_log_lines(const PostconditionReport& report){ + std::vector lines; + for (const PostconditionResult& item : report.results){ + lines.push_back(std::format( + "[Postcondition] {} {}: {}: {}", report.checkpoint, item.what, verdict_name(item.verdict), item.detail + )); + } + lines.push_back(std::format( + "[Postcondition] {}: {} passed, {} failed, {} not checked: {}", + report.checkpoint, + report.count(PostconditionVerdict::PASSED), + report.count(PostconditionVerdict::FAILED), + report.count(PostconditionVerdict::NOT_CHECKED), + summary_verdict(report) + )); + return lines; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPostconditionCheck.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPostconditionCheck.h new file mode 100644 index 0000000000..c04c0e8e7e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPostconditionCheck.h @@ -0,0 +1,89 @@ +/* Story Postcondition Check + * + * From: https://github.com/PokemonAutomation/ + * + * A checkpoint's postconditions (Types/Pokemon_StoryPostconditions.h) + * checked against what the game read once the run was over: a step of its + * own, not the run's verdict, which can be wrong. A postcondition the game + * can't read yet is reported as not checked, never as passed. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryPostconditionCheck_H +#define PokemonAutomation_Pokemon_StoryPostconditionCheck_H + +#include +#include +#include +#include +#include +#include +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What the game read after the run. Each part is unset (or, for items and +// flags, absent from the map) when the game can't read it: the matching +// postconditions are then not checked. +struct ObservedState{ + std::optional map; + std::optional tile; + std::optional facing; + // The Bag's count of each item read, 0 for one read and not there. + std::map> items; + // Each story flag read, and whether it is set. + std::map> flags; +}; + +// The result of one postcondition. +enum class PostconditionVerdict{ + PASSED, + FAILED, + NOT_CHECKED, +}; + +// One postcondition checked: "map", "tile", "facing", "item LIFT_KEY", +// "flag ...", its verdict and what was expected and read. +struct PostconditionResult{ + std::string what; + PostconditionVerdict verdict = PostconditionVerdict::NOT_CHECKED; + std::string detail; +}; + +// Every postcondition of one checkpoint, checked. +struct PostconditionReport{ + std::string checkpoint; + std::vector results; + + size_t count(PostconditionVerdict verdict) const; + // Every postcondition was read and held: none failed, none unchecked, + // and there was at least one. + bool all_passed() const; +}; + +// Where `checkpoint` ends: its postconditions' position, else the last +// step's declared pose or target. Unset when a step after that moves the +// player in a way the plan does not place (taps of legs, a single step). +std::optional checkpoint_end_pose(const StoryCheckpoint& checkpoint); + +// Checks the end position (map, tile among the pose's tiles, facing), +// then each item count and flag, against `observed`. +PostconditionReport check_postconditions(const StoryCheckpoint& checkpoint, const ObservedState& observed); + +// The report as log lines, one per postcondition and a summary: +// [Postcondition] 00.31 map: passed: RocketHideout_B3F +// [Postcondition] 00.31 item RARE_CANDY: failed: expected 2, read 1 +// [Postcondition] 00.31 flag hideout_lift_key_grunt: not checked: the game can't read it +// [Postcondition] 00.31: 3 passed, 1 failed, 1 not checked: failed +// The summary is "passed" only when every postcondition passed; +// "incomplete" when none failed and some were not checked. +std::vector postcondition_log_lines(const PostconditionReport& report); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.cpp new file mode 100644 index 0000000000..b836256ce2 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.cpp @@ -0,0 +1,509 @@ +/* Story Save Policy Tests + * + * From: https://github.com/PokemonAutomation/ + * + * When a run saves (Types/Pokemon_StorySaveMode.h): the decision table, + * then the segment runner and verify mode in each mode against a world + * that only records what happened. Then the postcondition check + * (Pokemon_StoryPostconditionCheck.h) on FRLG 00.31's end state. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Data/Pokemon_StoryStepJson.h" +#include "Pokemon_StoryPostconditionCheck.h" +#include "Pokemon_StorySavePolicy_Tests.h" +#include "Pokemon_StorySegments.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// One row of the decision table. +struct SaveDecision{ + StorySaveMode mode; + CheckpointVerdict verdict; + SavePoint point; + bool saves; +}; + +constexpr SaveDecision SAVE_DECISIONS[] = { + {StorySaveMode::NONE, CheckpointVerdict::FAILED, SavePoint::CHECKPOINT_END, false}, + {StorySaveMode::NONE, CheckpointVerdict::FAILED, SavePoint::RUN_END, false}, + {StorySaveMode::NONE, CheckpointVerdict::PASSED, SavePoint::CHECKPOINT_END, false}, + {StorySaveMode::NONE, CheckpointVerdict::PASSED, SavePoint::RUN_END, false}, + {StorySaveMode::AFTER_VERIFICATION, CheckpointVerdict::FAILED, SavePoint::CHECKPOINT_END, false}, + {StorySaveMode::AFTER_VERIFICATION, CheckpointVerdict::FAILED, SavePoint::RUN_END, false}, + {StorySaveMode::AFTER_VERIFICATION, CheckpointVerdict::PASSED, SavePoint::CHECKPOINT_END, false}, + {StorySaveMode::AFTER_VERIFICATION, CheckpointVerdict::PASSED, SavePoint::RUN_END, true}, + {StorySaveMode::PER_CHECKPOINT, CheckpointVerdict::FAILED, SavePoint::CHECKPOINT_END, false}, + {StorySaveMode::PER_CHECKPOINT, CheckpointVerdict::FAILED, SavePoint::RUN_END, false}, + {StorySaveMode::PER_CHECKPOINT, CheckpointVerdict::PASSED, SavePoint::CHECKPOINT_END, true}, + {StorySaveMode::PER_CHECKPOINT, CheckpointVerdict::PASSED, SavePoint::RUN_END, true}, +}; + +UnitTestResult test_decision_table(){ + for (const SaveDecision& row : SAVE_DECISIONS){ + if (story_save_allowed(row.mode, row.verdict, row.point) != row.saves){ + return std::format( + "Wrong decision for {}{}{}", story_save_mode_name(row.mode), + row.verdict == CheckpointVerdict::PASSED ? ", passed" : ", failed", + row.point == SavePoint::RUN_END ? ", run end" : ", mid-run" + ); + } + } + return true; +} + + +// A world of three checkpoints that only records what happened: each +// checkpoint's walk, each save and each reload. +struct Lab{ + std::vector trace; + std::vector lines; + // Checkpoints whose walk fails this many more times. + std::map failures; + // The game's postcondition check: none when unset. + std::optional postconditions; + + SegmentHooks hooks(){ + SegmentHooks hooks; + hooks.save = [this](RunState&){ + trace.push_back("save"); + return outcome_ok(); + }; + hooks.reload = [this](RunState&){ + trace.push_back("reload"); + return outcome_ok(); + }; + hooks.log = [this](const std::string& line){ lines.push_back(line); }; + if (postconditions){ + hooks.check_postconditions = [this](const std::string& id, RunState&){ + trace.push_back(std::format("check {}", id)); + return *postconditions; + }; + } + return hooks; + } + bool has(const std::string& line) const{ + return std::find(lines.begin(), lines.end(), line) != lines.end(); + } + std::string all() const{ + std::string text; + for (const std::string& line : lines){ + text += std::format("\n{}", line); + } + return text; + } +}; + +CheckpointSpec walk_row(std::string id, Lab& lab){ + CheckpointSpec spec; + spec.id = id; + spec.saves = true; + spec.build = [&lab, id]{ + Checkpoint checkpoint; + checkpoint.id = id; + Event walk; + walk.name = "walk"; + walk.act = [&lab, id](RunState&){ + lab.trace.push_back(id); + int& left = lab.failures[id]; + if (left > 0){ + left--; + return outcome_failed("blocked", "a wanderer on the path"); + } + return outcome_ok(); + }; + Recovery stop; + stop.kind = RecoveryKind::STOP; + walk.recoveries.push_back(std::move(stop)); + checkpoint.events.push_back(std::move(walk)); + return checkpoint; + }; + return spec; +} + +Segment three_rows(Lab& lab){ + Segment segment; + segment.id = "00"; + for (std::string_view id : {"00.01", "00.02", "00.03"}){ + segment.checkpoints.push_back(walk_row(std::string(id), lab)); + } + return segment; +} + +SegmentReport run_in(StorySaveMode mode, Lab& lab){ + Segment segment = three_rows(lab); + SegmentHooks hooks = lab.hooks(); + RunState state; + return run_segment(SegmentRange{}, SegmentPolicy{.save_mode = mode}, segment, hooks, state); +} + +UnitTestResult test_none_never_saves(){ + Lab lab; + const SegmentReport report = run_in(StorySaveMode::NONE, lab); + const std::vector expected = {"00.01", "00.02", "00.03"}; + if (!report.completed || lab.trace != expected){ + return std::format("Expected three checkpoints and no save:{}", lab.all()); + } + if (!lab.has("[Segment] 00: save mode none") || !lab.has("[Checkpoint] 00.02: not saving (save mode none)")){ + return std::format("Expected the skipped saves logged:{}", lab.all()); + } + return true; +} + +UnitTestResult test_per_checkpoint_saves_each(){ + Lab lab; + const SegmentReport report = run_in(StorySaveMode::PER_CHECKPOINT, lab); + const std::vector expected = {"00.01", "save", "00.02", "save", "00.03", "save"}; + if (!report.completed || lab.trace != expected){ + return std::format("Expected a save after each checkpoint:{}", lab.all()); + } + return true; +} + +UnitTestResult test_after_verification_saves_at_the_end(){ + Lab lab; + const SegmentReport report = run_in(StorySaveMode::AFTER_VERIFICATION, lab); + const std::vector expected = {"00.01", "00.02", "00.03", "save"}; + if (!report.completed || lab.trace != expected){ + return std::format("Expected one save, at the end:{}", lab.all()); + } + if (!lab.has("[Postcondition] 00.03: not checked: the game has no postcondition check")){ + return std::format("Expected the missing check logged as not checked:{}", lab.all()); + } + return true; +} + +UnitTestResult test_after_verification_checks_before_saving(){ + Lab lab; + lab.postconditions = outcome_ok(); + const SegmentReport report = run_in(StorySaveMode::AFTER_VERIFICATION, lab); + const std::vector expected = {"00.01", "00.02", "00.03", "check 00.03", "save"}; + if (!report.completed || lab.trace != expected){ + return std::format("Expected the check, then the save:{}", lab.all()); + } + return true; +} + +// FRLG 00.31, 2026-11-10: the run said it passed on the wrong floor. +UnitTestResult test_failed_postconditions_never_save(){ + Lab lab; + lab.postconditions = outcome_failed("postconditions", "map: expected RocketHideout_B3F, read RocketHideout_B4F"); + const SegmentReport report = run_in(StorySaveMode::AFTER_VERIFICATION, lab); + if (report.completed || report.failed_checkpoint != "00.03"){ + return std::format("Expected the run failed at its last checkpoint:{}", lab.all()); + } + if (std::find(lab.trace.begin(), lab.trace.end(), "save") != lab.trace.end()){ + return std::format("A run whose postconditions failed must not save:{}", lab.all()); + } + if (!lab.has("[Checkpoint] 00.03: postconditions failed, not saving")){ + return std::format("Expected the refused save logged:{}", lab.all()); + } + return true; +} + +// Without per-checkpoint saves, a reload would go back to the run's start. +UnitTestResult test_no_reload_after_the_first(){ + Lab lab; + lab.failures["00.02"] = 1; + const SegmentReport report = run_in(StorySaveMode::NONE, lab); + const std::vector expected = {"00.01", "00.02"}; + if (report.completed || report.reloads != 0 || lab.trace != expected){ + return std::format("Expected 00.02 to fail without a reload:{}", lab.all()); + } + if (!lab.has("[Segment] 00: 00.02 failed; save mode none left no save at its start, so no reload")){ + return std::format("Expected why it didn't reload:{}", lab.all()); + } + return true; +} + +UnitTestResult test_first_row_still_reloads(){ + Lab lab; + lab.failures["00.01"] = 1; + const SegmentReport report = run_in(StorySaveMode::NONE, lab); + const std::vector expected = {"00.01", "reload", "00.01", "00.02", "00.03"}; + if (!report.completed || report.reloads != 1 || lab.trace != expected){ + return std::format("Expected the first checkpoint retried from the start save:{}", lab.all()); + } + return true; +} + +VerifyReport verify_in(StorySaveMode mode, Lab& lab){ + Segment segment = three_rows(lab); + SegmentHooks hooks = lab.hooks(); + RunState state; + const VerifyPolicy policy{.runs = 3, .passes_needed = 2, .save_mode = mode}; + return verify_checkpoint("00.02", policy, segment, hooks, state); +} + +UnitTestResult test_verify_saves_once_every_run_passed(){ + Lab lab; + const VerifyReport report = verify_in(StorySaveMode::AFTER_VERIFICATION, lab); + const std::vector expected = {"00.02", "reload", "00.02", "reload", "00.02", "save"}; + if (!report.verified || !report.saved || lab.trace != expected){ + return std::format("Expected one save, after the last run:{}", lab.all()); + } + if (!lab.has("[Verify] 00.02: every run passed: saved at the end state")){ + return std::format("Expected the save logged:{}", lab.all()); + } + return true; +} + +UnitTestResult test_verify_no_save_after_a_failed_run(){ + Lab lab; + lab.failures["00.02"] = 1; + const VerifyReport report = verify_in(StorySaveMode::AFTER_VERIFICATION, lab); + if (!report.verified || report.saved || std::find(lab.trace.begin(), lab.trace.end(), "save") != lab.trace.end()){ + return std::format("Verified 2/3, but a failed run means no save:{}", lab.all()); + } + if (!lab.has("[Verify] 00.02: not every run passed: not saving")){ + return std::format("Expected why it didn't save:{}", lab.all()); + } + return true; +} + + +// FRLG 00.31's end, in the shared format: beside B3F's Rare Candy, with +// the LIFT KEY and both Rare Candies. +inline constexpr std::string_view CHECKPOINT_0031 = R"({ + "id": "00.31", + "title": "Rocket Hideout to the LIFT KEY", + "start": {"map": "CeladonCity_PokemonCenter_1F", "tiles": [[7, 4]], "facing": "north"}, + "events": [ + {"id": "beside_b3f_rare_candy", "kind": "route", "args": {"target": {"map": "RocketHideout_B3F", "tiles": [[12, 13]], "facing": "north"}}}, + {"id": "b3f_rare_candy", "kind": "talk"} + ], + "postconditions": { + "position": {"map": "RocketHideout_B3F", "tiles": [[12, 13]], "facing": "north"}, + "items": [{"item": "LIFT_KEY", "quantity": 1}, {"item": "RARE_CANDY", "quantity": 2}] + } +})"; + +StoryCheckpoint checkpoint_0031(){ + return read_story_checkpoint(parse_json(std::string(CHECKPOINT_0031)), "00.31"); +} + +ObservedState read_0031(std::string map, int candies){ + ObservedState observed; + observed.map = std::move(map); + observed.tile = TilePos{12, 13}; + observed.facing = Direction::NORTH; + observed.items = {{"LIFT_KEY", 1}, {"RARE_CANDY", (size_t)candies}}; + return observed; +} + +UnitTestResult test_postconditions_json(){ + const StoryCheckpoint checkpoint = checkpoint_0031(); + const StoryPostconditions& post = checkpoint.postconditions; + if (!post.position || post.position->map != "RocketHideout_B3F" || post.items.size() != 2 + || post.items[1] != StoryItem{.item = "RARE_CANDY", .quantity = 2} + ){ + return "Unexpected postconditions read."; + } + const StoryCheckpoint again = read_story_checkpoint(story_checkpoint_json(checkpoint), "again"); + if (again.postconditions != post){ + return std::format("The postconditions should survive a write and read: {}", story_checkpoint_json(checkpoint).dump()); + } + return true; +} + +UnitTestResult test_postconditions_pass(){ + const PostconditionReport report = check_postconditions(checkpoint_0031(), read_0031("RocketHideout_B3F", 2)); + const std::vector lines = postcondition_log_lines(report); + if (!report.all_passed() || lines.back() != "[Postcondition] 00.31: 5 passed, 0 failed, 0 not checked: passed"){ + return std::format("Expected every postcondition passed: {}", lines.back()); + } + return true; +} + +// The 2026-11-10 false pass: still on B4F, the Rare Candy not picked up. +UnitTestResult test_postconditions_fail(){ + const PostconditionReport report = check_postconditions(checkpoint_0031(), read_0031("RocketHideout_B4F", 1)); + const std::vector lines = postcondition_log_lines(report); + const std::vector expected = { + "[Postcondition] 00.31 map: failed: expected RocketHideout_B3F, read RocketHideout_B4F", + "[Postcondition] 00.31 tile: not checked: on another map", + "[Postcondition] 00.31 facing: not checked: on another map", + "[Postcondition] 00.31 item LIFT_KEY: passed: 1", + "[Postcondition] 00.31 item RARE_CANDY: failed: expected 2, read 1", + "[Postcondition] 00.31: 1 passed, 2 failed, 2 not checked: failed", + }; + if (lines != expected){ + std::string text; + for (const std::string& line : lines){ + text += std::format("\n{}", line); + } + return std::format("Unexpected lines:{}", text); + } + return true; +} + +UnitTestResult test_postconditions_not_checked(){ + StoryCheckpoint checkpoint = checkpoint_0031(); + checkpoint.postconditions.flags = {"hideout_lift_key_grunt"}; + ObservedState observed; + observed.map = "RocketHideout_B3F"; + const PostconditionReport report = check_postconditions(checkpoint, observed); + const std::vector lines = postcondition_log_lines(report); + if (report.all_passed() || report.count(PostconditionVerdict::NOT_CHECKED) != 5 + || lines.back() != "[Postcondition] 00.31: 1 passed, 0 failed, 5 not checked: incomplete" + ){ + return std::format("What isn't read is not checked, never passed: {}", lines.back()); + } + observed.flags["hideout_lift_key_grunt"] = false; + if (check_postconditions(checkpoint, observed).count(PostconditionVerdict::FAILED) != 1){ + return "A flag read clear should fail."; + } + return true; +} + +UnitTestResult test_end_pose_from_the_plan(){ + StoryCheckpoint checkpoint = checkpoint_0031(); + checkpoint.postconditions.position.reset(); + const std::optional end = checkpoint_end_pose(checkpoint); + if (!end || end->map != "RocketHideout_B3F" || end->tiles != std::vector{TilePos{12, 13}}){ + return "Expected the last route's target as the end."; + } + StoryCheckpoint stepped = checkpoint; + StoryStep step; + step.kind = StoryStepKind::STEP; + step.name = "one more"; + stepped.steps.push_back(std::move(step)); + if (checkpoint_end_pose(stepped)){ + return "A step after the last target leaves the end unknown."; + } + StoryStep legs; + legs.kind = StoryStepKind::LEGS; + legs.name = "taps"; + checkpoint.steps.push_back(std::move(legs)); + if (checkpoint_end_pose(checkpoint)){ + return "Legs after the last target leave the end unknown."; + } + if (!check_postconditions(checkpoint, read_0031("RocketHideout_B3F", 2)).all_passed()){ + return "Without an end pose, the items alone should be checked."; + } + return true; +} + + +// The scenario to run. +struct SavePolicyInput{ + std::string name; + UnitTestResult (*test)() = nullptr; +}; + +// What the scenario checks; it returns its own failure. +struct SavePolicyExpectation{ + std::string_view description; +}; + +// A save-policy scenario and its expected result. +struct SavePolicyCase{ + SavePolicyInput input; + SavePolicyExpectation expectation; +}; + +class Test_StorySavePolicy : public UnitTest{ +public: + explicit Test_StorySavePolicy(SavePolicyCase test_case) + : UnitTest(std::format("Pokemon::StorySavePolicy - {}", test_case.input.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_case.input.test(); + } + +private: + SavePolicyCase m_case; +}; + +const SavePolicyCase SAVE_POLICY_CASES[] = { + { + .input = {.name = "decision table", .test = test_decision_table}, + .expectation = {.description = "mode x verdict x save point, all twelve rows"}, + }, + { + .input = {.name = "none never saves", .test = test_none_never_saves}, + .expectation = {.description = "three passing checkpoints, no save, each skip logged"}, + }, + { + .input = {.name = "per checkpoint saves each", .test = test_per_checkpoint_saves_each}, + .expectation = {.description = "a save after every passing checkpoint"}, + }, + { + .input = {.name = "after verification saves at the end", .test = test_after_verification_saves_at_the_end}, + .expectation = {.description = "one save after the last checkpoint; no check logged as not checked"}, + }, + { + .input = {.name = "after verification checks before saving", .test = test_after_verification_checks_before_saving}, + .expectation = {.description = "the game's postcondition check runs before the save"}, + }, + { + .input = {.name = "failed postconditions never save", .test = test_failed_postconditions_never_save}, + .expectation = {.description = "a failed check fails the run and refuses the save"}, + }, + { + .input = {.name = "no reload after the first checkpoint", .test = test_no_reload_after_the_first}, + .expectation = {.description = "a later checkpoint has no save to reload, so it fails at once"}, + }, + { + .input = {.name = "the first checkpoint still reloads", .test = test_first_row_still_reloads}, + .expectation = {.description = "the first checkpoint reloads the run's start save"}, + }, + { + .input = {.name = "verify saves once every run passed", .test = test_verify_saves_once_every_run_passed}, + .expectation = {.description = "3/3 passed: one save at the end of run 3"}, + }, + { + .input = {.name = "verify: no save after a failed run", .test = test_verify_no_save_after_a_failed_run}, + .expectation = {.description = "2/3 verified, but no save"}, + }, + { + .input = {.name = "postconditions: json", .test = test_postconditions_json}, + .expectation = {.description = "00.31's postconditions read and written back"}, + }, + { + .input = {.name = "postconditions: pass", .test = test_postconditions_pass}, + .expectation = {.description = "B3F (12, 13) north, LIFT_KEY 1, RARE_CANDY 2: passed"}, + }, + { + .input = {.name = "postconditions: fail", .test = test_postconditions_fail}, + .expectation = {.description = "still on B4F with 1 Rare Candy: failed"}, + }, + { + .input = {.name = "postconditions: not checked", .test = test_postconditions_not_checked}, + .expectation = {.description = "unread parts are not checked, never passed"}, + }, + { + .input = {.name = "postconditions: end pose from the plan", .test = test_end_pose_from_the_plan}, + .expectation = {.description = "the last route's target, or unknown after legs"}, + }, +}; + +} // namespace + + +void add_tests_StorySavePolicy(UnitTestDatabase& database){ + for (const SavePolicyCase& test_case : SAVE_POLICY_CASES){ + database.add(test_case); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.h new file mode 100644 index 0000000000..4e95d5e81a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.h @@ -0,0 +1,23 @@ +/* Story Save Policy Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StorySavePolicy_Tests_H +#define PokemonAutomation_Pokemon_StorySavePolicy_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for when a run saves (save modes) and the postcondition check. +void add_tests_StorySavePolicy(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 854ae22f17..c46ab2764e 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp @@ -95,37 +95,109 @@ Outcome reload(RunState& state, SegmentHooks& hooks){ return outcome_ok(); } +// The segment's save hook as a checkpoint's save. +Act hook_save(SegmentHooks& hooks){ + return [&hooks](RunState& state){ + return hooks.save ? hooks.save(state) : outcome_failed("no_save_hook"); + }; +} + +// `save`, after the game's postcondition check of checkpoint `id`: one +// that failed stops the save. Without a check, logs that nothing was +// checked, never that it passed. +Act checked_save(Act save, std::string id, SegmentHooks& hooks){ + return [save = std::move(save), id = std::move(id), &hooks](RunState& state) mutable{ + if (!hooks.check_postconditions){ + say(std::format("[Postcondition] {}: not checked: the game has no postcondition check", id), hooks); + return save(state); + } + const Outcome checked = hooks.check_postconditions(id, state); + if (!checked.succeeded()){ + say(checkpoint_log_line(id, "postconditions failed, not saving"), hooks); + return outcome_failed("postconditions_failed", to_string(checked)); + } + return save(state); + }; +} + +// A row to run, and where it stands in the run. +struct Row{ + CheckpointSpec& spec; + // The run's first: its save is the one the run started from. + bool first = false; + // The run's last: it ends at the run's end state. + bool last = false; +}; + +// The checkpoint's save as `policy.save_mode` allows: one the mode skips +// logs that it did not save; the run's last in AFTER_VERIFICATION saves +// (with the segment's hook if it has none) after the postcondition check. +void set_save(const Row& row, const SegmentPolicy& policy, SegmentHooks& hooks, Checkpoint& checkpoint){ + const StorySaveMode mode = policy.save_mode; + const bool saves_at_end = mode == StorySaveMode::AFTER_VERIFICATION && row.last; + if ((row.spec.saves || saves_at_end) && !checkpoint.save){ + checkpoint.save = hook_save(hooks); + } + if (!checkpoint.save){ + return; + } + const SavePoint point = row.last ? SavePoint::RUN_END : SavePoint::CHECKPOINT_END; + if (!story_save_allowed(mode, CheckpointVerdict::PASSED, point)){ + checkpoint.save = [&hooks, id = row.spec.id, mode](RunState&){ + say(checkpoint_log_line(id, std::format("not saving (save mode {})", story_save_mode_name(mode))), hooks); + return outcome_ok(); + }; + return; + } + if (saves_at_end){ + checkpoint.save = checked_save(std::move(checkpoint.save), row.spec.id, hooks); + } +} + +// Attempts the row gets: a row after the first has a save at its start +// only when every checkpoint saves, so otherwise a reload would go back +// to the run's start, and it gets one. +size_t row_attempts(const Row& row, const SegmentPolicy& policy){ + if (row.first || policy.save_mode == StorySaveMode::PER_CHECKPOINT){ + return policy.attempts_per_checkpoint; + } + return 1; +} + // One row to success through run_checkpoint_attempts(), reloading and // rebuilding after each failed attempt. Returns the last attempt's report, // or the reload's failure; `run` says how many attempts it took. CheckpointReport run_row( - const Segment& segment, const SegmentPolicy& policy, CheckpointSpec& spec, + const Segment& segment, const Row& row, const SegmentPolicy& policy, SegmentHooks& hooks, SegmentReport& report, CheckpointRun& run, RunState& state ){ + const size_t max_attempts = row_attempts(row, policy); CheckpointReport result; const CheckpointAttempts attempts{ - .max_attempts = policy.attempts_per_checkpoint, + .max_attempts = max_attempts, .run = [&](size_t attempt){ run.attempts = attempt; - Checkpoint checkpoint = spec.build(); - if (spec.saves && !checkpoint.save){ - checkpoint.save = [&hooks](RunState& state){ - return hooks.save ? hooks.save(state) : outcome_failed("no_save_hook"); - }; - } + Checkpoint checkpoint = row.spec.build(); + set_save(row, policy, hooks, checkpoint); EventLogger log = [&hooks](const std::string& line){ say(line, hooks); }; result = run_checkpoint(state, checkpoint, log); if (result.completed){ return AttemptResult::PASSED; } if (result.failure.failure == GAME_NOT_RUNNING){ - say(std::format("[Segment] {}: {} failed; the game is not running, so no reload", segment.id, spec.id), hooks); + say(std::format("[Segment] {}: {} failed; the game is not running, so no reload", segment.id, row.spec.id), hooks); return AttemptResult::FINAL; } + if (attempt >= max_attempts && max_attempts < policy.attempts_per_checkpoint){ + say(std::format( + "[Segment] {}: {} failed; save mode {} left no save at its start, so no reload", + segment.id, row.spec.id, story_save_mode_name(policy.save_mode) + ), hooks); + } return AttemptResult::FAILED; }, .reset = [&](size_t next_attempt){ - say(checkpoint_reset_line(spec.id, next_attempt, policy.attempts_per_checkpoint), hooks); + say(checkpoint_reset_line(row.spec.id, next_attempt, policy.attempts_per_checkpoint), hooks); report.reloads++; Outcome reloaded = reload(state, hooks); if (!reloaded.succeeded()){ @@ -136,7 +208,7 @@ CheckpointReport run_row( }, .log = [&hooks](const std::string& line){ say(line, hooks); }, }; - run.passed = run_checkpoint_attempts(spec.id, attempts).passed; + run.passed = run_checkpoint_attempts(row.spec.id, attempts).passed; return result; } @@ -166,11 +238,15 @@ SegmentReport run_segment( return stop_segment(segment.id, selected.failure, hooks, report); } say(std::format("[Segment] {}: start, {} checkpoints", segment.id, selected.last - selected.first + 1), hooks); + if (policy.save_mode != StorySaveMode::PER_CHECKPOINT){ + say(std::format("[Segment] {}: save mode {}", segment.id, story_save_mode_name(policy.save_mode)), hooks); + } for (size_t c = selected.first; c <= selected.last; c++){ CheckpointSpec& spec = segment.checkpoints[c]; report.checkpoints_run++; report.runs.push_back(CheckpointRun{.id = spec.id}); - CheckpointReport result = run_row(segment, policy, spec, hooks, report, report.runs.back(), state); + const Row row{.spec = spec, .first = c == selected.first, .last = c == selected.last}; + CheckpointReport result = run_row(segment, row, policy, hooks, report, report.runs.back(), state); if (!result.completed){ report.failed_checkpoint = spec.id; report.failed_event = result.failed_name; @@ -186,13 +262,20 @@ SegmentReport run_segment( namespace{ -// One verify run: the checkpoint built fresh, without its end save. -// Returns true if it passed. +// One verify run: the checkpoint built fresh. Its end save only if +// `save_at_end` (AFTER_VERIFICATION's last run, every run before it +// passed), after the postcondition check. Returns true if it passed. bool verify_run( - size_t run, const VerifyPolicy& policy, CheckpointSpec& spec, SegmentHooks& hooks, RunState& state + size_t run, const VerifyPolicy& policy, bool save_at_end, + CheckpointSpec& spec, SegmentHooks& hooks, RunState& state ){ Checkpoint checkpoint = spec.build(); - checkpoint.save = nullptr; + if (save_at_end){ + Act save = checkpoint.save ? std::move(checkpoint.save) : hook_save(hooks); + checkpoint.save = checked_save(std::move(save), spec.id, hooks); + }else{ + checkpoint.save = nullptr; + } EventLogger log = [&hooks](const std::string& line){ say(line, hooks); }; const CheckpointReport result = run_checkpoint(state, checkpoint, log); if (result.completed){ @@ -208,7 +291,19 @@ bool verify_run( return false; } +// AFTER_VERIFICATION saves at the end of the last run when every run +// before it passed. +bool verify_saves_after(const VerifyReport& report, const VerifyPolicy& policy, size_t run){ + return policy.save_mode == StorySaveMode::AFTER_VERIFICATION && run == policy.runs && report.passes + 1 == run; +} + VerifyReport verify_summary(const VerifyPolicy& policy, SegmentHooks& hooks, VerifyReport& report){ + if (policy.save_mode == StorySaveMode::AFTER_VERIFICATION){ + say(std::format( + "[Verify] {}: {}", report.checkpoint, + report.saved ? "every run passed: saved at the end state" : "not every run passed: not saving" + ), hooks); + } report.verified = report.failure.succeeded() && report.passes >= policy.passes_needed; say(std::format( "[Verify] {}: {}/{} passed, {} needed: {}", @@ -251,7 +346,10 @@ VerifyReport verify_checkpoint( } } report.runs++; - report.passes += verify_run(run, policy, spec, hooks, state) ? 1 : 0; + const bool save_at_end = verify_saves_after(report, policy, run); + const bool passed = verify_run(run, policy, save_at_end, spec, hooks, state); + report.passes += passed ? 1 : 0; + report.saved = save_at_end && passed; } return verify_summary(policy, hooks, report); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h index 8fd66e55f4..280504487f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h @@ -57,9 +57,15 @@ struct SegmentHooks{ // overlay, so whoever watches the stream sees the step under way; and, // once run records land (#132), for the run's events. EventLogger status; + // Optional: the game's postcondition check of a checkpoint, by id + // (check_postconditions(), Pokemon_StoryPostconditionCheck.h), run + // before a save in AFTER_VERIFICATION mode: one that failed stops the + // save and fails the run. The game logs its lines. + MoveOnlyFunction check_postconditions; }; -// Runs the checkpoints in `range`, in order. Logs through `hooks.log`, +// Runs the checkpoints in `range`, in order, saving as `policy.save_mode` +// allows (story_save_allowed()). Logs through `hooks.log`, // around the checkpoint lines: // [Segment] 00: start, 3 checkpoints // [Checkpoint] 00.02: failed, resetting for attempt 2/3 @@ -83,6 +89,9 @@ struct VerifyPolicy{ size_t runs = 3; // Passing runs the checkpoint needs to be verified. size_t passes_needed = 2; + // AFTER_VERIFICATION saves once, at the end of the last run, when + // every run passed; any other mode never saves. + StorySaveMode save_mode = StorySaveMode::NONE; }; // Verification results for multiple runs of a checkpoint. @@ -92,13 +101,17 @@ struct VerifyReport{ size_t passes = 0; // At least VerifyPolicy::passes_needed runs passed. bool verified = false; + // AFTER_VERIFICATION: every run passed and the last saved at its end. + bool saved = false; // What stopped the runs early: an unknown checkpoint, a bad policy or // a failed reload. Runs that fail are counted, not stopped at. Outcome failure; }; // Runs checkpoint `id` of `segment` as `policy` says, from the save the -// game is on. No retries, no in-place recoveries and no save at its end. +// game is on. No retries, no in-place recoveries and no save at its end, +// but for `policy.save_mode` AFTER_VERIFICATION's one save at the end of +// the last run, when every run passed (after the postcondition check). // Logs through `hooks.log`, after each run's checkpoint lines: // [Verify] 00.15b: start, 3 runs from one save, 2 must pass // [Verify] 00.15b: run 1/3 passed diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp new file mode 100644 index 0000000000..5fddda901a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp @@ -0,0 +1,160 @@ +/* Story Step Executor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Pokemon_BuiltinStoryActions.h" +#include "Pokemon_StoryStepExecutor.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +Pose pose_of(const GridPose& pose){ + return tile_pose(pose.map, pose.tiles, pose.facing); +} + +Outcome unsupported_step(const StoryStep& step){ + return outcome_failed("unsupported_step", std::format("{} {}", story_step_kind_name(step.kind), step.name)); +} + + +void StoryStepExecutor::begin_attempt(const StoryCheckpoint&){} + +bool StoryStepExecutor::holds(std::string_view condition, RunState& state){ + return state.flags.contains(std::string(condition)); +} + + +Event story_event(const StoryStep& step, StoryStepExecutor& executor){ + Event event; + event.name = step.name; + event.why = step.why; + for (const std::string& name : step.skip_if){ + event.skip_if.push_back(condition(name, [&executor, name](RunState& state){ + return executor.holds(name, state); + })); + } + event.act = [&executor, &step](RunState& state){ + return executor.run(step, state); + }; + if (step.pose_after){ + event.pose_learned = pose_of(*step.pose_after); + } + return event; +} + +namespace{ + +// The first event of a checkpoint that starts from a save: where the save +// leaves the player, for a run that reloaded it. +Event from_save_event(const Pose& start){ + Event event; + event.name = "from_save"; + event.why = "where the checkpoint's save leaves the player"; + event.act = [](RunState&){ return outcome_ok(); }; + event.pose_learned = start; + return event; +} + +} // namespace + +namespace{ + +// `event`, for a once_per_save step known in `prepared` as `key`: skipped +// while `prepared` has it, and added to it when it succeeds changing +// nothing. +void run_once_per_save(std::string key, Event& event, PreparedSteps& prepared){ + event.skip_if.push_back(condition("done_from_this_save", [&prepared, key](RunState&){ + return prepared.contains(key); + })); + event.act = [act = std::move(event.act), &prepared, key](RunState& state) mutable{ + Outcome outcome = act(state); + if (outcome.succeeded() && outcome.changed_nothing){ + prepared.insert(key); + } + return outcome; + }; +} + +} // namespace + +Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor& executor, PreparedSteps* prepared){ + executor.begin_attempt(data); + Checkpoint checkpoint; + checkpoint.id = data.id; + if (data.start){ + checkpoint.events.push_back(from_save_event(pose_of(*data.start))); + } + for (const StoryStep& step : data.steps){ + checkpoint.events.push_back(story_event(step, executor)); + if (prepared != nullptr && step.once_per_save){ + run_once_per_save(std::format("{}/{}", data.id, step.name), checkpoint.events.back(), *prepared); + } + } + return checkpoint; +} + + +namespace{ + +// What is wrong with a step's action and args, each as a line: a GAME +// step without an action, args that don't fit a built-in action's spec, +// an empty leg. +std::vector action_problems(const StoryStep& step){ + if (step.kind == StoryStepKind::GAME){ + return step.action.empty() ? std::vector{"no action"} : std::vector{}; + } + const StoryActionSpec* spec = find_story_action(builtin_story_actions(), step.kind, step.action); + if (spec == nullptr){ + // A game's own action: the game checks it when it loads the step. + return {}; + } + std::vector problems = story_args_errors(*spec, step.args); + const std::vector* legs = value_if_at_it>(step.args, step.args.find("legs")); + if (legs != nullptr && legs->empty()){ + problems.emplace_back("no legs"); + } + for (const StoryLeg& leg : legs ? *legs : std::vector{}){ + if (leg.tiles <= 0){ + problems.emplace_back("a leg of no tiles"); + } + } + return problems; +} + +} // namespace + +std::vector lint_story_checkpoint(const StoryCheckpoint& data){ + std::vector problems; + if (data.id.empty()){ + problems.emplace_back("a checkpoint has no id"); + } + std::set names; + for (size_t c = 0; c < data.steps.size(); c++){ + const StoryStep& step = data.steps[c]; + const std::string where = std::format("{} step {}", data.id, c + 1); + if (step.name.empty()){ + problems.emplace_back(std::format("{}: no name", where)); + }else if (!names.insert(step.name).second){ + problems.emplace_back(std::format("{}: a second step named {}", where, step.name)); + } + for (const std::string& problem : action_problems(step)){ + problems.emplace_back(std::format("{} {}: {} {}", where, step.name, story_step_kind_name(step.kind), problem)); + } + // skip_if's conditions must all hold; once per save is one more. + if (step.once_per_save && !step.skip_if.empty()){ + problems.emplace_back(std::format("{} {}: once per save with skip_if", where, step.name)); + } + } + return problems; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h new file mode 100644 index 0000000000..069845ec0c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h @@ -0,0 +1,107 @@ +/* Story Step Executor + * + * From: https://github.com/PokemonAutomation/ + * + * One vocabulary of story steps for the tile games (FRLG, BDSP): a route, + * a fixed walk, a step onto a trigger, a talk, a YES/NO, a scene, a + * battle, the nurse, a shop, a save, and so on. A checkpoint is a list of + * such steps, plain data (Types/), so a game's story is a table its unit + * tests can plan without a console. + * + * build_story_checkpoint() turns a table row into engine events + * (Pokemon_StoryEvents.h). Each event's action asks the game's + * StoryStepExecutor to do its step; a game implements the kinds it uses, + * and a step it has no way of doing fails by name (unsupported_step()) + * instead of doing something else. + * + * Steps never match dialogue or menu text: they look for screen state (a + * dialogue box, an arrow, a fade, a battle menu, colours, positions). The + * few reads that need text (item names in a shop or the Bag) take the + * game's language from the program's options (StoryRunOptions), and with + * no reader for it fall back to checks that need none (a row's position, + * digits, a changed screen), so a run never fails because its language + * is not supported. + * + * Poses are the game's own (Pose, with a TilePose for these games): a + * checkpoint's start, a scene's end and a route's target are poses, and + * an executor that knows where a step left the player says so in its + * Outcome, which the engine writes into the run. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepExecutor_H +#define PokemonAutomation_Pokemon_StoryStepExecutor_H + +#include +#include +#include +#include +#include "Pokemon_StoryEvents.h" +#include "Pokemon_TilePose.h" +#include "Types/Pokemon_GridPose.h" +#include "Types/Pokemon_StoryCheckpoint.h" +#include "Types/Pokemon_StoryStep.h" +#include "Types/Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How a game does its story steps: an interface with no data. run() is the +// game's: it does the step's kind its own way (FRLG and BDSP bind kinds and +// variants to actions in a table), and returns unsupported_step() for a +// kind it has no way of doing. +class StoryStepExecutor{ +public: + virtual ~StoryStepExecutor() = default; + + // A checkpoint is being built for a new attempt: build_story_checkpoint() + // calls this first, so a game can start the attempt afresh (trainers + // who can see us again, the row's own settings). Does nothing by default. + virtual void begin_attempt(const StoryCheckpoint& data); + + // Does `step`, from the run so far. + virtual Outcome run(const StoryStep& step, RunState& state) = 0; + + // Whether the condition named in a step's skip_if holds: by default, + // whether the run has the flag (set by an earlier step's action). + virtual bool holds(std::string_view condition, RunState& state); +}; + +// `pose` as the engine's Pose: a TilePose, TILE for one tile, SET for several. +Pose pose_of(const GridPose& pose); + +// "unsupported_step: TRAIN train_in_grass": what an executor without the kind returns. +Outcome unsupported_step(const StoryStep& step); + + +// The step as an event that runs it with `executor`. Both must outlive +// the event. +Event story_event(const StoryStep& step, StoryStepExecutor& executor); + +// The once_per_save steps done from the save the game is on that changed +// nothing, as "/". The game keeps it across reloads and +// empties it when it saves or loads another save. +using PreparedSteps = std::set; + +// The checkpoint `data` as events: "from_save" first when it has a start +// (the start pose, for a run that reloaded its save), then one event per +// step. `data` and `executor` must outlive the checkpoint. Saving is the +// game's: it sets the checkpoint's save, or adds a SAVE step. +// With `prepared`, each once_per_save step is skipped while `prepared` has +// it, and added to it when it succeeds changing nothing; `prepared` must +// then outlive the checkpoint. Without, once_per_save steps run every time. +Checkpoint build_story_checkpoint( + const StoryCheckpoint& data, StoryStepExecutor& executor, PreparedSteps* prepared = nullptr +); + +// Problems an author should fix before running: an empty id, unnamed or +// repeated steps, a GAME step without an action, a built-in action's args +// that don't fit its spec (a route without a target), empty legs. +std::vector lint_story_checkpoint(const StoryCheckpoint& data); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp new file mode 100644 index 0000000000..d3deb509d6 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp @@ -0,0 +1,828 @@ +/* Story Steps Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Story tables built into checkpoints and run against a fake executor + * that writes down each step it is asked to do: the order of the events, + * skipped steps, the pose each step leaves, and how a failure is named. + * Nothing here belongs to one game. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/Options/Pokemon_GameLanguages.h" +#include "Pokemon/Options/Pokemon_StoryRunOptions.h" +#include "Pokemon_AutoStorySelect.h" +#include "Pokemon_AutoStoryStats.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_BuiltinStoryActions.h" +#include "Pokemon_StorySegments.h" +#include "Pokemon_StoryStepExecutor.h" +#include "Pokemon_TilePose.h" +#include "Pokemon_StoryStepExecutor_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// A world of two maps. Routes arrive on their target; a step moves a tile +// from the run's pose. Each step it does is written down as "KIND name", +// with the pose it started from when that is known. +class FakeExecutor : public StoryStepExecutor{ +public: + std::vector trace; + 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. + std::map failures_left; + // The pose each step started from, by name. + std::vector> poses_seen; + // The checkpoints begun, one per attempt. + std::vector attempts; + // Game steps by name that change nothing in the game. + std::set unchanged; + + virtual void begin_attempt(const StoryCheckpoint& data) override{ + attempts.push_back(data.id); + } + + virtual Outcome run(const StoryStep& step, RunState& state) override{ + poses_seen.emplace_back(step.name, to_string(state.pose)); + trace.push_back(std::format("{} {}", story_step_kind_name(step.kind), step.name)); + if (failing.contains(step.name)){ + return outcome_failed("blocked", std::format("{} was blocked", step.name)); + } + size_t& left = failures_left[step.name]; + if (left > 0){ + left--; + return outcome_failed("blocked", std::format("{} was blocked", step.name)); + } + return run_kind(step, state); + } + + virtual bool holds(std::string_view condition, RunState& state) override{ + return conditions.contains(condition) || StoryStepExecutor::holds(condition, state); + } + +private: + // The kinds this world has; any other is unsupported. + Outcome run_kind(const StoryStep& step, RunState& state){ + switch (step.kind){ + case StoryStepKind::ROUTE: + return outcome_ok(pose_of(story_arg(step.args, "target"))); + case StoryStepKind::STEP: + return step_one_tile(step, state); + case StoryStepKind::TALK: + case StoryStepKind::MASH: + return outcome_ok(); + case StoryStepKind::BATTLE: + // The first battle is lost; a step that may lose goes on. + return story_arg(step.args, "may_lose") ? outcome_ok() : outcome_failed("blackout"); + case StoryStepKind::SHOP: + return shop(step); + case StoryStepKind::GAME: + return game(step, state); + default: + return unsupported_step(step); + } + } + + Outcome step_one_tile(const StoryStep& step, const RunState& state){ + const std::vector tiles = tiles_of(state.pose); + if (tiles.size() != 1){ + return outcome_failed("no_pose", to_string(state.pose)); + } + 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 : story_arg>(step.args, "items")){ + trace.push_back(std::format(" bought {} {}", item.quantity, item.item)); + } + return outcome_ok(); + } + + // A game step sets a run flag named for its action. + Outcome game(const StoryStep& step, RunState& state){ + trace.push_back(std::format(" game {}", step.action)); + state.flags.insert(step.action); + return unchanged.contains(step.name) ? outcome_unchanged() : outcome_ok(); + } +}; + +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; +} + +// 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.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.args = {{"direction", direction}}; + return step; +} + +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; +} + +// A lab checkpoint: to the table, a trigger, the scene into the lab, a +// talk, a shop, a game step. +StoryCheckpoint lab_checkpoint(){ + StoryStep shop = make(StoryStepKind::SHOP, "potions"); + shop.args = {{"items", std::vector{{.item = "potion", .quantity = 5}, {.item = "antidote", .quantity = 3}}}}; + StoryStep game = make(StoryStepKind::GAME, "dance"); + game.action = "dance"; + return StoryCheckpoint{ + .id = "00.03", + .title = "to the lab", + .start = grid("Town", {6, 8}, Direction::SOUTH), + .steps = { + route_to("below_trigger", grid("Town", {12, 2}, Direction::NORTH)), + step_into("trigger", Direction::NORTH), + scene("to_the_lab", grid("Lab", {6, 4}, Direction::NORTH)), + make(StoryStepKind::TALK, "talk_oak"), + shop, + game, + }, + }; +} + +struct Run{ + CheckpointReport report; + RunState state; + std::vector lines; +}; + +Run run(const StoryCheckpoint& data, StoryStepExecutor& executor){ + Run ret; + Checkpoint checkpoint = build_story_checkpoint(data, executor); + EventLogger log = [&ret](const std::string& line){ ret.lines.push_back(line); }; + ret.report = run_checkpoint(ret.state, checkpoint, log); + return ret; +} + +std::string joined(std::span lines){ + std::string text; + for (const std::string& line : lines){ + text += std::format("\n {}", line); + } + return text; +} + + +UnitTestResult test_events_in_table_order(){ + const StoryCheckpoint data = lab_checkpoint(); + FakeExecutor executor; + const Run result = run(data, executor); + const std::vector expected{ + "ROUTE below_trigger", + "STEP trigger", + "MASH to_the_lab", + "TALK talk_oak", + "SHOP potions", + " bought 5 potion", + " bought 3 antidote", + "GAME dance", + " game dance", + }; + if (!result.report.completed || executor.trace != expected){ + return std::format("Expected the steps in table order:{}\nbut ran:{}", joined(expected), joined(executor.trace)); + } + // "from_save" is the engine's own event: the executor is not asked. + const std::string first = event_log_line("00.03", 1, "from_save", "start"); + if (result.lines.empty() || std::find(result.lines.begin(), result.lines.end(), first) == result.lines.end()){ + return std::format("Expected the from_save event first:{}", joined(result.lines)); + } + return true; +} + +UnitTestResult test_skip_if(){ + StoryCheckpoint data = lab_checkpoint(); + data.steps[0].skip_if = {"has_parcel"}; + data.steps[3].skip_if = {"has_parcel", "talked"}; + FakeExecutor executor; + executor.conditions = {"has_parcel"}; + // The route is skipped; the talk needs both conditions, so it runs. + const Run result = run(data, executor); + if (!result.report.completed || result.report.events_skipped != 1){ + return std::format("Expected one step skipped, got {}:{}", result.report.events_skipped, joined(result.lines)); + } + if (std::find(executor.trace.begin(), executor.trace.end(), "ROUTE below_trigger") != executor.trace.end()){ + return std::format("Expected the route skipped:{}", joined(executor.trace)); + } + if (std::find(executor.trace.begin(), executor.trace.end(), "TALK talk_oak") == executor.trace.end()){ + return std::format("Expected the talk run, one of its conditions not holding:{}", joined(executor.trace)); + } + + // By default a condition is a run flag: the game step "dance" sets + // one, and a talk after it that needs it is skipped. + StoryStep after = make(StoryStepKind::TALK, "talk_after_dance"); + after.skip_if = {"dance"}; + data = lab_checkpoint(); + data.steps.push_back(after); + FakeExecutor plain; + const Run flagged = run(data, plain); + if (!flagged.report.completed || flagged.report.events_skipped != 1 || plain.trace.back() != " game dance"){ + return std::format("Expected the talk after the dance skipped on its flag:{}", joined(plain.trace)); + } + return true; +} + +UnitTestResult test_pose_propagation(){ + const StoryCheckpoint data = lab_checkpoint(); + FakeExecutor executor; + const Run result = run(data, executor); + // Each step starts where the one before left the player: the save, the + // route's target, a tile north of it, the scene's end, and the scene's + // end again after a talk that says nothing of where it leaves us. + const std::vector> expected{ + {"below_trigger", "Town (6, 8) facing south (tile)"}, + {"trigger", "Town (12, 2) facing north (tile)"}, + {"to_the_lab", "Town (12, 1) facing north (tile)"}, + {"talk_oak", "Lab (6, 4) facing north (tile)"}, + {"potions", "Lab (6, 4) facing north (tile)"}, + {"dance", "Lab (6, 4) facing north (tile)"}, + }; + if (!result.report.completed || executor.poses_seen != expected){ + std::string text; + for (const auto& item : executor.poses_seen){ + text += std::format("\n {}: {}", item.first, item.second); + } + return std::format("Unexpected poses at the steps' starts:{}", text); + } + if (to_string(result.state.pose) != "Lab (6, 4) facing north (tile)"){ + return std::format("Expected the run to end at the scene's end, got {}", to_string(result.state.pose)); + } + return true; +} + +UnitTestResult test_failure_names_the_step(){ + const StoryCheckpoint data = lab_checkpoint(); + FakeExecutor executor; + executor.failing = {"trigger"}; + const Run result = run(data, executor); + // Event 3: from_save is event 1. + if (result.report.completed || result.report.failed_event != 3 || result.report.failed_name != "trigger" + || result.report.failure.failure != "blocked" + ){ + return std::format("Expected a failure at event 3 trigger, blocked:{}", joined(result.lines)); + } + if (executor.trace.size() != 2){ + return std::format("Expected nothing run after the failed step:{}", joined(executor.trace)); + } + return true; +} + +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.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 std::format("Expected TRAIN unsupported:{}", joined(result.lines)); + } + StoryStep rival = make(StoryStepKind::BATTLE, "rival"); + 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"){ + return std::format("Expected the rival's battle passed and Brock's lost:{}", joined(result.lines)); + } + return true; +} + +// Runs `tables` as one segment whose saves and reloads go into the +// executor's trace and whose log lines go into `lines`. Whatever blocked a +// step has gone by the reload. +SegmentReport run_tables(std::span tables, FakeExecutor& executor, std::vector& lines){ + Segment segment; + segment.id = "00"; + for (const StoryCheckpoint& data : tables){ + segment.checkpoints.push_back(CheckpointSpec{ + .id = data.id, .title = data.title, .saves = true, + .build = [&data, &executor]{ return build_story_checkpoint(data, executor); }, + }); + } + SegmentHooks hooks; + hooks.save = [&executor](RunState&){ + executor.trace.push_back("save"); + return outcome_ok(); + }; + hooks.reload = [&executor](RunState&){ + executor.trace.push_back("reload"); + executor.failing.clear(); + return outcome_ok(); + }; + hooks.log = [&lines](const std::string& line){ lines.push_back(line); }; + RunState state; + return run_segment(SegmentRange{}, SegmentPolicy{}, segment, hooks, state); +} + +UnitTestResult test_segment_of_tables(){ + // Two rows built into a segment, run with saves and a reload from the + // game's hooks: the second row's first attempt fails, its retry starts + // over from its start pose. + const std::vector tables{ + lab_checkpoint(), + StoryCheckpoint{ + .id = "00.04", + .title = "the parcel", + .start = grid("Lab", {6, 4}, Direction::NORTH), + .steps = {make(StoryStepKind::TALK, "give_parcel")}, + }, + }; + FakeExecutor executor; + executor.failing = {"give_parcel"}; + std::vector lines; + const SegmentReport report = run_tables(tables, executor, lines); + const std::vector tail{"save", "TALK give_parcel", "reload", "TALK give_parcel", "save"}; + const bool tail_matches = executor.trace.size() >= tail.size() + && std::equal(tail.begin(), tail.end(), executor.trace.end() - (std::ptrdiff_t)tail.size()); + if (!report.completed || report.reloads != 1 || !tail_matches){ + return std::format("Expected 00.04 reloaded once and passed:{}{}", joined(executor.trace), joined(lines)); + } + // Each attempt is begun anew: 00.03 once, 00.04 twice. + if (executor.attempts != std::vector{"00.03", "00.04", "00.04"}){ + return std::format("Expected the executor told of each attempt:{}", joined(executor.attempts)); + } + // The report and the log tell a one-shot pass from a retried one. + const bool runs_ok = report.runs.size() == 2 + && 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](std::string_view line){ + return std::find(lines.begin(), lines.end(), line) != lines.end(); + }; + if (!runs_ok + || !has("[Checkpoint] 00.03: passed on attempt 1 (one-shot)") + || !has("[Checkpoint] 00.04: passed on attempt 2 (1 reset)") + || !has("[Segment] 00: 1 of 2 checkpoints one-shot") + ){ + return std::format("Expected 00.03 one-shot and 00.04 passed on attempt 2:{}", joined(lines)); + } + return true; +} + + +// The two tables of test_segment_of_tables() as a segment run by `executor`, +// 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 = grid("Lab", {6, 4}, Direction::NORTH), + .steps = {make(StoryStepKind::TALK, "give_parcel")}, + }, + }; + FakeExecutor executor; + std::vector lines; + + SegmentReport run(const SegmentPolicy& policy){ + Segment segment; + segment.id = "00"; + for (const StoryCheckpoint& data : tables){ + segment.checkpoints.push_back(CheckpointSpec{ + .id = data.id, .title = data.title, .saves = true, + .build = [&data, this]{ return build_story_checkpoint(data, executor); }, + }); + } + SegmentHooks hooks; + hooks.save = [this](RunState&){ + executor.trace.push_back("save"); + return outcome_ok(); + }; + hooks.reload = [this](RunState&){ + executor.trace.push_back("reload"); + return outcome_ok(); + }; + hooks.log = [this](const std::string& line){ lines.push_back(line); }; + RunState state; + return run_segment(SegmentRange{}, policy, segment, hooks, state); + } + bool has(std::string_view line) const{ + return std::find(lines.begin(), lines.end(), line) != lines.end(); + } + size_t count(std::string_view item) const{ + return (size_t)std::count(executor.trace.begin(), executor.trace.end(), item); + } +}; + +UnitTestResult test_policy_attempts_then_fail(){ + // Three attempts by default, then the segment stops on the last one's failure. + PolicyLab lab; + lab.executor.failing = {"give_parcel"}; + const SegmentReport report = lab.run(SegmentPolicy{}); + if (report.completed || report.reloads != 2 || lab.count("TALK give_parcel") != 3 + || report.runs.size() != 2 || report.runs[1].passed || report.runs[1].attempts != 3 + || report.failed_checkpoint != "00.04" || report.failure.failure != "blocked" + ){ + return std::format("Expected 00.04 tried 3 times, then failed:{}{}", joined(lab.executor.trace), joined(lab.lines)); + } + return true; +} + +UnitTestResult test_policy_stop_at_first_failure(){ + PolicyLab lab; + lab.executor.failing = {"give_parcel"}; + 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 + ){ + return std::format("Expected a stop at the first failure, with no reload:{}{}", joined(lab.executor.trace), joined(lab.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`. +struct BossLab{ + StoryCheckpoint table{ + .id = "00.15b", + .title = "the rival", + .start = grid("Cerulean", {23, 7}, Direction::NORTH), + .steps = {once("teach_known"), once("teach_new"), make(StoryStepKind::BATTLE, "rival")}, + }; + FakeExecutor executor; + PreparedSteps prepared; + std::vector lines; + + static StoryStep once(std::string name){ + StoryStep step = make(StoryStepKind::GAME, name); + step.action = name; + step.once_per_save = true; + return step; + } + BossLab(){ + executor.unchanged = {"teach_known"}; + } + Segment segment(){ + Segment segment; + 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); }, + }); + return segment; + } + SegmentHooks hooks(){ + SegmentHooks hooks; + hooks.save = [this](RunState&){ + executor.trace.push_back("save"); + prepared.clear(); + return outcome_ok(); + }; + hooks.reload = [this](RunState&){ + executor.trace.push_back("reload"); + return outcome_ok(); + }; + hooks.log = [this](const std::string& line){ lines.push_back(line); }; + return hooks; + } + size_t count(std::string_view item) const{ + return (size_t)std::count(executor.trace.begin(), executor.trace.end(), item); + } +}; + +// A retry after a reload of the same save skips the preparation that +// changed nothing and goes to the battle; the TEACH that taught runs +// again, as the reload undid it. The save at the end empties the memory. +UnitTestResult test_once_per_save_retry(){ + BossLab lab; + StoryStep battle = make(StoryStepKind::BATTLE, "rival"); + battle.args = {{"may_lose", true}}; + lab.table.steps.back() = battle; + lab.executor.failures_left = {{"rival", 1}}; + Segment segment = lab.segment(); + SegmentHooks hooks = lab.hooks(); + RunState state; + const SegmentReport report = run_segment(SegmentRange{}, SegmentPolicy{}, segment, hooks, state); + if (!report.completed || report.reloads != 1 || lab.count("GAME teach_known") != 1 + || lab.count("GAME teach_new") != 2 || lab.count("BATTLE rival") != 2 + ){ + return std::format("Expected the known TEACH once, the new one twice, the battle twice:{}{}", joined(lab.executor.trace), joined(lab.lines)); + } + if (!lab.prepared.empty()){ + return "Expected the save to empty the prepared steps."; + } + return true; +} + +// Verify mode: three runs from one save; the preparation that changed +// nothing runs in the first only. +UnitTestResult test_once_per_save_verify(){ + BossLab lab; + StoryStep battle = make(StoryStepKind::BATTLE, "rival"); + battle.args = {{"may_lose", true}}; + lab.table.steps.back() = battle; + Segment segment = lab.segment(); + SegmentHooks hooks = lab.hooks(); + RunState state; + const VerifyReport report = verify_checkpoint("00.15b", VerifyPolicy{}, segment, hooks, state); + if (!report.verified || report.runs != 3 || lab.count("GAME teach_known") != 1 + || lab.count("GAME teach_new") != 3 || lab.count("BATTLE rival") != 3 + ){ + return std::format("Expected the known TEACH once in 3 runs, the new one each run:{}{}", joined(lab.executor.trace), joined(lab.lines)); + } + // Without the memory, every run prepares. + FakeExecutor plain; + plain.unchanged = {"teach_known"}; + Segment without; + without.id = "00"; + without.checkpoints.push_back(CheckpointSpec{ + .id = lab.table.id, .title = "", .saves = true, + .build = [&]{ return build_story_checkpoint(lab.table, plain); }, + }); + RunState again; + verify_checkpoint("00.15b", VerifyPolicy{}, without, hooks, again); + if (std::count(plain.trace.begin(), plain.trace.end(), "GAME teach_known") != 3){ + return std::format("Expected every run to prepare without PreparedSteps:{}", joined(plain.trace)); + } + return true; +} + + +// Two sections of a story, as BDSP has segments 00 and 01. +const std::vector& two_sections(){ + static const std::vector rows{ + StoryCheckpoint{.id = "00.01", .title = "Leave the house", .start = std::nullopt, .steps = {}}, + StoryCheckpoint{.id = "00.02", .title = "Walk to Sandgem Town", .start = std::nullopt, .steps = {}}, + StoryCheckpoint{.id = "01.01", .title = "Jubilife to Barry", .start = std::nullopt, .steps = {}}, + }; + return rows; +} + +const StringSelectDatabase& two_sections_database(){ + static const StringSelectDatabase database = []{ + std::vector labels; + for (const StoryCheckpoint& checkpoint : two_sections()){ + labels.push_back(story_checkpoint_label(checkpoint)); + } + return story_checkpoint_database(labels); + }(); + return database; +} + +// The dropdowns list the checkpoints as "id title", slugged by their index +// in the whole story, which is story_index() of a section's own index. +UnitTestResult test_checkpoint_dropdowns(){ + const StringSelectDatabase& database = two_sections_database(); + const std::vector expected{"00.01 Leave the house", "00.02 Walk to Sandgem Town", "01.01 Jubilife to Barry"}; + if (database.size() != expected.size()){ + return std::format("Expected 3 entries, got {}", database.size()); + } + for (size_t c = 0; c < expected.size(); c++){ + if (database[c].display_name != expected[c] || database[c].slug != std::to_string(c)){ + return std::format("Unexpected entry {}: {} {}", c, database[c].slug, database[c].display_name); + } + } + if (database[story_index(true, 0, 2)].display_name != "01.01 Jubilife to Barry"){ + return "Expected the second section's first entry at story_index(true, 0, 2)."; + } + if (story_checkpoint_label(StoryCheckpoint{.id = "00.09", .title = "Pewter Gym: Camper Liam, then Brock", .start = std::nullopt, .steps = {}}) + != "00.09 Pewter Gym: Camper Liam, then Brock" + ){ + return "Unexpected label."; + } + StoryRunOptions options(database, Gen8ToGen9Languages_Database()); + if (options.start_index() != 0 || options.end_index() != 2 || !options.check_validity().empty()){ + return "Expected the whole story by default."; + } + options.START_CHECKPOINT.set_by_index(2); + options.END_CHECKPOINT.set_by_index(1); + if (options.check_validity().empty()){ + return "Expected a start after the end to be refused."; + } + return true; +} + +// A segment's report in the shared AutoStory stats. +UnitTestResult test_story_stats(){ + SegmentReport report; + report.reloads = 2; + report.runs = { + 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_counts(report.story_counts(), stats); + if (stats.m_segment != 1 || stats.m_checkpoint != 2 || stats.m_reset != 2){ + return "Expected 1 segment, 2 checkpoints and 2 resets."; + } + return true; +} + +// The program's option group: 3 attempts, no stop, Thorough, by default; +// Fast when chosen. +UnitTestResult test_run_options(){ + StoryRunOptions options(two_sections_database(), Gen8ToGen9Languages_Database()); + const SegmentPolicy policy = options.policy(); + if (policy.attempts_per_checkpoint != 3 || options.check_level() != StoryCheckLevel::DEFAULT){ + return "Expected 3 attempts, no stop at the first failure, and Thorough checks by default."; + } + options.CHECKS.set(StoryCheckLevel::FAST); + if (options.check_level() != StoryCheckLevel::FAST){ + return "Expected Fast checks once chosen."; + } + // Every game language can be chosen, read or not. + if (options.language() != Language::English){ + return "Expected English by default."; + } + options.LANGUAGE.set(Language::Japanese); + if (options.language() != Language::Japanese || !options.check_validity().empty()){ + return "Expected Japanese to be chosen and valid, reader or not."; + } + return true; +} + +// Verify mode: off by default; 3 runs and 2 passes when on, for one +// checkpoint only, never needing more passes than runs. +UnitTestResult test_verify_options(){ + StoryRunOptions options(two_sections_database(), Gen8ToGen9Languages_Database()); + if (options.VERIFY.policy()){ + return "Expected verify mode off by default."; + } + options.VERIFY.set_enabled(true); + if (options.check_validity().empty()){ + return "Expected verify mode refused over more than one checkpoint."; + } + options.END_CHECKPOINT.set_by_index(options.start_index()); + const std::optional policy = options.VERIFY.policy(); + if (!options.check_validity().empty() || !policy || policy->runs != 3 || policy->passes_needed != 2){ + return std::format("Expected 3 runs and 2 passes on one checkpoint: {}", options.check_validity()); + } + options.VERIFY.RUNS.set(2); + options.VERIFY.PASSES.set(3); + if (options.check_validity().empty()){ + return "Expected more passes than runs refused."; + } + return true; +} + +UnitTestResult test_lint(){ + StoryStep no_target = make(StoryStepKind::ROUTE, "walk"); + StoryStep again = make(StoryStepKind::TALK, "walk"); + StoryStep bad_legs = make(StoryStepKind::LEGS, "legs"); + 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 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 action", + }; + const std::vector problems = lint_story_checkpoint(data); + if (problems != expected){ + return std::format("Unexpected lint:{}", joined(problems)); + } + if (!lint_story_checkpoint(lab_checkpoint()).empty()){ + return std::format("Expected the lab checkpoint to lint clean:{}", joined(lint_story_checkpoint(lab_checkpoint()))); + } + return true; +} + + +struct StoryStepInput{ + std::string name; + UnitTestResult (*test)(); +}; + +struct StoryStepExpectation{ + std::string_view description; +}; + +struct StoryStepTestCase{ + StoryStepInput input; + StoryStepExpectation expectation; +}; + +class Test_StoryStepExecutor : public UnitTest{ +public: + explicit Test_StoryStepExecutor(StoryStepTestCase scenario) + : UnitTest(std::format("Pokemon::StoryStepExecutor - {}", scenario.input.name)) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.input.test(); + } + +private: + StoryStepTestCase m_scenario; +}; + +const StoryStepTestCase STORY_STEP_CASES[] = { + { + .input = {.name = "steps run in table order", .test = test_events_in_table_order}, + .expectation = {.description = "executes story steps sequentially as defined in table"}, + }, + { + .input = {.name = "skip_if asks the executor", .test = test_skip_if}, + .expectation = {.description = "delegates skip condition check to executor"}, + }, + { + .input = {.name = "each step starts where the last left the player", .test = test_pose_propagation}, + .expectation = {.description = "propagates player pose across sequential step executions"}, + }, + { + .input = {.name = "a failure names its step", .test = test_failure_names_the_step}, + .expectation = {.description = "records failing step identifier on error"}, + }, + { + .input = {.name = "unsupported kinds and lost battles", .test = test_unsupported_and_lost_battles}, + .expectation = {.description = "flags unsupported step types and handles battle defeat"}, + }, + { + .input = {.name = "tables as a segment, with a reload", .test = test_segment_of_tables}, + .expectation = {.description = "converts step tables into segment with checkpoint reload support"}, + }, + { + .input = {.name = "lint", .test = test_lint}, + .expectation = {.description = "verifies lint validation rules on story checkpoints"}, + }, + { + .input = {.name = "the run options' defaults", .test = test_run_options}, + .expectation = {.description = "validates initial default story run option values"}, + }, + { + .input = {.name = "the run options' verify mode", .test = test_verify_options}, + .expectation = {.description = "configures verification mode options and passes count"}, + }, + { + .input = {.name = "start and end checkpoint dropdowns", .test = test_checkpoint_dropdowns}, + .expectation = {.description = "populates start and end dropdown selections correctly"}, + }, + { + .input = {.name = "a segment's run in the AutoStory stats", .test = test_story_stats}, + .expectation = {.description = "updates story run statistics following segment completion"}, + }, + { + .input = {.name = "policy: attempts per checkpoint, then fail", .test = test_policy_attempts_then_fail}, + .expectation = {.description = "enforces max checkpoint attempt policy before terminal failure"}, + }, + { + .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}, + .expectation = {.description = "skips steps that changed nothing during once per save retry"}, + }, + { + .input = {.name = "once per save: verify runs prepare once", .test = test_once_per_save_verify}, + .expectation = {.description = "executes once per save prepare step only once during verification"}, + }, +}; + +} // namespace + + +void add_tests_StoryStepExecutor(UnitTestDatabase& database){ + for (const auto& scenario : STORY_STEP_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.h new file mode 100644 index 0000000000..d2d6c053e5 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.h @@ -0,0 +1,23 @@ +/* Story Step Executor Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepExecutor_Tests_H +#define PokemonAutomation_Pokemon_StoryStepExecutor_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for high-level story step dispatching and table conversion. +void add_tests_StoryStepExecutor(UnitTestDatabase& database); + + + +} // 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..50cda4ade3 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp @@ -0,0 +1,143 @@ +/* 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 +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon_StoryActionArg.h" +#ifndef PA_STORY_DATA_STANDALONE +#include "Pokemon_StoryActionArg_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 std::format("expected error \"{}\", got \"{}\"", test.expectation.error, 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(std::format("Pokemon::StoryActionArg - {}", 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_StoryActionArg_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h new file mode 100644 index 0000000000..d20848c4c2 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h @@ -0,0 +1,23 @@ +/* Story Action Arg Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActionArg_Tests_H +#define PokemonAutomation_Pokemon_StoryActionArg_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for step args: checking them against an action's spec. +void add_tests_StoryActionArg(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#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..5839da93a0 --- /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() ? "" : std::format(" ({})", arg.why))); + } + } + return errors; +} + +StoryActionArgs with_fallbacks(const StoryActionSpec& spec, StoryActionArgs args){ + for (const StoryArgSpec& arg : spec.args){ + if (arg.fallback){ + args.try_emplace(arg.key, *arg.fallback); + } + } + return args; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h new file mode 100644 index 0000000000..729cb7799f --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h @@ -0,0 +1,52 @@ +/* Story Action Spec + * + * From: https://github.com/PokemonAutomation/ + * + * What an action declares: the kind of step it does, its name and the + * args it takes, with their types and fallbacks (Pokemon_StoryActionArg.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActionSpec_H +#define PokemonAutomation_Pokemon_StoryActionSpec_H + +#include +#include +#include +#include "Pokemon_StoryActionArg.h" +#include "Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// One argument an action takes. A missing optional one reads as `fallback` +// when it has one. +struct StoryArgSpec{ + std::string key; + StoryArgType type = StoryArgType::WORD; + bool required = false; + std::optional fallback; + // What it is for, shown in lint errors. + std::string why; +}; + +// An action: the kind of step it does, its name and the args it takes. +struct StoryActionSpec{ + StoryStepKind kind = StoryStepKind::GAME; + std::string name; + std::vector args; +}; + +// Each way `args` don't fit `spec`: a key it doesn't name, a value of +// another type, a required one missing. Empty when they fit. +std::vector story_args_errors(const StoryActionSpec& spec, const StoryActionArgs& args); + +// `args` with each missing optional arg of `spec` set to its fallback. +StoryActionArgs with_fallbacks(const StoryActionSpec& spec, StoryActionArgs args); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.cpp new file mode 100644 index 0000000000..aade2b3809 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.cpp @@ -0,0 +1,32 @@ +/* Story Checks + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryCheckLevel.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string story_check_level_name(StoryCheckLevel level){ + switch (level){ + case StoryCheckLevel::TESTING: + return "testing"; + case StoryCheckLevel::THOROUGH: + return "thorough"; + case StoryCheckLevel::DEFAULT: + return "default"; + case StoryCheckLevel::FAST: + return "fast"; + case StoryCheckLevel::SPEEDRUN: + return "speedrun"; + } + return "?"; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h new file mode 100644 index 0000000000..86de9f8c76 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h @@ -0,0 +1,43 @@ +/* Story Check Level + * + * From: https://github.com/PokemonAutomation/ + * + * How much a story step reads the screen to confirm what it did. The + * program's options choose it (StoryRunOptions); each game decides what + * its steps check at each level. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryCheckLevel_H +#define PokemonAutomation_Pokemon_StoryCheckLevel_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How much a step reads the screen to confirm what it did. +enum class StoryCheckLevel{ + // Everything THOROUGH checks, each checkpoint run 3 times by default to + // make sure it really passes. + TESTING, + // Check everything for the user: Bag items, Pokemon stats, + // preconditions. + THOROUGH, + // Assume most things are fine; check the most important ones. + DEFAULT, + // Minimal checks. + FAST, + // Almost no checks, to be as fast as possible. + SPEEDRUN, +}; + +// Returns the readable string representation of a story check level. +std::string story_check_level_name(StoryCheckLevel level); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h new file mode 100644 index 0000000000..1a4719017c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h @@ -0,0 +1,40 @@ +/* Story Checkpoint + * + * From: https://github.com/PokemonAutomation/ + * + * A checkpoint of a tile game's story table as plain data: where its save + * leaves the player and its steps in order. build_story_checkpoint() + * (Pokemon_StoryStepExecutor.h) turns it into engine events. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryCheckpoint_H +#define PokemonAutomation_Pokemon_StoryCheckpoint_H + +#include +#include +#include +#include "Pokemon_GridPose.h" +#include "Pokemon_StoryPostconditions.h" +#include "Pokemon_StoryStep.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Milestone row in the story table grouping related steps and starting pose. +struct StoryCheckpoint{ + std::string id; + std::string title; + // Where its starting save leaves the player; none for a new game. + std::optional start; + std::vector steps; + // What must hold when it is done; checked on its own after a run. + StoryPostconditions postconditions; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryPostconditions.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryPostconditions.h new file mode 100644 index 0000000000..5b3cd7df37 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryPostconditions.h @@ -0,0 +1,43 @@ +/* Story Postconditions + * + * From: https://github.com/PokemonAutomation/ + * + * What must hold once a checkpoint is done, as plain data from its plan: + * where the player stands, what the Bag holds, which story flags moved. + * check_postconditions() (Pokemon_StoryPostconditionCheck.h) checks them + * against what the game read, as a step of its own after the run. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryPostconditions_H +#define PokemonAutomation_Pokemon_StoryPostconditions_H + +#include +#include +#include +#include "Pokemon_GridPose.h" +#include "Pokemon_StoryActionArg.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The end state a checkpoint's plan promises: position, Bag items and flags. +struct StoryPostconditions{ + // Where the checkpoint ends; unset, it is the last step's target + // (checkpoint_end_pose()). + std::optional position; + // Each item's count in the Bag, exactly, by the game's item id + // ("LIFT_KEY", "RARE_CANDY"). + std::vector items; + // Story flags that must be set: a trainer beaten, a door open. + std::vector flags; + + bool operator==(const StoryPostconditions& other) const = default; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.cpp new file mode 100644 index 0000000000..7fbeebf500 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.cpp @@ -0,0 +1,43 @@ +/* Story Save Mode + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StorySaveMode.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string story_save_mode_name(StorySaveMode mode){ + switch (mode){ + case StorySaveMode::NONE: + return "none"; + case StorySaveMode::AFTER_VERIFICATION: + return "after_verification"; + case StorySaveMode::PER_CHECKPOINT: + return "per_checkpoint"; + } + return "?"; +} + +bool story_save_allowed(StorySaveMode mode, CheckpointVerdict verdict, SavePoint point){ + if (verdict != CheckpointVerdict::PASSED){ + return false; + } + switch (mode){ + case StorySaveMode::NONE: + return false; + case StorySaveMode::AFTER_VERIFICATION: + return point == SavePoint::RUN_END; + case StorySaveMode::PER_CHECKPOINT: + return true; + } + return false; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h new file mode 100644 index 0000000000..04ad331908 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h @@ -0,0 +1,59 @@ +/* Story Save Mode + * + * From: https://github.com/PokemonAutomation/ + * + * When an AutoStory run may save the game. A run's own verdict can be + * wrong (FRLG 00.31, 2026-11-10: a warp leg confirmed B3F while still on + * B4F), and a save made then overwrites the only good one. So a segment + * under test never saves, a verified one saves once at its end, and only + * a playthrough of verified segments saves at each checkpoint. + * + */ + +#ifndef PokemonAutomation_Pokemon_StorySaveMode_H +#define PokemonAutomation_Pokemon_StorySaveMode_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// When a run saves. A failed run never saves, in any mode. +enum class StorySaveMode{ + // Testing: never save; the save the run started from stays. + NONE, + // Verification: save once, at the end of a run that passed. + AFTER_VERIFICATION, + // Reproduction (a playthrough of verified segments): save at the end + // of each checkpoint that passed. + PER_CHECKPOINT, +}; + +// Returns the wire and log name of a save mode: "none", "after_verification", "per_checkpoint". +std::string story_save_mode_name(StorySaveMode mode); + +// How a checkpoint ended: passed (and its postconditions, where checked, +// did not fail) or not. +enum class CheckpointVerdict{ + PASSED, + FAILED, +}; + +// Where a save would be made. +enum class SavePoint{ + // A checkpoint's end, with more checkpoints of the run after it. + CHECKPOINT_END, + // The last checkpoint's end: the run's end state. + RUN_END, +}; + +// Whether a run in `mode` saves at `point` after a checkpoint that ended +// as `verdict`. +bool story_save_allowed(StorySaveMode mode, CheckpointVerdict verdict, SavePoint point); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h index ed034e6eed..1e782e6ed9 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h @@ -16,6 +16,7 @@ #include #include "Pokemon/AutoStory/Pokemon_AutoStoryStats.h" #include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "Pokemon_StorySaveMode.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -27,6 +28,10 @@ struct SegmentPolicy{ // 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; + // When the run saves. In the other modes no checkpoint after the first + // has a save at its start, so only the first is retried with a reload. + // The options' default is NONE; the engine's stays the playthrough's. + StorySaveMode save_mode = StorySaveMode::PER_CHECKPOINT; }; // The checkpoints to run, by id, both inclusive. An unset end is the diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h new file mode 100644 index 0000000000..26cd129bce --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h @@ -0,0 +1,60 @@ +/* Story Step + * + * From: https://github.com/PokemonAutomation/ + * + * One step of a tile game's story (FRLG, BDSP) as plain data: its kind, + * the action that does it and the action's args. A game's executor does it + * (Pokemon_StoryStepExecutor.h); the shared JSON reads and writes it + * (Data/Pokemon_StoryStepJson.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStep_H +#define PokemonAutomation_Pokemon_StoryStep_H + +#include +#include +#include +#include "Pokemon_GridPose.h" +#include "Pokemon_StoryActionArg.h" +#include "Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Specification of an atomic story task with actions and postconditions. +struct StoryStep{ + StoryStepKind kind = StoryStepKind::TALK; + std::string name; + std::string why; + + // How the step does its kind: one of the built-in actions + // (Pokemon_BuiltinStoryActions.h) or the game's own; for a GAME step, the + // game's action. Empty is the kind's default action. + std::string action; + // The arguments the action reads, parsed against its spec when the + // game loads the step, with the spec's fallbacks filled in. + StoryActionArgs args; + + // Skipped when all of these hold (and there is at least one): names + // the game's executor answers (StoryStepExecutor::holds()), run flags + // unless the game reads them off the screen. + std::vector skip_if; + // Preparation for what follows, done once per save: a TEACH, a check, + // a read. Once it has succeeded and changed nothing + // (Outcome::changed_nothing), the attempts after a reload of the same + // save skip it, so a retry goes from the reload straight to the + // battle. One that changed the game (a TM taught) runs again, as the + // reload undid it. Only with build_story_checkpoint()'s PreparedSteps. + bool once_per_save = false; + // Where the step leaves the player, when its action does not say: the + // end of a scene that moves the player. + std::optional pose_after; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp new file mode 100644 index 0000000000..28b755779b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp @@ -0,0 +1,52 @@ +/* Story Step Kind + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string story_step_kind_name(StoryStepKind kind){ + switch (kind){ + case StoryStepKind::NEW_GAME: + return "NEW_GAME"; + case StoryStepKind::OPTIONS: + return "OPTIONS"; + case StoryStepKind::ROUTE: + return "ROUTE"; + case StoryStepKind::LEGS: + return "LEGS"; + case StoryStepKind::STEP: + return "STEP"; + case StoryStepKind::TALK: + return "TALK"; + case StoryStepKind::ANSWER: + return "ANSWER"; + case StoryStepKind::MASH: + return "MASH"; + case StoryStepKind::BATTLE: + return "BATTLE"; + case StoryStepKind::TRAIN: + return "TRAIN"; + case StoryStepKind::HEAL: + return "HEAL"; + case StoryStepKind::SHOP: + return "SHOP"; + case StoryStepKind::SAVE: + return "SAVE"; + case StoryStepKind::READY: + return "READY"; + case StoryStepKind::GAME: + return "GAME"; + } + return "?"; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h new file mode 100644 index 0000000000..2e43aa8118 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h @@ -0,0 +1,45 @@ +/* Story Step Kind + * + * From: https://github.com/PokemonAutomation/ + * + * The kinds of story step the tile games (FRLG, BDSP) share. A game's + * executor does each kind its own way (Pokemon_StoryStepExecutor.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepKind_H +#define PokemonAutomation_Pokemon_StoryStepKind_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Action category classification for individual story steps. +enum class StoryStepKind{ + NEW_GAME, // title screen (no save) to the first room + OPTIONS, // the game's options as the story needs them + ROUTE, // plan and walk to `target` + LEGS, // walk `legs` as given + STEP, // one step `direction`: onto a trigger, into a door + TALK, // A at what the player faces + ANSWER, // text to a YES/NO, then `yes` + MASH, // text until the overworld is back: a scene + BATTLE, // text into a battle, fight it, text to the overworld + TRAIN, // fight `battles` wild battles where the player stands + HEAL, // the nurse, from in front of her or of the Center's door + SHOP, // `items` from a shop + SAVE, // save the game where the player stands + READY, // before a big battle: items, and the nurse at `target` if they can't + GAME, // a step only this game has, named by `variant` +}; + +// Returns the readable string representation of a story step kind. +std::string story_step_kind_name(StoryStepKind kind); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_GameLanguages.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_GameLanguages.cpp new file mode 100644 index 0000000000..42f0dadf08 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_GameLanguages.cpp @@ -0,0 +1,43 @@ +/* Game Languages + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_GameLanguages.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const EnumDropdownDatabase& Gen8ToGen9Languages_Database(){ + static const EnumDropdownDatabase database({ + {Language::English, "en", "English"}, + {Language::Japanese, "ja", "Japanese"}, + {Language::Spanish, "es", "Spanish"}, + {Language::French, "fr", "French"}, + {Language::German, "de", "German"}, + {Language::Italian, "it", "Italian"}, + {Language::Korean, "ko", "Korean"}, + {Language::ChineseSimplified, "zh-Hans", "Chinese (Simplified)"}, + {Language::ChineseTraditional, "zh-Hant", "Chinese (Traditional)"}, + }); + return database; +} + +const EnumDropdownDatabase& FireRedLeafGreenLanguages_Database(){ + static const EnumDropdownDatabase database({ + {Language::English, "en", "English"}, + {Language::Japanese, "ja", "Japanese"}, + {Language::Spanish, "es", "Spanish"}, + {Language::French, "fr", "French"}, + {Language::German, "de", "German"}, + {Language::Italian, "it", "Italian"}, + }); + return database; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_GameLanguages.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_GameLanguages.h new file mode 100644 index 0000000000..eec094dfaf --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_GameLanguages.h @@ -0,0 +1,35 @@ +/* Game Languages + * + * From: https://github.com/PokemonAutomation/ + * + * The languages each game can be played in, as dropdown databases for a + * program's language option. A program offers its game's set, so a user + * can't pick a language the game doesn't have. + * + */ + +#ifndef PokemonAutomation_Pokemon_GameLanguages_H +#define PokemonAutomation_Pokemon_GameLanguages_H + +#include "Common/Cpp/Options/EnumDropdownDatabase.h" +#include "CommonFramework/Language.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The nine languages of the Switch games of generations 8 and 9: Sword and +// Shield, Brilliant Diamond and Shining Pearl, Legends: Arceus, Scarlet and +// Violet, Legends: Z-A. Japanese, English, French, Italian, German, +// Spanish, Korean, Chinese (Simplified and Traditional). +const EnumDropdownDatabase& Gen8ToGen9Languages_Database(); + +// The six languages of FireRed and LeafGreen: Japanese, English, French, +// Italian, German, Spanish. +const EnumDropdownDatabase& FireRedLeafGreenLanguages_Database(); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp new file mode 100644 index 0000000000..5834a024a4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp @@ -0,0 +1,162 @@ +/* Story Run Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryRunOptions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const EnumDropdownDatabase& StoryCheckLevel_Database(){ + static const EnumDropdownDatabase database({ + {StoryCheckLevel::TESTING, "testing", "Testing: run each checkpoint 3 times to be sure it really passes"}, + {StoryCheckLevel::THOROUGH, "thorough", "Thorough: check everything for the user (Bag items, Pok\u00e9mon stats, preconditions)"}, + {StoryCheckLevel::DEFAULT, "default", "Default: check the most important things, assume the rest is fine"}, + {StoryCheckLevel::FAST, "fast", "Fast: minimal checks"}, + {StoryCheckLevel::SPEEDRUN, "speedrun", "Speedrun: almost no checks, as fast as possible"}, + }); + return database; +} + + +const EnumDropdownDatabase& StorySaveMode_Database(){ + static const EnumDropdownDatabase database({ + {StorySaveMode::NONE, "none", "None: never save (testing a checkpoint; the start save stays)"}, + {StorySaveMode::AFTER_VERIFICATION, "after_verification", "After verification: save once, at the end of a run that passed"}, + {StorySaveMode::PER_CHECKPOINT, "per_checkpoint", "Each checkpoint: save after each checkpoint that passed (a playthrough)"}, + }); + return database; +} + + +std::string story_checkpoint_label(const StoryCheckpoint& checkpoint){ + return checkpoint.title.empty() ? checkpoint.id : std::format("{} {}", checkpoint.id, checkpoint.title); +} + + + +StoryVerifyOptions::StoryVerifyOptions() + : GroupOption( + "Verify Mode: run the start checkpoint (also the end) from its save several times, never saving at its end", + LockMode::LOCK_WHILE_RUNNING, + EnableMode::DEFAULT_DISABLED + ) + , RUNS( + "Runs:
Runs of the checkpoint, each from its save.", + LockMode::LOCK_WHILE_RUNNING, + 3, 1, 20 + ) + , PASSES( + "Passes needed:
Runs that must pass for the checkpoint to be verified.", + LockMode::LOCK_WHILE_RUNNING, + 2, 1, 20 + ) +{ + PA_ADD_OPTION(RUNS); + PA_ADD_OPTION(PASSES); +} + +std::optional StoryVerifyOptions::policy() const{ + if (!enabled()){ + return std::nullopt; + } + return VerifyPolicy{.runs = RUNS, .passes_needed = PASSES}; +} + +std::string StoryVerifyOptions::check_validity() const{ + if (enabled() && PASSES > RUNS){ + return "Verify mode can't need more passes than it has runs."; + } + return GroupOption::check_validity(); +} + + +StoryRunOptions::StoryRunOptions(const StringSelectDatabase& checkpoints, const EnumDropdownDatabase& languages) + : StoryRangeOptions("Story Run", checkpoints) + , ATTEMPTS_PER_CHECKPOINT( + "Attempts per checkpoint:
A failed checkpoint reloads its save and runs again, up to this many times in all. " + "1 stops at the first failure, leaving the game where it failed.", + LockMode::LOCK_WHILE_RUNNING, + 3, 1, 20 + ) + , CHECKS( + "Checks:
How much each step reads the screen to confirm what it did, from Testing (the most) to Speedrun (almost none).", + StoryCheckLevel_Database(), + LockMode::LOCK_WHILE_RUNNING, + StoryCheckLevel::DEFAULT + ) + , LANGUAGE( + "Game language:
For the few reads that need text (item names in a shop or the Bag). " + "Story steps never match dialogue text; with no reader for this language they check positions, digits and the screen instead.", + languages, + LockMode::LOCK_WHILE_RUNNING, + Language::English + ) + , SAVE_MODE( + "Save:
When the run saves the game. A failed run never saves. " + "None keeps the save the run started from; After verification saves once at the end, after the checkpoint " + "passed 2-3 times; Each checkpoint is for a playthrough of verified checkpoints.", + StorySaveMode_Database(), + LockMode::LOCK_WHILE_RUNNING, + StorySaveMode::NONE + ) + , POSTCONDITIONS_ONLY( + "Check postconditions only:
Run nothing: read where the game stands and check the end checkpoint's " + "position, items and flags. What the game can't read yet is reported as not checked.", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(ATTEMPTS_PER_CHECKPOINT); + PA_ADD_OPTION(CHECKS); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(VERIFY); + PA_ADD_OPTION(SAVE_MODE); + PA_ADD_OPTION(POSTCONDITIONS_ONLY); +} + +std::string StoryRunOptions::check_validity() const{ + std::string error = StoryRangeOptions::check_validity(); + if (!error.empty()){ + return error; + } + if (VERIFY.enabled() && start_index() != end_index()){ + return "Verify mode runs one checkpoint: set the end checkpoint to the start checkpoint."; + } + if (VERIFY.enabled() && POSTCONDITIONS_ONLY){ + return "Check postconditions only runs nothing: turn off Verify Mode."; + } + return error; +} + +SegmentPolicy StoryRunOptions::policy() const{ + SegmentPolicy policy; + policy.attempts_per_checkpoint = ATTEMPTS_PER_CHECKPOINT; + policy.save_mode = SAVE_MODE; + return policy; +} + +std::optional StoryRunOptions::verify_policy() const{ + std::optional policy = VERIFY.policy(); + if (policy){ + policy->save_mode = SAVE_MODE; + } + return policy; +} + +StoryCheckLevel StoryRunOptions::check_level() const{ + return CHECKS; +} + +Language StoryRunOptions::language() const{ + return LANGUAGE; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h new file mode 100644 index 0000000000..43e979cbf8 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h @@ -0,0 +1,104 @@ +/* Story Run Options + * + * From: https://github.com/PokemonAutomation/ + * + * The options every AutoStory program shows for where to start and end, how + * hard to try and how much to check: the shared range group + * (Pokemon_StoryRangeOptions.h) plus the run policy, read into the shared + * SegmentPolicy (Pokemon/AutoStory/Pokemon_StorySegments.h), the checks + * level (Types/Pokemon_StoryCheckLevel.h), the language the game's steps + * read text in, when the run saves (Types/Pokemon_StorySaveMode.h) and + * whether it only checks postconditions. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRunOptions_H +#define PokemonAutomation_Pokemon_StoryRunOptions_H + +#include +#include +#include +#include +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Language.h" +#include "CommonTools/Options/StringSelectOption.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" +#include "Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h" +#include "Pokemon_StoryRangeOptions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A checkpoint's label in the start and end dropdowns, as SV labels its +// segments: "00.09 Pewter Gym: Camper Liam, then Brock". The labels of a +// story's checkpoints, in order, make its dropdowns +// (story_checkpoint_database()). +std::string story_checkpoint_label(const StoryCheckpoint& checkpoint); + + +// Verify mode, off by default (verify_checkpoint()): the start checkpoint +// RUNS times from its save, never saving at its end; verified when at +// least PASSES pass. For a battle that has lost twice or more, given its +// own checkpoint saved right before it. +class StoryVerifyOptions : public GroupOption{ +public: + StoryVerifyOptions(); + + // The runs and passes, unset when verify mode is off. + std::optional policy() const; + virtual std::string check_validity() const override; + +public: + SimpleIntegerOption RUNS; + SimpleIntegerOption PASSES; +}; + + +// The range group (START_CHECKPOINT, END_CHECKPOINT, start_index(), +// end_index()) with the run policy added to the same group, so the saved +// settings keep one flat object. +class StoryRunOptions : public StoryRangeOptions{ +public: + // `checkpoints`: story_checkpoint_database() of the game's story, kept + // alive by the caller; the dropdowns start on its first and last. + // `languages`: the ones the game has (Pokemon_GameLanguages.h). + StoryRunOptions(const StringSelectDatabase& checkpoints, const EnumDropdownDatabase& languages); + + // The range's check, then verify mode's: one checkpoint only. + virtual std::string check_validity() const override; + + // The policy these options set, with the save mode. + SegmentPolicy policy() const; + // Verify mode's runs and passes with the save mode; unset when off. + std::optional verify_policy() const; + // The checks level, for the game's steps to read. + StoryCheckLevel check_level() const; + // The game's language, for the steps that read text. + Language language() const; + +public: + SimpleIntegerOption ATTEMPTS_PER_CHECKPOINT; + EnumDropdownOption CHECKS; + // Any language the game has, whether or not a reader supports it: + // steps without one use language-free checks, so none is refused. + EnumDropdownOption LANGUAGE; + // On, it runs one checkpoint: the start, which must also be the end. + StoryVerifyOptions VERIFY; + // When the run saves; NONE (testing) by default. + EnumDropdownOption SAVE_MODE; + // On, nothing runs: the game reads where it stands and checks the end + // checkpoint's postconditions (Pokemon_StoryPostconditionCheck.h). + BooleanCheckBoxOption POSTCONDITIONS_ONLY; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index e06d5849d5..df0b993bbf 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1482,6 +1482,8 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Options/Pokemon_BoxSortingTable.cpp Source/Pokemon/Options/Pokemon_BoxSortingTable.h Source/Pokemon/Options/Pokemon_EncounterBotOptions.h + Source/Pokemon/Options/Pokemon_GameLanguages.cpp + Source/Pokemon/Options/Pokemon_GameLanguages.h Source/Pokemon/Options/Pokemon_HomeSpriteSelectOption.cpp Source/Pokemon/Options/Pokemon_HomeSpriteSelectOption.h Source/Pokemon/Options/Pokemon_IvJudgeOption.cpp @@ -1496,17 +1498,30 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Options/Pokemon_StoryRangeOptions.h Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.h + Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp + Source/Pokemon/Options/Pokemon_StoryRunOptions.h + Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp + Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h + Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp + Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.h + Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp + Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h + Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp + Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h Source/Pokemon/AutoStory/Pokemon_AutoStorySelect.h Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.cpp Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.h Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h + Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.cpp + Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.cpp Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.h Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.h + Source/Pokemon/AutoStory/Pokemon_MapUtil.h Source/Pokemon/AutoStory/Pokemon_StoryCheckpointTypes.h Source/Pokemon/AutoStory/Pokemon_StoryEvent.h Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp @@ -1519,16 +1534,40 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.h Source/Pokemon/AutoStory/Pokemon_StoryOutcome.h Source/Pokemon/AutoStory/Pokemon_StoryPose.h + Source/Pokemon/AutoStory/Pokemon_StoryPostconditionCheck.cpp + Source/Pokemon/AutoStory/Pokemon_StoryPostconditionCheck.h Source/Pokemon/AutoStory/Pokemon_StoryRunCounts_Tests.cpp Source/Pokemon/AutoStory/Pokemon_StoryRunCounts_Tests.h + Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.h Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp Source/Pokemon/AutoStory/Pokemon_StorySegments.h Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp + Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h + Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.h Source/Pokemon/AutoStory/Pokemon_TilePose.cpp Source/Pokemon/AutoStory/Pokemon_TilePose.h + Source/Pokemon/AutoStory/Types/Pokemon_GridPose.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryPostconditions.h + Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.cpp Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h Source/Pokemon/Pokemon_AdvRng.cpp Source/Pokemon/Pokemon_AdvRng.h Source/Pokemon/Pokemon_BdspRng.cpp diff --git a/devtools/story-data-tests/CMakeLists.txt b/devtools/story-data-tests/CMakeLists.txt new file mode 100644 index 0000000000..d4ffa63f0a --- /dev/null +++ b/devtools/story-data-tests/CMakeLists.txt @@ -0,0 +1,51 @@ +# Offline codec checks, no Qt application or controller initialization: +# cmake -S devtools/story-data-tests -B build/story-data-tests +# cmake --build build/story-data-tests -j4 +# ctest --test-dir build/story-data-tests --output-on-failure +cmake_minimum_required(VERSION 3.24) +project(StoryDataTests LANGUAGES CXX) +enable_testing() +get_filename_component(ROOT "../.." ABSOLUTE) +set(STORY "${ROOT}/SerialPrograms/Source/Pokemon/AutoStory") +add_executable(StoryDataTests + "${STORY}/Data/Pokemon_StoryStepJson.cpp" + "${STORY}/Data/Pokemon_StoryStepJson_Tests.cpp" + "${STORY}/Pokemon_BuiltinStoryActions.cpp" + "${STORY}/Types/Pokemon_StoryActionArg.cpp" + "${STORY}/Types/Pokemon_StoryActionSpec.cpp" + "${ROOT}/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.cpp" + "${ROOT}/Common/Cpp/Exceptions.cpp" + "${ROOT}/Common/Cpp/Json/JsonValue.cpp" + "${ROOT}/Common/Cpp/Json/JsonObject.cpp" + "${ROOT}/Common/Cpp/Json/JsonArray.cpp" + "${ROOT}/Common/Cpp/Json/JsonTools.cpp" + "${ROOT}/Common/Cpp/Filesystem/FileIO.cpp" + "${ROOT}/Common/Cpp/Filesystem/FilePath.cpp" + "${ROOT}/Common/Cpp/Strings/Unicode.cpp") +# Reuse the Qt/controller-free support sources; each codec has its own test main. +get_target_property(STORY_DATA_SOURCES StoryDataTests SOURCES) +list(REMOVE_ITEM STORY_DATA_SOURCES "${STORY}/Data/Pokemon_StoryStepJson_Tests.cpp") +add_executable(AuthoredCheckpointTests ${STORY_DATA_SOURCES} + "${STORY}/Data/Pokemon_AuthoredCheckpointJson.cpp" + "${STORY}/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp") +add_executable(StoryActionArgTests + "${STORY}/Types/Pokemon_StoryActionArg.cpp" + "${STORY}/Types/Pokemon_StoryActionSpec.cpp" + "${STORY}/Types/Pokemon_StoryActionArg_Tests.cpp" + "${ROOT}/Common/Cpp/Exceptions.cpp") + +foreach(TEST_TARGET IN ITEMS StoryDataTests AuthoredCheckpointTests StoryActionArgTests) +target_include_directories(${TEST_TARGET} PRIVATE "${ROOT}" "${ROOT}/SerialPrograms/Source") +target_compile_features(${TEST_TARGET} PRIVATE cxx_std_23) +target_compile_definitions(${TEST_TARGET} PRIVATE PA_STORY_DATA_STANDALONE) +if(MSVC) + target_compile_definitions(${TEST_TARGET} PRIVATE _CRT_SECURE_NO_WARNINGS) + target_compile_options(${TEST_TARGET} PRIVATE /W4 /WX) + set_property(SOURCE "${ROOT}/Common/Cpp/Filesystem/FileIO.cpp" APPEND PROPERTY COMPILE_OPTIONS /wd4505) +else() + target_compile_options(${TEST_TARGET} PRIVATE -Wall -Wextra -Werror) +endif() +endforeach() +add_test(NAME StoryData COMMAND StoryDataTests) +add_test(NAME AuthoredCheckpoint COMMAND AuthoredCheckpointTests) +add_test(NAME StoryActionArg COMMAND StoryActionArgTests) diff --git a/devtools/story-data-tests/README.md b/devtools/story-data-tests/README.md new file mode 100644 index 0000000000..a2081dc492 --- /dev/null +++ b/devtools/story-data-tests/README.md @@ -0,0 +1,39 @@ +# Shared story-record codec tests + +Run without Qt, controllers, profiles or game saves: + +```sh +cmake -S devtools/story-data-tests -B build/story-data-tests +cmake --build build/story-data-tests -j4 +ctest --test-dir build/story-data-tests --output-on-failure +``` + +For a multi-configuration generator, add `--config Debug` to the build, +`-C Debug` to CTest and use `build/story-data-tests/Debug/StoryDataTests.exe`. +The same native cases are registered in the application's unit-test runner. + +`Pokemon_StoryStepJson` encodes and reads the common `StoryCheckpoint`, +`StoryStep` and `GridPose` records. It keeps action order, alternative tiles +and absent facing, and fills arg fallbacks. Unknown fields, kinds, actions and +args, invalid primitive types and missing required args fail. Encoding does not +establish semantic route validity. + +The portable workflow checks the Python reader against the synthetic +conformance cases at +[PokemonSimulation revision 866613f](https://github.com/dayfine/PokemonSimulation/tree/866613fa03e5c4a5eb7e57c91b59fafb44fc7ee3/data/story). +Those cases still use the older pose and per-kind step fields, so the native +reader, which reads steps as an action plus typed args, no longer runs them. +This fixture revision is a contract-test dependency, not an approved +map-resource revision. + +See the [shared checkpoint contract](https://github.com/dayfine/PokemonSimulation/blob/866613fa03e5c4a5eb7e57c91b59fafb44fc7ee3/docs/story/CHECKPOINT_CONTRACT.md) +for the field boundary and proposed common requirements, state, save/retry and +handoff envelope. Both games can use those policies; their menu/detector/action +bindings remain game specific. + +These are synthetic codec tests, not exports of either game's authored story +tables or captured controller replay. Evaluated FRLG/BDSP table exporters, +policy/state envelope binding and execution parity remain subsequent work. +No gameplay behavior changes here. + +The same CTest command also runs `AuthoredCheckpointTests`: shared authored-envelope parsing/writing and embedded-resource lookup for FRLG, BDSP, and opaque future game settings. Game adapters must validate their own execution object before running anything. The shared codec does not interpret FRLG menus, BDSP save-card policy, native bookkeeping, or controller evidence. diff --git a/docs/design/AutoStory.md b/docs/design/AutoStory.md index d14601e42e..4e5d1eb607 100644 --- a/docs/design/AutoStory.md +++ b/docs/design/AutoStory.md @@ -885,3 +885,48 @@ among the agents is recorded outside this doc. trade-back, or a levelled Pokémon brought in from another save. Optional trades the game itself offers (e.g. the Vermilion Farfetch'd) are allowed only behind an option. + +## 10. Step arguments (user, 2026-11-09) + +A story step's `variant` used to carry its action's arguments as free text, +for example `"mart CeruleanCity_Mart budget=1500 floor=1500 potion=3 +awakening=2"`. Each action parsed its own words, so a typo or a missing +argument showed up only when the step ran, and the Python reader in +PokemonSimulation had to copy every action's parser to read a plan. + +Now `variant` is only the action's name, the key it is registered under in a +game's action table. Its arguments move to `args`, a JSON object on the step +whose values are flags, whole numbers or words (`StoryStep::args`, +`Types/Pokemon_StoryArgs.h`). Each action declares the arguments it takes, +with a type and whether each one is required (`StoryArgSpec`). A game checks +every step's `args` against those specs when it loads the plan, so an +unknown key, a word where a number belongs or a missing budget fails at +load. Items to buy stay in the step's `items` list and are not repeated in +`args`. The shared JSON codec reads and writes `args` without knowing any +action, and omits it when it is empty. + +During the migration, a plan may still carry an old variant string. +`split_legacy_variant()` turns it into a name and args: the leading plain +words take the action's positional keys (a Mart's `map`), `key=value` +words become numbers when they are all digits and words otherwise, and any +remaining plain word becomes a flag (`if_present`). The word helpers in +`Pokemon_StoryVariant.h` are deprecated and will be removed once no action +reads them. + +The actions that take arguments today, all FRLG (BDSP's are listed for a +later change): + +| Action | Arguments | Notes | +|---|---|---| +| `mart` | `map` word, required; `budget` number, required; `floor` number | What to buy goes in `items`. | +| `teach` | `item` word (`tm03`, `hm01`, `tutor`), `move` word, `slot` number, all required; `forget` word | | +| `pc` | `op` word (`deposit`), `slot` number, `box` number, all required; `if_present` flag | | +| `grind`, `grind_check` | `slot`, `level`, `encounters` numbers and `pace` word, required; `heal_every`, `chance` numbers; `beat` word | `grind_check` takes the same arguments. | +| `capture` | `species` word, `catches`, `encounters`, `balls` numbers, all required; `pace` word | | +| `level` | `slot`, `min` numbers, required | Built in C++, not in a plan. | +| `fossil` | `fossil` word (`helix`, `dome`), required | | +| `use_item` | `item` word, required; `slot` number | 00.30 onwards. | +| `lift_floor` | `from`, `to` words, required | 00.30 onwards. | + +Plain names such as `run`, `trainer_line`, `cut_tree` and `bike` take no +arguments and stay as they are.