From 6bd08e24da2e685229b6d3d2b837198da46b98dd Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 07:27:02 -0800 Subject: [PATCH 01/20] BDSP AutoStory: count a tap as a step only if the view scrolled The tap counters read any screen change as our own step, so cloud shadows (r83, r84), TVs and conveyors counted as tiles walked. Outside, the camera follows the player: walk_view_shift() finds the scroll that lines up two frames around the player, and tap_moved() counts a tap only if a scroll lines up at least twice as well as none. Inside, the camera can stay put while the player crosses a room, so the old screen-change line still decides there. WalkUntil's tap walks and dpad_tiles() use it. Measured offline on r83/r84's Floaroma video: standing frames with screen changes up to 57 never read as scrolled; walking read a scroll 2 to 6 times better than none. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_AutoStory_Walk_Tests.cpp | 89 +++++++++++++++++++ .../AutoStory/PokemonBDSP_AutoStory_Walks.cpp | 2 +- .../Utils/PokemonBDSP_AutoStory_Walk.cpp | 74 ++++++++++++++- .../Utils/PokemonBDSP_AutoStory_Walk.h | 27 ++++++ 4 files changed, 187 insertions(+), 5 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp index c38ff46daf..3176624408 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp @@ -5,6 +5,7 @@ */ #include +#include #include #include #include "Common/Cpp/Filesystem/Filesystem.h" @@ -14,6 +15,7 @@ #include "Utils/PokemonBDSP_AutoStory_Indoors.h" #include "Utils/PokemonBDSP_AutoStory_Location.h" #include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "Utils/PokemonBDSP_AutoStory_Walk.h" #include "PokemonBDSP_AutoStory_Walk_Tests.h" namespace PokemonAutomation{ @@ -237,6 +239,92 @@ class Test_LocationBannerShowing : public UnitTest{ } }; +// walk_view_shift(): a step scrolls the whole view; scenery that moves on +// its own does not. Synthetic 384x216 screens of 8-pixel blocks in mixed +// colours, as grass and flowers are, with one change each. +uint32_t scenery_at(int x, int y){ + const uint32_t block = (uint32_t)((x >> 3) * 73856093u) ^ (uint32_t)((y >> 3) * 19349663u); + const uint32_t hashed = block * 2654435761u; + return 0xff000000 | (hashed & 0x00ffffff); +} +ImageRGB32 scenery(int shift_x, int shift_y){ + ImageRGB32 screen(384, 216); + for (int y = 0; y < 216; y++){ + for (int x = 0; x < 384; x++){ + screen.pixel(x, y) = scenery_at(x + shift_x + 1000, y + shift_y + 1000); + } + } + return screen; +} +// Each colour channel of the pixels in [x0, x1) x [y0, y1) times `scale`, +// or set to `fill` if given. +void paint(ImageRGB32& screen, int x0, int y0, int x1, int y1, double scale, uint32_t fill = 0){ + for (int y = y0; y < y1; y++){ + for (int x = x0; x < x1; x++){ + uint32_t p = screen.pixel(x, y); + if (fill != 0){ + screen.pixel(x, y) = fill; + continue; + } + uint32_t out = 0xff000000; + for (int shift = 0; shift < 24; shift += 8){ + out |= (uint32_t)(((p >> shift) & 0xff) * scale) << shift; + } + screen.pixel(x, y) = out; + } + } +} + +class Test_ViewShift : public UnitTest{ +public: + Test_ViewShift() + : UnitTest("PokemonBDSP::AutoStory - a step scrolls the view; moving scenery does not") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const ImageRGB32 before = scenery(0, 0); + struct Case{ + std::string name; + ImageRGB32 after; + bool scrolled; + }; + std::vector cases; + cases.push_back({"the same view", scenery(0, 0), false}); + cases.push_back({"a step east: the view scrolls 16 pixels west", scenery(16, 0), true}); + cases.push_back({"a step south", scenery(0, 12), true}); + { + // r83, r84: a cloud's shadow over the top of the view. + ImageRGB32 shadow = scenery(0, 0); + paint(shadow, 0, 0, 384, 90, 0.6); + cases.push_back({"a cloud shadow over the top third", std::move(shadow), false}); + } + { + // Jubilife's TV screens, the mine's conveyors. + ImageRGB32 tv = scenery(0, 0); + paint(tv, 20, 20, 110, 80, 0, 0xffffffff); + cases.push_back({"a TV lights up in a corner", std::move(tv), false}); + } + { + // A turn changes only the player's sprite. + ImageRGB32 turned = scenery(0, 0); + paint(turned, 175, 75, 210, 150, 0, 0xffff4040); + cases.push_back({"the player turns", std::move(turned), false}); + } + for (const Case& item : cases){ + const ViewShift shift = walk_view_shift(before, item.after); + if (shift.scrolled() != item.scrolled){ + return std::format("{}: {} (shift {}, {}; difference {:.1f} unshifted, {:.1f} shifted).", + item.name, item.scrolled ? "did not read as a scroll" : "read as a scroll", + shift.dx, shift.dy, shift.unshifted, shift.shifted); + } + } + const ViewShift east = walk_view_shift(before, scenery(16, 0)); + if (east.dx != -8 || east.dy != 0){ + return std::format("A 16-pixel scroll west read as ({}, {}) on the half-size copy, expected (-8, 0).", east.dx, east.dy); + } + return true; + } +}; + } @@ -248,6 +336,7 @@ void add_tests_AutoStory_Walk(UnitTestDatabase& database){ database.add(); database.add(); database.add(); + database.add(); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walks.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walks.cpp index f3423bede7..39b5fa595d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walks.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walks.cpp @@ -161,7 +161,7 @@ void dpad_tiles(VideoStream& stream, ProControllerContext& context, DpadPosition context.wait_for_all_requests(); const VideoSnapshot after = stream.video().snapshot(); const double change = before && after ? walk_screen_change(*before.frame, *after.frame) : 100; - if (change > 30){ + if (!before || !after || tap_moved(*before.frame, *after.frame, 30)){ moved++; continue; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp index 53d7a461e0..b333d339dd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp @@ -20,6 +20,7 @@ #include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" #include "PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h" #include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP_AutoStory_Indoors.h" #include "PokemonBDSP_AutoStory_Walk.h" namespace PokemonAutomation{ @@ -46,6 +47,68 @@ double walk_screen_change(const ImageViewRGB32& before, const ImageViewRGB32& af } +bool ViewShift::scrolled() const{ + constexpr double LEAST_DIFFERENCE = 3; // standing still in the video: 0 to 1.5 + return (dx != 0 || dy != 0) && unshifted >= LEAST_DIFFERENCE && unshifted >= 2 * shifted; +} + +ViewShift walk_view_shift(const ImageViewRGB32& before, const ImageViewRGB32& after){ + constexpr int W = 192; + constexpr int H = 108; + // A step scrolls 2 to 10 pixels of the copy in 300 ms. + constexpr int REACH = 12; + const ImageRGB32 a = before.scale_to(W, H); + const ImageRGB32 b = after.scale_to(W, H); + // The player's box, which moves with the camera, not with the scenery. + auto in_player_box = [](int x, int y){ + return x >= W * 42 / 100 && x < W * 58 / 100 && y >= H * 30 / 100 && y < H * 75 / 100; + }; + auto difference = [&](int dx, int dy){ + uint64_t sum = 0; + size_t count = 0; + for (int y = REACH; y < H - REACH; y++){ + for (int x = REACH; x < W - REACH; x++){ + if (in_player_box(x, y)){ + continue; + } + const uint32_t p = a.pixel(x - dx, y - dy); + const uint32_t q = b.pixel(x, y); + for (int shift = 0; shift < 24; shift += 8){ + const int c = (int)((p >> shift) & 0xff) - (int)((q >> shift) & 0xff); + sum += c < 0 ? -c : c; + } + count += 3; + } + } + return (double)sum / (double)count; + }; + ViewShift best; + best.unshifted = difference(0, 0); + best.shifted = best.unshifted; + for (int dy = -REACH; dy <= REACH; dy++){ + for (int dx = -REACH; dx <= REACH; dx++){ + if (dx == 0 && dy == 0){ + continue; + } + const double d = difference(dx, dy); + if (d < best.shifted){ + best.shifted = d; + best.dx = dx; + best.dy = dy; + } + } + } + return best; +} + +bool tap_moved(const ImageViewRGB32& before, const ImageViewRGB32& after, double line){ + if (indoors(after)){ + return walk_screen_change(before, after) >= line; + } + return walk_view_shift(before, after).scrolled(); +} + + namespace{ // The battle's text box, held for 250ms. @@ -327,7 +390,11 @@ class WalkUntil{ m_before = std::move(after); return {ChunkNext::NEXT_CHUNK, WalkStop::LIMIT}; } - const bool still = still_chunk(change); + // Taps count what scrolled the view, not scenery that moved (r84: + // cloud shadows read as steps). + const bool still = m_spec.input == WalkInput::TAPS + ? !tap_moved(*m_before.frame, *after.frame, still_line(change)) + : change < still_line(change); if (!still){ // A quiet tap and then a moving one: the first moved too. What // blocks a tap still blocks the next; the view barely changed @@ -347,12 +414,11 @@ class WalkUntil{ // NPC measured 17.2 after steps of 63 to 65 (r250a, Floaroma's old // woman), over the fixed line of 16, so for taps "still" is also // anything under 40% of the walk's own steps. - bool still_chunk(double change){ + double still_line(double change){ m_largest = std::max(m_largest, change); - const double line = m_spec.input == WalkInput::TAPS + return m_spec.input == WalkInput::TAPS ? std::max(WALK_TAP_BLOCKED_CHANGE, 0.4 * m_largest) : WALK_BLOCKED_CHANGE; - return change < line; } void escape_battle(const std::string& what){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h index 504edccfe8..08e118c61f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h @@ -160,6 +160,33 @@ constexpr double WALK_TAP_BLOCKED_CHANGE = 16.0; // More than walking changes in 400ms: a new scene, such as a battle opening. constexpr double WALK_SCENE_CHANGE = 120.0; +// How the view scrolled between two frames, on 192x108 copies: the shift +// (dx, dy) of `before` that best lines up with `after`, leaving out the +// middle where the player stands, and the mean difference per colour +// channel (0 to 255) with and without it. Outside, the camera follows the +// player, so a step scrolls everything one way; a TV, a conveyor, a +// passer-by or a cloud shadow changes part of the view with no common +// scroll. In r83's and r84's Floaroma video, frames 300 ms apart while +// standing (screen changes up to 57, cloud shadows, text boxes) never read +// as scrolled; walking read a shift 2 to 6 times better than none. +struct ViewShift{ + int dx = 0; + int dy = 0; + double unshifted = 0; + double shifted = 0; + + // A shift lines up at least twice as well as none, and none leaves a + // real difference. + bool scrolled() const; +}; +ViewShift walk_view_shift(const ImageViewRGB32& before, const ImageViewRGB32& after); + +// Whether the player moved between `before` and `after`, frames around a +// D-pad tap. Outside: only if the view scrolled. Inside, the camera can +// stay put while the player crosses a room (the house's 1F), so there a +// screen change of at least `line` counts, as it did before. +bool tap_moved(const ImageViewRGB32& before, const ImageViewRGB32& after, double line); + // One straight walk timed finely, to check a map against the game: holds the // stick at `stick` and samples the screen every 100ms until the view has been From d73147dbfeb0be45d575d3f7f44620da71b2d547 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 00:45:48 -0800 Subject: [PATCH 02/20] BDSP walk: the late-tap check counts a scrolled view, as look() does The merge of bdsp/autostory-v4 brought back a call to still_chunk(), which this branch replaced with tap_moved(); use tap_moved() there too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp index 375f4d29dd..eca572b3ba 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp @@ -478,7 +478,7 @@ class WalkUntil{ ){ VideoSnapshot after = snapshot_or_fail(m_stream, m_spec.label); const double change = walk_screen_change(*m_before_still.frame, *after.frame); - if (!still_chunk(change)){ + if (tap_moved(*m_before_still.frame, *after.frame, still_line(change))){ m_result.moved_chunks++; } } From 168d7284dc07f28ecbd6759c47c53d5992f0989f Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 07:13:37 -0800 Subject: [PATCH 03/20] BDSP MenuDetector: narrow the white columns clear of the cursor glow The selected menu icon glows about 0.008 past its left edge. With the cursor on the first icon of a row (TOWN MAP on the second row), the first 0.015-wide column took the glow's edge and its stddev rose to about 12, over the white test's 10, so overworld_to_menu() timed out with the menu on screen. Columns of 0.010 end just short of the glow. New image test: a French menu with the cursor on the map and a NEW tag on the Trainer Card (both column modes). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Inference/PokemonBDSP_MenuDetector.cpp | 98 ++++++++++--------- 1 file changed, 54 insertions(+), 44 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.cpp index 6d23f8fb83..d4af9f47d1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.cpp @@ -28,10 +28,14 @@ constexpr double STRIPE_BOTTOM = 0.598; // Each column sits in the gap right of an icon, clear of the "NEW" tag on // its top right corner. The tag on TOWN MAP extends into a column at 0.160. constexpr double STRIPE_LEFT = 0.166; +// The selected icon glows about 0.008 past its left edge, into the gap left +// of it. A column of 0.015 reached the glow from 0.177 (cursor on the first +// icon of a row); 0.010 ends just short of it. +constexpr double STRIPE_WIDTH = 0.010; ImageFloatBox menu_stripe(size_t index, bool skip_new_banner){ double top = skip_new_banner ? STRIPE_TOP_BELOW_BANNER : STRIPE_TOP; - return ImageFloatBox(STRIPE_LEFT + 0.166 * (double)index, top, 0.015, STRIPE_BOTTOM - top); + return ImageFloatBox(STRIPE_LEFT + 0.166 * (double)index, top, STRIPE_WIDTH, STRIPE_BOTTOM - top); } } // namespace @@ -149,52 +153,58 @@ class Test_MenuDetector : public ImageUnitTest{ MenuExpectation m_expectation; }; +// Every image runs with both column modes. +constexpr std::array MENU_CASES{{ + {.input = {.image = "PokemonBDSP/MenuDetector/FrenchCursorOnMap_True.png", .columns = Columns::FromTop}, + .expectation = {.detected = true}}, + {.input = {.image = "PokemonBDSP/MenuDetector/FrenchCursorOnMap_True.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = true}}, + {.input = {.image = "PokemonBDSP/MenuDetector/NewGameBagOptions_True.png", .columns = Columns::FromTop}, + .expectation = {.detected = true}}, + {.input = {.image = "PokemonBDSP/MenuDetector/NewGameBagOptions_True.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = true}}, + {.input = {.image = "PokemonBDSP/MenuDetector/JubilifeTownMapNew_True.png", .columns = Columns::FromTop}, + .expectation = {.detected = true}}, + {.input = {.image = "PokemonBDSP/MenuDetector/JubilifeTownMapNew_True.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = true}}, + {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaMenuThreeNew_True.png", .columns = Columns::FromTop}, + .expectation = {.detected = true}}, + {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaMenuThreeNew_True.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = true}}, + {.input = {.image = "PokemonBDSP/MenuDetector/Home_False.png", .columns = Columns::FromTop}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/Home_False.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/OverworldSandgemMart_False.png", .columns = Columns::FromTop}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/OverworldSandgemMart_False.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/OverworldOreburghMine_False.png", .columns = Columns::FromTop}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/OverworldOreburghMine_False.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/IntroDialog_False.png", .columns = Columns::FromTop}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/IntroDialog_False.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/IntroBarry_False.png", .columns = Columns::FromTop}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/IntroBarry_False.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaOldManDialog_False.png", .columns = Columns::FromTop}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaOldManDialog_False.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaCloudShadows_False.png", .columns = Columns::FromTop}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaCloudShadows_False.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = false}}, +}}; + } // namespace void add_tests_MenuDetector(UnitTestDatabase& database){ - static constexpr std::array CASES{{ - {.input = {.image = "PokemonBDSP/MenuDetector/NewGameBagOptions_True.png", .columns = Columns::FromTop}, - .expectation = {.detected = true}}, - {.input = {.image = "PokemonBDSP/MenuDetector/NewGameBagOptions_True.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = true}}, - {.input = {.image = "PokemonBDSP/MenuDetector/JubilifeTownMapNew_True.png", .columns = Columns::FromTop}, - .expectation = {.detected = true}}, - {.input = {.image = "PokemonBDSP/MenuDetector/JubilifeTownMapNew_True.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = true}}, - {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaMenuThreeNew_True.png", .columns = Columns::FromTop}, - .expectation = {.detected = true}}, - {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaMenuThreeNew_True.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = true}}, - {.input = {.image = "PokemonBDSP/MenuDetector/Home_False.png", .columns = Columns::FromTop}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/Home_False.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/OverworldSandgemMart_False.png", .columns = Columns::FromTop}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/OverworldSandgemMart_False.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/OverworldOreburghMine_False.png", .columns = Columns::FromTop}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/OverworldOreburghMine_False.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/IntroDialog_False.png", .columns = Columns::FromTop}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/IntroDialog_False.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/IntroBarry_False.png", .columns = Columns::FromTop}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/IntroBarry_False.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaOldManDialog_False.png", .columns = Columns::FromTop}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaOldManDialog_False.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaCloudShadows_False.png", .columns = Columns::FromTop}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaCloudShadows_False.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = false}}, - }}; - for (const MenuCase& test : CASES){ + for (const MenuCase& test : MENU_CASES){ database.add(test); } } From 5fedcce60d1d201b60e889de9ed490b644dc82f0 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:57:05 -0800 Subject: [PATCH 04/20] BDSP AutoStory: stop for Starter RNG at the Verity Lakefront Adds a "Stop for Starter RNG" option (off by default) to BDSPAutoStory. When on, plan_story_run() stops after 00.01 saves at the Verity Lakefront (17, 14) facing north, where 00.02 and Starter RNG (#1366, Start point: Verity Lakefront) start. With it off, the table and run are unchanged. --- .../AutoStory/PokemonBDSP_AutoStory.cpp | 32 ++++++++++--- .../AutoStory/PokemonBDSP_AutoStory.h | 2 + ...onBDSP_AutoStory_StorySimulation_Tests.cpp | 21 +++++++++ .../PokemonBDSP_AutoStory_StoryTable.cpp | 46 +++++++++++++++++++ .../PokemonBDSP_AutoStory_StoryTable.h | 34 ++++++++++++++ ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 45 ++++++++++++++++++ 6 files changed, 174 insertions(+), 6 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp index 9e10c1ac1f..22a44c3177 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp @@ -142,6 +142,13 @@ BDSPAutoStory::BDSPAutoStory() LockMode::LOCK_WHILE_RUNNING, StarterChoice::CHIMCHAR ) + , STOP_FOR_STARTER_RNG( + "Stop for Starter RNG:
Off by default. At the end of 00.01, save at the Verity Lakefront (17, 14) " + "facing Lake Verity's entrance and stop, where the Starter RNG program starts (Start point: Verity Lakefront). " + "After Starter RNG, let Rowan's scene finish out of the lake, save at the Verity Lakefront, and start AutoStory at 00.03.", + LockMode::LOCK_WHILE_RUNNING, + false + ) , NOTIFICATIONS({ &NOTIFICATION_PROGRAM_FINISH, &NOTIFICATION_ERROR_RECOVERABLE, @@ -152,6 +159,7 @@ BDSPAutoStory::BDSPAutoStory() PA_ADD_OPTION(NEW_GAME_INTRO); PA_ADD_OPTION(PLAYER_NAME); PA_ADD_OPTION(STARTER); + PA_ADD_OPTION(STOP_FOR_STARTER_RNG); PA_ADD_OPTION(NOTIFICATIONS); } @@ -248,7 +256,10 @@ void BDSPAutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerCo StoryEnv story{env, context, STARTER, PLAYER_NAME}; StoryExecutor executor(story); - executor.set_stop_rows(rows_that_stop(checkpoints)); + const StoryRunPlan plan = plan_story_run( + checkpoints, first, last, StoryHandoffs{.starter_rng = STOP_FOR_STARTER_RNG} + ); + executor.set_stop_rows(rows_that_stop(plan.rows)); // A start with a save always loads it first, so the run never walks // from wherever the game was left (console B, 2026-11-11: a run from // 00.04b walked from 00.04d's position). @@ -257,19 +268,28 @@ void BDSPAutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerCo if (new_game && RUN.VERIFY.policy()){ throw UserSetupError(env.console, "Verify mode reloads the start's save between runs: turn off \"Start a new game first\"."); } - std::set saved = saved_before_the_run(checkpoints, first, start); - Pokemon::Segment segment = make_story_segment(checkpoints, executor, saved); + std::set saved = saved_before_the_run(plan.rows, 0, start); + Pokemon::Segment segment = make_story_segment(plan.rows, executor, saved); Pokemon::StoryGameHooks game = story_game(env, context); Pokemon::RunState state; - start_story(env, context, checkpoints[first], start, game, state); + start_story(env, context, plan.rows.front(), start, game, state); if (const std::optional verify = RUN.VERIFY.policy()){ - const std::string summary = verify_story_checkpoint(checkpoints[first].id, *verify, segment, game, state); + const std::string summary = verify_story_checkpoint(plan.rows.front().id, *verify, segment, game, state); send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, summary); return; } const std::string done = run_story( - Pokemon::SegmentRange{checkpoints[first].id, checkpoints[last].id}, RUN.policy(), segment, game, state, env + Pokemon::SegmentRange{plan.rows.front().id, plan.rows.back().id}, RUN.policy(), segment, game, state, env ); + if (plan.stop == StoryHandoff::STARTER_RNG){ + const std::string handoff = + "Stopped for Starter RNG: saved at the Verity Lakefront (17, 14), facing Lake Verity's entrance. " + "Run Starter RNG now (Start point: Verity Lakefront). " + "After Starter RNG, let Rowan's scene finish out of the lake, save at the Verity Lakefront, and start AutoStory at 00.03."; + env.log(handoff, COLOR_BLUE); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, handoff); + return; + } send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, done); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h index 154eccade4..2640e20c8e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h @@ -49,6 +49,8 @@ class BDSPAutoStory : public SingleSwitchProgramInstance{ BooleanCheckBoxOption NEW_GAME_INTRO; StringOption PLAYER_NAME; EnumDropdownOption STARTER; + // The RNG program the run stops for (StoryHandoff). + BooleanCheckBoxOption STOP_FOR_STARTER_RNG; EventNotificationsOption NOTIFICATIONS; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index 79bab21f0a..1ffcf63afc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -442,6 +442,27 @@ UnitTestResult test_start_and_end(Logger&){ if (!report.completed || one.begun() != std::vector{"00.02"}){ return "Expected 00.02 alone:" + joined(one.begun()); } + // With Stop for Starter RNG on, a 00.00..01.11 run stops after 00.01 + // saves at the Verity Lakefront (17, 14) facing north. + Simulation handoff_sim; + const StoryRunPlan plan = plan_story_run( + story_checkpoints(), 0, story_checkpoints().size() - 1, StoryHandoffs{.starter_rng = true} + ); + Pokemon::Segment handoff_segment = make_story_segment(plan.rows, handoff_sim.game, handoff_sim.saved); + Pokemon::SegmentHooks hooks; + hooks.reload = [&](RunState&){ return Pokemon::outcome_ok(); }; + RunState handoff_state; + const Pokemon::SegmentReport handoff_report = Pokemon::run_segment( + {.from = plan.rows.front().id, .to = plan.rows.back().id}, handoff_sim.policy, handoff_segment, hooks, handoff_state + ); + if (!handoff_report.completed || plan.stop != StoryHandoff::STARTER_RNG || + handoff_sim.begun() != std::vector{"00.00", "00.01"} || + handoff_sim.count("00.01/save_for_starter_rng") != 1 || + handoff_state.pose.map != "VerityLakefront" || + Pokemon::tiles_of(handoff_state.pose) != std::vector{{17, 14}} + ){ + return "Expected Starter RNG handoff to stop after 00.01 saved at VerityLakefront (17, 14):" + joined(handoff_sim.trace); + } return true; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 3977dedaa1..b2ec0db15d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -7,6 +7,8 @@ * */ +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" #include "PokemonBDSP_AutoStory_StoryData.h" #include "PokemonBDSP_AutoStory_StoryTable.h" @@ -15,11 +17,55 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ +namespace{ + +// `row` with a save appended at its end, where the next checkpoint starts: +// in BDSP rows normally save at their start, so a run that stops after +// 00.01 for Starter RNG makes 00.02's Lakefront save before stopping. +StoryCheckpoint with_handoff_save(StoryCheckpoint row){ + Pokemon::StoryStep save; + save.kind = Pokemon::StoryStepKind::SAVE; + save.name = "save_for_starter_rng"; + save.why = "the save at the Verity Lakefront where Starter RNG starts"; + if (!row.steps.empty()){ + const Pokemon::StoryStep& last = row.steps.back(); + if (last.pose_after){ + save.pose_after = last.pose_after; + }else if (last.kind == Pokemon::StoryStepKind::ROUTE){ + const Pokemon::GridPose& target = Pokemon::story_arg(last.args, "target"); + save.pose_after = Pokemon::TileDeclared{ + .map = target.map, .tiles = target.tiles, .facing = target.facing + }; + } + } + row.steps.push_back(std::move(save)); + return row; +} + +} // namespace + + const std::vector& story_checkpoints(){ static const std::vector checkpoints = load_authored_story(); return checkpoints; } +StoryRunPlan plan_story_run( + const std::vector& checkpoints, size_t first, size_t last, const StoryHandoffs& handoffs +){ + StoryRunPlan plan; + for (size_t c = first; c <= last && c < checkpoints.size(); c++){ + const StoryCheckpoint& row = checkpoints[c]; + if (row.id == STARTER_RNG_HANDOFF_ROW && handoffs.starter_rng){ + plan.rows.push_back(with_handoff_save(row)); + plan.stop = StoryHandoff::STARTER_RNG; + return plan; + } + plan.rows.push_back(row); + } + return plan; +} + } // namespace PokemonBDSP } // namespace NintendoSwitch diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h index 72504da1b8..77254e4532 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h @@ -33,6 +33,40 @@ inline constexpr std::string_view RUNNING_SHOES_ROW = "00.03"; // Story step name in which Mom gives the Running Shoes. inline constexpr std::string_view RUNNING_SHOES_STEP = "rowan_and_dawn"; +// 00.01 ends at the Verity Lakefront (17, 14) facing north, where 00.02 and +// Starter RNG (Start point: Verity Lakefront) start. +inline constexpr std::string_view STARTER_RNG_HANDOFF_ROW = "00.01"; + +// An upstream RNG program the user may run part-way through the story. +enum class StoryHandoff{ + NONE, + // The run stops after 00.01 saves at the Verity Lakefront (17, 14), + // facing Lake Verity's entrance, where Starter RNG starts. + STARTER_RNG, +}; + +// The handoffs a run stops for (AutoStory's options). +struct StoryHandoffs{ + bool starter_rng = false; +}; + +// What a run from table row `first` to `last` does. +struct StoryRunPlan{ + // The checkpoints to run, in order. + std::vector rows; + // NONE: the run ends after `rows`. STARTER_RNG: the run stops after + // `rows`, the last of which (00.01) saves at the Verity Lakefront. + StoryHandoff stop = StoryHandoff::NONE; +}; + +// The rows of `checkpoints` from `first` to `last`, both inclusive, as a +// run with `handoffs` takes them: a run that reaches 00.01 with +// `handoffs.starter_rng` on saves at the Verity Lakefront at the end of +// 00.01 and stops there for Starter RNG. +StoryRunPlan plan_story_run( + const std::vector& checkpoints, size_t first, size_t last, const StoryHandoffs& handoffs = {} +); + } // namespace PokemonBDSP diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index 09f4e95ba9..57d504b136 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -231,6 +231,47 @@ UnitTestResult test_route204_north_line(Logger& logger){ return true; } +// plan_story_run() with Starter RNG handoff: off leaves the range unchanged; +// on stops after 00.01 with a save at the Verity Lakefront (17, 14) facing +// north, where 00.02 and Starter RNG start; starting past 00.01 runs on. +UnitTestResult test_plan_story_run_starter_rng(Logger&){ + const std::vector& table = story_checkpoints(); + const StoryRunPlan full = plan_story_run(table, 0, table.size() - 1, StoryHandoffs{.starter_rng = false}); + if (full.stop != StoryHandoff::NONE || full.rows.size() != table.size()){ + return "With Starter RNG handoff off, expected the full table with no stop."; + } + const StoryRunPlan handoff = plan_story_run(table, 0, table.size() - 1, StoryHandoffs{.starter_rng = true}); + if (handoff.stop != StoryHandoff::STARTER_RNG || handoff.rows.size() != 2 || + handoff.rows[0].id != "00.00" || handoff.rows[1].id != "00.01" + ){ + return "Expected a 00.00..01.11 run with Starter RNG handoff to stop after 00.01."; + } + const StoryCheckpoint& lakefront_row = handoff.rows.back(); + const std::vector problems = Pokemon::lint_story_checkpoint(lakefront_row); + if (!problems.empty()){ + return "00.01 with Starter RNG handoff save: " + problems[0]; + } + if (lakefront_row.steps.empty() || lakefront_row.steps.back().kind != StoryStepKind::SAVE || + lakefront_row.steps.back().name != "save_for_starter_rng" + ){ + return "Expected 00.01 with Starter RNG handoff to end with save_for_starter_rng."; + } + const std::optional end = end_pose(lakefront_row); + const std::optional next_start = table[2].start + ? std::make_optional(Pokemon::pose_of(*table[2].start)) + : std::nullopt; + if (!end || !next_start || end->map != "VerityLakefront" || + Pokemon::to_string(*end) != Pokemon::to_string(*next_start) + ){ + return "Expected 00.01's Starter RNG handoff save to end at 00.02's VerityLakefront (17, 14) start pose."; + } + const StoryRunPlan from_0002 = plan_story_run(table, 2, 4, StoryHandoffs{.starter_rng = true}); + if (from_0002.stop != StoryHandoff::NONE || from_0002.rows.size() != 3 || from_0002.rows.front().id != "00.02"){ + return "Expected a run starting at 00.02 to pass through without stopping for 00.01's handoff."; + } + return true; +} + struct AutoStoryStoryTableInput{ std::string name; @@ -283,6 +324,10 @@ const AutoStoryStoryTableCase AUTO_STORY_STORY_TABLE_CASES[] = { .input = {"Route 204 North: the line into Floaroma", test_route204_north_line}, .expectation = {}, }, + { + .input = {"Starter RNG handoff: stops after 00.01 saved at the Verity Lakefront", test_plan_story_run_starter_rng}, + .expectation = {}, + }, }; void add_tests_AutoStory_StoryTable(UnitTestDatabase& database){ From 03bc3d44653c5d72df23b3227abdfb09b4a223a6 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:00:34 -0800 Subject: [PATCH 05/20] BDSP: port Starter RNG from #1366 (theastrogoth) Port the remaining Starter RNG files from PokemonAutomation/Arduino-Source#1366 (by theastrogoth) onto the merged BDSP RNG infrastructure: - BdspRngFilterRow / BdspRngFilterTable / BdspRngFilterSnapshot - RngAim, RngCalibration, RngExecution, RngTargets, RngTimeline, TargetSelection - StarterNavigation, SummaryNavigation, StarterRng Adapt to the upstreamed BlinkRecovery, BlinkScenes, AdvanceClock, and SingleSwitchProgramDescriptor APIs, and register StarterRng in PokemonBDSP_Panels. --- .../Options/PokemonBDSP_RngFilter.cpp | 212 ++++++ .../Options/PokemonBDSP_RngFilter.h | 100 +++ .../Source/PokemonBDSP/PokemonBDSP_Panels.cpp | 2 + .../RngManipulation/PokemonBDSP_RngAim.cpp | 77 ++ .../RngManipulation/PokemonBDSP_RngAim.h | 52 ++ .../PokemonBDSP_RngCalibration.cpp | 188 +++++ .../PokemonBDSP_RngCalibration.h | 79 ++ .../PokemonBDSP_RngExecution.cpp | 130 ++++ .../PokemonBDSP_RngExecution.h | 59 ++ .../PokemonBDSP_RngTargets.cpp | 155 ++++ .../RngManipulation/PokemonBDSP_RngTargets.h | 52 ++ .../PokemonBDSP_RngTimeline.cpp | 140 ++++ .../RngManipulation/PokemonBDSP_RngTimeline.h | 57 ++ .../PokemonBDSP_StarterNavigation.cpp | 255 +++++++ .../PokemonBDSP_StarterNavigation.h | 102 +++ .../PokemonBDSP_StarterRng.cpp | 701 ++++++++++++++++++ .../RngManipulation/PokemonBDSP_StarterRng.h | 127 ++++ .../PokemonBDSP_SummaryNavigation.cpp | 165 +++++ .../PokemonBDSP_SummaryNavigation.h | 41 + .../PokemonBDSP_TargetSelection.cpp | 122 +++ .../PokemonBDSP_TargetSelection.h | 57 ++ SerialPrograms/cmake/SourceFiles.cmake | 20 + 22 files changed, 2893 insertions(+) create mode 100644 SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.h diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp new file mode 100644 index 0000000000..eeabbcea8d --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp @@ -0,0 +1,212 @@ +/* BDSP RNG Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Logging/Logger.h" +#include "PokemonBDSP_RngFilter.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +const uint8_t BDSP_HEIGHT_MIN = 0; +const uint8_t BDSP_HEIGHT_MAX = 255; + + +BdspRngFilterRow::BdspRngFilterRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , misc(static_cast(parent_table).feature_flags) + , height( + LockMode::UNLOCK_WHILE_RUNNING, + BDSP_HEIGHT_MIN, BDSP_HEIGHT_MAX, BDSP_HEIGHT_MIN, BDSP_HEIGHT_MIN, + BDSP_HEIGHT_MIN, BDSP_HEIGHT_MAX, BDSP_HEIGHT_MAX, BDSP_HEIGHT_MAX + ) + , iv_hp(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_atk(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_def(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_spatk(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_spdef(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_speed(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) +{ + if (misc.feature_flags.action){ + PA_ADD_OPTION(misc.action); + } + if (misc.feature_flags.shiny){ + PA_ADD_OPTION(misc.shiny); + } + if (misc.feature_flags.gender){ + PA_ADD_OPTION(misc.gender); + } + if (misc.feature_flags.nature){ + PA_ADD_OPTION(misc.nature); + } + PA_ADD_OPTION(height); + PA_ADD_OPTION(iv_hp); + PA_ADD_OPTION(iv_atk); + PA_ADD_OPTION(iv_def); + PA_ADD_OPTION(iv_spatk); + PA_ADD_OPTION(iv_spdef); + PA_ADD_OPTION(iv_speed); +} +std::unique_ptr BdspRngFilterRow::clone() const{ + std::unique_ptr ret(new BdspRngFilterRow(parent())); + ret->misc.set(misc); + ret->height.set(height); + ret->iv_hp.set(iv_hp); + ret->iv_atk.set(iv_atk); + ret->iv_def.set(iv_def); + ret->iv_spatk.set(iv_spatk); + ret->iv_spdef.set(iv_spdef); + ret->iv_speed.set(iv_speed); + return ret; +} +bool BdspRngFilterRow::match_iv( + const IntegerRangeCell& desired, const IvRange& actual +){ + uint8_t lo, hi; + desired.current_values(lo, hi); + if (lo == 0 && hi == 31){ + return true; + } + if (actual.high < (int8_t)lo){ + return false; + } + if ((int8_t)hi < actual.low){ + return false; + } + return true; +} +bool BdspRngFilterRow::matches( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + uint8_t height, + const IvRanges& ivs +) const{ + if (!misc.matches(shiny, gender, nature)){ + return false; + } + + uint8_t height_lo, height_hi; + this->height.current_values(height_lo, height_hi); + if (height < height_lo || height_hi < height){ + return false; + } + + if (!match_iv(iv_hp, ivs.hp)){ + return false; + } + if (!match_iv(iv_atk, ivs.attack)){ + return false; + } + if (!match_iv(iv_def, ivs.defense)){ + return false; + } + if (!match_iv(iv_spatk, ivs.spatk)){ + return false; + } + if (!match_iv(iv_spdef, ivs.spdef)){ + return false; + } + if (!match_iv(iv_speed, ivs.speed)){ + return false; + } + + return true; +} + + +BdspRngFilterTable::BdspRngFilterTable( + const std::string& label, + const StatsHuntMiscFeatureFlags& p_feature_flags +) + : EditableTableOption_t(label, LockMode::UNLOCK_WHILE_RUNNING) + , feature_flags(p_feature_flags) +{} +std::vector BdspRngFilterTable::make_header() const{ + std::vector ret; + if (feature_flags.action){ + ret.emplace_back("Action"); + } + if (feature_flags.shiny){ + ret.emplace_back("Shininess"); + } + if (feature_flags.gender){ + ret.emplace_back("Gender"); + } + if (feature_flags.nature){ + ret.emplace_back("Nature"); + } + + ret.emplace_back("Height"); + + ret.emplace_back("HP"); + ret.emplace_back("Atk"); + ret.emplace_back("Def"); + ret.emplace_back("SpAtk"); + ret.emplace_back("SpDef"); + ret.emplace_back("Spd"); + + return ret; +} +BdspRngFilterSnapshot BdspRngFilterTable::make_snapshot() const{ + return BdspRngFilterSnapshot(copy_snapshot()); +} +StatsHuntAction BdspRngFilterTable::get_action( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + uint8_t height, + const IvRanges& ivs +) const{ + return make_snapshot().get_action(shiny, gender, nature, height, ivs); +} + + +BdspRngFilterSnapshot::BdspRngFilterSnapshot(std::vector> rows) + : m_rows(std::move(rows)) +{} +StatsHuntAction BdspRngFilterSnapshot::get_action( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + uint8_t height, + const IvRanges& ivs +) const{ + StatsHuntAction action = StatsHuntAction::Discard; + for (size_t c = 0; c < m_rows.size(); c++){ + const BdspRngFilterRow& filter = *m_rows[c]; + + if (!filter.matches(shiny, gender, nature, height, ivs)){ + continue; + } + + StatsHuntAction filter_action = filter.misc.action; + + // No action matched so far. Take the current action and continue. + if (action == StatsHuntAction::Discard){ + action = filter_action; + continue; + } + + // Conflicting actions. + if (action != filter_action){ + global_logger_tagged().log( + "Multiple filters matched with conflicting actions. Stopping program...", + COLOR_RED + ); + return StatsHuntAction::StopProgram; + } + } + return action; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h new file mode 100644 index 0000000000..d9d66aff06 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h @@ -0,0 +1,100 @@ +/* BDSP RNG Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngFilter_H +#define PokemonAutomation_PokemonBDSP_RngFilter_H + +#include +#include +#include +#include "Common/Cpp/Options/EditableTableOption.h" +#include "Common/Cpp/Options/IntegerRangeOption.h" +#include "Pokemon/Pokemon_NatureChecker.h" +#include "Pokemon/Pokemon_StatsCalculation.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class BdspRngFilterTable; +class BdspRngFilterRow : public EditableTableRow{ +public: + BdspRngFilterRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + + bool matches( + bool shiny, + Pokemon::StatsHuntGenderFilter gender, + Pokemon::NatureCheckerValue nature, + uint8_t height, + const Pokemon::IvRanges& ivs + ) const; + +private: + static bool match_iv(const IntegerRangeCell& desired, const Pokemon::IvRange& actual); + +public: + Pokemon::StatsHuntRowMisc misc; + + IntegerRangeCell height; + + IntegerRangeCell iv_hp; + IntegerRangeCell iv_atk; + IntegerRangeCell iv_def; + IntegerRangeCell iv_spatk; + IntegerRangeCell iv_spdef; + IntegerRangeCell iv_speed; +}; + + +// The table copied once. Calling get_action() on the table itself clones every row on +// every call, which is far too slow for a scan running over millions of advances. +class BdspRngFilterSnapshot{ +public: + explicit BdspRngFilterSnapshot(std::vector> rows); + + Pokemon::StatsHuntAction get_action( + bool shiny, + Pokemon::StatsHuntGenderFilter gender, + Pokemon::NatureCheckerValue nature, + uint8_t height, + const Pokemon::IvRanges& ivs + ) const; + +private: + std::vector> m_rows; +}; + + +class BdspRngFilterTable : public EditableTableOption_t{ +public: + BdspRngFilterTable( + const std::string& label, + const Pokemon::StatsHuntMiscFeatureFlags& p_feature_flags + ); + virtual std::vector make_header() const override; + + BdspRngFilterSnapshot make_snapshot() const; + + Pokemon::StatsHuntAction get_action( + bool shiny, + Pokemon::StatsHuntGenderFilter gender, + Pokemon::NatureCheckerValue nature, + uint8_t height, + const Pokemon::IvRanges& ivs + ) const; + +public: + const Pokemon::StatsHuntMiscFeatureFlags feature_flags; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.cpp index 7f1b00688e..a9f0675086 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.cpp @@ -41,6 +41,7 @@ #include "Programs/RngManipulation/PokemonBDSP_BedroomSeedFinder.h" #include "Programs/RngManipulation/PokemonBDSP_IntroSeedFinder.h" +#include "Programs/RngManipulation/PokemonBDSP_StarterRng.h" #include "Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.h" #include "Programs/TestPrograms/PokemonBDSP_SoundListener.h" @@ -67,6 +68,7 @@ void add_beta_and_developer_panels(std::vector& ret){ ret.emplace_back("---- Untested/Beta/WIP ----"); ret.emplace_back(make_SingleSwitchProgram()); ret.emplace_back(make_SingleSwitchProgram()); + ret.emplace_back(make_SingleSwitchProgram()); } if (STATIC_GLOBALS.DEVELOPER_MODE){ ret.emplace_back("---- Developer Tools ----"); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.cpp new file mode 100644 index 0000000000..2e11e5261b --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.cpp @@ -0,0 +1,77 @@ +/* BDSP RNG Aim + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "PokemonBDSP_RngAim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +uint64_t aimed_advance(uint64_t press, uint64_t span, int64_t bias){ + int64_t advance = (int64_t)(press + span) + bias; + return advance < 0 ? 0 : (uint64_t)advance; +} + +int64_t press_for_advance(uint64_t target, uint64_t span, int64_t bias){ + return (int64_t)target - (int64_t)span - bias; +} + + +RngAim::RngAim(size_t minimum_samples, double threshold) + : m_minimum_samples(minimum_samples) + , m_threshold(threshold) +{} + +void RngAim::reset(){ + m_bias = 0; + m_offsets.clear(); +} + +bool RngAim::record_offset(Logger& logger, int64_t offset, bool enabled){ + m_offsets.emplace_back(offset); + if (!enabled || m_offsets.size() < m_minimum_samples){ + return false; + } + double mean = 0; + for (int64_t o : m_offsets){ + mean += (double)o; + } + mean /= (double)m_offsets.size(); + if (std::abs(mean) < m_threshold){ + return false; + } + int64_t shift = (int64_t)std::llround(mean); + if (shift == 0){ + return false; + } + m_bias += shift; + logger.log( + std::to_string(m_offsets.size()) + " measured attempt(s) average " + + tostr_fixed(mean, 2) + " advance(s) off, so the aim shifts by " + + std::to_string(shift) + " to " + std::to_string(m_bias) + ".", + COLOR_BLUE + ); + m_offsets.clear(); + return true; +} + +std::string RngAim::describe_correction() const{ + if (m_bias == 0){ + return ""; + } + return ", plus " + std::to_string(m_bias) + " measured"; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.h new file mode 100644 index 0000000000..608f448315 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.h @@ -0,0 +1,52 @@ +/* BDSP RNG Aim + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngAim_H +#define PokemonAutomation_PokemonBDSP_RngAim_H + +#include +#include +#include +#include + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// The advance where a press will generate the target Pokemon +uint64_t aimed_advance(uint64_t press, uint64_t span, int64_t bias); + +// The press that would reach "target" through a schedule of a certain length +int64_t press_for_advance(uint64_t target, uint64_t span, int64_t bias); + + +class RngAim{ +public: + explicit RngAim(size_t minimum_samples = 3, double threshold = 1.0); + + int64_t bias() const{ return m_bias; } + + void reset(); + + bool record_offset(Logger& logger, int64_t offset, bool enabled); + + std::string describe_correction() const; + +private: + size_t m_minimum_samples; + double m_threshold; + + int64_t m_bias = 0; + std::vector m_offsets; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.cpp new file mode 100644 index 0000000000..1e427daf5a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.cpp @@ -0,0 +1,188 @@ +/* BDSP RNG Calibration + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonBDSP_RngCalibration.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +NatureAdjustment bdsp_nature_adjustment(uint8_t nature, size_t stat_index){ + if (nature >= 25 || stat_index >= 5){ + return NatureAdjustment::NEUTRAL; + } + size_t raised = nature / 5; + size_t lowered = nature % 5; + if (raised == lowered){ + // Hardy, Docile, Serious, Bashful, Quirky. + return NatureAdjustment::NEUTRAL; + } + if (stat_index == raised){ + return NatureAdjustment::POSITIVE; + } + if (stat_index == lowered){ + return NatureAdjustment::NEGATIVE; + } + return NatureAdjustment::NEUTRAL; +} + + +// The nature index orders stats [Atk, Def, Spe, SpA, SpD]; +static const size_t NATURE_INDEX_ATTACK = 0; +static const size_t NATURE_INDEX_DEFENSE = 1; +static const size_t NATURE_INDEX_SPEED = 2; +static const size_t NATURE_INDEX_SPATK = 3; +static const size_t NATURE_INDEX_SPDEF = 4; + + +StatReads bdsp_expected_stats( + const BdspPokemonResult& generated, + const BaseStats& base_stats, + uint8_t level +){ + StatReads ret; + ret.hp = (int16_t)calc_stats_hp(base_stats.hp, level, generated.ivs.hp, 0); + ret.attack = (int16_t)calc_stats_nonhp( + base_stats.attack, level, generated.ivs.attack, 0, + bdsp_nature_adjustment(generated.nature, NATURE_INDEX_ATTACK) + ); + ret.defense = (int16_t)calc_stats_nonhp( + base_stats.defense, level, generated.ivs.defense, 0, + bdsp_nature_adjustment(generated.nature, NATURE_INDEX_DEFENSE) + ); + ret.spatk = (int16_t)calc_stats_nonhp( + base_stats.spatk, level, generated.ivs.spatk, 0, + bdsp_nature_adjustment(generated.nature, NATURE_INDEX_SPATK) + ); + ret.spdef = (int16_t)calc_stats_nonhp( + base_stats.spdef, level, generated.ivs.spdef, 0, + bdsp_nature_adjustment(generated.nature, NATURE_INDEX_SPDEF) + ); + ret.speed = (int16_t)calc_stats_nonhp( + base_stats.speed, level, generated.ivs.speed, 0, + bdsp_nature_adjustment(generated.nature, NATURE_INDEX_SPEED) + ); + return ret; +} + + +bool advances_between( + const Xorshift128State& from, + const Xorshift128State& to, + uint64_t search_max, + uint64_t& advances +){ + Xorshift128 rng(from); + for (uint64_t c = 0; c <= search_max; c++){ + if (rng.state() == to){ + advances = c; + return true; + } + rng.next(); + } + return false; +} + + +const BaseStats& starter_base_stats(BdspStarter starter){ + // Order: HP, Atk, Def, SpA, SpD, Spe. + static const BaseStats TURTWIG {55, 68, 64, 45, 55, 31}; + static const BaseStats CHIMCHAR{44, 58, 44, 58, 44, 61}; + static const BaseStats PIPLUP {53, 51, 53, 61, 56, 40}; + switch (starter){ + case BdspStarter::Turtwig: return TURTWIG; + case BdspStarter::Chimchar: return CHIMCHAR; + case BdspStarter::Piplup: return PIPLUP; + } + return TURTWIG; +} + + +// A reading of -1 was not taken, so it rules nothing out. +static bool stat_fits(int16_t observed, int16_t expected){ + return observed < 0 || observed == expected; +} + + +bool consistent_with( + const BdspPokemonResult& generated, + const BdspObservedStarter& observed +){ + if (observed.nature != NatureCheckerValue::UnableToDetect + && bdsp_nature_to_checker_value(generated.nature) != observed.nature + ){ + return false; + } + if (observed.gender_known && generated.gender != observed.gender){ + return false; + } + if (observed.shiny_known && (generated.shiny != BdspShiny::None) != observed.shiny){ + return false; + } + + StatReads expected = bdsp_expected_stats(generated, observed.base_stats, observed.level); + return stat_fits(observed.stats.hp, expected.hp) + && stat_fits(observed.stats.attack, expected.attack) + && stat_fits(observed.stats.defense, expected.defense) + && stat_fits(observed.stats.spatk, expected.spatk) + && stat_fits(observed.stats.spdef, expected.spdef) + && stat_fits(observed.stats.speed, expected.speed); +} + + +BdspHitIdentification identify_hit_advance( + const Xorshift128State& state, + const BdspStaticTemplate& tmpl, + uint64_t intended_advance, + uint64_t radius, + const BdspObservedStarter& observed +){ + BdspHitIdentification ret; + + uint64_t first = intended_advance > radius ? intended_advance - radius : 0; + uint64_t last = intended_advance + radius; + + BdspStaticSearcher searcher(state, tmpl, 0); + + std::vector matches = searcher.scan( + first, last, + [&](const BdspPokemonResult& candidate){ return consistent_with(candidate, observed); } + ); + ret.candidates = matches.size(); + + if (ret.candidates == 0){ + ret.failure_reason = "no advance within " + std::to_string(radius) + + " of " + std::to_string(intended_advance) + + " produces that Pokemon. Either the recovered state was wrong, or the press " + "missed by more than the search covered."; + return ret; + } + if (ret.candidates > 1){ + ret.failure_reason = std::to_string(ret.candidates) + + " advances fit what was read ("; + for (size_t c = 0; c < matches.size(); c++){ + ret.failure_reason += (c == 0 ? "" : ", ") + std::to_string(matches[c].advances); + } + ret.failure_reason += "), so which one was hit cannot be told apart here."; + return ret; + } + + ret.success = true; + ret.advance = matches[0].advances; + ret.offset = (int64_t)ret.advance - (int64_t)intended_advance; + return ret; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.h new file mode 100644 index 0000000000..8687e695de --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.h @@ -0,0 +1,79 @@ +/* BDSP RNG Calibration + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngCalibration_H +#define PokemonAutomation_PokemonBDSP_RngCalibration_H + +#include +#include +#include "Pokemon/Pokemon_BdspRng.h" +#include "Pokemon/Pokemon_NatureChecker.h" +#include "Pokemon/Pokemon_StatsCalculation.h" +#include "PokemonBDSP_StarterNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +Pokemon::NatureAdjustment bdsp_nature_adjustment(uint8_t nature, size_t stat_index); + +Pokemon::StatReads bdsp_expected_stats( + const Pokemon::BdspPokemonResult& generated, + const Pokemon::BaseStats& base_stats, + uint8_t level +); + +struct BdspObservedStarter{ + Pokemon::NatureCheckerValue nature = Pokemon::NatureCheckerValue::UnableToDetect; + Pokemon::BdspGender gender = Pokemon::BdspGender::Genderless; + bool gender_known = false; + Pokemon::StatReads stats; + Pokemon::BaseStats base_stats; + uint8_t level = 5; + bool shiny = false; + bool shiny_known = false; +}; + + +struct BdspHitIdentification{ + bool success = false; + uint64_t advance = 0; + int64_t offset = 0; + size_t candidates = 0; + std::string failure_reason; +}; + + +BdspHitIdentification identify_hit_advance( + const Pokemon::Xorshift128State& state, + const Pokemon::BdspStaticTemplate& tmpl, + uint64_t intended_advance, + uint64_t radius, + const BdspObservedStarter& observed +); + + +bool advances_between( + const Pokemon::Xorshift128State& from, + const Pokemon::Xorshift128State& to, + uint64_t search_max, + uint64_t& advances +); + + +const Pokemon::BaseStats& starter_base_stats(BdspStarter starter); + +bool consistent_with( + const Pokemon::BdspPokemonResult& generated, + const BdspObservedStarter& observed +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.cpp new file mode 100644 index 0000000000..6827c5a889 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.cpp @@ -0,0 +1,130 @@ +/* BDSP RNG Execution + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/PrettyPrint.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP_RngExecution.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +static size_t first_free_blink(const BdspTimelineContext& timeline){ + size_t before_blinks = 1 + (timeline.plus_one_on_menu_close ? 1 : 0) + + timeline.advance_delay + timeline.pokemon_models; + size_t last_waited = before_blinks + timeline.advance_delay_2_after_events - 1; + return last_waited + 1 + timeline.advance_delay_2; +} + + +static size_t timeline_depth(const BdspTimelineContext& timeline, size_t max_schedules){ + return first_free_blink(timeline) + 4 * max_schedules + 2; +} + +void schedule_span_bounds( + const BdspTimelineContext& timeline, size_t max_schedules, + uint64_t& lowest, uint64_t& highest +){ + lowest = first_free_blink(timeline) + 1 + timeline.advances_after_accept; + highest = timeline_depth(timeline, max_schedules) - 1 + timeline.advances_after_accept; +} + + +std::vector schedule_presses( + const Pokemon::Xorshift128State& state, + const BdspTimelineContext& timeline, + const NavigationTimings& timings, + uint64_t press, + size_t max_schedules +){ + std::vector schedules; + + size_t first_free = first_free_blink(timeline); + size_t last_waited = first_free - 1 - timeline.advance_delay_2; + + Pokemon::Xorshift128 rng(state); + rng.advance(press); + BdspTimelineResult simulated = simulate_timeline( + rng, timeline, timeline_depth(timeline, max_schedules) + ); + const std::vector& at = simulated.advance_times; + if (at.size() < first_free + 2){ + return schedules; + } + + // The second press goes between the last blink it waits for and the next. + double starly = (at[last_waited] + at[last_waited + 1]) / 2; + if (starly < timings.ready_seconds){ + return schedules; + } + double earliest_select = starly + timings.move_seconds; + + for (size_t blink = first_free; + blink + 1 < at.size() && schedules.size() < max_schedules; + blink++ + ){ + double gap_start = at[blink]; + double gap_end = at[blink + 1]; + + // Centred in the gap when there is room, pushed as late as the navigation + // demands when there is not. + double select_at = std::max( + (gap_start + gap_end - timings.prompt_seconds) / 2, earliest_select + ); + double confirm_at = select_at + timings.prompt_seconds; + if (select_at - gap_start < timings.guard_seconds + || gap_end - confirm_at < timings.guard_seconds + ){ + continue; + } + + schedules.push_back(PressSchedule{ + /*span*/ blink + 1 + timeline.advances_after_accept, + /*starly_seconds*/ starly, + /*select_seconds*/ select_at, + /*confirm_seconds*/ confirm_at, + /*blinks_before_confirm*/ blink + 1 - first_free, + }); + } + + return schedules; +} + + +bool wait_until_moment(ProControllerContext& context, Logger& logger, WallClock when){ + context.wait_for_all_requests(); + + WallClock now = current_time(); + if (when < now){ + double late = std::chrono::duration_cast>( + now - when + ).count(); + logger.log( + "The moment passed " + tostr_fixed(late, 3) + " seconds ago. " + "Abandoning the attempt rather than starting late.", + COLOR_ORANGE + ); + return false; + } + + Milliseconds wait = std::chrono::duration_cast(when - now); + pbf_wait(context, wait); + logger.log("Waiting " + std::to_string(wait.count()) + " ms for the timeline.", + COLOR_BLUE); + return true; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.h new file mode 100644 index 0000000000..c5ab0d7ebe --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.h @@ -0,0 +1,59 @@ +/* BDSP RNG Execution + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngExecution_H +#define PokemonAutomation_PokemonBDSP_RngExecution_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "PokemonBDSP_RngTimeline.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +struct PressSchedule{ + uint64_t span = 0; + double starly_seconds = 0; + double select_seconds = 0; + double confirm_seconds = 0; + uint64_t blinks_before_confirm = 0; +}; + +struct NavigationTimings{ + double ready_seconds = 0; + double move_seconds = 0; + double prompt_seconds = 0; + double guard_seconds = 0.30; +}; + + +void schedule_span_bounds( + const BdspTimelineContext& timeline, size_t max_schedules, + uint64_t& lowest, uint64_t& highest +); + +std::vector schedule_presses( + const Pokemon::Xorshift128State& state, + const BdspTimelineContext& timeline, + const NavigationTimings& timings, + uint64_t press, + size_t max_schedules +); + + +bool wait_until_moment(ProControllerContext& context, Logger& logger, WallClock when); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.cpp new file mode 100644 index 0000000000..b0d9785d0a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.cpp @@ -0,0 +1,155 @@ +/* BDSP RNG Targets + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "PokemonBDSP_RngTargets.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +static BdspStaticTemplate starter_template(){ + BdspStaticTemplate ret; + ret.species = "starter"; + ret.level = 5; + ret.guaranteed_ivs = 0; + ret.ability_kind = 3; + ret.gender_ratio = 31; // Seven males to one female. + return ret; +} + +static BdspStaticTemplate legendary_template(const char* species, uint8_t level){ + BdspStaticTemplate ret; + ret.species = species; + ret.level = level; + ret.guaranteed_ivs = 3; + ret.ability_kind = 3; + ret.gender_ratio = 255; // Genderless. + return ret; +} + + +static const BdspRngTargetInfo& target_table(BdspRngTarget target){ + static const BdspRngTargetInfo STARTER{ + "starter", "Starter", + starter_template(), + BdspTimelineContext{ + /*npcs*/ 0, + /*pokemon_models*/ 2, + /*white_delay_seconds*/ 0.0, + /*advance_delay*/ 41, + /*advance_delay_2*/ 48, + /*advance_delay_2_after_events*/ 10, + /*plus_one_on_menu_close*/ false, + /*advances_after_accept*/ 65, + }, + /*observation_npcs*/ 2, + /*has_timeline*/ true, + }; + + static const BdspRngTargetInfo DIALGA{ + "dialga", "Dialga", + legendary_template("dialga", 47), + BdspTimelineContext{1, 1, 2.0, 0, 0, 10, false}, + /*observation_npcs*/ 1, + /*has_timeline*/ true, + }; + static const BdspRngTargetInfo PALKIA{ + "palkia", "Palkia", + legendary_template("palkia", 47), + BdspTimelineContext{1, 1, 2.0, 0, 0, 10, false}, + 1, true, + }; + + static const BdspRngTargetInfo GIRATINA{ + "giratina", "Giratina", + legendary_template("giratina", 47), + BdspTimelineContext{1, 1, 2.0, 2, 0, 10, false}, + 1, true, + }; + + static const BdspRngTargetInfo REGIROCK{ + "regirock", "Regirock", + legendary_template("regirock", 30), + BdspTimelineContext{1, 1, 3.0, 3, 0, 10, false}, + 1, true, + }; + static const BdspRngTargetInfo REGICE{ + "regice", "Regice", + legendary_template("regice", 30), + BdspTimelineContext{1, 1, 3.0, 3, 0, 10, false}, + 1, true, + }; + static const BdspRngTargetInfo REGISTEEL{ + "registeel", "Registeel", + legendary_template("registeel", 30), + BdspTimelineContext{1, 1, 3.0, 3, 0, 10, false}, + 1, true, + }; + + static const BdspRngTargetInfo CRESSELIA{ + "cresselia", "Cresselia", + [](){ + BdspStaticTemplate ret = legendary_template("cresselia", 50); + ret.gender_ratio = 254; // Always female. + ret.roamer = true; + return ret; + }(), + BdspTimelineContext{}, + 1, false, + }; + + static const BdspRngTargetInfo TRAINER_ID{ + "trainer-id", "Trainer ID / SID", + BdspStaticTemplate{}, + BdspTimelineContext{}, + /*observation_npcs*/ 0, + /*has_timeline*/ false, + }; + + switch (target){ + case BdspRngTarget::Starter: return STARTER; + case BdspRngTarget::Dialga: return DIALGA; + case BdspRngTarget::Palkia: return PALKIA; + case BdspRngTarget::Giratina: return GIRATINA; + case BdspRngTarget::Regirock: return REGIROCK; + case BdspRngTarget::Regice: return REGICE; + case BdspRngTarget::Registeel: return REGISTEEL; + case BdspRngTarget::Cresselia: return CRESSELIA; + case BdspRngTarget::TrainerId: return TRAINER_ID; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RNG target."); +} + +const BdspRngTargetInfo& bdsp_rng_target_info(BdspRngTarget target){ + return target_table(target); +} + + +const EnumDropdownDatabase& BdspRngTarget_Database(){ + static const EnumDropdownDatabase database{ + {BdspRngTarget::Starter, "starter", "Starter"}, + {BdspRngTarget::Dialga, "dialga", "Dialga"}, + {BdspRngTarget::Palkia, "palkia", "Palkia"}, + {BdspRngTarget::Giratina, "giratina", "Giratina"}, + {BdspRngTarget::Regirock, "regirock", "Regirock"}, + {BdspRngTarget::Regice, "regice", "Regice"}, + {BdspRngTarget::Registeel, "registeel", "Registeel"}, + {BdspRngTarget::Cresselia, "cresselia", "Cresselia"}, + {BdspRngTarget::TrainerId, "trainer-id", "Trainer ID / SID"}, + }; + return database; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.h new file mode 100644 index 0000000000..f3f557f881 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.h @@ -0,0 +1,52 @@ +/* BDSP RNG Targets + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngTargets_H +#define PokemonAutomation_PokemonBDSP_RngTargets_H + +#include +#include +#include "Common/Cpp/Options/EnumDropdownDatabase.h" +#include "Pokemon/Pokemon_BdspRng.h" +#include "PokemonBDSP_RngTimeline.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +enum class BdspRngTarget{ + Starter, + Dialga, + Palkia, + Giratina, + Regirock, + Regice, + Registeel, + Cresselia, + TrainerId, +}; + + +struct BdspRngTargetInfo{ + const char* slug; + const char* display_name; + Pokemon::BdspStaticTemplate pokemon; + BdspTimelineContext timeline; + uint8_t observation_npcs; + bool has_timeline; +}; + + +const BdspRngTargetInfo& bdsp_rng_target_info(BdspRngTarget target); + +const EnumDropdownDatabase& BdspRngTarget_Database(); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.cpp new file mode 100644 index 0000000000..99d0dfee73 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.cpp @@ -0,0 +1,140 @@ +/* BDSP RNG Timeline + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "PokemonBDSP_BlinkModel.h" +#include "PokemonBDSP_RngTimeline.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +namespace{ + +enum class TimelineEventType : uint8_t{ + NpcTick = 0, + PokemonBlink = 1, +}; + +struct TimelineEvent{ + double time_seconds; + TimelineEventType type; + uint8_t index; + + // Member order is the tie-break + auto operator<=>(const TimelineEvent&) const = default; +}; + +using TimelineQueue = std::priority_queue< + TimelineEvent, std::vector, std::greater +>; + +} + + +static void spend_advances( + BdspTimelineResult& result, Xorshift128& rng, + double now_seconds, uint64_t count +){ + for (uint64_t c = 0; c < count; c++){ + rng.next(); + result.advance_times.emplace_back(now_seconds); + } +} + + +BdspTimelineResult simulate_timeline( + Xorshift128 rng, + const BdspTimelineContext& context, + uint64_t max_advances +){ + BdspTimelineResult result; + double now = 0.0; + + spend_advances(result, rng, now, 1); + if (context.plus_one_on_menu_close){ + spend_advances(result, rng, now, 1); + } + + now += context.white_delay_seconds; + + spend_advances(result, rng, now, context.advance_delay); + + TimelineQueue queue; + for (uint8_t c = 0; c < context.npcs; c++){ + queue.push(TimelineEvent{now + BDSP_NPC_TICK_SECONDS, TimelineEventType::NpcTick, c}); + } + for (uint8_t c = 0; c < context.pokemon_models; c++){ + double interval = bdsp_pokemon_blink_interval(rng.next()); + result.advance_times.emplace_back(now); + queue.push(TimelineEvent{now + interval, TimelineEventType::PokemonBlink, c}); + } + + uint64_t events_handled = 0; + bool second_delay_spent = false; + + while (result.advance_times.size() < max_advances){ + if (queue.empty()){ + result.end_state = rng.state(); + return result; + } + + TimelineEvent event = queue.top(); + queue.pop(); + now = event.time_seconds; + + if (context.advance_delay_2 != 0 + && !second_delay_spent + && events_handled >= context.advance_delay_2_after_events + ){ + spend_advances(result, rng, now, context.advance_delay_2); + second_delay_spent = true; + } + + switch (event.type){ + case TimelineEventType::NpcTick: + rng.next(); + result.advance_times.emplace_back(now); + event.time_seconds += BDSP_NPC_TICK_SECONDS; + break; + + case TimelineEventType::PokemonBlink: + event.time_seconds += bdsp_pokemon_blink_interval(rng.next()); + result.advance_times.emplace_back(now); + break; + } + + queue.push(event); + events_handled++; + } + + result.end_state = rng.state(); + result.reached_target = true; + return result; +} + + +bool time_of_advance(const BdspTimelineResult& result, uint64_t advance, double& seconds){ + if (advance >= result.advance_times.size()){ + return false; + } + seconds = result.advance_times[(size_t)advance]; + return true; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.h new file mode 100644 index 0000000000..17bfffa6c7 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.h @@ -0,0 +1,57 @@ +/* BDSP RNG Timeline + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngTimeline_H +#define PokemonAutomation_PokemonBDSP_RngTimeline_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Pokemon/Pokemon_Xorshift128.h" +#include "PokemonBDSP_BlinkModel.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +struct BdspTimelineContext{ + uint8_t npcs = 1; + uint8_t pokemon_models = 0; + double white_delay_seconds = 0; + uint32_t advance_delay = 0; + uint32_t advance_delay_2 = 0; + uint32_t advance_delay_2_after_events = 10; + bool plus_one_on_menu_close = false; + uint32_t advances_after_accept = 0; +}; + + +struct BdspTimelineResult{ + std::vector advance_times; + Pokemon::Xorshift128State end_state; + bool reached_target = false; + uint64_t advances() const{ return advance_times.size(); } + double duration_seconds() const{ + return advance_times.empty() ? 0.0 : advance_times.back(); + } +}; + + +BdspTimelineResult simulate_timeline( + Pokemon::Xorshift128 rng, + const BdspTimelineContext& context, + uint64_t max_advances +); + +bool time_of_advance(const BdspTimelineResult& result, uint64_t advance, double& seconds); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.cpp new file mode 100644 index 0000000000..e1eb1da88e --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.cpp @@ -0,0 +1,255 @@ +/* BDSP Starter Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h" +#include "PokemonBDSP_StarterNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +const Milliseconds AFTER_BRIEFCASE = 4000ms; +const Milliseconds PRE_BRIEFCASE_DURATION = 18200ms; +const Milliseconds PROMPT_ANIMATION = 1000ms; +const Milliseconds SCHEDULING_SLACK = 100ms; + + +uint8_t starter_cursor_steps(BdspStarter starter){ + switch (starter){ + case BdspStarter::Turtwig: return 0; + case BdspStarter::Chimchar: return 1; + case BdspStarter::Piplup: return 2; + } + return 0; +} + +const char* starter_slug(BdspStarter starter){ + switch (starter){ + case BdspStarter::Turtwig: return "turtwig"; + case BdspStarter::Chimchar: return "chimchar"; + case BdspStarter::Piplup: return "piplup"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown starter."); +} + +// behind the house to the north +void navigate_bedroom_to_skip_spot(Logger& logger, ProControllerContext& context){ + logger.log("Leaving the bedroom for the spot where advances pass quickly."); + pbf_mash_button(context, BUTTON_B, 1000ms); // exit dialogue with the Switch + pbf_wait(context, 1000ms); + pbf_press_dpad(context, DPAD_RIGHT, 1200ms, 1500ms); + pbf_press_dpad(context, DPAD_DOWN, 2300ms, 500ms); + pbf_press_dpad(context, DPAD_LEFT, 1100ms, 1000ms); + pbf_press_dpad(context, DPAD_DOWN, 750ms, 4000ms); + pbf_press_dpad(context, DPAD_LEFT, 850ms, 1000ms); + pbf_press_dpad(context, DPAD_UP, 4100ms, 1000ms); + pbf_press_dpad(context, DPAD_RIGHT, 950ms, 500ms); + context.wait_for_all_requests(); +} + + +void navigate_skip_spot_to_lakefront(Logger& logger, ProControllerContext& context){ + logger.log("Walking from the skip spot to the lakefront."); + pbf_press_dpad(context, DPAD_LEFT, 1350ms, 500ms); + pbf_press_dpad(context, DPAD_UP, 5000ms, 0ms); + + // Clearing the dialogue with Barry + pbf_mash_button(context, BUTTON_B, 5000ms); + pbf_wait(context, 1000ms); + + pbf_press_dpad(context, DPAD_UP, 600ms, 1000ms); + pbf_press_dpad(context, DPAD_LEFT, 8500ms, 1000ms); + pbf_press_dpad(context, DPAD_UP, 1950ms, 1000ms); + context.wait_for_all_requests(); +} + + +void navigate_to_lake_blinks(Logger& logger, ProControllerContext& context){ + logger.log("Walking into the lake, then advancing to the lake blink position."); + pbf_move_left_joystick(context, {0.0, 1.0}, 1600ms, 0ms); + + pbf_wait(context, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 4000ms); + pbf_press_button(context, BUTTON_A, 100ms, 2000ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 2500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 5500ms); + pbf_press_button(context, BUTTON_A, 100ms, 4500ms); + pbf_press_button(context, BUTTON_A, 100ms, 0ms); + context.wait_for_all_requests(); +} + +void navigate_to_pre_briefcase(Logger& logger, ProControllerContext& context){ + logger.log("Advancing to the pre-briefcase position."); + + // total duration equal to PRE_BRIEFCASE_DURATION (above) + pbf_wait(context, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 3500ms); + pbf_press_button(context, BUTTON_A, 100ms, 2000ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 5500ms); + pbf_press_button(context, BUTTON_A, 100ms, 2000ms); + pbf_press_button(context, BUTTON_A, 100ms, 0ms); + context.wait_for_all_requests(); +} + + +const Milliseconds BRIEFCASE_PRESS_TO_STARLY_READY = + 80ms + AFTER_BRIEFCASE + 100ms; +const Milliseconds SELECT_PRESS_TO_CONFIRM_READY = + 80ms + PROMPT_ANIMATION + 100ms + 200ms; + +static Milliseconds starly_press_to_select_ready(BdspStarter starter){ + return 80ms + 5500ms + 100ms + 1200ms + + starter_cursor_steps(starter) * (100ms + 600ms); +} + + +// The whole blind button press sequence +bool issue_starter_sequence( + ProControllerContext& context, + BdspStarter starter, + double starly_seconds, + double select_seconds, + double confirm_seconds, + std::string& failure_reason +){ + auto to_ms = [](double seconds){ + return std::chrono::duration_cast( + std::chrono::duration(seconds) + ); + }; + + // Where the run stands after each fixed stretch, + // measured from the moment the briefcase press is completed + Milliseconds starly_at = to_ms(starly_seconds); + Milliseconds select_at = to_ms(select_seconds); + Milliseconds confirm_at = to_ms(confirm_seconds); + Milliseconds after_dialog = BRIEFCASE_PRESS_TO_STARLY_READY; + Milliseconds after_starly = starly_at + starly_press_to_select_ready(starter); + Milliseconds after_select = select_at + SELECT_PRESS_TO_CONFIRM_READY; + + auto too_tight = [&](const char* what, Milliseconds needed, Milliseconds have){ + failure_reason = std::string(what) + " is scheduled " + + std::to_string((needed - have).count()) + + " ms before the navigation ahead of it can finish"; + return false; + }; + if (starly_at < after_dialog){ + return too_tight("the Starly press", after_dialog, starly_at); + } + if (select_at < after_starly){ + return too_tight("the selecting press", after_starly, select_at); + } + if (confirm_at < after_select){ + return too_tight("the confirming press", after_select, confirm_at); + } + + // The briefcase press + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + + // Past the briefcase dialogue + pbf_wait(context, AFTER_BRIEFCASE); + pbf_press_button(context, BUTTON_A, 100ms, 0ms); + + // The Starly press + pbf_wait(context, starly_at - after_dialog); + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + + // Open the briefcase and hover over the chosen ball + pbf_wait(context, 5500ms); + pbf_press_button(context, BUTTON_A, 100ms, 0ms); + pbf_wait(context, 1200ms); + for (uint8_t c = 0; c < starter_cursor_steps(starter); c++){ + pbf_press_dpad(context, DPAD_RIGHT, 100ms, 600ms); + } + + // The selecting press, then the cursor onto "Yes" + pbf_wait(context, select_at - after_starly); + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + pbf_wait(context, PROMPT_ANIMATION); + pbf_press_dpad(context, DPAD_UP, 100ms, 200ms); + + // The confirming press + pbf_wait(context, confirm_at - after_select); + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + + // battle start + pbf_wait(context, 3000ms); + pbf_press_button(context, BUTTON_A, 100ms, 0ms); + + context.wait_for_all_requests(); + return true; +} + + +// Where the blind run leaves off. Feedback-driven, since nothing past the +// confirming press is timed against the RNG. +bool clear_starter_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.log("Mashing A through the battle."); + EndBattleWatcher battle_over; + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 180s); + }, + {{battle_over}} + ); + if (ret < 0){ + env.log("The battle never ended.", COLOR_RED); + return false; + } + env.log("Battle over."); + return true; +} + + +double seconds_to_move_to_starter(BdspStarter starter){ + return std::chrono::duration_cast>( + starly_press_to_select_ready(starter) - 80ms + ).count(); +} + +// kept as short as the prompt animation allows to avoid extra blinks from the starter +double seconds_from_select_to_confirm(){ + return std::chrono::duration_cast>( + SELECT_PRESS_TO_CONFIRM_READY + SCHEDULING_SLACK + ).count(); +} + + +double seconds_to_pre_briefcase(){ + return std::chrono::duration_cast>( + PRE_BRIEFCASE_DURATION + ).count(); +} + + +double seconds_from_briefcase_to_starly_ready(){ + return std::chrono::duration_cast>( + BRIEFCASE_PRESS_TO_STARLY_READY + ).count(); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.h new file mode 100644 index 0000000000..dacda12b65 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.h @@ -0,0 +1,102 @@ +/* BDSP Starter Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_StarterNavigation_H +#define PokemonAutomation_PokemonBDSP_StarterNavigation_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +enum class BdspStarter{ + Turtwig, + Chimchar, + Piplup, +}; + + +uint8_t starter_cursor_steps(BdspStarter starter); +const char* starter_slug(BdspStarter starter); + + +// Measured over 14 attempts spanning 40k to 734k advances, +/-0.01% +const double BDSP_SKIP_ADVANCES_PER_MINUTE = 19653; + +// Measured over the same attempts, +/-29 +const double BDSP_SKIP_NAVIGATION_ADVANCES = 6902; + +// How far short of the target to stop quickly skipping advances +const double BDSP_SKIP_BUFFER_BASE = 750; +const double BDSP_SKIP_BUFFER_PER_ADVANCE = 0.0002; +inline uint64_t bdsp_skip_buffer(double advances_skipped){ + return (uint64_t)(BDSP_SKIP_BUFFER_BASE + BDSP_SKIP_BUFFER_PER_ADVANCE * advances_skipped); +} + + +const double BDSP_SKIP_RATE_SIGMA = 0.0001; +const double BDSP_SKIP_SCATTER_SIGMA = 67; +inline double bdsp_skip_landing_sigma(double advances_skipped){ + double from_rate = BDSP_SKIP_RATE_SIGMA * advances_skipped; + return std::sqrt(from_rate * from_rate + BDSP_SKIP_SCATTER_SIGMA * BDSP_SKIP_SCATTER_SIGMA); +} + + +inline uint64_t bdsp_lake_advances_needed(double advances_skipped){ + return bdsp_skip_buffer(advances_skipped) + + (uint64_t)(2 * bdsp_skip_landing_sigma(advances_skipped)); +} + + +void navigate_bedroom_to_skip_spot(Logger& logger, ProControllerContext& context); + +void navigate_skip_spot_to_lakefront(Logger& logger, ProControllerContext& context); + + +void navigate_to_lake_blinks(Logger& logger, ProControllerContext& context); + +void navigate_to_pre_briefcase(Logger& logger, ProControllerContext& context); + + +bool issue_starter_sequence( + ProControllerContext& context, + BdspStarter starter, + double starly_seconds, + double select_seconds, + double confirm_seconds, + std::string& failure_reason +); + + +// Mash A until the battle with the wild Starly is over. +bool clear_starter_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +double seconds_to_move_to_starter(BdspStarter starter); + + +double seconds_from_select_to_confirm(); + + +double seconds_from_briefcase_to_starly_ready(); + + +double seconds_to_pre_briefcase(); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp new file mode 100644 index 0000000000..4d6502f8fa --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp @@ -0,0 +1,701 @@ +/* BDSP Starter RNG + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "Pokemon/Pokemon_Notification.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Inference/Rng/PokemonBDSP_BlinkScenes.h" +#include "PokemonBDSP/Inference/Rng/PokemonBDSP_SummaryReader.h" +#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" +#include "PokemonBDSP_BlinkRecovery.h" +#include "PokemonBDSP_RngCalibration.h" +#include "PokemonBDSP_RngExecution.h" +#include "PokemonBDSP_SummaryNavigation.h" +#include "PokemonBDSP_RngTargets.h" +#include "PokemonBDSP_RngTimeline.h" +#include "PokemonBDSP_StarterRng.h" +#include "PokemonBDSP_TargetSelection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +const size_t LAKE_BLINKS_PRESS_RETRIES = 10; + +const double GAP_GUARD_SECONDS = 0.30; + +const uint64_t HIT_SEARCH_RADIUS = 20; +const size_t MAX_SCHEDULES = 8; + +const uint64_t SKIP_ARRIVAL_OVERSHOOT_ALLOWANCE = 200000; + + +const size_t CALIBRATION_MIN_SAMPLES = 3; +const double CALIBRATION_THRESHOLD = 1.0; + + +StarterRng_Descriptor::StarterRng_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:StarterRng", + STRING_POKEMON + " BDSP", "Starter RNG", + "", + "Starter RNG manipulation using blinks.", + PanelQualityStanding::OFFICIAL_BETA, + ProgramControllerClass::StandardController_RequiresPrecision, + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS + ) +{} + +struct StarterRng_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , missed(m_stats["Missed"]) + , hits(m_stats["Hit"]) + , shinies(m_stats["Shiny"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back(Stat("Missed", HIDDEN_IF_ZERO)); + m_display_order.emplace_back(Stat("Hit", HIDDEN_IF_ZERO)); + m_display_order.emplace_back(Stat("Shiny", HIDDEN_IF_ZERO)); + m_display_order.emplace_back(Stat("Errors", HIDDEN_IF_ZERO)); + } + std::atomic& resets; + std::atomic& missed; + std::atomic& hits; + std::atomic& shinies; + std::atomic& errors; +}; +std::unique_ptr StarterRng_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +StarterRng::StarterRng() + : m_aim(CALIBRATION_MIN_SAMPLES, CALIBRATION_THRESHOLD) + , LANGUAGE( + "Game Language:", + summary_nature_languages(), + LockMode::LOCK_WHILE_RUNNING, true + ) + , START_POINT( + "Start point:
" + "Where you have saved your game. Starting from the bedroom allows the possibility to skip advances quickly.", + { + {BdspStartPoint::Lakefront, "lakefront", "Verity Lakefront"}, + {BdspStartPoint::Bedroom, "bedroom", "Bedroom"}, + }, + LockMode::LOCK_WHILE_RUNNING, + BdspStartPoint::Lakefront + ) + , STARTER( + "Starter:
", + { + {BdspStarter::Turtwig, "turtwig", "Turtwig"}, + {BdspStarter::Chimchar, "chimchar", "Chimchar"}, + {BdspStarter::Piplup, "piplup", "Piplup"}, + }, + LockMode::LOCK_WHILE_RUNNING, + BdspStarter::Turtwig + ) + , FILTERS( + "Stop Conditions:
" + "If the " + STRING_POKEMON + " matches any one of these filters, the program will " + "stop.
", + StatsHuntMiscFeatureFlags{ + /*action*/ false, /*shiny*/ true, /*gender*/ true, /*nature*/ true + } + ) + , COLLECTION_DISPLAY(true) + , MAX_RESETS( + "Maximum resets:
" + "Set this to zero to keep going until a shiny is caught.", + LockMode::LOCK_WHILE_RUNNING, + 0, 0, 1000 + ) + , MAX_TARGET_WAIT_MINUTES( + "Wait at most (minutes) for a target:
" + "Time limit for waiting at Verity Lake. Rarer targets will require longer " + "wait times.", + LockMode::LOCK_WHILE_RUNNING, + 30, 5, 1440 + ) + , MAX_SKIP_MINUTES( + "Skip at most (minutes):
" + "Time limit for skipping advances in Twinleaf Town.", + LockMode::LOCK_WHILE_RUNNING, + 30, 5, 1440 + ) + , AUTO_CALIBRATE( + "Correct the timing automatically:
" + "Shift the target advances when several attempts miss.", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , USE_SOUND_DETECTION( + "Use sound detection:", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , TAKE_VIDEO( + "Take Video:
" + "Record a video when the shiny is found.", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_SHINY( + "Shiny Starter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + { + std::vector> defaults; + auto row = std::make_unique(FILTERS); + row->misc.shiny.set(StatsHuntShinyFilter::Shiny); + defaults.emplace_back(std::move(row)); + FILTERS.set_default(std::move(defaults)); + FILTERS.restore_defaults(); + } + + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(PLAYER_MODEL); + PA_ADD_OPTION(START_POINT); + PA_ADD_OPTION(STARTER); + PA_ADD_OPTION(FILTERS); + PA_ADD_OPTION(COLLECTION_DISPLAY); + PA_ADD_OPTION(STATE_DISPLAY); + PA_ADD_OPTION(TARGET_DISPLAY); + PA_ADD_OPTION(MAX_RESETS); + PA_ADD_OPTION(MAX_TARGET_WAIT_MINUTES); + PA_ADD_OPTION(MAX_SKIP_MINUTES); + PA_ADD_OPTION(AUTO_CALIBRATE); + PA_ADD_OPTION(USE_SOUND_DETECTION); + PA_ADD_OPTION(TAKE_VIDEO); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); + + START_POINT.add_listener(*this); + StarterRng::on_config_value_changed(this); +} + + +void StarterRng::on_config_value_changed(void*){ + MAX_SKIP_MINUTES.set_visibility( + START_POINT == BdspStartPoint::Bedroom + ? ConfigOptionState::ENABLED + : ConfigOptionState::HIDDEN + ); +} + + +bool StarterRng::wanted( + const BdspRngFilterSnapshot& filters, const BdspPokemonResult& pokemon +){ + auto exactly = [](uint8_t iv){ return IvRange{(int8_t)iv, (int8_t)iv}; }; + IvRanges ivs; + ivs.hp = exactly(pokemon.ivs.hp); + ivs.attack = exactly(pokemon.ivs.attack); + ivs.defense = exactly(pokemon.ivs.defense); + ivs.spatk = exactly(pokemon.ivs.spatk); + ivs.spdef = exactly(pokemon.ivs.spdef); + ivs.speed = exactly(pokemon.ivs.speed); + + StatsHuntGenderFilter gender = StatsHuntGenderFilter::Genderless; + switch (pokemon.gender){ + case BdspGender::Male: gender = StatsHuntGenderFilter::Male; break; + case BdspGender::Female: gender = StatsHuntGenderFilter::Female; break; + default: break; + } + + return filters.get_action( + pokemon.shiny != BdspShiny::None, + gender, + bdsp_nature_to_checker_value(pokemon.nature), + pokemon.height, + ivs + ) != StatsHuntAction::Discard; +} + + +BdspSkipResult StarterRng::skip_advances_from_bedroom( + SingleSwitchProgramEnvironment& env, ProControllerContext& context +){ + BdspSkipResult skip; + const BdspRngTargetInfo& target_info = bdsp_rng_target_info(BdspRngTarget::Starter); + + // Expected wait duration at the lake after a long skip + double longest_skip = MAX_SKIP_MINUTES * BDSP_SKIP_ADVANCES_PER_MINUTE; + double lake_minutes = bdsp_lake_advances_needed(longest_skip) + * BDSP_NPC_TICK_SECONDS / (target_info.observation_npcs * 60.0); + if (lake_minutes > MAX_TARGET_WAIT_MINUTES){ + throw UserSetupError(env.logger(), + "A skip of up to " + std::to_string((uint16_t)MAX_SKIP_MINUTES) + + " minutes can leave up to " + + tostr_fixed(lake_minutes, 1) + " minutes of waiting at the lake, but the target " + "wait is capped at " + std::to_string((uint16_t)MAX_TARGET_WAIT_MINUTES) + + ". Raise the target wait to at least " + + std::to_string((uint16_t)std::ceil(lake_minutes)) + + " minutes, or lower the skip limit." + ); + } + + env.log("Starting in the bedroom."); + pbf_press_button(context, BUTTON_A, 100ms, 2000ms); // open dialogue box + context.wait_for_all_requests(); + + std::vector setups = bedroom_eye_templates(PLAYER_MODEL.model_number()); + std::vector eyes = load_eye_templates(setups); + + std::vector> watchers; + std::vector callbacks; + make_blink_watchers(setups, eyes, watchers, callbacks); + + BlinkRecoveryConfig bedroom_config; + bedroom_config.npcs = 1; + + BlinkRecovery recovery = recover_state_from_blinks( + env, context, watchers, callbacks, COLLECTION_DISPLAY, bedroom_config + ); + if (!recovery.success){ + skip.failure_reason = "could not determine the RNG state in the bedroom: " + + recovery.failure_reason; + return skip; + } + skip.state = recovery.state; + env.log("Bedroom RNG state: " + recovery.state.to_string(), COLOR_BLUE); + STATE_DISPLAY.set_state(recovery.state, recovery.clock.anchor_advance); + STATE_DISPLAY.set_confidence_unique(); + + // take into account remaning navigation time and the desired buffer + uint64_t soonest = recovery.clock.advance_at(current_time()) + + (uint64_t)BDSP_SKIP_NAVIGATION_ADVANCES + bdsp_skip_buffer(0); + uint64_t furthest = soonest + + (uint64_t)(MAX_SKIP_MINUTES * BDSP_SKIP_ADVANCES_PER_MINUTE); + + BdspStaticSearcher searcher(recovery.state, target_info.pokemon, 0); + BdspRngFilterSnapshot filters = FILTERS.make_snapshot(); + std::vector hits = searcher.scan( + soonest, furthest, + [&filters](const BdspPokemonResult& result){ return wanted(filters, result); }, + true, &context + ); + if (hits.empty()){ + skip.failure_reason = "no target within " + std::to_string((uint16_t)MAX_SKIP_MINUTES) + + " minutes of skipping"; + return skip; + } + const BdspRngHit& hit = hits[0]; + skip.target_advance = hit.advances; + TARGET_DISPLAY.set_target(hit.result, hit.advances); + + uint64_t start = recovery.clock.advance_at(current_time()); + + // The buffer depends on how far the skip runs, so size it from the raw distance. + double raw_skip = (double)hit.advances - (double)start - BDSP_SKIP_NAVIGATION_ADVANCES; + uint64_t buffer = bdsp_skip_buffer(raw_skip); + double to_skip = raw_skip - (double)buffer; + if (to_skip < 0){ + to_skip = 0; + } + double wait_seconds = to_skip * 60 / BDSP_SKIP_ADVANCES_PER_MINUTE; + skip.buffer = buffer; + + env.log("Target advance " + std::to_string(hit.advances) + ": " + hit.result.to_string(), + COLOR_BLUE); + env.log("Skipping " + std::to_string((uint64_t)to_skip) + " advances from " + + std::to_string(start) + ", which is " + tostr_fixed(wait_seconds, 1) + + "s on the spot, stopping " + std::to_string(buffer) + + " advances short to avoid overshooting.", COLOR_BLUE); + + navigate_bedroom_to_skip_spot(env.logger(), context); + + + WallClock leave_at = current_time() + std::chrono::duration_cast( + std::chrono::duration(wait_seconds) + ); + + while (current_time() + 2s < leave_at){ + WallClock now = current_time(); + WallClock until = std::min(leave_at - 2s, now + 180s); + pbf_wait(context, std::chrono::duration_cast(until - now)); + context.wait_for_all_requests(); + } + WallClock now = current_time(); + if (now < leave_at){ + pbf_wait(context, std::chrono::duration_cast(leave_at - now)); + context.wait_for_all_requests(); + } + + navigate_skip_spot_to_lakefront(env.logger(), context); + skip.success = true; + return skip; +} + + +void StarterRng::report_skip_arrival( + SingleSwitchProgramEnvironment& env, + const BdspSkipResult& skip, + const BlinkRecovery& arrival +) const{ + // Generous enough to catch an overshoot, and a match is unique anyway. + uint64_t search_max = skip.target_advance + SKIP_ARRIVAL_OVERSHOOT_ALLOWANCE; + uint64_t travelled = 0; + if (!advances_between(skip.state, arrival.state, search_max, travelled)){ + env.log( + "Could not place the lake state against the bedroom one, so the skip " + "cannot be measured this attempt.", + COLOR_ORANGE + ); + return; + } + + uint64_t here = travelled + arrival.clock.advance_at(current_time()); + int64_t short_by = (int64_t)skip.target_advance - (int64_t)here; + env.log( + "Skip landed on advance " + std::to_string(here) + " of " + + std::to_string(skip.target_advance) + ": " + + (short_by >= 0 + ? std::to_string(short_by) + " short, aimed for " + std::to_string(skip.buffer) + : "OVERSHOT by " + std::to_string(-short_by)), + short_by >= 0 ? COLOR_BLUE : COLOR_ORANGE + ); +} + + +BdspAttemptOutcome StarterRng::run_attempt( + SingleSwitchProgramEnvironment& env, ProControllerContext& context +){ + StarterRng_Descriptor::Stats& stats = env.current_stats(); + COLLECTION_DISPLAY.reset(); + STATE_DISPLAY.reset(); + TARGET_DISPLAY.reset(); + + auto abandon = [&](const std::string& reason) -> BdspAttemptOutcome{ + env.log("Abandoning this attempt: " + reason, COLOR_ORANGE); + TARGET_DISPLAY.set_note(reason); + return BdspAttemptOutcome::Abandoned; + }; + + const BdspRngTargetInfo& target_info = bdsp_rng_target_info(BdspRngTarget::Starter); + + BdspSkipResult skip; + if (START_POINT == BdspStartPoint::Bedroom){ + skip = skip_advances_from_bedroom(env, context); + if (!skip.success){ + return abandon(skip.failure_reason); + } + } + + navigate_to_lake_blinks(env.logger(), context); + + std::vector setups = lake_eye_templates(PLAYER_MODEL.model_number()); + std::vector eyes = load_eye_templates(setups); + + // The rival's dialogue box being up is what says the pair have stopped walking. + ShortDialogDetector dialog; + BlinkSceneConfig scene; + scene.frame_filter = [&dialog](const ImageViewRGB32& frame){ return dialog.detect(frame); }; + scene.press_retries = LAKE_BLINKS_PRESS_RETRIES; + + if (!wait_for_blink_scene(env, context, setups, eyes, scene, "Lake blinks")){ + return abandon("never reached the lake blink position"); + } + + // Now blink watchers can be created safely + std::vector> watchers; + std::vector callbacks; + make_blink_watchers(setups, eyes, watchers, callbacks); + + BlinkRecoveryConfig blink_config; + blink_config.npcs = target_info.observation_npcs; + + BlinkRecovery recovery = recover_state_from_blinks( + env, context, watchers, callbacks, COLLECTION_DISPLAY, blink_config + ); + if (!recovery.success){ + return abandon("could not determine the RNG state: " + recovery.failure_reason); + } + + uint64_t seed0 = 0; + uint64_t seed1 = 0; + xorshift128_state_to_seed_pair(recovery.state, seed0, seed1); + env.log("RNG state: " + recovery.state.to_string(), COLOR_BLUE); + env.log("PokeFinder seeds: " + tostr_hex_padded(16, seed0) + + " " + tostr_hex_padded(16, seed1), COLOR_BLUE); + env.log("Tick fitted at " + tostr_default(recovery.clock.tick_seconds) + "s over " + + std::to_string(recovery.events) + " rolls.", COLOR_BLUE); + env.log("Anchored on advance " + std::to_string(recovery.clock.anchor_advance) + + "; now at advance " + std::to_string(recovery.clock.advance_at(current_time())) + + ".", COLOR_BLUE); + STATE_DISPLAY.set_state(recovery.state, recovery.clock.anchor_advance); + STATE_DISPLAY.set_confidence_unique(); + + if (skip.success){ + report_skip_arrival(env, skip, recovery); + } + + + const BdspTimelineContext& timeline = target_info.timeline; + + NavigationTimings timings; + timings.ready_seconds = seconds_from_briefcase_to_starly_ready(); + timings.move_seconds = seconds_to_move_to_starter(STARTER) + 0.25; // small buffer + timings.prompt_seconds = seconds_from_select_to_confirm(); + timings.guard_seconds = GAP_GUARD_SECONDS; + + BdspStaticSearcher searcher(recovery.state, target_info.pokemon, 0); + + // A press cannot be sooner than the walk to the pre-briefcase position takes + double lead_seconds = seconds_to_pre_briefcase() + 15; + uint64_t lead_advances = (uint64_t)( + lead_seconds * recovery.clock.npcs / recovery.clock.tick_seconds + ) + 1; + + TargetSearchRequest search; + search.state = recovery.state; + search.timeline = timeline; + search.timings = timings; + search.pokemon = target_info.pokemon; + search.npcs = recovery.clock.npcs; + search.tick_seconds = recovery.clock.tick_seconds; + search.bias = m_aim.bias(); + search.first_press = recovery.clock.advance_at(current_time()) + lead_advances; + search.window_advances = (uint64_t)( + (double)MAX_TARGET_WAIT_MINUTES * 60 * recovery.clock.npcs / recovery.clock.tick_seconds + ); + search.max_schedules = MAX_SCHEDULES; + BdspRngFilterSnapshot filters = FILTERS.make_snapshot(); + search.wanted = [&filters](const BdspPokemonResult& result){ return wanted(filters, result); }; + + TargetSelectionResult selection = select_target(search); + + if (selection.matches_found != 0){ + env.log( + std::to_string(selection.matches_found) + " matching advance(s) in " + + std::to_string(selection.advances_scanned), + COLOR_BLUE + ); + } + if (!selection.success){ + return abandon(selection.failure_reason); + } + + uint64_t press_advance = selection.press_advance; + uint64_t target_advance = selection.target_advance; + const PressSchedule& schedule = selection.schedule; + const BdspPokemonResult& target = selection.target; + + double wait_seconds = std::chrono::duration_cast>( + recovery.clock.time_of_advance(press_advance) - current_time() + ).count(); + env.log("Target advance " + std::to_string(target_advance) + ": " + target.to_string(), + COLOR_BLUE); + env.log("Pressing at advance " + std::to_string(press_advance) + ", in " + + tostr_default(wait_seconds) + "s.", COLOR_BLUE); + env.log("Schedule spans " + std::to_string(schedule.span) + " advances, confirming after " + + std::to_string(schedule.blinks_before_confirm) + " Starly blink(s), " + + tostr_default(schedule.confirm_seconds) + "s in" + + m_aim.describe_correction() + ".", COLOR_BLUE); + TARGET_DISPLAY.set_target(target, target_advance); + + hold_and_reanchor( + env, context, watchers, callbacks, recovery, blink_config, + press_advance, lead_seconds, STATE_DISPLAY + ); + + navigate_to_pre_briefcase(env.logger(), context); + + // FIRST PRESS, centred in the advance rather than aimed right at the beginning of it + WallClock briefcase_time = recovery.clock.middle_of_advance(press_advance); + + while (current_time() + 3s < briefcase_time){ + STATE_DISPLAY.set_advances(recovery.clock.advance_at(current_time())); + pbf_wait(context, 1000ms); + context.wait_for_all_requests(); + } + + STATE_DISPLAY.set_advances(press_advance); + + env.log("Timeline starts at advance " + std::to_string(press_advance) + + ". Blind from here: Starly press at " + tostr_default(schedule.starly_seconds) + + "s, selecting at " + tostr_default(schedule.select_seconds) + + "s, confirming at " + tostr_default(schedule.confirm_seconds) + + "s, on advance " + std::to_string(target_advance - timeline.advances_after_accept) + + ".", COLOR_BLUE); + + std::string sequence_failure; + if (!wait_until_moment(context, env.logger(), briefcase_time)){ + return abandon("the briefcase press moment passed before it could be sent"); + } + if (!issue_starter_sequence( + context, STARTER, + schedule.starly_seconds, schedule.select_seconds, schedule.confirm_seconds, + sequence_failure + )){ + return abandon(sequence_failure); + } + env.log("Timeline finished; the starter should be in hand.", COLOR_BLUE); + + STATE_DISPLAY.set_advances(target_advance); + + + // Check what was actually obtained. + DoublesShinyDetection wild; + ShinyDetectionResult own; + detect_shiny_battle( + env, env.console, context, + wild, own, + NOTIFICATION_ERROR_RECOVERABLE, + YOUR_POKEMON, + 30s, + USE_SOUND_DETECTION + ); + bool shiny_known = own.shiny_type != ShinyType::UNKNOWN; + + if (is_likely_shiny(own.shiny_type)){ + stats.shinies++; + send_program_notification( + env, NOTIFICATION_SHINY, + COLOR_STAR_SHINY, "Shiny Starter", + {{"Advance", std::to_string(target_advance)}, {"Details", target.to_string()}}, + "", own.get_best_screenshot() + ); + if (TAKE_VIDEO){ + pbf_wait(context, 5000ms); + pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 5000ms); + context.wait_for_all_requests(); + } + return BdspAttemptOutcome::Hit; + } + + BdspObservedStarter observed; + if (!clear_starter_battle(env, context) + || !read_observed_pokemon( + env, context, LANGUAGE, starter_base_stats(STARTER), 5, false, shiny_known, observed + ) + ){ + stats.errors++; + return BdspAttemptOutcome::Unverifiable; + } + + BdspHitIdentification hit = identify_hit_advance( + recovery.state, target_info.pokemon, target_advance, HIT_SEARCH_RADIUS, observed + ); + if (!hit.success){ + env.log("Could not tell which advance that was: " + hit.failure_reason, COLOR_ORANGE); + if (consistent_with(target, observed)){ + env.log("What was read matches the target, so it counts as a hit.", COLOR_BLUE); + stats.hits++; + return BdspAttemptOutcome::Hit; + } + env.log("What was read is not the target, so it counts as a miss.", COLOR_ORANGE); + stats.missed++; + return BdspAttemptOutcome::Missed; + } + if (m_aim.record_offset(env.logger(), hit.offset, AUTO_CALIBRATE)){ + TARGET_DISPLAY.set_correction(m_aim.bias()); + } + + if (hit.offset == 0){ + env.log("Landed on advance " + std::to_string(target_advance) + ", as aimed.", + COLOR_BLUE); + stats.hits++; + return BdspAttemptOutcome::Hit; + } + + env.log( + "Landed on advance " + std::to_string(hit.advance) + " instead of " + + std::to_string(target_advance) + " — " + + (hit.offset > 0 ? "late by " : "early by ") + + std::to_string(hit.offset > 0 ? hit.offset : -hit.offset) + " advance(s).", + COLOR_ORANGE + ); + stats.missed++; + + if (wanted(filters, searcher.generate(hit.advance))){ + env.log("It passes the filter anyway, so this one will do. Stopping.", COLOR_BLUE); + return BdspAttemptOutcome::Hit; + } + return BdspAttemptOutcome::Missed; +} + + +void StarterRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + StarterRng_Descriptor::Stats& stats = env.current_stats(); + + require_player(env.console, context, BUTTON_B); + + m_aim.reset(); + + bool reset = false; + uint64_t resets = 0; + while (true){ + if (MAX_RESETS != 0 && resets >= MAX_RESETS){ + env.log("Reached the reset limit.", COLOR_ORANGE); + break; + } + resets++; + + bool started = true; + if (reset){ + go_home(env.console, context); + if (!reset_game_from_home( + env, env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + )){ + started = false; + } + } + + bool done = false; + if (started){ + reset = true; + done = run_attempt(env, context) == BdspAttemptOutcome::Hit; + } + + stats.resets++; + env.update_stats(); + + if (done){ + break; + } + } + + env.update_stats(); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h new file mode 100644 index 0000000000..7ac087c5e2 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h @@ -0,0 +1,127 @@ +/* BDSP Starter RNG + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_StarterRng_H +#define PokemonAutomation_PokemonBDSP_StarterRng_H + +#include +#include +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Pokemon_BdspRng.h" +#include "Pokemon/Pokemon_NatureChecker.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" +#include "PokemonBDSP/Options/PokemonBDSP_PlayerModelOption.h" +#include "PokemonBDSP/Options/PokemonBDSP_RngFilter.h" +#include "PokemonBDSP_BlinkRecovery.h" +#include "PokemonBDSP_RngAim.h" +#include "PokemonBDSP_RngDisplays.h" +#include "PokemonBDSP_StarterNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +enum class BdspStartPoint{ + Lakefront, + Bedroom, +}; + + +struct BdspSkipResult{ + bool success = false; + Pokemon::Xorshift128State state; + uint64_t target_advance = 0; + uint64_t buffer = 0; + std::string failure_reason; +}; + + +enum class BdspAttemptOutcome{ + Abandoned, + Missed, + Hit, + Unverifiable, +}; + + +class StarterRng_Descriptor : public SingleSwitchProgramDescriptor{ +public: + StarterRng_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class StarterRng : public SingleSwitchProgramInstance, public ConfigOption::Listener{ +public: + using Descriptor = StarterRng_Descriptor; + StarterRng(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + virtual void on_config_value_changed(void* object) override; + + BdspAttemptOutcome run_attempt(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + // Takes a snapshot rather than the table: the table clones itself on every query, + // which a scan over millions of advances cannot afford. + static bool wanted( + const BdspRngFilterSnapshot& filters, const Pokemon::BdspPokemonResult& pokemon + ); + + BdspSkipResult skip_advances_from_bedroom( + SingleSwitchProgramEnvironment& env, ProControllerContext& context + ); + + void report_skip_arrival( + SingleSwitchProgramEnvironment& env, + const BdspSkipResult& skip, + const BlinkRecovery& arrival + ) const; + +private: + RngAim m_aim; + +private: + OCR::LanguageOCROption LANGUAGE; + PlayerModelOption PLAYER_MODEL; + EnumDropdownOption START_POINT; + EnumDropdownOption STARTER; + + BdspRngFilterTable FILTERS; + + BlinkCollectionDisplay COLLECTION_DISPLAY; + RngStateDisplay STATE_DISPLAY; + RngTargetDisplay TARGET_DISPLAY; + + SimpleIntegerOption MAX_RESETS; + SimpleIntegerOption MAX_TARGET_WAIT_MINUTES; + SimpleIntegerOption MAX_SKIP_MINUTES; + + BooleanCheckBoxOption AUTO_CALIBRATE; + + BooleanCheckBoxOption USE_SOUND_DETECTION; + BooleanCheckBoxOption TAKE_VIDEO; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp new file mode 100644 index 0000000000..096b854679 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp @@ -0,0 +1,165 @@ +/* BDSP Summary Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_NatureChecker.h" +#include "PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h" +#include "PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h" +#include "PokemonBDSP/Inference/Rng/PokemonBDSP_SummaryReader.h" +#include "PokemonBDSP_SummaryNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; + + +const size_t MENU_ATTEMPTS = 3; + + +bool open_menu(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.log("Mashing B through dialogue, trying the menu as we go."); + MenuWatcher menu(COLOR_RED, true); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + for (size_t c = 0; c < 40; c++){ + pbf_press_button(context, BUTTON_B, 100ms, 700ms); + pbf_press_button(context, BUTTON_B, 100ms, 700ms); + pbf_press_button(context, BUTTON_X, 100ms, 1200ms); + } + }, + {{menu}} + ); + if (ret < 0){ + env.log("Never got back to the overworld menu.", COLOR_RED); + return false; + } + env.log("Menu is open."); + return true; +} + + +bool open_starter_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + for (size_t attempt = 0; attempt < MENU_ATTEMPTS; attempt++){ + pbf_wait(context, 1200ms); + context.wait_for_all_requests(); + + env.log("Moving one entry left, then opening it."); + pbf_press_dpad(context, DPAD_LEFT, 160ms, 840ms); + pbf_press_button(context, BUTTON_A, 160ms, 1500ms); + + pbf_press_button(context, BUTTON_A, 100ms, 1000ms); + context.wait_for_all_requests(); + + SelectionArrowFinder arrow(env.console, {0.360, 0.110, 0.200, 0.290}, COLOR_RED); + if (wait_until(env.console, context, 10s, {{arrow}}) >= 0){ + break; + } + if (attempt + 1 >= MENU_ATTEMPTS){ + env.log("Never reached the party from the menu.", COLOR_RED); + return false; + } + env.log("That was not the party. Backing out and trying again.", COLOR_ORANGE); + bool back_at_menu = false; + for (size_t c = 0; c < 5 && !back_at_menu; c++){ + pbf_press_button(context, BUTTON_B, 160ms, 1000ms); + context.wait_for_all_requests(); + MenuWatcher menu(COLOR_RED, true); + back_at_menu = wait_until(env.console, context, 2s, {{menu}}) >= 0; + } + if (!back_at_menu){ + env.log("Backing out never returned to the menu.", COLOR_RED); + return false; + } + } + + env.log("Opening the summary."); + pbf_press_button(context, BUTTON_A, 100ms, 2000ms); + context.wait_for_all_requests(); + + env.log("Moving to the Trainer Memo page."); + pbf_press_dpad(context, DPAD_RIGHT, 100ms, 1500ms); + context.wait_for_all_requests(); + return true; +} + + +bool navigate_to_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + return open_menu(env, context) + && open_starter_summary(env, context); +} + + +bool read_observed_pokemon( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + Language language, + const Pokemon::BaseStats& base_stats, + uint8_t level, + bool shiny, + bool shiny_known, + BdspObservedStarter& observed +){ + if (!navigate_to_summary(env, context)){ + env.log("Could not reach the summary, so this attempt says nothing about timing.", + COLOR_ORANGE); + return false; + } + + SummaryReader reader; + + // 2nd page: nature and gender + { + VideoSnapshot memo = env.console.video().snapshot(); + observed.nature = reader.read_nature(env.logger(), language, memo); + Pokemon::BdspGender gender = reader.read_gender(env.logger(), memo); + observed.gender = gender; + observed.gender_known = gender != Pokemon::BdspGender::Genderless; + } + // 3rd page: stats + { + pbf_press_dpad(context, DPAD_RIGHT, 100ms, 1500ms); + context.wait_for_all_requests(); + VideoSnapshot skills = env.console.video().snapshot(); + observed.stats = reader.read_stats(env.logger(), skills); + } + observed.base_stats = base_stats; + observed.level = level; + observed.shiny = shiny; + observed.shiny_known = shiny_known; + + auto stat = [](int16_t value){ + return value < 0 ? std::string("?") : std::to_string(value); + }; + bool nature_read = observed.nature != Pokemon::NatureCheckerValue::UnableToDetect; + env.log( + "Read from the summary: nature " + + (nature_read + ? Pokemon::NATURE_CHECKER_VALUE_STRINGS().get_string(observed.nature) + : std::string("UNREAD")) + + ", gender " + + (observed.gender_known + ? std::string(Pokemon::bdsp_gender_name(observed.gender)) + : std::string("UNREAD")) + + ", stats " + stat(observed.stats.hp) + "/" + stat(observed.stats.attack) + + "/" + stat(observed.stats.defense) + "/" + stat(observed.stats.spatk) + + "/" + stat(observed.stats.spdef) + "/" + stat(observed.stats.speed) + ".", + nature_read && observed.gender_known ? COLOR_BLUE : COLOR_ORANGE + ); + return true; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h new file mode 100644 index 0000000000..34bf6d6307 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h @@ -0,0 +1,41 @@ +/* BDSP Summary Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_SummaryNavigation_H +#define PokemonAutomation_PokemonBDSP_SummaryNavigation_H + +#include "CommonFramework/Language.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Pokemon_StatsCalculation.h" +#include "PokemonBDSP_RngCalibration.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +bool open_menu(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +bool open_starter_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +bool navigate_to_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +bool read_observed_pokemon( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + Language language, + const Pokemon::BaseStats& base_stats, + uint8_t level, + bool shiny, + bool shiny_known, + BdspObservedStarter& observed +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.cpp new file mode 100644 index 0000000000..39420aa7fc --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.cpp @@ -0,0 +1,122 @@ +/* BDSP Target Selection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "PokemonBDSP_RngAim.h" +#include "PokemonBDSP_TargetSelection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +TargetSelectionResult select_target(const TargetSearchRequest& request){ + TargetSelectionResult result; + + if (!request.wanted){ + result.failure_reason = "No filter was supplied, so nothing can be searched for."; + return result; + } + + BdspStaticSearcher searcher(request.state, request.pokemon, 0); + + // How many advances the scene can spend between the press and the generation + uint64_t lowest_span = 0; + uint64_t highest_span = 0; + schedule_span_bounds(request.timeline, request.max_schedules, lowest_span, highest_span); + + int64_t last_press = (int64_t)(request.first_press + request.window_advances); + + // One sweep, walking the RNG forward rather than jumping to each advance. + uint64_t scan_from = (uint64_t)std::max( + 0, (int64_t)request.first_press + (int64_t)lowest_span + request.bias + ); + uint64_t scan_to = (uint64_t)std::max( + 0, last_press + (int64_t)highest_span + request.bias + ); + std::map wanted_targets; + for (const BdspRngHit& hit : searcher.scan(scan_from, scan_to, request.wanted)){ + wanted_targets.emplace(hit.advances, hit.result); + } + + result.advances_scanned = scan_to - scan_from + 1; + result.matches_found = wanted_targets.size(); + + if (wanted_targets.empty()){ + result.failure_reason = "no matches found within " + + std::to_string(result.advances_scanned) + " advances."; + return result; + } + + uint8_t press_step = request.npcs == 0 ? 1 : request.npcs; + std::set candidate_presses; + for (const auto& item : wanted_targets){ + int64_t lowest_press = std::max( + press_for_advance(item.first, highest_span, request.bias), + (int64_t)request.first_press + ); + int64_t highest_press = std::min( + press_for_advance(item.first, lowest_span, request.bias), + last_press + ); + for (int64_t press = lowest_press; press <= highest_press; press++){ + if (press % press_step != 0){ + continue; + } + candidate_presses.insert((uint64_t)press); + } + } + + double seconds_per_advance = request.tick_seconds / (double)press_step; + bool found = false; + double best_seconds = 0; + for (uint64_t press : candidate_presses){ + double press_at_seconds = (double)(press - request.first_press) * seconds_per_advance; + if (found && press_at_seconds >= best_seconds){ + break; + } + for (const PressSchedule& option : schedule_presses( + request.state, request.timeline, request.timings, press, request.max_schedules + )){ + auto hit = wanted_targets.find(aimed_advance(press, option.span, request.bias)); + if (hit == wanted_targets.end()){ + continue; + } + if (!found || press_at_seconds + option.confirm_seconds < best_seconds){ + found = true; + best_seconds = press_at_seconds + option.confirm_seconds; + result.press_advance = press; + result.schedule = option; + result.target = hit->second; + } + // the first hit is the best this press has to offer + break; + } + } + if (!found){ + // Around one advance in fifty is unreachable due to rapid blinks + result.failure_reason = std::to_string(wanted_targets.size()) + + " matching advance(s) in range, but none reachable"; + return result; + } + + result.target_advance = aimed_advance( + result.press_advance, result.schedule.span, request.bias + ); + result.success = true; + return result; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.h new file mode 100644 index 0000000000..7c1fb044d0 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.h @@ -0,0 +1,57 @@ +/* BDSP Target Selection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_TargetSelection_H +#define PokemonAutomation_PokemonBDSP_TargetSelection_H + +#include +#include +#include +#include +#include "Pokemon/Pokemon_BdspRng.h" +#include "Pokemon/Pokemon_Xorshift128.h" +#include "PokemonBDSP_RngExecution.h" +#include "PokemonBDSP_RngTimeline.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +struct TargetSearchRequest{ + Pokemon::Xorshift128State state; + BdspTimelineContext timeline; + NavigationTimings timings; + Pokemon::BdspStaticTemplate pokemon; + uint8_t npcs = 1; + double tick_seconds = BDSP_NPC_TICK_SECONDS; + int64_t bias = 0; + uint64_t first_press = 0; + uint64_t window_advances = 0; + size_t max_schedules = 8; + std::function wanted; +}; + + +struct TargetSelectionResult{ + bool success = false; + uint64_t press_advance = 0; + uint64_t target_advance = 0; + PressSchedule schedule; + Pokemon::BdspPokemonResult target; + size_t matches_found = 0; + uint64_t advances_scanned = 0; + std::string failure_reason; +}; + + +TargetSelectionResult select_target(const TargetSearchRequest& request); + + +} +} +} +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 2b78fa0d2f..93f0bcb3ca 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1891,6 +1891,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Options/PokemonBDSP_LearnMove.h Source/PokemonBDSP/Options/PokemonBDSP_PlayerModelOption.cpp Source/PokemonBDSP/Options/PokemonBDSP_PlayerModelOption.h + Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp + Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.cpp Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h Source/PokemonBDSP/PokemonBDSP_Panels.cpp @@ -1961,12 +1963,30 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_BlinkRecovery.h Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_IntroSeedFinder.cpp Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_IntroSeedFinder.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.h Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngDisplays.cpp Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngDisplays.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StateReidentifier.cpp Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StateReidentifier.h Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StateSolver.cpp Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StateSolver.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.h Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.cpp Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.h Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.cpp From 874c461438ba1e778d227b225dd57562f3ffa448 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:19:13 -0800 Subject: [PATCH 06/20] BDSP Starter RNG: make the attempt loop callable Extract the Starter RNG attempt and reset loop out of StarterRng::program() into PokemonBDSP_StarterRngAttempts (run_starter_rng_attempts / run_starter_rng_attempt / resolve_starter_rng_step), parameterized by StarterRngSettings and StarterRngAttemptIO and returning StarterRngRunResult. Add finish_battle_on_shiny and close_summary_after_read options (with close_starter_summary in SummaryNavigation) so AutoStory can continue directly from Lake Verity or Verity Lakefront, and add unit tests for per-starter tables, bedroom skip buffer/landing math, aim calibration, and attempt loop outcome transitions. --- .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 2 + .../PokemonBDSP_StarterRng.cpp | 549 +------------ .../RngManipulation/PokemonBDSP_StarterRng.h | 53 +- .../PokemonBDSP_StarterRngAttempts.cpp | 744 ++++++++++++++++++ .../PokemonBDSP_StarterRngAttempts.h | 209 +++++ .../PokemonBDSP_StarterRng_Tests.cpp | 305 +++++++ .../PokemonBDSP_StarterRng_Tests.h | 23 + .../PokemonBDSP_SummaryNavigation.cpp | 20 + .../PokemonBDSP_SummaryNavigation.h | 3 + SerialPrograms/cmake/SourceFiles.cmake | 4 + 10 files changed, 1345 insertions(+), 567 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index afac33d987..30d00f6b2d 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -18,6 +18,7 @@ #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h" +#include "Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h" #include "PokemonBDSP_Tests.h" namespace PokemonAutomation{ @@ -40,6 +41,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_StoryData(database); add_tests_AutoStory_Walk(database); add_tests_AutoStory_PlannedRoute(database); + add_tests_StarterRng(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp index 4d6502f8fa..1031be4513 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp @@ -4,34 +4,15 @@ * */ -#include -#include #include #include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" #include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "Pokemon/Pokemon_Notification.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" #include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" -#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" -#include "PokemonBDSP/Inference/Rng/PokemonBDSP_BlinkScenes.h" #include "PokemonBDSP/Inference/Rng/PokemonBDSP_SummaryReader.h" -#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" -#include "PokemonBDSP_BlinkRecovery.h" -#include "PokemonBDSP_RngCalibration.h" -#include "PokemonBDSP_RngExecution.h" -#include "PokemonBDSP_SummaryNavigation.h" -#include "PokemonBDSP_RngTargets.h" -#include "PokemonBDSP_RngTimeline.h" #include "PokemonBDSP_StarterRng.h" -#include "PokemonBDSP_TargetSelection.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -40,16 +21,6 @@ namespace PokemonBDSP{ using namespace Pokemon; -const size_t LAKE_BLINKS_PRESS_RETRIES = 10; - -const double GAP_GUARD_SECONDS = 0.30; - -const uint64_t HIT_SEARCH_RADIUS = 20; -const size_t MAX_SCHEDULES = 8; - -const uint64_t SKIP_ARRIVAL_OVERSHOOT_ALLOWANCE = 200000; - - const size_t CALIBRATION_MIN_SAMPLES = 3; const double CALIBRATION_THRESHOLD = 1.0; @@ -67,26 +38,6 @@ StarterRng_Descriptor::StarterRng_Descriptor() ) {} -struct StarterRng_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , missed(m_stats["Missed"]) - , hits(m_stats["Hit"]) - , shinies(m_stats["Shiny"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back(Stat("Missed", HIDDEN_IF_ZERO)); - m_display_order.emplace_back(Stat("Hit", HIDDEN_IF_ZERO)); - m_display_order.emplace_back(Stat("Shiny", HIDDEN_IF_ZERO)); - m_display_order.emplace_back(Stat("Errors", HIDDEN_IF_ZERO)); - } - std::atomic& resets; - std::atomic& missed; - std::atomic& hits; - std::atomic& shinies; - std::atomic& errors; -}; std::unique_ptr StarterRng_Descriptor::make_stats() const{ return std::unique_ptr(new Stats()); } @@ -216,438 +167,6 @@ void StarterRng::on_config_value_changed(void*){ } -bool StarterRng::wanted( - const BdspRngFilterSnapshot& filters, const BdspPokemonResult& pokemon -){ - auto exactly = [](uint8_t iv){ return IvRange{(int8_t)iv, (int8_t)iv}; }; - IvRanges ivs; - ivs.hp = exactly(pokemon.ivs.hp); - ivs.attack = exactly(pokemon.ivs.attack); - ivs.defense = exactly(pokemon.ivs.defense); - ivs.spatk = exactly(pokemon.ivs.spatk); - ivs.spdef = exactly(pokemon.ivs.spdef); - ivs.speed = exactly(pokemon.ivs.speed); - - StatsHuntGenderFilter gender = StatsHuntGenderFilter::Genderless; - switch (pokemon.gender){ - case BdspGender::Male: gender = StatsHuntGenderFilter::Male; break; - case BdspGender::Female: gender = StatsHuntGenderFilter::Female; break; - default: break; - } - - return filters.get_action( - pokemon.shiny != BdspShiny::None, - gender, - bdsp_nature_to_checker_value(pokemon.nature), - pokemon.height, - ivs - ) != StatsHuntAction::Discard; -} - - -BdspSkipResult StarterRng::skip_advances_from_bedroom( - SingleSwitchProgramEnvironment& env, ProControllerContext& context -){ - BdspSkipResult skip; - const BdspRngTargetInfo& target_info = bdsp_rng_target_info(BdspRngTarget::Starter); - - // Expected wait duration at the lake after a long skip - double longest_skip = MAX_SKIP_MINUTES * BDSP_SKIP_ADVANCES_PER_MINUTE; - double lake_minutes = bdsp_lake_advances_needed(longest_skip) - * BDSP_NPC_TICK_SECONDS / (target_info.observation_npcs * 60.0); - if (lake_minutes > MAX_TARGET_WAIT_MINUTES){ - throw UserSetupError(env.logger(), - "A skip of up to " + std::to_string((uint16_t)MAX_SKIP_MINUTES) - + " minutes can leave up to " - + tostr_fixed(lake_minutes, 1) + " minutes of waiting at the lake, but the target " - "wait is capped at " + std::to_string((uint16_t)MAX_TARGET_WAIT_MINUTES) - + ". Raise the target wait to at least " - + std::to_string((uint16_t)std::ceil(lake_minutes)) - + " minutes, or lower the skip limit." - ); - } - - env.log("Starting in the bedroom."); - pbf_press_button(context, BUTTON_A, 100ms, 2000ms); // open dialogue box - context.wait_for_all_requests(); - - std::vector setups = bedroom_eye_templates(PLAYER_MODEL.model_number()); - std::vector eyes = load_eye_templates(setups); - - std::vector> watchers; - std::vector callbacks; - make_blink_watchers(setups, eyes, watchers, callbacks); - - BlinkRecoveryConfig bedroom_config; - bedroom_config.npcs = 1; - - BlinkRecovery recovery = recover_state_from_blinks( - env, context, watchers, callbacks, COLLECTION_DISPLAY, bedroom_config - ); - if (!recovery.success){ - skip.failure_reason = "could not determine the RNG state in the bedroom: " - + recovery.failure_reason; - return skip; - } - skip.state = recovery.state; - env.log("Bedroom RNG state: " + recovery.state.to_string(), COLOR_BLUE); - STATE_DISPLAY.set_state(recovery.state, recovery.clock.anchor_advance); - STATE_DISPLAY.set_confidence_unique(); - - // take into account remaning navigation time and the desired buffer - uint64_t soonest = recovery.clock.advance_at(current_time()) - + (uint64_t)BDSP_SKIP_NAVIGATION_ADVANCES + bdsp_skip_buffer(0); - uint64_t furthest = soonest - + (uint64_t)(MAX_SKIP_MINUTES * BDSP_SKIP_ADVANCES_PER_MINUTE); - - BdspStaticSearcher searcher(recovery.state, target_info.pokemon, 0); - BdspRngFilterSnapshot filters = FILTERS.make_snapshot(); - std::vector hits = searcher.scan( - soonest, furthest, - [&filters](const BdspPokemonResult& result){ return wanted(filters, result); }, - true, &context - ); - if (hits.empty()){ - skip.failure_reason = "no target within " + std::to_string((uint16_t)MAX_SKIP_MINUTES) - + " minutes of skipping"; - return skip; - } - const BdspRngHit& hit = hits[0]; - skip.target_advance = hit.advances; - TARGET_DISPLAY.set_target(hit.result, hit.advances); - - uint64_t start = recovery.clock.advance_at(current_time()); - - // The buffer depends on how far the skip runs, so size it from the raw distance. - double raw_skip = (double)hit.advances - (double)start - BDSP_SKIP_NAVIGATION_ADVANCES; - uint64_t buffer = bdsp_skip_buffer(raw_skip); - double to_skip = raw_skip - (double)buffer; - if (to_skip < 0){ - to_skip = 0; - } - double wait_seconds = to_skip * 60 / BDSP_SKIP_ADVANCES_PER_MINUTE; - skip.buffer = buffer; - - env.log("Target advance " + std::to_string(hit.advances) + ": " + hit.result.to_string(), - COLOR_BLUE); - env.log("Skipping " + std::to_string((uint64_t)to_skip) + " advances from " - + std::to_string(start) + ", which is " + tostr_fixed(wait_seconds, 1) - + "s on the spot, stopping " + std::to_string(buffer) - + " advances short to avoid overshooting.", COLOR_BLUE); - - navigate_bedroom_to_skip_spot(env.logger(), context); - - - WallClock leave_at = current_time() + std::chrono::duration_cast( - std::chrono::duration(wait_seconds) - ); - - while (current_time() + 2s < leave_at){ - WallClock now = current_time(); - WallClock until = std::min(leave_at - 2s, now + 180s); - pbf_wait(context, std::chrono::duration_cast(until - now)); - context.wait_for_all_requests(); - } - WallClock now = current_time(); - if (now < leave_at){ - pbf_wait(context, std::chrono::duration_cast(leave_at - now)); - context.wait_for_all_requests(); - } - - navigate_skip_spot_to_lakefront(env.logger(), context); - skip.success = true; - return skip; -} - - -void StarterRng::report_skip_arrival( - SingleSwitchProgramEnvironment& env, - const BdspSkipResult& skip, - const BlinkRecovery& arrival -) const{ - // Generous enough to catch an overshoot, and a match is unique anyway. - uint64_t search_max = skip.target_advance + SKIP_ARRIVAL_OVERSHOOT_ALLOWANCE; - uint64_t travelled = 0; - if (!advances_between(skip.state, arrival.state, search_max, travelled)){ - env.log( - "Could not place the lake state against the bedroom one, so the skip " - "cannot be measured this attempt.", - COLOR_ORANGE - ); - return; - } - - uint64_t here = travelled + arrival.clock.advance_at(current_time()); - int64_t short_by = (int64_t)skip.target_advance - (int64_t)here; - env.log( - "Skip landed on advance " + std::to_string(here) + " of " - + std::to_string(skip.target_advance) + ": " - + (short_by >= 0 - ? std::to_string(short_by) + " short, aimed for " + std::to_string(skip.buffer) - : "OVERSHOT by " + std::to_string(-short_by)), - short_by >= 0 ? COLOR_BLUE : COLOR_ORANGE - ); -} - - -BdspAttemptOutcome StarterRng::run_attempt( - SingleSwitchProgramEnvironment& env, ProControllerContext& context -){ - StarterRng_Descriptor::Stats& stats = env.current_stats(); - COLLECTION_DISPLAY.reset(); - STATE_DISPLAY.reset(); - TARGET_DISPLAY.reset(); - - auto abandon = [&](const std::string& reason) -> BdspAttemptOutcome{ - env.log("Abandoning this attempt: " + reason, COLOR_ORANGE); - TARGET_DISPLAY.set_note(reason); - return BdspAttemptOutcome::Abandoned; - }; - - const BdspRngTargetInfo& target_info = bdsp_rng_target_info(BdspRngTarget::Starter); - - BdspSkipResult skip; - if (START_POINT == BdspStartPoint::Bedroom){ - skip = skip_advances_from_bedroom(env, context); - if (!skip.success){ - return abandon(skip.failure_reason); - } - } - - navigate_to_lake_blinks(env.logger(), context); - - std::vector setups = lake_eye_templates(PLAYER_MODEL.model_number()); - std::vector eyes = load_eye_templates(setups); - - // The rival's dialogue box being up is what says the pair have stopped walking. - ShortDialogDetector dialog; - BlinkSceneConfig scene; - scene.frame_filter = [&dialog](const ImageViewRGB32& frame){ return dialog.detect(frame); }; - scene.press_retries = LAKE_BLINKS_PRESS_RETRIES; - - if (!wait_for_blink_scene(env, context, setups, eyes, scene, "Lake blinks")){ - return abandon("never reached the lake blink position"); - } - - // Now blink watchers can be created safely - std::vector> watchers; - std::vector callbacks; - make_blink_watchers(setups, eyes, watchers, callbacks); - - BlinkRecoveryConfig blink_config; - blink_config.npcs = target_info.observation_npcs; - - BlinkRecovery recovery = recover_state_from_blinks( - env, context, watchers, callbacks, COLLECTION_DISPLAY, blink_config - ); - if (!recovery.success){ - return abandon("could not determine the RNG state: " + recovery.failure_reason); - } - - uint64_t seed0 = 0; - uint64_t seed1 = 0; - xorshift128_state_to_seed_pair(recovery.state, seed0, seed1); - env.log("RNG state: " + recovery.state.to_string(), COLOR_BLUE); - env.log("PokeFinder seeds: " + tostr_hex_padded(16, seed0) - + " " + tostr_hex_padded(16, seed1), COLOR_BLUE); - env.log("Tick fitted at " + tostr_default(recovery.clock.tick_seconds) + "s over " - + std::to_string(recovery.events) + " rolls.", COLOR_BLUE); - env.log("Anchored on advance " + std::to_string(recovery.clock.anchor_advance) - + "; now at advance " + std::to_string(recovery.clock.advance_at(current_time())) - + ".", COLOR_BLUE); - STATE_DISPLAY.set_state(recovery.state, recovery.clock.anchor_advance); - STATE_DISPLAY.set_confidence_unique(); - - if (skip.success){ - report_skip_arrival(env, skip, recovery); - } - - - const BdspTimelineContext& timeline = target_info.timeline; - - NavigationTimings timings; - timings.ready_seconds = seconds_from_briefcase_to_starly_ready(); - timings.move_seconds = seconds_to_move_to_starter(STARTER) + 0.25; // small buffer - timings.prompt_seconds = seconds_from_select_to_confirm(); - timings.guard_seconds = GAP_GUARD_SECONDS; - - BdspStaticSearcher searcher(recovery.state, target_info.pokemon, 0); - - // A press cannot be sooner than the walk to the pre-briefcase position takes - double lead_seconds = seconds_to_pre_briefcase() + 15; - uint64_t lead_advances = (uint64_t)( - lead_seconds * recovery.clock.npcs / recovery.clock.tick_seconds - ) + 1; - - TargetSearchRequest search; - search.state = recovery.state; - search.timeline = timeline; - search.timings = timings; - search.pokemon = target_info.pokemon; - search.npcs = recovery.clock.npcs; - search.tick_seconds = recovery.clock.tick_seconds; - search.bias = m_aim.bias(); - search.first_press = recovery.clock.advance_at(current_time()) + lead_advances; - search.window_advances = (uint64_t)( - (double)MAX_TARGET_WAIT_MINUTES * 60 * recovery.clock.npcs / recovery.clock.tick_seconds - ); - search.max_schedules = MAX_SCHEDULES; - BdspRngFilterSnapshot filters = FILTERS.make_snapshot(); - search.wanted = [&filters](const BdspPokemonResult& result){ return wanted(filters, result); }; - - TargetSelectionResult selection = select_target(search); - - if (selection.matches_found != 0){ - env.log( - std::to_string(selection.matches_found) + " matching advance(s) in " - + std::to_string(selection.advances_scanned), - COLOR_BLUE - ); - } - if (!selection.success){ - return abandon(selection.failure_reason); - } - - uint64_t press_advance = selection.press_advance; - uint64_t target_advance = selection.target_advance; - const PressSchedule& schedule = selection.schedule; - const BdspPokemonResult& target = selection.target; - - double wait_seconds = std::chrono::duration_cast>( - recovery.clock.time_of_advance(press_advance) - current_time() - ).count(); - env.log("Target advance " + std::to_string(target_advance) + ": " + target.to_string(), - COLOR_BLUE); - env.log("Pressing at advance " + std::to_string(press_advance) + ", in " - + tostr_default(wait_seconds) + "s.", COLOR_BLUE); - env.log("Schedule spans " + std::to_string(schedule.span) + " advances, confirming after " - + std::to_string(schedule.blinks_before_confirm) + " Starly blink(s), " - + tostr_default(schedule.confirm_seconds) + "s in" - + m_aim.describe_correction() + ".", COLOR_BLUE); - TARGET_DISPLAY.set_target(target, target_advance); - - hold_and_reanchor( - env, context, watchers, callbacks, recovery, blink_config, - press_advance, lead_seconds, STATE_DISPLAY - ); - - navigate_to_pre_briefcase(env.logger(), context); - - // FIRST PRESS, centred in the advance rather than aimed right at the beginning of it - WallClock briefcase_time = recovery.clock.middle_of_advance(press_advance); - - while (current_time() + 3s < briefcase_time){ - STATE_DISPLAY.set_advances(recovery.clock.advance_at(current_time())); - pbf_wait(context, 1000ms); - context.wait_for_all_requests(); - } - - STATE_DISPLAY.set_advances(press_advance); - - env.log("Timeline starts at advance " + std::to_string(press_advance) - + ". Blind from here: Starly press at " + tostr_default(schedule.starly_seconds) - + "s, selecting at " + tostr_default(schedule.select_seconds) - + "s, confirming at " + tostr_default(schedule.confirm_seconds) - + "s, on advance " + std::to_string(target_advance - timeline.advances_after_accept) - + ".", COLOR_BLUE); - - std::string sequence_failure; - if (!wait_until_moment(context, env.logger(), briefcase_time)){ - return abandon("the briefcase press moment passed before it could be sent"); - } - if (!issue_starter_sequence( - context, STARTER, - schedule.starly_seconds, schedule.select_seconds, schedule.confirm_seconds, - sequence_failure - )){ - return abandon(sequence_failure); - } - env.log("Timeline finished; the starter should be in hand.", COLOR_BLUE); - - STATE_DISPLAY.set_advances(target_advance); - - - // Check what was actually obtained. - DoublesShinyDetection wild; - ShinyDetectionResult own; - detect_shiny_battle( - env, env.console, context, - wild, own, - NOTIFICATION_ERROR_RECOVERABLE, - YOUR_POKEMON, - 30s, - USE_SOUND_DETECTION - ); - bool shiny_known = own.shiny_type != ShinyType::UNKNOWN; - - if (is_likely_shiny(own.shiny_type)){ - stats.shinies++; - send_program_notification( - env, NOTIFICATION_SHINY, - COLOR_STAR_SHINY, "Shiny Starter", - {{"Advance", std::to_string(target_advance)}, {"Details", target.to_string()}}, - "", own.get_best_screenshot() - ); - if (TAKE_VIDEO){ - pbf_wait(context, 5000ms); - pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 5000ms); - context.wait_for_all_requests(); - } - return BdspAttemptOutcome::Hit; - } - - BdspObservedStarter observed; - if (!clear_starter_battle(env, context) - || !read_observed_pokemon( - env, context, LANGUAGE, starter_base_stats(STARTER), 5, false, shiny_known, observed - ) - ){ - stats.errors++; - return BdspAttemptOutcome::Unverifiable; - } - - BdspHitIdentification hit = identify_hit_advance( - recovery.state, target_info.pokemon, target_advance, HIT_SEARCH_RADIUS, observed - ); - if (!hit.success){ - env.log("Could not tell which advance that was: " + hit.failure_reason, COLOR_ORANGE); - if (consistent_with(target, observed)){ - env.log("What was read matches the target, so it counts as a hit.", COLOR_BLUE); - stats.hits++; - return BdspAttemptOutcome::Hit; - } - env.log("What was read is not the target, so it counts as a miss.", COLOR_ORANGE); - stats.missed++; - return BdspAttemptOutcome::Missed; - } - if (m_aim.record_offset(env.logger(), hit.offset, AUTO_CALIBRATE)){ - TARGET_DISPLAY.set_correction(m_aim.bias()); - } - - if (hit.offset == 0){ - env.log("Landed on advance " + std::to_string(target_advance) + ", as aimed.", - COLOR_BLUE); - stats.hits++; - return BdspAttemptOutcome::Hit; - } - - env.log( - "Landed on advance " + std::to_string(hit.advance) + " instead of " - + std::to_string(target_advance) + " — " - + (hit.offset > 0 ? "late by " : "early by ") - + std::to_string(hit.offset > 0 ? hit.offset : -hit.offset) + " advance(s).", - COLOR_ORANGE - ); - stats.missed++; - - if (wanted(filters, searcher.generate(hit.advance))){ - env.log("It passes the filter anyway, so this one will do. Stopping.", COLOR_BLUE); - return BdspAttemptOutcome::Hit; - } - return BdspAttemptOutcome::Missed; -} - - void StarterRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ StarterRng_Descriptor::Stats& stats = env.current_stats(); @@ -655,47 +174,41 @@ void StarterRng::program(SingleSwitchProgramEnvironment& env, ProControllerConte m_aim.reset(); - bool reset = false; - uint64_t resets = 0; - while (true){ - if (MAX_RESETS != 0 && resets >= MAX_RESETS){ - env.log("Reached the reset limit.", COLOR_ORANGE); - break; - } - resets++; - - bool started = true; - if (reset){ - go_home(env.console, context); - if (!reset_game_from_home( - env, env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - )){ - started = false; - } - } - - bool done = false; - if (started){ - reset = true; - done = run_attempt(env, context) == BdspAttemptOutcome::Hit; - } - - stats.resets++; - env.update_stats(); + BdspRngFilterSnapshot filters = FILTERS.make_snapshot(); + StarterRngSettings settings{ + .language = LANGUAGE, + .player_model = PLAYER_MODEL.model_number(), + .start_point = START_POINT, + .starter = STARTER, + .wanted = [&filters](const BdspPokemonResult& result){ + return starter_wanted(filters, result); + }, + .filters = &filters, + .max_resets = MAX_RESETS, + .max_target_wait_minutes = MAX_TARGET_WAIT_MINUTES, + .max_skip_minutes = MAX_SKIP_MINUTES, + .auto_calibrate = AUTO_CALIBRATE, + .use_sound_detection = USE_SOUND_DETECTION, + .take_video = TAKE_VIDEO, + .reset_first = false, + .finish_battle_on_shiny = false, + .close_summary_after_read = false, + }; + StarterRngAttemptIO io{ + .collection_display = &COLLECTION_DISPLAY, + .state_display = &STATE_DISPLAY, + .target_display = &TARGET_DISPLAY, + .notification_shiny = &NOTIFICATION_SHINY, + .notification_error = &NOTIFICATION_ERROR_RECOVERABLE, + .stats = &stats, + }; - if (done){ - break; - } - } + run_starter_rng_attempts(env, context, settings, io, m_aim); - env.update_stats(); GO_HOME_WHEN_DONE.run_end_of_program(context); } - - } } } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h index 7ac087c5e2..ba081486b2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h @@ -8,57 +8,30 @@ #define PokemonAutomation_PokemonBDSP_StarterRng_H #include -#include #include "Common/Cpp/Options/BooleanCheckBoxOption.h" #include "Common/Cpp/Options/EnumDropdownOption.h" #include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonTools/Options/LanguageOCROption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "CommonTools/Options/LanguageOCROption.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Pokemon_BdspRng.h" -#include "Pokemon/Pokemon_NatureChecker.h" -#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "PokemonBDSP/Options/PokemonBDSP_PlayerModelOption.h" #include "PokemonBDSP/Options/PokemonBDSP_RngFilter.h" -#include "PokemonBDSP_BlinkRecovery.h" #include "PokemonBDSP_RngAim.h" #include "PokemonBDSP_RngDisplays.h" #include "PokemonBDSP_StarterNavigation.h" +#include "PokemonBDSP_StarterRngAttempts.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonBDSP{ -enum class BdspStartPoint{ - Lakefront, - Bedroom, -}; - - -struct BdspSkipResult{ - bool success = false; - Pokemon::Xorshift128State state; - uint64_t target_advance = 0; - uint64_t buffer = 0; - std::string failure_reason; -}; - - -enum class BdspAttemptOutcome{ - Abandoned, - Missed, - Hit, - Unverifiable, -}; - - class StarterRng_Descriptor : public SingleSwitchProgramDescriptor{ public: StarterRng_Descriptor(); - struct Stats; + using Stats = StarterRngStats; virtual std::unique_ptr make_stats() const override; }; @@ -73,24 +46,6 @@ class StarterRng : public SingleSwitchProgramInstance, public ConfigOption::List private: virtual void on_config_value_changed(void* object) override; - BdspAttemptOutcome run_attempt(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - // Takes a snapshot rather than the table: the table clones itself on every query, - // which a scan over millions of advances cannot afford. - static bool wanted( - const BdspRngFilterSnapshot& filters, const Pokemon::BdspPokemonResult& pokemon - ); - - BdspSkipResult skip_advances_from_bedroom( - SingleSwitchProgramEnvironment& env, ProControllerContext& context - ); - - void report_skip_arrival( - SingleSwitchProgramEnvironment& env, - const BdspSkipResult& skip, - const BlinkRecovery& arrival - ) const; - private: RngAim m_aim; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp new file mode 100644 index 0000000000..1f15c57748 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp @@ -0,0 +1,744 @@ +/* BDSP Starter RNG Attempts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" +#include "Pokemon/Pokemon_NatureChecker.h" +#include "Pokemon/Pokemon_Notification.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Inference/Rng/PokemonBDSP_BlinkScenes.h" +#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" +#include "PokemonBDSP_BlinkRecovery.h" +#include "PokemonBDSP_RngCalibration.h" +#include "PokemonBDSP_RngExecution.h" +#include "PokemonBDSP_RngTargets.h" +#include "PokemonBDSP_RngTimeline.h" +#include "PokemonBDSP_StarterRngAttempts.h" +#include "PokemonBDSP_SummaryNavigation.h" +#include "PokemonBDSP_TargetSelection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +namespace{ + +const size_t LAKE_BLINKS_PRESS_RETRIES = 10; + +const double GAP_GUARD_SECONDS = 0.30; + +const uint64_t HIT_SEARCH_RADIUS = 20; +const size_t MAX_SCHEDULES = 8; + +const uint64_t SKIP_ARRIVAL_OVERSHOOT_ALLOWANCE = 200000; + + +std::function resolve_wanted_predicate( + const StarterRngSettings& settings +){ + if (settings.wanted){ + return settings.wanted; + } + if (settings.filters != nullptr){ + const BdspRngFilterSnapshot* filters = settings.filters; + return [filters](const BdspPokemonResult& result){ + return starter_wanted(*filters, result); + }; + } + return [](const BdspPokemonResult& result){ + return result.shiny != BdspShiny::None; + }; +} + + +BdspSkipResult skip_advances_from_bedroom( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const StarterRngSettings& settings, + const std::function& wanted_fn, + BlinkCollectionDisplay& collection_display, + RngStateDisplay& state_display, + RngTargetDisplay& target_display +){ + BdspSkipResult skip; + const BdspRngTargetInfo& target_info = bdsp_rng_target_info(BdspRngTarget::Starter); + + // Expected wait duration at the lake after a long skip + double longest_skip = settings.max_skip_minutes * BDSP_SKIP_ADVANCES_PER_MINUTE; + double lake_minutes = bdsp_lake_advances_needed(longest_skip) + * BDSP_NPC_TICK_SECONDS / (target_info.observation_npcs * 60.0); + if (lake_minutes > settings.max_target_wait_minutes){ + throw UserSetupError(env.logger(), + "A skip of up to " + std::to_string(settings.max_skip_minutes) + + " minutes can leave up to " + + tostr_fixed(lake_minutes, 1) + " minutes of waiting at the lake, but the target " + "wait is capped at " + std::to_string(settings.max_target_wait_minutes) + + ". Raise the target wait to at least " + + std::to_string((uint16_t)std::ceil(lake_minutes)) + + " minutes, or lower the skip limit." + ); + } + + env.log("Starting in the bedroom."); + pbf_press_button(context, BUTTON_A, 100ms, 2000ms); // open dialogue box + context.wait_for_all_requests(); + + std::vector setups = bedroom_eye_templates(settings.player_model); + std::vector eyes = load_eye_templates(setups); + + std::vector> watchers; + std::vector callbacks; + make_blink_watchers(setups, eyes, watchers, callbacks); + + BlinkRecoveryConfig bedroom_config; + bedroom_config.npcs = 1; + + BlinkRecovery recovery = recover_state_from_blinks( + env, context, watchers, callbacks, collection_display, bedroom_config + ); + if (!recovery.success){ + skip.failure_reason = "could not determine the RNG state in the bedroom: " + + recovery.failure_reason; + return skip; + } + skip.state = recovery.state; + env.log("Bedroom RNG state: " + recovery.state.to_string(), COLOR_BLUE); + state_display.set_state(recovery.state, recovery.clock.anchor_advance); + state_display.set_confidence_unique(); + + // take into account remaining navigation time and the desired buffer + uint64_t soonest = recovery.clock.advance_at(current_time()) + + (uint64_t)BDSP_SKIP_NAVIGATION_ADVANCES + bdsp_skip_buffer(0); + uint64_t furthest = soonest + + (uint64_t)(settings.max_skip_minutes * BDSP_SKIP_ADVANCES_PER_MINUTE); + + BdspStaticSearcher searcher(recovery.state, target_info.pokemon, 0); + std::vector hits = searcher.scan( + soonest, furthest, + wanted_fn, + true, &context + ); + if (hits.empty()){ + skip.failure_reason = "no target within " + std::to_string(settings.max_skip_minutes) + + " minutes of skipping"; + return skip; + } + const BdspRngHit& hit = hits[0]; + skip.target_advance = hit.advances; + target_display.set_target(hit.result, hit.advances); + + uint64_t start = recovery.clock.advance_at(current_time()); + + // The buffer depends on how far the skip runs, so size it from the raw distance. + double raw_skip = (double)hit.advances - (double)start - BDSP_SKIP_NAVIGATION_ADVANCES; + uint64_t buffer = bdsp_skip_buffer(raw_skip); + double to_skip = raw_skip - (double)buffer; + if (to_skip < 0){ + to_skip = 0; + } + double wait_seconds = to_skip * 60 / BDSP_SKIP_ADVANCES_PER_MINUTE; + skip.buffer = buffer; + + env.log("Target advance " + std::to_string(hit.advances) + ": " + hit.result.to_string(), + COLOR_BLUE); + env.log("Skipping " + std::to_string((uint64_t)to_skip) + " advances from " + + std::to_string(start) + ", which is " + tostr_fixed(wait_seconds, 1) + + "s on the spot, stopping " + std::to_string(buffer) + + " advances short to avoid overshooting.", COLOR_BLUE); + + navigate_bedroom_to_skip_spot(env.logger(), context); + + WallClock leave_at = current_time() + std::chrono::duration_cast( + std::chrono::duration(wait_seconds) + ); + + while (current_time() + 2s < leave_at){ + WallClock now = current_time(); + WallClock until = std::min(leave_at - 2s, now + 180s); + pbf_wait(context, std::chrono::duration_cast(until - now)); + context.wait_for_all_requests(); + } + WallClock now = current_time(); + if (now < leave_at){ + pbf_wait(context, std::chrono::duration_cast(leave_at - now)); + context.wait_for_all_requests(); + } + + navigate_skip_spot_to_lakefront(env.logger(), context); + skip.success = true; + return skip; +} + + +void report_skip_arrival( + SingleSwitchProgramEnvironment& env, + const BdspSkipResult& skip, + const BlinkRecovery& arrival +){ + // Generous enough to catch an overshoot, and a match is unique anyway. + uint64_t search_max = skip.target_advance + SKIP_ARRIVAL_OVERSHOOT_ALLOWANCE; + uint64_t travelled = 0; + if (!advances_between(skip.state, arrival.state, search_max, travelled)){ + env.log( + "Could not place the lake state against the bedroom one, so the skip " + "cannot be measured this attempt.", + COLOR_ORANGE + ); + return; + } + + uint64_t here = travelled + arrival.clock.advance_at(current_time()); + int64_t short_by = (int64_t)skip.target_advance - (int64_t)here; + env.log( + "Skip landed on advance " + std::to_string(here) + " of " + + std::to_string(skip.target_advance) + ": " + + (short_by >= 0 + ? std::to_string(short_by) + " short, aimed for " + std::to_string(skip.buffer) + : "OVERSHOT by " + std::to_string(-short_by)), + short_by >= 0 ? COLOR_BLUE : COLOR_ORANGE + ); +} + +} // namespace + + +StarterRngStats::StarterRngStats() + : resets(m_stats["Resets"]) + , missed(m_stats["Missed"]) + , hits(m_stats["Hit"]) + , shinies(m_stats["Shiny"]) + , errors(m_stats["Errors"]) +{ + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back(Stat("Missed", HIDDEN_IF_ZERO)); + m_display_order.emplace_back(Stat("Hit", HIDDEN_IF_ZERO)); + m_display_order.emplace_back(Stat("Shiny", HIDDEN_IF_ZERO)); + m_display_order.emplace_back(Stat("Errors", HIDDEN_IF_ZERO)); +} + + +bool starter_wanted( + const BdspRngFilterSnapshot& filters, + const BdspPokemonResult& pokemon +){ + auto exactly = [](uint8_t iv){ + return IvRange{(int8_t)iv, (int8_t)iv}; + }; + IvRanges ivs; + ivs.hp = exactly(pokemon.ivs.hp); + ivs.attack = exactly(pokemon.ivs.attack); + ivs.defense = exactly(pokemon.ivs.defense); + ivs.spatk = exactly(pokemon.ivs.spatk); + ivs.spdef = exactly(pokemon.ivs.spdef); + ivs.speed = exactly(pokemon.ivs.speed); + + StatsHuntGenderFilter gender = StatsHuntGenderFilter::Genderless; + switch (pokemon.gender){ + case BdspGender::Male: + gender = StatsHuntGenderFilter::Male; + break; + case BdspGender::Female: + gender = StatsHuntGenderFilter::Female; + break; + default: + break; + } + + return filters.get_action( + pokemon.shiny != BdspShiny::None, + gender, + bdsp_nature_to_checker_value(pokemon.nature), + pokemon.height, + ivs + ) != StatsHuntAction::Discard; +} + + +bool resolve_starter_rng_step( + const BdspStarterAttemptResult& attempt, + uint64_t resets_used, + uint16_t max_resets, + StarterRngRunResult& result +){ + result.resets_used = resets_used; + if (attempt.target_advance != 0){ + result.target = attempt.target; + result.target_advance = attempt.target_advance; + } + if (!attempt.failure_reason.empty()){ + result.last_failure_reason = attempt.failure_reason; + } + + if (attempt.outcome == BdspAttemptOutcome::Hit){ + result.outcome = attempt.shiny + ? StarterRngOutcome::SHINY + : StarterRngOutcome::HIT; + return true; + } + + if (max_resets != 0 && resets_used >= max_resets){ + result.outcome = attempt.outcome == BdspAttemptOutcome::Abandoned + ? StarterRngOutcome::ABANDONED + : StarterRngOutcome::OUT_OF_RESETS; + return true; + } + + return false; +} + + +BdspStarterAttemptResult run_starter_rng_attempt( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const StarterRngSettings& settings, + const StarterRngAttemptIO& io, + RngAim& aim +){ + BlinkCollectionDisplay fallback_collection(true); + RngStateDisplay fallback_state; + RngTargetDisplay fallback_target; + + BlinkCollectionDisplay& collection_display = io.collection_display != nullptr + ? *io.collection_display + : fallback_collection; + RngStateDisplay& state_display = io.state_display != nullptr + ? *io.state_display + : fallback_state; + RngTargetDisplay& target_display = io.target_display != nullptr + ? *io.target_display + : fallback_target; + + collection_display.reset(); + state_display.reset(); + target_display.reset(); + + auto record_miss = [&](){ + if (io.stats != nullptr){ + io.stats->missed++; + } + if (io.on_miss){ + io.on_miss(); + } + }; + auto record_hit = [&](){ + if (io.stats != nullptr){ + io.stats->hits++; + } + if (io.on_hit){ + io.on_hit(); + } + }; + auto record_shiny = [&](){ + if (io.stats != nullptr){ + io.stats->shinies++; + } + if (io.on_shiny){ + io.on_shiny(); + } + }; + auto record_error = [&](){ + if (io.stats != nullptr){ + io.stats->errors++; + } + if (io.on_error){ + io.on_error(); + } + }; + + auto abandon = [&](const std::string& reason) -> BdspStarterAttemptResult{ + env.log("Abandoning this attempt: " + reason, COLOR_ORANGE); + target_display.set_note(reason); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Abandoned, + .failure_reason = reason, + }; + }; + + std::function wanted_fn = resolve_wanted_predicate(settings); + const BdspRngTargetInfo& target_info = bdsp_rng_target_info(BdspRngTarget::Starter); + + BdspSkipResult skip; + if (settings.start_point == BdspStartPoint::Bedroom){ + skip = skip_advances_from_bedroom( + env, context, settings, wanted_fn, + collection_display, state_display, target_display + ); + if (!skip.success){ + return abandon(skip.failure_reason); + } + } + + navigate_to_lake_blinks(env.logger(), context); + + std::vector setups = lake_eye_templates(settings.player_model); + std::vector eyes = load_eye_templates(setups); + + // The rival's dialogue box being up is what says the pair have stopped walking. + ShortDialogDetector dialog; + BlinkSceneConfig scene; + scene.frame_filter = [&dialog](const ImageViewRGB32& frame){ + return dialog.detect(frame); + }; + scene.press_retries = LAKE_BLINKS_PRESS_RETRIES; + + if (!wait_for_blink_scene(env, context, setups, eyes, scene, "Lake blinks")){ + return abandon("never reached the lake blink position"); + } + + // Now blink watchers can be created safely + std::vector> watchers; + std::vector callbacks; + make_blink_watchers(setups, eyes, watchers, callbacks); + + BlinkRecoveryConfig blink_config; + blink_config.npcs = target_info.observation_npcs; + + BlinkRecovery recovery = recover_state_from_blinks( + env, context, watchers, callbacks, collection_display, blink_config + ); + if (!recovery.success){ + return abandon("could not determine the RNG state: " + recovery.failure_reason); + } + + uint64_t seed0 = 0; + uint64_t seed1 = 0; + xorshift128_state_to_seed_pair(recovery.state, seed0, seed1); + env.log("RNG state: " + recovery.state.to_string(), COLOR_BLUE); + env.log("PokeFinder seeds: " + tostr_hex_padded(16, seed0) + + " " + tostr_hex_padded(16, seed1), COLOR_BLUE); + env.log("Tick fitted at " + tostr_default(recovery.clock.tick_seconds) + "s over " + + std::to_string(recovery.events) + " rolls.", COLOR_BLUE); + env.log("Anchored on advance " + std::to_string(recovery.clock.anchor_advance) + + "; now at advance " + std::to_string(recovery.clock.advance_at(current_time())) + + ".", COLOR_BLUE); + state_display.set_state(recovery.state, recovery.clock.anchor_advance); + state_display.set_confidence_unique(); + + if (skip.success){ + report_skip_arrival(env, skip, recovery); + } + + const BdspTimelineContext& timeline = target_info.timeline; + + NavigationTimings timings; + timings.ready_seconds = seconds_from_briefcase_to_starly_ready(); + timings.move_seconds = seconds_to_move_to_starter(settings.starter) + 0.25; // small buffer + timings.prompt_seconds = seconds_from_select_to_confirm(); + timings.guard_seconds = GAP_GUARD_SECONDS; + + BdspStaticSearcher searcher(recovery.state, target_info.pokemon, 0); + + // A press cannot be sooner than the walk to the pre-briefcase position takes + double lead_seconds = seconds_to_pre_briefcase() + 15; + uint64_t lead_advances = (uint64_t)( + lead_seconds * recovery.clock.npcs / recovery.clock.tick_seconds + ) + 1; + + TargetSearchRequest search; + search.state = recovery.state; + search.timeline = timeline; + search.timings = timings; + search.pokemon = target_info.pokemon; + search.npcs = recovery.clock.npcs; + search.tick_seconds = recovery.clock.tick_seconds; + search.bias = aim.bias(); + search.first_press = recovery.clock.advance_at(current_time()) + lead_advances; + search.window_advances = (uint64_t)( + (double)settings.max_target_wait_minutes * 60 * recovery.clock.npcs / recovery.clock.tick_seconds + ); + search.max_schedules = MAX_SCHEDULES; + search.wanted = wanted_fn; + + TargetSelectionResult selection = select_target(search); + + if (selection.matches_found != 0){ + env.log( + std::to_string(selection.matches_found) + " matching advance(s) in " + + std::to_string(selection.advances_scanned), + COLOR_BLUE + ); + } + if (!selection.success){ + return abandon(selection.failure_reason); + } + + uint64_t press_advance = selection.press_advance; + uint64_t target_advance = selection.target_advance; + const PressSchedule& schedule = selection.schedule; + const BdspPokemonResult& target = selection.target; + + double wait_seconds = std::chrono::duration_cast>( + recovery.clock.time_of_advance(press_advance) - current_time() + ).count(); + env.log("Target advance " + std::to_string(target_advance) + ": " + target.to_string(), + COLOR_BLUE); + env.log("Pressing at advance " + std::to_string(press_advance) + ", in " + + tostr_default(wait_seconds) + "s.", COLOR_BLUE); + env.log("Schedule spans " + std::to_string(schedule.span) + " advances, confirming after " + + std::to_string(schedule.blinks_before_confirm) + " Starly blink(s), " + + tostr_default(schedule.confirm_seconds) + "s in" + + aim.describe_correction() + ".", COLOR_BLUE); + target_display.set_target(target, target_advance); + + hold_and_reanchor( + env, context, watchers, callbacks, recovery, blink_config, + press_advance, lead_seconds, state_display + ); + + navigate_to_pre_briefcase(env.logger(), context); + + // FIRST PRESS, centred in the advance rather than aimed right at the beginning of it + WallClock briefcase_time = recovery.clock.middle_of_advance(press_advance); + + while (current_time() + 3s < briefcase_time){ + state_display.set_advances(recovery.clock.advance_at(current_time())); + pbf_wait(context, 1000ms); + context.wait_for_all_requests(); + } + + state_display.set_advances(press_advance); + + env.log("Timeline starts at advance " + std::to_string(press_advance) + + ". Blind from here: Starly press at " + tostr_default(schedule.starly_seconds) + + "s, selecting at " + tostr_default(schedule.select_seconds) + + "s, confirming at " + tostr_default(schedule.confirm_seconds) + + "s, on advance " + std::to_string(target_advance - timeline.advances_after_accept) + + ".", COLOR_BLUE); + + std::string sequence_failure; + if (!wait_until_moment(context, env.logger(), briefcase_time)){ + return abandon("the briefcase press moment passed before it could be sent"); + } + if (!issue_starter_sequence( + context, settings.starter, + schedule.starly_seconds, schedule.select_seconds, schedule.confirm_seconds, + sequence_failure + )){ + return abandon(sequence_failure); + } + env.log("Timeline finished; the starter should be in hand.", COLOR_BLUE); + + state_display.set_advances(target_advance); + + // Check what was actually obtained. + DoublesShinyDetection wild; + ShinyDetectionResult own; + detect_shiny_battle( + env, env.console, context, + wild, own, + io.notification_error != nullptr ? *io.notification_error : EventNotificationOption_NOOP(), + YOUR_POKEMON, + 30s, + settings.use_sound_detection + ); + bool shiny_known = own.shiny_type != ShinyType::UNKNOWN; + + if (is_likely_shiny(own.shiny_type)){ + record_shiny(); + if (io.notification_shiny != nullptr){ + send_program_notification( + env, *io.notification_shiny, + COLOR_STAR_SHINY, "Shiny Starter", + {{"Advance", std::to_string(target_advance)}, {"Details", target.to_string()}}, + "", own.get_best_screenshot() + ); + } + if (settings.take_video){ + pbf_wait(context, 5000ms); + pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 5000ms); + context.wait_for_all_requests(); + } + if (settings.finish_battle_on_shiny){ + if (!clear_starter_battle(env, context)){ + record_error(); + } + } + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = true, + .target = target, + .target_advance = target_advance, + }; + } + + BdspObservedStarter observed; + if (!clear_starter_battle(env, context) + || !read_observed_pokemon( + env, context, settings.language, + starter_base_stats(settings.starter), 5, false, shiny_known, observed + ) + ){ + record_error(); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Unverifiable, + .shiny = false, + .target = target, + .target_advance = target_advance, + .failure_reason = "could not verify the obtained starter", + }; + } + + if (settings.close_summary_after_read){ + if (!close_starter_summary(env, context)){ + record_error(); + } + } + + BdspHitIdentification hit = identify_hit_advance( + recovery.state, target_info.pokemon, target_advance, HIT_SEARCH_RADIUS, observed + ); + if (!hit.success){ + env.log("Could not tell which advance that was: " + hit.failure_reason, COLOR_ORANGE); + if (consistent_with(target, observed)){ + env.log("What was read matches the target, so it counts as a hit.", COLOR_BLUE); + record_hit(); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = false, + .target = target, + .target_advance = target_advance, + }; + } + env.log("What was read is not the target, so it counts as a miss.", COLOR_ORANGE); + record_miss(); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Missed, + .shiny = false, + .target = target, + .target_advance = target_advance, + .failure_reason = hit.failure_reason, + }; + } + if (aim.record_offset(env.logger(), hit.offset, settings.auto_calibrate)){ + target_display.set_correction(aim.bias()); + } + + if (hit.offset == 0){ + env.log("Landed on advance " + std::to_string(target_advance) + ", as aimed.", + COLOR_BLUE); + record_hit(); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = false, + .target = target, + .target_advance = target_advance, + }; + } + + env.log( + "Landed on advance " + std::to_string(hit.advance) + " instead of " + + std::to_string(target_advance) + " — " + + (hit.offset > 0 ? "late by " : "early by ") + + std::to_string(hit.offset > 0 ? hit.offset : -hit.offset) + " advance(s).", + COLOR_ORANGE + ); + record_miss(); + + BdspPokemonResult actual = searcher.generate(hit.advance); + if (wanted_fn(actual)){ + env.log("It passes the filter anyway, so this one will do. Stopping.", COLOR_BLUE); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = false, + .target = actual, + .target_advance = hit.advance, + }; + } + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Missed, + .shiny = false, + .target = target, + .target_advance = target_advance, + }; +} + + +StarterRngRunResult run_starter_rng_attempts( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const StarterRngSettings& settings, + const StarterRngAttemptIO& io, + RngAim& aim +){ + StarterRngRunResult result; + bool reset = settings.reset_first; + uint64_t resets = 0; + BdspStarterAttemptResult last_attempt; + + while (true){ + if (settings.max_resets != 0 && resets >= settings.max_resets){ + env.log("Reached the reset limit.", COLOR_ORANGE); + resolve_starter_rng_step(last_attempt, resets, settings.max_resets, result); + break; + } + resets++; + + bool started = true; + if (reset){ + go_home(env.console, context); + if (!reset_game_from_home( + env, env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + )){ + started = false; + } + } + + if (started){ + reset = true; + last_attempt = run_starter_rng_attempt(env, context, settings, io, aim); + }else{ + last_attempt = BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Abandoned, + .failure_reason = "failed to reset the game from the Home screen", + }; + } + + if (io.stats != nullptr){ + io.stats->resets++; + } + if (io.on_reset){ + io.on_reset(); + } + env.update_stats(); + + if (last_attempt.outcome == BdspAttemptOutcome::Hit){ + resolve_starter_rng_step(last_attempt, resets, settings.max_resets, result); + break; + } + if (!last_attempt.failure_reason.empty()){ + result.last_failure_reason = last_attempt.failure_reason; + } + result.resets_used = resets; + if (last_attempt.target_advance != 0){ + result.target = last_attempt.target; + result.target_advance = last_attempt.target_advance; + } + } + + env.update_stats(); + return result; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h new file mode 100644 index 0000000000..c1c7977194 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h @@ -0,0 +1,209 @@ +/* BDSP Starter RNG Attempts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_StarterRngAttempts_H +#define PokemonAutomation_PokemonBDSP_StarterRngAttempts_H + +#include +#include +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Pokemon_BdspRng.h" +#include "Pokemon/Pokemon_Xorshift128.h" +#include "PokemonBDSP/Options/PokemonBDSP_RngFilter.h" +#include "PokemonBDSP_RngAim.h" +#include "PokemonBDSP_RngDisplays.h" +#include "PokemonBDSP_StarterNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +enum class BdspStartPoint{ + Lakefront, + Bedroom, +}; + + +struct BdspSkipResult{ + bool success = false; + Pokemon::Xorshift128State state; + uint64_t target_advance = 0; + uint64_t buffer = 0; + std::string failure_reason; +}; + + +enum class BdspAttemptOutcome{ + Abandoned, + Missed, + Hit, + Unverifiable, +}; + + +struct StarterRngStats : public StatsTracker{ + StarterRngStats(); + + std::atomic& resets; + std::atomic& missed; + std::atomic& hits; + std::atomic& shinies; + std::atomic& errors; +}; + + +// Evaluates whether a generated starter satisfies the filter snapshot. +// Takes a snapshot rather than the table because scanning millions of +// advances cannot afford cloning the table on every query. +bool starter_wanted( + const BdspRngFilterSnapshot& filters, + const Pokemon::BdspPokemonResult& pokemon +); + + +// Settings for a Starter RNG attempt loop. +// +// In-game state traversal after the starter is chosen and the wild Starly +// battle begins at Lake Verity: +// - Shiny hit (`Outcome::SHINY`): +// `detect_shiny_battle(...)` finishes at the start of the Starly battle. +// * When `finish_battle_on_shiny == false` (standalone `StarterRng` default): +// returns immediately while still inside the Starly battle at Lake Verity. +// * When `finish_battle_on_shiny == true` (for AutoStory): +// calls `clear_starter_battle(env, context)`, which mashes A until +// `EndBattleWatcher` detects the black-screen battle exit transition. +// The player ends up right at the start of the post-battle Lake Verity +// cutscene (Rowan's lines and walking out of the lake to VerityLakefront +// `(17, 14..15)`), ready for AutoStory's `after_starly` step. +// - Non-shiny starter (`clear_starter_battle` + `read_observed_pokemon`): +// 1. `clear_starter_battle(env, context)` mashes A until `EndBattleWatcher` +// detects the end of the Starly battle. +// 2. `read_observed_pokemon(...)` calls `open_menu(env, context)`, which +// mashes `B, B, X` until `MenuWatcher` detects the overworld X menu. +// Because the X menu cannot open during the post-battle Lake Verity +// cutscene or the warp out of the lake, `open_menu` advances through +// all of Rowan's and Barry's post-battle dialogue (`after_starly`) and +// the warp back to `VerityLakefront (17, 14..15)`, then opens the X menu +// once the player has overworld control on `VerityLakefront`. +// 3. `open_starter_summary(env, context)` selects `POKEMON` (one entry left +// on the 2-icon pre-Pokedex X menu), opens the starter's Summary screen, +// reads Nature & Gender on the 2nd tab (Trainer Memo), and presses Right +// to read the 6 stats on the 3rd tab (Skills/Stats). +// * When `close_summary_after_read == false` (standalone `StarterRng` default): +// leaves the game on the 3rd tab of the starter's Summary screen. +// * When `close_summary_after_read == true` (for AutoStory): +// calls `close_starter_summary(env, context)` after reading the summary, +// which presses B back to the X menu and X to close it, leaving the +// player standing on the `VerityLakefront` overworld at `(17, 14..15)` +// (with `after_starly` already completed, ready for checkpoint `00.03`). +struct StarterRngSettings{ + Language language = Language::English; + uint8_t player_model = 1; + BdspStartPoint start_point = BdspStartPoint::Lakefront; + BdspStarter starter = BdspStarter::Turtwig; + + // Predicate for target selection and hit verification. If `wanted` is + // empty and `filters` is non-null, `starter_wanted(*filters, ...)` is used. + std::function wanted; + const BdspRngFilterSnapshot* filters = nullptr; + + uint16_t max_resets = 0; + uint16_t max_target_wait_minutes = 30; + uint16_t max_skip_minutes = 30; + + bool auto_calibrate = true; + bool use_sound_detection = true; + bool take_video = true; + + bool reset_first = false; + bool finish_battle_on_shiny = false; + bool close_summary_after_read = false; +}; + + +struct StarterRngAttemptIO{ + BlinkCollectionDisplay* collection_display = nullptr; + RngStateDisplay* state_display = nullptr; + RngTargetDisplay* target_display = nullptr; + EventNotificationOption* notification_shiny = nullptr; + EventNotificationOption* notification_error = nullptr; + StarterRngStats* stats = nullptr; + + std::function on_reset; + std::function on_miss; + std::function on_hit; + std::function on_shiny; + std::function on_error; +}; + + +enum class StarterRngOutcome{ + HIT, + SHINY, + OUT_OF_RESETS, + ABANDONED, +}; + + +struct StarterRngRunResult{ + using Outcome = StarterRngOutcome; + using enum StarterRngOutcome; + + Outcome outcome = Outcome::ABANDONED; + Pokemon::BdspPokemonResult target{}; + uint64_t target_advance = 0; + uint64_t resets_used = 0; + std::string last_failure_reason; +}; + + +struct BdspStarterAttemptResult{ + BdspAttemptOutcome outcome = BdspAttemptOutcome::Abandoned; + bool shiny = false; + Pokemon::BdspPokemonResult target{}; + uint64_t target_advance = 0; + std::string failure_reason; +}; + + +// Pure helper that maps the latest attempt result and reset count to a +// finished `StarterRngRunResult` when the loop should terminate, or returns +// `false` when the loop should continue to the next reset. +bool resolve_starter_rng_step( + const BdspStarterAttemptResult& attempt, + uint64_t resets_used, + uint16_t max_resets, + StarterRngRunResult& result +); + + +BdspStarterAttemptResult run_starter_rng_attempt( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const StarterRngSettings& settings, + const StarterRngAttemptIO& io, + RngAim& aim +); + + +StarterRngRunResult run_starter_rng_attempts( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const StarterRngSettings& settings, + const StarterRngAttemptIO& io, + RngAim& aim +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp new file mode 100644 index 0000000000..09d19104c2 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp @@ -0,0 +1,305 @@ +/* BDSP Starter RNG Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonBDSP_RngAim.h" +#include "PokemonBDSP_RngCalibration.h" +#include "PokemonBDSP_StarterNavigation.h" +#include "PokemonBDSP_StarterRngAttempts.h" +#include "PokemonBDSP_StarterRng_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +namespace{ + +struct StarterTableRow{ + BdspStarter starter; + std::string slug; + uint8_t cursor_steps; + BaseStats base_stats; + double move_seconds; +}; + +const std::vector STARTER_TABLE_ROWS = { + { + .starter = BdspStarter::Turtwig, + .slug = "turtwig", + .cursor_steps = 0, + .base_stats = {55, 68, 64, 45, 55, 31}, + .move_seconds = 6.8, + }, + { + .starter = BdspStarter::Chimchar, + .slug = "chimchar", + .cursor_steps = 1, + .base_stats = {44, 58, 44, 58, 44, 61}, + .move_seconds = 7.5, + }, + { + .starter = BdspStarter::Piplup, + .slug = "piplup", + .cursor_steps = 2, + .base_stats = {53, 51, 53, 61, 56, 40}, + .move_seconds = 8.2, + }, +}; + + +UnitTestResult test_starter_tables(Logger&){ + for (const StarterTableRow& row : STARTER_TABLE_ROWS){ + const std::string got_slug = starter_slug(row.starter); + if (got_slug != row.slug){ + return std::format("starter_slug mismatch: got {}, expected {}", got_slug, row.slug); + } + const uint8_t got_steps = starter_cursor_steps(row.starter); + if (got_steps != row.cursor_steps){ + return std::format( + "starter_cursor_steps({}) = {}, expected {}", + row.slug, got_steps, row.cursor_steps + ); + } + const BaseStats& stats = starter_base_stats(row.starter); + if (stats.hp != row.base_stats.hp + || stats.attack != row.base_stats.attack + || stats.defense != row.base_stats.defense + || stats.spatk != row.base_stats.spatk + || stats.spdef != row.base_stats.spdef + || stats.speed != row.base_stats.speed + ){ + return std::format( + "starter_base_stats({}) = {}/{}/{}/{}/{}/{}, expected {}/{}/{}/{}/{}/{}", + row.slug, + stats.hp, stats.attack, stats.defense, stats.spatk, stats.spdef, stats.speed, + row.base_stats.hp, row.base_stats.attack, row.base_stats.defense, + row.base_stats.spatk, row.base_stats.spdef, row.base_stats.speed + ); + } + const double move_s = seconds_to_move_to_starter(row.starter); + if (std::abs(move_s - row.move_seconds) > 1e-9){ + return std::format( + "seconds_to_move_to_starter({}) = {}, expected {}", + row.slug, move_s, row.move_seconds + ); + } + } + return true; +} + + +UnitTestResult test_skip_buffer_and_landing_math(Logger&){ + if (bdsp_skip_buffer(0.0) != 750){ + return std::format("bdsp_skip_buffer(0) = {}, expected 750", bdsp_skip_buffer(0.0)); + } + if (bdsp_skip_buffer(100000.0) != 770){ + return std::format("bdsp_skip_buffer(100000) = {}, expected 770", bdsp_skip_buffer(100000.0)); + } + + const double sigma0 = bdsp_skip_landing_sigma(0.0); + if (std::abs(sigma0 - 67.0) > 1e-9){ + return std::format("bdsp_skip_landing_sigma(0) = {}, expected 67.0", sigma0); + } + + const uint64_t lake0 = bdsp_lake_advances_needed(0.0); + if (lake0 != 750 + 2 * 67){ + return std::format("bdsp_lake_advances_needed(0) = {}, expected {}", lake0, 750 + 2 * 67); + } + + // At 1,000,000 advances skipped: buffer = 750 + 200 = 950, + // sigma = sqrt(100^2 + 67^2) = sqrt(14489) ~ 120.37, 2*sigma = 240, total = 1190. + const uint64_t lake1m = bdsp_lake_advances_needed(1000000.0); + if (lake1m != 1190){ + return std::format("bdsp_lake_advances_needed(1e6) = {}, expected 1190", lake1m); + } + return true; +} + + +UnitTestResult test_aim_and_calibration(Logger& logger){ + if (aimed_advance(1000, 200, 0) != 1200){ + return "aimed_advance(1000, 200, 0) != 1200"; + } + if (aimed_advance(1000, 200, 3) != 1203){ + return "aimed_advance(1000, 200, 3) != 1203"; + } + if (press_for_advance(1203, 200, 3) != 1000){ + return "press_for_advance(1203, 200, 3) != 1000"; + } + + RngAim aim(3, 1.0); + if (aim.bias() != 0){ + return "initial bias != 0"; + } + if (aim.record_offset(logger, 2, true) || aim.record_offset(logger, 2, true)){ + return "should not adjust before 3 samples"; + } + if (!aim.record_offset(logger, 2, true)){ + return "expected adjustment on 3rd sample of +2"; + } + if (aim.bias() != 2){ + return std::format("bias after three +2 offsets = {}, expected 2", aim.bias()); + } + return true; +} + + +UnitTestResult test_attempt_loop_transitions(Logger&){ + BdspPokemonResult sample_target{}; + sample_target.ec = 0x12345678; + sample_target.pid = 0x87654321; + sample_target.nature = 3; + + // 1. Miss when below max_resets continues the loop. + { + StarterRngRunResult result; + BdspStarterAttemptResult miss{ + .outcome = BdspAttemptOutcome::Missed, + .shiny = false, + .target = sample_target, + .target_advance = 1500, + }; + if (resolve_starter_rng_step(miss, 1, 3, result)){ + return "expected loop to continue on miss 1 of 3"; + } + if (result.resets_used != 1 || result.target_advance != 1500){ + return "expected resets_used = 1 and target_advance = 1500 after miss"; + } + } + + // 2. Non-shiny hit stops with Outcome::HIT. + { + StarterRngRunResult result; + BdspStarterAttemptResult hit{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = false, + .target = sample_target, + .target_advance = 1505, + }; + if (!resolve_starter_rng_step(hit, 2, 3, result)){ + return "expected loop to terminate on non-shiny hit"; + } + if (result.outcome != StarterRngOutcome::HIT + || result.resets_used != 2 + || result.target_advance != 1505 + || result.target.pid != sample_target.pid + ){ + return "unexpected result fields on non-shiny hit"; + } + } + + // 3. Shiny hit stops with Outcome::SHINY. + { + StarterRngRunResult result; + BdspStarterAttemptResult shiny_hit{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = true, + .target = sample_target, + .target_advance = 2048, + }; + if (!resolve_starter_rng_step(shiny_hit, 1, 0, result)){ + return "expected loop to terminate on shiny hit"; + } + if (result.outcome != StarterRngOutcome::SHINY + || result.resets_used != 1 + || result.target_advance != 2048 + ){ + return "unexpected result fields on shiny hit"; + } + } + + // 4. Miss reaching max_resets stops with Outcome::OUT_OF_RESETS. + { + StarterRngRunResult result; + BdspStarterAttemptResult miss{ + .outcome = BdspAttemptOutcome::Missed, + .shiny = false, + .target = sample_target, + .target_advance = 1600, + }; + if (!resolve_starter_rng_step(miss, 3, 3, result)){ + return "expected loop to terminate when resets_used == max_resets"; + } + if (result.outcome != StarterRngOutcome::OUT_OF_RESETS || result.resets_used != 3){ + return "expected OUT_OF_RESETS on miss at reset limit"; + } + } + + // 5. Abandoned attempt reaching max_resets stops with Outcome::ABANDONED and preserves reason. + { + StarterRngRunResult result; + BdspStarterAttemptResult abandoned{ + .outcome = BdspAttemptOutcome::Abandoned, + .shiny = false, + .failure_reason = "no matching target within the allowed wait time", + }; + if (!resolve_starter_rng_step(abandoned, 1, 1, result)){ + return "expected loop to terminate on abandoned single attempt"; + } + if (result.outcome != StarterRngOutcome::ABANDONED + || result.resets_used != 1 + || result.last_failure_reason != "no matching target within the allowed wait time" + ){ + return "expected ABANDONED with failure_reason preserved"; + } + } + + return true; +} + + +struct StarterRngTestCase{ + std::string name; + std::function body; +}; + +class Test_StarterRng : public UnitTest{ +public: + explicit Test_StarterRng(StarterRngTestCase test_case) + : UnitTest("PokemonBDSP::StarterRng - " + test_case.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + StarterRngTestCase m_case; +}; + +const StarterRngTestCase STARTER_RNG_CASES[] = { + {"per-starter tables and timings", test_starter_tables}, + {"bedroom skip buffer and landing math", test_skip_buffer_and_landing_math}, + {"aim offset and calibration bias", test_aim_and_calibration}, + {"attempt loop outcome resolution", test_attempt_loop_transitions}, +}; + +} // namespace + + +void add_tests_StarterRng(UnitTestDatabase& database){ + for (const StarterRngTestCase& test_case : STARTER_RNG_CASES){ + database.add(test_case); + } +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h new file mode 100644 index 0000000000..be4c4fa2dd --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h @@ -0,0 +1,23 @@ +/* BDSP Starter RNG Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_StarterRng_Tests_H +#define PokemonAutomation_PokemonBDSP_StarterRng_Tests_H + +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +void add_tests_StarterRng(UnitTestDatabase& database); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp index 096b854679..3d9737b4ee 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp @@ -98,6 +98,26 @@ bool navigate_to_summary(SingleSwitchProgramEnvironment& env, ProControllerConte } +bool close_starter_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.log("Backing out of the summary screen to the overworld."); + bool back_at_menu = false; + for (size_t c = 0; c < 6 && !back_at_menu; c++){ + pbf_press_button(context, BUTTON_B, 160ms, 1000ms); + context.wait_for_all_requests(); + MenuWatcher menu(COLOR_RED, true); + back_at_menu = wait_until(env.console, context, 2s, {{menu}}) >= 0; + } + if (!back_at_menu){ + env.log("Never returned to the X menu from the summary.", COLOR_ORANGE); + return false; + } + pbf_press_button(context, BUTTON_X, 160ms, 1000ms); + context.wait_for_all_requests(); + env.log("Closed the menu."); + return true; +} + + bool read_observed_pokemon( SingleSwitchProgramEnvironment& env, ProControllerContext& context, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h index 34bf6d6307..0c1933c3d5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h @@ -23,6 +23,9 @@ bool open_starter_summary(SingleSwitchProgramEnvironment& env, ProControllerCont bool navigate_to_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context); +// Backs out of the Pokemon summary screen (3rd page -> party -> X menu -> overworld). +bool close_starter_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool read_observed_pokemon( SingleSwitchProgramEnvironment& env, ProControllerContext& context, diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 93f0bcb3ca..3e8fd0722b 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1979,6 +1979,10 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.h Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StateReidentifier.cpp Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StateReidentifier.h Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StateSolver.cpp From 21024393403394afe9a7b1fa26db3cbbebcfecb6 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:31:36 -0800 Subject: [PATCH 07/20] BDSP AutoStory: run Starter RNG in 00.02 Adds "Run Starter RNG in AutoStory" (off by default), "Starter RNG Maximum Resets", and "Starter RNG Stop Conditions" to BDSPAutoStory. When enabled, plan_story_run() replaces 00.02's Lake Verity steps (after 00.02's Verity Lakefront start save) with the starter_rng game action, which runs run_starter_rng_attempts() from VerityLakefront (17, 14) through the Starly battle and Rowan's scene, closes the menu on VerityLakefront (17, 14..15), and continues into 00.03. --- .../PokemonBDSP_AutoStory_Events_Lake.cpp | 11 ++ .../AutoStory/PokemonBDSP_AutoStory.cpp | 100 +++++++++++++++++- .../AutoStory/PokemonBDSP_AutoStory.h | 19 +++- .../PokemonBDSP_AutoStory_StoryExecutor.h | 2 + ...onBDSP_AutoStory_StorySimulation_Tests.cpp | 21 ++++ .../PokemonBDSP_AutoStory_StoryTable.cpp | 22 +++- .../PokemonBDSP_AutoStory_StoryTable.h | 7 +- ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 31 ++++++ .../PokemonBDSP_StarterRngAttempts.cpp | 8 ++ .../PokemonBDSP_StarterRngAttempts.h | 9 +- 10 files changed, 220 insertions(+), 10 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Lake.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Lake.cpp index 0c7841c7fe..2b4924116f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Lake.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Lake.cpp @@ -118,6 +118,16 @@ void azure_flute_if_there(VideoStream& stream, ProControllerContext& context){ +// 00.02 with Run Starter RNG in AutoStory: runs Starter RNG from the +// Verity Lakefront (17, 14) start save through the Starly battle and +// Rowan's scene, ending on the VerityLakefront overworld at (17, 14..15). +Pokemon::Outcome starter_rng(StoryExecutor& executor, Pokemon::RunState&, const Pokemon::StoryStep&){ + if (!executor.env().run_starter_rng){ + return Pokemon::outcome_failed("starter_rng_not_configured", "Starter RNG is not configured on StoryEnv."); + } + return executor.env().run_starter_rng(); +} + // 00.04: Dawn's catching tutorial on Route 202: her lines and her demo // battle, B for 70 s. void catch_tutorial(VideoStream& stream, ProControllerContext& context){ @@ -134,6 +144,7 @@ void add_lake_events(StoryEvents& events){ events.emplace("azure_flute_if_there", console_event(azure_flute_if_there)); events.emplace("starter_briefcase", console_event(starter_briefcase)); events.emplace("choose_starter", choose_starter); + events.emplace("starter_rng", starter_rng); events.emplace("catch_tutorial", console_event(catch_tutorial)); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp index 22a44c3177..d6b44b5c00 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp @@ -22,6 +22,7 @@ #include "Pokemon/Options/Pokemon_GameLanguages.h" #include "Pokemon/Options/Pokemon_StoryRunOptions.h" #include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" +#include "PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h" #include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_StoryLanguage.h" @@ -53,6 +54,18 @@ std::unique_ptr BDSPAutoStory_Descriptor::make_stats() const{ return std::make_unique(); } +BdspStarter bdsp_starter_for_choice(StarterChoice choice){ + switch (choice){ + case StarterChoice::TURTWIG: + return BdspStarter::Turtwig; + case StarterChoice::CHIMCHAR: + return BdspStarter::Chimchar; + case StarterChoice::PIPLUP: + return BdspStarter::Piplup; + } + return BdspStarter::Chimchar; +} + namespace{ @@ -123,6 +136,10 @@ std::string verify_story_checkpoint( } // namespace +BDSPAutoStory::~BDSPAutoStory(){ + RUN_STARTER_RNG.remove_listener(*this); +} + BDSPAutoStory::BDSPAutoStory() : RUN(checkpoint_database(), Pokemon::Gen8ToGen9Languages_Database()) , NEW_GAME_INTRO( @@ -149,7 +166,30 @@ BDSPAutoStory::BDSPAutoStory() LockMode::LOCK_WHILE_RUNNING, false ) + , RUN_STARTER_RNG( + "Run Starter RNG in AutoStory:
Off by default. In 00.02, run Starter RNG from the Verity Lakefront save " + "using the Starter RNG filter table below, then continue the story at 00.03.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , STARTER_RNG_MAX_RESETS( + "Starter RNG Maximum Resets:
0 means no limit.", + LockMode::LOCK_WHILE_RUNNING, + 0, 0, 9999 + ) + , STARTER_RNG_FILTERS( + "Starter RNG Stop Conditions:
Stop Starter RNG when the starter matches any row in this table.", + Pokemon::StatsHuntMiscFeatureFlags{ + /*action*/ false, /*shiny*/ true, /*gender*/ true, /*nature*/ true + } + ) + , NOTIFICATION_SHINY( + "Shiny Starter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) , NOTIFICATIONS({ + &NOTIFICATION_SHINY, &NOTIFICATION_PROGRAM_FINISH, &NOTIFICATION_ERROR_RECOVERABLE, &NOTIFICATION_ERROR_FATAL, @@ -160,7 +200,21 @@ BDSPAutoStory::BDSPAutoStory() PA_ADD_OPTION(PLAYER_NAME); PA_ADD_OPTION(STARTER); PA_ADD_OPTION(STOP_FOR_STARTER_RNG); + PA_ADD_OPTION(RUN_STARTER_RNG); + PA_ADD_OPTION(STARTER_RNG_MAX_RESETS); + PA_ADD_OPTION(STARTER_RNG_FILTERS); PA_ADD_OPTION(NOTIFICATIONS); + + BDSPAutoStory::on_config_value_changed(this); + RUN_STARTER_RNG.add_listener(*this); +} + +void BDSPAutoStory::on_config_value_changed(void*){ + const ConfigOptionState visibility = RUN_STARTER_RNG + ? ConfigOptionState::ENABLED + : ConfigOptionState::HIDDEN; + STARTER_RNG_MAX_RESETS.set_visibility(visibility); + STARTER_RNG_FILTERS.set_visibility(visibility); } namespace{ @@ -254,10 +308,52 @@ void BDSPAutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerCo // The reads that use text (Location.h) take the game's language from here. set_story_language(RUN.language()); - StoryEnv story{env, context, STARTER, PLAYER_NAME}; + StoryEnv story{env, context, STARTER, PLAYER_NAME, {}}; + RngAim starter_rng_aim; + const BdspRngFilterSnapshot starter_rng_filters = STARTER_RNG_FILTERS.make_snapshot(); + if (RUN_STARTER_RNG){ + story.run_starter_rng = [&]() -> Pokemon::Outcome{ + StarterRngSettings settings; + settings.language = RUN.language(); + settings.player_model = 1; + settings.start_point = BdspStartPoint::Lakefront; + settings.starter = bdsp_starter_for_choice(STARTER); + settings.filters = &starter_rng_filters; + settings.max_resets = STARTER_RNG_MAX_RESETS; + settings.reset_first = false; + settings.finish_battle_on_shiny = true; + settings.close_summary_after_read = true; + + uint64_t resets_logged = 0; + StarterRngAttemptIO io; + io.notification_shiny = &NOTIFICATION_SHINY; + io.notification_error = &NOTIFICATION_ERROR_RECOVERABLE; + io.on_reset = [&](){ + resets_logged++; + env.console.overlay().add_log(std::format("Starter RNG: try {}", resets_logged)); + }; + + const StarterRngRunResult result = run_starter_rng_attempts(env, context, settings, io, starter_rng_aim); + if (result.outcome == StarterRngOutcome::HIT || result.outcome == StarterRngOutcome::SHINY){ + env.log( + std::format( + "Starter RNG succeeded after {} reset(s) on advance {}: {}.", + result.resets_used, result.target_advance, result.target.to_string() + ), + COLOR_BLUE + ); + return Pokemon::outcome_ok(); + } + const std::string detail = result.last_failure_reason.empty() + ? std::format("Starter RNG stopped after {} reset(s) without hitting a target.", result.resets_used) + : result.last_failure_reason; + return Pokemon::outcome_failed("starter_rng_failed", detail); + }; + } StoryExecutor executor(story); const StoryRunPlan plan = plan_story_run( - checkpoints, first, last, StoryHandoffs{.starter_rng = STOP_FOR_STARTER_RNG} + checkpoints, first, last, + StoryHandoffs{.starter_rng = STOP_FOR_STARTER_RNG, .run_starter_rng = RUN_STARTER_RNG} ); executor.set_stop_rows(rows_that_stop(plan.rows)); // A start with a save always loads it first, so the run never walks diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h index 2640e20c8e..c7093d27ad 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h @@ -13,12 +13,16 @@ #ifndef PokemonAutomation_PokemonBDSP_AutoStory_H #define PokemonAutomation_PokemonBDSP_AutoStory_H +#include #include "Common/Cpp/Options/BooleanCheckBoxOption.h" #include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" #include "Common/Cpp/Options/StringOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "Pokemon/Options/Pokemon_StoryRunOptions.h" +#include "PokemonBDSP/Options/PokemonBDSP_RngFilter.h" +#include "PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.h" #include "PokemonBDSP_AutoStory_StoryExecutor.h" namespace PokemonAutomation{ @@ -26,6 +30,10 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ +// Maps AutoStory's starter option to Starter RNG's starter enum. +BdspStarter bdsp_starter_for_choice(StarterChoice choice); + + // Descriptor for the BDSP AutoStory single-switch program. class BDSPAutoStory_Descriptor : public SingleSwitchProgramDescriptor{ public: @@ -36,22 +44,29 @@ class BDSPAutoStory_Descriptor : public SingleSwitchProgramDescriptor{ // Single-switch program instance executing BDSP story automation. -class BDSPAutoStory : public SingleSwitchProgramInstance{ +class BDSPAutoStory : public SingleSwitchProgramInstance, public ConfigOption::Listener{ public: using Descriptor = BDSPAutoStory_Descriptor; + ~BDSPAutoStory(); BDSPAutoStory(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; private: + virtual void on_config_value_changed(void* object) override; + // The start and end checkpoints, attempts, checks and language. Pokemon::StoryRunOptions RUN; BooleanCheckBoxOption NEW_GAME_INTRO; StringOption PLAYER_NAME; EnumDropdownOption STARTER; - // The RNG program the run stops for (StoryHandoff). + // The RNG program the run stops for or runs in 00.02 (StoryHandoff). BooleanCheckBoxOption STOP_FOR_STARTER_RNG; + BooleanCheckBoxOption RUN_STARTER_RNG; + SimpleIntegerOption STARTER_RNG_MAX_RESETS; + BdspRngFilterTable STARTER_RNG_FILTERS; + EventNotificationOption NOTIFICATION_SHINY; EventNotificationsOption NOTIFICATIONS; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h index bc8e9b535e..65c74a2f02 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h @@ -22,6 +22,7 @@ #ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryExecutor_H #define PokemonAutomation_PokemonBDSP_AutoStory_StoryExecutor_H +#include #include #include #include @@ -78,6 +79,7 @@ struct StoryEnv{ ProControllerContext& context; StarterChoice starter = StarterChoice::CHIMCHAR; std::string player_name; + std::function run_starter_rng; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index 1ffcf63afc..ded2e4a211 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -463,6 +463,27 @@ UnitTestResult test_start_and_end(Logger&){ ){ return "Expected Starter RNG handoff to stop after 00.01 saved at VerityLakefront (17, 14):" + joined(handoff_sim.trace); } + // With Run Starter RNG in AutoStory on, 00.02 saves at the Verity + // Lakefront, runs 00.02/starter_rng, and chains into 00.03 and on. + Simulation in_program_sim; + const StoryRunPlan in_program_plan = plan_story_run( + story_checkpoints(), 0, 3, StoryHandoffs{.starter_rng = true, .run_starter_rng = true} + ); + Pokemon::Segment in_program_segment = make_story_segment(in_program_plan.rows, in_program_sim.game, in_program_sim.saved); + RunState in_program_state; + const Pokemon::SegmentReport in_program_report = Pokemon::run_segment( + {.from = "00.00", .to = "00.03"}, in_program_sim.policy, in_program_segment, hooks, in_program_state + ); + if (!in_program_report.completed || + in_program_sim.begun() != std::vector{"00.00", "00.01", "00.02", "00.03"} || + in_program_sim.count("save in 00.02") != 1 || + in_program_sim.count("card for 00.02: Verity Lakefront") != 1 || + in_program_sim.count("00.02/starter_rng") != 1 || + in_program_sim.count("00.02/choose_starter") != 0 + ){ + return "Expected 00.02 with Run Starter RNG in AutoStory to save at Verity Lakefront, run 00.02/starter_rng, and continue to 00.03:" + + joined(in_program_sim.trace); + } return true; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index b2ec0db15d..a962e2132b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -42,6 +42,22 @@ StoryCheckpoint with_handoff_save(StoryCheckpoint row){ return row; } +// `row` (00.02) with its Lake Verity steps replaced by the in-program +// Starter RNG action, keeping 00.02's start save at VerityLakefront (17, 14) +// and its end pose at VerityLakefront (17, 14..15). +StoryCheckpoint with_starter_rng_step(StoryCheckpoint row){ + Pokemon::StoryStep step; + step.kind = Pokemon::StoryStepKind::GAME; + step.name = std::string(STARTER_RNG_ACTION); + step.action = std::string(STARTER_RNG_ACTION); + step.why = "Starter RNG at Lake Verity through the Starly battle and Rowan's scene"; + if (!row.steps.empty()){ + step.pose_after = row.steps.back().pose_after; + } + row.steps = {std::move(step)}; + return row; +} + } // namespace @@ -56,11 +72,15 @@ StoryRunPlan plan_story_run( StoryRunPlan plan; for (size_t c = first; c <= last && c < checkpoints.size(); c++){ const StoryCheckpoint& row = checkpoints[c]; - if (row.id == STARTER_RNG_HANDOFF_ROW && handoffs.starter_rng){ + if (row.id == STARTER_RNG_HANDOFF_ROW && handoffs.starter_rng && !handoffs.run_starter_rng){ plan.rows.push_back(with_handoff_save(row)); plan.stop = StoryHandoff::STARTER_RNG; return plan; } + if (row.id == STARTER_RNG_CHECKPOINT_ROW && handoffs.run_starter_rng){ + plan.rows.push_back(with_starter_rng_step(row)); + continue; + } plan.rows.push_back(row); } return plan; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h index 77254e4532..8b35df520f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h @@ -36,6 +36,10 @@ inline constexpr std::string_view RUNNING_SHOES_STEP = "rowan_and_dawn"; // 00.01 ends at the Verity Lakefront (17, 14) facing north, where 00.02 and // Starter RNG (Start point: Verity Lakefront) start. inline constexpr std::string_view STARTER_RNG_HANDOFF_ROW = "00.01"; +// 00.02 is the Lake Verity starter and Starly battle checkpoint, which +// Run Starter RNG in AutoStory replaces with STARTER_RNG_ACTION. +inline constexpr std::string_view STARTER_RNG_CHECKPOINT_ROW = "00.02"; +inline constexpr std::string_view STARTER_RNG_ACTION = "starter_rng"; // An upstream RNG program the user may run part-way through the story. enum class StoryHandoff{ @@ -45,9 +49,10 @@ enum class StoryHandoff{ STARTER_RNG, }; -// The handoffs a run stops for (AutoStory's options). +// The handoffs a run stops for or runs in-program (AutoStory's options). struct StoryHandoffs{ bool starter_rng = false; + bool run_starter_rng = false; }; // What a run from table row `first` to `last` does. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index 57d504b136..d908c7219e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -24,6 +24,7 @@ #include "Data/PokemonBDSP_AutoStory_StoryMaps.h" #include "Actions/PokemonBDSP_AutoStory_Events.h" #include "Data/PokemonBDSP_AutoStory_WalkRules.h" +#include "PokemonBDSP_AutoStory.h" #include "PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_StoryTable_Tests.h" @@ -269,6 +270,36 @@ UnitTestResult test_plan_story_run_starter_rng(Logger&){ if (from_0002.stop != StoryHandoff::NONE || from_0002.rows.size() != 3 || from_0002.rows.front().id != "00.02"){ return "Expected a run starting at 00.02 to pass through without stopping for 00.01's handoff."; } + const StoryRunPlan in_program = plan_story_run( + table, 0, table.size() - 1, StoryHandoffs{.starter_rng = true, .run_starter_rng = true} + ); + if (in_program.stop != StoryHandoff::NONE || in_program.rows.size() != table.size()){ + return "With Run Starter RNG in AutoStory on, expected the full table with no handoff stop."; + } + const StoryCheckpoint& rng_row = in_program.rows[2]; + const std::vector rng_problems = Pokemon::lint_story_checkpoint(rng_row); + if (!rng_problems.empty()){ + return "00.02 with Run Starter RNG in AutoStory: " + rng_problems[0]; + } + if (rng_row.id != "00.02" || rng_row.saves_in != "Verity Lakefront" || rng_row.steps.size() != 1 || + rng_row.steps[0].kind != StoryStepKind::GAME || rng_row.steps[0].action != STARTER_RNG_ACTION || + !story_events().contains(rng_row.steps[0].action) + ){ + return "Expected 00.02 with Run Starter RNG in AutoStory to run the starter_rng game event after its Verity Lakefront start save."; + } + const std::optional rng_end = end_pose(rng_row); + const std::optional row0003_start = table[3].start + ? std::make_optional(Pokemon::pose_of(*table[3].start)) + : std::nullopt; + if (!rng_end || !row0003_start || Pokemon::to_string(*rng_end) != Pokemon::to_string(*row0003_start)){ + return "Expected 00.02's starter_rng step to end at 00.03's VerityLakefront (17, 14..15) start pose."; + } + if (bdsp_starter_for_choice(StarterChoice::TURTWIG) != BdspStarter::Turtwig || + bdsp_starter_for_choice(StarterChoice::CHIMCHAR) != BdspStarter::Chimchar || + bdsp_starter_for_choice(StarterChoice::PIPLUP) != BdspStarter::Piplup + ){ + return "Expected StarterChoice to map 1-to-1 to BdspStarter."; + } return true; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp index 1f15c57748..324bc2c2d9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp @@ -569,6 +569,14 @@ BdspStarterAttemptResult run_starter_rng_attempt( if (settings.finish_battle_on_shiny){ if (!clear_starter_battle(env, context)){ record_error(); + }else if (settings.close_summary_after_read){ + if (!open_menu(env, context)){ + record_error(); + }else{ + pbf_press_button(context, BUTTON_X, 160ms, 1000ms); + context.wait_for_all_requests(); + env.log("Closed the menu."); + } } } return BdspStarterAttemptResult{ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h index c1c7977194..ccd10e6dd5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h @@ -79,10 +79,11 @@ bool starter_wanted( // returns immediately while still inside the Starly battle at Lake Verity. // * When `finish_battle_on_shiny == true` (for AutoStory): // calls `clear_starter_battle(env, context)`, which mashes A until -// `EndBattleWatcher` detects the black-screen battle exit transition. -// The player ends up right at the start of the post-battle Lake Verity -// cutscene (Rowan's lines and walking out of the lake to VerityLakefront -// `(17, 14..15)`), ready for AutoStory's `after_starly` step. +// `EndBattleWatcher` detects the black-screen battle exit transition, and +// when `close_summary_after_read == true` also advances through Rowan's +// post-battle scene (`open_menu`) to `VerityLakefront (17, 14..15)` and +// closes the X menu so both `SHINY` and `HIT` end on the `VerityLakefront` +// overworld ready for checkpoint `00.03`. // - Non-shiny starter (`clear_starter_battle` + `read_observed_pokemon`): // 1. `clear_starter_battle(env, context)` mashes A until `EndBattleWatcher` // detects the end of the Starly battle. From 76f07262a9c0473b6e6fc75d37db40f984959576 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 17:42:31 -0800 Subject: [PATCH 08/20] BDSP AutoStory: red test: the Starter RNG handoff save checks the Verity Lakefront card --- .../PokemonBDSP_AutoStory_StorySimulation_Tests.cpp | 3 ++- .../PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 10 +++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index 1ffcf63afc..fb5a37423b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -458,10 +458,11 @@ UnitTestResult test_start_and_end(Logger&){ if (!handoff_report.completed || plan.stop != StoryHandoff::STARTER_RNG || handoff_sim.begun() != std::vector{"00.00", "00.01"} || handoff_sim.count("00.01/save_for_starter_rng") != 1 || + handoff_sim.count("card for 00.01: Verity Lakefront") != 1 || handoff_state.pose.map != "VerityLakefront" || Pokemon::tiles_of(handoff_state.pose) != std::vector{{17, 14}} ){ - return "Expected Starter RNG handoff to stop after 00.01 saved at VerityLakefront (17, 14):" + joined(handoff_sim.trace); + return std::format("Expected Starter RNG handoff to stop after 00.01 saved at VerityLakefront (17, 14), checking the Verity Lakefront card:{}", joined(handoff_sim.trace)); } return true; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index 57d504b136..d458890c47 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -249,13 +249,21 @@ UnitTestResult test_plan_story_run_starter_rng(Logger&){ const StoryCheckpoint& lakefront_row = handoff.rows.back(); const std::vector problems = Pokemon::lint_story_checkpoint(lakefront_row); if (!problems.empty()){ - return "00.01 with Starter RNG handoff save: " + problems[0]; + return std::format("00.01 with Starter RNG handoff save: {}", problems[0]); } if (lakefront_row.steps.empty() || lakefront_row.steps.back().kind != StoryStepKind::SAVE || lakefront_row.steps.back().name != "save_for_starter_rng" ){ return "Expected 00.01 with Starter RNG handoff to end with save_for_starter_rng."; } + // The save card is checked as every other start save is: it must name + // 00.02's map. + if (lakefront_row.steps.back().action != table[2].saves_in || table[2].saves_in.empty()){ + return std::format( + "Expected the handoff save to check the card for \"{}\", got \"{}\".", + table[2].saves_in, lakefront_row.steps.back().action + ); + } const std::optional end = end_pose(lakefront_row); const std::optional next_start = table[2].start ? std::make_optional(Pokemon::pose_of(*table[2].start)) From 1e40b62538cd45321d6103b2e870cba9abaa40f5 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 17:42:52 -0800 Subject: [PATCH 09/20] BDSP AutoStory: the Starter RNG handoff save checks the card; one handoff text; no handoff in verify mode --- .../AutoStory/PokemonBDSP_AutoStory.cpp | 21 ++++++++++++------- .../PokemonBDSP_AutoStory_StoryTable.cpp | 10 ++++++--- .../PokemonBDSP_AutoStory_StoryTable.h | 4 +++- 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp index 22a44c3177..02e0c3117a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include "CommonFramework/Exceptions/OperationFailedException.h" #include "CommonFramework/Notifications/ProgramNotifications.h" #include "CommonFramework/VideoPipeline/VideoOverlay.h" @@ -56,6 +57,14 @@ std::unique_ptr BDSPAutoStory_Descriptor::make_stats() const{ namespace{ +// What the user does around Starter RNG when the run stops for it: the +// option's help and the run's closing message. +constexpr std::string_view STARTER_RNG_HANDOFF_TEXT = + "At the end of 00.01 save at the Verity Lakefront (17, 14), facing Lake Verity's entrance, and stop. " + "Run the Starter RNG program from that save (Start point: Verity Lakefront). " + "When it is done, close the Summary page and the menu, let Rowan's scene finish so the player stands " + "on the Verity Lakefront overworld, save, and start AutoStory at 00.03."; + // The start and end dropdowns' entries: segments 00 and 01 joined, 00.00 // to 01.11. The options hold a reference to it. const StringSelectDatabase& checkpoint_database(){ @@ -143,9 +152,7 @@ BDSPAutoStory::BDSPAutoStory() StarterChoice::CHIMCHAR ) , STOP_FOR_STARTER_RNG( - "Stop for Starter RNG:
Off by default. At the end of 00.01, save at the Verity Lakefront (17, 14) " - "facing Lake Verity's entrance and stop, where the Starter RNG program starts (Start point: Verity Lakefront). " - "After Starter RNG, let Rowan's scene finish out of the lake, save at the Verity Lakefront, and start AutoStory at 00.03.", + std::format("Stop for Starter RNG:
Off by default. {}", STARTER_RNG_HANDOFF_TEXT), LockMode::LOCK_WHILE_RUNNING, false ) @@ -268,6 +275,9 @@ void BDSPAutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerCo if (new_game && RUN.VERIFY.policy()){ throw UserSetupError(env.console, "Verify mode reloads the start's save between runs: turn off \"Start a new game first\"."); } + if (plan.stop != StoryHandoff::NONE && RUN.VERIFY.policy()){ + throw UserSetupError(env.console, "Verify mode repeats the start's checkpoint, and its extra save at the end of 00.01 would overwrite the Verity Lakefront save: turn off \"Stop for Starter RNG\"."); + } std::set saved = saved_before_the_run(plan.rows, 0, start); Pokemon::Segment segment = make_story_segment(plan.rows, executor, saved); Pokemon::StoryGameHooks game = story_game(env, context); @@ -282,10 +292,7 @@ void BDSPAutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerCo Pokemon::SegmentRange{plan.rows.front().id, plan.rows.back().id}, RUN.policy(), segment, game, state, env ); if (plan.stop == StoryHandoff::STARTER_RNG){ - const std::string handoff = - "Stopped for Starter RNG: saved at the Verity Lakefront (17, 14), facing Lake Verity's entrance. " - "Run Starter RNG now (Start point: Verity Lakefront). " - "After Starter RNG, let Rowan's scene finish out of the lake, save at the Verity Lakefront, and start AutoStory at 00.03."; + const std::string handoff = std::format("Stopped for Starter RNG. {}", STARTER_RNG_HANDOFF_TEXT); env.log(handoff, COLOR_BLUE); send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, handoff); return; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index b2ec0db15d..4120e94c98 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -21,11 +21,14 @@ namespace{ // `row` with a save appended at its end, where the next checkpoint starts: // in BDSP rows normally save at their start, so a run that stops after -// 00.01 for Starter RNG makes 00.02's Lakefront save before stopping. -StoryCheckpoint with_handoff_save(StoryCheckpoint row){ +// 00.01 for Starter RNG makes 00.02's Lakefront save before stopping. As +// every start save does, it checks that the save card names `saves_in` +// (the next row's), and stops the program if not. +StoryCheckpoint with_handoff_save(StoryCheckpoint row, const std::string& saves_in){ Pokemon::StoryStep save; save.kind = Pokemon::StoryStepKind::SAVE; save.name = "save_for_starter_rng"; + save.action = saves_in; save.why = "the save at the Verity Lakefront where Starter RNG starts"; if (!row.steps.empty()){ const Pokemon::StoryStep& last = row.steps.back(); @@ -57,7 +60,8 @@ StoryRunPlan plan_story_run( for (size_t c = first; c <= last && c < checkpoints.size(); c++){ const StoryCheckpoint& row = checkpoints[c]; if (row.id == STARTER_RNG_HANDOFF_ROW && handoffs.starter_rng){ - plan.rows.push_back(with_handoff_save(row)); + const std::string saves_in = c + 1 < checkpoints.size() ? checkpoints[c + 1].saves_in : std::string(); + plan.rows.push_back(with_handoff_save(row, saves_in)); plan.stop = StoryHandoff::STARTER_RNG; return plan; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h index 77254e4532..d0027c1959 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h @@ -52,7 +52,9 @@ struct StoryHandoffs{ // What a run from table row `first` to `last` does. struct StoryRunPlan{ - // The checkpoints to run, in order. + // The checkpoints to run, in order. Copies, not pointers: a row the plan + // changes (the handoff save) must not change the table, and the run's + // steps capture these rows, which outlive the call. std::vector rows; // NONE: the run ends after `rows`. STARTER_RNG: the run stops after // `rows`, the last of which (00.01) saves at the Verity Lakefront. From 5824ff641533928a724832f226c9a79363abe781 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 17:43:14 -0800 Subject: [PATCH 10/20] BDSP AutoStory: document plan_story_run for Code Health --- .../Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h index d0027c1959..df9f82c8de 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h @@ -65,9 +65,7 @@ struct StoryRunPlan{ // run with `handoffs` takes them: a run that reaches 00.01 with // `handoffs.starter_rng` on saves at the Verity Lakefront at the end of // 00.01 and stops there for Starter RNG. -StoryRunPlan plan_story_run( - const std::vector& checkpoints, size_t first, size_t last, const StoryHandoffs& handoffs = {} -); +StoryRunPlan plan_story_run(const std::vector& table, size_t first, size_t last, const StoryHandoffs& handoffs = {}); From d141c1a9990a62980cd1ce4b87024cbc1c9f13fa Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 17:43:21 -0800 Subject: [PATCH 11/20] BDSP AutoStory: plan_story_run comment names its parameter --- .../Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h index df9f82c8de..487e7aafb3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h @@ -61,7 +61,7 @@ struct StoryRunPlan{ StoryHandoff stop = StoryHandoff::NONE; }; -// The rows of `checkpoints` from `first` to `last`, both inclusive, as a +// The rows of `table` from `first` to `last`, both inclusive, as a // run with `handoffs` takes them: a run that reaches 00.01 with // `handoffs.starter_rng` on saves at the Verity Lakefront at the end of // 00.01 and stops there for Starter RNG. From bf6e870aa3bf41ec5309a52d2b965271203c14a9 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 17:43:59 -0800 Subject: [PATCH 12/20] BDSP Starter RNG: red test: the default filter row is a shiny of any nature --- .../PokemonBDSP_StarterRng_Tests.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp index 09d19104c2..c8cfd5182c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp @@ -259,6 +259,40 @@ UnitTestResult test_attempt_loop_transitions(Logger&){ } +// The default filter row: a table that has it stops for a shiny of any +// nature and gender, and no other starter; an empty table never stops, which +// is why a caller must seed it. +UnitTestResult test_default_shiny_row(Logger&){ + BdspRngFilterTable empty("Filters", Pokemon::StatsHuntMiscFeatureFlags{false, true, true, true}); + BdspPokemonResult shiny{}; + shiny.shiny = BdspShiny::Star; + shiny.nature = 7; + BdspPokemonResult plain{}; + plain.nature = 7; + if (starter_wanted(empty.make_snapshot(), shiny)){ + return "an empty filter table must not match a shiny"; + } + + BdspRngFilterTable table("Filters", Pokemon::StatsHuntMiscFeatureFlags{false, true, true, true}); + set_default_shiny_row(table); + if (table.current_rows() != 1){ + return std::format("expected one default row, got {}", table.current_rows()); + } + const BdspRngFilterSnapshot snapshot = table.make_snapshot(); + if (!starter_wanted(snapshot, shiny)){ + return "the default row must match a shiny of any nature"; + } + shiny.nature = 20; + if (!starter_wanted(snapshot, shiny)){ + return "the default row must match a shiny of another nature"; + } + if (starter_wanted(snapshot, plain)){ + return "the default row must not match a non-shiny"; + } + return true; +} + + struct StarterRngTestCase{ std::string name; std::function body; @@ -288,6 +322,7 @@ const StarterRngTestCase STARTER_RNG_CASES[] = { {"bedroom skip buffer and landing math", test_skip_buffer_and_landing_math}, {"aim offset and calibration bias", test_aim_and_calibration}, {"attempt loop outcome resolution", test_attempt_loop_transitions}, + {"default filter row is shiny of any nature", test_default_shiny_row}, }; } // namespace From b0bb8841e5890ef427eb5a7ff2bdf57516495132 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 17:44:09 -0800 Subject: [PATCH 13/20] BDSP Starter RNG: set_default_shiny_row seeds the filter table; the standalone uses it --- .../Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp | 8 ++++++++ .../Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h | 6 ++++++ .../Programs/RngManipulation/PokemonBDSP_StarterRng.cpp | 9 +-------- 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp index eeabbcea8d..4db0232e56 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp @@ -157,6 +157,14 @@ std::vector BdspRngFilterTable::make_header() const{ BdspRngFilterSnapshot BdspRngFilterTable::make_snapshot() const{ return BdspRngFilterSnapshot(copy_snapshot()); } +void set_default_shiny_row(BdspRngFilterTable& table){ + std::vector> defaults; + auto row = std::make_unique(table); + row->misc.shiny.set(StatsHuntShinyFilter::Shiny); + defaults.emplace_back(std::move(row)); + table.set_default(std::move(defaults)); + table.restore_defaults(); +} StatsHuntAction BdspRngFilterTable::get_action( bool shiny, StatsHuntGenderFilter gender, diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h index d9d66aff06..652bc73753 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h @@ -94,6 +94,12 @@ class BdspRngFilterTable : public EditableTableOption_t{ }; +// Makes the table's default, and its current content, one row: a shiny of +// any nature, gender and IVs. An empty table matches nothing, so a program +// that stops on a match must seed its table with this. +void set_default_shiny_row(BdspRngFilterTable& table); + + } } } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp index 1031be4513..1d19e14261 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp @@ -127,14 +127,7 @@ StarterRng::StarterRng() &NOTIFICATION_ERROR_FATAL, }) { - { - std::vector> defaults; - auto row = std::make_unique(FILTERS); - row->misc.shiny.set(StatsHuntShinyFilter::Shiny); - defaults.emplace_back(std::move(row)); - FILTERS.set_default(std::move(defaults)); - FILTERS.restore_defaults(); - } + set_default_shiny_row(FILTERS); PA_ADD_OPTION(LANGUAGE); PA_ADD_OPTION(PLAYER_MODEL); From fe6aa2314444fd8eb2dd3fd97bd67c5aca351c64 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 17:47:45 -0800 Subject: [PATCH 14/20] BDSP AutoStory: Starter RNG default row, player model option, fatal on failure, unsettled shiny stops, program split --- .../AutoStory/PokemonBDSP_AutoStory.cpp | 126 ++++--------- .../AutoStory/PokemonBDSP_AutoStory.h | 23 ++- .../PokemonBDSP_AutoStory_StarterRng.cpp | 170 ++++++++++++++++++ .../PokemonBDSP_AutoStory_StarterRng.h | 87 +++++++++ .../PokemonBDSP_AutoStory_StoryTable.cpp | 1 + .../PokemonBDSP_AutoStory_StoryTable.h | 5 + ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 84 +++++++++ .../PokemonBDSP_StarterRngAttempts.cpp | 5 + .../PokemonBDSP_StarterRngAttempts.h | 6 + .../PokemonBDSP_StarterRng_Tests.cpp | 22 +++ SerialPrograms/cmake/SourceFiles.cmake | 2 + 11 files changed, 426 insertions(+), 105 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp index 2f2476ddfa..c1866f8105 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp @@ -55,18 +55,6 @@ std::unique_ptr BDSPAutoStory_Descriptor::make_stats() const{ return std::make_unique(); } -BdspStarter bdsp_starter_for_choice(StarterChoice choice){ - switch (choice){ - case StarterChoice::TURTWIG: - return BdspStarter::Turtwig; - case StarterChoice::CHIMCHAR: - return BdspStarter::Chimchar; - case StarterChoice::PIPLUP: - return BdspStarter::Piplup; - } - return BdspStarter::Chimchar; -} - namespace{ @@ -91,9 +79,11 @@ const StringSelectDatabase& checkpoint_database(){ return database; } -std::set rows_that_stop(const std::vector& rows){ - std::set ids; - for (const StoryCheckpoint& row : rows){ +// The rows whose failure ends the program: the rows that save nothing and +// retry nothing, and the plan's own (Starter RNG's, which resets by itself). +std::set rows_that_stop(const StoryRunPlan& plan){ + std::set ids = plan.fatal_rows; + for (const StoryCheckpoint& row : plan.rows){ if (row.on_failure == StoryFailure::STOP){ ids.insert(row.id); } @@ -146,7 +136,7 @@ std::string verify_story_checkpoint( BDSPAutoStory::~BDSPAutoStory(){ - RUN_STARTER_RNG.remove_listener(*this); + STARTER_RNG.RUN.remove_listener(*this); } BDSPAutoStory::BDSPAutoStory() @@ -169,34 +159,15 @@ BDSPAutoStory::BDSPAutoStory() StarterChoice::CHIMCHAR ) , STOP_FOR_STARTER_RNG( - std::format("Stop for Starter RNG:
Off by default. {}", STARTER_RNG_HANDOFF_TEXT), + std::format( + "Stop for Starter RNG:
Off by default. Ignored while Run Starter RNG in AutoStory is on. {}", + STARTER_RNG_HANDOFF_TEXT + ), LockMode::LOCK_WHILE_RUNNING, false ) - , RUN_STARTER_RNG( - "Run Starter RNG in AutoStory:
Off by default. In 00.02, run Starter RNG from the Verity Lakefront save " - "using the Starter RNG filter table below, then continue the story at 00.03.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , STARTER_RNG_MAX_RESETS( - "Starter RNG Maximum Resets:
0 means no limit.", - LockMode::LOCK_WHILE_RUNNING, - 0, 0, 9999 - ) - , STARTER_RNG_FILTERS( - "Starter RNG Stop Conditions:
Stop Starter RNG when the starter matches any row in this table.", - Pokemon::StatsHuntMiscFeatureFlags{ - /*action*/ false, /*shiny*/ true, /*gender*/ true, /*nature*/ true - } - ) - , NOTIFICATION_SHINY( - "Shiny Starter", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) , NOTIFICATIONS({ - &NOTIFICATION_SHINY, + &STARTER_RNG.NOTIFICATION_SHINY, &NOTIFICATION_PROGRAM_FINISH, &NOTIFICATION_ERROR_RECOVERABLE, &NOTIFICATION_ERROR_FATAL, @@ -207,21 +178,22 @@ BDSPAutoStory::BDSPAutoStory() PA_ADD_OPTION(PLAYER_NAME); PA_ADD_OPTION(STARTER); PA_ADD_OPTION(STOP_FOR_STARTER_RNG); - PA_ADD_OPTION(RUN_STARTER_RNG); - PA_ADD_OPTION(STARTER_RNG_MAX_RESETS); - PA_ADD_OPTION(STARTER_RNG_FILTERS); + PA_ADD_OPTION(STARTER_RNG.RUN); + PA_ADD_OPTION(STARTER_RNG.PLAYER_MODEL); + PA_ADD_OPTION(STARTER_RNG.MAX_RESETS); + PA_ADD_OPTION(STARTER_RNG.FILTERS); PA_ADD_OPTION(NOTIFICATIONS); BDSPAutoStory::on_config_value_changed(this); - RUN_STARTER_RNG.add_listener(*this); + STARTER_RNG.RUN.add_listener(*this); } +// Run Starter RNG takes precedence over Stop for Starter RNG: the stop +// option is greyed out while it is on, and the plan ignores it. void BDSPAutoStory::on_config_value_changed(void*){ - const ConfigOptionState visibility = RUN_STARTER_RNG - ? ConfigOptionState::ENABLED - : ConfigOptionState::HIDDEN; - STARTER_RNG_MAX_RESETS.set_visibility(visibility); - STARTER_RNG_FILTERS.set_visibility(visibility); + const bool run_in_story = STARTER_RNG.RUN; + STARTER_RNG.set_details_visible(run_in_story); + STOP_FOR_STARTER_RNG.set_visibility(run_in_story ? ConfigOptionState::DISABLED : ConfigOptionState::ENABLED); } namespace{ @@ -316,57 +288,27 @@ void BDSPAutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerCo set_story_language(RUN.language()); StoryEnv story{env, context, STARTER, PLAYER_NAME, {}}; - RngAim starter_rng_aim; - const BdspRngFilterSnapshot starter_rng_filters = STARTER_RNG_FILTERS.make_snapshot(); - if (RUN_STARTER_RNG){ - story.run_starter_rng = [&]() -> Pokemon::Outcome{ - StarterRngSettings settings; - settings.language = RUN.language(); - settings.player_model = 1; - settings.start_point = BdspStartPoint::Lakefront; - settings.starter = bdsp_starter_for_choice(STARTER); - settings.filters = &starter_rng_filters; - settings.max_resets = STARTER_RNG_MAX_RESETS; - settings.reset_first = false; - settings.finish_battle_on_shiny = true; - settings.close_summary_after_read = true; - - uint64_t resets_logged = 0; - StarterRngAttemptIO io; - io.notification_shiny = &NOTIFICATION_SHINY; - io.notification_error = &NOTIFICATION_ERROR_RECOVERABLE; - io.on_reset = [&](){ - resets_logged++; - env.console.overlay().add_log(std::format("Starter RNG: try {}", resets_logged)); - }; - - const StarterRngRunResult result = run_starter_rng_attempts(env, context, settings, io, starter_rng_aim); - if (result.outcome == StarterRngOutcome::HIT || result.outcome == StarterRngOutcome::SHINY){ - env.log( - std::format( - "Starter RNG succeeded after {} reset(s) on advance {}: {}.", - result.resets_used, result.target_advance, result.target.to_string() - ), - COLOR_BLUE - ); - return Pokemon::outcome_ok(); - } - const std::string detail = result.last_failure_reason.empty() - ? std::format("Starter RNG stopped after {} reset(s) without hitting a target.", result.resets_used) - : result.last_failure_reason; - return Pokemon::outcome_failed("starter_rng_failed", detail); - }; + if (STARTER_RNG.RUN){ + story.run_starter_rng = make_starter_rng_hook( + env, context, STARTER_RNG, STARTER_RNG.config(RUN.language(), STARTER), NOTIFICATION_ERROR_RECOVERABLE + ); } StoryExecutor executor(story); const StoryRunPlan plan = plan_story_run( checkpoints, first, last, - StoryHandoffs{.starter_rng = STOP_FOR_STARTER_RNG, .run_starter_rng = RUN_STARTER_RNG} + StoryHandoffs{.starter_rng = STOP_FOR_STARTER_RNG, .run_starter_rng = STARTER_RNG.RUN} ); - executor.set_stop_rows(rows_that_stop(plan.rows)); + executor.set_stop_rows(rows_that_stop(plan)); + run_plan(env, context, executor, plan, first == 0 && NEW_GAME_INTRO); +} + +void BDSPAutoStory::run_plan( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryExecutor& executor, const StoryRunPlan& plan, bool new_game +){ // A start with a save always loads it first, so the run never walks // from wherever the game was left (console B, 2026-11-11: a run from // 00.04b walked from 00.04d's position). - const bool new_game = first == 0 && NEW_GAME_INTRO; const Pokemon::StoryStart start = new_game ? Pokemon::StoryStart::NEW_GAME : Pokemon::StoryStart::FROM_SAVE; if (new_game && RUN.VERIFY.policy()){ throw UserSetupError(env.console, "Verify mode reloads the start's save between runs: turn off \"Start a new game first\"."); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h index c7093d27ad..1e292c101e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h @@ -13,27 +13,21 @@ #ifndef PokemonAutomation_PokemonBDSP_AutoStory_H #define PokemonAutomation_PokemonBDSP_AutoStory_H -#include #include "Common/Cpp/Options/BooleanCheckBoxOption.h" #include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" #include "Common/Cpp/Options/StringOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "Pokemon/Options/Pokemon_StoryRunOptions.h" -#include "PokemonBDSP/Options/PokemonBDSP_RngFilter.h" -#include "PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.h" +#include "PokemonBDSP_AutoStory_StarterRng.h" #include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryTable.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonBDSP{ -// Maps AutoStory's starter option to Starter RNG's starter enum. -BdspStarter bdsp_starter_for_choice(StarterChoice choice); - - // Descriptor for the BDSP AutoStory single-switch program. class BDSPAutoStory_Descriptor : public SingleSwitchProgramDescriptor{ public: @@ -55,18 +49,21 @@ class BDSPAutoStory : public SingleSwitchProgramInstance, public ConfigOption::L private: virtual void on_config_value_changed(void* object) override; + // Starts the plan's story and runs it to its end or its stop. + void run_plan( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryExecutor& executor, const StoryRunPlan& plan, bool new_game + ); + // The start and end checkpoints, attempts, checks and language. Pokemon::StoryRunOptions RUN; BooleanCheckBoxOption NEW_GAME_INTRO; StringOption PLAYER_NAME; EnumDropdownOption STARTER; - // The RNG program the run stops for or runs in 00.02 (StoryHandoff). + // The RNG program the run stops for (StoryHandoff), or runs in 00.02. BooleanCheckBoxOption STOP_FOR_STARTER_RNG; - BooleanCheckBoxOption RUN_STARTER_RNG; - SimpleIntegerOption STARTER_RNG_MAX_RESETS; - BdspRngFilterTable STARTER_RNG_FILTERS; + StoryStarterRngOptions STARTER_RNG; - EventNotificationOption NOTIFICATION_SHINY; EventNotificationsOption NOTIFICATIONS; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp new file mode 100644 index 0000000000..6bb5c7e2ef --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp @@ -0,0 +1,170 @@ +/* BDSP AutoStory: Starter RNG + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonBDSP_AutoStory_StarterRng.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +BdspStarter bdsp_starter_for_choice(StarterChoice choice){ + switch (choice){ + case StarterChoice::TURTWIG: + return BdspStarter::Turtwig; + case StarterChoice::CHIMCHAR: + return BdspStarter::Chimchar; + case StarterChoice::PIPLUP: + return BdspStarter::Piplup; + } + return BdspStarter::Chimchar; +} + + +StoryStarterRngOptions::StoryStarterRngOptions() + : RUN( + "Run Starter RNG in AutoStory:
Off by default. In 00.02, run Starter RNG from the Verity Lakefront " + "save using the stop conditions below, then continue the story at 00.03. " + "Takes precedence over Stop for Starter RNG. If it fails the program stops: it does not reload 00.02.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , MAX_RESETS( + "Starter RNG Maximum Resets:
0 means no limit.", + LockMode::LOCK_WHILE_RUNNING, + 0, 0, 9999 + ) + , FILTERS( + "Starter RNG Stop Conditions:
Stop Starter RNG when the starter matches any row in this table.", + Pokemon::StatsHuntMiscFeatureFlags{ + /*action*/ false, /*shiny*/ true, /*gender*/ true, /*nature*/ true + } + ) + , NOTIFICATION_SHINY( + "Shiny Starter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) +{ + set_default_shiny_row(FILTERS); +} + +void StoryStarterRngOptions::set_details_visible(bool visible){ + const ConfigOptionState state = visible ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN; + PLAYER_MODEL.set_visibility(state); + MAX_RESETS.set_visibility(state); + FILTERS.set_visibility(state); +} + +StoryStarterRngConfig StoryStarterRngOptions::config(Language language, StarterChoice starter) const{ + return StoryStarterRngConfig{ + .language = language, + .player_model = PLAYER_MODEL.model_number(), + .starter = starter, + .max_resets = MAX_RESETS, + }; +} + + +StarterRngSettings make_starter_rng_settings(const StoryStarterRngConfig& config, const BdspRngFilterSnapshot& filters){ + StarterRngSettings settings; + settings.language = config.language; + settings.player_model = config.player_model; + settings.start_point = BdspStartPoint::Lakefront; + settings.starter = bdsp_starter_for_choice(config.starter); + settings.filters = &filters; + settings.max_resets = config.max_resets; + settings.reset_first = false; + settings.finish_battle_on_shiny = true; + settings.close_summary_after_read = true; + return settings; +} + +std::string starter_rng_failure(const StarterRngRunResult& result){ + switch (result.outcome){ + case StarterRngOutcome::HIT: + return ""; + case StarterRngOutcome::SHINY: + if (!result.settled){ + return "Caught a shiny starter, but the Starly battle or Rowan's scene did not finish: " + "stopped with the shiny in the party; the game is not on the Verity Lakefront overworld."; + } + return ""; + case StarterRngOutcome::OUT_OF_RESETS: + case StarterRngOutcome::ABANDONED: + break; + } + if (result.last_failure_reason.empty()){ + return std::format("Starter RNG stopped after {} reset(s) without hitting a target.", result.resets_used); + } + return result.last_failure_reason; +} + + +namespace{ + +// What the hook keeps between its calls: the filters, copied once so that +// edits made while running do not apply, and the aim that Starter RNG's +// calibration builds up across them. +struct StarterRngHookState{ + StarterRngHookState(const StoryStarterRngOptions& options, const StoryStarterRngConfig& config) + : filters(options.FILTERS.make_snapshot()) + , settings(make_starter_rng_settings(config, filters)) + {} + + RngAim aim; + BdspRngFilterSnapshot filters; + StarterRngSettings settings; +}; + +} // namespace + + +std::function make_starter_rng_hook( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryStarterRngOptions& options, const StoryStarterRngConfig& config, + EventNotificationOption& error_notification +){ + if (options.FILTERS.current_rows() == 0){ + throw UserSetupError( + env.console, + "Starter RNG Stop Conditions is empty, so no starter would ever match: add a row, such as a shiny of any nature." + ); + } + std::shared_ptr state = std::make_shared(options, config); + return [&env, &context, &options, &error_notification, state]() -> Pokemon::Outcome{ + uint64_t resets_logged = 0; + StarterRngAttemptIO io; + io.notification_shiny = &options.NOTIFICATION_SHINY; + io.notification_error = &error_notification; + io.on_reset = [&]{ + resets_logged++; + env.console.overlay().add_log(std::format("Starter RNG: try {}", resets_logged)); + }; + const StarterRngRunResult result = run_starter_rng_attempts(env, context, state->settings, io, state->aim); + const std::string failure = starter_rng_failure(result); + if (!failure.empty()){ + throw_and_log(env.logger(), ErrorReportMode::SEND_ERROR_REPORT, failure); + } + env.log( + std::format( + "Starter RNG succeeded after {} reset(s) on advance {}: {}.", + result.resets_used, result.target_advance, result.target.to_string() + ), + COLOR_BLUE + ); + return Pokemon::outcome_ok(); + }; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h new file mode 100644 index 0000000000..d048774e37 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h @@ -0,0 +1,87 @@ +/* BDSP AutoStory: Starter RNG + * + * From: https://github.com/PokemonAutomation/ + * + * Run Starter RNG in AutoStory: its options, and the action that 00.02 runs + * in place of its Lake Verity steps (the Starter RNG program's reset loop, + * PokemonBDSP_StarterRngAttempts.h, called from the story). + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StarterRng_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StarterRng_H + +#include +#include +#include +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "Pokemon/AutoStory/Pokemon_StoryOutcome.h" +#include "PokemonBDSP/Options/PokemonBDSP_PlayerModelOption.h" +#include "PokemonBDSP/Options/PokemonBDSP_RngFilter.h" +#include "PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h" +#include "PokemonBDSP_AutoStory_StoryExecutor.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Maps AutoStory's starter option to Starter RNG's starter enum. +BdspStarter bdsp_starter_for_choice(StarterChoice choice); + + +// What the story tells Starter RNG about the game it plays. +struct StoryStarterRngConfig{ + Language language = Language::English; + // The player's appearance, 1 to 8: the lake's eye templates depend on it. + uint8_t player_model = 1; + StarterChoice starter = StarterChoice::CHIMCHAR; + uint16_t max_resets = 0; +}; + + +// AutoStory's options for Starter RNG. Only RUN is always shown; the rest +// show while it is on. +class StoryStarterRngOptions{ +public: + StoryStarterRngOptions(); + + void set_details_visible(bool visible); + // The options' values, for a story in `language` with `starter`. + StoryStarterRngConfig config(Language language, StarterChoice starter) const; + +public: + BooleanCheckBoxOption RUN; + PlayerModelOption PLAYER_MODEL; + SimpleIntegerOption MAX_RESETS; + BdspRngFilterTable FILTERS; + EventNotificationOption NOTIFICATION_SHINY; +}; + + +// Starter RNG's settings for the run in 00.02: from the Verity Lakefront +// save, through the Starly battle and Rowan's scene on a shiny or not, to +// the Lakefront overworld with the menu closed. +StarterRngSettings make_starter_rng_settings(const StoryStarterRngConfig& config, const BdspRngFilterSnapshot& filters); + +// Why the story cannot go on after Starter RNG ended as `result`; empty if +// it can: a starter was caught and the game stands on the Lakefront. +std::string starter_rng_failure(const StarterRngRunResult& result); + +// The action 00.02 runs. Throws a UserSetupError now if the filter table is +// empty. The action itself throws when Starter RNG fails, so that no row +// retry reruns the whole reset loop. +std::function make_starter_rng_hook( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryStarterRngOptions& options, const StoryStarterRngConfig& config, + EventNotificationOption& error_notification +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index ac2ecc49ac..e53264b5af 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -83,6 +83,7 @@ StoryRunPlan plan_story_run( } if (row.id == STARTER_RNG_CHECKPOINT_ROW && handoffs.run_starter_rng){ plan.rows.push_back(with_starter_rng_step(row)); + plan.fatal_rows.insert(row.id); continue; } plan.rows.push_back(row); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h index 38e8697726..90529ab85c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h @@ -14,6 +14,8 @@ #ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryTable_H #define PokemonAutomation_PokemonBDSP_AutoStory_StoryTable_H +#include +#include #include #include #include "PokemonBDSP_AutoStory_StoryExecutor.h" @@ -64,6 +66,9 @@ struct StoryRunPlan{ // NONE: the run ends after `rows`. STARTER_RNG: the run stops after // `rows`, the last of which (00.01) saves at the Verity Lakefront. StoryHandoff stop = StoryHandoff::NONE; + // Rows whose failure ends the program though they save at their start: + // a failed 00.02 with Run Starter RNG, whose reset loop is the retry. + std::set fatal_rows; }; // The rows of `table` from `first` to `last`, both inclusive, as a diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index bfff803f6b..3f1db39888 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -312,6 +312,78 @@ UnitTestResult test_plan_story_run_starter_rng(Logger&){ } +// The Starter RNG run's settings: the player's model, the starter and the +// reset limit come from AutoStory's options, and the run ends where 00.03 +// starts (Lakefront overworld, menu closed). +UnitTestResult test_starter_rng_settings(Logger&){ + BdspRngFilterTable table("Filters", Pokemon::StatsHuntMiscFeatureFlags{false, true, true, true}); + set_default_shiny_row(table); + const BdspRngFilterSnapshot filters = table.make_snapshot(); + const StoryStarterRngConfig config{ + .language = Language::French, .player_model = 5, .starter = StarterChoice::PIPLUP, .max_resets = 7 + }; + const StarterRngSettings settings = make_starter_rng_settings(config, filters); + if (settings.player_model != 5){ + return std::format("Expected the story's player model 5 to reach Starter RNG, got {}.", settings.player_model); + } + if (settings.starter != BdspStarter::Piplup || settings.language != Language::French || settings.max_resets != 7){ + return "Expected the starter, language and reset limit to come from the story's options."; + } + if (settings.filters != &filters || settings.start_point != BdspStartPoint::Lakefront){ + return "Expected the filter snapshot and the Verity Lakefront start point."; + } + if (settings.reset_first || !settings.finish_battle_on_shiny || !settings.close_summary_after_read){ + return "Expected a run that starts from the loaded save and leaves the Lakefront overworld on a shiny or not."; + } + return true; +} + +// What Starter RNG ending means for the story: a starter in hand and the +// game on the Lakefront lets it go on; anything else stops it with a reason. +UnitTestResult test_starter_rng_failure(Logger&){ + StarterRngRunResult result; + result.outcome = StarterRngOutcome::HIT; + if (!starter_rng_failure(result).empty()){ + return "Expected a hit to let the story go on."; + } + result.outcome = StarterRngOutcome::SHINY; + if (!starter_rng_failure(result).empty()){ + return "Expected a settled shiny to let the story go on."; + } + result.settled = false; + if (starter_rng_failure(result).empty()){ + return "Expected a shiny that did not settle (the game is mid-scene) to stop the story."; + } + for (const StarterRngOutcome outcome : {StarterRngOutcome::ABANDONED, StarterRngOutcome::OUT_OF_RESETS}){ + StarterRngRunResult failed; + failed.outcome = outcome; + failed.resets_used = 3; + if (starter_rng_failure(failed).empty()){ + return "Expected a run with no starter to stop the story."; + } + } + return true; +} + +// A failed Run Starter RNG ends the program: 00.02's row retry would rerun +// the whole reset loop. Without it no row is fatal on top of the table's. +UnitTestResult test_starter_rng_row_is_fatal(Logger&){ + const std::vector& table = story_checkpoints(); + const StoryRunPlan in_program = plan_story_run( + table, 0, 3, StoryHandoffs{.starter_rng = true, .run_starter_rng = true} + ); + if (in_program.fatal_rows != std::set{"00.02"}){ + return "Expected 00.02 to be fatal when Run Starter RNG in AutoStory is on."; + } + const StoryRunPlan plain = plan_story_run(table, 0, 3, StoryHandoffs{.starter_rng = true}); + const StoryRunPlan off = plan_story_run(table, 0, 3); + if (!plain.fatal_rows.empty() || !off.fatal_rows.empty()){ + return "Expected no fatal rows unless Run Starter RNG in AutoStory is on."; + } + return true; +} + + struct AutoStoryStoryTableInput{ std::string name; std::function body; @@ -367,6 +439,18 @@ const AutoStoryStoryTableCase AUTO_STORY_STORY_TABLE_CASES[] = { .input = {"Starter RNG handoff: stops after 00.01 saved at the Verity Lakefront", test_plan_story_run_starter_rng}, .expectation = {}, }, + { + .input = {"Run Starter RNG: settings come from the story's options", test_starter_rng_settings}, + .expectation = {}, + }, + { + .input = {"Run Starter RNG: what lets the story go on", test_starter_rng_failure}, + .expectation = {}, + }, + { + .input = {"Run Starter RNG: a failed 00.02 ends the program", test_starter_rng_row_is_fatal}, + .expectation = {}, + }, }; void add_tests_AutoStory_StoryTable(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp index 324bc2c2d9..7e6f0e29dc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp @@ -288,6 +288,7 @@ bool resolve_starter_rng_step( } if (attempt.outcome == BdspAttemptOutcome::Hit){ + result.settled = attempt.settled; result.outcome = attempt.shiny ? StarterRngOutcome::SHINY : StarterRngOutcome::HIT; @@ -566,12 +567,15 @@ BdspStarterAttemptResult run_starter_rng_attempt( pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 5000ms); context.wait_for_all_requests(); } + bool settled = true; if (settings.finish_battle_on_shiny){ if (!clear_starter_battle(env, context)){ record_error(); + settled = false; }else if (settings.close_summary_after_read){ if (!open_menu(env, context)){ record_error(); + settled = false; }else{ pbf_press_button(context, BUTTON_X, 160ms, 1000ms); context.wait_for_all_requests(); @@ -584,6 +588,7 @@ BdspStarterAttemptResult run_starter_rng_attempt( .shiny = true, .target = target, .target_advance = target_advance, + .settled = settled, }; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h index ccd10e6dd5..1e88d9b277 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h @@ -163,6 +163,10 @@ struct StarterRngRunResult{ uint64_t target_advance = 0; uint64_t resets_used = 0; std::string last_failure_reason; + // False when a shiny was caught but the game was not left where + // `finish_battle_on_shiny` and `close_summary_after_read` promise: the + // caller must not go on from it. + bool settled = true; }; @@ -172,6 +176,8 @@ struct BdspStarterAttemptResult{ Pokemon::BdspPokemonResult target{}; uint64_t target_advance = 0; std::string failure_reason; + // See StarterRngRunResult::settled. + bool settled = true; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp index c8cfd5182c..c561e57bc1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp @@ -155,6 +155,27 @@ UnitTestResult test_aim_and_calibration(Logger& logger){ } +// A shiny whose post-battle scene did not finish still ends the loop (the +// shiny must not be reset away), and says so. +UnitTestResult test_shiny_unsettled(Logger&){ + BdspStarterAttemptResult shiny{ + .outcome = BdspAttemptOutcome::Hit, .shiny = true, .target_advance = 9, .settled = false + }; + StarterRngRunResult result; + if (!resolve_starter_rng_step(shiny, 1, 3, result) || result.outcome != StarterRngOutcome::SHINY){ + return "expected a shiny to end the loop"; + } + if (result.settled){ + return "expected the unsettled shiny to say that the game is not settled"; + } + shiny.settled = true; + StarterRngRunResult settled; + if (!resolve_starter_rng_step(shiny, 1, 3, settled) || !settled.settled){ + return "expected a settled shiny to be settled"; + } + return true; +} + UnitTestResult test_attempt_loop_transitions(Logger&){ BdspPokemonResult sample_target{}; sample_target.ec = 0x12345678; @@ -323,6 +344,7 @@ const StarterRngTestCase STARTER_RNG_CASES[] = { {"aim offset and calibration bias", test_aim_and_calibration}, {"attempt loop outcome resolution", test_attempt_loop_transitions}, {"default filter row is shiny of any nature", test_default_shiny_row}, + {"a shiny that did not settle ends the loop unsettled", test_shiny_unsettled}, }; } // namespace diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index bf438c7d97..25c456a498 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1769,6 +1769,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp From bd1b9da10f3e8adf179963da26f2070c43bbeb85 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 17:54:46 -0800 Subject: [PATCH 15/20] BDSP AutoStory Starter RNG: lint fixes (private options, split tests and shiny settle, constants in StoryTable.cpp) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonBDSP_AutoStory.cpp | 24 +++++------ .../AutoStory/PokemonBDSP_AutoStory.h | 2 +- .../PokemonBDSP_AutoStory_StarterRng.cpp | 12 +++--- .../PokemonBDSP_AutoStory_StarterRng.h | 14 +++++-- ...onBDSP_AutoStory_StorySimulation_Tests.cpp | 20 ++++++++-- .../PokemonBDSP_AutoStory_StoryTable.cpp | 5 +++ .../PokemonBDSP_AutoStory_StoryTable.h | 4 -- ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 16 +++++++- .../PokemonBDSP_StarterRngAttempts.cpp | 40 ++++++++++++------- 9 files changed, 89 insertions(+), 48 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp index c1866f8105..99e99f6f08 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp @@ -136,7 +136,7 @@ std::string verify_story_checkpoint( BDSPAutoStory::~BDSPAutoStory(){ - STARTER_RNG.RUN.remove_listener(*this); + STARTER_RNG.run().remove_listener(*this); } BDSPAutoStory::BDSPAutoStory() @@ -167,7 +167,7 @@ BDSPAutoStory::BDSPAutoStory() false ) , NOTIFICATIONS({ - &STARTER_RNG.NOTIFICATION_SHINY, + &STARTER_RNG.notification_shiny(), &NOTIFICATION_PROGRAM_FINISH, &NOTIFICATION_ERROR_RECOVERABLE, &NOTIFICATION_ERROR_FATAL, @@ -178,20 +178,20 @@ BDSPAutoStory::BDSPAutoStory() PA_ADD_OPTION(PLAYER_NAME); PA_ADD_OPTION(STARTER); PA_ADD_OPTION(STOP_FOR_STARTER_RNG); - PA_ADD_OPTION(STARTER_RNG.RUN); - PA_ADD_OPTION(STARTER_RNG.PLAYER_MODEL); - PA_ADD_OPTION(STARTER_RNG.MAX_RESETS); - PA_ADD_OPTION(STARTER_RNG.FILTERS); + add_option(STARTER_RNG.run(), "RUN_STARTER_RNG"); + add_option(STARTER_RNG.player_model(), "STARTER_RNG_PLAYER_MODEL"); + add_option(STARTER_RNG.max_resets(), "MAX_RESETS"); + add_option(STARTER_RNG.filters(), "STARTER_RNG_FILTERS"); PA_ADD_OPTION(NOTIFICATIONS); BDSPAutoStory::on_config_value_changed(this); - STARTER_RNG.RUN.add_listener(*this); + STARTER_RNG.run().add_listener(*this); } // Run Starter RNG takes precedence over Stop for Starter RNG: the stop // option is greyed out while it is on, and the plan ignores it. void BDSPAutoStory::on_config_value_changed(void*){ - const bool run_in_story = STARTER_RNG.RUN; + const bool run_in_story = STARTER_RNG.run(); STARTER_RNG.set_details_visible(run_in_story); STOP_FOR_STARTER_RNG.set_visibility(run_in_story ? ConfigOptionState::DISABLED : ConfigOptionState::ENABLED); } @@ -288,7 +288,7 @@ void BDSPAutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerCo set_story_language(RUN.language()); StoryEnv story{env, context, STARTER, PLAYER_NAME, {}}; - if (STARTER_RNG.RUN){ + if (STARTER_RNG.run()){ story.run_starter_rng = make_starter_rng_hook( env, context, STARTER_RNG, STARTER_RNG.config(RUN.language(), STARTER), NOTIFICATION_ERROR_RECOVERABLE ); @@ -296,15 +296,15 @@ void BDSPAutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerCo StoryExecutor executor(story); const StoryRunPlan plan = plan_story_run( checkpoints, first, last, - StoryHandoffs{.starter_rng = STOP_FOR_STARTER_RNG, .run_starter_rng = STARTER_RNG.RUN} + StoryHandoffs{.starter_rng = STOP_FOR_STARTER_RNG, .run_starter_rng = STARTER_RNG.run()} ); executor.set_stop_rows(rows_that_stop(plan)); - run_plan(env, context, executor, plan, first == 0 && NEW_GAME_INTRO); + run_plan(env, context, plan, first == 0 && NEW_GAME_INTRO, executor); } void BDSPAutoStory::run_plan( SingleSwitchProgramEnvironment& env, ProControllerContext& context, - StoryExecutor& executor, const StoryRunPlan& plan, bool new_game + const StoryRunPlan& plan, bool new_game, StoryExecutor& executor ){ // A start with a save always loads it first, so the run never walks // from wherever the game was left (console B, 2026-11-11: a run from diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h index 1e292c101e..88ccce0d08 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h @@ -52,7 +52,7 @@ class BDSPAutoStory : public SingleSwitchProgramInstance, public ConfigOption::L // Starts the plan's story and runs it to its end or its stop. void run_plan( SingleSwitchProgramEnvironment& env, ProControllerContext& context, - StoryExecutor& executor, const StoryRunPlan& plan, bool new_game + const StoryRunPlan& plan, bool new_game, StoryExecutor& executor ); // The start and end checkpoints, attempts, checks and language. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp index 6bb5c7e2ef..d2639992cb 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp @@ -115,7 +115,7 @@ namespace{ // calibration builds up across them. struct StarterRngHookState{ StarterRngHookState(const StoryStarterRngOptions& options, const StoryStarterRngConfig& config) - : filters(options.FILTERS.make_snapshot()) + : filters(options.filters().make_snapshot()) , settings(make_starter_rng_settings(config, filters)) {} @@ -132,7 +132,7 @@ std::function make_starter_rng_hook( StoryStarterRngOptions& options, const StoryStarterRngConfig& config, EventNotificationOption& error_notification ){ - if (options.FILTERS.current_rows() == 0){ + if (options.filters().current_rows() == 0){ throw UserSetupError( env.console, "Starter RNG Stop Conditions is empty, so no starter would ever match: add a row, such as a shiny of any nature." @@ -142,7 +142,7 @@ std::function make_starter_rng_hook( return [&env, &context, &options, &error_notification, state]() -> Pokemon::Outcome{ uint64_t resets_logged = 0; StarterRngAttemptIO io; - io.notification_shiny = &options.NOTIFICATION_SHINY; + io.notification_shiny = &options.notification_shiny(); io.notification_error = &error_notification; io.on_reset = [&]{ resets_logged++; @@ -165,6 +165,6 @@ std::function make_starter_rng_hook( } -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h index d048774e37..3736dcd218 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h @@ -53,7 +53,13 @@ class StoryStarterRngOptions{ // The options' values, for a story in `language` with `starter`. StoryStarterRngConfig config(Language language, StarterChoice starter) const; -public: + BooleanCheckBoxOption& run(){ return RUN; } + PlayerModelOption& player_model(){ return PLAYER_MODEL; } + SimpleIntegerOption& max_resets(){ return MAX_RESETS; } + BdspRngFilterTable& filters(){ return FILTERS; } + EventNotificationOption& notification_shiny(){ return NOTIFICATION_SHINY; } + +private: BooleanCheckBoxOption RUN; PlayerModelOption PLAYER_MODEL; SimpleIntegerOption MAX_RESETS; @@ -81,7 +87,7 @@ std::function make_starter_rng_hook( ); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index 6ec7dab8e4..54c04262f2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -464,8 +464,14 @@ UnitTestResult test_start_and_end(Logger&){ ){ return std::format("Expected Starter RNG handoff to stop after 00.01 saved at VerityLakefront (17, 14), checking the Verity Lakefront card:{}", joined(handoff_sim.trace)); } - // With Run Starter RNG in AutoStory on, 00.02 saves at the Verity - // Lakefront, runs 00.02/starter_rng, and chains into 00.03 and on. + return true; +} + +// With Run Starter RNG in AutoStory on, 00.02 saves at the Verity +// Lakefront, runs 00.02/starter_rng, and chains into 00.03. +UnitTestResult test_run_starter_rng_in_story(Logger&){ + Pokemon::SegmentHooks hooks; + hooks.reload = [&](RunState&){ return Pokemon::outcome_ok(); }; Simulation in_program_sim; const StoryRunPlan in_program_plan = plan_story_run( story_checkpoints(), 0, 3, StoryHandoffs{.starter_rng = true, .run_starter_rng = true} @@ -482,8 +488,10 @@ UnitTestResult test_start_and_end(Logger&){ in_program_sim.count("00.02/starter_rng") != 1 || in_program_sim.count("00.02/choose_starter") != 0 ){ - return "Expected 00.02 with Run Starter RNG in AutoStory to save at Verity Lakefront, run 00.02/starter_rng, and continue to 00.03:" + - joined(in_program_sim.trace); + return std::format( + "Expected 00.02 with Run Starter RNG in AutoStory to save at Verity Lakefront, run 00.02/starter_rng, and continue to 00.03:{}", + joined(in_program_sim.trace) + ); } return true; } @@ -687,6 +695,10 @@ const AutoStoryStorySimulationCase AUTO_STORY_STORY_SIMULATION_CASES[] = { .input = {"start and end checkpoints", test_start_and_end}, .expectation = {}, }, + { + .input = {"Run Starter RNG in AutoStory chains 00.02 into 00.03", test_run_starter_rng_in_story}, + .expectation = {}, + }, { .input = {"a blackout in 00.04b's training resets to its save", test_training_blackout}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index e53264b5af..e6d946f3d4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -19,6 +19,11 @@ namespace PokemonBDSP{ namespace{ +// 00.02 is the Lake Verity starter and Starly battle checkpoint, which Run +// Starter RNG in AutoStory replaces with the game event STARTER_RNG_ACTION. +constexpr std::string_view STARTER_RNG_CHECKPOINT_ROW = "00.02"; +constexpr std::string_view STARTER_RNG_ACTION = "starter_rng"; + // `row` with a save appended at its end, where the next checkpoint starts: // in BDSP rows normally save at their start, so a run that stops after // 00.01 for Starter RNG makes 00.02's Lakefront save before stopping. As diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h index 90529ab85c..4412f1ea73 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h @@ -38,10 +38,6 @@ inline constexpr std::string_view RUNNING_SHOES_STEP = "rowan_and_dawn"; // 00.01 ends at the Verity Lakefront (17, 14) facing north, where 00.02 and // Starter RNG (Start point: Verity Lakefront) start. inline constexpr std::string_view STARTER_RNG_HANDOFF_ROW = "00.01"; -// 00.02 is the Lake Verity starter and Starly battle checkpoint, which -// Run Starter RNG in AutoStory replaces with STARTER_RNG_ACTION. -inline constexpr std::string_view STARTER_RNG_CHECKPOINT_ROW = "00.02"; -inline constexpr std::string_view STARTER_RNG_ACTION = "starter_rng"; // An upstream RNG program the user may run part-way through the story. enum class StoryHandoff{ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index 3f1db39888..61975459a5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -278,6 +278,14 @@ UnitTestResult test_plan_story_run_starter_rng(Logger&){ if (from_0002.stop != StoryHandoff::NONE || from_0002.rows.size() != 3 || from_0002.rows.front().id != "00.02"){ return "Expected a run starting at 00.02 to pass through without stopping for 00.01's handoff."; } + return true; +} + +// plan_story_run() with Run Starter RNG in AutoStory: 00.02 runs the +// starter_rng event after its Verity Lakefront start save and ends where +// 00.03 starts; the handoff stop is not taken. +UnitTestResult test_plan_story_run_in_program(Logger&){ + const std::vector& table = story_checkpoints(); const StoryRunPlan in_program = plan_story_run( table, 0, table.size() - 1, StoryHandoffs{.starter_rng = true, .run_starter_rng = true} ); @@ -287,10 +295,10 @@ UnitTestResult test_plan_story_run_starter_rng(Logger&){ const StoryCheckpoint& rng_row = in_program.rows[2]; const std::vector rng_problems = Pokemon::lint_story_checkpoint(rng_row); if (!rng_problems.empty()){ - return "00.02 with Run Starter RNG in AutoStory: " + rng_problems[0]; + return std::format("00.02 with Run Starter RNG in AutoStory: {}", rng_problems[0]); } if (rng_row.id != "00.02" || rng_row.saves_in != "Verity Lakefront" || rng_row.steps.size() != 1 || - rng_row.steps[0].kind != StoryStepKind::GAME || rng_row.steps[0].action != STARTER_RNG_ACTION || + rng_row.steps[0].kind != StoryStepKind::GAME || rng_row.steps[0].action != "starter_rng" || !story_events().contains(rng_row.steps[0].action) ){ return "Expected 00.02 with Run Starter RNG in AutoStory to run the starter_rng game event after its Verity Lakefront start save."; @@ -439,6 +447,10 @@ const AutoStoryStoryTableCase AUTO_STORY_STORY_TABLE_CASES[] = { .input = {"Starter RNG handoff: stops after 00.01 saved at the Verity Lakefront", test_plan_story_run_starter_rng}, .expectation = {}, }, + { + .input = {"Run Starter RNG: 00.02 runs the starter_rng event", test_plan_story_run_in_program}, + .expectation = {}, + }, { .input = {"Run Starter RNG: settings come from the story's options", test_starter_rng_settings}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp index 7e6f0e29dc..472708f58f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp @@ -306,6 +306,28 @@ bool resolve_starter_rng_step( } +// Leaves the game as the settings ask after a shiny: battle finished and, if +// asked, the starter summary read and the menu closed. False if a step failed. +static bool settle_after_shiny( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, const StarterRngSettings& settings +){ + if (!settings.finish_battle_on_shiny){ + return true; + } + if (!clear_starter_battle(env, context)){ + return false; + } + if (settings.close_summary_after_read){ + if (!open_menu(env, context)){ + return false; + } + pbf_press_button(context, BUTTON_X, 160ms, 1000ms); + context.wait_for_all_requests(); + env.log("Closed the menu."); + } + return true; +} + BdspStarterAttemptResult run_starter_rng_attempt( SingleSwitchProgramEnvironment& env, ProControllerContext& context, @@ -567,21 +589,9 @@ BdspStarterAttemptResult run_starter_rng_attempt( pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 5000ms); context.wait_for_all_requests(); } - bool settled = true; - if (settings.finish_battle_on_shiny){ - if (!clear_starter_battle(env, context)){ - record_error(); - settled = false; - }else if (settings.close_summary_after_read){ - if (!open_menu(env, context)){ - record_error(); - settled = false; - }else{ - pbf_press_button(context, BUTTON_X, 160ms, 1000ms); - context.wait_for_all_requests(); - env.log("Closed the menu."); - } - } + const bool settled = settle_after_shiny(env, context, settings); + if (!settled){ + record_error(); } return BdspStarterAttemptResult{ .outcome = BdspAttemptOutcome::Hit, From 29a22788834fa556fd1f1952f8c68b75b77dfae8 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 17:55:08 -0800 Subject: [PATCH 16/20] BDSP AutoStory Starter RNG: const filters accessor Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h | 1 + 1 file changed, 1 insertion(+) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h index 3736dcd218..a4f957ed5c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h @@ -57,6 +57,7 @@ class StoryStarterRngOptions{ PlayerModelOption& player_model(){ return PLAYER_MODEL; } SimpleIntegerOption& max_resets(){ return MAX_RESETS; } BdspRngFilterTable& filters(){ return FILTERS; } + const BdspRngFilterTable& filters() const{ return FILTERS; } EventNotificationOption& notification_shiny(){ return NOTIFICATION_SHINY; } private: From 89b2d42e2bfa07e5b14ed0a3359b007bbd80f2dd Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 17:59:23 -0800 Subject: [PATCH 17/20] BDSP AutoStory Starter RNG: drop const filters accessor Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp | 2 +- .../Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp index d2639992cb..f4a7eef503 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp @@ -114,7 +114,7 @@ namespace{ // edits made while running do not apply, and the aim that Starter RNG's // calibration builds up across them. struct StarterRngHookState{ - StarterRngHookState(const StoryStarterRngOptions& options, const StoryStarterRngConfig& config) + StarterRngHookState(StoryStarterRngOptions& options, const StoryStarterRngConfig& config) : filters(options.filters().make_snapshot()) , settings(make_starter_rng_settings(config, filters)) {} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h index a4f957ed5c..3736dcd218 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h @@ -57,7 +57,6 @@ class StoryStarterRngOptions{ PlayerModelOption& player_model(){ return PLAYER_MODEL; } SimpleIntegerOption& max_resets(){ return MAX_RESETS; } BdspRngFilterTable& filters(){ return FILTERS; } - const BdspRngFilterTable& filters() const{ return FILTERS; } EventNotificationOption& notification_shiny(){ return NOTIFICATION_SHINY; } private: From 7a46b79b48e32fbb79adb5bca01153a94b04d379 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 18:40:56 -0800 Subject: [PATCH 18/20] AutoStory: shared RNG handoff contract; BDSP Starter RNG adopts it Pokemon_StoryRngHandoff.h holds what every game's RNG handoff shares: the OFF/STOP/RUN mode, the result an RNG program's call ends in, and run_rng_handoff(), which logs a success and throws on a failure so no row retry reruns the reset loop. BDSP's Starter RNG hook now runs through it. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_AutoStory_Tests.h | 2 + .../AutoStory/Pokemon_StoryRngHandoff.cpp | 38 ++++++ .../AutoStory/Pokemon_StoryRngHandoff.h | 64 ++++++++++ .../Pokemon_StoryRngHandoff_Tests.cpp | 113 ++++++++++++++++++ .../AutoStory/Pokemon_StoryRngHandoff_Tests.h | 23 ++++ .../PokemonBDSP_AutoStory_StarterRng.cpp | 30 +++-- .../PokemonBDSP_AutoStory_StarterRng.h | 6 + SerialPrograms/cmake/SourceFiles.cmake | 4 + 8 files changed, 267 insertions(+), 13 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 906540637b..c6b1ec19a9 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -28,6 +28,7 @@ #include "Pokemon_StoryEvents_Tests.h" #include "Pokemon_StoryInterrupts_Tests.h" #include "Pokemon_StoryLog_Tests.h" +#include "Pokemon_StoryRngHandoff_Tests.h" #include "Pokemon_StorySavePolicy_Tests.h" #include "Pokemon_StorySegments_Tests.h" #include "Pokemon_StoryStepExecutor_Tests.h" @@ -44,6 +45,7 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_StoryRun(database); add_tests_AutoStoryStats(database); add_tests_StoryLog(database); + add_tests_StoryRngHandoff(database); add_tests_StoryRangeOptions(database); add_tests_StoryEvents(database); add_tests_StorySegments(database); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp new file mode 100644 index 0000000000..e23256397a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp @@ -0,0 +1,38 @@ +/* Story RNG Handoff + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryRngHandoff.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +RngHandoffMode rng_handoff_mode(bool stop, bool run){ + if (run){ + return RngHandoffMode::RUN; + } + return stop ? RngHandoffMode::STOP : RngHandoffMode::OFF; +} + +bool RngHandoffResult::succeeded() const{ + return failure.empty(); +} + +Outcome run_rng_handoff(Logger& logger, const std::string& program, const RngHandoffCall& call){ + const RngHandoffResult result = call(); + if (!result.succeeded()){ + throw_and_log(logger, ErrorReportMode::SEND_ERROR_REPORT, result.failure); + } + logger.log(program + " succeeded: " + result.summary, COLOR_BLUE); + return outcome_ok(); +} + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h new file mode 100644 index 0000000000..140d20e5ea --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h @@ -0,0 +1,64 @@ +/* Story RNG Handoff + * + * From: https://github.com/PokemonAutomation/ + * + * The part of an AutoStory run that hands the game to an RNG program (BDSP + * Starter RNG, FRLG Starter RNG and Gift RNG) and takes it back. A game + * supplies the program's call; the contract around it is shared: + * + * - A handoff row has a mode: OFF (the story plays it by hand), STOP (the run + * ends after the row's handoff save, for the user to run the RNG program) + * or RUN (the story calls the RNG program itself and continues). + * - The call ends in an RngHandoffResult: no failure means the game stands + * where the story goes on; a failure is the reason it does not. + * - A failed RUN stops the program. It never retries the row: the program's + * own reset loop is the retry, and a reload of the save would lose a + * shiny it caught. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRngHandoff_H +#define PokemonAutomation_Pokemon_StoryRngHandoff_H + +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Pokemon_StoryOutcome.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +enum class RngHandoffMode{ + OFF, + STOP, + RUN, +}; + +// The mode for a handoff's two options: RUN takes precedence over STOP. +RngHandoffMode rng_handoff_mode(bool stop, bool run); + + +// How an RNG program's call ended, as the story needs it. +struct RngHandoffResult{ + // Empty: the game stands where the story goes on. Otherwise why it does not. + std::string failure; + // What a success did, for the log: the resets used, the target hit. + std::string summary; + + bool succeeded() const; +}; + +// The call a handoff row runs in place of its steps. +using RngHandoffCall = std::function; + +// Runs `call` for the RNG program `program` ("Starter RNG"). A success is +// logged with its summary and returned as an ok Outcome. A failure throws +// OperationFailedException with an error report, so that no row retry +// reruns the program's reset loop. +Outcome run_rng_handoff(Logger& logger, const std::string& program, const RngHandoffCall& call); + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp new file mode 100644 index 0000000000..72a847d509 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp @@ -0,0 +1,113 @@ +/* Story RNG Handoff Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryRngHandoff.h" +#include "Pokemon_StoryRngHandoff_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +// rng_handoff_mode()'s two options. +struct ModeInput{ + bool stop; + bool run; +}; + +struct ModeCase{ + ModeInput input; + RngHandoffMode expected; +}; + +const ModeCase MODE_CASES[] = { + {.input = {.stop = false, .run = false}, .expected = RngHandoffMode::OFF}, + {.input = {.stop = true, .run = false}, .expected = RngHandoffMode::STOP}, + {.input = {.stop = false, .run = true}, .expected = RngHandoffMode::RUN}, + {.input = {.stop = true, .run = true}, .expected = RngHandoffMode::RUN}, +}; + +class Test_RngHandoffMode : public UnitTest{ +public: + Test_RngHandoffMode() + : UnitTest("Pokemon::StoryRngHandoff - RUN takes precedence over STOP") + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + for (const ModeCase& item : MODE_CASES){ + if (rng_handoff_mode(item.input.stop, item.input.run) != item.expected){ + return std::format( + "stop={}, run={}: wrong mode", item.input.stop, item.input.run + ); + } + } + return true; + } +}; + +// A success is an ok Outcome and calls the program once. +class Test_RngHandoffSuccess : public UnitTest{ +public: + Test_RngHandoffSuccess() + : UnitTest("Pokemon::StoryRngHandoff - a success is ok") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + int calls = 0; + const Outcome outcome = run_rng_handoff(logger, "Test RNG", [&]{ + calls++; + return RngHandoffResult{.summary = "2 resets"}; + }); + if (!outcome.succeeded()){ + return "Expected an ok outcome"; + } + if (calls != 1){ + return std::format("Expected 1 call, got {}", calls); + } + return true; + } +}; + +// A failure throws, once: nothing reruns the program. +class Test_RngHandoffFailure : public UnitTest{ +public: + Test_RngHandoffFailure() + : UnitTest("Pokemon::StoryRngHandoff - a failure throws without a retry") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + int calls = 0; + try{ + run_rng_handoff(logger, "Test RNG", [&]{ + calls++; + return RngHandoffResult{.failure = "out of resets"}; + }); + }catch (OperationFailedException&){ + if (calls != 1){ + return std::format("Expected 1 call, got {}", calls); + } + return true; + } + return "Expected OperationFailedException"; + } +}; + +} // namespace + + +void add_tests_StoryRngHandoff(UnitTestDatabase& database){ + database.add(); + database.add(); + database.add(); +} + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h new file mode 100644 index 0000000000..aca6f82c1b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h @@ -0,0 +1,23 @@ +/* Story RNG Handoff Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRngHandoff_Tests_H +#define PokemonAutomation_Pokemon_StoryRngHandoff_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the shared RNG handoff contract. +void add_tests_StoryRngHandoff(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp index f4a7eef503..8ceb126ce8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp @@ -108,6 +108,19 @@ std::string starter_rng_failure(const StarterRngRunResult& result){ } +Pokemon::RngHandoffResult starter_rng_handoff_result(const StarterRngRunResult& result){ + Pokemon::RngHandoffResult handoff; + handoff.failure = starter_rng_failure(result); + if (handoff.failure.empty()){ + handoff.summary = std::format( + "after {} reset(s) on advance {}: {}.", + result.resets_used, result.target_advance, result.target.to_string() + ); + } + return handoff; +} + + namespace{ // What the hook keeps between its calls: the filters, copied once so that @@ -148,19 +161,10 @@ std::function make_starter_rng_hook( resets_logged++; env.console.overlay().add_log(std::format("Starter RNG: try {}", resets_logged)); }; - const StarterRngRunResult result = run_starter_rng_attempts(env, context, state->settings, io, state->aim); - const std::string failure = starter_rng_failure(result); - if (!failure.empty()){ - throw_and_log(env.logger(), ErrorReportMode::SEND_ERROR_REPORT, failure); - } - env.log( - std::format( - "Starter RNG succeeded after {} reset(s) on advance {}: {}.", - result.resets_used, result.target_advance, result.target.to_string() - ), - COLOR_BLUE - ); - return Pokemon::outcome_ok(); + return Pokemon::run_rng_handoff(env.logger(), "Starter RNG", [&]{ + const StarterRngRunResult result = run_starter_rng_attempts(env, context, state->settings, io, state->aim); + return starter_rng_handoff_result(result); + }); }; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h index 3736dcd218..fc2df841e0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h @@ -19,6 +19,7 @@ #include "CommonFramework/Language.h" #include "CommonFramework/Notifications/EventNotificationOption.h" #include "Pokemon/AutoStory/Pokemon_StoryOutcome.h" +#include "Pokemon/AutoStory/Pokemon_StoryRngHandoff.h" #include "PokemonBDSP/Options/PokemonBDSP_PlayerModelOption.h" #include "PokemonBDSP/Options/PokemonBDSP_RngFilter.h" #include "PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h" @@ -77,6 +78,11 @@ StarterRngSettings make_starter_rng_settings(const StoryStarterRngConfig& config // it can: a starter was caught and the game stands on the Lakefront. std::string starter_rng_failure(const StarterRngRunResult& result); +// Starter RNG's end as the shared handoff contract has it +// (Pokemon_StoryRngHandoff.h): starter_rng_failure() and, on success, the +// resets used and the target hit. +Pokemon::RngHandoffResult starter_rng_handoff_result(const StarterRngRunResult& result); + // The action 00.02 runs. Throws a UserSetupError now if the filter table is // empty. The action itself throws when Starter RNG fails, so that no row // retry reruns the whole reset loop. diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 25c456a498..189dfe3e1f 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1563,6 +1563,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_AutoStorySelect.h Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.cpp Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp + Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h + Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp Source/Pokemon/AutoStory/Pokemon_StoryRun.h Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp From c2c6ae9bc7643d9c91e2e58545d444382b12366e Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 00:16:30 -0800 Subject: [PATCH 19/20] BDSP AutoStory: the Starter RNG handoff takes the shared RngHandoffMode; its stop reports through the shared report StoryHandoffs held two bools whose combination the plan decoded; it holds the mode of the options now, as FRLG's program derives it. The stop's log line, overlay line and notification text come from Pokemon::report_rng_handoff_stop. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Programs/AutoStory/PokemonBDSP_AutoStory.cpp | 9 ++++++--- .../PokemonBDSP_AutoStory_StorySimulation_Tests.cpp | 4 ++-- .../AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp | 4 ++-- .../AutoStory/PokemonBDSP_AutoStory_StoryTable.h | 8 +++++--- .../PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 12 ++++++------ 5 files changed, 21 insertions(+), 16 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp index 99e99f6f08..32051ab4dd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp @@ -15,6 +15,7 @@ #include "CommonFramework/VideoPipeline/VideoOverlay.h" #include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" #include "Pokemon/AutoStory/Pokemon_StoryPreflight.h" +#include "Pokemon/AutoStory/Pokemon_StoryRngHandoff.h" #include "Pokemon/AutoStory/Pokemon_StoryRun.h" #include "Pokemon/AutoStory/Pokemon_AutoStorySelect.h" #include "Pokemon/AutoStory/Pokemon_AutoStoryStats.h" @@ -296,7 +297,7 @@ void BDSPAutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerCo StoryExecutor executor(story); const StoryRunPlan plan = plan_story_run( checkpoints, first, last, - StoryHandoffs{.starter_rng = STOP_FOR_STARTER_RNG, .run_starter_rng = STARTER_RNG.run()} + StoryHandoffs{.starter_rng = Pokemon::rng_handoff_mode({.stop = STOP_FOR_STARTER_RNG, .run = STARTER_RNG.run()})} ); executor.set_stop_rows(rows_that_stop(plan)); run_plan(env, context, plan, first == 0 && NEW_GAME_INTRO, executor); @@ -330,8 +331,10 @@ void BDSPAutoStory::run_plan( Pokemon::SegmentRange{plan.rows.front().id, plan.rows.back().id}, RUN.policy(), segment, game, state, env ); if (plan.stop == StoryHandoff::STARTER_RNG){ - const std::string handoff = std::format("Stopped for Starter RNG. {}", STARTER_RNG_HANDOFF_TEXT); - env.log(handoff, COLOR_BLUE); + const std::string handoff = Pokemon::report_rng_handoff_stop( + env.console, std::format("Stopped for Starter RNG. {}", STARTER_RNG_HANDOFF_TEXT), {}, + [&](const std::string& line){ env.console.overlay().add_log(line); } + ); send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, handoff); return; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index 54c04262f2..64dcab1c23 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -446,7 +446,7 @@ UnitTestResult test_start_and_end(Logger&){ // saves at the Verity Lakefront (17, 14) facing north. Simulation handoff_sim; const StoryRunPlan plan = plan_story_run( - story_checkpoints(), 0, story_checkpoints().size() - 1, StoryHandoffs{.starter_rng = true} + story_checkpoints(), 0, story_checkpoints().size() - 1, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::STOP} ); Pokemon::Segment handoff_segment = make_story_segment(plan.rows, handoff_sim.game, handoff_sim.saved); Pokemon::SegmentHooks hooks; @@ -474,7 +474,7 @@ UnitTestResult test_run_starter_rng_in_story(Logger&){ hooks.reload = [&](RunState&){ return Pokemon::outcome_ok(); }; Simulation in_program_sim; const StoryRunPlan in_program_plan = plan_story_run( - story_checkpoints(), 0, 3, StoryHandoffs{.starter_rng = true, .run_starter_rng = true} + story_checkpoints(), 0, 3, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::RUN} ); Pokemon::Segment in_program_segment = make_story_segment(in_program_plan.rows, in_program_sim.game, in_program_sim.saved); RunState in_program_state; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index e6d946f3d4..80a864315c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -80,13 +80,13 @@ StoryRunPlan plan_story_run( StoryRunPlan plan; for (size_t c = first; c <= last && c < checkpoints.size(); c++){ const StoryCheckpoint& row = checkpoints[c]; - if (row.id == STARTER_RNG_HANDOFF_ROW && handoffs.starter_rng && !handoffs.run_starter_rng){ + if (row.id == STARTER_RNG_HANDOFF_ROW && handoffs.starter_rng == Pokemon::RngHandoffMode::STOP){ const std::string saves_in = c + 1 < checkpoints.size() ? checkpoints[c + 1].saves_in : std::string(); plan.rows.push_back(with_handoff_save(row, saves_in)); plan.stop = StoryHandoff::STARTER_RNG; return plan; } - if (row.id == STARTER_RNG_CHECKPOINT_ROW && handoffs.run_starter_rng){ + if (row.id == STARTER_RNG_CHECKPOINT_ROW && handoffs.starter_rng == Pokemon::RngHandoffMode::RUN){ plan.rows.push_back(with_starter_rng_step(row)); plan.fatal_rows.insert(row.id); continue; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h index 4412f1ea73..39f744058c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h @@ -18,6 +18,7 @@ #include #include #include +#include "Pokemon/AutoStory/Pokemon_StoryRngHandoff.h" #include "PokemonBDSP_AutoStory_StoryExecutor.h" namespace PokemonAutomation{ @@ -49,8 +50,9 @@ enum class StoryHandoff{ // The handoffs a run stops for or runs in-program (AutoStory's options). struct StoryHandoffs{ - bool starter_rng = false; - bool run_starter_rng = false; + // STOP: the run stops after 00.01 for the user's Starter RNG. RUN: 00.02 + // runs it in the program. The mode of the options: Pokemon::rng_handoff_mode(). + Pokemon::RngHandoffMode starter_rng = Pokemon::RngHandoffMode::OFF; }; // What a run from table row `first` to `last` does. @@ -69,7 +71,7 @@ struct StoryRunPlan{ // The rows of `table` from `first` to `last`, both inclusive, as a // run with `handoffs` takes them: a run that reaches 00.01 with -// `handoffs.starter_rng` on saves at the Verity Lakefront at the end of +// `handoffs.starter_rng` STOP saves at the Verity Lakefront at the end of // 00.01 and stops there for Starter RNG. StoryRunPlan plan_story_run(const std::vector& table, size_t first, size_t last, const StoryHandoffs& handoffs = {}); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index 61975459a5..9f3c7c56fa 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -237,11 +237,11 @@ UnitTestResult test_route204_north_line(Logger& logger){ // north, where 00.02 and Starter RNG start; starting past 00.01 runs on. UnitTestResult test_plan_story_run_starter_rng(Logger&){ const std::vector& table = story_checkpoints(); - const StoryRunPlan full = plan_story_run(table, 0, table.size() - 1, StoryHandoffs{.starter_rng = false}); + const StoryRunPlan full = plan_story_run(table, 0, table.size() - 1, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::OFF}); if (full.stop != StoryHandoff::NONE || full.rows.size() != table.size()){ return "With Starter RNG handoff off, expected the full table with no stop."; } - const StoryRunPlan handoff = plan_story_run(table, 0, table.size() - 1, StoryHandoffs{.starter_rng = true}); + const StoryRunPlan handoff = plan_story_run(table, 0, table.size() - 1, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::STOP}); if (handoff.stop != StoryHandoff::STARTER_RNG || handoff.rows.size() != 2 || handoff.rows[0].id != "00.00" || handoff.rows[1].id != "00.01" ){ @@ -274,7 +274,7 @@ UnitTestResult test_plan_story_run_starter_rng(Logger&){ ){ return "Expected 00.01's Starter RNG handoff save to end at 00.02's VerityLakefront (17, 14) start pose."; } - const StoryRunPlan from_0002 = plan_story_run(table, 2, 4, StoryHandoffs{.starter_rng = true}); + const StoryRunPlan from_0002 = plan_story_run(table, 2, 4, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::STOP}); if (from_0002.stop != StoryHandoff::NONE || from_0002.rows.size() != 3 || from_0002.rows.front().id != "00.02"){ return "Expected a run starting at 00.02 to pass through without stopping for 00.01's handoff."; } @@ -287,7 +287,7 @@ UnitTestResult test_plan_story_run_starter_rng(Logger&){ UnitTestResult test_plan_story_run_in_program(Logger&){ const std::vector& table = story_checkpoints(); const StoryRunPlan in_program = plan_story_run( - table, 0, table.size() - 1, StoryHandoffs{.starter_rng = true, .run_starter_rng = true} + table, 0, table.size() - 1, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::RUN} ); if (in_program.stop != StoryHandoff::NONE || in_program.rows.size() != table.size()){ return "With Run Starter RNG in AutoStory on, expected the full table with no handoff stop."; @@ -378,12 +378,12 @@ UnitTestResult test_starter_rng_failure(Logger&){ UnitTestResult test_starter_rng_row_is_fatal(Logger&){ const std::vector& table = story_checkpoints(); const StoryRunPlan in_program = plan_story_run( - table, 0, 3, StoryHandoffs{.starter_rng = true, .run_starter_rng = true} + table, 0, 3, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::RUN} ); if (in_program.fatal_rows != std::set{"00.02"}){ return "Expected 00.02 to be fatal when Run Starter RNG in AutoStory is on."; } - const StoryRunPlan plain = plan_story_run(table, 0, 3, StoryHandoffs{.starter_rng = true}); + const StoryRunPlan plain = plan_story_run(table, 0, 3, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::STOP}); const StoryRunPlan off = plan_story_run(table, 0, 3); if (!plain.fatal_rows.empty() || !off.fatal_rows.empty()){ return "Expected no fatal rows unless Run Starter RNG in AutoStory is on."; From 122697311aff6fef3e3492da16ebdecabda2d7c2 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 10:41:26 -0800 Subject: [PATCH 20/20] CI: pin CommandLineTests with the BDSP MenuDetector French menu image --- .github/workflows/cpp-ci-serial-programs-base.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/cpp-ci-serial-programs-base.yml b/.github/workflows/cpp-ci-serial-programs-base.yml index 673b391abb..df008e51c0 100644 --- a/.github/workflows/cpp-ci-serial-programs-base.yml +++ b/.github/workflows/cpp-ci-serial-programs-base.yml @@ -257,9 +257,9 @@ jobs: uses: actions/checkout@v7 if: inputs.run-tests with: - # The fork's fixtures: upstream's plus the SystemKeyboardDetector and HomeTileReader screenshots. + # The fork's fixtures: upstream's plus the SystemKeyboardDetector, HomeTileReader and BDSP MenuDetector screenshots. repository: 'dayfine/CommandLineTests' - ref: 'eae4697738d5fe18975e77c05a4e01216bed68e7' + ref: '248d24fc7d1803c5187aae680d37ad1c5c0f13e7' path: 'CommandLineTests' # The unit tests assume the downloadable resources they need are already downloaded