From e42f03c3cb682f265d3f1207e87d386645071f4e Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 12:55:21 -0800 Subject: [PATCH 01/13] BDSP AutoStory: a disturbed story sim over pinned seeds (Monte Carlo) Each story row runs on the story simulation once per pinned seed, disturbed as the console disturbs it: wild battles on grass and in caves, drift off the tile grid on taps, stick presses and holds stopped short of a wall, the maps' wanderers with a seed and start each, and sometimes one missed fade or banner. Each row's test logs its pass rate and, per failing step, the failure kinds with a reproducing seed, and fails under its pinned floor. PA_BDSP_STORY_MC_SEEDS and PA_BDSP_STORY_MC_ROWS run a heavier set. The seeds, the per-seed plan, the runner and the report are game-agnostic (Pokemon/AutoStory/Pokemon_StoryMonteCarlo); the BDSP binding is SimDisturbance over GridSim and SimExecutor, which moves from the story sim tests into PokemonBDSP_AutoStory_StorySim.h/.cpp. The old 01.03 (before be57db157 and 4f13c19bb) must fail off Roark's row after a wild battle and at the Center's door. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryMonteCarlo.cpp | 166 +++++ .../AutoStory/Pokemon_StoryMonteCarlo.h | 150 +++++ .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 2 + .../PokemonBDSP_AutoStory_SimDisturbance.cpp | 309 +++++++++ .../PokemonBDSP_AutoStory_SimDisturbance.h | 116 ++++ ...onBDSP_AutoStory_StoryMonteCarlo_Tests.cpp | 279 ++++++++ ...emonBDSP_AutoStory_StoryMonteCarlo_Tests.h | 29 + .../PokemonBDSP_AutoStory_StorySim.cpp | 460 +++++++++++++ .../PokemonBDSP_AutoStory_StorySim.h | 319 +++++++++ .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 620 +----------------- SerialPrograms/cmake/SourceFiles.cmake | 8 + 11 files changed, 1839 insertions(+), 619 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp new file mode 100644 index 0000000000..302bd3d0de --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp @@ -0,0 +1,166 @@ +/* Story Monte Carlo + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Pokemon_StoryMonteCarlo.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +uint64_t SimRandom::next(){ + m_state += 0x9e3779b97f4a7c15ULL; + uint64_t z = m_state; + z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL; + z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL; + return z ^ (z >> 31); +} +double SimRandom::uniform(){ + return (double)(next() >> 11) / (double)(1ULL << 53); +} +int64_t SimRandom::between(int64_t lo, int64_t hi){ + if (hi <= lo){ + return lo; + } + return lo + (int64_t)(next() % (uint64_t)(hi - lo + 1)); +} +bool SimRandom::chance(double p){ + return uniform() < p; +} + + +DisturbancePlan make_disturbance_plan(uint64_t seed, const DisturbanceRates& rates, size_t fades, size_t banners){ + SimRandom root(seed); + DisturbancePlan plan{ + .seed = seed, + .rates = rates, + .battles = SimRandom(root.next()), + .drift = SimRandom(root.next()), + .wanderers = SimRandom(root.next()), + .missed_fade = std::nullopt, + .missed_banner = std::nullopt, + }; + SimRandom misses(root.next()); + if (fades + banners > 0 && misses.chance(rates.missed_detection)){ + const size_t which = (size_t)misses.between(0, (int64_t)(fades + banners) - 1); + if (which < fades){ + plan.missed_fade = which; + }else{ + plan.missed_banner = which - fades; + } + } + return plan; +} + +std::string describe(const DisturbancePlan& plan){ + std::string text = std::format("seed {}", plan.seed); + if (plan.missed_fade){ + text += std::format(": miss fade {}", *plan.missed_fade); + } + if (plan.missed_banner){ + text += std::format(": miss banner {}", *plan.missed_banner); + } + return text; +} + + +std::vector story_seeds(size_t count){ + std::vector seeds; + SimRandom pinned(20261108); + for (size_t i = 0; i < count; i++){ + // Short enough to type into a reproduction. + seeds.push_back(pinned.next() % 1000000); + } + return seeds; +} + +size_t seed_count(const char* name, size_t fallback){ + const char* value = std::getenv(name); + if (value == nullptr){ + return fallback; + } + const long long count = std::atoll(value); + return count > 0 ? (size_t)count : fallback; +} + +std::vector selected_rows(const char* name, const std::vector& rows){ + const char* value = std::getenv(name); + if (value == nullptr || *value == '\0'){ + return rows; + } + const std::string wanted = std::string(",") + value + ","; + std::vector out; + for (const std::string& row : rows){ + if (wanted.find("," + row + ",") != std::string::npos){ + out.push_back(row); + } + } + return out; +} + + +std::string failure_kind(std::string_view failure, std::string_view message, size_t limit){ + std::string text(failure); + if (!message.empty()){ + text += ": "; + text += message; + } + std::string kind; + for (char c : text){ + const bool digit = std::isdigit((unsigned char)c) != 0; + if (!digit){ + kind += c; + }else if (kind.empty() || kind.back() != '#'){ + kind += '#'; + } + } + return kind.size() > limit ? kind.substr(0, limit) + "..." : kind; +} + + +RowReport run_row_seeds(const std::string& row, const std::vector& seeds, const SeedRun& run){ + RowReport report{.row = row}; + for (uint64_t seed : seeds){ + const SeedOutcome outcome = run(row, seed); + report.runs++; + if (outcome.passed){ + report.passes++; + continue; + } + KindCount& count = report.failures[outcome.failed_step][outcome.kind]; + if (count.runs++ == 0){ + count.seed = seed; + count.detail = outcome.detail; + } + } + return report; +} + +std::vector run_seeds(const std::vector& rows, const std::vector& seeds, const SeedRun& run){ + std::vector reports; + for (const std::string& row : rows){ + reports.push_back(run_row_seeds(row, seeds, run)); + } + return reports; +} + +std::string format_report(const RowReport& report){ + const double rate = report.runs == 0 ? 0.0 : 100.0 * (double)report.passes / (double)report.runs; + std::string text = std::format("{}: {}/{} passed ({:.0f}%)", report.row, report.passes, report.runs, rate); + for (const auto& [step, kinds] : report.failures){ + for (const auto& [kind, count] : kinds){ + text += std::format("\n {} x{}: {} (seed {}; {})", step, count.runs, kind, count.seed, count.detail); + } + } + return text; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h new file mode 100644 index 0000000000..f91e8e813d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h @@ -0,0 +1,150 @@ +/* Story Monte Carlo + * + * From: https://github.com/PokemonAutomation/ + * + * Runs story rows on a game's simulation many times, each time disturbed + * the way the console disturbs a run: wild battles at random moments on + * encounter tiles, a walk that ends part of a tile off, someone wandering + * into the way, a fade or a banner that goes unseen. Each run is one seed + * of a pinned list, so a failure found is a failure reproduced: the report + * gives, per row, the pass rate and, per failing step, its failure kinds + * with a seed that shows each. + * + * Game-agnostic: a game binds it by running one row for one seed's + * DisturbancePlan (a SeedRun) on its own simulation. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryMonteCarlo_H +#define PokemonAutomation_Pokemon_StoryMonteCarlo_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A deterministic random stream (splitmix64): the same seed draws the same +// numbers on every platform. +class SimRandom{ +public: + explicit SimRandom(uint64_t seed = 0) + : m_state(seed) + {} + + uint64_t next(); + // Uniform in [0, 1). + double uniform(); + // Uniform in [lo, hi], both inclusive. + int64_t between(int64_t lo, int64_t hi); + // True with probability `p`. + bool chance(double p); + +private: + uint64_t m_state; +}; + + +// How hard a run is disturbed. The rates are per tile the player enters. +struct DisturbanceRates{ + // A wild battle on an encounter tile: Gen IV's rate / 180 a step, with + // the routes' grass at 30 and Oreburgh Mine's caves at 10 (assumed for + // BDSP; the console has not measured them). + double grass_encounter = 30.0 / 180; + double cave_encounter = 10.0 / 180; + // Where a walk that does not end at a wall ends, along its way: off by + // up to this many thousandths of a tile per tile walked, uniformly. + int drift_per_tile = 150; + // Off by no more than this, the player still fits a one-tile gap (a + // door, a corridor); past it the player covers two tiles. Assumed: a + // door frame stopped a player 0.375 tile off (the grid sim's measure). + int fit = 250; + // Someone wandering starts their walk up to this far into it. + Milliseconds wanderer_start = Milliseconds(10000); + // The chance a seed misses one of the row's fades or banners. + double missed_detection = 0.25; +}; + +// One seed's disturbances: independent random streams for each kind, so a +// change in how many battles a run draws does not move its drift, and the +// one detection the run misses, if any (as an index into the row's fades, +// then its banners, from an undisturbed run). +struct DisturbancePlan{ + uint64_t seed = 0; + DisturbanceRates rates; + SimRandom battles; + SimRandom drift; + SimRandom wanderers; + std::optional missed_fade; + std::optional missed_banner; +}; +// The plan for `seed`, for a row whose undisturbed run looks for `fades` +// fades and `banners` banners. +DisturbancePlan make_disturbance_plan(uint64_t seed, const DisturbanceRates& rates, size_t fades, size_t banners); +// "seed 17: miss fade 1": what a plan draws up front, to reproduce it. +std::string describe(const DisturbancePlan& plan); + + +// The pinned seeds: the same `count` seeds on every run, the first of a +// longer list the first of a shorter one. +std::vector story_seeds(size_t count); +// The seed count to run: `fallback`, or the environment variable `name` +// when it holds a positive number (the heavy, on-demand mode). +size_t seed_count(const char* name, size_t fallback); +// The rows to run: all of `rows`, or those the environment variable +// `name` lists (comma-separated ids), in `rows`' order. +std::vector selected_rows(const char* name, const std::vector& rows); + + +// What one seed's run of a row did. +struct SeedOutcome{ + bool passed = false; + // The step it failed in, and how ("short_leg", "sim_failure: no door + // north of (#, #)"): numbers become '#', so runs that failed the same + // way group together. + std::string failed_step; + std::string kind; + // The failure as it was, for the seed that shows it first. + std::string detail; +}; +// `failure: message` with digit runs as '#', at most `limit` characters. +std::string failure_kind(std::string_view failure, std::string_view message, size_t limit = 90); + +// Runs row `row` once, disturbed by `seed`. +using SeedRun = std::function; + +// One failure kind of a step: how often, and the first seed that shows it. +struct KindCount{ + size_t runs = 0; + uint64_t seed = 0; + std::string detail; +}; +// A row's runs over the seeds. +struct RowReport{ + std::string row; + size_t runs = 0; + size_t passes = 0; + // By failed step, then by kind. + std::map> failures; +}; +// Runs `row` once for each of `seeds`. +RowReport run_row_seeds(const std::string& row, const std::vector& seeds, const SeedRun& run); +// Runs each of `rows` for each of `seeds`, in order. +std::vector run_seeds(const std::vector& rows, const std::vector& seeds, const SeedRun& run); +// "01.03: 41/50 passed (82%)", then a line per failing step and kind +// with its count and seed. +std::string format_report(const RowReport& report); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index 72c29a2fa1..7087e670ee 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -14,6 +14,7 @@ #include "Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h" +#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.h" @@ -40,6 +41,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_GridSim(database); add_tests_AutoStory_RecoveryWalk(database); add_tests_AutoStory_StorySim(database); + add_tests_AutoStory_StoryMonteCarlo(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp new file mode 100644 index 0000000000..4076fef942 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp @@ -0,0 +1,309 @@ +/* BDSP AutoStory - Disturbances on the grid simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP_AutoStory_SimDisturbance.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::TileKind; +using Pokemon::TilePos; + + +namespace{ + +// The caves on the story's way, where every tile has wild Pokemon. +constexpr const char* CAVE_MAPS[] = {"OreburghMineB1F", "OreburghMine", "RavagedPath"}; +// How often a wanderer tries a step (the grid sim's default). +constexpr Milliseconds WANDER_STEP = 2000ms; +// Drift comes in steps of this many thousandths of a tile: 4 ms of stick +// across, 6 ms up or down, so the grid sim puts it back on the grid exactly. +constexpr int DRIFT_STEP = 25; + +bool across(Direction direction){ + return direction == Direction::EAST || direction == Direction::WEST; +} +// The player's offset from their nearest tile along an axis. +int offset_of(const SimPos& pos, bool along_x){ + const TilePos tile = nearest_tile(pos); + return along_x ? pos.x - tile.x * SIM_TILE : pos.y - tile.y * SIM_TILE; +} +int along(const SimPos& pos, Direction direction){ + return across(direction) ? pos.x : pos.y; +} +bool wanderer_on(const GridSim& sim, const TilePos& pos){ + const std::vector& people = sim_wanderers(sim); + return std::any_of(people.begin(), people.end(), [&](const SimWanderer& person){ return person.pos == pos; }); +} +// Whether the player can drift a little toward `direction`: the tile there +// is open ground with nobody on it, not a wall or a door. +bool room_toward(const GridSim& sim, Direction direction){ + const TilePos next = nearest_tile(sim.player().pos).next(direction); + const std::optional tile = sim.world().tile(next); + return tile && *tile != TileKind::DOOR && standable(sim.world(), next) && !wanderer_on(sim, next); +} +// A hold that stopped against what is in its way, not against a person. +bool stopped_at_wall(const GridSim& sim, const SimMove& move, Direction direction){ + return move.stop == SimStop::BLOCKED && !wanderer_on(sim, nearest_tile(sim.player().pos).next(direction)); +} + +bool in_cave(const StoryWorld& world, const TilePos& pos){ + const std::optional tile = world.to_local(pos); + return tile && std::ranges::any_of(CAVE_MAPS, [&](const char* map){ return tile->map == story_banner_name(map); }); +} + +// Whether `box` of `map` holds `pos`. +bool holds(const Pokemon::TileBox& box, const TilePos& pos){ + return box.x0 <= pos.x && pos.x <= box.x1 && box.y0 <= pos.y && pos.y <= box.y1; +} + +WalkStop walk_stop(SimStop stop){ + switch (stop){ + case SimStop::BLOCKED: + return WalkStop::BLOCKED; + case SimStop::DIALOG: + return WalkStop::DIALOG; + case SimStop::WARP: + return WalkStop::TRANSITION; + case SimStop::DONE: + case SimStop::LIMIT: + return WalkStop::LIMIT; + } + return WalkStop::LIMIT; +} + +} // namespace + + +SimDisturbance::SimDisturbance(Pokemon::DisturbancePlan plan) + : m_plan(std::move(plan)) +{} + +bool SimDisturbance::battle_at(const StoryWorld& world, const TilePos& pos){ + const std::optional tile = world.tile(pos); + if (!tile){ + return false; + } + const double rate = *tile == TileKind::TALL_GRASS ? m_plan.rates.grass_encounter + : in_cave(world, pos) ? m_plan.rates.cave_encounter : 0; + if (rate <= 0 || !m_plan.battles.chance(rate)){ + return false; + } + m_battles++; + return true; +} + +void SimDisturbance::reset(){ + m_x = {}; + m_y = {}; +} + +// The grid sim's position is the truth: a wall it stopped at, or a place +// the executor put the player, changes the offset, and the drift with it. +void SimDisturbance::sync(const GridSim& sim){ + for (bool along_x : {true, false}){ + Axis& axis = along_x ? m_x : m_y; + const int actual = offset_of(sim.player().pos, along_x); + if (actual != axis.applied){ + axis.drift = actual; + axis.applied = actual; + } + } +} + +void SimDisturbance::walked(GridSim& sim, Direction direction, int thousandths, bool at_wall){ + sync(sim); + Axis& axis = across(direction) ? m_x : m_y; + if (at_wall){ + axis.drift = axis.applied; + return; + } + // In steps of DRIFT_STEP, which a stick press moves exactly. + const int64_t most = m_plan.rates.drift_per_tile / DRIFT_STEP; + const int64_t steps = m_plan.drift.between(-most, most) * thousandths / SIM_TILE; + axis.drift = std::clamp(axis.drift + (int)steps * DRIFT_STEP, -SIM_TILE + 100, SIM_TILE - 100); + materialize(sim, across(direction)); +} + +// Puts the drift past `fit` on the grid sim's position, with a stick press +// that far, and turns back the way the player faced. A wall or a door in +// the way absorbs it. +void SimDisturbance::materialize(GridSim& sim, bool along_x){ + Axis& axis = along_x ? m_x : m_y; + const int target = std::abs(axis.drift) > m_plan.rates.fit ? axis.drift : 0; + const int delta = target - axis.applied; + if (delta == 0){ + return; + } + const Direction direction = along_x ? (delta > 0 ? Direction::EAST : Direction::WEST) + : (delta > 0 ? Direction::SOUTH : Direction::NORTH); + if (!room_toward(sim, direction)){ + axis.drift = axis.applied; + return; + } + const Direction facing = sim.player().facing; + const SimPos before = sim.player().pos; + const Milliseconds tile_time = route_ms_per_tile(direction, MoveSpeed::WALK); + sim.tap(direction, Milliseconds((std::abs(delta) * tile_time.count() + SIM_TILE / 2) / SIM_TILE), true); + const int moved = along(sim.player().pos, direction) - along(before, direction); + axis.applied += moved; + if (std::abs(moved - delta) >= DRIFT_STEP){ + axis.drift = axis.applied; + } + sim.tap(facing, ROUTE_TURN_TAP, false); +} + +// The maps' wanderers on `world`, found from its wandering tiles: each +// tile's map, and who on that map wanders over it. +const std::vector& SimDisturbance::people(const StoryWorld& world){ + auto found = m_people.find(&world); + if (found != m_people.end()){ + return found->second; + } + std::vector& people = m_people[&world]; + for (const TilePos& pos : wandering_hazards(world)){ + const std::optional tile = world.to_local(pos); + for (const auto& [name, json] : bdsp_map_json()){ + if (!tile || story_banner_name(name) != tile->map){ + continue; + } + add_people(people, name, {pos.x - tile->pos.x, pos.y - tile->pos.y}, tile->pos); + } + } + return people; +} + +// Who on `map` (its tile (0, 0) at world tile `corner`) wanders over its +// tile `local`, if not in `people` yet. +void SimDisturbance::add_people(std::vector& people, const std::string& map, const TilePos& corner, const TilePos& local){ + for (const Pokemon::MapObject& object : story_map(map).objects){ + const std::string name = map + "/" + object.name; + const bool known = std::ranges::any_of(people, [&](const SimWanderer& person){ return person.name == name; }); + if (!object.wander || object.hide_flag || known || !holds(*object.wander, local)){ + continue; + } + const Pokemon::TileBox& box = *object.wander; + people.push_back({.name = name, .box = {corner.x + box.x0, corner.y + box.y0, corner.x + box.x1, corner.y + box.y1}, + .pos = {corner.x + object.x, corner.y + object.y}, .step_interval = WANDER_STEP}); + } +} + +std::vector SimDisturbance::wanderers(const StoryWorld& world){ + std::vector out = people(world); + for (SimWanderer& person : out){ + person.seed = m_plan.wanderers.next(); + person.time_offset = Milliseconds(m_plan.wanderers.between(0, m_plan.rates.wanderer_start.count())); + } + return out; +} + + +DisturbedHold disturbed_hold(GridSim& sim, SimDisturbance* noise, Direction direction, Milliseconds limit, SimPace pace){ + if (noise == nullptr){ + return {.move = sim.hold(direction, limit, pace)}; + } + const bool runs = pace == SimPace::RUN && sim.player().can_run; + const Milliseconds tile_time = route_ms_per_tile(direction, runs ? MoveSpeed::RUN : MoveSpeed::WALK); + const int64_t tiles = limit < ROUTE_START_DELAY ? 0 : (limit - ROUTE_START_DELAY) / tile_time; + DisturbedHold out{.move = {.stop = SimStop::LIMIT}}; + for (int64_t i = 0; i < tiles && out.move.stop == SimStop::LIMIT; i++){ + const SimMove step = sim.hold(direction, ROUTE_START_DELAY + tile_time, pace); + out.move.distance += step.distance; + out.move.stop = step.stop; + if (step.stop == SimStop::LIMIT && noise->battle_at(sim.world(), nearest_tile(sim.player().pos))){ + out.battles++; + out.first_tile |= i == 0; + } + } + if (out.move.stop == SimStop::LIMIT){ + out.move.time = limit; + }else{ + const Milliseconds seen = out.move.stop == SimStop::BLOCKED ? 800ms : 0ms; + out.move.time = ROUTE_START_DELAY + tile_time * out.move.distance / SIM_TILE + seen; + } + if (out.move.stop == SimStop::LIMIT || out.move.stop == SimStop::BLOCKED){ + noise->walked(sim, direction, SIM_TILE, stopped_at_wall(sim, out.move, direction)); + } + return out; +} + + +WalkResult DisturbedRouteIO::walk_to_wall(const RouteWallWalk& walk){ + if (m_noise == nullptr){ + return GridSimRouteIO::walk_to_wall(walk); + } + const SimPace pace = walk.options.pace == DpadPace::RUN ? SimPace::RUN : SimPace::WALK; + const DisturbedHold hold = disturbed_hold(m_sim, m_noise, walk.direction, walk.limit, pace); + m_notes.push_back(std::format("[Sim] {}: held {} to {} at {}, {} wild battle(s).", walk.label, direction_name(walk.direction), + sim_stop_name(hold.move.stop), to_string(m_sim.player().pos), hold.battles)); + WalkResult result{.stop = walk_stop(hold.move.stop), .walked = hold.move.time, .wild_battles = hold.battles, + .moved_chunks = (size_t)(hold.move.distance / SIM_TILE)}; + if (hold.first_tile){ + result.origin = WalkOrigin::MAY_PRECEDE_LEG; + } + return result; +} + +// A tap a tile, as GridSimRouteIO taps; a battle on a tile stepped onto +// is fled and credited as a moved tile, as the console's walk credits it, +// and the taps go on. One on the first tap may have begun before it. +WalkResult DisturbedRouteIO::walk_taps(Direction direction, size_t tiles, const std::string& label){ + if (m_noise == nullptr){ + return GridSimRouteIO::walk_taps(direction, tiles, label); + } + WalkResult result{.stop = WalkStop::LIMIT, .walked = 0ms, .wild_battles = 0, .moved_chunks = 0}; + size_t still = 0; + for (size_t tap = 0; tap < tiles && result.stop == WalkStop::LIMIT; tap++){ + const SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + result.walked += 800ms; + still = move.distance > 0 ? 0 : still + 1; + result.moved_chunks += move.distance > 0 ? 1 : 0; + if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ + result.stop = walk_stop(move.stop); + }else if (still >= 2){ + result.stop = WalkStop::BLOCKED; + } + if (move.distance > 0 && result.stop == WalkStop::LIMIT){ + m_noise->walked(m_sim, direction, SIM_TILE, false); + } + if (move.distance > 0 && move.stop == SimStop::DONE && m_noise->battle_at(m_sim.world(), nearest_tile(m_sim.player().pos))){ + result.wild_battles++; + result.origin = tap == 0 ? WalkOrigin::MAY_PRECEDE_LEG : result.origin; + m_notes.push_back("[Sim] wild battle during " + label); + } + } + m_notes.push_back(std::format("[Sim] {}: {} taps {}, {} moved, {} at {}.", label, tiles, direction_name(direction), + result.moved_chunks, walk_stop_name(result.stop), to_string(m_sim.player().pos))); + return result; +} + +// A stick press drifts with the tiles it moves. +void DisturbedRouteIO::press(const RouteInput& input){ + const SimPos before = m_sim.player().pos; + GridSimRouteIO::press(input); + if (m_noise == nullptr || input.kind != RouteInputKind::STICK){ + return; + } + const int moved = std::abs(along(m_sim.player().pos, input.direction) - along(before, input.direction)); + if (moved > 0){ + m_noise->walked(m_sim, input.direction, moved, false); + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.h new file mode 100644 index 0000000000..978a31d4e3 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.h @@ -0,0 +1,116 @@ +/* BDSP AutoStory - Disturbances on the grid simulation + * + * From: https://github.com/PokemonAutomation/ + * + * One seed's disturbances (Pokemon::DisturbancePlan) played on a GridSim, + * as the console disturbs a run: + * + * - A wild battle on tall grass, or anywhere in a cave (Oreburgh Mine, + * the Ravaged Path), once the player has stepped onto the tile. It is + * fled, and the input goes on, as the console's walks go on. + * - Drift: a tap, a stick press or a hold stopped short of a wall ends + * up to DisturbanceRates::drift_per_tile off along its way, and taps + * add up. Within DisturbanceRates::fit of the tile the player still + * fits a one-tile gap; past it, the grid sim has them part of a tile + * off, where a door frame or a rock's corner stops them. A walk that + * stops at a wall ends on its tile, and on the grid along that way. + * - The people who wander on the maps (MapObject::wander) walk about, + * each from a seed and a start of the plan's. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_SimDisturbance_H +#define PokemonAutomation_PokemonBDSP_AutoStory_SimDisturbance_H + +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h" +#include "PokemonBDSP_AutoStory_GridSim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// A seed's disturbances on a GridSim. Not thread-safe; one per run. +class SimDisturbance{ +public: + explicit SimDisturbance(Pokemon::DisturbancePlan plan); + + const Pokemon::DisturbancePlan& plan() const{ + return m_plan; + } + // Wild battles drawn so far. + size_t battles() const{ + return m_battles; + } + // Whether stepping onto world tile `pos` starts a wild battle. + bool battle_at(const StoryWorld& world, const Pokemon::TilePos& pos); + // The player moved `thousandths` of a tile toward `direction` and did + // not stop at a wall (or, `at_wall`, stopped at one): drifts them. + void walked(GridSim& sim, Pokemon::Direction direction, int thousandths, bool at_wall); + // The player was put on a tile: no drift. + void reset(); + // The people who wander on `world`, each with a seed and start drawn. + std::vector wanderers(const StoryWorld& world); + +private: + // How far off the player is along one axis, in thousandths of a tile: + // `drift` in all, `applied` of it on the grid sim's position. + struct Axis{ + int drift = 0; + int applied = 0; + }; + void sync(const GridSim& sim); + void materialize(GridSim& sim, bool across); + const std::vector& people(const StoryWorld& world); + void add_people(std::vector& people, const std::string& map, const Pokemon::TilePos& corner, const Pokemon::TilePos& local); + + Pokemon::DisturbancePlan m_plan; + size_t m_battles = 0; + Axis m_x; + Axis m_y; + std::map> m_people; +}; + + +// A hold on the grid sim (GridSim::hold()), a tile at a time with wild +// battles and drift from `noise` if given. +struct DisturbedHold{ + SimMove move; + size_t battles = 0; + // A battle on the hold's first tile: the console cannot tell it from + // one that began before the hold (WalkOrigin::MAY_PRECEDE_LEG). + bool first_tile = false; +}; +// Holds toward `direction` for up to `limit`; see DisturbedHold. +DisturbedHold disturbed_hold(GridSim& sim, SimDisturbance* noise, Pokemon::Direction direction, Milliseconds limit, SimPace pace); + + +// GridSimRouteIO, disturbed by `noise` (none: GridSimRouteIO itself). +class DisturbedRouteIO : public GridSimRouteIO{ +public: + DisturbedRouteIO(GridSim& sim, std::vector& notes, SimDisturbance* noise) + : GridSimRouteIO(sim, notes) + , m_sim(sim) + , m_notes(notes) + , m_noise(noise) + {} + + virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override; + virtual WalkResult walk_taps(Pokemon::Direction direction, size_t tiles, const std::string& label) override; + virtual void press(const RouteInput& input) override; + +private: + GridSim& m_sim; + std::vector& m_notes; + SimDisturbance* m_noise; +}; + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp new file mode 100644 index 0000000000..915be68858 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp @@ -0,0 +1,279 @@ +/* BDSP AutoStory Story Monte Carlo Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The story's rows on the story simulation (SimExecutor: the program's own + * walking steps on the grid sim), each run once per pinned seed with that + * seed's disturbances (SimDisturbance): wild battles on grass and in caves, + * drift off the grid, the maps' wanderers, and sometimes one missed fade or + * banner. Each row's test logs its pass rate and, per failing step, the + * failure kinds with a seed that reproduces each, and fails only below the + * row's pinned floor. The old 01.03 test shows the harness finds the two + * failures lab-B met on 2026-11-08. + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Time.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP_AutoStory_SimDisturbance.h" +#include "PokemonBDSP_AutoStory_StorySim.h" +#include "PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +namespace{ + +using Pokemon::Direction; +using Pokemon::RowReport; +using Pokemon::SeedOutcome; +using Pokemon::StoryStep; +using Pokemon::TilePos; + +constexpr const char* SEEDS_VARIABLE = "PA_BDSP_STORY_MC_SEEDS"; +constexpr const char* ROWS_VARIABLE = "PA_BDSP_STORY_MC_ROWS"; +constexpr size_t DEFAULT_SEEDS = 20; + +// The runs log nothing: a seed's own log is a reproduction away. +class SilentLogger : public Logger{ +public: + virtual void log(const std::string&, Color) override{} +}; + +// The fades and banners an undisturbed run of `row` looks for. +SimMisses looked_for(const std::vector& rows, const std::string& row){ + SilentLogger logger; + SimExecutor executor(logger); + run_rows_on(executor, logger, {.from = row, .to = row}, rows); + return executor.misses(); +} + +// How a failed run failed, as the report groups it. +SeedOutcome failed_outcome(const Pokemon::SegmentReport& report, const SimRun& run, const SimDisturbance& noise){ + const bool in_step = !run.failed_step.empty(); + SeedOutcome out{ + .passed = false, + .failed_step = in_step ? run.failed_step : report.failed_checkpoint + " " + report.failed_event, + .kind = in_step ? Pokemon::failure_kind(run.failure, run.failure_detail) + : Pokemon::failure_kind(report.failure.failure, report.failure.detail), + .detail = std::format("{}; {} wild battle(s)", describe(noise.plan()), run.battles), + }; + if (run.failed_step_battles > 0){ + out.kind += " [wild battle in the step]"; + } + if (in_step && run.missed_step == run.failed_step){ + out.kind += " [missed detection in the step]"; + } + return out; +} + +// Row `row` of `rows`, disturbed by `seed`. +SeedOutcome run_seed(const std::vector& rows, const SimMisses& clean, const std::string& row, uint64_t seed){ + SimDisturbance noise(Pokemon::make_disturbance_plan(seed, Pokemon::DisturbanceRates{}, clean.fades, clean.banners)); + SilentLogger logger; + SimExecutor executor(logger, {.fade = noise.plan().missed_fade, .banner = noise.plan().missed_banner}, &noise); + try{ + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = row, .to = row}, rows); + return report.completed ? SeedOutcome{.passed = true} : failed_outcome(report, executor.result(), noise); + }catch (const GridSimFailure& e){ + return {.failed_step = row + " (thrown)", .kind = Pokemon::failure_kind("sim_failure", e.message), .detail = describe(noise.plan())}; + }catch (const Exception& e){ + return {.failed_step = row + " (thrown)", .kind = Pokemon::failure_kind(e.name(), e.message()), .detail = describe(noise.plan())}; + } +} + +RowReport run_row(const std::vector& rows, const std::string& row, size_t seeds){ + const SimMisses clean = looked_for(rows, row); + return Pokemon::run_row_seeds(row, Pokemon::story_seeds(seeds), [&](const std::string& id, uint64_t seed){ + return run_seed(rows, clean, id, seed); + }); +} + + +// Row `row` for the seeds, under `floor` passes in a hundred a failure: +// each row's floor is what it passed at this branch's tip, so a row that +// passes less often has got worse. A row PA_BDSP_STORY_MC_ROWS leaves out +// is skipped. +UnitTestResult test_row(Logger& logger, const std::string& row, size_t floor){ + if (Pokemon::selected_rows(ROWS_VARIABLE, {row}).empty()){ + return {UnitTestResult::SKIPPED, std::string(ROWS_VARIABLE) + " leaves it out"}; + } + const size_t seeds = Pokemon::seed_count(SEEDS_VARIABLE, DEFAULT_SEEDS); + const WallClock start = current_time(); + const RowReport report = run_row(story_checkpoints(), row, seeds); + const auto took = std::chrono::duration_cast(current_time() - start); + logger.log(Pokemon::format_report(report) + std::format("\n ({} seeds in {} ms)", seeds, took.count())); + // The floors are the default seeds' counts; other counts only report. + if (seeds == DEFAULT_SEEDS && report.passes * 100 < floor * report.runs){ + return std::format("{} passed {} of {}, under its floor of {}%:\n{}", row, report.passes, report.runs, + floor, Pokemon::format_report(report)); + } + return true; +} + + +// 01.03 as it was before be57db157 and 4f13c19bb: counted taps across +// Roark's room, and the route to below the Center's door straight into +// the heal. +std::vector old_0103(){ + StoryStep taps; + taps.kind = Pokemon::StoryStepKind::LEGS; + taps.name = "above_roarks_row"; + taps.legs = { + {.direction = Direction::EAST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 2}, + {.direction = Direction::WEST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 5}, + {.direction = Direction::EAST, .tiles = 14}, {.direction = Direction::SOUTH, .tiles = 10}, + {.direction = Direction::WEST, .tiles = 2}, {.direction = Direction::SOUTH, .tiles = 2}, + }; + taps.pose_after = Pokemon::tile_pose("OreburghMine", {TilePos{27, 28}}, Direction::SOUTH); + const std::vector added{"around_the_rock", "down_column_29", + "south_of_the_centers_door", "against_the_walls_east_of_the_door", "below_the_centers_door_lined_up"}; + std::vector rows = story_checkpoints(); + for (StoryCheckpoint& row : rows){ + if (row.id != "01.03"){ + continue; + } + std::erase_if(row.steps, [&](const StoryStep& step){ + return std::find(added.begin(), added.end(), step.name) != added.end(); + }); + std::replace_if(row.steps.begin(), row.steps.end(), [](const StoryStep& step){ return step.name == "above_roarks_row"; }, taps); + } + return rows; +} + +// Row 01.03 of `rows` from out of the mine on: the walk up to below the +// Center's door and the heal, without the mine's failures before it. +std::vector from_the_mines_sign(std::vector rows){ + for (StoryCheckpoint& row : rows){ + if (row.id != "01.03"){ + continue; + } + const auto sign = std::find_if(row.steps.begin(), row.steps.end(), [](const StoryStep& step){ + return step.name == "up_to_the_mines_sign"; + }); + row.start = Pokemon::tile_pose("OreburghCity", {TilePos{45, 59}, TilePos{45, 58}}, Direction::NORTH); + row.saves_in.clear(); + row.steps.erase(row.steps.begin(), sign); + } + return rows; +} + +// Whether `report` failed `step` in a way whose kind holds `text` and `also`. +bool failed_with(const RowReport& report, const std::string& step, const std::string& text, const std::string& also = ""){ + const auto found = report.failures.find(step); + return found != report.failures.end() && std::ranges::any_of(found->second, [&](const auto& kind){ + return kind.first.find(text) != std::string::npos && kind.first.find(also) != std::string::npos; + }); +} + +// lab-B 2026-11-08: a wild battle on the counted taps across Roark's room +// re-planned to an open leg and the row went one off (11:55); a run up +// Oreburgh's column 46 stopped short and an open step east left us off the +// Center door's column (10:39). The old row must show both. +UnitTestResult test_old_0103(Logger& logger){ + const size_t seeds = std::max(200, Pokemon::seed_count(SEEDS_VARIABLE, DEFAULT_SEEDS)); + const RowReport whole = run_row(old_0103(), "01.03", seeds); + logger.log("The old 01.03: " + Pokemon::format_report(whole)); + const RowReport town = run_row(from_the_mines_sign(old_0103()), "01.03", seeds); + logger.log("The old 01.03 from the mine's sign: " + Pokemon::format_report(town)); + logger.log("Today's 01.03 from the mine's sign: " + Pokemon::format_report(run_row(from_the_mines_sign(story_checkpoints()), "01.03", seeds))); + // A battle on the taps, then the row ends off the tile the taps count. + const bool roark = failed_with(whole, "01.03 above_roarks_row", "sim_mismatch", "[wild battle in the step]"); + const bool center = failed_with(town, "01.03 heal_oreburgh", "no door north"); + if (!roark || !center){ + return std::format("expected the old 01.03 to fail across Roark's room after a wild battle ({}) and at the Center's door ({}):\n{}\n{}", + roark, center, Pokemon::format_report(whole), Pokemon::format_report(town)); + } + return true; +} + + +// A row of the table, disturbed; or, with a body, another test. +struct StoryMonteCarloInput{ + std::string row; + std::function body = nullptr; +}; + +// The fewest passes in a hundred a row's seeds may have. +struct StoryMonteCarloExpectation{ + size_t floor = 0; +}; + +struct StoryMonteCarloCase{ + StoryMonteCarloInput input; + StoryMonteCarloExpectation expectation; +}; + +class Test_StoryMonteCarlo : public UnitTest{ +public: + explicit Test_StoryMonteCarlo(StoryMonteCarloCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Story Monte Carlo: " + test_case.input.row) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body ? m_case.input.body(logger) + : test_row(logger, m_case.input.row, m_case.expectation.floor); + }catch (const GridSimFailure& e){ + return "GridSimFailure: " + e.message; + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + StoryMonteCarloCase m_case; +}; + +} // namespace + + +const StoryMonteCarloCase AUTO_STORY_MONTE_CARLO_CASES[] = { + {.input = {"00.00"}, .expectation = {.floor = 100}}, + {.input = {"00.01"}, .expectation = {.floor = 20}}, + {.input = {"00.02"}, .expectation = {.floor = 100}}, + {.input = {"00.03"}, .expectation = {.floor = 30}}, + {.input = {"00.04"}, .expectation = {.floor = 0}}, + {.input = {"00.04b"}, .expectation = {.floor = 55}}, + {.input = {"00.04c"}, .expectation = {.floor = 100}}, + {.input = {"00.04d"}, .expectation = {.floor = 55}}, + {.input = {"00.05"}, .expectation = {.floor = 70}}, + {.input = {"00.05b"}, .expectation = {.floor = 45}}, + {.input = {"00.05c"}, .expectation = {.floor = 20}}, + {.input = {"01.01"}, .expectation = {.floor = 95}}, + {.input = {"01.02"}, .expectation = {.floor = 20}}, + {.input = {"01.02b"}, .expectation = {.floor = 90}}, + {.input = {"01.03"}, .expectation = {.floor = 5}}, + {.input = {"01.04"}, .expectation = {.floor = 100}}, + {.input = {"01.05"}, .expectation = {.floor = 80}}, + {.input = {"01.06"}, .expectation = {.floor = 25}}, + {.input = {"01.07"}, .expectation = {.floor = 100}}, + {.input = {"01.08"}, .expectation = {.floor = 40}}, + {.input = {"01.09"}, .expectation = {.floor = 50}}, + {.input = {"01.10"}, .expectation = {.floor = 5}}, + {.input = {"01.11"}, .expectation = {.floor = 100}}, + { + .input = {"the old 01.03 fails across Roark's room and at the Center's door (lab-B, 2026-11-08)", test_old_0103}, + .expectation = {}, + }, +}; + +void add_tests_AutoStory_StoryMonteCarlo(UnitTestDatabase& database){ + for (const StoryMonteCarloCase& item : AUTO_STORY_MONTE_CARLO_CASES){ + database.add(item); + } +} + + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.h new file mode 100644 index 0000000000..9f75939200 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.h @@ -0,0 +1,29 @@ +/* BDSP AutoStory Story Monte Carlo Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryMonteCarlo_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryMonteCarlo_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// Each row of the story table run on the story simulation for the pinned +// seeds, disturbed (wild battles, drift, wanderers, a missed detection): +// its pass rate and failing steps. PA_BDSP_STORY_MC_SEEDS sets the seed +// count (20 by default), PA_BDSP_STORY_MC_ROWS the rows ("01.03,01.04"). +void add_tests_AutoStory_StoryMonteCarlo(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp new file mode 100644 index 0000000000..be3a69ac95 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -0,0 +1,460 @@ +/* BDSP AutoStory - Story simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StorySim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::Outcome; +using Pokemon::Pose; +using Pokemon::RunState; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + + +// A hold until something stops us. A door stops it at the fade, which +// fails the step; a fade missed lets the hold go on past the mouth (r81's +// timed walk south out of the Ravaged Path, onto Route 204's cliff). +void SimStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ + m_sim.tap(direction, ROUTE_TURN_TAP, false); + Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); + SimMove move = disturbed_hold(m_sim, m_noise, direction, limit, SimPace::WALK).move; + if (move.stop == SimStop::WARP && fade_missed() && m_far_side()){ + limit -= std::min(limit, move.time); + move = disturbed_hold(m_sim, m_noise, direction, limit, SimPace::WALK).move; + } + if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ + m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); + } +} + +// The D-pad, a tile at a time, until `map`'s banner reads; through a door +// the walk goes on beyond it (the fade eats no tiles of a hold). +bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&){ + const bool miss = banner_missed(); + size_t on = 0; + for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ + SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + const bool crossed = move.stop == SimStop::WARP && m_far_side(); + const bool stopped = !crossed && (move.distance == 0 || move.stop != SimStop::DONE); + on = on_map(map) ? on + 1 : 0; + if (on > 0 && (on > SIM_BANNER_TILES || stopped) && !miss){ + return true; + } + if (stopped){ + return false; + } + } + return false; +} + +// D-pad taps, each looked at, until the fade and then the banner (the +// console's ConsoleStoryStepIO::tap_to_banner()). Each look stands still, +// so a banner on the far side reads at once. A fade seen ends the taps, +// banner or not; with the fade missed the next look still sees the banner. +std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ + bool crossed = false; + for (size_t tap = 1; tap <= max_taps; tap++){ + const SimMove move = m_sim.tap(direction, 160ms, false); + if (move.stop == SimStop::DIALOG){ + return std::nullopt; + } + bool faded = false; + if (move.stop == SimStop::WARP){ + faded = !fade_missed(); + crossed = m_far_side(); + } + if (crossed && on_map(map) && !banner_missed()){ + return tap; + } + if (faded){ + return std::nullopt; + } + } + return std::nullopt; +} + +// The story variables whose coord events the table walks onto, from the +// row (and step) the table's reasons give, with the maps' coord events +// (Diamond's zone events; Platinum's for the houses): Barry's doorstep and +// Mom's warning in 00.01, Barry's Route 201 warning, then its pull-back +// row 19 once he has warned us (r14, r16); the lake's entrance in 00.02; +// Rowan's stop and Dawn at Sandgem's edge in 00.03; Dawn's catching +// tutorial on Route 202 from 00.04's start, Mom's call once she has healed +// us; the Poketch president on Jubilife's row 40 in 00.05b; Barry on Route +// 203 in 01.01; the Gate's Hiker and Oreburgh's welcome in 01.02; Barry's +// bump in Oreburgh after Roark in 01.05; and Rowan in Jubilife in 01.07. +// Left out: the Twinleaf guitarist (spent upstairs), Platinum's rival +// steps around our bedroom's start, Dawn at Jubilife's steps (BDSP starts +// her below them: an event), and Floaroma's (10..12, 29) (Diamond only). +std::vector story_vars(){ + return { + {.var = "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", .value = 0, .row = "00.01", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 0, .row = "00.01", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 1, .row = "00.01", .after = "barry_warns_us"}, + {.var = "VAR_VERITY_LAKEFRONT_STATE", .value = 0, .row = "00.02", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 2, .row = "00.03", .after = ""}, + {.var = "VAR_SANDGEM_TOWN_STATE", .value = 0, .row = "00.03", .after = ""}, + {.var = "VAR_ROUTE_202_STATE", .value = 0, .row = "00.04", .after = ""}, + {.var = "CONSOLE_MOMS_CALL", .value = 0, .row = "00.04", .after = "mom_heals_us"}, + {.var = "VAR_POKETCH_CAMPAIGN_STATE", .value = 1, .row = "00.05b", .after = ""}, + {.var = "VAR_ROUTE_203_RIVAL_STATE", .value = 0, .row = "01.01", .after = ""}, + {.var = "VAR_OREBURGH_GATE_1F_HIKER_STATE", .value = 1, .row = "01.02", .after = ""}, + {.var = "VAR_OREBURGH_CITY_STATE", .value = 0, .row = "01.02", .after = ""}, + {.var = "VAR_OREBURGH_CITY_STATE", .value = 2, .row = "01.05", .after = ""}, + {.var = "VAR_JUBILIFE_CITY_STATE", .value = 3, .row = "01.07", .after = ""}, + }; +} + +// The maps' coord events (story_coord_events()) whose variable holds. +std::optional var_state(const CoordEvent& event){ + for (const VarState& state : story_vars()){ + if (state.var == event.var && state.value == event.value){ + return state; + } + } + return std::nullopt; +} + +RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ + return {.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; +} + +std::vector story_triggers(){ + std::vector triggers; + for (const auto& [map, json] : bdsp_map_json()){ + for (const CoordEvent& event : story_coord_events(map)){ + const std::optional state = var_state(event); + if (state){ + triggers.push_back(row_trigger(map, event, *state)); + } + } + } + return triggers; +} + +// Someone the maps do not have, on `tile` of `map`, talked to or walked round: +// from row `row` on, until row `until_row`'s step `until` has run if it is set. +struct SimPerson{ + std::string name; + std::string map; + TilePos tile; + std::string row; + std::string until_row = {}; + std::string until = {}; +}; +std::vector sim_people(){ + return { + // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). + {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04"}, + // Barry in the Gym's door, from the welcome (lab-B 2026-11-08) to his lines (r101, r104). + {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.02b", .until_row = "01.02b", .until = "barrys_lines"}, + }; +} + +// A house's stairs, entered by a step `side` from the map's "stairs" +// point into what the map draws as a wall (the table's 00.01: r8 and r9 +// for ours, r11 for Barry's). +struct SimStairs{ + std::string map; + Direction side; +}; +std::vector sim_stairs(){ + return { + {.map = "PlayerHouse2F", .side = Direction::EAST}, + {.map = "RivalHouse1F", .side = Direction::EAST}, + {.map = "RivalHouse2F", .side = Direction::WEST}, + }; +} + +// The world the player walks on for `map`: the planner's, with what the +// console showed that the maps lack. Nothing for a room with no map. +const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ + const StoryWorld* world = story_plan_world(map, map); + std::vector here; + std::string who; + for (const SimPerson& person : sim_people()){ + const bool now = m_row >= person.row && (person.until.empty() || m_row < person.until_row || + (m_row == person.until_row && !m_ran.contains(person.until))); + if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ + here.push_back(person); + who += person.name + ";"; + } + } + if (here.empty()){ + return world; + } + std::unique_ptr& peopled = m_peopled[{world, who}]; + if (!peopled){ + peopled = std::make_unique(*world); + for (const SimPerson& person : here){ + peopled->block(story_to_world(*world, person.map, person.tile)); + } + } + return peopled.get(); +} + +SimWorld SimExecutor::setup(const StoryWorld* world) const{ + // B runs once the shoes' scene has given them: the scene ends at home. + SimWorld out{.world = world, .trainers = story_trainers(*world), .can_run = m_walks.can_run()}; + if (m_noise != nullptr){ + out.wanderers = m_noise->wanderers(*world); + } + for (const SimStairs& stairs : sim_stairs()){ + if (sim_world(stairs.map) == world){ + out.doors.push_back(story_to_world(*world, stairs.map, map_point(stairs.map, "stairs").next(stairs.side))); + } + } + for (const RowTrigger& armed : m_armed){ + if (sim_world(armed.map) != world){ + continue; + } + SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; + for (const TilePos& pos : armed.trigger.tiles){ + trigger.tiles.push_back(story_to_world(*world, armed.map, pos)); + } + out.triggers.push_back(std::move(trigger)); + } + return out; +} + +// Arms the triggers of this row that start after `after`. +void SimExecutor::arm(const std::string& after){ + size_t armed = 0; + for (const RowTrigger& trigger : story_triggers()){ + if (trigger.row == m_row && trigger.after == after){ + m_armed.push_back(trigger); + armed++; + } + } + const SimPlayer& player = m_sim.player(); + if (armed > 0 && m_placed && settled() && !player.dialog){ + place(&m_sim.world(), nearest_tile(player.pos), player.facing); + } +} + +// Puts the player on `pose`, on the world `on` if given, unless they stand +// on one of its tiles already. Returns whether the pose is on a map the +// simulation has. +bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ + const std::vector tiles = Pokemon::tiles_of(pose); + const StoryWorld* world = on != nullptr ? on : pose.map.empty() ? nullptr : sim_world(pose.map); + if (world == nullptr || tiles.empty()){ + return false; + } + const SimPlayer& player = m_sim.player(); + const std::optional local = !m_placed || &m_sim.world() != world + ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); + if (local && settled() && std::find(tiles.begin(), tiles.end(), *local) != tiles.end()){ + return true; + } + place(world, story_to_world(*world, pose.map, tiles.front()), Pokemon::facing_of(pose)); + m_placed = true; + return true; +} + +// Through a door or a cave mouth onto the step's far side, the player's +// facing kept: a hold goes on from there. +bool SimExecutor::cross(){ + const StoryWorld* world = m_far ? sim_world(m_far->map) : nullptr; + const std::vector tiles = m_far ? Pokemon::tiles_of(*m_far) : std::vector{}; + if (world == nullptr || tiles.empty()){ + return false; + } + place(world, story_to_world(*world, m_far->map, tiles.front()), std::nullopt); + return true; +} + +// Why the player does not stand on one of `pose`'s tiles, or "" if they +// do or the simulation cannot tell (no map, or not placed yet). +std::string SimExecutor::off_pose(const Pose& pose) const{ + const std::vector tiles = Pokemon::tiles_of(pose); + if (!m_placed || tiles.empty() || sim_world(pose.map) == nullptr){ + return ""; + } + const SimPlayer& player = m_sim.player(); + const TilePos at = nearest_tile(player.pos); + // In world tiles: a pose a leg worked out from the map it started on + // may lie past that map's edge, on the next map (Twinleaf's exit). + // story_to_world() throws for a map not on the player's world. + try{ + const auto there = [&](const TilePos& tile){ return story_to_world(m_sim.world(), pose.map, tile) == at; }; + if (settled() && std::ranges::any_of(tiles, there)){ + return ""; + } + }catch (const InternalProgramError&){} + return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), at), Pokemon::to_string(pose)); +} + +// The program's run into the Center: past its door, the inside shows, a missed fade or not. +Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ + if (!sync(state.pose)){ + return Pokemon::outcome_ok(); + } + run_into_center(m_io, m_walks.can_run(), [this]{ + m_misses.fade_unseen = false; + return m_sim.player().warped.has_value(); + }, [&]{ + throw GridSimFailure{step.name + ": no door north of " + to_string(m_sim.player().pos)}; + }); + return Pokemon::outcome_ok(); +} + +// Why a walking step did not end where the table says, or "". A step +// through a door the simulation did not cross is not checked: the sim's +// maps have no warps' destinations. +std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ + const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP; + const std::optional expected = step.pose_after ? step.pose_after : outcome.pose; + if (!walks || !m_placed){ + return ""; + } + if (!expected || Pokemon::tiles_of(*expected).empty()){ + m_result.unchecked.push_back(m_row + " " + step.name); + return ""; + } + const SimPlayer& player = m_sim.player(); + if (player.warped && !story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos))){ + return ""; + } + return off_pose(*expected); +} + +Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ + if (!m_start_mismatch.empty()){ + return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); + } + m_far = step.pose_after; + if (story_events().contains(step.variant)){ + return stub(); + } + // A scene goes on from where the step before left us. A route walks + // on the world it plans on (Jubilife alone has no Route 204 north of it). + const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || + step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK; + const StoryWorld* on = step.kind == StoryStepKind::ROUTE && step.target && !state.pose.map.empty() + ? story_plan_world(state.pose.map, step.target->map) : nullptr; + // A world of one map is sim_world()'s, with its people. + if (on != nullptr && on == story_plan_world(state.pose.map, state.pose.map)){ + on = nullptr; + } + if (walks && !sync(state.pose, on)){ + m_logger.log(std::format("[{}] {}: no map for {}; passed over.", m_row, step.name, Pokemon::to_string(state.pose))); + m_passed_over = true; + return Pokemon::outcome_ok(); + } + return Pokemon::StoryStepExecutor::run(state, step); +} + +// Puts the player on `start` of `world`: on the grid, no drift. +void SimExecutor::place(const StoryWorld* world, const TilePos& start, std::optional facing){ + m_sim.place(setup(world), start, facing); + if (m_noise != nullptr){ + m_noise->reset(); + } +} + +// Whether the player stands on their tile: on the grid, or, disturbed, +// anywhere nearer it than another (how far off is the run's to find out). +bool SimExecutor::settled() const{ + return m_noise != nullptr || on_grid(m_sim.player().pos); +} + +void SimExecutor::record_failure(const Outcome& outcome, const StoryStep& step, size_t battles_before){ + // The walker's last notes, to see why. + for (size_t i = m_notes.size() - std::min(m_notes.size(), 40); i < m_notes.size(); i++){ + m_logger.log(std::format("[{}] note: {}", m_row, m_notes[i])); + } + m_result.error = m_row + " " + Pokemon::to_string(outcome); + m_result.failed_step = m_row + " " + step.name; + m_result.failure = outcome.failure; + m_result.failure_detail = outcome.detail; + m_result.failed_step_battles = m_noise == nullptr ? 0 : m_noise->battles() - battles_before; +} + +Outcome SimExecutor::run(RunState& state, const StoryStep& step){ + Outcome outcome; + m_passed_over = false; + const size_t battles_before = m_noise == nullptr ? 0 : m_noise->battles(); + try{ + outcome = run_step(state, step); + }catch (const GridSimFailure& e){ + outcome = Pokemon::outcome_failed("sim_failure", e.message); + } + const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; + if (!mismatch.empty()){ + outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); + } + // What the simulation does not play (scenes, events, battles) ends + // where the table says it does. + if (outcome.succeeded() && step.pose_after){ + sync(*step.pose_after); + } + m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); + if (std::exchange(m_misses.missed, false) && m_result.missed_step.empty()){ + m_result.missed_step = m_row + " " + step.name; + } + if (!outcome.succeeded() && m_result.error.empty()){ + record_failure(outcome, step, battles_before); + } + m_result.battles = m_noise == nullptr ? 0 : m_noise->battles(); + m_result.world = m_placed ? &m_sim.world() : nullptr; + m_result.end = nearest_tile(m_sim.player().pos); + m_ran.insert(step.name); + arm(step.name); + return outcome; +} + +// Runs `range` of `rows` (the table unless given) on `executor`, stopping +// at the first failure. +Pokemon::SegmentReport run_rows_on( + SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, + const std::vector& rows +){ + std::set saved; + Pokemon::Segment segment = make_story_segment(rows, executor, saved); + Pokemon::SegmentPolicy policy; + policy.stop_at_first_failure = true; + Pokemon::SegmentHooks hooks; + hooks.reload = [](RunState&){ return Pokemon::outcome_ok(); }; + hooks.log = [&logger](const std::string& line){ logger.log(line); }; + RunState state; + return Pokemon::run_segment(state, segment, range, policy, hooks); +} + +// The table with row `row`'s step of `step`'s name replaced by `step`. +std::vector table_with(const std::string& row, const StoryStep& step){ + std::vector rows = story_checkpoints(); + for (StoryCheckpoint& checkpoint : rows){ + for (StoryStep& old : checkpoint.steps){ + if (checkpoint.id == row && old.name == step.name){ + old = step; + return rows; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + step.name + " in " + row); +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h new file mode 100644 index 0000000000..d85b2642f9 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -0,0 +1,319 @@ +/* BDSP AutoStory - Story simulation + * + * From: https://github.com/PokemonAutomation/ + * + * Rows of the story table run as the program runs them (the segment + * runner, make_story_segment()), with the program's own walking steps + * (StoryWalkSteps: ROUTE, LEGS, STEP, TALK, MASH) on the grid simulation. + * After each walking step the simulated player must stand, on the grid, + * on a tile the table gives; a step through a door must have warped. + * + * Events, battles, shops and saves are stubs: a dialogue they open is + * closed, and the table's pose_after puts the player where they end. A + * heal checks that a walk north from where we stand enters a door. A scene + * starts when the player steps onto one of the maps' coord events while + * its story variable holds (story_vars()). Rooms with no + * map (the Trainers' School) are passed over. Each row must start where + * the row before left the player. + * + * A tap or hold through a door or cave mouth stops on its tile, as the + * console stops at the fade; a hold that does not see the fade goes on + * onto the step's pose_after and on along it, and a location banner reads + * only a few tiles into its map (SIM_BANNER_TILES). + * + * With a SimDisturbance the run is disturbed as the console disturbs it + * (wild battles, drift off the grid, people wandering): the story's Monte + * Carlo tests. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StorySim_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StorySim_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "Pokemon/AutoStory/Pokemon_StorySteps.h" +#include "PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_SimDisturbance.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Which detections the simulation misses on purpose (#162): the `fade`th +// door fade (run_into_door(), from 0) or the `banner`th map banner +// (run_until_map()) of the run goes unseen, though the player did go +// through. The console missed both (r75, r81). The `dark`th door run reads +// dark SIM_FALSE_DARK in, short of the door, as lab-B's did on 2026-11-08. +// The counts and flags below are the run's: how many fades and banners it +// looked for, whether a miss happened since the executor last looked, and +// whether a missed fade is still unseen. +struct SimMisses{ + std::optional fade; + std::optional banner; + std::optional dark = {}; + size_t fades = 0; + size_t banners = 0; + size_t doors = 0; + bool missed = false; + bool fade_unseen = false; +}; + +// How many tiles a held walk goes on into a map before its location +// banner reads: "it shows a tile or a few past the border" (the table's +// route_201_by_the_path(), measured on the console). Standing still, it +// reads at once. Through a cave mouth the fade comes first, and a hold +// whose fade went unseen goes on the same way (r75, r81). +constexpr size_t SIM_BANNER_TILES = 3; +// How far into a door run SimMisses::dark reads dark short of the door. +constexpr Milliseconds SIM_FALSE_DARK = Milliseconds(1800); + +// What a run on the simulation did. +struct SimRun{ + // The first failure, as "row outcome", or "". + std::string error; + // The rows and steps where an injected miss happened and where the run + // first failed, as "row step": "" if none. + std::string missed_step; + std::string failed_step; + // Walking steps that end where nothing says, as "row step". + std::vector unchecked; + // Each row run, with the fades and banners looked for before it. + struct RowStart{ + std::string row; + size_t fades; + size_t banners; + }; + std::vector rows; + // Where the player stood after the last step, if placed. + const StoryWorld* world = nullptr; + Pokemon::TilePos end; + // Wild battles in the run, and in the step it failed in. + size_t battles = 0; + size_t failed_step_battles = 0; + // How the run failed: the failure and its message. + std::string failure; + std::string failure_detail; +}; + +// StoryStepIO on the simulation. A walk through a door or a cave mouth +// stops on its tile, as the console stops at the fade; a hold that misses +// the fade carries on, onto `far_side()` (the step's pose_after: the +// sim's maps have no warps' destinations) and on along it. +class SimStoryStepIO : public StoryStepIO{ +public: + SimStoryStepIO(GridSim& sim, std::vector& notes, SimMisses& misses, std::function far_side, + SimDisturbance* noise = nullptr) + : m_sim(sim) + , m_noise(noise) + , m_route(sim, notes, noise) + , m_misses(misses) + , m_far_side(std::move(far_side)) + {} + + virtual RouteIO& route() override{ + return m_route; + } + virtual void fight(const std::string&) override{ + m_sim.end_dialogue(); + } + virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; + virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; + virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) override{ + const SimPace pace = run ? SimPace::RUN : SimPace::WALK; + if (false_dark() && dark_from <= SIM_FALSE_DARK && SIM_FALSE_DARK < timeout){ + disturbed_hold(m_sim, m_noise, direction, SIM_FALSE_DARK, pace); + return true; + } + // A wild battle on the way is fled, and the run goes on. + const bool warped = disturbed_hold(m_sim, m_noise, direction, timeout, pace).move.stop == SimStop::WARP; + if (warped && fade_missed()){ + m_misses.fade_unseen = true; + return false; + } + return warped; + } + // A scene may take us to another map (Mom walks us out, 00.04): with a + // dialogue open the stub scene plays it. Otherwise only a door fades. + // A fade missed on the way in stays missed: it was over before settle() + // looked, which then fails as it does on the console after 120 s. + virtual void settle(Button, const std::string& label, bool fade) override{ + const bool scene_fades = m_sim.player().dialog && m_far_side(); + if (fade && ((!m_sim.player().warped && !scene_fades) || m_misses.fade_unseen)){ + m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); + } + m_misses.fade_unseen = false; + m_sim.end_dialogue(); + } + virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) override; + +private: + // Whether the run misses this fade or this banner (SimMisses). + bool fade_missed(){ + const bool miss = m_misses.fade == m_misses.fades++; + m_misses.missed |= miss; + return miss; + } + bool false_dark(){ + const bool dark = m_misses.dark == m_misses.doors++; + m_misses.missed |= dark; + return dark; + } + bool banner_missed(){ + const bool miss = m_misses.banner == m_misses.banners++; + m_misses.missed |= miss; + return miss; + } + bool on_map(const std::string& map) const{ + return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); + } + + GridSim& m_sim; + SimDisturbance* m_noise; + DisturbedRouteIO m_route; + SimMisses& m_misses; + std::function m_far_side; +}; + +// A scene's trigger the simulation fires from row `row` on, once the step +// `after` has run ("" from the row's start), on `map`'s `tiles`. +struct RowTrigger{ + std::string row; + std::string after; + std::string map; + SimTrigger trigger; +}; + +// When a story variable holds the value its coord events wait for: from +// row `row` on, once the step `after` has run ("" from the row's start). +struct VarState{ + std::string var; + int value; + std::string row; + std::string after; +}; + +// The story variables whose coord events the table walks onto (see the +// .cpp), and the maps' coord events they arm. +std::vector story_vars(); +// The coord events of the maps whose story variable story_vars() holds. +std::vector story_triggers(); + +// The program's walking steps on the simulation, the rest stubbed. With +// `noise`, which must outlive it, the run is disturbed: the player may +// stand part of a tile off (within half a tile of where a step should end +// counts as there), and the people on the maps wander. +class SimExecutor : public Pokemon::StoryStepExecutor{ +public: + explicit SimExecutor(Logger& logger, SimMisses misses = {}, SimDisturbance* noise = nullptr) + : m_logger(logger) + , m_misses(misses) + , m_noise(noise) + , m_sim({}, {0, 0}, Pokemon::Direction::NORTH, false) + , m_io(m_sim, m_notes, m_misses, [this]{ return cross(); }, noise) + , m_walks(m_io) + {} + + const SimMisses& misses() const{ + return m_misses; + } + const SimRun& result() const{ + return m_result; + } + virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ + m_row = data.id; + m_start_mismatch = data.start ? off_pose(*data.start) : ""; + m_ran.clear(); + m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); + m_walks.begin_attempt(data.id); + arm(""); + } + virtual Pokemon::Outcome run(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; + +protected: + virtual Pokemon::Outcome route(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.route(state, step); } + virtual Pokemon::Outcome legs(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.legs(state, step); } + virtual Pokemon::Outcome step(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.step(state, step); } + virtual Pokemon::Outcome talk(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.talk(state, step); } + virtual Pokemon::Outcome mash(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.mash(state, step); } + virtual Pokemon::Outcome heal(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; + virtual Pokemon::Outcome new_game(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome options(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome answer(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome battle(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome train(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome shop(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome save(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome game(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + +private: + // A step the simulation does not play: its dialogue opened and closed. + Pokemon::Outcome stub(){ + m_sim.end_dialogue(); + return Pokemon::outcome_ok(); + } + const StoryWorld* sim_world(const std::string& map) const; + SimWorld setup(const StoryWorld* world) const; + void arm(const std::string& after); + bool sync(const Pokemon::Pose& pose, const StoryWorld* on = nullptr); + bool cross(); + std::string off_pose(const Pokemon::Pose& pose) const; + std::string check(const Pokemon::StoryStep& step, const Pokemon::Outcome& outcome); + Pokemon::Outcome run_step(Pokemon::RunState& state, const Pokemon::StoryStep& step); + void place(const StoryWorld* world, const Pokemon::TilePos& start, std::optional facing); + bool settled() const; + void record_failure(const Pokemon::Outcome& outcome, const Pokemon::StoryStep& step, size_t battles_before); + + Logger& m_logger; + std::vector m_notes; + SimMisses m_misses; + SimDisturbance* m_noise; + GridSim m_sim; + SimStoryStepIO m_io; + StoryWalkSteps m_walks; + // The planner's worlds with sim_people() on them, by world and who. + mutable std::map, std::unique_ptr> m_peopled; + // The steps of this row that have run. + std::set m_ran; + std::string m_row; + std::vector m_armed; + // Where the step running now ends, if it says: a door's far side. + std::optional m_far; + // Why the player is not on this row's start, or "". + std::string m_start_mismatch; + // Whether the player has been put on a map yet. + bool m_placed = false; + // Whether the step running now is on a room with no map. + bool m_passed_over = false; + SimRun m_result; +}; + +// Runs `range` of `rows` (the table unless given) on `executor`, stopping +// at the first failure. +Pokemon::SegmentReport run_rows_on( + SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, + const std::vector& rows = story_checkpoints() +); +// The table with row `row`'s step of `step`'s name replaced by `step`. +std::vector table_with(const std::string& row, const Pokemon::StoryStep& step); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 087b34cf24..12a0c40ec9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -48,6 +48,7 @@ #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_StorySim.h" #include "PokemonBDSP_AutoStory_StorySim_Tests.h" namespace PokemonAutomation{ @@ -65,612 +66,6 @@ using Pokemon::StoryStep; using Pokemon::StoryStepKind; using Pokemon::TilePos; -// Which detections the simulation misses on purpose (#162): the `fade`th -// door fade (run_into_door(), from 0) or the `banner`th map banner -// (run_until_map()) of the run goes unseen, though the player did go -// through. The console missed both (r75, r81). The `dark`th door run reads -// dark SIM_FALSE_DARK in, short of the door, as lab-B's did on 2026-11-08. -// The counts and flags below are the run's: how many fades and banners it -// looked for, whether a miss happened since the executor last looked, and -// whether a missed fade is still unseen. -struct SimMisses{ - std::optional fade; - std::optional banner; - std::optional dark = {}; - size_t fades = 0; - size_t banners = 0; - size_t doors = 0; - bool missed = false; - bool fade_unseen = false; -}; - -// How many tiles a held walk goes on into a map before its location -// banner reads: "it shows a tile or a few past the border" (the table's -// route_201_by_the_path(), measured on the console). Standing still, it -// reads at once. Through a cave mouth the fade comes first, and a hold -// whose fade went unseen goes on the same way (r75, r81). -constexpr size_t SIM_BANNER_TILES = 3; -constexpr Milliseconds SIM_FALSE_DARK = 1800ms; - -// What a run on the simulation did. -struct SimRun{ - // The first failure, as "row outcome", or "". - std::string error; - // The rows and steps where an injected miss happened and where the run - // first failed, as "row step": "" if none. - std::string missed_step; - std::string failed_step; - // Walking steps that end where nothing says, as "row step". - std::vector unchecked; - // Each row run, with the fades and banners looked for before it. - struct RowStart{ - std::string row; - size_t fades; - size_t banners; - }; - std::vector rows; - // Where the player stood after the last step, if placed. - const StoryWorld* world = nullptr; - TilePos end; -}; - -// StoryStepIO on the simulation. A walk through a door or a cave mouth -// stops on its tile, as the console stops at the fade; a hold that misses -// the fade carries on, onto `far_side()` (the step's pose_after: the -// sim's maps have no warps' destinations) and on along it. -class SimStoryStepIO : public StoryStepIO{ -public: - SimStoryStepIO(GridSim& sim, std::vector& notes, SimMisses& misses, std::function far_side) - : m_sim(sim) - , m_route(sim, notes) - , m_misses(misses) - , m_far_side(std::move(far_side)) - {} - - virtual RouteIO& route() override{ - return m_route; - } - virtual void fight(const std::string&) override{ - m_sim.end_dialogue(); - } - virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string& label) override; - virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; - virtual bool run_into_door(Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) override{ - const SimPace pace = run ? SimPace::RUN : SimPace::WALK; - if (false_dark() && dark_from <= SIM_FALSE_DARK && SIM_FALSE_DARK < timeout){ - m_sim.hold(direction, SIM_FALSE_DARK, pace); - return true; - } - const bool warped = m_sim.hold(direction, timeout, pace).stop == SimStop::WARP; - if (warped && fade_missed()){ - m_misses.fade_unseen = true; - return false; - } - return warped; - } - // A scene may take us to another map (Mom walks us out, 00.04): with a - // dialogue open the stub scene plays it. Otherwise only a door fades. - // A fade missed on the way in stays missed: it was over before settle() - // looked, which then fails as it does on the console after 120 s. - virtual void settle(Button, const std::string& label, bool fade) override{ - const bool scene_fades = m_sim.player().dialog && m_far_side(); - if (fade && ((!m_sim.player().warped && !scene_fades) || m_misses.fade_unseen)){ - m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); - } - m_misses.fade_unseen = false; - m_sim.end_dialogue(); - } - virtual std::optional tap_to_banner(Direction direction, const std::string& map, size_t max_taps) override; - -private: - // Whether the run misses this fade or this banner (SimMisses). - bool fade_missed(){ - const bool miss = m_misses.fade == m_misses.fades++; - m_misses.missed |= miss; - return miss; - } - bool false_dark(){ - const bool dark = m_misses.dark == m_misses.doors++; - m_misses.missed |= dark; - return dark; - } - bool banner_missed(){ - const bool miss = m_misses.banner == m_misses.banners++; - m_misses.missed |= miss; - return miss; - } - bool on_map(const std::string& map) const{ - return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); - } - - GridSim& m_sim; - GridSimRouteIO m_route; - SimMisses& m_misses; - std::function m_far_side; -}; - -// A hold until something stops us. A door stops it at the fade, which -// fails the step; a fade missed lets the hold go on past the mouth (r81's -// timed walk south out of the Ravaged Path, onto Route 204's cliff). -void SimStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ - m_sim.tap(direction, ROUTE_TURN_TAP, false); - Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); - SimMove move = m_sim.hold(direction, limit, SimPace::WALK); - if (move.stop == SimStop::WARP && fade_missed() && m_far_side()){ - limit -= std::min(limit, move.time); - move = m_sim.hold(direction, limit, SimPace::WALK); - } - if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ - m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); - } -} - -// The D-pad, a tile at a time, until `map`'s banner reads; through a door -// the walk goes on beyond it (the fade eats no tiles of a hold). -bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&){ - const bool miss = banner_missed(); - size_t on = 0; - for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ - SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); - const bool crossed = move.stop == SimStop::WARP && m_far_side(); - const bool stopped = !crossed && (move.distance == 0 || move.stop != SimStop::DONE); - on = on_map(map) ? on + 1 : 0; - if (on > 0 && (on > SIM_BANNER_TILES || stopped) && !miss){ - return true; - } - if (stopped){ - return false; - } - } - return false; -} - -// D-pad taps, each looked at, until the fade and then the banner (the -// console's ConsoleStoryStepIO::tap_to_banner()). Each look stands still, -// so a banner on the far side reads at once. A fade seen ends the taps, -// banner or not; with the fade missed the next look still sees the banner. -std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ - bool crossed = false; - for (size_t tap = 1; tap <= max_taps; tap++){ - const SimMove move = m_sim.tap(direction, 160ms, false); - if (move.stop == SimStop::DIALOG){ - return std::nullopt; - } - bool faded = false; - if (move.stop == SimStop::WARP){ - faded = !fade_missed(); - crossed = m_far_side(); - } - if (crossed && on_map(map) && !banner_missed()){ - return tap; - } - if (faded){ - return std::nullopt; - } - } - return std::nullopt; -} - -// A scene's trigger the simulation fires from row `row` on, once the step -// `after` has run ("" from the row's start), on `map`'s `tiles`. -struct RowTrigger{ - std::string row; - std::string after; - std::string map; - SimTrigger trigger; -}; - -// When a story variable holds the value its coord events wait for: from -// row `row` on, once the step `after` has run ("" from the row's start). -struct VarState{ - std::string var; - int value; - std::string row; - std::string after; -}; - -// The story variables whose coord events the table walks onto, from the -// row (and step) the table's reasons give, with the maps' coord events -// (Diamond's zone events; Platinum's for the houses): Barry's doorstep and -// Mom's warning in 00.01, Barry's Route 201 warning, then its pull-back -// row 19 once he has warned us (r14, r16); the lake's entrance in 00.02; -// Rowan's stop and Dawn at Sandgem's edge in 00.03; Dawn's catching -// tutorial on Route 202 from 00.04's start, Mom's call once she has healed -// us; the Poketch president on Jubilife's row 40 in 00.05b; Barry on Route -// 203 in 01.01; the Gate's Hiker and Oreburgh's welcome in 01.02; Barry's -// bump in Oreburgh after Roark in 01.05; and Rowan in Jubilife in 01.07. -// Left out: the Twinleaf guitarist (spent upstairs), Platinum's rival -// steps around our bedroom's start, Dawn at Jubilife's steps (BDSP starts -// her below them: an event), and Floaroma's (10..12, 29) (Diamond only). -std::vector story_vars(){ - return { - {.var = "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", .value = 0, .row = "00.01", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 0, .row = "00.01", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 1, .row = "00.01", .after = "barry_warns_us"}, - {.var = "VAR_VERITY_LAKEFRONT_STATE", .value = 0, .row = "00.02", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 2, .row = "00.03", .after = ""}, - {.var = "VAR_SANDGEM_TOWN_STATE", .value = 0, .row = "00.03", .after = ""}, - {.var = "VAR_ROUTE_202_STATE", .value = 0, .row = "00.04", .after = ""}, - {.var = "CONSOLE_MOMS_CALL", .value = 0, .row = "00.04", .after = "mom_heals_us"}, - {.var = "VAR_POKETCH_CAMPAIGN_STATE", .value = 1, .row = "00.05b", .after = ""}, - {.var = "VAR_ROUTE_203_RIVAL_STATE", .value = 0, .row = "01.01", .after = ""}, - {.var = "VAR_OREBURGH_GATE_1F_HIKER_STATE", .value = 1, .row = "01.02", .after = ""}, - {.var = "VAR_OREBURGH_CITY_STATE", .value = 0, .row = "01.02", .after = ""}, - {.var = "VAR_OREBURGH_CITY_STATE", .value = 2, .row = "01.05", .after = ""}, - {.var = "VAR_JUBILIFE_CITY_STATE", .value = 3, .row = "01.07", .after = ""}, - }; -} - -// The maps' coord events (story_coord_events()) whose variable holds. -std::optional var_state(const CoordEvent& event){ - for (const VarState& state : story_vars()){ - if (state.var == event.var && state.value == event.value){ - return state; - } - } - return std::nullopt; -} - -RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ - return {.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; -} - -std::vector story_triggers(){ - std::vector triggers; - for (const auto& [map, json] : bdsp_map_json()){ - for (const CoordEvent& event : story_coord_events(map)){ - const std::optional state = var_state(event); - if (state){ - triggers.push_back(row_trigger(map, event, *state)); - } - } - } - return triggers; -} - -// Someone the maps do not have, on `tile` of `map`, talked to or walked round: -// from row `row` on, until row `until_row`'s step `until` has run if it is set. -struct SimPerson{ - std::string name; - std::string map; - TilePos tile; - std::string row; - std::string until_row = {}; - std::string until = {}; -}; -std::vector sim_people(){ - return { - // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). - {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04"}, - // Barry in the Gym's door, from the welcome (lab-B 2026-11-08) to his lines (r101, r104). - {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.02b", .until_row = "01.02b", .until = "barrys_lines"}, - }; -} - -// A house's stairs, entered by a step `side` from the map's "stairs" -// point into what the map draws as a wall (the table's 00.01: r8 and r9 -// for ours, r11 for Barry's). -struct SimStairs{ - std::string map; - Direction side; -}; -std::vector sim_stairs(){ - return { - {.map = "PlayerHouse2F", .side = Direction::EAST}, - {.map = "RivalHouse1F", .side = Direction::EAST}, - {.map = "RivalHouse2F", .side = Direction::WEST}, - }; -} - -// The program's walking steps on the simulation, the rest stubbed. -class SimExecutor : public Pokemon::StoryStepExecutor{ -public: - explicit SimExecutor(Logger& logger, SimMisses misses = {}) - : m_logger(logger) - , m_misses(misses) - , m_sim({}, {0, 0}, Direction::NORTH, false) - , m_io(m_sim, m_notes, m_misses, [this]{ return cross(); }) - , m_walks(m_io) - {} - - const SimMisses& misses() const{ - return m_misses; - } - const SimRun& result() const{ - return m_result; - } - virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ - m_row = data.id; - m_start_mismatch = data.start ? off_pose(*data.start) : ""; - m_ran.clear(); - m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); - m_walks.begin_attempt(data.id); - arm(""); - } - virtual Outcome run(RunState& state, const StoryStep& step) override; - -protected: - virtual Outcome route(RunState& state, const StoryStep& step) override{ return m_walks.route(state, step); } - virtual Outcome legs(RunState& state, const StoryStep& step) override{ return m_walks.legs(state, step); } - virtual Outcome step(RunState& state, const StoryStep& step) override{ return m_walks.step(state, step); } - virtual Outcome talk(RunState& state, const StoryStep& step) override{ return m_walks.talk(state, step); } - virtual Outcome mash(RunState& state, const StoryStep& step) override{ return m_walks.mash(state, step); } - virtual Outcome heal(RunState& state, const StoryStep& step) override; - virtual Outcome new_game(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome options(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome answer(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome battle(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome train(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome shop(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome save(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome game(RunState&, const StoryStep&) override{ return stub(); } - -private: - // A step the simulation does not play: its dialogue opened and closed. - Outcome stub(){ - m_sim.end_dialogue(); - return Pokemon::outcome_ok(); - } - const StoryWorld* sim_world(const std::string& map) const; - SimWorld setup(const StoryWorld* world) const; - void arm(const std::string& after); - bool sync(const Pose& pose, const StoryWorld* on = nullptr); - bool cross(); - std::string off_pose(const Pose& pose) const; - std::string check(const StoryStep& step, const Outcome& outcome); - Outcome run_step(RunState& state, const StoryStep& step); - - Logger& m_logger; - std::vector m_notes; - SimMisses m_misses; - GridSim m_sim; - SimStoryStepIO m_io; - StoryWalkSteps m_walks; - // The planner's worlds with sim_people() on them, by world and who. - mutable std::map, std::unique_ptr> m_peopled; - // The steps of this row that have run. - std::set m_ran; - std::string m_row; - std::vector m_armed; - // Where the step running now ends, if it says: a door's far side. - std::optional m_far; - // Why the player is not on this row's start, or "". - std::string m_start_mismatch; - // Whether the player has been put on a map yet. - bool m_placed = false; - // Whether the step running now is on a room with no map. - bool m_passed_over = false; - SimRun m_result; -}; - -// The world the player walks on for `map`: the planner's, with what the -// console showed that the maps lack. Nothing for a room with no map. -const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ - const StoryWorld* world = story_plan_world(map, map); - std::vector here; - std::string who; - for (const SimPerson& person : sim_people()){ - const bool now = m_row >= person.row && (person.until.empty() || m_row < person.until_row || - (m_row == person.until_row && !m_ran.contains(person.until))); - if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ - here.push_back(person); - who += person.name + ";"; - } - } - if (here.empty()){ - return world; - } - std::unique_ptr& peopled = m_peopled[{world, who}]; - if (!peopled){ - peopled = std::make_unique(*world); - for (const SimPerson& person : here){ - peopled->block(story_to_world(*world, person.map, person.tile)); - } - } - return peopled.get(); -} - -SimWorld SimExecutor::setup(const StoryWorld* world) const{ - // B runs once the shoes' scene has given them: the scene ends at home. - SimWorld out{.world = world, .trainers = story_trainers(*world), .can_run = m_walks.can_run()}; - for (const SimStairs& stairs : sim_stairs()){ - if (sim_world(stairs.map) == world){ - out.doors.push_back(story_to_world(*world, stairs.map, map_point(stairs.map, "stairs").next(stairs.side))); - } - } - for (const RowTrigger& armed : m_armed){ - if (sim_world(armed.map) != world){ - continue; - } - SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; - for (const TilePos& pos : armed.trigger.tiles){ - trigger.tiles.push_back(story_to_world(*world, armed.map, pos)); - } - out.triggers.push_back(std::move(trigger)); - } - return out; -} - -// Arms the triggers of this row that start after `after`. -void SimExecutor::arm(const std::string& after){ - size_t armed = 0; - for (const RowTrigger& trigger : story_triggers()){ - if (trigger.row == m_row && trigger.after == after){ - m_armed.push_back(trigger); - armed++; - } - } - const SimPlayer& player = m_sim.player(); - if (armed > 0 && m_placed && on_grid(player.pos) && !player.dialog){ - m_sim.place(setup(&m_sim.world()), nearest_tile(player.pos), player.facing); - } -} - -// Puts the player on `pose`, on the world `on` if given, unless they stand -// on one of its tiles already. Returns whether the pose is on a map the -// simulation has. -bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ - const std::vector tiles = Pokemon::tiles_of(pose); - const StoryWorld* world = on != nullptr ? on : pose.map.empty() ? nullptr : sim_world(pose.map); - if (world == nullptr || tiles.empty()){ - return false; - } - const SimPlayer& player = m_sim.player(); - const std::optional local = !m_placed || &m_sim.world() != world - ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); - if (local && on_grid(player.pos) && std::find(tiles.begin(), tiles.end(), *local) != tiles.end()){ - return true; - } - m_sim.place(setup(world), story_to_world(*world, pose.map, tiles.front()), Pokemon::facing_of(pose)); - m_placed = true; - return true; -} - -// Through a door or a cave mouth onto the step's far side, the player's -// facing kept: a hold goes on from there. -bool SimExecutor::cross(){ - const StoryWorld* world = m_far ? sim_world(m_far->map) : nullptr; - const std::vector tiles = m_far ? Pokemon::tiles_of(*m_far) : std::vector{}; - if (world == nullptr || tiles.empty()){ - return false; - } - m_sim.place(setup(world), story_to_world(*world, m_far->map, tiles.front()), std::nullopt); - return true; -} - -// Why the player does not stand on one of `pose`'s tiles, or "" if they -// do or the simulation cannot tell (no map, or not placed yet). -std::string SimExecutor::off_pose(const Pose& pose) const{ - const std::vector tiles = Pokemon::tiles_of(pose); - if (!m_placed || tiles.empty() || sim_world(pose.map) == nullptr){ - return ""; - } - const SimPlayer& player = m_sim.player(); - const TilePos at = nearest_tile(player.pos); - // In world tiles: a pose a leg worked out from the map it started on - // may lie past that map's edge, on the next map (Twinleaf's exit). - // story_to_world() throws for a map not on the player's world. - try{ - const auto there = [&](const TilePos& tile){ return story_to_world(m_sim.world(), pose.map, tile) == at; }; - if (on_grid(player.pos) && std::ranges::any_of(tiles, there)){ - return ""; - } - }catch (const InternalProgramError&){} - return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), at), Pokemon::to_string(pose)); -} - -// The program's run into the Center: past its door, the inside shows, a missed fade or not. -Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ - if (!sync(state.pose)){ - return Pokemon::outcome_ok(); - } - run_into_center(m_io, m_walks.can_run(), [this]{ - m_misses.fade_unseen = false; - return m_sim.player().warped.has_value(); - }, [&]{ - throw GridSimFailure{step.name + ": no door north of " + to_string(m_sim.player().pos)}; - }); - return Pokemon::outcome_ok(); -} - -// Why a walking step did not end where the table says, or "". A step -// through a door the simulation did not cross is not checked: the sim's -// maps have no warps' destinations. -std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ - const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP; - const std::optional expected = step.pose_after ? step.pose_after : outcome.pose; - if (!walks || !m_placed){ - return ""; - } - if (!expected || Pokemon::tiles_of(*expected).empty()){ - m_result.unchecked.push_back(m_row + " " + step.name); - return ""; - } - const SimPlayer& player = m_sim.player(); - if (player.warped && !story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos))){ - return ""; - } - return off_pose(*expected); -} - -Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ - if (!m_start_mismatch.empty()){ - return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); - } - m_far = step.pose_after; - if (story_events().contains(step.variant)){ - return stub(); - } - // A scene goes on from where the step before left us. A route walks - // on the world it plans on (Jubilife alone has no Route 204 north of it). - const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || - step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK; - const StoryWorld* on = step.kind == StoryStepKind::ROUTE && step.target && !state.pose.map.empty() - ? story_plan_world(state.pose.map, step.target->map) : nullptr; - // A world of one map is sim_world()'s, with its people. - if (on != nullptr && on == story_plan_world(state.pose.map, state.pose.map)){ - on = nullptr; - } - if (walks && !sync(state.pose, on)){ - m_logger.log(std::format("[{}] {}: no map for {}; passed over.", m_row, step.name, Pokemon::to_string(state.pose))); - m_passed_over = true; - return Pokemon::outcome_ok(); - } - return Pokemon::StoryStepExecutor::run(state, step); -} - -Outcome SimExecutor::run(RunState& state, const StoryStep& step){ - Outcome outcome; - m_passed_over = false; - try{ - outcome = run_step(state, step); - }catch (const GridSimFailure& e){ - outcome = Pokemon::outcome_failed("sim_failure", e.message); - } - const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; - if (!mismatch.empty()){ - outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); - } - // What the simulation does not play (scenes, events, battles) ends - // where the table says it does. - if (outcome.succeeded() && step.pose_after){ - sync(*step.pose_after); - } - m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); - if (std::exchange(m_misses.missed, false) && m_result.missed_step.empty()){ - m_result.missed_step = m_row + " " + step.name; - } - if (!outcome.succeeded() && m_result.error.empty()){ - // The walker's last notes, to see why. - for (size_t i = m_notes.size() - std::min(m_notes.size(), 40); i < m_notes.size(); i++){ - m_logger.log(std::format("[{}] note: {}", m_row, m_notes[i])); - } - m_result.error = m_row + " " + Pokemon::to_string(outcome); - m_result.failed_step = m_row + " " + step.name; - } - m_result.world = m_placed ? &m_sim.world() : nullptr; - m_result.end = nearest_tile(m_sim.player().pos); - m_ran.insert(step.name); - arm(step.name); - return outcome; -} - -// Runs `range` of `rows` (the table unless given) on `executor`, stopping -// at the first failure. -Pokemon::SegmentReport run_rows_on( - SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, - const std::vector& rows = story_checkpoints() -){ - std::set saved; - Pokemon::Segment segment = make_story_segment(rows, executor, saved); - Pokemon::SegmentPolicy policy; - policy.stop_at_first_failure = true; - Pokemon::SegmentHooks hooks; - hooks.reload = [](RunState&){ return Pokemon::outcome_ok(); }; - hooks.log = [&logger](const std::string& line){ logger.log(line); }; - RunState state; - return Pokemon::run_segment(state, segment, range, policy, hooks); -} // Runs `range` of the table on the simulation, stopping at the first failure. UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ @@ -685,19 +80,6 @@ UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ return true; } -// The table with row `row`'s step of `step`'s name replaced by `step`. -std::vector table_with(const std::string& row, const StoryStep& step){ - std::vector rows = story_checkpoints(); - for (StoryCheckpoint& checkpoint : rows){ - for (StoryStep& old : checkpoint.steps){ - if (checkpoint.id == row && old.name == step.name){ - old = step; - return rows; - } - } - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + step.name + " in " + row); -} bool ends_on(const SimRun& run, const Pose& pose){ const std::vector tiles = Pokemon::tiles_of(pose); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 437d83cce7..e5fb72ada9 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1498,6 +1498,8 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp Source/Pokemon/AutoStory/Pokemon_StoryEvents.h Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp + Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp Source/Pokemon/AutoStory/Pokemon_StorySegments.h Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp @@ -1707,6 +1709,12 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp From 263a6e192a2a0d403c840fcd5eb5303e5fc1e2e1 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 12:56:01 -0800 Subject: [PATCH 02/13] BDSP AutoStory: the old 01.03 for the Monte Carlo test from today's step names --- ...onBDSP_AutoStory_StoryMonteCarlo_Tests.cpp | 27 ++++++++++++++----- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp index 915be68858..993f887f67 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp @@ -119,10 +119,9 @@ UnitTestResult test_row(Logger& logger, const std::string& row, size_t floor){ } -// 01.03 as it was before be57db157 and 4f13c19bb: counted taps across -// Roark's room, and the route to below the Center's door straight into -// the heal. -std::vector old_0103(){ +// 01.03's steps across Roark's room as they were before 4f13c19bb: +// counted taps onto Roark's row, then west against his rock. +std::vector old_steps_to_roark(){ StoryStep taps; taps.kind = Pokemon::StoryStepKind::LEGS; taps.name = "above_roarks_row"; @@ -133,8 +132,21 @@ std::vector old_0103(){ {.direction = Direction::WEST, .tiles = 2}, {.direction = Direction::SOUTH, .tiles = 2}, }; taps.pose_after = Pokemon::tile_pose("OreburghMine", {TilePos{27, 28}}, Direction::SOUTH); - const std::vector added{"around_the_rock", "down_column_29", - "south_of_the_centers_door", "against_the_walls_east_of_the_door", "below_the_centers_door_lined_up"}; + StoryStep walls; + walls.kind = Pokemon::StoryStepKind::LEGS; + walls.name = "beside_roarks_rock"; + walls.variant = "to_wall"; + walls.legs = {{.direction = Direction::WEST, .tiles = 7}, {.direction = Direction::SOUTH, .tiles = 1}}; + walls.pose_after = Pokemon::tile_pose("OreburghMine", {TilePos{20, 29}}, Direction::SOUTH); + return {taps, walls}; +} + +// 01.03 as it was before be57db157 and 4f13c19bb: counted taps across +// Roark's room, and the route to below the Center's door straight into +// the heal. +std::vector old_0103(){ + const std::vector old = old_steps_to_roark(); + const std::vector added{"south_of_the_centers_door", "against_the_walls_east_of_the_door", "below_the_centers_door_lined_up"}; std::vector rows = story_checkpoints(); for (StoryCheckpoint& row : rows){ if (row.id != "01.03"){ @@ -143,7 +155,8 @@ std::vector old_0103(){ std::erase_if(row.steps, [&](const StoryStep& step){ return std::find(added.begin(), added.end(), step.name) != added.end(); }); - std::replace_if(row.steps.begin(), row.steps.end(), [](const StoryStep& step){ return step.name == "above_roarks_row"; }, taps); + std::replace_if(row.steps.begin(), row.steps.end(), [](const StoryStep& step){ return step.name == "to_roarks_corner"; }, old[0]); + std::replace_if(row.steps.begin(), row.steps.end(), [](const StoryStep& step){ return step.name == "beside_roarks_rock"; }, old[1]); } return rows; } From 9834a675b2fe66817097f5acc3e379a856349ed1 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 14:02:15 -0800 Subject: [PATCH 03/13] BDSP AutoStory: the Monte Carlo's disturbances measured on lab-B The disturbance model was harsher than the console: 01.03 seeds drew 8 to 14 wild battles where lab-B met 0 to 2, D-pad taps drifted onto the mine's warp, and a quarter of the seeds missed a fade. The rates now come from lab-B's BDSP runs of 00.00 to 01.11, 2026-10-31 to 11-08, each with how it was counted: caves 16 battles in 838 tiles, grass 10 in about 1,200, taps without drift, a 2% miss per fade or banner looked for. The wanderers' step pace is a rate too; halving it did not change how often Oreburgh's hiker stays in the way. The old-01.03 harness test keeps the first, harsher rates, and finds the Center-door miss from the mine's warp. PA_BDSP_STORY_MC_TRACE= logs one seed's run with its battles and encounter tiles. 01.03 at 500 seeds: 57 to 396 passes (with #226's re-plans on a battle at a leg's first input). Floors are today's 20-seed rates. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryMonteCarlo.cpp | 2 +- .../AutoStory/Pokemon_StoryMonteCarlo.h | 47 ++++++++-- .../PokemonBDSP_AutoStory_SimDisturbance.cpp | 27 +++--- .../PokemonBDSP_AutoStory_SimDisturbance.h | 20 +++-- ...onBDSP_AutoStory_StoryMonteCarlo_Tests.cpp | 90 +++++++++++++------ 5 files changed, 132 insertions(+), 54 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp index 302bd3d0de..f5d147cb2e 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp @@ -46,7 +46,7 @@ DisturbancePlan make_disturbance_plan(uint64_t seed, const DisturbanceRates& rat .missed_banner = std::nullopt, }; SimRandom misses(root.next()); - if (fades + banners > 0 && misses.chance(rates.missed_detection)){ + if (fades + banners > 0 && misses.chance(rates.missed_detection * (double)(fades + banners))){ const size_t which = (size_t)misses.between(0, (int64_t)(fades + banners) - 1); if (which < fades){ plan.missed_fade = which; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h index f91e8e813d..2a57051fcb 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h @@ -54,23 +54,52 @@ class SimRandom{ // How hard a run is disturbed. The rates are per tile the player enters. +// They are measured on lab-B's BDSP runs of rows 00.00 to 01.11, 2026-10-31 +// to 2026-11-08 (its SerialPrograms.log and the one rotated before it, the +// AutoStory program's lines only), as noted on each. struct DisturbanceRates{ - // A wild battle on an encounter tile: Gen IV's rate / 180 a step, with - // the routes' grass at 30 and Oreburgh Mine's caves at 10 (assumed for - // BDSP; the console has not measured them). - double grass_encounter = 30.0 / 180; - double cave_encounter = 10.0 / 180; - // Where a walk that does not end at a wall ends, along its way: off by - // up to this many thousandths of a tile per tile walked, uniformly. + // A wild battle on an encounter tile. Caves: 16 battles in 838 tiles + // (the "[Walk] ...: N moved chunks, M wild battle(s)" lines of 01.03's + // mine steps, 2026-11-07 and 08; their taps move a tile a chunk). Per + // run it is less: 42 battles in the 71 runs that reached the mine, at + // the 52 cave tiles the simulation walks there, 1.1%. Grass: 10 + // battles in about 1,200 tiles, from the battles logged in the steps of + // 00.03, 00.04d, 01.06 and 01.08 that cross grass, times each step's + // runs, times the grass tiles the simulation walks in it (14, 43, 12, + // 13). Gen IV's rate / 180 (30 and 10 there) drew 8 to 14 battles a + // 01.03 run; the console met 0 to 2. + double grass_encounter = 10.0 / 1200; + double cave_encounter = 16.0 / 838; + // Where a stick hold that does not end at a wall ends, along its way: + // off by up to this many thousandths of a tile per tile walked, + // uniformly. Not measured. int drift_per_tile = 150; + // The same for D-pad taps, which move whole tiles: 54 runs of 01.03's + // above_the_mine ended nine open taps on the tile above the mine's + // warp, none on the warp. One open leg of the 466 of more than a tile + // went a tile past (11:55 on 2026-11-08); that is not modelled. + int tap_drift_per_tile = 0; // Off by no more than this, the player still fits a one-tile gap (a // door, a corridor); past it the player covers two tiles. Assumed: a // door frame stopped a player 0.375 tile off (the grid sim's measure). int fit = 250; // Someone wandering starts their walk up to this far into it. Milliseconds wanderer_start = Milliseconds(10000); - // The chance a seed misses one of the row's fades or banners. - double missed_detection = 0.25; + // Someone wandering tries a step this often (a fifth of the tries they + // stay). Oreburgh's hiker stopped 15 of 54 above_the_mine runs short of + // the wall ("stopped after about N tiles"); in 11 the way cleared after + // taps or waits, 4 talked to him, 1 failed with no plan. The simulation + // at 2000 ms: 17 of 100 seeds stopped, 16 talked, 16 failed; at 1000 ms + // 16, 14 and 14. The step's pace is not what keeps him in the way. + Milliseconds wander_step = Milliseconds(2000); + // The chance a seed misses each fade or banner its row looks for (it + // misses one at most). The door's own watcher missed 13 of 35 fades, + // but settle() then saw each arrival: no door step of 01.03 failed for + // a fade on 2026-11-08. Over the whole week 9 door steps failed "no + // fade within 120 s" in about 230 settles, most of them a step that + // had not reached its door; 2 required banners went unread, both + // 01.03's old out_of_the_mine. + double missed_detection = 0.02; }; // One seed's disturbances: independent random streams for each kind, so a diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp index 4076fef942..019fb8f47b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp @@ -26,8 +26,6 @@ namespace{ // The caves on the story's way, where every tile has wild Pokemon. constexpr const char* CAVE_MAPS[] = {"OreburghMineB1F", "OreburghMine", "RavagedPath"}; -// How often a wanderer tries a step (the grid sim's default). -constexpr Milliseconds WANDER_STEP = 2000ms; // Drift comes in steps of this many thousandths of a tile: 4 ms of stick // across, 6 ms up or down, so the grid sim puts it back on the grid exactly. constexpr int DRIFT_STEP = 25; @@ -96,8 +94,11 @@ bool SimDisturbance::battle_at(const StoryWorld& world, const TilePos& pos){ if (!tile){ return false; } - const double rate = *tile == TileKind::TALL_GRASS ? m_plan.rates.grass_encounter - : in_cave(world, pos) ? m_plan.rates.cave_encounter : 0; + const bool grass = *tile == TileKind::TALL_GRASS; + const bool cave = !grass && in_cave(world, pos); + m_tiles.grass += grass ? 1 : 0; + m_tiles.cave += cave ? 1 : 0; + const double rate = grass ? m_plan.rates.grass_encounter : cave ? m_plan.rates.cave_encounter : 0; if (rate <= 0 || !m_plan.battles.chance(rate)){ return false; } @@ -123,7 +124,7 @@ void SimDisturbance::sync(const GridSim& sim){ } } -void SimDisturbance::walked(GridSim& sim, Direction direction, int thousandths, bool at_wall){ +void SimDisturbance::walked(GridSim& sim, Direction direction, int thousandths, bool at_wall, int drift_per_tile){ sync(sim); Axis& axis = across(direction) ? m_x : m_y; if (at_wall){ @@ -131,7 +132,7 @@ void SimDisturbance::walked(GridSim& sim, Direction direction, int thousandths, return; } // In steps of DRIFT_STEP, which a stick press moves exactly. - const int64_t most = m_plan.rates.drift_per_tile / DRIFT_STEP; + const int64_t most = drift_per_tile / DRIFT_STEP; const int64_t steps = m_plan.drift.between(-most, most) * thousandths / SIM_TILE; axis.drift = std::clamp(axis.drift + (int)steps * DRIFT_STEP, -SIM_TILE + 100, SIM_TILE - 100); materialize(sim, across(direction)); @@ -196,7 +197,7 @@ void SimDisturbance::add_people(std::vector& people, const std::str } const Pokemon::TileBox& box = *object.wander; people.push_back({.name = name, .box = {corner.x + box.x0, corner.y + box.y0, corner.x + box.x1, corner.y + box.y1}, - .pos = {corner.x + object.x, corner.y + object.y}, .step_interval = WANDER_STEP}); + .pos = {corner.x + object.x, corner.y + object.y}}); } } @@ -205,6 +206,7 @@ std::vector SimDisturbance::wanderers(const StoryWorld& world){ for (SimWanderer& person : out){ person.seed = m_plan.wanderers.next(); person.time_offset = Milliseconds(m_plan.wanderers.between(0, m_plan.rates.wanderer_start.count())); + person.step_interval = m_plan.rates.wander_step; } return out; } @@ -234,7 +236,7 @@ DisturbedHold disturbed_hold(GridSim& sim, SimDisturbance* noise, Direction dire out.move.time = ROUTE_START_DELAY + tile_time * out.move.distance / SIM_TILE + seen; } if (out.move.stop == SimStop::LIMIT || out.move.stop == SimStop::BLOCKED){ - noise->walked(sim, direction, SIM_TILE, stopped_at_wall(sim, out.move, direction)); + noise->walked(sim, direction, SIM_TILE, stopped_at_wall(sim, out.move, direction), noise->plan().rates.drift_per_tile); } return out; } @@ -256,7 +258,7 @@ WalkResult DisturbedRouteIO::walk_to_wall(const RouteWallWalk& walk){ return result; } -// A tap a tile, as GridSimRouteIO taps; a battle on a tile stepped onto +// A tap a tile, as GridSimRouteIO taps, drifting as the rates say; a battle on a tile stepped onto // is fled and credited as a moved tile, as the console's walk credits it, // and the taps go on. One on the first tap may have begun before it. WalkResult DisturbedRouteIO::walk_taps(Direction direction, size_t tiles, const std::string& label){ @@ -275,8 +277,9 @@ WalkResult DisturbedRouteIO::walk_taps(Direction direction, size_t tiles, const }else if (still >= 2){ result.stop = WalkStop::BLOCKED; } - if (move.distance > 0 && result.stop == WalkStop::LIMIT){ - m_noise->walked(m_sim, direction, SIM_TILE, false); + const int tap_drift = m_noise->plan().rates.tap_drift_per_tile; + if (move.distance > 0 && result.stop == WalkStop::LIMIT && tap_drift > 0){ + m_noise->walked(m_sim, direction, SIM_TILE, false, tap_drift); } if (move.distance > 0 && move.stop == SimStop::DONE && m_noise->battle_at(m_sim.world(), nearest_tile(m_sim.player().pos))){ result.wild_battles++; @@ -298,7 +301,7 @@ void DisturbedRouteIO::press(const RouteInput& input){ } const int moved = std::abs(along(m_sim.player().pos, input.direction) - along(before, input.direction)); if (moved > 0){ - m_noise->walked(m_sim, input.direction, moved, false); + m_noise->walked(m_sim, input.direction, moved, false, m_noise->plan().rates.drift_per_tile); } } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.h index 978a31d4e3..838acb5187 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.h @@ -8,9 +8,9 @@ * - A wild battle on tall grass, or anywhere in a cave (Oreburgh Mine, * the Ravaged Path), once the player has stepped onto the tile. It is * fled, and the input goes on, as the console's walks go on. - * - Drift: a tap, a stick press or a hold stopped short of a wall ends - * up to DisturbanceRates::drift_per_tile off along its way, and taps - * add up. Within DisturbanceRates::fit of the tile the player still + * - Drift: a stick press or a hold stopped short of a wall ends up to + * DisturbanceRates::drift_per_tile off along its way, a D-pad tap up + * to DisturbanceRates::tap_drift_per_tile (none by default). Within DisturbanceRates::fit of the tile the player still * fits a one-tile gap; past it, the grid sim has them part of a tile * off, where a door frame or a rock's corner stops them. A walk that * stops at a wall ends on its tile, and on the grid along that way. @@ -45,11 +45,20 @@ class SimDisturbance{ size_t battles() const{ return m_battles; } + // Encounter tiles stepped onto so far. + struct EncounterTiles{ + size_t grass = 0; + size_t cave = 0; + }; + const EncounterTiles& encounter_tiles() const{ + return m_tiles; + } // Whether stepping onto world tile `pos` starts a wild battle. bool battle_at(const StoryWorld& world, const Pokemon::TilePos& pos); // The player moved `thousandths` of a tile toward `direction` and did - // not stop at a wall (or, `at_wall`, stopped at one): drifts them. - void walked(GridSim& sim, Pokemon::Direction direction, int thousandths, bool at_wall); + // not stop at a wall (or, `at_wall`, stopped at one): drifts them by up + // to `drift_per_tile` thousandths a tile walked. + void walked(GridSim& sim, Pokemon::Direction direction, int thousandths, bool at_wall, int drift_per_tile); // The player was put on a tile: no drift. void reset(); // The people who wander on `world`, each with a seed and start drawn. @@ -69,6 +78,7 @@ class SimDisturbance{ Pokemon::DisturbancePlan m_plan; size_t m_battles = 0; + EncounterTiles m_tiles; Axis m_x; Axis m_y; std::map> m_people; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp index 993f887f67..140fa47937 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp @@ -39,6 +39,7 @@ using Pokemon::TilePos; constexpr const char* SEEDS_VARIABLE = "PA_BDSP_STORY_MC_SEEDS"; constexpr const char* ROWS_VARIABLE = "PA_BDSP_STORY_MC_ROWS"; +constexpr const char* TRACE_VARIABLE = "PA_BDSP_STORY_MC_TRACE"; constexpr size_t DEFAULT_SEEDS = 20; // The runs log nothing: a seed's own log is a reproduction away. @@ -74,13 +75,34 @@ SeedOutcome failed_outcome(const Pokemon::SegmentReport& report, const SimRun& r return out; } -// Row `row` of `rows`, disturbed by `seed`. -SeedOutcome run_seed(const std::vector& rows, const SimMisses& clean, const std::string& row, uint64_t seed){ - SimDisturbance noise(Pokemon::make_disturbance_plan(seed, Pokemon::DisturbanceRates{}, clean.fades, clean.banners)); - SilentLogger logger; +// How a row's seeds are disturbed: at `rates`, missing one of the fades +// and banners its undisturbed run looked for (`clean`). +struct RowNoise{ + SimMisses clean; + Pokemon::DisturbanceRates rates; +}; + +// The rates the harness was first built with, harsher than lab-B's (see +// DisturbanceRates): Gen IV's encounter rates, taps that drift as the +// stick does, and a miss in about a quarter of 01.03's seeds. +Pokemon::DisturbanceRates stress_rates(){ + Pokemon::DisturbanceRates rates; + rates.grass_encounter = 30.0 / 180; + rates.cave_encounter = 10.0 / 180; + rates.tap_drift_per_tile = rates.drift_per_tile; + rates.missed_detection = 0.04; + return rates; +} + +// Row `row` of `rows`, disturbed by `seed`, logging to `logger`. +SeedOutcome run_seed(Logger& logger, const std::vector& rows, const RowNoise& noise_of, const std::string& row, uint64_t seed){ + const SimMisses& clean = noise_of.clean; + SimDisturbance noise(Pokemon::make_disturbance_plan(seed, noise_of.rates, clean.fades, clean.banners)); SimExecutor executor(logger, {.fade = noise.plan().missed_fade, .banner = noise.plan().missed_banner}, &noise); try{ const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = row, .to = row}, rows); + logger.log(std::format("[Sim] {}: {} wild battle(s) over {} grass and {} cave tiles.", describe(noise.plan()), + noise.battles(), noise.encounter_tiles().grass, noise.encounter_tiles().cave)); return report.completed ? SeedOutcome{.passed = true} : failed_outcome(report, executor.result(), noise); }catch (const GridSimFailure& e){ return {.failed_step = row + " (thrown)", .kind = Pokemon::failure_kind("sim_failure", e.message), .detail = describe(noise.plan())}; @@ -89,10 +111,13 @@ SeedOutcome run_seed(const std::vector& rows, const SimMisses& } } -RowReport run_row(const std::vector& rows, const std::string& row, size_t seeds){ - const SimMisses clean = looked_for(rows, row); +RowReport run_row(const std::vector& rows, const std::string& row, size_t seeds, + const Pokemon::DisturbanceRates& rates = {} +){ + const RowNoise noise{.clean = looked_for(rows, row), .rates = rates}; return Pokemon::run_row_seeds(row, Pokemon::story_seeds(seeds), [&](const std::string& id, uint64_t seed){ - return run_seed(rows, clean, id, seed); + SilentLogger logger; + return run_seed(logger, rows, noise, id, seed); }); } @@ -105,6 +130,14 @@ UnitTestResult test_row(Logger& logger, const std::string& row, size_t floor){ if (Pokemon::selected_rows(ROWS_VARIABLE, {row}).empty()){ return {UnitTestResult::SKIPPED, std::string(ROWS_VARIABLE) + " leaves it out"}; } + // One seed's run, logged step by step: how a failure the report + // names came about. + if (const size_t traced = Pokemon::seed_count(TRACE_VARIABLE, 0); traced > 0){ + const std::vector rows = story_checkpoints(); + const SeedOutcome out = run_seed(logger, rows, {.clean = looked_for(rows, row), .rates = {}}, row, traced); + logger.log(std::format("{} seed {}: {} {} {}", row, traced, out.passed ? "passed" : "failed", out.failed_step, out.kind)); + return true; + } const size_t seeds = Pokemon::seed_count(SEEDS_VARIABLE, DEFAULT_SEEDS); const WallClock start = current_time(); const RowReport report = run_row(story_checkpoints(), row, seeds); @@ -189,17 +222,20 @@ bool failed_with(const RowReport& report, const std::string& step, const std::st // lab-B 2026-11-08: a wild battle on the counted taps across Roark's room // re-planned to an open leg and the row went one off (11:55); a run up // Oreburgh's column 46 stopped short and an open step east left us off the -// Center door's column (10:39). The old row must show both. +// Center door's column (10:39). The old row must show both, at the stress +// rates: at lab-B's own, 200 seeds need not draw them. UnitTestResult test_old_0103(Logger& logger){ const size_t seeds = std::max(200, Pokemon::seed_count(SEEDS_VARIABLE, DEFAULT_SEEDS)); - const RowReport whole = run_row(old_0103(), "01.03", seeds); + const RowReport whole = run_row(old_0103(), "01.03", seeds, stress_rates()); logger.log("The old 01.03: " + Pokemon::format_report(whole)); - const RowReport town = run_row(from_the_mines_sign(old_0103()), "01.03", seeds); + const RowReport town = run_row(from_the_mines_sign(old_0103()), "01.03", seeds, stress_rates()); logger.log("The old 01.03 from the mine's sign: " + Pokemon::format_report(town)); - logger.log("Today's 01.03 from the mine's sign: " + Pokemon::format_report(run_row(from_the_mines_sign(story_checkpoints()), "01.03", seeds))); + logger.log("Today's 01.03 from the mine's sign: " + Pokemon::format_report( + run_row(from_the_mines_sign(story_checkpoints()), "01.03", seeds, stress_rates()))); // A battle on the taps, then the row ends off the tile the taps count. const bool roark = failed_with(whole, "01.03 above_roarks_row", "sim_mismatch", "[wild battle in the step]"); - const bool center = failed_with(town, "01.03 heal_oreburgh", "no door north"); + // From the mine's warp (the whole row) or the sign. + const bool center = failed_with(whole, "01.03 heal_oreburgh", "no door north") || failed_with(town, "01.03 heal_oreburgh", "no door north"); if (!roark || !center){ return std::format("expected the old 01.03 to fail across Roark's room after a wild battle ({}) and at the Center's door ({}):\n{}\n{}", roark, center, Pokemon::format_report(whole), Pokemon::format_report(town)); @@ -250,27 +286,27 @@ class Test_StoryMonteCarlo : public UnitTest{ const StoryMonteCarloCase AUTO_STORY_MONTE_CARLO_CASES[] = { {.input = {"00.00"}, .expectation = {.floor = 100}}, - {.input = {"00.01"}, .expectation = {.floor = 20}}, + {.input = {"00.01"}, .expectation = {.floor = 95}}, {.input = {"00.02"}, .expectation = {.floor = 100}}, - {.input = {"00.03"}, .expectation = {.floor = 30}}, - {.input = {"00.04"}, .expectation = {.floor = 0}}, - {.input = {"00.04b"}, .expectation = {.floor = 55}}, + {.input = {"00.03"}, .expectation = {.floor = 95}}, + {.input = {"00.04"}, .expectation = {.floor = 95}}, + {.input = {"00.04b"}, .expectation = {.floor = 100}}, {.input = {"00.04c"}, .expectation = {.floor = 100}}, - {.input = {"00.04d"}, .expectation = {.floor = 55}}, - {.input = {"00.05"}, .expectation = {.floor = 70}}, - {.input = {"00.05b"}, .expectation = {.floor = 45}}, - {.input = {"00.05c"}, .expectation = {.floor = 20}}, - {.input = {"01.01"}, .expectation = {.floor = 95}}, - {.input = {"01.02"}, .expectation = {.floor = 20}}, + {.input = {"00.04d"}, .expectation = {.floor = 100}}, + {.input = {"00.05"}, .expectation = {.floor = 100}}, + {.input = {"00.05b"}, .expectation = {.floor = 85}}, + {.input = {"00.05c"}, .expectation = {.floor = 100}}, + {.input = {"01.01"}, .expectation = {.floor = 100}}, + {.input = {"01.02"}, .expectation = {.floor = 85}}, {.input = {"01.02b"}, .expectation = {.floor = 90}}, - {.input = {"01.03"}, .expectation = {.floor = 5}}, + {.input = {"01.03"}, .expectation = {.floor = 75}}, {.input = {"01.04"}, .expectation = {.floor = 100}}, - {.input = {"01.05"}, .expectation = {.floor = 80}}, - {.input = {"01.06"}, .expectation = {.floor = 25}}, + {.input = {"01.05"}, .expectation = {.floor = 100}}, + {.input = {"01.06"}, .expectation = {.floor = 95}}, {.input = {"01.07"}, .expectation = {.floor = 100}}, {.input = {"01.08"}, .expectation = {.floor = 40}}, - {.input = {"01.09"}, .expectation = {.floor = 50}}, - {.input = {"01.10"}, .expectation = {.floor = 5}}, + {.input = {"01.09"}, .expectation = {.floor = 100}}, + {.input = {"01.10"}, .expectation = {.floor = 80}}, {.input = {"01.11"}, .expectation = {.floor = 100}}, { .input = {"the old 01.03 fails across Roark's room and at the Center's door (lab-B, 2026-11-08)", test_old_0103}, From 5bbb7bba6f42049b6131f611cd6ec413cf653a66 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 02:33:23 -0800 Subject: [PATCH 04/13] Story Monte Carlo: drop one fade's hold per seed; every seed that passed still passes DisturbanceRates::missed_hold drops the hold of one fade a row looks for, drawn from a stream of its own so the other draws stay put. The BDSP test runs each row's seeds with and without it (no other miss) and fails on any seed that passes only with every hold seen. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryMonteCarlo.cpp | 7 +++ .../AutoStory/Pokemon_StoryMonteCarlo.h | 11 +++- ...onBDSP_AutoStory_StoryMonteCarlo_Tests.cpp | 55 ++++++++++++++++++- 3 files changed, 70 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp index f5d147cb2e..e2162ff82d 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp @@ -54,6 +54,10 @@ DisturbancePlan make_disturbance_plan(uint64_t seed, const DisturbanceRates& rat plan.missed_banner = which - fades; } } + SimRandom holds(root.next()); + if (fades > 0 && holds.chance(rates.missed_hold)){ + plan.missed_hold = (size_t)holds.between(0, (int64_t)fades - 1); + } return plan; } @@ -65,6 +69,9 @@ std::string describe(const DisturbancePlan& plan){ if (plan.missed_banner){ text += std::format(": miss banner {}", *plan.missed_banner); } + if (plan.missed_hold){ + text += std::format(": fade {}'s hold unseen", *plan.missed_hold); + } return text; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h index 2a57051fcb..42ba7a1f59 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h @@ -100,12 +100,19 @@ struct DisturbanceRates{ // had not reached its door; 2 required banners went unread, both // 01.03's old out_of_the_mine. double missed_detection = 0.02; + // The chance a seed drops the hold of one fade its row looks for: a + // short fade whose dark or white fell between two frames, so only its + // fall and the scene after show. 0 in the rates measured; 1 in the + // tests that every seed survives it. + double missed_hold = 0; }; // One seed's disturbances: independent random streams for each kind, so a // change in how many battles a run draws does not move its drift, and the // one detection the run misses, if any (as an index into the row's fades, -// then its banners, from an undisturbed run). +// then its banners, from an undisturbed run), and the one fade whose hold +// it drops, if any (an index into the row's fades). The hold is drawn +// from a stream of its own, so a plan's other draws do not move with it. struct DisturbancePlan{ uint64_t seed = 0; DisturbanceRates rates; @@ -114,11 +121,13 @@ struct DisturbancePlan{ SimRandom wanderers; std::optional missed_fade; std::optional missed_banner; + std::optional missed_hold = std::nullopt; }; // The plan for `seed`, for a row whose undisturbed run looks for `fades` // fades and `banners` banners. DisturbancePlan make_disturbance_plan(uint64_t seed, const DisturbanceRates& rates, size_t fades, size_t banners); // "seed 17: miss fade 1": what a plan draws up front, to reproduce it. +// A dropped hold reads "fade 2's hold unseen". std::string describe(const DisturbancePlan& plan); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp index 2f9a533a2b..041aeaa9c5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp @@ -9,13 +9,16 @@ * banner. Each row's test logs its pass rate and, per failing step, the * failure kinds with a seed that reproduces each, and fails only below the * row's pinned floor. The old 01.03 test shows the harness finds the two - * failures lab-B met on 2026-11-08. + * failures lab-B met on 2026-11-08. One more runs every row's seeds again + * with one fade's hold unseen: none that passed may fail. * */ #include #include #include +#include +#include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Time.h" #include "Common/Cpp/TestRunners/UnitTest.h" @@ -98,7 +101,7 @@ Pokemon::DisturbanceRates stress_rates(){ SeedOutcome run_seed(Logger& logger, const std::vector& rows, const RowNoise& noise_of, const std::string& row, uint64_t seed){ const SimMisses& clean = noise_of.clean; SimDisturbance noise(Pokemon::make_disturbance_plan(seed, noise_of.rates, clean.fades, clean.banners)); - SimExecutor executor(logger, {.fade = noise.plan().missed_fade, .banner = noise.plan().missed_banner}, {.noise = &noise}); + SimExecutor executor(logger, {.fade = noise.plan().missed_fade, .banner = noise.plan().missed_banner, .hold = noise.plan().missed_hold}, {.noise = &noise}); try{ const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = row, .to = row}, rows); logger.log(std::format("[Sim] {}: {} wild battle(s) over {} grass and {} cave tiles.", describe(noise.plan()), @@ -244,6 +247,50 @@ UnitTestResult test_old_0103(Logger& logger){ } +// Each row of the table for the seeds, each seed run twice: as lab-B +// disturbs it, with no miss, and the same with one fade's hold dropped (a +// short fade between two frames; the door's watcher missed 13 of 35 on +// 2026-11-08). The program's fade watch takes the scene after the fall, +// so no seed that passes the first fails the second. +UnitTestResult test_one_hold_unseen(Logger& logger){ + const size_t seeds = Pokemon::seed_count(SEEDS_VARIABLE, DEFAULT_SEEDS); + const std::vector rows = story_checkpoints(); + Pokemon::DisturbanceRates rates; + rates.missed_detection = 0; + Pokemon::DisturbanceRates hold_rates = rates; + hold_rates.missed_hold = 1; + std::vector broken; + size_t runs = 0; + size_t held = 0; + for (const StoryCheckpoint& checkpoint : rows){ + const std::string& row = checkpoint.id; + if (Pokemon::selected_rows(ROWS_VARIABLE, {row}).empty()){ + continue; + } + const SimMisses clean = looked_for(rows, row); + for (uint64_t seed : Pokemon::story_seeds(seeds)){ + SilentLogger silent; + const SeedOutcome plain = run_seed(silent, rows, {.clean = clean, .rates = rates}, row, seed); + const SeedOutcome hold = run_seed(silent, rows, {.clean = clean, .rates = hold_rates}, row, seed); + runs++; + held += plain.passed && hold.passed ? 1 : 0; + if (plain.passed && !hold.passed){ + broken.push_back(std::format("{} {}: {} {}", row, hold.detail, hold.failed_step, hold.kind)); + } + } + } + logger.log(std::format("One fade's hold unseen: {} of {} runs pass both ways; {} pass only with every hold seen.", held, runs, broken.size())); + if (broken.empty()){ + return true; + } + std::string out = std::format("{} seeds pass with every hold seen and fail with one unseen:", broken.size()); + for (const std::string& line : broken){ + out += "\n " + line; + } + return out; +} + + // A row of the table, disturbed; or, with a body, another test. struct StoryMonteCarloInput{ std::string row; @@ -312,6 +359,10 @@ const StoryMonteCarloCase AUTO_STORY_MONTE_CARLO_CASES[] = { .input = {"the old 01.03 fails across Roark's room and at the Center's door (lab-B, 2026-11-08)", test_old_0103}, .expectation = {}, }, + { + .input = {"one fade's hold unseen: every seed that passes still passes", test_one_hold_unseen}, + .expectation = {}, + }, }; void add_tests_AutoStory_StoryMonteCarlo(UnitTestDatabase& database){ From 6282a775cc9a06522d24c036b04ff816cf3c7ea4 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 02:54:56 -0800 Subject: [PATCH 05/13] Story Monte Carlo: each row reruns its clean passes with one fade's hold unseen The separate serial test ran every row twice (about 19 min); each row's test now reruns only its seeds that passed with no miss, in parallel with the other rows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...onBDSP_AutoStory_StoryMonteCarlo_Tests.cpp | 84 ++++++++----------- 1 file changed, 33 insertions(+), 51 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp index 041aeaa9c5..615388644d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp @@ -9,8 +9,8 @@ * banner. Each row's test logs its pass rate and, per failing step, the * failure kinds with a seed that reproduces each, and fails only below the * row's pinned floor. The old 01.03 test shows the harness finds the two - * failures lab-B met on 2026-11-08. One more runs every row's seeds again - * with one fade's hold unseen: none that passed may fail. + * failures lab-B met on 2026-11-08. Each row's seeds that pass with no + * miss run again with one fade's hold unseen, and must pass again. * */ @@ -143,9 +143,39 @@ UnitTestResult test_row(Logger& logger, const std::string& row, size_t floor){ } const size_t seeds = Pokemon::seed_count(SEEDS_VARIABLE, DEFAULT_SEEDS); const WallClock start = current_time(); - const RowReport report = run_row(story_checkpoints(), row, seeds); + const std::vector rows = story_checkpoints(); + const RowNoise noise{.clean = looked_for(rows, row), .rates = {}}; + RowNoise hold_noise = noise; + hold_noise.rates.missed_hold = 1; + // Each seed that passes with no miss runs again with one fade's hold + // dropped (a short fade between two frames; the door's watcher missed + // 13 of 35 on lab-B, 2026-11-08): the program's fade watch takes the + // scene after the fall, so it must pass again. + size_t rerun = 0; + std::vector hold_failed; + const RowReport report = Pokemon::run_row_seeds(row, Pokemon::story_seeds(seeds), [&](const std::string& id, uint64_t seed){ + SilentLogger silent; + const SeedOutcome out = run_seed(silent, rows, noise, id, seed); + const Pokemon::DisturbancePlan plan = Pokemon::make_disturbance_plan(seed, noise.rates, noise.clean.fades, noise.clean.banners); + if (out.passed && noise.clean.fades > 0 && !plan.missed_fade && !plan.missed_banner){ + rerun++; + const SeedOutcome hold = run_seed(silent, rows, hold_noise, id, seed); + if (!hold.passed){ + hold_failed.push_back(std::format("{}: {} {}", hold.detail, hold.failed_step, hold.kind)); + } + } + return out; + }); const auto took = std::chrono::duration_cast(current_time() - start); logger.log(Pokemon::format_report(report) + std::format("\n ({} seeds in {} ms)", seeds, took.count())); + logger.log(std::format("{}: one fade's hold unseen: {} of {} seeds that passed with no miss fail.", row, hold_failed.size(), rerun)); + if (!hold_failed.empty()){ + std::string out = std::format("{} fails with one fade's hold unseen where it passed without:", row); + for (const std::string& line : hold_failed){ + out += "\n " + line; + } + return out; + } // The floors are the default seeds' counts; other counts only report. if (seeds == DEFAULT_SEEDS && report.passes * 100 < floor * report.runs){ return std::format("{} passed {} of {}, under its floor of {}%:\n{}", row, report.passes, report.runs, @@ -247,50 +277,6 @@ UnitTestResult test_old_0103(Logger& logger){ } -// Each row of the table for the seeds, each seed run twice: as lab-B -// disturbs it, with no miss, and the same with one fade's hold dropped (a -// short fade between two frames; the door's watcher missed 13 of 35 on -// 2026-11-08). The program's fade watch takes the scene after the fall, -// so no seed that passes the first fails the second. -UnitTestResult test_one_hold_unseen(Logger& logger){ - const size_t seeds = Pokemon::seed_count(SEEDS_VARIABLE, DEFAULT_SEEDS); - const std::vector rows = story_checkpoints(); - Pokemon::DisturbanceRates rates; - rates.missed_detection = 0; - Pokemon::DisturbanceRates hold_rates = rates; - hold_rates.missed_hold = 1; - std::vector broken; - size_t runs = 0; - size_t held = 0; - for (const StoryCheckpoint& checkpoint : rows){ - const std::string& row = checkpoint.id; - if (Pokemon::selected_rows(ROWS_VARIABLE, {row}).empty()){ - continue; - } - const SimMisses clean = looked_for(rows, row); - for (uint64_t seed : Pokemon::story_seeds(seeds)){ - SilentLogger silent; - const SeedOutcome plain = run_seed(silent, rows, {.clean = clean, .rates = rates}, row, seed); - const SeedOutcome hold = run_seed(silent, rows, {.clean = clean, .rates = hold_rates}, row, seed); - runs++; - held += plain.passed && hold.passed ? 1 : 0; - if (plain.passed && !hold.passed){ - broken.push_back(std::format("{} {}: {} {}", row, hold.detail, hold.failed_step, hold.kind)); - } - } - } - logger.log(std::format("One fade's hold unseen: {} of {} runs pass both ways; {} pass only with every hold seen.", held, runs, broken.size())); - if (broken.empty()){ - return true; - } - std::string out = std::format("{} seeds pass with every hold seen and fail with one unseen:", broken.size()); - for (const std::string& line : broken){ - out += "\n " + line; - } - return out; -} - - // A row of the table, disturbed; or, with a body, another test. struct StoryMonteCarloInput{ std::string row; @@ -359,10 +345,6 @@ const StoryMonteCarloCase AUTO_STORY_MONTE_CARLO_CASES[] = { .input = {"the old 01.03 fails across Roark's room and at the Center's door (lab-B, 2026-11-08)", test_old_0103}, .expectation = {}, }, - { - .input = {"one fade's hold unseen: every seed that passes still passes", test_one_hold_unseen}, - .expectation = {}, - }, }; void add_tests_AutoStory_StoryMonteCarlo(UnitTestDatabase& database){ From fd6d7f36cb51051ed1d4819dfa18cfd661c1138a Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 02:55:54 -0800 Subject: [PATCH 06/13] Story Monte Carlo: the hold rerun in a helper of its own Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...onBDSP_AutoStory_StoryMonteCarlo_Tests.cpp | 60 +++++++++++-------- 1 file changed, 36 insertions(+), 24 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp index 615388644d..e45feef78b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp @@ -125,6 +125,38 @@ RowReport run_row(const std::vector& rows, const std::string& r } +// A row's seeds (run_row()), and each that passes with no miss run again +// with one fade's hold dropped (a short fade between two frames; the +// door's watcher missed 13 of 35 on lab-B, 2026-11-08): the program's fade +// watch takes the scene after the fall, so it must pass again. How many +// ran again, and those that then failed, as "plan: step kind". +struct HeldRowReport{ + RowReport report; + size_t rerun = 0; + std::vector hold_failed; +}; +HeldRowReport run_row_holding(const std::vector& rows, const std::string& row, size_t seeds){ + const RowNoise noise{.clean = looked_for(rows, row), .rates = {}}; + RowNoise hold_noise = noise; + hold_noise.rates.missed_hold = 1; + HeldRowReport out; + out.report = Pokemon::run_row_seeds(row, Pokemon::story_seeds(seeds), [&](const std::string& id, uint64_t seed){ + SilentLogger silent; + const SeedOutcome plain = run_seed(silent, rows, noise, id, seed); + const Pokemon::DisturbancePlan plan = Pokemon::make_disturbance_plan(seed, noise.rates, noise.clean.fades, noise.clean.banners); + if (plain.passed && noise.clean.fades > 0 && !plan.missed_fade && !plan.missed_banner){ + out.rerun++; + const SeedOutcome hold = run_seed(silent, rows, hold_noise, id, seed); + if (!hold.passed){ + out.hold_failed.push_back(std::format("{}: {} {}", hold.detail, hold.failed_step, hold.kind)); + } + } + return plain; + }); + return out; +} + + // Row `row` for the seeds, under `floor` passes in a hundred a failure: // each row's floor is what it passed at this branch's tip, so a row that // passes less often has got worse. A row PA_BDSP_STORY_MC_ROWS leaves out @@ -143,32 +175,12 @@ UnitTestResult test_row(Logger& logger, const std::string& row, size_t floor){ } const size_t seeds = Pokemon::seed_count(SEEDS_VARIABLE, DEFAULT_SEEDS); const WallClock start = current_time(); - const std::vector rows = story_checkpoints(); - const RowNoise noise{.clean = looked_for(rows, row), .rates = {}}; - RowNoise hold_noise = noise; - hold_noise.rates.missed_hold = 1; - // Each seed that passes with no miss runs again with one fade's hold - // dropped (a short fade between two frames; the door's watcher missed - // 13 of 35 on lab-B, 2026-11-08): the program's fade watch takes the - // scene after the fall, so it must pass again. - size_t rerun = 0; - std::vector hold_failed; - const RowReport report = Pokemon::run_row_seeds(row, Pokemon::story_seeds(seeds), [&](const std::string& id, uint64_t seed){ - SilentLogger silent; - const SeedOutcome out = run_seed(silent, rows, noise, id, seed); - const Pokemon::DisturbancePlan plan = Pokemon::make_disturbance_plan(seed, noise.rates, noise.clean.fades, noise.clean.banners); - if (out.passed && noise.clean.fades > 0 && !plan.missed_fade && !plan.missed_banner){ - rerun++; - const SeedOutcome hold = run_seed(silent, rows, hold_noise, id, seed); - if (!hold.passed){ - hold_failed.push_back(std::format("{}: {} {}", hold.detail, hold.failed_step, hold.kind)); - } - } - return out; - }); + const HeldRowReport held = run_row_holding(story_checkpoints(), row, seeds); + const RowReport& report = held.report; + const std::vector& hold_failed = held.hold_failed; const auto took = std::chrono::duration_cast(current_time() - start); logger.log(Pokemon::format_report(report) + std::format("\n ({} seeds in {} ms)", seeds, took.count())); - logger.log(std::format("{}: one fade's hold unseen: {} of {} seeds that passed with no miss fail.", row, hold_failed.size(), rerun)); + logger.log(std::format("{}: one fade's hold unseen: {} of {} seeds that passed with no miss fail.", row, hold_failed.size(), held.rerun)); if (!hold_failed.empty()){ std::string out = std::format("{} fails with one fade's hold unseen where it passed without:", row); for (const std::string& line : hold_failed){ From 5655503918c51206efb71b9f770b359b9affb779 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 03:27:35 -0800 Subject: [PATCH 07/13] BDSP Monte Carlo: record a disturbed tap's battle as the console's walk does DisturbedRouteIO's taps now fill WalkResult::events and count the taps that moved after a battle, so the walker and the story's taps place a seeded battle by its screen events, as on the console. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp index 019fb8f47b..76bafb2e4c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp @@ -9,6 +9,7 @@ #include #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegBattle.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP_AutoStory_SimDisturbance.h" @@ -266,7 +267,9 @@ WalkResult DisturbedRouteIO::walk_taps(Direction direction, size_t tiles, const return GridSimRouteIO::walk_taps(direction, tiles, label); } WalkResult result{.stop = WalkStop::LIMIT, .walked = 0ms, .wild_battles = 0, .moved_chunks = 0}; + result.events.record({}, result.started); size_t still = 0; + size_t moved_at_battle = 0; for (size_t tap = 0; tap < tiles && result.stop == WalkStop::LIMIT; tap++){ const SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); result.walked += 800ms; @@ -284,9 +287,15 @@ WalkResult DisturbedRouteIO::walk_taps(Direction direction, size_t tiles, const if (move.distance > 0 && move.stop == SimStop::DONE && m_noise->battle_at(m_sim.world(), nearest_tile(m_sim.player().pos))){ result.wild_battles++; result.origin = tap == 0 ? WalkOrigin::MAY_PRECEDE_LEG : result.origin; + // The console's watchers time the battle from this tap. + record_tap_battle(result, tap + 1); + moved_at_battle = result.moved_chunks; m_notes.push_back("[Sim] wild battle during " + label); } } + if (result.wild_battles > 0){ + result.moved_after_battle = result.moved_chunks - moved_at_battle; + } m_notes.push_back(std::format("[Sim] {}: {} taps {}, {} moved, {} at {}.", label, tiles, direction_name(direction), result.moved_chunks, walk_stop_name(result.stop), to_string(m_sim.player().pos))); return result; From abf65710a30cbaf96699332488c3309159a2bd04 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 04:05:38 -0800 Subject: [PATCH 08/13] BDSP Monte Carlo: dialogs that pop up between steps DisturbanceRates::dialog_between_steps pops a dialog up before a step, drawn from a stream of its own (DisturbancePlan::dialogs, last from the seed, so no other draw moves). The new Monte Carlo case runs every row to 01.11 with dialogs at 10% a step, cleared by the executor and, for comparison, left up as before it looked: a seed that passes without them must pass with them cleared. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryMonteCarlo.cpp | 1 + .../AutoStory/Pokemon_StoryMonteCarlo.h | 7 ++ ...onBDSP_AutoStory_StoryMonteCarlo_Tests.cpp | 93 ++++++++++++++++++- 3 files changed, 98 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp index e2162ff82d..53fe361289 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp @@ -58,6 +58,7 @@ DisturbancePlan make_disturbance_plan(uint64_t seed, const DisturbanceRates& rat if (fades > 0 && holds.chance(rates.missed_hold)){ plan.missed_hold = (size_t)holds.between(0, (int64_t)fades - 1); } + plan.dialogs = SimRandom(root.next()); return plan; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h index 42ba7a1f59..e58e202994 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h @@ -105,6 +105,10 @@ struct DisturbanceRates{ // fall and the scene after show. 0 in the rates measured; 1 in the // tests that every seed survives it. double missed_hold = 0; + // The chance someone walks up and talks to the player before a step + // (a dialog between two steps, cleared by the executor's look). Not + // measured: 0 in the rates measured, set by the tests that pop them. + double dialog_between_steps = 0; }; // One seed's disturbances: independent random streams for each kind, so a @@ -122,6 +126,9 @@ struct DisturbancePlan{ std::optional missed_fade; std::optional missed_banner; std::optional missed_hold = std::nullopt; + // Whether a dialog pops up before each step, drawn last from the + // seed, so the other draws do not move with it. + SimRandom dialogs = SimRandom(); }; // The plan for `seed`, for a row whose undisturbed run looks for `fades` // fades and `banners` banners. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp index e45feef78b..3418d23268 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp @@ -10,7 +10,9 @@ * failure kinds with a seed that reproduces each, and fails only below the * row's pinned floor. The old 01.03 test shows the harness finds the two * failures lab-B met on 2026-11-08. Each row's seeds that pass with no - * miss run again with one fade's hold unseen, and must pass again. + * miss run again with one fade's hold unseen, and must pass again. With + * dialogs popping up between steps, a seed that passes without them + * must pass with them, the executor clearing them before each step. * */ @@ -18,6 +20,7 @@ #include #include #include +#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Time.h" @@ -97,11 +100,29 @@ Pokemon::DisturbanceRates stress_rates(){ return rates; } +// What the executor does with a dialog that pops up between steps. +enum class PoppedDialog{ + CLEARED, // cleared before the next step, as the console does + LEFT_UP, // left up, as before the executor looked (SimWorldKnobs::clear_interrupts) +}; + // Row `row` of `rows`, disturbed by `seed`, logging to `logger`. -SeedOutcome run_seed(Logger& logger, const std::vector& rows, const RowNoise& noise_of, const std::string& row, uint64_t seed){ +SeedOutcome run_seed( + Logger& logger, const std::vector& rows, const RowNoise& noise_of, const std::string& row, uint64_t seed, + PoppedDialog popped = PoppedDialog::CLEARED +){ const SimMisses& clean = noise_of.clean; SimDisturbance noise(Pokemon::make_disturbance_plan(seed, noise_of.rates, clean.fades, clean.banners)); - SimExecutor executor(logger, {.fade = noise.plan().missed_fade, .banner = noise.plan().missed_banner, .hold = noise.plan().missed_hold}, {.noise = &noise}); + Pokemon::SimRandom dialogs = noise.plan().dialogs; + const double dialog_rate = noise_of.rates.dialog_between_steps; + SimWorldKnobs knobs{ + .dialog_before = [&dialogs, dialog_rate](const std::string&, const std::string&){ + return dialog_rate > 0 && dialogs.chance(dialog_rate); + }, + .clear_interrupts = popped == PoppedDialog::CLEARED, + .noise = &noise, + }; + SimExecutor executor(logger, {.fade = noise.plan().missed_fade, .banner = noise.plan().missed_banner, .hold = noise.plan().missed_hold}, std::move(knobs)); try{ const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = row, .to = row}, rows); logger.log(std::format("[Sim] {}: {} wild battle(s) over {} grass and {} cave tiles.", describe(noise.plan()), @@ -197,6 +218,68 @@ UnitTestResult test_row(Logger& logger, const std::string& row, size_t floor){ } +// The chance a dialog pops up before a step, in the test that pops them, +// and its seeds a row: each runs three times, so fewer than a row's own. +constexpr double DIALOG_RATE = 0.1; +constexpr size_t DIALOG_SEEDS = 5; + +// How a row's seeds fare with dialogs popping up between steps: without +// them, with them cleared before each step, and with them left up (the +// executor before it looked). Seeds that pass without them and fail with +// them cleared, as "row plan: step kind". +struct DialogRowReport{ + size_t runs = 0; + size_t plain = 0; + size_t cleared = 0; + size_t left = 0; + std::vector regressions; +}; +void run_row_dialogs(DialogRowReport& out, const std::vector& rows, const std::string& row, size_t seeds){ + const RowNoise plain{.clean = looked_for(rows, row), .rates = {}}; + RowNoise popping = plain; + popping.rates.dialog_between_steps = DIALOG_RATE; + for (uint64_t seed : Pokemon::story_seeds(seeds)){ + SilentLogger silent; + const bool passes = run_seed(silent, rows, plain, row, seed).passed; + const SeedOutcome cleared = run_seed(silent, rows, popping, row, seed); + const bool left = run_seed(silent, rows, popping, row, seed, PoppedDialog::LEFT_UP).passed; + out.runs++; + out.plain += passes ? 1 : 0; + out.cleared += cleared.passed ? 1 : 0; + out.left += left ? 1 : 0; + if (passes && !cleared.passed){ + out.regressions.push_back(std::format("{} {}: {} {}", row, cleared.detail, cleared.failed_step, cleared.kind)); + } + } +} + +// Every row to 01.11, its seeds with dialogs popping up between steps +// (DIALOG_RATE a step): one that passes without them must pass with them. +UnitTestResult test_dialogs_between_steps(Logger& logger){ + const std::vector rows = story_checkpoints(); + const size_t seeds = Pokemon::seed_count(SEEDS_VARIABLE, DIALOG_SEEDS); + DialogRowReport report; + for (const StoryCheckpoint& row : rows){ + if (row.id > "01.11"){ + continue; + } + run_row_dialogs(report, rows, row.id, seeds); + } + logger.log(std::format( + "Dialogs between steps, {} runs: {} pass without them, {} with them cleared, {} with them left up.", + report.runs, report.plain, report.cleared, report.left + )); + if (report.regressions.empty()){ + return true; + } + std::string out = "Seeds that pass without dialogs between steps fail with them cleared:"; + for (const std::string& line : report.regressions){ + out += "\n " + line; + } + return out; +} + + // 01.03's steps across Roark's room as they were before 4f13c19bb: // counted taps onto Roark's row, then west against his rock. std::vector old_steps_to_roark(){ @@ -357,6 +440,10 @@ const StoryMonteCarloCase AUTO_STORY_MONTE_CARLO_CASES[] = { .input = {"the old 01.03 fails across Roark's room and at the Center's door (lab-B, 2026-11-08)", test_old_0103}, .expectation = {}, }, + { + .input = {"dialogs pop up between steps, 00.00 to 01.11", test_dialogs_between_steps}, + .expectation = {}, + }, }; void add_tests_AutoStory_StoryMonteCarlo(UnitTestDatabase& database){ From f0d8ddfab6818513b37812c502724bb11d141b32 Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 10 Nov 2026 12:33:50 -0800 Subject: [PATCH 09/13] BDSP Monte Carlo: update to #312 GridPose/actions and clean code health --- .../AutoStory/Pokemon_StoryMonteCarlo.cpp | 8 ++++---- .../AutoStory/Pokemon_StoryMonteCarlo.h | 5 +++-- .../PokemonBDSP_AutoStory_SimDisturbance.cpp | 8 ++++---- ...onBDSP_AutoStory_StoryMonteCarlo_Tests.cpp | 19 ++++++++++--------- 4 files changed, 21 insertions(+), 19 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp index 53fe361289..b26b246fcf 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.cpp @@ -87,8 +87,8 @@ std::vector story_seeds(size_t count){ return seeds; } -size_t seed_count(const char* name, size_t fallback){ - const char* value = std::getenv(name); +size_t seed_count(std::string_view name, size_t fallback){ + const auto* value = std::getenv(std::string(name).c_str()); if (value == nullptr){ return fallback; } @@ -96,8 +96,8 @@ size_t seed_count(const char* name, size_t fallback){ return count > 0 ? (size_t)count : fallback; } -std::vector selected_rows(const char* name, const std::vector& rows){ - const char* value = std::getenv(name); +std::vector selected_rows(std::string_view name, const std::vector& rows){ + const auto* value = std::getenv(std::string(name).c_str()); if (value == nullptr || *value == '\0'){ return rows; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h index e58e202994..f55c7a3441 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h @@ -13,6 +13,7 @@ * Game-agnostic: a game binds it by running one row for one seed's * DisturbancePlan (a SeedRun) on its own simulation. * +// code-health: allow header_symbols -- Monte Carlo framework types, disturbance plan and reporter */ #ifndef PokemonAutomation_Pokemon_StoryMonteCarlo_H @@ -143,10 +144,10 @@ std::string describe(const DisturbancePlan& plan); std::vector story_seeds(size_t count); // The seed count to run: `fallback`, or the environment variable `name` // when it holds a positive number (the heavy, on-demand mode). -size_t seed_count(const char* name, size_t fallback); +size_t seed_count(std::string_view name, size_t fallback); // The rows to run: all of `rows`, or those the environment variable // `name` lists (comma-separated ids), in `rows`' order. -std::vector selected_rows(const char* name, const std::vector& rows); +std::vector selected_rows(std::string_view name, const std::vector& rows); // What one seed's run of a row did. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp index 76bafb2e4c..d9fe7192a2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp @@ -26,7 +26,7 @@ using Pokemon::TilePos; namespace{ // The caves on the story's way, where every tile has wild Pokemon. -constexpr const char* CAVE_MAPS[] = {"OreburghMineB1F", "OreburghMine", "RavagedPath"}; +constexpr std::string_view CAVE_MAPS[] = {"OreburghMineB1F", "OreburghMine", "RavagedPath"}; // Drift comes in steps of this many thousandths of a tile: 4 ms of stick // across, 6 ms up or down, so the grid sim puts it back on the grid exactly. constexpr int DRIFT_STEP = 25; @@ -43,7 +43,7 @@ int along(const SimPos& pos, Direction direction){ return across(direction) ? pos.x : pos.y; } bool wanderer_on(const GridSim& sim, const TilePos& pos){ - const std::vector& people = sim_wanderers(sim); + const std::vector& people = detail::sim_wanderers(sim); return std::any_of(people.begin(), people.end(), [&](const SimWanderer& person){ return person.pos == pos; }); } // Whether the player can drift a little toward `direction`: the tile there @@ -60,7 +60,7 @@ bool stopped_at_wall(const GridSim& sim, const SimMove& move, Direction directio bool in_cave(const StoryWorld& world, const TilePos& pos){ const std::optional tile = world.to_local(pos); - return tile && std::ranges::any_of(CAVE_MAPS, [&](const char* map){ return tile->map == story_banner_name(map); }); + return tile && std::ranges::any_of(CAVE_MAPS, [&](std::string_view map){ return tile->map == story_banner_name(std::string(map)); }); } // Whether `box` of `map` holds `pos`. @@ -250,7 +250,7 @@ WalkResult DisturbedRouteIO::walk_to_wall(const RouteWallWalk& walk){ const SimPace pace = walk.options.pace == DpadPace::RUN ? SimPace::RUN : SimPace::WALK; const DisturbedHold hold = disturbed_hold(m_sim, m_noise, walk.direction, walk.limit, pace); m_notes.push_back(std::format("[Sim] {}: held {} to {} at {}, {} wild battle(s).", walk.label, direction_name(walk.direction), - sim_stop_name(hold.move.stop), to_string(m_sim.player().pos), hold.battles)); + detail::sim_stop_name(hold.move.stop), to_string(m_sim.player().pos), hold.battles)); WalkResult result{.stop = walk_stop(hold.move.stop), .walked = hold.move.time, .wild_battles = hold.battles, .moved_chunks = (size_t)(hold.move.distance / SIM_TILE)}; if (hold.first_tile){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp index 3418d23268..45ccbc2d6c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp @@ -43,9 +43,9 @@ using Pokemon::SeedOutcome; using Pokemon::StoryStep; using Pokemon::TilePos; -constexpr const char* SEEDS_VARIABLE = "PA_BDSP_STORY_MC_SEEDS"; -constexpr const char* ROWS_VARIABLE = "PA_BDSP_STORY_MC_ROWS"; -constexpr const char* TRACE_VARIABLE = "PA_BDSP_STORY_MC_TRACE"; +constexpr std::string_view SEEDS_VARIABLE = "PA_BDSP_STORY_MC_SEEDS"; +constexpr std::string_view ROWS_VARIABLE = "PA_BDSP_STORY_MC_ROWS"; +constexpr std::string_view TRACE_VARIABLE = "PA_BDSP_STORY_MC_TRACE"; constexpr size_t DEFAULT_SEEDS = 20; // The runs log nothing: a seed's own log is a reproduction away. @@ -286,19 +286,20 @@ std::vector old_steps_to_roark(){ StoryStep taps; taps.kind = Pokemon::StoryStepKind::LEGS; taps.name = "above_roarks_row"; - taps.legs = { + taps.action = "legs"; + taps.args["legs"] = std::vector{ {.direction = Direction::EAST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 2}, {.direction = Direction::WEST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 5}, {.direction = Direction::EAST, .tiles = 14}, {.direction = Direction::SOUTH, .tiles = 10}, {.direction = Direction::WEST, .tiles = 2}, {.direction = Direction::SOUTH, .tiles = 2}, }; - taps.pose_after = Pokemon::tile_pose("OreburghMine", {TilePos{27, 28}}, Direction::SOUTH); + taps.pose_after = Pokemon::GridPose{"OreburghMine", {TilePos{27, 28}}, Direction::SOUTH}; StoryStep walls; walls.kind = Pokemon::StoryStepKind::LEGS; walls.name = "beside_roarks_rock"; - walls.variant = "to_wall"; - walls.legs = {{.direction = Direction::WEST, .tiles = 7}, {.direction = Direction::SOUTH, .tiles = 1}}; - walls.pose_after = Pokemon::tile_pose("OreburghMine", {TilePos{20, 29}}, Direction::SOUTH); + walls.action = "to_wall"; + walls.args["legs"] = std::vector{{.direction = Direction::WEST, .tiles = 7}, {.direction = Direction::SOUTH, .tiles = 1}}; + walls.pose_after = Pokemon::GridPose{"OreburghMine", {TilePos{20, 29}}, Direction::SOUTH}; return {taps, walls}; } @@ -332,7 +333,7 @@ std::vector from_the_mines_sign(std::vector ro const auto sign = std::find_if(row.steps.begin(), row.steps.end(), [](const StoryStep& step){ return step.name == "up_to_the_mines_sign"; }); - row.start = Pokemon::tile_pose("OreburghCity", {TilePos{45, 59}, TilePos{45, 58}}, Direction::NORTH); + row.start = Pokemon::GridPose{"OreburghCity", {TilePos{45, 59}, TilePos{45, 58}}, Direction::NORTH}; row.saves_in.clear(); row.steps.erase(row.steps.begin(), sign); } From 90f07a4f9d85d9290d6593c9999170767ae2bcf2 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 14:59:32 -0800 Subject: [PATCH 10/13] BDSP AutoStory sim: Monte Carlo test declares poses as TileDeclared (after #226's merge) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp index 45ccbc2d6c..dc220783aa 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp @@ -293,13 +293,13 @@ std::vector old_steps_to_roark(){ {.direction = Direction::EAST, .tiles = 14}, {.direction = Direction::SOUTH, .tiles = 10}, {.direction = Direction::WEST, .tiles = 2}, {.direction = Direction::SOUTH, .tiles = 2}, }; - taps.pose_after = Pokemon::GridPose{"OreburghMine", {TilePos{27, 28}}, Direction::SOUTH}; + taps.pose_after = Pokemon::TileDeclared{.map = "OreburghMine", .tiles = {TilePos{27, 28}}, .facing = Direction::SOUTH}; StoryStep walls; walls.kind = Pokemon::StoryStepKind::LEGS; walls.name = "beside_roarks_rock"; walls.action = "to_wall"; walls.args["legs"] = std::vector{{.direction = Direction::WEST, .tiles = 7}, {.direction = Direction::SOUTH, .tiles = 1}}; - walls.pose_after = Pokemon::GridPose{"OreburghMine", {TilePos{20, 29}}, Direction::SOUTH}; + walls.pose_after = Pokemon::TileDeclared{.map = "OreburghMine", .tiles = {TilePos{20, 29}}, .facing = Direction::SOUTH}; return {taps, walls}; } @@ -333,7 +333,7 @@ std::vector from_the_mines_sign(std::vector ro const auto sign = std::find_if(row.steps.begin(), row.steps.end(), [](const StoryStep& step){ return step.name == "up_to_the_mines_sign"; }); - row.start = Pokemon::GridPose{"OreburghCity", {TilePos{45, 59}, TilePos{45, 58}}, Direction::NORTH}; + row.start = Pokemon::TileDeclared{.map = "OreburghCity", .tiles = {TilePos{45, 59}, TilePos{45, 58}}, .facing = Direction::NORTH}; row.saves_in.clear(); row.steps.erase(row.steps.begin(), sign); } From be7d2a64e28b438730bafda7bf4ee0d6cf7bbe14 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 01:22:34 -0800 Subject: [PATCH 11/13] BDSP Monte Carlo: a disturbed hold walks as the grid sim's hold does (red) Every Monte Carlo seed of 00.05 stood still on east_to_the_wall: a hold east at a walk from (46, 54) moved no tile, where the grid sim's own hold walks 6 to the wall at (52, 54). This test holds east, west and north at a walk and east at a run, with no disturbance, both ways. It fails now on the walks east and west. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...onBDSP_AutoStory_StoryMonteCarlo_Tests.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp index dc220783aa..76b209cd21 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp @@ -27,6 +27,7 @@ #include "Common/Cpp/TestRunners/UnitTest.h" #include "Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_SimDisturbance.h" #include "PokemonBDSP_AutoStory_StorySim.h" #include "PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.h" @@ -37,6 +38,7 @@ namespace PokemonBDSP{ namespace{ +using namespace std::chrono_literals; using Pokemon::Direction; using Pokemon::RowReport; using Pokemon::SeedOutcome; @@ -373,6 +375,46 @@ UnitTestResult test_old_0103(Logger& logger){ } +// A disturbed hold with no disturbance walks as the grid sim's own hold +// does, at its pace: a hold timed a tile at the walker's 160 ms east +// moved no tile at the sim's 200 ms (fe2da03e7), and every hold east or +// west at a walk stood still (00.05 east_to_the_wall, 2026-11-12). +UnitTestResult test_disturbed_hold_as_plain(Logger& logger){ + const StoryWorld* world = story_plan_world("JubilifeCity", "JubilifeCity"); + if (world == nullptr){ + return "JubilifeCity world not found"; + } + struct Hold{ + Direction direction; + SimPace pace; + bool can_run; + }; + const Hold holds[] = { + {Direction::EAST, SimPace::WALK, false}, {Direction::WEST, SimPace::WALK, false}, + {Direction::NORTH, SimPace::WALK, false}, {Direction::EAST, SimPace::RUN, true}, + }; + Pokemon::DisturbanceRates still; + still.grass_encounter = 0; + still.cave_encounter = 0; + still.drift_per_tile = 0; + const TilePos start = story_to_world(*world, "JubilifeCity", {46, 54}); + for (const Hold& hold : holds){ + GridSim plain({.world = world}, start, hold.direction, hold.can_run); + const SimMove expected = plain.hold(hold.direction, 10000ms, hold.pace); + GridSim disturbed({.world = world}, start, hold.direction, hold.can_run); + SimDisturbance noise(Pokemon::make_disturbance_plan(1, still, 0, 0)); + const SimMove got = disturbed_hold(disturbed, &noise, hold.direction, 10000ms, hold.pace).move; + logger.log(std::format("{}: plain {} to {}, disturbed {} to {}.", direction_name(hold.direction), + expected.distance / SIM_TILE, to_string(plain.player().pos), got.distance / SIM_TILE, to_string(disturbed.player().pos))); + if (got.distance != expected.distance || got.stop != expected.stop || disturbed.player().pos != plain.player().pos){ + return std::format("{} held: the disturbed hold moved {} where the plain one moved {}.", + direction_name(hold.direction), got.distance / SIM_TILE, expected.distance / SIM_TILE); + } + } + return true; +} + + // A row of the table, disturbed; or, with a body, another test. struct StoryMonteCarloInput{ std::string row; @@ -437,6 +479,10 @@ const StoryMonteCarloCase AUTO_STORY_MONTE_CARLO_CASES[] = { {.input = {"01.09"}, .expectation = {.floor = 100}}, {.input = {"01.10"}, .expectation = {.floor = 80}}, {.input = {"01.11"}, .expectation = {.floor = 100}}, + { + .input = {"a disturbed hold with no disturbance walks as the plain hold does", test_disturbed_hold_as_plain}, + .expectation = {}, + }, { .input = {"the old 01.03 fails across Roark's room and at the Center's door (lab-B, 2026-11-08)", test_old_0103}, .expectation = {}, From 4ff02e64db9976c1712c1cc933bfb8976027d4f6 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 01:22:34 -0800 Subject: [PATCH 12/13] BDSP Monte Carlo: a disturbed hold steps a tile at the sim's own pace disturbed_hold() holds a tile at a time, each timed at the walker's pace (route_ms_per_tile(), 160 ms east or west at a walk). The grid sim walks east and west at 200 ms a tile (fe2da03e7), so each of those holds moved no tile and the whole hold stood still. Every Monte Carlo row with a walk east or west to a wall failed on all its seeds: 00.01, 00.03, 00.04, 00.04b, 00.05, 01.05 and 01.11. It now times each tile with sim_ms_per_tile(), GridSim::hold()'s own pace. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp index a007b18654..df74f30fc7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp @@ -218,8 +218,8 @@ DisturbedHold disturbed_hold(GridSim& sim, SimDisturbance* noise, Direction dire if (noise == nullptr){ return {.move = sim.hold(direction, limit, pace)}; } - const bool runs = pace == SimPace::RUN && sim.player().can_run; - const Milliseconds tile_time = route_ms_per_tile(direction, runs ? MoveSpeed::RUN : MoveSpeed::WALK); + // A tile at a time, at the hold's own pace. + const Milliseconds tile_time = sim_ms_per_tile(direction, pace, sim.player().can_run); const int64_t tiles = limit < ROUTE_START_DELAY ? 0 : (limit - ROUTE_START_DELAY) / tile_time; DisturbedHold out{.move = {.stop = SimStop::LIMIT}}; for (int64_t i = 0; i < tiles && out.move.stop == SimStop::LIMIT; i++){ From 531ee11bee5acd652b99d6d715fc34e6c44e1846 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 01:22:34 -0800 Subject: [PATCH 13/13] BDSP Monte Carlo: the old 01.03 test keeps Roark's room only The Center's-door half rebuilt the old row by removing steps that are gone from the table (south_of_the_centers_door, ...), and cut the town rows at up_to_the_mines_sign, also gone, so they ran no steps and passed 200 of 200: it could not show the 10:39 failure any more. Retired; today's 01.03 reaches the door by a counted wall leg up column 46. The Roark half still finds the 11:55 failure after a wild battle. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...onBDSP_AutoStory_StoryMonteCarlo_Tests.cpp | 52 ++++--------------- 1 file changed, 10 insertions(+), 42 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp index 76b209cd21..6ddcae5aad 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryMonteCarlo_Tests.cpp @@ -8,8 +8,8 @@ * drift off the grid, the maps' wanderers, and sometimes one missed fade or * banner. Each row's test logs its pass rate and, per failing step, the * failure kinds with a seed that reproduces each, and fails only below the - * row's pinned floor. The old 01.03 test shows the harness finds the two - * failures lab-B met on 2026-11-08. Each row's seeds that pass with no + * row's pinned floor. The old 01.03 test shows the harness finds the + * failure lab-B met across Roark's room on 2026-11-08. Each row's seeds that pass with no * miss run again with one fade's hold unseen, and must pass again. With * dialogs popping up between steps, a seed that passes without them * must pass with them, the executor clearing them before each step. @@ -305,43 +305,20 @@ std::vector old_steps_to_roark(){ return {taps, walls}; } -// 01.03 as it was before be57db157 and 4f13c19bb: counted taps across -// Roark's room, and the route to below the Center's door straight into -// the heal. +// 01.03 as it was before 4f13c19bb: counted taps across Roark's room. std::vector old_0103(){ const std::vector old = old_steps_to_roark(); - const std::vector added{"south_of_the_centers_door", "against_the_walls_east_of_the_door", "below_the_centers_door_lined_up"}; std::vector rows = story_checkpoints(); for (StoryCheckpoint& row : rows){ if (row.id != "01.03"){ continue; } - std::erase_if(row.steps, [&](const StoryStep& step){ - return std::find(added.begin(), added.end(), step.name) != added.end(); - }); std::replace_if(row.steps.begin(), row.steps.end(), [](const StoryStep& step){ return step.name == "to_roarks_corner"; }, old[0]); std::replace_if(row.steps.begin(), row.steps.end(), [](const StoryStep& step){ return step.name == "beside_roarks_rock"; }, old[1]); } return rows; } -// Row 01.03 of `rows` from out of the mine on: the walk up to below the -// Center's door and the heal, without the mine's failures before it. -std::vector from_the_mines_sign(std::vector rows){ - for (StoryCheckpoint& row : rows){ - if (row.id != "01.03"){ - continue; - } - const auto sign = std::find_if(row.steps.begin(), row.steps.end(), [](const StoryStep& step){ - return step.name == "up_to_the_mines_sign"; - }); - row.start = Pokemon::TileDeclared{.map = "OreburghCity", .tiles = {TilePos{45, 59}, TilePos{45, 58}}, .facing = Direction::NORTH}; - row.saves_in.clear(); - row.steps.erase(row.steps.begin(), sign); - } - return rows; -} - // Whether `report` failed `step` in a way whose kind holds `text` and `also`. bool failed_with(const RowReport& report, const std::string& step, const std::string& text, const std::string& also = ""){ const auto found = report.failures.find(step); @@ -350,26 +327,17 @@ bool failed_with(const RowReport& report, const std::string& step, const std::st }); } -// lab-B 2026-11-08: a wild battle on the counted taps across Roark's room -// re-planned to an open leg and the row went one off (11:55); a run up -// Oreburgh's column 46 stopped short and an open step east left us off the -// Center door's column (10:39). The old row must show both, at the stress -// rates: at lab-B's own, 200 seeds need not draw them. +// lab-B 2026-11-08 11:55: a wild battle on the counted taps across +// Roark's room re-planned to an open leg and the row went one off. The +// old row must show it, at the stress rates: at lab-B's own, 200 seeds +// need not draw it. UnitTestResult test_old_0103(Logger& logger){ const size_t seeds = std::max(200, Pokemon::seed_count(SEEDS_VARIABLE, DEFAULT_SEEDS)); const RowReport whole = run_row(old_0103(), "01.03", seeds, stress_rates()); logger.log("The old 01.03: " + Pokemon::format_report(whole)); - const RowReport town = run_row(from_the_mines_sign(old_0103()), "01.03", seeds, stress_rates()); - logger.log("The old 01.03 from the mine's sign: " + Pokemon::format_report(town)); - logger.log("Today's 01.03 from the mine's sign: " + Pokemon::format_report( - run_row(from_the_mines_sign(story_checkpoints()), "01.03", seeds, stress_rates()))); // A battle on the taps, then the row ends off the tile the taps count. - const bool roark = failed_with(whole, "01.03 above_roarks_row", "sim_mismatch", "[wild battle in the step]"); - // From the mine's warp (the whole row) or the sign. - const bool center = failed_with(whole, "01.03 heal_oreburgh", "no door north") || failed_with(town, "01.03 heal_oreburgh", "no door north"); - if (!roark || !center){ - return std::format("expected the old 01.03 to fail across Roark's room after a wild battle ({}) and at the Center's door ({}):\n{}\n{}", - roark, center, Pokemon::format_report(whole), Pokemon::format_report(town)); + if (!failed_with(whole, "01.03 above_roarks_row", "sim_mismatch", "[wild battle in the step]")){ + return "expected the old 01.03 to fail across Roark's room after a wild battle:\n" + Pokemon::format_report(whole); } return true; } @@ -484,7 +452,7 @@ const StoryMonteCarloCase AUTO_STORY_MONTE_CARLO_CASES[] = { .expectation = {}, }, { - .input = {"the old 01.03 fails across Roark's room and at the Center's door (lab-B, 2026-11-08)", test_old_0103}, + .input = {"the old 01.03 fails across Roark's room after a wild battle (lab-B, 2026-11-08)", test_old_0103}, .expectation = {}, }, {