Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ namespace Pokemon{

namespace{

constexpr std::string_view SHARED_FIELDS[] = {"save", "reload_when_chained", "dev_only"};
constexpr std::string_view SHARED_FIELDS[] = {"save", "reload_when_chained", "dev_only", "verify"};

bool is_known_field(std::string_view key, std::initializer_list<std::string_view> game_fields){
for (std::string_view field : SHARED_FIELDS){
Expand Down Expand Up @@ -74,6 +74,37 @@ bool read_dev_only(const JsonObject& execution, std::string_view where){
return true;
}

// One of verify's figures: a whole number of at least `least`.
size_t read_verify_figure(const JsonObject& verify, std::string_view name, size_t least, std::string_view where){
const int64_t value = verify.get_integer_throw(std::string(name), std::string(where));
if (value < (int64_t)least){
throw ParseException(std::format("{}: verify {} is {}, at least {}", where, name, value, least));
}
return (size_t)value;
}

std::optional<StoryVerify> read_verify(const JsonObject& execution, std::string_view where){
const JsonValue* value = execution.get_value("verify");
if (value == nullptr){
return std::nullopt;
}
const JsonObject& verify = value->to_object_throw(std::string(where));
for (const auto& [key, figure] : verify){
if (key != "tries" && key != "min_pass" && key != "reset_budget"){
throw ParseException(std::format("{}: unknown verify field {}", where, key));
}
}
StoryVerify figures{
.tries = read_verify_figure(verify, "tries", /*least=*/1, where),
.min_pass = read_verify_figure(verify, "min_pass", /*least=*/0, where),
.reset_budget = read_verify_figure(verify, "reset_budget", /*least=*/1, where),
};
if (figures.min_pass > figures.tries){
throw ParseException(std::format("{}: verify min_pass {} is more than its {} tries", where, figures.min_pass, figures.tries));
}
return figures;
}

} // namespace


Expand All @@ -89,6 +120,7 @@ StoryRowExecution read_story_row_execution(
.autosave = read_autosave(execution, where),
.reload = read_reload(execution, where),
.dev_only = read_dev_only(execution, where),
.verify = read_verify(execution, where),
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@

#include <functional>
#include <initializer_list>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "Common/Cpp/Json/JsonObject.h"
#include "Pokemon/AutoStory/Types/Pokemon_StoryVerify.h"

namespace PokemonAutomation{
namespace Pokemon{
Expand All @@ -46,10 +48,13 @@ struct StoryRowExecution{
// "dev_only": true: a lab walk the story does not need (developer
// mode lists and plays it, a user's run does not).
bool dev_only = false;
// "verify": {"tries", "min_pass", "reset_budget"}: the row runs as a
// verification loop (Pokemon_StoryVerify.h).
std::optional<StoryVerify> verify = std::nullopt;
};

// The shared fields of `execution`: "save", "reload_when_chained" and
// "dev_only", each optional. Throws ParseException naming `where` for a
// The shared fields of `execution`: "save", "reload_when_chained",
// "dev_only" and "verify", each optional. Throws ParseException naming `where` for a
// malformed one, and for a field that is neither shared nor one of
// `game_fields`, which the game reads itself.
StoryRowExecution read_story_row_execution(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
#include "Pokemon_StoryRun_Tests.h"
#include "Pokemon_StorySavePolicy_Tests.h"
#include "Pokemon_StorySegments_Tests.h"
#include "Pokemon_StoryVerifyRows_Tests.h"
#include "Pokemon_StoryStepExecutor_Tests.h"
#include "Pokemon_Transitions_Tests.h"
#include "Types/Pokemon_StoryActionArg_Tests.h"
Expand All @@ -46,7 +47,7 @@


// Registers every shared AutoStory suite, for the unit test runner.
inline void add_tests_AutoStory(UnitTestDatabase& database){

Check warning on line 50 in SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h

View workflow job for this annotation

GitHub Actions / code-health

Code health (advisory)

PokemonAutomation::Pokemon::add_tests_AutoStory( UnitTestDatabase & database): function_lines=31 (advisory above 25, limit 50)
add_tests_AutoStorySelect(database);
add_tests_StoryRun(database);
add_tests_StoryRunCounts(database);
Expand All @@ -57,6 +58,7 @@
add_tests_StoryRangeOptions(database);
add_tests_StoryEvents(database);
add_tests_StorySegments(database);
add_tests_StoryVerifyRows(database);
add_tests_StoryStepExecutor(database);
add_tests_StoryStepJson(database);
add_tests_StoryActionArg(database);
Expand Down
134 changes: 133 additions & 1 deletion SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* Story Segments

Check warning on line 1 in SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp

View workflow job for this annotation

GitHub Actions / code-health

Code health (advisory)

<file>: file_lines=506 (advisory above 500, limit 1000)
*
* From: https://github.com/PokemonAutomation/
*
Expand Down Expand Up @@ -212,6 +212,136 @@
return result;
}

// Whether a verify try that completed passes: the game's postcondition
// check, then its pass predicate.
Outcome verify_pass(const std::string& id, SegmentHooks& hooks, RunState& state){
if (hooks.check_postconditions){
const Outcome checked = hooks.check_postconditions(id, state);
if (!checked.succeeded()){
return outcome_failed("postconditions_failed", to_string(checked));
}
}
if (hooks.verify_pass){
const Outcome passed = hooks.verify_pass(id, state);
if (!passed.succeeded()){
return outcome_failed("verify_no_pass", to_string(passed));
}
}
return outcome_ok();
}

// The verification loop of a row with `verify` (run_segment()).
class VerifyRow{
public:
VerifyRow(const Row& row, const SegmentPolicy& policy, SegmentHooks& hooks, SegmentReport& report, CheckpointRun& run, RunState& state)
: m_row(row)
, m_verify(*row.spec.verify)
, m_policy(policy)
, m_hooks(hooks)
, m_report(report)
, m_run(run)
, m_state(state)
{}

CheckpointReport run(){

Check warning on line 246 in SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp

View workflow job for this annotation

GitHub Actions / code-health

Code health (advisory)

PokemonAutomation::Pokemon::VerifyRow::run(): function_lines=30 (advisory above 25, limit 50)
const std::string& id = m_row.spec.id;
say(std::format(
"[Verify] {}: phase 1, {} tries from one save, {} must pass; phase 2, up to {} tries, the first pass saved",
id, m_verify.tries, m_verify.min_pass, m_verify.reset_budget
), m_hooks);
size_t passes = 0;
for (size_t c = 1; c <= m_verify.tries; c++){
const std::optional<bool> passed = try_once(/*phase=*/1, c, m_verify.tries);
if (!passed){
return std::move(m_result);
}
passes += *passed ? 1 : 0;
}
if (passes < m_verify.min_pass){
return stop("verify_below_min_pass", std::format("phase 1 passed {} of {}, under {}", passes, m_verify.tries, m_verify.min_pass));
}
for (size_t c = 1; c <= m_verify.reset_budget; c++){
const std::optional<bool> passed = try_once(/*phase=*/2, c, m_verify.reset_budget);
if (!passed){
return std::move(m_result);
}
if (*passed){
m_run.passed = true;
say(std::format("[Verify] {}: phase 2 try {} passed and saved", id, c), m_hooks);
return std::move(m_result);
}
}
return stop("verify_out_of_budget", std::format("no pass in {} phase 2 tries", m_verify.reset_budget));
}

private:
CheckpointReport stop(std::string failure, std::string detail){
say(std::format("[Verify] {}: {}; stopping", m_row.spec.id, detail), m_hooks);
m_result = failed_report(outcome_failed(std::move(failure), std::move(detail)));
return std::move(m_result);
}

// The checkpoint built fresh; phase 1 checks the pass in place of a
// save, phase 2 before the save.
Checkpoint build(size_t phase){
Checkpoint checkpoint = m_row.spec.build();
if (phase == 1){
checkpoint.save = nullptr;
}else{
set_save(m_row, m_policy, m_hooks, checkpoint);
}
checkpoint.save = [save = std::move(checkpoint.save), id = m_row.spec.id, &hooks = m_hooks](RunState& state) mutable{
const Outcome passed = verify_pass(id, hooks, state);
if (!passed.succeeded() || !save){
return passed;
}
return save(state);
};
return checkpoint;
}

// One try, reloading the start save first after the first; whether it
// passed, or none when the loop stops (no reload, the start check
// failed, the game is not running).
std::optional<bool> try_once(size_t phase, size_t index, size_t of){

Check warning on line 306 in SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp

View workflow job for this annotation

GitHub Actions / code-health

Code health (advisory)

PokemonAutomation::Pokemon::VerifyRow::try_once( size_t phase , size_t index , size_t of): function_lines=28 (advisory above 25, limit 50)
const std::string& id = m_row.spec.id;
if (m_run.attempts > 0){
m_report.reloads++;
Outcome reloaded = reload(m_state, m_hooks);
if (!reloaded.succeeded()){
m_result = failed_report(std::move(reloaded));
return std::nullopt;
}
}
m_run.attempts++;
Checkpoint checkpoint = build(phase);
EventLogger log = [&hooks = m_hooks](const std::string& line){ say(line, hooks); };
m_result = run_checkpoint(m_state, checkpoint, log);
if (m_result.completed){
say(std::format("[Verify] {}: phase {} try {}/{} passed", id, phase, index, of), m_hooks);
return true;
}
say(std::format(
"[Verify] {}: phase {} try {}/{} failed{}: {}", id, phase, index, of,
m_result.failed_name.empty() ? "" : std::format(" at {}", m_result.failed_name), to_string(m_result.failure)
), m_hooks);
if (m_result.failure.failure == "start_failed" || m_result.failure.failure == GAME_NOT_RUNNING){
say(std::format("[Verify] {}: stopping", id), m_hooks);
return std::nullopt;
}
return false;
}

const Row& m_row;
const StoryVerify& m_verify;
const SegmentPolicy& m_policy;
SegmentHooks& m_hooks;
SegmentReport& m_report;
CheckpointRun& m_run;
RunState& m_state;
CheckpointReport m_result;
};

SegmentReport stop_segment(const std::string& id, Outcome failure, SegmentHooks& hooks, SegmentReport& report){
std::string where;
if (!report.failed_checkpoint.empty()){
Expand All @@ -228,7 +358,7 @@
} // namespace


SegmentReport run_segment(

Check warning on line 361 in SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp

View workflow job for this annotation

GitHub Actions / code-health

Code health (advisory)

PokemonAutomation::Pokemon::run_segment( const SegmentRange & range , const SegmentPolicy & policy , Segment & segment , SegmentHooks & hooks , RunState & state): function_lines=32 (advisory above 25, limit 50)
const SegmentRange& range, const SegmentPolicy& policy,
Segment& segment, SegmentHooks& hooks, RunState& state
){
Expand All @@ -246,7 +376,9 @@
report.checkpoints_run++;
report.runs.push_back(CheckpointRun{.id = spec.id});
const Row row{.spec = spec, .first = c == selected.first, .last = c == selected.last};
CheckpointReport result = run_row(segment, row, policy, hooks, report, report.runs.back(), state);
CheckpointReport result = spec.verify
? VerifyRow(row, policy, hooks, report, report.runs.back(), state).run()
: run_row(segment, row, policy, hooks, report, report.runs.back(), state);
if (!result.completed){
report.failed_checkpoint = spec.id;
report.failed_event = result.failed_name;
Expand Down
17 changes: 16 additions & 1 deletion SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@
#define PokemonAutomation_Pokemon_StorySegments_H

#include <cstddef>
#include <optional>
#include <string>
#include <vector>
#include "Common/Cpp/MoveOnlyFunction.h"
#include "Pokemon_StoryEvents.h"
#include "Pokemon_StoryLog.h"
#include "Types/Pokemon_StorySegmentTypes.h"
#include "Types/Pokemon_StoryVerify.h"

namespace PokemonAutomation{
namespace Pokemon{
Expand All @@ -31,11 +33,14 @@ namespace Pokemon{
// One row of a segment. `build` makes the checkpoint anew for each attempt.
// `saves` has the segment save the game (SegmentHooks::save) after the
// checkpoint's end check, when the checkpoint has no save of its own.
// `verify` runs the row as a verification loop (Pokemon_StoryVerify.h)
// instead of the policy's attempts.
struct CheckpointSpec{
std::string id;
std::string title;
bool saves = false;
MoveOnlyFunction<Checkpoint()> build;
std::optional<StoryVerify> verify = std::nullopt;
};

// Collection of ordered checkpoints that make up a story segment.
Expand All @@ -62,10 +67,20 @@ struct SegmentHooks{
// before a save in AFTER_VERIFICATION mode: one that failed stops the
// save and fails the run. The game logs its lines.
MoveOnlyFunction<Outcome(const std::string& checkpoint, RunState& state)> check_postconditions;
// Optional: whether a verify row's try that completed passes, by the
// game's own measure (FRLG's League: the items a fight spent within
// its caps). Run after check_postconditions.
MoveOnlyFunction<Outcome(const std::string& checkpoint, RunState& state)> verify_pass;
};

// Runs the checkpoints in `range`, in order, saving as `policy.save_mode`
// allows (story_save_allowed()). Logs through `hooks.log`,
// allows (story_save_allowed()). A row with `verify` runs its loop: phase
// 1's tries save nothing and reload between them; below min_pass the
// segment stops ("verify_below_min_pass"); phase 2 reloads and tries
// again until a try passes, which saves, or stops after reset_budget
// ("verify_out_of_budget"). A try whose start check fails stops the loop
// at once: the save does not meet the row's preconditions. Logs through
// `hooks.log`,
// around the checkpoint lines:
// [Segment] 00: start, 3 checkpoints
// [Checkpoint] 00.02: failed, resetting for attempt 2/3
Expand Down
Loading
Loading