diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp index 2b67c07b8b..22fdc088dc 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp @@ -17,6 +17,7 @@ #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Json/JsonArray.h" #include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon/AutoStory/Grid/Pokemon_GridStoryArgs.h" #include "Pokemon_StoryStepJson.h" namespace PokemonAutomation{ @@ -180,9 +181,40 @@ StoryActionArgs read_args( } +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_story_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", "source"}, source); + 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); @@ -191,9 +223,15 @@ void read_metadata(const JsonValue& value, std::string_view source, StoryCheckpo } 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); + } } @@ -213,12 +251,40 @@ DeclaredPose read_declared_pose(const JsonValue& value, std::string_view source) return result; } +// A gate change, {"opened": ["SilphCo_5F/door_1"], "switches": {"mansion": true}}: +// the gates a step opens, the switches it sets; both optional. +GateChange read_gate_change(const JsonValue& value, std::string_view source){ + const JsonObject& root = fields(value, {"opened", "switches"}, source); + GateChange result; + if (const JsonValue* field = root.get_value("opened")){ + for (std::string& key : read_strings(*field, source)){ + result.opened.insert(std::move(key)); + } + } + if (const JsonValue* field = root.get_value("switches")){ + for (const auto& [id, on] : field->to_object_throw(std::string(source))){ + result.switches[id] = on.to_boolean_throw(std::string(source)); + } + } + return result; +} + +// A checkpoint's "start_gates", written as a gate change from nothing open. +GateState read_gate_state(const JsonValue& value, std::string_view source){ + GateState result; + apply_gate_change(result, read_gate_change(value, source)); + return result; +} + // Read a step, its args parsed against its action among `actions` (the // game's) 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){ +StoryStep read_story_step( + const JsonValue& value, std::string_view source, + std::span actions, const StoryArgKind* declared_pose +){ const JsonObject& root = fields( - value, {"id", "kind", "why", "action", "args"}, source + value, {"id", "kind", "why", "action", "args", "skip_if", "declared_after", "gates_after", "flags_after"}, source ); StoryStep result; result.name = root.get_string_throw("id"); @@ -233,6 +299,18 @@ StoryStep read_story_step(const JsonValue& value, std::string_view source, std:: 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 = declared_pose ? DeclaredPose(declared_pose->read(*field, source)) : read_declared_pose(*field, source); + } + if (const JsonValue* field = root.get_value("gates_after")){ + result.gates_after = read_gate_change(*field, source); + } + if (const JsonValue* field = root.get_value("flags_after")){ + result.flags_after = read_strings(*field, source); + } return result; } @@ -244,7 +322,7 @@ StoryCheckpoint read_story_checkpoint( const JsonValue& value, std::string_view source, std::span actions, const StoryArgKind* declared_pose ){ - const JsonObject& root = fields(value, {"id", "title", "start", "events", "metadata"}, source); + const JsonObject& root = fields(value, {"id", "title", "start", "start_gates", "start_flags", "events", "metadata"}, source); StoryCheckpoint result; result.id = root.get_string_throw("id"); if (result.id.empty()){ @@ -254,9 +332,16 @@ StoryCheckpoint read_story_checkpoint( if (const JsonValue* start = root.get_value("start")){ result.start = declared_pose ? DeclaredPose(declared_pose->read(*start, source)) : read_declared_pose(*start, source); } + if (const JsonValue* gates = root.get_value("start_gates")){ + result.start_gates = read_gate_state(*gates, source); + } + if (const JsonValue* flags = root.get_value("start_flags")){ + result.start_flags = read_strings(*flags, 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); + StoryStep step = read_story_step(event, source, actions, declared_pose); if (step.name.empty() || !names.insert(step.name).second){ throw ParseException("Empty or duplicate story event id."); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h index 2025ac3662..a9c12b30ac 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h @@ -29,7 +29,11 @@ namespace Pokemon{ // action among `actions` (the game's) and their fallbacks filled in. // Unknown fields, kinds, actions and args, mistyped values and missing // required args fail. A game whose poses are not zones passes -// `declared_pose`, which reads "start" instead. +// `declared_pose`, which reads "start" and "declared_after" instead. +// The grid games' fields: a step's "skip_if", "declared_after", +// "gates_after" and "flags_after"; the checkpoint's "start_gates" and +// "start_flags"; "metadata" "verified" and "postconditions". steps_json +// keeps the "events" array as read, dumped compactly. StoryCheckpoint read_story_checkpoint( const JsonValue& value, std::string_view source, std::span actions, const StoryArgKind* declared_pose = nullptr diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp index ef5d025d44..536ab71e42 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp @@ -19,7 +19,10 @@ #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Json/JsonArray.h" #include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon/AutoStory/Grid/Pokemon_GridStoryArgs.h" #include "Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" +#include "Pokemon/Navigation/Pokemon_GateState.h" #include "Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h" #include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h" #include "Pokemon_StoryStepJson.h" @@ -39,6 +42,8 @@ enum class Record{ DECLARED, // A declared pose read by the test's registered kind. REGISTERED_DECLARED, + // A checkpoint whose poses are tile ones (GridArg::TILE_DECLARED). + TILE_CHECKPOINT, STEP, CHECKPOINT, }; @@ -116,6 +121,64 @@ const WireCase CASES[] = { const DeclaredPose expected = make_registered_arg(Pair{5, 6}); return expect(std::get(record) == expected, "the game's pose (5, 6)"); }}}, + {.name = "grid step fields", .input = {.record = Record::TILE_CHECKPOINT, .json = R"({"id":"x","title":"X","start":{"map":"A"},"events":[{"id":"all","kind":"talk","skip_if":["flag"],"declared_after":{"map":"B","tiles":[[0,0],[1,0]],"facing":"east"},"flags_after":["card_key_held"]}]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + const StoryStep& step = checkpoint.steps.at(0); + const DeclaredPose start = make_registered_arg(TileDeclared{.map = "A", .tiles = {}, .facing = std::nullopt}); + const DeclaredPose after = make_registered_arg(TileDeclared{.map = "B", .tiles = {{0, 0}, {1, 0}}, .facing = Direction::EAST}); + const std::vector skip_if{"flag"}; + const std::vector flags_after{"card_key_held"}; + return expect(checkpoint.start == start && step.skip_if == skip_if && step.pose_after == after && step.flags_after == flags_after && !step.gates_after, + "skip_if, a tile pose after, a flag after and no gate change"); + }}}, + {.name = "step opens gates", .input = {.json = R"({"id":"unlock","kind":"talk","gates_after":{"opened":["SilphCo_5F/door_1"],"switches":{"mansion":true}}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryStep& step = step_of(record); + GateChange expected; + expected.opened.insert("SilphCo_5F/door_1"); + expected.switches["mansion"] = true; + return expect(step.gates_after && *step.gates_after == expected, "door_1 opened and the mansion switch on"); + }}}, + {.name = "checkpoint gate state", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"16.02","title":"Silph","start_gates":{"opened":["SilphCo_5F/door_1"]},"events":[{"id":"a","kind":"talk","gates_after":{"opened":["SilphCo_5F/door_2"]}},{"id":"b","kind":"talk","gates_after":{"switches":{"mansion":true}}},{"id":"c","kind":"talk"}]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + if (!checkpoint.start_gates || checkpoint.start_gates->opened.size() != 1){ + return std::string("Expected start_gates with door_1 open."); + } + const GateState first = checkpoint_gates(checkpoint, 1); + const GateState all = checkpoint_gates(checkpoint, 3); + if (!(checkpoint_gates(checkpoint, 0) == *checkpoint.start_gates) || first.opened.size() != 2 || first.switch_on("mansion")){ + return std::string("Expected the start, then door_2 as well after one step."); + } + return expect(all.switch_on("mansion") && checkpoint_gates(checkpoint, 99) == all, "the switch on after the steps, and past the end the same"); + }}}, + {.name = "checkpoint without gates", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[{"id":"a","kind":"talk"}]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + return expect(!checkpoint.start_gates && checkpoint_gates(checkpoint, 1) == GateState(), "no start gates and nothing open"); + }}}, + {.name = "checkpoint start flags", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"16.02","title":"Silph","start_flags":["has_pass"],"events":[]})"}, .expectation = {.check = [](const ReadRecord& record){ + const std::vector flags{"has_pass"}; + return expect(std::get(record).start_flags == flags, "has_pass held at the start"); + }}}, + {.name = "checkpoint postconditions and verification", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[],"metadata":{"phase":"reproduction","verified":{"steps_hash":"sha256:ab","runs":"3/3"},"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"}; + const StoryVerification verified{.steps_hash = "sha256:ab", .build = "", .date = "", .runs = "3/3"}; + return expect(checkpoint.metadata.verified == verified && post.position == position && post.items == items && post.flags == flags, + "the verification, position, item and flag"); + }}}, + {.name = "grid args", .input = {.json = R"({"id":"g","kind":"game_action","action":"grid","args":{"facing":"west","to":{"map":"PalletTown","tiles":[[3,4]],"facing":"north"},"legs":[{"direction":"north","tiles":3}],"items":[{"item":"Potion","quantity":2}]}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs& args = step_of(record).args; + const GridPose to{.map = "PalletTown", .tiles = {{3, 4}}, .facing = Direction::NORTH}; + const std::vector legs{{.direction = Direction::NORTH, .tiles = 3}}; + const std::vector items{{.item = "Potion", .quantity = 2}}; + return expect(registered_arg(args, "facing") == Direction::WEST && registered_arg(args, "to") == to + && registered_arg>(args, "legs") == legs && registered_arg>(args, "items") == items, + "west, PalletTown (3, 4) north, north 3, two Potions"); + }}}, {.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"); @@ -132,7 +195,8 @@ const WireCase CASES[] = { {.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", "two steps in order"); + && 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 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); @@ -143,6 +207,13 @@ const WireCase CASES[] = { {.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 = "registered arg malformed", .input = {.json = R"({"id":"j","kind":"game_action","action":"jump","args":{"to":[3]}})"}, .expectation = {.rejected = true}}, {.name = "registered declared pose malformed", .input = {.record = Record::REGISTERED_DECLARED, .json = R"({"place":"HotelZ"})"}, .expectation = {.rejected = true}}, + {.name = "gate change with an unknown field", .input = {.json = R"({"id":"x","kind":"talk","gates_after":{"closed":["a/b"]}})"}, .expectation = {.rejected = true}}, + {.name = "verification without steps hash", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[],"metadata":{"verified":{"runs":"3/3"}}})"}, .expectation = {.rejected = true}}, + {.name = "unknown postcondition", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[],"metadata":{"postconditions":{"money":5}}})"}, .expectation = {.rejected = true}}, + {.name = "grid arg, unknown direction", .input = {.json = R"({"id":"g","kind":"game_action","action":"grid","args":{"facing":"up"}})"}, .expectation = {.rejected = true}}, + {.name = "grid arg, tile of three coordinates", .input = {.json = R"({"id":"g","kind":"game_action","action":"grid","args":{"to":{"map":"M","tiles":[[1,2,3]]}}})"}, .expectation = {.rejected = true}}, + {.name = "grid arg, negative quantity", .input = {.json = R"({"id":"g","kind":"game_action","action":"grid","args":{"items":[{"item":"Potion","quantity":-1}]}})"}, .expectation = {.rejected = true}}, + {.name = "tile start with a place", .input = {.record = Record::TILE_CHECKPOINT, .json = R"({"id":"x","title":"X","start":{"place":"HotelZ"},"events":[]})"}, .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 = "args on a kind with none", .input = {.json = R"({"id":"a","kind":"talk","args":{"yes":true}})"}, .expectation = {.rejected = true}}, @@ -181,6 +252,12 @@ std::vector test_actions(){ actions.push_back({.kind = StoryStepKind::GAME, .name = "jump", .args = { {.key = "to", .type = StoryArgType::REGISTERED, .required = true, .fallback = std::nullopt, .why = "where to", .kind = &PAIR_KIND}, }}); + actions.push_back({.kind = StoryStepKind::GAME, .name = "grid", .args = { + {.key = "facing", .type = StoryArgType::REGISTERED, .required = false, .fallback = std::nullopt, .why = "", .kind = &grid_arg_kind(GridArg::DIRECTION)}, + {.key = "to", .type = StoryArgType::REGISTERED, .required = false, .fallback = std::nullopt, .why = "", .kind = &grid_arg_kind(GridArg::GRID_POSE)}, + {.key = "legs", .type = StoryArgType::REGISTERED, .required = false, .fallback = std::nullopt, .why = "", .kind = &grid_arg_kind(GridArg::LEGS)}, + {.key = "items", .type = StoryArgType::REGISTERED, .required = false, .fallback = std::nullopt, .why = "", .kind = &grid_arg_kind(GridArg::ITEMS)}, + }}); actions.push_back({.kind = StoryStepKind::GAME, .name = "profile", .args = {}}); return actions; } @@ -203,6 +280,8 @@ ReadRecord read_record(const WireCase::Input& input, std::string_view source){ const std::string json = std::format(R"({{"id":"x","title":"X","events":[{}]}})", input.json); return read_story_checkpoint(parse_json(json), source, actions).steps.at(0); } + case Record::TILE_CHECKPOINT: + return read_story_checkpoint(parse_json(std::string(input.json)), source, actions, &grid_arg_kind(GridArg::TILE_DECLARED)); case Record::CHECKPOINT: return read_story_checkpoint(parse_json(std::string(input.json)), source, actions); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryActions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryActions.cpp new file mode 100644 index 0000000000..77b37e9811 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryActions.cpp @@ -0,0 +1,41 @@ +/* Grid Story Actions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon_GridStoryActions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +StoryActionSpec grid_legs_spec(){ + return {.kind = StoryStepKind::LEGS, .name = "legs", .args = { + {.key = "legs", .type = StoryArgType::REGISTERED, .required = true, .fallback = std::nullopt, + .why = "the straight legs to walk", .kind = &grid_arg_kind(GridArg::LEGS)}, + {.key = "run", .type = StoryArgType::BOOLEAN, .required = false, .fallback = StoryArgValue(false), + .why = "run instead of walk", .kind = nullptr}, + }, .console_only = false}; +} + +StoryActionSpec grid_face_spec(){ + return {.kind = StoryStepKind::STEP, .name = "face", .args = { + {.key = "direction", .type = StoryArgType::REGISTERED, .required = true, .fallback = std::nullopt, + .why = "the way to step or face", .kind = &grid_arg_kind(GridArg::DIRECTION)}, + }, .console_only = false}; +} + +Outcome grid_moves_unsupported(std::string_view step, StoryBackendKind kind){ + return outcome_failed( + "unsupported_step", + std::format("{}: the {} backend has no tile moves", step, story_backend_kind_name(kind)) + ); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryActions.h b/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryActions.h new file mode 100644 index 0000000000..835ff5ce46 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryActions.h @@ -0,0 +1,103 @@ +/* Grid Story Actions + * + * From: https://github.com/PokemonAutomation/ + * + * The story actions every tile game (FRLG, BDSP) shares: "legs", straight + * legs walked as given, and "face", a turn or a single step. They read + * their args with the grid arg kinds (Pokemon_GridStoryArgs.h) and move + * the player through the game's backend, which adds move_leg() and face() + * to StoryBackend (GridMoveBackend): how a tile is crossed (a D-pad tap, a + * held stick) and how sure the pose stays is the game's. + * + */ + +#ifndef PokemonAutomation_Pokemon_GridStoryActions_H +#define PokemonAutomation_Pokemon_GridStoryActions_H + +#include +#include +#include +#include "Pokemon/AutoStory/Engine/Pokemon_StoryBackend.h" +#include "Pokemon/AutoStory/Engine/Pokemon_StoryGame.h" +#include "Pokemon/AutoStory/Engine/Pokemon_StoryPoseConcept.h" +#include "Pokemon/AutoStory/Pokemon_StoryOutcome.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h" +#include "Pokemon/Navigation/Pokemon_Direction.h" +#include "Pokemon_GridStoryArgs.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A tile game's backend: a StoryBackend that also walks `tiles` tiles in a +// straight line and turns in place. +template +concept GridMoveBackend = std::derived_from> + && requires(Backend& backend, Direction direction, int tiles, StoryPace pace){ + backend.move_leg(direction, tiles, pace); + backend.face(direction); + }; + +// "legs" (StoryStepKind::LEGS): {"legs": [{"direction": "north", "tiles": +// 3}, ...]}, and "run" (false: walk). +StoryActionSpec grid_legs_spec(); +// "face" (StoryStepKind::STEP): {"direction": "north"}. +StoryActionSpec grid_face_spec(); + +// "legs" and "face" on a game's `Backend`. A step run on a backend of +// another type fails as "unsupported_step" before any input. +template + requires GridMoveBackend +std::vector> grid_story_actions(); + +// The "legs" handler on `Backend`: each leg in order. +template +Outcome grid_walk_legs(StoryBackend& backend, const StoryActionCall& call, RunState& state); +// The "face" handler on `Backend`. +template +Outcome grid_face(StoryBackend& backend, const StoryActionCall& call, RunState& state); + +// The failure of a grid action on a backend that is not the game's. +Outcome grid_moves_unsupported(std::string_view step, StoryBackendKind kind); + + + +template +Outcome grid_walk_legs(StoryBackend& backend, const StoryActionCall& call, RunState&){ + Backend* grid = dynamic_cast(&backend); + if (grid == nullptr){ + return grid_moves_unsupported(call.step.name, backend.kind()); + } + const StoryPace pace = story_arg(call.args, "run") ? StoryPace::RUN : StoryPace::WALK; + for (const StoryLeg& leg : registered_arg>(call.args, "legs")){ + backend.scope().throw_if_cancelled(); + grid->move_leg(leg.direction, leg.tiles, pace); + } + return outcome_ok(); +} + +template +Outcome grid_face(StoryBackend& backend, const StoryActionCall& call, RunState&){ + Backend* grid = dynamic_cast(&backend); + if (grid == nullptr){ + return grid_moves_unsupported(call.step.name, backend.kind()); + } + grid->face(registered_arg(call.args, "direction")); + return outcome_ok(); +} + +template + requires GridMoveBackend +std::vector> grid_story_actions(){ + return { + {.spec = grid_legs_spec(), .handler = &grid_walk_legs}, + {.spec = grid_face_spec(), .handler = &grid_face}, + }; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryActions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryActions_Tests.cpp new file mode 100644 index 0000000000..deefcc5bfb --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryActions_Tests.cpp @@ -0,0 +1,175 @@ +/* Grid Story Actions Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Each case reads one step from JSON with the grid actions' specs, runs + * its action on a scripted backend and checks the moves it made. The pose + * type does not matter to the grid actions: the cases use ZonePose, the + * one the scripted backend is built for. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h" +#include "Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.h" +#include "Pokemon/AutoStory/Engine/Pokemon_ZonePose.h" +#include "Pokemon_GridStoryActions.h" +#include "Pokemon_GridStoryActions_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// The scripted backend with tile moves: records each as an input. +class FakeGridBackend : public FakeStoryBackend{ +public: + using FakeStoryBackend::FakeStoryBackend; + + void move_leg(Direction direction, int tiles, StoryPace pace){ + m_moves.push_back(std::format("leg {} {} {}", direction_name(direction), tiles, pace == StoryPace::RUN ? "run" : "walk")); + } + void face(Direction direction){ + m_moves.push_back(std::format("face {}", direction_name(direction))); + } + + const std::vector& moves() const{ + return m_moves; + } + +private: + std::vector m_moves; +}; + +// Which backend a step runs on. +enum class Backend{ + GRID, + PLAIN, // the scripted backend with no tile moves +}; + +struct GridActionCase{ + std::string name; + struct Input{ + // One step, as a checkpoint's event. + std::string_view step_json; + Backend backend = Backend::GRID; + }; + Input input; + struct Expectation{ + // The moves made, then the failure if any: "leg north 3 walk, + // face west / ok". + std::string text; + }; + Expectation expectation; +}; + +const GridActionCase CASES[] = { + { + .name = "legs walk each leg in order", + .input = {.step_json = R"({"id":"w","kind":"legs","args":{"legs":[ + {"direction":"north","tiles":3},{"direction":"east","tiles":2}]}})"}, + .expectation = {.text = "leg north 3 walk, leg east 2 walk / ok"}, + }, + { + .name = "legs with run run every leg", + .input = {.step_json = R"({"id":"w","kind":"legs","args":{"run":true,"legs":[{"direction":"south","tiles":1}]}})"}, + .expectation = {.text = "leg south 1 run / ok"}, + }, + { + .name = "face turns to the direction", + .input = {.step_json = R"({"id":"f","kind":"step","action":"face","args":{"direction":"west"}})"}, + .expectation = {.text = "face west / ok"}, + }, + { + .name = "legs on a backend with no tile moves fail before any input", + .input = { + .step_json = R"({"id":"w","kind":"legs","args":{"legs":[{"direction":"north","tiles":1}]}})", + .backend = Backend::PLAIN, + }, + .expectation = {.text = " / unsupported_step"}, + }, +}; + +std::string joined(const std::vector& lines){ + std::string text; + for (const std::string& line : lines){ + text += std::format("{}{}", text.empty() ? "" : ", ", line); + } + return text; +} + +// What `test`'s step did: its moves (or a plain backend's inputs) and how +// it ended. +std::string run_case(const GridActionCase::Input& input, CancellableScope& scope){ + const std::vector> actions = grid_story_actions(); + std::vector specs; + for (const StoryAction& action : actions){ + specs.push_back(action.spec); + } + const std::string json = std::format(R"({{"id":"x","title":"X","events":[{}]}})", input.step_json); + const StoryStep step = read_story_checkpoint(parse_json(json), "test", specs).steps.at(0); + const StoryActionSpec* spec = find_story_action(specs, step.kind, step.action); + if (spec == nullptr){ + return "no action"; + } + const StoryAction& action = actions[(size_t)(spec - specs.data())]; + const StoryActionCall call{.step = step, .args = step.args}; + RunState state; + + FakeGridBackend grid({}, scope); + FakeStoryBackend plain({}, scope); + const bool on_grid = input.backend == Backend::GRID; + const Outcome outcome = on_grid ? action.handler(grid, call, state) : action.handler(plain, call, state); + return std::format( + "{} / {}", joined(on_grid ? grid.moves() : plain.inputs()), outcome.succeeded() ? "ok" : outcome.failure + ); +} + + +class GridStoryActionTest : public UnitTest{ +public: + explicit GridStoryActionTest(GridActionCase test_case) + : UnitTest(std::format("Pokemon::GridStoryActions - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope& scope) const override{ + try{ + const std::string got = run_case(m_case.input, scope); + if (got != m_case.expectation.text){ + return std::format("expected \"{}\", got \"{}\"", m_case.expectation.text, got); + } + }catch (const ParseException& error){ + return std::format("expected \"{}\", the step did not read: {}", m_case.expectation.text, error.message()); + } + return true; + } + +private: + GridActionCase m_case; +}; + + +} // namespace + + +void add_tests_GridStoryActions(UnitTestDatabase& database){ + for (const GridActionCase& test : CASES){ + database.add(test); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryActions_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryActions_Tests.h new file mode 100644 index 0000000000..148604f159 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryActions_Tests.h @@ -0,0 +1,23 @@ +/* Grid Story Actions Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_GridStoryActions_Tests_H +#define PokemonAutomation_Pokemon_GridStoryActions_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the shared tile actions: legs and face read from JSON and run on a scripted backend. +void add_tests_GridStoryActions(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryArgs.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryArgs.cpp new file mode 100644 index 0000000000..69bab1c746 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryArgs.cpp @@ -0,0 +1,153 @@ +/* Grid Story Args + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon_GridStoryArgs.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// The wire names of the directions. +constexpr std::array, 4> DIRECTIONS{{ + {Direction::NORTH, "north"}, + {Direction::EAST, "east"}, + {Direction::SOUTH, "south"}, + {Direction::WEST, "west"}, +}}; + +Direction read_direction(std::string_view name, std::string_view source){ + for (const auto& [value, label] : DIRECTIONS){ + if (label == name){ + return value; + } + } + throw ParseException(std::format("{}: unsupported direction {}", source, name)); +} + +// `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; +} + +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("{}: number exceeds native int", source)); + } + return (int)number; +} + +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; +} + +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_direction(row.get_string_throw("direction"), source), + .tiles = integer(row.get_value_throw("tiles"), source)}); + } + return result; +} + +StoryArgKind make_kind(GridArg arg){ + switch (arg){ + case GridArg::DIRECTION: + return {.name = "direction", .read = [](const JsonValue& value, std::string_view source){ + return make_registered_arg(read_direction(value.to_string_throw(std::string(source)), source)); + }}; + case GridArg::GRID_POSE: + return {.name = "grid_pose", .read = [](const JsonValue& value, std::string_view source){ + return make_registered_arg(read_grid_pose(value, source)); + }}; + case GridArg::LEGS: + return {.name = "legs", .read = [](const JsonValue& value, std::string_view source){ + return make_registered_arg(read_legs(value, source)); + }}; + case GridArg::ITEMS: + return {.name = "items", .read = [](const JsonValue& value, std::string_view source){ + return make_registered_arg(read_story_items(value, source)); + }}; + case GridArg::TILE_DECLARED: + return {.name = "tile_declared", .read = [](const JsonValue& value, std::string_view source){ + GridPose grid = read_grid_pose(value, source); + return make_registered_arg(TileDeclared{.map = std::move(grid.map), .tiles = std::move(grid.tiles), .facing = grid.facing}); + }}; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown grid arg kind."); +} + + +} // namespace + + +const StoryArgKind& grid_arg_kind(GridArg arg){ + static const std::array KINDS{ + make_kind(GridArg::DIRECTION), make_kind(GridArg::GRID_POSE), make_kind(GridArg::LEGS), + make_kind(GridArg::ITEMS), make_kind(GridArg::TILE_DECLARED), + }; + return KINDS[(size_t)arg]; +} + +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"); + 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_direction(field->to_string_throw(), source); + } + return result; +} + +std::vector read_story_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); + const int64_t quantity = row.get_value_throw("quantity").to_integer_throw(std::string(source)); + if (quantity < 0){ + throw ParseException(std::format("{}: a quantity is not negative", source)); + } + result.push_back({.item = row.get_string_throw("item"), .quantity = (size_t)quantity}); + } + return result; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryArgs.h b/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryArgs.h new file mode 100644 index 0000000000..518be42388 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryArgs.h @@ -0,0 +1,81 @@ +/* Grid Story Args + * + * From: https://github.com/PokemonAutomation/ + * + * The arg kinds the tile games (FRLG, BDSP) register with the story core + * (StoryArgType::REGISTERED): a direction, a grid pose, straight legs, + * items, and the tile pose a checkpoint declares. A game puts + * grid_arg_kind() on its arg specs and passes the TILE_DECLARED kind to + * read_story_checkpoint(); its actions read the values back with + * registered_arg(), registered_arg(), ... + * + */ + +#ifndef PokemonAutomation_Pokemon_GridStoryArgs_H +#define PokemonAutomation_Pokemon_GridStoryArgs_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h" +#include "Pokemon/Navigation/Pokemon_Direction.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A straight leg of a fixed walk: {"direction": "north", "tiles": 3}. +struct StoryLeg{ + Direction direction = Direction::NORTH; + int tiles = 0; + + bool operator==(const StoryLeg& other) const = default; +}; + +// An item and how many to get: {"item": "Potion", "quantity": 2}. +struct StoryItem{ + std::string item = {}; + size_t quantity = 0; + + bool operator==(const StoryItem& other) const = default; +}; + +// A checkpoint's declared tile pose: on one of `tiles` of `map` (any tile +// when none), facing `facing` if set. +struct TileDeclared{ + std::string map = {}; + std::vector tiles = {}; + std::optional facing = {}; + + bool operator==(const TileDeclared& other) const = default; +}; + +// The registered kinds, by what they hold. +enum class GridArg{ + DIRECTION, // Direction: "north" + GRID_POSE, // GridPose: {"map": "PalletTown", "tiles": [[3, 4]], "facing": "north"} + LEGS, // std::vector + ITEMS, // std::vector + TILE_DECLARED, // TileDeclared, as a grid pose +}; + +// The kind for `arg`; it lives as long as the program. +const StoryArgKind& grid_arg_kind(GridArg arg); + +// A grid pose read from JSON; no "tiles" reads as none (any tile). +// Malformed and unknown fields throw ParseException naming `source`. +GridPose read_grid_pose(const JsonValue& value, std::string_view source); + +// Items read from JSON, [{"item": ..., "quantity": ...}]. +std::vector read_story_items(const JsonValue& value, std::string_view source); + + + +} // 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 6ec14c739c..af97d11165 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -18,6 +18,7 @@ #include "Engine/Pokemon_StoryBackend_Tests.h" #include "Engine/Pokemon_StoryEngine_Tests.h" #include "Engine/Pokemon_StorySavePolicy_Tests.h" +#include "Grid/Pokemon_GridStoryActions_Tests.h" #include "Options/Pokemon_StoryRangeOptions_Tests.h" #include "Pokemon_AutoStorySelect_Tests.h" #include "Pokemon_CheckpointAttempts_Tests.h" @@ -43,6 +44,7 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_StoryEvents(database); add_tests_StoryEngine(database); add_tests_StorySavePolicy(database); + add_tests_GridStoryActions(database); } 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_StoryCheckpoint.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h index dd8fdb7242..262a948c3e 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h @@ -10,11 +10,14 @@ #ifndef PokemonAutomation_Pokemon_StoryCheckpoint_H #define PokemonAutomation_Pokemon_StoryCheckpoint_H +#include #include #include #include +#include "Pokemon/Navigation/Pokemon_GateState.h" #include "Pokemon_DeclaredPose.h" #include "Pokemon_StoryCheckpointMetadata.h" +#include "Pokemon_StoryPostconditions.h" #include "Pokemon_StoryStep.h" namespace PokemonAutomation{ @@ -31,8 +34,29 @@ struct StoryCheckpoint{ // Its phase and verification (JSON "metadata"), which decide when a // run of it may save. StoryCheckpointMetadata metadata = {}; + // The steps' JSON ("events") as read, dumped compactly: what a hash of + // the verified steps covers. Empty for a checkpoint built in code. + std::string steps_json = {}; + // What must hold when it is done; checked on its own after a run. + // JSON: "metadata": {"postconditions": ...}. + StoryPostconditions postconditions = {}; + // Which gates are open and which switches are on at the start, where the + // save has any of the story's gates (Silph Co., Pokemon Mansion); none + // where the checkpoint does not say, which the run infers from the + // story so far, or else observes. JSON: "start_gates". + std::optional start_gates = {}; + // The run flags that hold at the start, as flags_after would have set + // them in the story so far, which a reload loses ("card_key_held" in a + // save made after the Card Key). JSON: "start_flags". + std::vector start_flags = {}; }; +// The gate state of `checkpoint` once its first `steps_done` steps are done: +// its start_gates (nothing open, no switch on if it has none) with the +// steps' gates_after applied in order. `steps_done` past the last step is +// the end. +GateState checkpoint_gates(const StoryCheckpoint& checkpoint, size_t steps_done); + } // namespace Pokemon diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointGates.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointGates.cpp new file mode 100644 index 0000000000..2a3561835c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointGates.cpp @@ -0,0 +1,28 @@ +/* Story Checkpoint Gates + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryCheckpoint.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +GateState checkpoint_gates(const StoryCheckpoint& checkpoint, size_t steps_done){ + GateState gates = checkpoint.start_gates.value_or(GateState()); + const size_t done = std::min(steps_done, checkpoint.steps.size()); + for (size_t c = 0; c < done; c++){ + if (checkpoint.steps[c].gates_after){ + apply_gate_change(gates, *checkpoint.steps[c].gates_after); + } + } + return gates; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h index 672c87e88c..c9a6637f02 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h @@ -36,9 +36,24 @@ std::string story_phase_name(StoryPhase phase); // The phase named `name`; none for another name. std::optional read_story_phase(std::string_view name); -// A checkpoint's "metadata" object. +// The runs that moved the checkpoint out of testing, as recorded. +struct StoryVerification{ + // The hash of the steps those runs ran: "sha256:". + std::string steps_hash = {}; + // The build those runs used (a commit). + std::string build = {}; + std::string date = {}; + // Passes out of runs, e.g. "3/3". + std::string runs = {}; + + bool operator==(const StoryVerification& other) const = default; +}; + +// A checkpoint's "metadata" object, less its postconditions, which the +// checkpoint keeps beside its steps (StoryCheckpoint::postconditions). struct StoryCheckpointMetadata{ StoryPhase phase = StoryPhase::TESTING; + std::optional verified = std::nullopt; // Where the steps came from: a walkthrough, a console recording. std::string source = {}; 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..9f12ea0656 --- /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/AutoStory/Grid/Pokemon_GridStoryArgs.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_StoryStep.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h index 9f3128d801..24afa319c6 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h @@ -11,7 +11,11 @@ #ifndef PokemonAutomation_Pokemon_StoryStep_H #define PokemonAutomation_Pokemon_StoryStep_H +#include #include +#include +#include "Pokemon/Navigation/Pokemon_GateState.h" +#include "Pokemon_DeclaredPose.h" #include "Pokemon_StoryActionArg.h" #include "Pokemon_StoryStepKind.h" @@ -31,7 +35,21 @@ struct StoryStep{ // 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 answers, run flags unless the game reads them off the + // screen. + std::vector skip_if = {}; + // Where the step leaves the player, when its action does not say: the + // end of a scene that moves the player. JSON: "declared_after". + std::optional pose_after = {}; + // The gates the step opens and the switches it sets + // (Pokemon/Navigation/Pokemon_GateState.h), applied to the run's gate + // state when the step is done. + std::optional gates_after = {}; + // The run flags the step sets when it is done (JSON "flags_after"): what + // the story's later steps and the planner read, as "card_key_held" after + // the Card Key is picked up, which lets plans open card-key gates. + std::vector flags_after = {}; }; diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.cpp new file mode 100644 index 0000000000..0663f79588 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.cpp @@ -0,0 +1,30 @@ +/* Direction + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_Direction.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string direction_name(Direction direction){ + switch (direction){ + case Direction::NORTH: + return "north"; + case Direction::EAST: + return "east"; + case Direction::SOUTH: + return "south"; + case Direction::WEST: + return "west"; + } + return "?"; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.h new file mode 100644 index 0000000000..5024b3ec69 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.h @@ -0,0 +1,36 @@ +/* Direction + * + * From: https://github.com/PokemonAutomation/ + * + * The four cardinal directions the player can face or move in. + * + */ + +#ifndef PokemonAutomation_Pokemon_Direction_H +#define PokemonAutomation_Pokemon_Direction_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Row 0 is the top of a map, so SOUTH increases y. +enum class Direction{ + NORTH, + EAST, + SOUTH, + WEST, +}; +// Array containing all four cardinal directions. +constexpr Direction ALL_DIRECTIONS[] = { + Direction::NORTH, Direction::EAST, Direction::SOUTH, Direction::WEST, +}; +// Returns the lowercase name string of a cardinal direction. +std::string direction_name(Direction direction); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.cpp new file mode 100644 index 0000000000..8488e7783d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.cpp @@ -0,0 +1,67 @@ +/* Gate State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_GateState.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +bool GateState::switch_on(const std::string& id) const{ + return switches_on.contains(id); +} + +std::string gate_key(const std::string& map, const std::string& gate_id){ + return map + "/" + gate_id; +} + +void apply_gate_change(GateState& state, const GateChange& change){ + state.opened.insert(change.opened.begin(), change.opened.end()); + for (const auto& [id, on] : change.switches){ + if (on){ + state.switches_on.insert(id); + }else{ + state.switches_on.erase(id); + } + } +} + +GateChange gate_change_between(const GateState& before, const GateState& after){ + GateChange change; + for (const std::string& key : after.opened){ + if (!before.opened.contains(key)){ + change.opened.insert(key); + } + } + for (const std::string& id : after.switches_on){ + if (!before.switch_on(id)){ + change.switches[id] = true; + } + } + for (const std::string& id : before.switches_on){ + if (!after.switch_on(id)){ + change.switches[id] = false; + } + } + return change; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +size_t std::hash::operator()(const PokemonAutomation::Pokemon::GateState& state) const{ + size_t hash = 0; + for (const std::string& key : state.opened){ + hash = hash * 31 + std::hash()(key); + } + for (const std::string& id : state.switches_on){ + hash = hash * 37 + std::hash()(id); + } + return hash; +} diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.h new file mode 100644 index 0000000000..b8d007d668 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.h @@ -0,0 +1,76 @@ +/* Gate State + * + * From: https://github.com/PokemonAutomation/ + * + * Which of the maps' gates (MapData::gates) are open: the card-key doors + * the player has opened, and the state of each switch. A switch is shared + * by every map that lists it as a floor (Pokemon Mansion's statue + * switch), and every gate that follows it is open or closed with it. + * + * The state is plain data, with no map in it; the story keeps it + * (Pokemon_StoryCheckpoint.h). What it makes of a map's tiles is + * Pokemon_GateTiles.h, and the gated planner (Pokemon_GatedPlanner.h) + * searches over it. + * + */ + +#ifndef PokemonAutomation_Pokemon_GateState_H +#define PokemonAutomation_Pokemon_GateState_H + +#include +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Which gates are open and which switches are on. +struct GateState{ + // The card-key gates opened, each as gate_key(map, gate id). + std::set opened; + // The switches (by id) that are on. One not here is off, as at a new game. + std::set switches_on; + + bool operator==(const GateState& other) const = default; + + bool switch_on(const std::string& id) const; +}; + +// What a story step does to the state: gates it opens and switches it sets. +// What a step does to a GateState: gates it opens, switches it sets. +struct GateChange{ + std::set opened; + // The switch's new state, on or off. + std::map switches; + + bool operator==(const GateChange& other) const = default; +}; + +// Names a gate across maps: "SilphCo_5F/door_1". +std::string gate_key(const std::string& map, const std::string& gate_id); + +// Puts `change` on `state`: its gates are opened and its switches set. +void apply_gate_change(GateState& state, const GateChange& change); + +// The change that takes `before` to `after`: the gates `after` has opened +// that `before` has not, and the switches whose state differs. A card-key +// gate does not close again, so one `before` has opened and `after` has not +// is ignored. +GateChange gate_change_between(const GateState& before, const GateState& after); + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +// A hash of GateState, for planners that keep it in the search state. +template <> +struct std::hash{ + size_t operator()(const PokemonAutomation::Pokemon::GateState& state) const; +}; + +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.cpp new file mode 100644 index 0000000000..84fa47bcb1 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.cpp @@ -0,0 +1,35 @@ +/* Grid + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +TilePos TilePos::next(Direction direction) const{ + switch (direction){ + case Direction::NORTH: + return {x, y - 1}; + case Direction::EAST: + return {x + 1, y}; + case Direction::SOUTH: + return {x, y + 1}; + case Direction::WEST: + return {x - 1, y}; + } + return *this; +} + +std::string to_string(const TilePos& pos){ + return std::format("({}, {})", pos.x, pos.y); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.h new file mode 100644 index 0000000000..6fda4044c8 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.h @@ -0,0 +1,78 @@ +/* Grid + * + * From: https://github.com/PokemonAutomation/ + * + * Tiles on an overworld grid, shared by the games that + * move the player a tile at a time. + * + */ + +#ifndef PokemonAutomation_Pokemon_Grid_H +#define PokemonAutomation_Pokemon_Grid_H + +#include +#include +#include +#include +#include +#include "Pokemon_Direction.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Grid coordinate with integer x and y components. +struct TilePos{ + int x = 0; + int y = 0; + + TilePos next(Direction direction) const; + bool operator==(const TilePos& other) const = default; + // x, then y: an order for sets and maps of tiles, not a walking order. + auto operator<=>(const TilePos& other) const = default; +}; +// Formats a TilePos as "(x, y)". +std::string to_string(const TilePos& pos); + + +// One value per tile of a map, row by row from the top. +template +struct Grid{ + int width = 0; + int height = 0; + std::vector cells; + + bool contains(const TilePos& pos) const{ + return 0 <= pos.x && pos.x < width && 0 <= pos.y && pos.y < height; + } + // `pos` must be inside the grid. + const Cell& at(const TilePos& pos) const{ + return cells[(size_t)pos.y * width + pos.x]; + } +}; +// The cell at `pos` of `grid`, to change it; `pos` must be inside the grid. +// A free function, so that Grid stays a plain value whose methods only read. +template +Cell& cell_at(const TilePos& pos, Grid& grid); + +template +Cell& cell_at(const TilePos& pos, Grid& grid){ + return grid.cells[(size_t)pos.y * grid.width + pos.x]; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +// Hash specialization for TilePos. +template <> +struct std::hash{ + size_t operator()(const PokemonAutomation::Pokemon::TilePos& pos) const{ + return std::hash()(((long long)pos.x << 32) ^ (unsigned)pos.y); + } +}; + + +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 854dc2f69d..6d7ad7b36e 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1569,7 +1569,14 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StoryOutcome.h Source/Pokemon/AutoStory/Pokemon_StoryPose.cpp Source/Pokemon/AutoStory/Pokemon_StoryPose.h + Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryActions.cpp + Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryActions.h + Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryActions_Tests.cpp + Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryActions_Tests.h + Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryArgs.cpp + Source/Pokemon/AutoStory/Grid/Pokemon_GridStoryArgs.h Source/Pokemon/AutoStory/Types/Pokemon_DeclaredPose.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 @@ -1577,13 +1584,21 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointGates.cpp Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.cpp Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryPostconditions.h Source/Pokemon/AutoStory/Types/Pokemon_StoryRegisteredArg.h 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/Navigation/Pokemon_Direction.cpp + Source/Pokemon/Navigation/Pokemon_Direction.h + Source/Pokemon/Navigation/Pokemon_GateState.cpp + Source/Pokemon/Navigation/Pokemon_GateState.h + Source/Pokemon/Navigation/Pokemon_Grid.cpp + Source/Pokemon/Navigation/Pokemon_Grid.h Source/Pokemon/Pokemon_AdvRng.cpp Source/Pokemon/Pokemon_AdvRng.h Source/Pokemon/Pokemon_BdspRng.cpp