From 3ed042abf1f8648cb9b40d03a8da7939179fd58c Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 00:14:43 -0800 Subject: [PATCH 1/3] AutoStory: the tile-game step executor and the story JSON readers --- .../AutoStory/Data/Pokemon_StoryStepJson.cpp | 384 +++++++++++++++ .../AutoStory/Data/Pokemon_StoryStepJson.h | 60 +++ .../Data/Pokemon_StoryStepJson_Tests.cpp | 295 ++++++++++++ .../Data/Pokemon_StoryStepJson_Tests.h | 30 ++ .../AutoStory/Pokemon_AutoStory_Tests.h | 4 + .../AutoStory/Pokemon_StoryStepExecutor.cpp | 181 +++++++ .../AutoStory/Pokemon_StoryStepExecutor.h | 132 +++++ .../Pokemon_StoryStepExecutor_Tests.cpp | 451 ++++++++++++++++++ .../Pokemon_StoryStepExecutor_Tests.h | 23 + SerialPrograms/cmake/SourceFiles.cmake | 8 + 10 files changed, 1568 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.h 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..095cbd5014 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp @@ -0,0 +1,384 @@ +/* Story Step JSON + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#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)); +} + +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; +} + +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; +} + +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; +} + +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; +} + +std::vector> read_integer_rows(const JsonValue& value, std::string_view source){ + std::vector> result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + std::vector row; + for (const JsonValue& number : item.to_array_throw(std::string(source))){ + row.push_back(number.to_integer_throw(std::string(source))); + } + result.push_back(std::move(row)); + } + return result; +} + +std::vector read_timed_legs(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 timed leg is [turn degrees, ms]", source)); + } + result.push_back({.turn = integer(pair[0], source), .ms = integer(pair[1], source)}); + } + 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 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); + case StoryArgType::INTEGER_ROWS: + return read_integer_rows(value, source); + case StoryArgType::TIMED_LEGS: + return read_timed_legs(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)); +} + + +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; +} + + +StoryVerification read_verification(const JsonValue& value, std::string_view source){ + const JsonObject& root = fields(value, {"steps_hash", "build", "date", "runs"}, source); + StoryVerification result; + result.steps_hash = root.get_string_throw("steps_hash"); + if (const JsonValue* field = root.get_value("build")){ + result.build = field->to_string_throw(); + } + if (const JsonValue* field = root.get_value("date")){ + result.date = field->to_string_throw(); + } + if (const JsonValue* field = root.get_value("runs")){ + result.runs = field->to_string_throw(); + } + return result; +} + +// Reads "metadata" into `checkpoint`. A missing phase is testing. +void read_metadata(const JsonValue& value, std::string_view source, StoryCheckpoint& checkpoint){ + const JsonObject& root = fields(value, {"phase", "verified", "source", "postconditions"}, source); + if (const JsonValue* field = root.get_value("phase")){ + const std::string name = field->to_string_throw(); + const std::optional phase = read_story_phase(name); + if (!phase){ + throw ParseException(std::format("{}: unknown phase {}", source, name)); + } + checkpoint.metadata.phase = *phase; + } + if (const JsonValue* field = root.get_value("verified")){ + checkpoint.metadata.verified = read_verification(*field, source); + } + if (const JsonValue* field = root.get_value("source")){ + checkpoint.metadata.source = field->to_string_throw(); + } + if (const JsonValue* field = root.get_value("postconditions")){ + checkpoint.postconditions = read_postconditions(*field, source); + } +} + + +} // namespace + + +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"); + // None: any tile of the map, or a game with no tiles (a zone). + if (const JsonValue* field = root.get_value("tiles")){ + result.tiles = read_tiles(*field, source); + } + if (const JsonValue* field = root.get_value("facing")){ + result.facing = read_enum(DIRECTIONS, field->to_string_throw(), source); + } + return result; +} + +DeclaredPose read_declared_pose(const JsonValue& value, std::string_view source){ + const JsonObject& root = value.to_object_throw(std::string(source)); + const bool tile = root.get_value("map") != nullptr; + const bool zone = root.get_value("place") != nullptr; + if (tile == zone){ + throw ParseException(std::format("{}: a declared pose has a \"map\" (tiles) or a \"place\" (a zone), not {}", source, tile ? "both" : "neither")); + } + if (tile){ + GridPose grid = read_grid_pose(value, source); + return TileDeclared{.map = std::move(grid.map), .tiles = std::move(grid.tiles), .facing = grid.facing}; + } + fields(value, {"place", "spot", "heading"}, source); + ZoneDeclared result; + result.place = root.get_string_throw("place"); + if (const JsonValue* field = root.get_value("spot")){ + result.spot = field->to_string_throw(std::string(source)); + } + if (const JsonValue* field = root.get_value("heading")){ + result.heading = integer(*field, source); + } + 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", "once_per_save"}, 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_declared_pose(*field, source); + } + if (const JsonValue* field = root.get_value("once_per_save")){ + result.once_per_save = field->to_boolean_throw(std::string(source)); + } + 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", "metadata"}, 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_declared_pose(*start, source); + } + std::set names; + result.steps_json = root.get_value_throw("events").dump(-1); + 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* metadata = root.get_value("metadata")){ + read_metadata(*metadata, source, result); + } + 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..a67f5df31c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h @@ -0,0 +1,60 @@ +/* Story Step JSON + * + * From: https://github.com/PokemonAutomation/ + * + * Readers of the shared JSON wire form of the story data types (Types/): + * poses, steps and checkpoints, read strictly. 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{ + + +// Read a grid pose, {"map": "PalletTown", "tiles": [[3, 4]], "facing": "north"}; +// malformed and unknown fields fail. No "tiles" reads +// as none (any tile, or a game with no tiles). +GridPose read_grid_pose(const JsonValue& value, std::string_view source); + +// Read a declared pose (a checkpoint's "start", a step's "declared_after"): +// a tile one as a grid pose, {"map": ..., "tiles": [[x, y]], "facing": ...}, +// or a zone one, {"place": "LumioseCity", "spot": "HotelZ", "heading": 90} +// (spot and heading optional). One with both or neither of "map" and "place", +// and malformed or unknown fields, fail. +DeclaredPose read_declared_pose(const JsonValue& value, std::string_view source); + + +// 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() +); + + +// Read the common checkpoint, its steps read as read_story_step() does. +// Its steps_json keeps the "events" array as read, dumped compactly. +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..296b300744 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp @@ -0,0 +1,295 @@ +/* Story Step JSON Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Each case reads a record from JSON: accepted cases check the values + * read, rejected cases check that the read fails. The standalone + * StoryDataTests also checks PokemonSimulation's shared case file when given + * its path (devtools/story-data-tests/StoryWireCases.h). + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h" +#include "Pokemon/Navigation/Pokemon_Direction.h" +#include "Pokemon_StoryStepJson.h" +#include "Pokemon_StoryStepJson_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// Which record a case reads. +enum class Record{ + POSE, + DECLARED, + STEP, + CHECKPOINT, +}; + +// What a read gives. +using ReadRecord = std::variant; + +// "" when the record read is as expected, else what differs. +using ReadCheck = std::string (*)(const ReadRecord& record); + +struct WireCase{ + // A record to read, and which kind it is. + std::string_view name; + struct Input{ + Record record = Record::STEP; + std::string_view json; + }; + + // What reading it gives: a record the check accepts, or a rejection. + struct Expectation{ + ReadCheck check = nullptr; + bool rejected = false; + }; + + Input input; + Expectation expectation; +}; + +std::string expect(bool ok, std::string_view what){ + return ok ? "" : std::format("Expected {}.", what); +} + +const StoryStep& step_of(const ReadRecord& record){ + return std::get(record); +} + +const WireCase CASES[] = { + {.name = "no args", .input = {.json = R"({"id":"talk","kind":"talk"})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryStep& step = step_of(record); + return expect(step.name == "talk" && step.kind == StoryStepKind::TALK && step.args.empty() && !step.pose_after, "a bare talk step"); + }}}, + {.name = "all shared fields", .input = {.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 = {.check = [](const ReadRecord& record){ + const StoryStep& step = step_of(record); + const DeclaredPose after = TileDeclared{.map = "B", .tiles = {{0, 0}, {1, 0}}, .facing = Direction::EAST}; + return expect(step.kind == StoryStepKind::GAME && step.why == "source reason" && step.action == "profile" + && step.skip_if == std::vector{"flag"} && step.pose_after == after, "every shared field read"); + }}}, + {.name = "once per save", .input = {.json = R"({"id":"heal","kind":"game_action","action":"profile","once_per_save":true})"}, .expectation = {.check = [](const ReadRecord& record){ + return expect(step_of(record).once_per_save, "a once_per_save step"); + }}}, + {.name = "every time by default", .input = {.json = R"({"id":"heal","kind":"game_action","action":"profile"})"}, .expectation = {.check = [](const ReadRecord& record){ + return expect(!step_of(record).once_per_save, "a step run every time"); + }}}, + {.name = "route fills its fallback", .input = {.json = R"({"id":"r","kind":"route","args":{"target":{"map":"A","tiles":[[1,2]]}}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"fight_wild", false}, {"target", GridPose{.map = "A", .tiles = {{1, 2}}, .facing = std::nullopt}}}; + return expect(step_of(record).args == expected, "the target and fight_wild false"); + }}}, + {.name = "legs", .input = {.json = R"({"id":"l","kind":"legs","action":"legs","args":{"legs":[{"direction":"south","tiles":2}],"fight_wild":true}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"fight_wild", true}, {"legs", std::vector{{.direction = Direction::SOUTH, .tiles = 2}}}}; + return expect(step_of(record).args == expected, "one south leg of 2 tiles"); + }}}, + {.name = "direction", .input = {.json = R"({"id":"s","kind":"step","args":{"direction":"west"}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"direction", Direction::WEST}}; + return expect(step_of(record).args == expected, "direction west"); + }}}, + {.name = "items", .input = {.json = R"({"id":"s","kind":"shop","args":{"items":[{"item":"potion","quantity":5}]}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"items", std::vector{{.item = "potion", .quantity = 5}}}}; + return expect(step_of(record).args == expected, "5 potions"); + }}}, + {.name = "game args", .input = {.json = R"({"id":"buy","kind":"game_action","action":"mart","args":{"map":"CeruleanCity_Mart","budget":3000,"if_present":true}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"budget", int64_t(3000)}, {"if_present", true}, {"map", std::string("CeruleanCity_Mart")}}; + return expect(step_of(record).args == expected, "the Mart args"); + }}}, + {.name = "game words", .input = {.json = R"({"id":"buy","kind":"game_action","action":"mart","args":{"map":"M","budget":1,"skip":["a","b"]}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"budget", int64_t(1)}, {"if_present", false}, {"map", std::string("M")}, {"skip", std::vector{"a", "b"}}}; + return expect(step_of(record).args == expected, "the words and if_present false"); + }}}, + {.name = "game integer rows", .input = {.json = R"({"id":"w","kind":"game_action","action":"walk","args":{"legs":[[0,4500],[-90,0],[]]}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"legs", std::vector>{{0, 4500}, {-90, 0}, {}}}}; + return expect(step_of(record).args == expected, "three rows, the last empty"); + }}}, + {.name = "timed legs", .input = {.json = R"({"id":"w","kind":"game_action","action":"timed_walk","args":{"legs":[[0,4500],[-90,1200]]}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"legs", std::vector{{.turn = 0, .ms = 4500}, {.turn = -90, .ms = 1200}}}}; + return expect(step_of(record).args == expected, "two timed legs"); + }}}, + {.name = "unknown facing stays absent", .input = {.record = Record::POSE, .json = R"({"map":"M","tiles":[[0,0]]})"}, .expectation = {.check = [](const ReadRecord& record){ + return expect(std::get(record) == GridPose{.map = "M", .tiles = {{0, 0}}, .facing = std::nullopt}, "one tile, no facing"); + }}}, + {.name = "no tiles", .input = {.record = Record::POSE, .json = R"({"map":"M","tiles":[]})"}, .expectation = {.check = [](const ReadRecord& record){ + return expect(std::get(record).tiles.empty(), "no tiles"); + }}}, + {.name = "declared tile pose", .input = {.record = Record::DECLARED, .json = R"({"map":"M","tiles":[[1,2]],"facing":"north"})"}, .expectation = {.check = [](const ReadRecord& record){ + const DeclaredPose expected = TileDeclared{.map = "M", .tiles = {{1, 2}}, .facing = Direction::NORTH}; + return expect(std::get(record) == expected, "a tile pose facing north"); + }}}, + {.name = "declared place", .input = {.record = Record::DECLARED, .json = R"({"place":"LumioseCity","spot":"HotelZ","heading":90})"}, .expectation = {.check = [](const ReadRecord& record){ + const DeclaredPose expected = ZoneDeclared{.place = "LumioseCity", .spot = "HotelZ", .heading = 90}; + return expect(std::get(record) == expected, "a zone pose with spot and heading"); + }}}, + {.name = "declared place alone", .input = {.record = Record::DECLARED, .json = R"({"place":"HotelZ"})"}, .expectation = {.check = [](const ReadRecord& record){ + const DeclaredPose expected = ZoneDeclared{.place = "HotelZ", .spot = std::nullopt, .heading = std::nullopt}; + return expect(std::get(record) == expected, "a zone pose alone"); + }}}, + {.name = "checkpoint starting at a place", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"03.01","title":"Lobby","start":{"place":"HotelZ"},"events":[{"id":"down","kind":"scene","declared_after":{"place":"HotelZLobby","heading":180}}]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + const DeclaredPose start = ZoneDeclared{.place = "HotelZ", .spot = std::nullopt, .heading = std::nullopt}; + return expect(checkpoint.start == start && checkpoint.steps.size() == 1 && checkpoint.steps[0].kind == StoryStepKind::MASH, "a zone start and one scene"); + }}}, + {.name = "ordered checkpoint", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"00.05","title":"Parcel","events":[ {"id":"first","kind":"talk"}, {"id":"second","kind":"scene"} ]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + return expect(checkpoint.id == "00.05" && checkpoint.title == "Parcel" && !checkpoint.start && checkpoint.steps.size() == 2 + && checkpoint.steps[0].name == "first" && checkpoint.steps[1].name == "second" + && checkpoint.steps_json == R"([{"id":"first","kind":"talk"},{"id":"second","kind":"scene"}])", "two steps in order and their compact JSON"); + }}}, + {.name = "checkpoint postconditions", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[],"metadata":{"phase":"reproduction","postconditions":{"position":{"map":"M","tiles":[[3,4]]},"items":[{"item":"LIFT_KEY","quantity":1}],"flags":["f"]}}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + const StoryPostconditions& post = checkpoint.postconditions; + // Named, not temporaries in the comparison: GCC's -Wdangling-pointer + // flags the braced vector temporaries there. + const GridPose position{.map = "M", .tiles = {{3, 4}}, .facing = std::nullopt}; + const std::vector items{{.item = "LIFT_KEY", .quantity = 1}}; + const std::vector flags{"f"}; + return expect(checkpoint.metadata.phase == StoryPhase::REPRODUCTION + && post.position == position && post.items == items && post.flags == flags, + "the phase, position, item and flag"); + }}}, + {.name = "integer rows, not rows", .input = {.json = R"({"id":"w","kind":"game_action","action":"walk","args":{"legs":[0,4500]}})"}, .expectation = {.rejected = true}}, + {.name = "integer rows, fraction", .input = {.json = R"({"id":"w","kind":"game_action","action":"walk","args":{"legs":[[0,4.5]]}})"}, .expectation = {.rejected = true}}, + {.name = "timed leg of three numbers", .input = {.json = R"({"id":"w","kind":"game_action","action":"timed_walk","args":{"legs":[[0,4500,1]]}})"}, .expectation = {.rejected = true}}, + {.name = "unknown arg", .input = {.json = R"({"id":"a","kind":"game_action","action":"mart","args":{"map":"M","budget":1,"budgte":1}})"}, .expectation = {.rejected = true}}, + {.name = "missing required arg", .input = {.json = R"({"id":"a","kind":"game_action","action":"mart","args":{"map":"M"}})"}, .expectation = {.rejected = true}}, + {.name = "route without target", .input = {.json = R"({"id":"a","kind":"route"})"}, .expectation = {.rejected = true}}, + {.name = "args on a kind with none", .input = {.json = R"({"id":"a","kind":"talk","args":{"yes":true}})"}, .expectation = {.rejected = true}}, + {.name = "game step without action", .input = {.json = R"({"id":"a","kind":"game_action"})"}, .expectation = {.rejected = true}}, + {.name = "unknown action name", .input = {.json = R"({"id":"a","kind":"game_action","action":"dance"})"}, .expectation = {.rejected = true}}, + {.name = "fractional arg", .input = {.json = R"({"id":"a","kind":"game_action","action":"mart","args":{"map":"M","budget":1.5}})"}, .expectation = {.rejected = true}}, + {.name = "args not an object", .input = {.json = R"({"id":"a","kind":"game_action","action":"mart","args":["map"]})"}, .expectation = {.rejected = true}}, + {.name = "old field", .input = {.json = R"({"id":"a","kind":"battle","may_lose":true})"}, .expectation = {.rejected = true}}, + {.name = "old variant", .input = {.json = R"({"id":"a","kind":"game_action","variant":"mart"})"}, .expectation = {.rejected = true}}, + {.name = "unknown field", .input = {.json = R"({"id":"a","kind":"talk","mystery":0})"}, .expectation = {.rejected = true}}, + {.name = "unknown kind", .input = {.json = R"({"id":"a","kind":"magic"})"}, .expectation = {.rejected = true}}, + {.name = "boolean count", .input = {.json = R"({"id":"a","kind":"train","args":{"battles":false}})"}, .expectation = {.rejected = true}}, + {.name = "wrong bool", .input = {.json = R"({"id":"a","kind":"answer","args":{"yes":0}})"}, .expectation = {.rejected = true}}, + {.name = "old pose", .input = {.record = Record::POSE, .json = R"({"map":"M","certainty":"unknown","where":{"kind":"unknown"}})"}, .expectation = {.rejected = true}}, + {.name = "bad coordinate", .input = {.record = Record::POSE, .json = R"({"map":"M","tiles":[[0,true]]})"}, .expectation = {.rejected = true}}, + {.name = "declared map and place", .input = {.record = Record::DECLARED, .json = R"({"map":"M","place":"HotelZ"})"}, .expectation = {.rejected = true}}, + {.name = "declared place with tiles", .input = {.record = Record::DECLARED, .json = R"({"place":"HotelZ","tiles":[[1,2]]})"}, .expectation = {.rejected = true}}, + {.name = "declared map with heading", .input = {.record = Record::DECLARED, .json = R"({"map":"M","heading":90})"}, .expectation = {.rejected = true}}, + {.name = "declared neither", .input = {.record = Record::DECLARED, .json = R"({"spot":"Lobby"})"}, .expectation = {.rejected = true}}, + {.name = "duplicate events", .input = {.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 = "walk", .args = { + {.key = "legs", .type = StoryArgType::INTEGER_ROWS, .required = true, .fallback = std::nullopt, .why = "rows of numbers"}, + }}); + actions.push_back({.kind = StoryStepKind::GAME, .name = "timed_walk", .args = { + {.key = "legs", .type = StoryArgType::TIMED_LEGS, .required = true, .fallback = std::nullopt, .why = "[turn degrees, ms] legs"}, + }}); + actions.push_back({.kind = StoryStepKind::GAME, .name = "profile", .args = {}}); + return actions; +} + + +// `input` read, with `source` naming it in parse errors. +ReadRecord read_record(const WireCase::Input& input, std::string_view source){ + static const std::vector actions = test_actions(); + const JsonValue value = parse_json(std::string(input.json)); + switch (input.record){ + case Record::POSE: + return read_grid_pose(value, source); + case Record::DECLARED: + return read_declared_pose(value, source); + case Record::STEP: + return read_story_step(value, source, actions); + case Record::CHECKPOINT: + return read_story_checkpoint(value, source, actions); + } + throw ParseException("Unknown test record."); +} + +// "" when `test` reads as expected, else what differs. +std::string check_case(const WireCase& test){ + try{ + const ReadRecord record = read_record(test.input, test.name); + if (test.expectation.rejected){ + return "Expected rejection, read accepted record."; + } + return test.expectation.check(record); + }catch (const ParseException& error){ + return test.expectation.rejected ? "" : std::format("Unexpected parse failure: {}", error.message()); + } +} + + +#ifndef PA_STORY_DATA_STANDALONE + +class StoryJsonTest : public UnitTest{ +public: + explicit StoryJsonTest(WireCase test) + : UnitTest(std::format("Pokemon::StoryStepJson - {}", test.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); + } +} + +#else + +size_t run_story_step_json_cases(){ + size_t failed = 0; + for (const WireCase& test : CASES){ + const std::string error = check_case(test); + std::cout << test.name << ": " << (error.empty() ? "PASS" : error) << '\n'; + failed += !error.empty(); + } + return failed; +} + +#endif + + + +} // namespace Pokemon +} // namespace PokemonAutomation 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..507d670981 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h @@ -0,0 +1,30 @@ +/* Story Step JSON Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepJson_Tests_H +#define PokemonAutomation_Pokemon_StoryStepJson_Tests_H + +#include +#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); + +#ifdef PA_STORY_DATA_STANDALONE +// Standalone StoryDataTests only: runs the built-in cases, prints one line +// per case, returns how many failed. +size_t run_story_step_json_cases(); +#endif + + + +} // 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 5fa5e61830..f647539ef1 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -12,9 +12,11 @@ #define PokemonAutomation_Pokemon_AutoStory_Tests_H #include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/Pokemon_StoryStepJson_Tests.h" #include "Pokemon_StoryEvents_Tests.h" #include "Pokemon_StoryFailureClasses_Tests.h" #include "Pokemon_StoryLog_Tests.h" +#include "Pokemon_StoryStepExecutor_Tests.h" #include "Types/Pokemon_StoryActionArg_Tests.h" namespace PokemonAutomation{ @@ -27,6 +29,8 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_StoryLog(database); add_tests_StoryFailureClasses(database); add_tests_StoryEvents(database); + add_tests_StoryStepExecutor(database); + add_tests_StoryStepJson(database); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp new file mode 100644 index 0000000000..ee108c1f20 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp @@ -0,0 +1,181 @@ +/* Story Step Executor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#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); +} + +GridPose grid_pose_of(const DeclaredPose& pose){ + if (const TileDeclared* tile = std::get_if(&pose)){ + return GridPose{.map = tile->map, .tiles = tile->tiles, .facing = tile->facing}; + } + return GridPose{.map = std::get(pose).place, .tiles = {}, .facing = std::nullopt}; +} + +Pose pose_of(const DeclaredPose& pose){ + return pose_of(grid_pose_of(pose)); +} + +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 (size_t index = 0; index < data.steps.size(); index++){ + const StoryStep& step = data.steps[index]; + checkpoint.events.push_back(story_event(step, executor)); + if (StoryPausePoints* pause = executor.pause_points()){ + checkpoint.events.back().act = [ + act = std::move(checkpoint.events.back().act), pause, label = story_step_pause_label(data.id, index, step.name) + ](RunState& state) mutable{ + pause->before_step(label); + return act(state); + }; + } + 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..dfc22dd35b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h @@ -0,0 +1,132 @@ +/* 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_DeclaredPose.h" +#include "Types/Pokemon_GridPose.h" +#include "Types/Pokemon_StoryBreakpoints.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 +// action names to handlers 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. A SAVE step must save only when + // the run's save mode allows a save part-way (PER_CHECKPOINT): nothing + // here knows the mode. The story engine's own SAVE action does this + // for a game on the engine. + 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); + + // The game's pause points (Pokemon_StoryBreakpoints.h), which the + // checkpoints built for this executor call before each of their steps. + // The game owns them and sets them before it builds a checkpoint; it + // calls before_leg() from its own leg loops. None by default: no pauses. + void set_pause_points(StoryPausePoints* pause){ + m_pause = pause; + } + StoryPausePoints* pause_points() const{ + return m_pause; + } + +private: + StoryPausePoints* m_pause = nullptr; +}; + +// `pose` as the engine's Pose: a TilePose, TILE for one tile, SET for several. +Pose pose_of(const GridPose& pose); + +// A declared pose as a grid pose: a place reads as a map with no tiles. +GridPose grid_pose_of(const DeclaredPose& pose); + +// pose_of(grid_pose_of(pose)). +Pose pose_of(const DeclaredPose& 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..ade175345d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp @@ -0,0 +1,451 @@ +/* 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_StoryEvents.h" +#include "Pokemon_BuiltinStoryActions.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}; +} + +// A declared pose on one tile. +TileDeclared declared(std::string map, TilePos tile, Direction facing){ + return TileDeclared{.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 = declared("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", declared("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; +} + +// An executor with pause points pauses before each of its checkpoint's steps, +// labelled with the checkpoint and the step's place; a skipped step does not +// pause, as it does not run. +UnitTestResult test_pause_points(){ + StoryCheckpoint data = lab_checkpoint(); + data.steps[1].skip_if = {"done"}; + std::vector paused; + FakeExecutor executor; + executor.conditions = {"done"}; + StoryPausePoints pause(StoryBreakpoints::STEPS, [&paused](std::string_view label){ + paused.emplace_back(label); + }); + executor.set_pause_points(&pause); + const Run result = run(data, executor); + const std::vector expected{ + "00.03/1 below_trigger", "00.03/3 to_the_lab", "00.03/4 talk_oak", "00.03/5 potions", "00.03/6 dance", + }; + if (paused != expected){ + return std::format("Expected a pause before each step that ran:{}{}", joined(paused), joined(result.lines)); + } + FakeExecutor plain; + const Run quiet = run(data, plain); + return quiet.report.completed ? UnitTestResult(true) : UnitTestResult(joined(quiet.lines)); +} + + +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 StoryStepTestCase{ + std::string name; + struct Input{ + UnitTestResult (*test)(); + }; + + struct Expectation{ + std::string_view description; + }; + + Input input; + Expectation expectation; +}; + +class Test_StoryStepExecutor : public UnitTest{ +public: + explicit Test_StoryStepExecutor(StoryStepTestCase scenario) + : UnitTest(std::format("Pokemon::StoryStepExecutor - {}", scenario.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[] = { + { + .name = "steps run in table order", .input = {.test = test_events_in_table_order}, + .expectation = {.description = "executes story steps sequentially as defined in table"}, + }, + { + .name = "skip_if asks the executor", .input = {.test = test_skip_if}, + .expectation = {.description = "delegates skip condition check to executor"}, + }, + { + .name = "each step starts where the last left the player", .input = {.test = test_pose_propagation}, + .expectation = {.description = "propagates player pose across sequential step executions"}, + }, + { + .name = "a failure names its step", .input = {.test = test_failure_names_the_step}, + .expectation = {.description = "records failing step identifier on error"}, + }, + { + .name = "unsupported kinds and lost battles", .input = {.test = test_unsupported_and_lost_battles}, + .expectation = {.description = "flags unsupported step types and handles battle defeat"}, + }, + { + .name = "pause points pause before each step", .input = {.test = test_pause_points}, + .expectation = {.description = "calls the game's pause points before each step that runs"}, + }, + { + .name = "lint", .input = {.test = test_lint}, + .expectation = {.description = "verifies lint validation rules on story checkpoints"}, + }, +}; + +} // 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/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 46deae7c65..133744d559 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1445,6 +1445,10 @@ file(GLOB LIBRARY_SOURCES Source/NintendoSwitch/Programs/Typewriter/NintendoSwitch_TypewriterTextMapping.h Source/PanelLists.cpp Source/PanelLists.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_AutoStory_Tests.h Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.cpp Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h @@ -1467,6 +1471,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.cpp Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.h Source/Pokemon/AutoStory/Pokemon_StoryPose.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_DeclaredPose.h From c63edb19793d31273882802f4b9ee47351cb3876 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 00:54:02 -0800 Subject: [PATCH 2/3] AutoStory: step JSON reads directions by direction_name(); no standalone test build The JSON reader read directions from its own copy of direction_name()'s table; it uses the shared names now. The step kind table stays, with a note on why its wire names differ from the log names. The standalone test entry point is dropped (nothing builds it), rejected-format cases are named by what they reject, and the executor tests are plain named tests. --- .../AutoStory/Data/Pokemon_StoryStepJson.cpp | 27 +++++----- .../AutoStory/Data/Pokemon_StoryStepJson.h | 4 +- .../Data/Pokemon_StoryStepJson_Tests.cpp | 31 ++---------- .../Data/Pokemon_StoryStepJson_Tests.h | 7 --- .../Pokemon_StoryStepExecutor_Tests.cpp | 49 ++++--------------- 5 files changed, 32 insertions(+), 86 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp index 095cbd5014..f385690433 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp @@ -27,7 +27,9 @@ namespace Pokemon{ namespace{ -// The wire names of the step kinds. +// The wire names of the step kinds. They are not story_step_kind_name()'s +// log names: the JSON names a MASH step "scene" and a GAME step +// "game_action", after what the story author writes. constexpr std::array, 15> KINDS{{ {StoryStepKind::NEW_GAME, "new_game"}, {StoryStepKind::OPTIONS, "options"}, @@ -46,13 +48,6 @@ constexpr std::array, 15> KINDS{{ {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`. @@ -80,6 +75,16 @@ Enum read_enum(const std::array, N>& names, st throw ParseException(std::format("{}: unsupported value {}", source, name)); } +// A direction by its direction_name(): "north", "east", ... +Direction read_direction(std::string_view name, std::string_view source){ + for (Direction direction : ALL_DIRECTIONS){ + if (direction_name(direction) == name){ + return direction; + } + } + throw ParseException(std::format("{}: unsupported value {}", source, name)); +} + 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()){ @@ -108,7 +113,7 @@ 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), + result.push_back({.direction = read_direction(row.get_string_throw("direction"), source), .tiles = integer(row.get_value_throw("tiles"), source)}); } return result; @@ -169,7 +174,7 @@ StoryArgValue read_arg(const JsonValue& value, StoryArgType type, std::string_vi 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); + return read_direction(value.to_string_throw(std::string(source)), source); case StoryArgType::GRID_POSE: return read_grid_pose(value, source); case StoryArgType::LEGS: @@ -295,7 +300,7 @@ GridPose read_grid_pose(const JsonValue& value, std::string_view source){ result.tiles = read_tiles(*field, source); } if (const JsonValue* field = root.get_value("facing")){ - result.facing = read_enum(DIRECTIONS, field->to_string_throw(), source); + result.facing = read_direction(field->to_string_throw(), source); } return result; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h index a67f5df31c..3caaf38191 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h @@ -9,8 +9,8 @@ * */ -#ifndef PokemonAutomation_StoryStepJson_H -#define PokemonAutomation_StoryStepJson_H +#ifndef PokemonAutomation_Pokemon_StoryStepJson_H +#define PokemonAutomation_Pokemon_StoryStepJson_H #include #include diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp index 296b300744..73a4dc3882 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp @@ -3,15 +3,12 @@ * From: https://github.com/PokemonAutomation/ * * Each case reads a record from JSON: accepted cases check the values - * read, rejected cases check that the read fails. The standalone - * StoryDataTests also checks PokemonSimulation's shared case file when given - * its path (devtools/story-data-tests/StoryWireCases.h). + * read, rejected cases check that the read fails. * */ #include #include -#include #include #include #include @@ -175,13 +172,13 @@ const WireCase CASES[] = { {.name = "unknown action name", .input = {.json = R"({"id":"a","kind":"game_action","action":"dance"})"}, .expectation = {.rejected = true}}, {.name = "fractional arg", .input = {.json = R"({"id":"a","kind":"game_action","action":"mart","args":{"map":"M","budget":1.5}})"}, .expectation = {.rejected = true}}, {.name = "args not an object", .input = {.json = R"({"id":"a","kind":"game_action","action":"mart","args":["map"]})"}, .expectation = {.rejected = true}}, - {.name = "old field", .input = {.json = R"({"id":"a","kind":"battle","may_lose":true})"}, .expectation = {.rejected = true}}, - {.name = "old variant", .input = {.json = R"({"id":"a","kind":"game_action","variant":"mart"})"}, .expectation = {.rejected = true}}, + {.name = "may_lose outside args", .input = {.json = R"({"id":"a","kind":"battle","may_lose":true})"}, .expectation = {.rejected = true}}, + {.name = "variant instead of action", .input = {.json = R"({"id":"a","kind":"game_action","variant":"mart"})"}, .expectation = {.rejected = true}}, {.name = "unknown field", .input = {.json = R"({"id":"a","kind":"talk","mystery":0})"}, .expectation = {.rejected = true}}, {.name = "unknown kind", .input = {.json = R"({"id":"a","kind":"magic"})"}, .expectation = {.rejected = true}}, {.name = "boolean count", .input = {.json = R"({"id":"a","kind":"train","args":{"battles":false}})"}, .expectation = {.rejected = true}}, {.name = "wrong bool", .input = {.json = R"({"id":"a","kind":"answer","args":{"yes":0}})"}, .expectation = {.rejected = true}}, - {.name = "old pose", .input = {.record = Record::POSE, .json = R"({"map":"M","certainty":"unknown","where":{"kind":"unknown"}})"}, .expectation = {.rejected = true}}, + {.name = "certainty and where in a pose", .input = {.record = Record::POSE, .json = R"({"map":"M","certainty":"unknown","where":{"kind":"unknown"}})"}, .expectation = {.rejected = true}}, {.name = "bad coordinate", .input = {.record = Record::POSE, .json = R"({"map":"M","tiles":[[0,true]]})"}, .expectation = {.rejected = true}}, {.name = "declared map and place", .input = {.record = Record::DECLARED, .json = R"({"map":"M","place":"HotelZ"})"}, .expectation = {.rejected = true}}, {.name = "declared place with tiles", .input = {.record = Record::DECLARED, .json = R"({"place":"HotelZ","tiles":[[1,2]]})"}, .expectation = {.rejected = true}}, @@ -243,8 +240,6 @@ std::string check_case(const WireCase& test){ } -#ifndef PA_STORY_DATA_STANDALONE - class StoryJsonTest : public UnitTest{ public: explicit StoryJsonTest(WireCase test) @@ -261,34 +256,16 @@ class StoryJsonTest : public UnitTest{ WireCase m_case; }; -#endif - } // namespace -#ifndef PA_STORY_DATA_STANDALONE - void add_tests_StoryStepJson(UnitTestDatabase& database){ for (const WireCase& test : CASES){ database.add(test); } } -#else - -size_t run_story_step_json_cases(){ - size_t failed = 0; - for (const WireCase& test : CASES){ - const std::string error = check_case(test); - std::cout << test.name << ": " << (error.empty() ? "PASS" : error) << '\n'; - failed += !error.empty(); - } - return failed; -} - -#endif - } // namespace Pokemon diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h index 507d670981..9c4f9565ad 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h @@ -7,7 +7,6 @@ #ifndef PokemonAutomation_Pokemon_StoryStepJson_Tests_H #define PokemonAutomation_Pokemon_StoryStepJson_Tests_H -#include #include "Common/Cpp/TestRunners/UnitTestDatabase.h" namespace PokemonAutomation{ @@ -17,12 +16,6 @@ namespace Pokemon{ // Registers unit tests for the lossless shared story-data wire contract. void add_tests_StoryStepJson(UnitTestDatabase& database); -#ifdef PA_STORY_DATA_STANDALONE -// Standalone StoryDataTests only: runs the built-in cases, prints one line -// per case, returns how many failed. -size_t run_story_step_json_cases(); -#endif - } // namespace Pokemon diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp index ade175345d..400d17ed34 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp @@ -377,18 +377,10 @@ UnitTestResult test_lint(){ } +// A named test; it returns its own failure. struct StoryStepTestCase{ std::string name; - struct Input{ - UnitTestResult (*test)(); - }; - - struct Expectation{ - std::string_view description; - }; - - Input input; - Expectation expectation; + UnitTestResult (*test)(); }; class Test_StoryStepExecutor : public UnitTest{ @@ -398,7 +390,7 @@ class Test_StoryStepExecutor : public UnitTest{ , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - return m_scenario.input.test(); + return m_scenario.test(); } private: @@ -406,34 +398,13 @@ class Test_StoryStepExecutor : public UnitTest{ }; const StoryStepTestCase STORY_STEP_CASES[] = { - { - .name = "steps run in table order", .input = {.test = test_events_in_table_order}, - .expectation = {.description = "executes story steps sequentially as defined in table"}, - }, - { - .name = "skip_if asks the executor", .input = {.test = test_skip_if}, - .expectation = {.description = "delegates skip condition check to executor"}, - }, - { - .name = "each step starts where the last left the player", .input = {.test = test_pose_propagation}, - .expectation = {.description = "propagates player pose across sequential step executions"}, - }, - { - .name = "a failure names its step", .input = {.test = test_failure_names_the_step}, - .expectation = {.description = "records failing step identifier on error"}, - }, - { - .name = "unsupported kinds and lost battles", .input = {.test = test_unsupported_and_lost_battles}, - .expectation = {.description = "flags unsupported step types and handles battle defeat"}, - }, - { - .name = "pause points pause before each step", .input = {.test = test_pause_points}, - .expectation = {.description = "calls the game's pause points before each step that runs"}, - }, - { - .name = "lint", .input = {.test = test_lint}, - .expectation = {.description = "verifies lint validation rules on story checkpoints"}, - }, + {.name = "steps run in table order", .test = test_events_in_table_order}, + {.name = "skip_if asks the executor", .test = test_skip_if}, + {.name = "each step starts where the last left the player", .test = test_pose_propagation}, + {.name = "a failure names its step", .test = test_failure_names_the_step}, + {.name = "unsupported kinds and lost battles", .test = test_unsupported_and_lost_battles}, + {.name = "pause points pause before each step", .test = test_pause_points}, + {.name = "lint", .test = test_lint}, }; } // namespace From c36984634dedadd53a969b4a3ed7543f18f32789 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 01:13:00 -0800 Subject: [PATCH 3/3] AutoStory: the step JSON tests read checkpoint metadata (moved from the engine PR) --- .../AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp index 73a4dc3882..7daaee3eeb 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp @@ -161,6 +161,15 @@ const WireCase CASES[] = { && post.position == position && post.items == items && post.flags == flags, "the phase, position, item and flag"); }}}, + {.name = "checkpoint without metadata is testing", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + return expect(checkpoint.metadata.phase == StoryPhase::TESTING && !checkpoint.metadata.verified, "the testing phase and no verification"); + }}}, + {.name = "verified checkpoint", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[],"metadata":{"phase":"verification","verified":{"steps_hash":"sha256:ab","build":"1","date":"d","runs":"3/3"}}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpointMetadata& metadata = std::get(record).metadata; + return expect(metadata.phase == StoryPhase::VERIFICATION && metadata.verified && metadata.verified->steps_hash == "sha256:ab", + "the verification phase and its steps hash"); + }}}, {.name = "integer rows, not rows", .input = {.json = R"({"id":"w","kind":"game_action","action":"walk","args":{"legs":[0,4500]}})"}, .expectation = {.rejected = true}}, {.name = "integer rows, fraction", .input = {.json = R"({"id":"w","kind":"game_action","action":"walk","args":{"legs":[[0,4.5]]}})"}, .expectation = {.rejected = true}}, {.name = "timed leg of three numbers", .input = {.json = R"({"id":"w","kind":"game_action","action":"timed_walk","args":{"legs":[[0,4500,1]]}})"}, .expectation = {.rejected = true}}, @@ -184,6 +193,8 @@ const WireCase CASES[] = { {.name = "declared place with tiles", .input = {.record = Record::DECLARED, .json = R"({"place":"HotelZ","tiles":[[1,2]]})"}, .expectation = {.rejected = true}}, {.name = "declared map with heading", .input = {.record = Record::DECLARED, .json = R"({"map":"M","heading":90})"}, .expectation = {.rejected = true}}, {.name = "declared neither", .input = {.record = Record::DECLARED, .json = R"({"spot":"Lobby"})"}, .expectation = {.rejected = true}}, + {.name = "unknown phase", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[],"metadata":{"phase":"tested"}})"}, .expectation = {.rejected = true}}, + {.name = "unknown metadata field", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[],"metadata":{"phase":"testing","runs":3}})"}, .expectation = {.rejected = true}}, {.name = "duplicate events", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[{"id":"a","kind":"talk"},{"id":"a","kind":"talk"}]})"}, .expectation = {.rejected = true}}, };