Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ enum class ScreenEvent : uint8_t{
};
// How many ScreenEvent values there are.
constexpr size_t SCREEN_EVENT_COUNT = 11;
static_assert((size_t)ScreenEvent::SWITCH_HOME_MENU + 1 == SCREEN_EVENT_COUNT, "SWITCH_HOME_MENU is the last ScreenEvent");
// "dialog box", for the log.
std::string screen_event_name(ScreenEvent event);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@
#include <string>
#include <utility>
#include <vector>
#include "Common/Cpp/Time.h"
#include "Common/Cpp/TestRunners/UnitTest.h"
#include "CommonFramework/ImageTypes/ImageRGB32.h"
#include "ScreenEventLog.h"
#include "ScreenEventTypes.h"
#include "ScreenFades.h"
#include "ScreenEvents.h"
Expand Down Expand Up @@ -179,10 +181,99 @@ const ScreenEventsCase SCREEN_EVENTS_CASES[] = {
},
};

namespace{

// A stream of frames into a ScreenEventLog, and its describe() text.
struct ScreenEventLogCase{
struct Frame{
int ms;
std::vector<ScreenEvent> events;
};
struct Input{
size_t capacity;
std::vector<Frame> frames;
};
struct Expectation{
// describe() of the log, times from the first frame.
std::string text;
size_t dropped;
};

std::string name;
Input input;
Expectation expectation;
};

class Test_ScreenEventLog : public UnitTest{
public:
explicit Test_ScreenEventLog(ScreenEventLogCase test_case)
: UnitTest(std::format("CommonTools::ScreenEventLog - {}", test_case.name))
, m_case(std::move(test_case))
{}
virtual UnitTestResult run(Logger&, CancellableScope&) const override{
ScreenEventLog log(m_case.input.capacity);
const WallClock origin = current_time();
for (const ScreenEventLogCase::Frame& frame : m_case.input.frames){
ScreenEvents events;
for (ScreenEvent event : frame.events){
events.set(event, true);
}
log.record(events, origin + Milliseconds(frame.ms));
}
if (log.dropped() != m_case.expectation.dropped){
return std::format("dropped(): expected {}, got {}", m_case.expectation.dropped, log.dropped());
}
return expect_equal("describe()", describe(log, origin), m_case.expectation.text);
}

private:
ScreenEventLogCase m_case;
};

} // namespace

const ScreenEventLogCase SCREEN_EVENT_LOG_CASES[] = {
{
.name = "no frames",
.input = {.capacity = 8, .frames = {}},
.expectation = {.text = "no changes", .dropped = 0},
},
{
.name = "the first frame's events all rise",
.input = {.capacity = 8, .frames = {{.ms = 0, .events = {ScreenEvent::DIALOG_BOX, ScreenEvent::SCREEN_STILL}}}},
.expectation = {.text = "+0 ms dialog box rose\n+0 ms screen still rose\n", .dropped = 0},
},
{
.name = "only changes are kept, rising and falling",
.input = {.capacity = 8, .frames = {
{.ms = 0, .events = {ScreenEvent::PLAYER_CAN_MOVE}},
{.ms = 100, .events = {ScreenEvent::PLAYER_CAN_MOVE}},
{.ms = 200, .events = {ScreenEvent::FADE_BLACK}},
{.ms = 900, .events = {}},
}},
.expectation = {
.text = "+0 ms player can move rose\n+200 ms black fade rose\n+200 ms player can move fell\n+900 ms black fade fell\n",
.dropped = 0,
},
},
{
.name = "the oldest changes drop past the capacity",
.input = {.capacity = 2, .frames = {
{.ms = 0, .events = {ScreenEvent::DIALOG_BOX}},
{.ms = 100, .events = {}},
{.ms = 200, .events = {ScreenEvent::CHOICE_BOX}},
}},
.expectation = {.text = "(1 older changes dropped)\n+100 ms dialog box fell\n+200 ms choice box rose\n", .dropped = 1},
},
};

void add_tests_ScreenEvents(UnitTestDatabase& database){
for (const auto& item : SCREEN_EVENTS_CASES){
database.add<Test_ScreenEvents>(item);
}
for (const auto& item : SCREEN_EVENT_LOG_CASES){
database.add<Test_ScreenEventLog>(item);
}
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,19 +61,35 @@ void check_in_story_order(
}
}

namespace{

// Throws ParseException naming `source` unless `previous` ends on the
// game's autosave in `rows`; `run` says in whose run ("" or " in a
// user's run").
void check_reload_after(
std::optional<std::string_view> previous, const StoryRows& rows, std::string_view run, std::string_view source
){
if (!previous || !rows.autosaves.contains(*previous)){
throw ParseException(std::format(
"{}: reload_when_chained after a checkpoint that does not end on the game's autosave{}: the reload would load an older save",
source, run
));
}
}

} // namespace

void add_story_row(
std::string_view id, const StoryRowExecution& execution, RowSave start,
std::optional<std::string_view> previous_id, std::string_view source, StoryRows& rows
const PreviousRows& previous, std::string_view source, StoryRows& rows
){
if (execution.reload != StoryReload::NEVER){
if (start == RowSave::WITHOUT_SAVE){
throw ParseException(std::format("{}: reload_when_chained on a checkpoint with no save to reload", source));
}
if (!previous_id || !rows.autosaves.contains(*previous_id)){
throw ParseException(std::format(
"{}: reload_when_chained after a checkpoint that does not end on the game's autosave: the reload would load an older save",
source
));
check_reload_after(previous.in_dev_run, rows, "", source);
if (!execution.dev_only && previous.in_user_run != previous.in_dev_run){
check_reload_after(previous.in_user_run, rows, " in a user's run", source);
}
rows.reload_when_chained.emplace(id);
}
Expand Down
30 changes: 23 additions & 7 deletions SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.h
Original file line number Diff line number Diff line change
Expand Up @@ -121,13 +121,21 @@
WITHOUT_SAVE, // a new game
};

// The rows a row follows in play: in a developer's run, and in a user's,
// which skips the dev-only rows. None for the first row.
struct PreviousRows{
std::optional<std::string_view> in_dev_run;
std::optional<std::string_view> in_user_run;
};

// Adds row `id` to the sets of `rows`. Throws ParseException naming
// `source` when it reloads and starts WITHOUT_SAVE or the row before it,
// `previous_id`, does not end on the game's autosave: a reload loads the
// last save, which must be that autosave.
// `source` when it reloads and starts WITHOUT_SAVE or a row it follows
// (`previous`: in a developer's run; and in a user's, unless it is
// dev-only itself) does not end on the game's autosave: a reload loads
// the last save, which must be that autosave.
void add_story_row(
std::string_view id, const StoryRowExecution& execution, RowSave start,
std::optional<std::string_view> previous_id, std::string_view source, StoryRows& rows
const PreviousRows& previous, std::string_view source, StoryRows& rows
);

// The dev file `dev`'s row, in place of the built-in file `builtin_name`:
Expand All @@ -154,7 +162,7 @@


template <typename Checkpoint>
StoryData<Checkpoint> load_story_data(

Check warning on line 165 in SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.h

View workflow job for this annotation

GitHub Actions / code-health

Code health (advisory)

PokemonAutomation::Pokemon::load_story_data( std :: span<const EmbeddedJsonFile> builtin , std :: span<const StoryDevFile> dev_files , const StoryFileReader<Checkpoint> & reader): function_lines=49 (advisory above 25, limit 50)
std::span<const EmbeddedJsonFile> builtin, std::span<const StoryDevFile> dev_files,
const StoryFileReader<Checkpoint>& reader
){
Expand Down Expand Up @@ -182,15 +190,23 @@
return reader.plays_before(a.row.checkpoint, b.row.checkpoint);
});
}
// A reload loads the save the row before it in play ends on.
// A reload loads the save the row before it in play ends on, in a
// developer's run and in a user's.
std::optional<size_t> last_user_row;
for (auto& [row, source] : rows){
const bool new_game = reader.starts_without_save && reader.starts_without_save(row.checkpoint);
const detail::PreviousRows previous{
.in_dev_run = data.checkpoints.empty() ? std::nullopt : std::optional<std::string_view>(data.checkpoints.back().id),
.in_user_run = last_user_row ? std::optional<std::string_view>(data.checkpoints[*last_user_row].id) : std::nullopt,
};
detail::add_story_row(
row.checkpoint.id, row.execution,
new_game ? detail::RowSave::WITHOUT_SAVE : detail::RowSave::FROM_SAVE,
data.checkpoints.empty() ? std::nullopt : std::optional<std::string_view>(data.checkpoints.back().id),
source, data
previous, source, data
);
if (!row.execution.dev_only){
last_user_row = data.checkpoints.size();
}
data.checkpoints.push_back(std::move(row.checkpoint));
}
return data;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,24 @@ const LoadCase LOAD_CASES[] = {
.input = {.builtin = {{"test-01.00.plan", file_text("01.00", R"({"save": "menu"})")}, ROW_1}},
.expectation = {.error = "test-01.01.plan: reload_when_chained after a checkpoint that does not end on the game's autosave"},
},
{
.name = "reload_when_chained after a dev-only autosave row, the user's row before it not autosaving, fails",
.input = {.builtin = {
{"test-01.00.plan", file_text("01.00", R"({"save": "menu"})")},
{"test-01.005.plan", file_text("01.005", R"({"dev_only": true, "save": "autosave"})")},
ROW_1,
}},
.expectation = {.error = "test-01.01.plan: reload_when_chained after a checkpoint that does not end on the game's autosave in a user's run"},
},
{
.name = "reload_when_chained after a dev-only row, both rows before it autosaving",
.input = {.builtin = {
ROW_0,
{"test-01.005.plan", file_text("01.005", R"({"dev_only": true, "save": "autosave"})")},
ROW_1,
}},
.expectation = {.summary = "rows 01.00 01.005 01.01 | titles Row Row Row | autosave 01.00 01.005 | chained 01.01 | always | dev_only 01.005 | dev "},
},
{
.name = "reload_when_chained on the first row fails",
.input = {.builtin = {ROW_1}},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -323,8 +323,10 @@
return result;
}

StoryStep read_story_step(const JsonValue& value, std::string_view source, std::span<const StoryActionSpec> actions){

Check warning on line 326 in SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp

View workflow job for this annotation

GitHub Actions / code-health

Code health (advisory)

PokemonAutomation::Pokemon::read_story_step( const JsonValue & value , std :: string_view source , std :: span<const StoryActionSpec> actions): function_lines=28 (advisory above 25, limit 50)
const JsonObject& root = fields(value, {"id", "kind", "why", "action", "args", "skip_if", "declared_after"}, source);
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()){
Expand All @@ -344,6 +346,9 @@
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;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,12 @@ const WireCase CASES[] = {
return expect(step.kind == StoryStepKind::GAME && step.why == "source reason" && step.action == "profile"
&& step.skip_if == std::vector<std::string>{"flag"} && step.pose_after == after, "every shared field read");
}}},
{.input = {.name = "once per save", .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");
}}},
{.input = {.name = "every time by default", .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");
}}},
{.input = {.name = "route fills its fallback", .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");
Expand Down
6 changes: 3 additions & 3 deletions SerialPrograms/Source/Pokemon/AutoStory/Engine/MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,13 @@ Each move deletes that game's executor; the last one deletes `StoryStepExecutor`
readers.
- **PLZA** (ZonePose, in the engine with its instantiations and `observed_state()`): a declared
pose (`"start"`, a step's `"declared_after"`) is a place, `{"place": "HotelZ"}` with an
optional `"spot"` and `"heading"` (`ZoneDeclared`, read by
`StoryPoseTraits<ZonePose>::from_declared()`). Walks are `TIMED_LEGS` args; tile args fail
optional `"spot"` and `"heading"` (`ZoneDeclared`). The run keeps only the place, as a map
with no tiles; spot and heading wait for a position reader. Walks are `TIMED_LEGS` args; tile args fail
the lint. Turns are `stick()` after the camera recenter; the minimap arrow is the
`"heading"` reading.

A new pose type: a struct with `pose_matches` / `pose_text`, a `StoryPoseTraits` specialization
(`TILE_MOVES`, `Declared`, `from_declared()`), and an explicit instantiation line in each engine
(`TILE_MOVES`, `Declared`), and an explicit instantiation line in each engine
`.cpp`.

## Moves in shared code when the last executor goes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,12 @@

// `game` with its SAVE step "save" saving `current` only while `mode` is
// PER_CHECKPOINT: a checkpoint under test or verification must not save
// part-way.
// part-way. Sets `saved` when it saves.
template <StoryPose PoseType>
StoryGame<PoseType> with_gated_save_step(
StoryGame<PoseType> game, const StorySaveMode& mode, const StoryCheckpoint* const& current
StoryGame<PoseType> game, const StorySaveMode& mode, const StoryCheckpoint* const& current, bool& saved
){
StoryActionHandler<PoseType> gated = [&mode, &current, save = game.save](
StoryActionHandler<PoseType> gated = [&mode, &current, &saved, save = game.save](
StoryBackend<PoseType>& backend, const StoryActionCall&, RunState&
){
if (mode != StorySaveMode::PER_CHECKPOINT){
Expand All @@ -83,7 +83,9 @@
if (!save || current == nullptr){
return outcome_failed("unsupported_step", "save needs StoryGame::save");
}
return save(backend, *current);
Outcome outcome = save(backend, *current);
saved = saved || outcome.succeeded();
return outcome;
};
game.actions.push_back({.spec = {.kind = StoryStepKind::SAVE, .name = "save", .args = {}}, .handler = std::move(gated)});
return game;
Expand Down Expand Up @@ -181,7 +183,7 @@

template <StoryPose PoseType>
StoryEngine<PoseType>::StoryEngine(const StoryGame<PoseType>& game, StoryBackend<PoseType>& backend)
: m_game(with_gated_save_step(game, m_save_mode, m_checkpoint))
: m_game(with_gated_save_step(game, m_save_mode, m_checkpoint, m_saved_part_way))
, m_backend(backend)
, m_registry(m_game)
, m_runner(m_registry, backend)
Expand All @@ -202,7 +204,7 @@
}

template <StoryPose PoseType>
StoryEngineReport StoryEngine<PoseType>::run_once(

Check warning on line 207 in SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp

View workflow job for this annotation

GitHub Actions / code-health

Code health (advisory)

PokemonAutomation::Pokemon::StoryEngine<PoseType>::run_once( const StoryCheckpoint & checkpoint , SavePoint point , SaveGate gate , RunState & state): function_lines=36 (advisory above 25, limit 50)
const StoryCheckpoint& checkpoint, SavePoint point, SaveGate gate, RunState& state
){
StoryEngineReport report;
Expand All @@ -222,7 +224,9 @@
m_backend.log(report.save.reason);
m_save_mode = report.save.mode;
m_checkpoint = &checkpoint;
m_saved_part_way = false;
report.run = run_steps(checkpoint, state);
report.saved_part_way = m_saved_part_way;
m_save_mode = StorySaveMode::NONE;
m_checkpoint = nullptr;
if (!report.run.completed){
Expand Down Expand Up @@ -254,7 +258,7 @@
}

template <StoryPose PoseType>
StoryEngineReport StoryEngine<PoseType>::run_with_retries(

Check warning on line 261 in SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp

View workflow job for this annotation

GitHub Actions / code-health

Code health (advisory)

PokemonAutomation::Pokemon::StoryEngine<PoseType>::run_with_retries( const StoryCheckpoint & checkpoint , SavePoint point , size_t attempts , RunState & state , CheckpointRun & run): function_lines=39 (advisory above 25, limit 50)
const StoryCheckpoint& checkpoint, SavePoint point, size_t attempts, RunState& state, CheckpointRun& run
){
StoryEngineReport report;
Expand All @@ -266,6 +270,13 @@
if (report.verdict == CheckpointVerdict::PASSED){
return AttemptResult::PASSED;
}
if (report.saved_part_way){
m_backend.log(std::format(
"[Checkpoint] {}: a save step saved part-way, so a reload would not return to its start: no retry",
checkpoint.id
));
return AttemptResult::FINAL;
}
return repeats_on_reload(report.run.failure) ? AttemptResult::FINAL : AttemptResult::FAILED;
},
.reset = [&](size_t next_attempt){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,10 @@ class StoryEngine{
// `attempts_per_checkpoint` runs, only when a reload returns to the
// save it started from: the first checkpoint's, or one the checkpoint
// before it saved at its end. In none and after_verification modes
// (#329) that leaves only the first. No reload either for a failure
// every attempt would repeat: a lint, a console_only action, the game
// not running. Logs "[Segment] <id>: ..." lines.
// that leaves only the first. No reload once a SAVE step has saved
// part-way through the attempt (the reload would land there), nor for
// a failure every attempt would repeat: a lint, a console_only action,
// the game not running. Logs "[Segment] <id>: ..." lines.
SegmentReport run_segment(
std::string_view id, std::span<const StoryCheckpoint> checkpoints, size_t attempts_per_checkpoint,
RunState& state
Expand Down Expand Up @@ -109,9 +110,11 @@ class StoryEngine{
const StoryCheckpoint& checkpoint, SavePoint point, size_t attempts, RunState& state, CheckpointRun& run
);

// Declared first: m_game's save step reads them.
// Declared first: m_game's save step reads them, and sets
// m_saved_part_way when it saves.
StorySaveMode m_save_mode = StorySaveMode::NONE;
const StoryCheckpoint* m_checkpoint = nullptr;
bool m_saved_part_way = false;
StoryGame<PoseType> m_game;
StoryBackend<PoseType>& m_backend;
StoryActionRegistry<PoseType> m_registry;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ struct StoryEngineReport{
// Checked after steps that completed.
std::optional<PostconditionReport> postconditions = std::nullopt;
bool saved = false;
// A SAVE step among its steps saved: a reload now returns there, not
// to the save the checkpoint started from.
bool saved_part_way = false;
};


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ const EngineCase ENGINE_CASES[] = {
{.name = "failed run never saves", .input = {.phase = "reproduction", .end_map = ""},
.expectation = {.mode = StorySaveMode::PER_CHECKPOINT, .verdict = CheckpointVerdict::FAILED, .saves = 0,
.line = "[Save] 00.31: run failed: not saved"}},
{.name = "save step skipped while testing", .input = {.phase = "testing", .steps = SAVE_STEPS},
.expectation = {.mode = StorySaveMode::NONE, .saves = 0, .line = "[Save] save step skipped: save mode none"}},
{.name = "save step skipped while verifying", .input = {.phase = "verification", .steps = SAVE_STEPS},
.expectation = {.mode = StorySaveMode::AFTER_VERIFICATION, .saves = 1, .line = "[Save] save step skipped: save mode after_verification"}},
{.name = "save step saves in reproduction", .input = {.phase = "reproduction", .steps = SAVE_STEPS},
Expand Down
Loading
Loading