diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/executor.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/executor.rs index f4fe575..a5e2862 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/executor.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/executor.rs @@ -422,6 +422,16 @@ struct Walk { /// without this the same tile is aimed at once per hold for ever, which is what a ledge, a /// tile-pair rule or a person on the far side of it looks like. stalled: bool, + /// The ledge hop the held press is making, as the tile it was pressed from and its direction. + /// + /// Row 64. The route search takes a ledge the one way the cartridge does + /// ([`path::route_avoiding`]), and the cartridge's way is to take the joypad: `HandleLedges` + /// sets `wJoyIgnore` and simulates the two tiles of the jump, so the scene reads + /// [`Scene::Unknown`] for the length of it. Without this the walk ended on that scene change + /// like any other, `scripted` and all, and [`MacroMachine::observe_push`] wrote a hop the walk + /// asked for as a push-back: the tile walled for the session and the target rested for the + /// window. Set when the press begins, cleared when the fly has moved. + hop: Option<(Tile, Facing)>, /// The warp this walk began standing on, while it has not yet stepped off it. /// /// Row 64, Mt. Moon, two days. A ladder, a cave mouth, a staircase -- every warp whose exit @@ -866,6 +876,13 @@ impl MacroMachine { // ended every walk north this way, `Done` with nothing recorded, once per hold for eight // hours. let now = class(state.scene()); + // A ledge the walk pressed into is the cartridge carrying the fly where the walk asked it + // to go, not the world moving on under it ([`Walk::hop`]): the walk waits it out and + // re-plans from the landing. + if now != started_in && !spans.contains(&now) && self.hopping(state) { + self.active.as_mut()?.frames += 1; + return Some(buttons::NONE); + } if now != started_in && !spans.contains(&now) { let pushed = state.scripted() || self.moved_away(state); let at = pushed.then(|| state.player()).flatten(); @@ -1004,6 +1021,24 @@ impl MacroMachine { self.pending_push_calm = 0; } + /// Whether the running walk is mid-hop: it pressed into a ledge ([`Walk::hop`]), the + /// cartridge has the joypad with no text up, and the fly is on the hop's own line -- the tile + /// it pressed from, the ledge, or the landing -- on the walk's own map. A wild battle on the + /// landing is a battle, and ends the walk as a scene change always has. + fn hopping(&self, state: &mut dyn MacroState) -> bool { + let Some(active) = self.active.as_ref() else { return false }; + let Some(Step::Walk(walk)) = active.plan.front() else { return false }; + let Some((from, facing)) = walk.hop else { return false }; + if state.scene() != Scene::Unknown || !state.scripted() || state.text_open() { + return false; + } + let Some(player) = state.player() else { return false }; + let at = Tile::new(player.x, player.y); + let over = from.step(facing); + let landing = over.and_then(|tile| tile.step(facing)); + player.map == walk.map && (at == from || Some(at) == over || Some(at) == landing) + } + /// Whether the fly is standing somewhere other than where the running macro began. /// /// The other half of "the game moved the fly": a script can finish its push-back inside the @@ -1567,10 +1602,12 @@ fn walk_frame(walk: &mut Walk, state: &mut dyn MacroState) -> Progress { if let Some((facing, from)) = walk.holding { if here != from { // Moved: this tile is done and the failure run is broken. The plan's head is spent, - // and the next one steps from where the player now stands. + // and the next one steps from where the player now stands -- two tiles on, after a + // ledge ([`Walk::hop`]). walk.plan.pop_front(); walk.expect = Some(here); walk.holding = None; + walk.hop = None; walk.held = 0; walk.failures = 0; walk.gap = STEP_GAP; @@ -1590,6 +1627,7 @@ fn walk_frame(walk: &mut Walk, state: &mut dyn MacroState) -> Progress { walk.plan.clear(); walk.expect = None; walk.holding = None; + walk.hop = None; walk.held = 0; walk.gap = STEP_GAP; walk.failures += 1; @@ -1642,6 +1680,10 @@ fn walk_frame(walk: &mut Walk, state: &mut dyn MacroState) -> Progress { }; walk.holding = Some((first, here)); walk.held = 1; + walk.hop = state + .map_grid() + .is_some_and(|grid| grid.map() == walk.map && grid.hops(here.x, here.y, first)) + .then_some((here, first)); Progress::Hold(button(first)) } @@ -2204,6 +2246,7 @@ fn walk_then( best_distance: distance, continues, stalled: false, + hop: None, step_off, }, target, diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/path.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/path.rs index 274cc2a..dd26c04 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/path.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/path.rs @@ -143,11 +143,12 @@ pub enum Way { /// A *directed* wall, which is the only shape that fits what the game encodes. Two of its rules /// are invisible to the collision table [`super::state::walkable`] reads: /// -/// - **ledges.** `HandleLedges` (`home/overworld.asm`) matches a triple of facing, the tile the -/// player stands on and the tile in front against `LedgeTiles`, and hops the player *two* tiles -/// that way. The ledge tile itself is absent from every tileset's passable list, so the -/// predicate already calls it [`Walkable::No`] and the search never plans through one in either -/// direction — a hop is a move the walk declines to use rather than one it gets wrong. +/// - **ledges.** `HandleLedges` (`engine/overworld/ledges.asm`) matches a triple of facing, the +/// tile the player stands on and the tile in front against `LedgeTiles`, and hops the player +/// *two* tiles that way. The ledge tile itself is absent from every tileset's passable list, so +/// the predicate calls it [`Walkable::No`] from both sides. With the decoded grid the search +/// takes the hop the one way the cartridge does (row 64, [`route_avoiding`]); without one, or +/// from the side below, it is a wall the walk declines to plan through. /// - **tile-pair collisions.** `TilePairCollisionsLand` and `...Water` /// (`data/tilesets/tile_pair_collisions.asm`) refuse a step *between* two tiles that are each /// passable on their own — the water/land boundary, a forest's tree line, a gym's floor edge. @@ -254,6 +255,36 @@ pub fn route_avoiding( open.push(Reverse((step_cost + heuristic(next), step_cost, next))); } } + // **A ledge is a step the cartridge takes one way** (row 64). The ledge tile reads + // [`Walkable::No`] and the loop above never plans onto it, which is right from below and + // wrong from above: pressed into from its top side the cartridge hops the fly over it and + // lands it two tiles on. Before this, Route 4 east of Mt. Moon had no road to Cerulean at + // all -- the way down is three ledges -- so `GO OBJECTIVE` refused `no route` on the + // mountain's far side and the fly walked back into the cave. One press, one plan entry; + // the executor holds the walk while the cartridge carries the fly over. + if let Some(grid) = grid { + for facing in super::cartridge::FACINGS { + if !grid.hops(tile.x, tile.y, facing) || refused.contains(&(tile, facing)) { + continue; + } + let Some(landing) = tile.step(facing).and_then(|over| over.step(facing)) else { + continue; + }; + if landing.x >= size.width || landing.y >= size.height { + continue; + } + if state.pushed_tile(landing.x, landing.y) + || !grid.walkable(landing.x, landing.y).is_walkable() + { + continue; + } + let step_cost = cost + 2; + if best.get(&landing).is_none_or(|(known, _, _)| step_cost < *known) { + best.insert(landing, (step_cost, tile, facing)); + open.push(Reverse((step_cost + heuristic(landing), step_cost, landing))); + } + } + } } // Nothing reachable is a goal. Walk to whatever gets closest, so the predicate's window has diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/state.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/state.rs index 645813b..ae01242 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/state.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/state.rs @@ -421,7 +421,13 @@ impl Walkable { /// - **directed walls**: one step out of one tile in one direction that the cartridge refuses /// although both tiles are passable. Pokered has two such rules and the tile-pair lists are the /// one that can be read ahead of time; a ledge is already [`Walkable::No`] in the collision -/// list, and a person in the way is the sprite list's answer, not the ground's. +/// list, and a person in the way is the sprite list's answer, not the ground's; +/// - **ledge hops** (row 64): the one step the collision list calls a wall that the cartridge +/// *does* take, one way, two tiles at a time -- `HandleLedges` matching the facing, the tile +/// stood on and the ledge tile in front against `LedgeTiles` +/// ([`crate::pokemon_red::mapgrid::LEDGE_TILES`]). A hop is a fact about the tables, like a +/// wall, and only [`super::path::route_avoiding`] reads it: [`MapGrid::reachable`] keeps the +/// ground as the collision list draws it, which is what a map's pieces are measured on. /// /// Nothing here is a fact about the run: no ledger, no visit, no target. Those stay where they /// are, session state in the executor layer. @@ -437,6 +443,9 @@ pub struct MapGrid { /// Row-major bitmask of the directions a step out of this tile is refused in /// ([`MapGrid::wall`]). walls: Vec, + /// Row-major bitmask of the directions a press out of this tile hops a ledge in + /// ([`MapGrid::ledge`]), landing two tiles that way. + hops: Vec, } impl MapGrid { @@ -450,6 +459,7 @@ impl MapGrid { tiles: vec![Walkable::Unknown; cells], ids: vec![None; cells], walls: vec![0; cells], + hops: vec![0; cells], } } @@ -486,6 +496,18 @@ impl MapGrid { } } + /// Record that a press out of `(x, y)` in `facing` hops the ledge in front, two tiles. + pub fn ledge(&mut self, x: u8, y: u8, facing: Facing) { + if let Some(index) = self.index(x, y) { + self.hops[index] |= wall_bit(facing); + } + } + + /// Whether a press out of `(x, y)` in `facing` is a ledge hop ([`MapGrid::ledge`]). + pub fn hops(&self, x: u8, y: u8, facing: Facing) -> bool { + self.index(x, y).is_some_and(|index| self.hops[index] & wall_bit(facing) != 0) + } + /// Whether the player could stand on this tile. Off the map is [`Walkable::No`], which is the /// window predicate's own answer for it. pub fn walkable(&self, x: u8, y: u8) -> Walkable { diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs index f1da422..0e811d2 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs @@ -188,6 +188,13 @@ struct World { prompt: bool, /// Whether the cartridge is driving the player right now ([`MacroState::scripted`]). scripted: bool, + /// Ledges, as the tile a press hops from and its direction (row 64). Empty everywhere but the + /// tests about them, and with it empty the world has no decoded grid, as before. + ledges: Vec<(Tile, Facing)>, + /// A hop the cartridge is carrying the player through: frames left, the ledge tile, the + /// landing. `HandleLedges` takes the joypad for the length of it, so the scene reads + /// `Unknown` and the world is scripted. + hop: Option<(u32, Tile, Tile)>, /// A frame at which the cartridge takes the joypad, which is what the Viridian gate does. scripted_at: Option, /// Every completed pulse, in order. @@ -265,6 +272,8 @@ impl World { box_open: false, prompt: false, scripted: false, + ledges: Vec::new(), + hop: None, scripted_at: None, pulses: Vec::new(), held: 0, @@ -393,6 +402,23 @@ impl World { fn frame(&mut self, mask: u8) { self.frames += 1; + // A ledge hop in flight: the cartridge's own joypad states, whatever is pressed. + if let Some((left, over, landing)) = self.hop { + let left = left.saturating_sub(1); + if left == 8 { + self.player = over; + } + if left == 0 { + self.player = landing; + self.scene = Scene::Overworld; + self.scripted = false; + self.hop = None; + } else { + self.hop = Some((left, over, landing)); + } + self.previous = mask; + return; + } if let Some((at, next)) = self.pending && self.frames >= at { @@ -537,6 +563,15 @@ impl World { return; } let next = Tile::new(x as u8, y as u8); + // `HandleLedges`: the press over a ledge takes the joypad and hops two tiles. + if self.ledges.contains(&(self.player, facing)) + && let Some(landing) = next.step(facing) + { + self.scene = Scene::Unknown; + self.scripted = true; + self.hop = Some((16, next, landing)); + return; + } if self.walkable(next.x, next.y) != Walkable::Yes { return; } @@ -750,6 +785,25 @@ impl MacroState for World { fn objective(&mut self) -> Option { self.objective } + + /// The decoded grid, only for a world with ledges in it (row 64): the same walls the window + /// reads, plus the hops. Every other fixture keeps answering from the window, as before. + fn map_grid(&mut self) -> Option> { + if self.ledges.is_empty() { + return None; + } + let mut grid = super::state::MapGrid::new(self.map, self.size.width, self.size.height); + for y in 0..self.size.height { + for x in 0..self.size.width { + let wall = self.walls.contains(&Tile::new(x, y)); + grid.set(x, y, if wall { 0x60 } else { 0x01 }, if wall { Walkable::No } else { Walkable::Yes }); + } + } + for (tile, facing) in &self.ledges { + grid.ledge(tile.x, tile.y, *facing); + } + Some(std::sync::Arc::new(grid)) + } } fn direction_of(mask: u8) -> Option { @@ -5523,3 +5577,38 @@ fn a_walk_off_its_ladder_does_not_step_onto_another_warp() { assert_eq!(run(&mut world, MacroKind::GoWarp), Ok(MacroAbort::Blocked)); assert_eq!(world.map, 0x25, "the other ladder was not taken for this one"); } + +#[test] +fn a_ledge_the_walk_presses_into_is_hopped_and_is_not_a_push_back() { + // Row 64, Route 4 east of Mt. Moon: Cerulean is three ledges down from the cave's exit, and a + // ledge read as a wall both ways, so `GO OBJECTIVE` refused `no route` there. The route search + // takes a hop the one way the cartridge does, and the walk waits while the cartridge carries + // the fly over -- `HandleLedges` takes the joypad for it, which is the same reading as a + // scripted push-back, and a push-back walls the tile for the session. + let mut world = World::room().at(3, 1); + world.map = 0x0f; + for x in 0..8 { + world.walls.insert(Tile::new(x, 3)); + world.ledges.push((Tile::new(x, 2), Facing::Down)); + } + let goal = Tile::new(3, 6); + world.objective = Some(Objective { map: 0x0f, tile: Some(goal), warp: None, edge: None, target: None }); + let mut machine = MacroMachine::new(0x1234_5678); + assert_eq!(run_with(&mut machine, &mut world, MacroKind::GoObjective), Ok(MacroAbort::Done)); + assert_eq!(world.player, goal, "over the ledge and on to the goal in one walk"); + hand_back(&mut machine, &mut world); + assert!(world.pushes.is_empty(), "the hop the walk asked for walled nothing: {:?}", world.pushes); + assert!(!world.targets.blocked(world.map, TargetKey::Tile(goal)), "nor rested the goal"); + + // From below, the ledge is a wall: nothing plans up it. + let mut below = World::room().at(3, 6); + below.map = 0x0f; + for x in 0..8 { + below.walls.insert(Tile::new(x, 3)); + below.ledges.push((Tile::new(x, 2), Facing::Down)); + } + below.objective = + Some(Objective { map: 0x0f, tile: Some(Tile::new(3, 1)), warp: None, edge: None, target: None }); + assert!(run(&mut below, MacroKind::GoObjective).is_err(), "a ledge is not climbed"); + assert_eq!(below.player, Tile::new(3, 6)); +} diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests/map_aware.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests/map_aware.rs index 1257e99..0226bf1 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests/map_aware.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests/map_aware.rs @@ -36,6 +36,8 @@ struct Ground { npcs: Vec, /// Whether the whole map is decoded, or only the window can answer. decoded: bool, + /// Ledges, as the tile a press hops from and its direction, as the grid records them (row 64). + ledges: Vec<(Tile, Facing)>, } impl Ground { @@ -52,6 +54,7 @@ impl Ground { connections: Connections::default(), npcs: Vec::new(), decoded: true, + ledges: Vec::new(), } } @@ -205,6 +208,9 @@ impl MacroState for Ground { for (tile, facing) in &self.pair_walls { grid.wall(tile.x, tile.y, *facing); } + for (tile, facing) in &self.ledges { + grid.ledge(tile.x, tile.y, *facing); + } Some(Arc::new(grid)) } @@ -342,3 +348,32 @@ fn a_connection_on_the_far_edge_is_a_goal_and_the_walls_along_it_are_not() { .count(); assert_eq!(count, 20); } + +#[test] +fn a_ledge_is_one_press_down_and_a_wall_up() { + // Row 64: Route 4 east of Mt. Moon, where every road to Cerulean is a ledge down. A row of + // ledge tiles across the map, which the collision list calls a wall. + let mut ground = Ground::new(12, 10, (5, 1)); + for x in 0..12 { + ground.walls.insert(Tile::new(x, 4)); + ground.ledges.push((Tile::new(x, 3), Facing::Down)); + } + let below = Tile::new(5, 8); + let route = path::route(&mut ground, &[below]).expect("a route down"); + assert_eq!(route.goal, Some(0), "the goal itself, over the ledge"); + // Two steps to the ledge's edge, one press that hops two tiles, three steps on. + assert_eq!(route.steps, vec![Facing::Down; 6]); + + // Up is a wall: the search gets as close as it can and reaches nothing. + ground.player = below; + let route = path::route(&mut ground, &[Tile::new(5, 1)]); + assert!(route.as_ref().is_none_or(|route| route.goal.is_none()), "a ledge is not climbed: {route:?}"); + + // And without the decoded grid there is nothing to read a ledge from: a wall, as before. + let mut blind = Ground::new(12, 10, (5, 1)); + for x in 0..12 { + blind.walls.insert(Tile::new(x, 4)); + } + let route = path::route(&mut blind, &[below]); + assert!(route.as_ref().is_none_or(|route| route.goal.is_none()), "no hop without a ledge: {route:?}"); +} diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid.rs index d13e630..0a76ceb 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid.rs @@ -29,6 +29,8 @@ //! What it does **not** model is what it did not model before: sprites standing on ground (the //! sprite list answers that, and [`super::macros::path::frontier`] reads it), warps that fire on //! the step onto them, and scripts that push the fly off a tile (a session ledger answers that). +//! Ledges it has modelled since row 64 ([`LEDGE_TILES`]): a wall in the collision list, and a hop +//! the route search may take the one way the cartridge takes it. use std::sync::Arc; @@ -76,6 +78,7 @@ const ANCHOR_ROW: usize = 1; /// Tileset ids the tile-pair lists name (`constants/tileset_constants.asm`, counted in the order /// that file declares them: OVERWORLD 0 … FOREST 3 … CAVERN 17). pub mod tileset { + pub const OVERWORLD: u8 = 0; pub const FOREST: u8 = 3; pub const CAVERN: u8 = 17; } @@ -110,6 +113,31 @@ pub const TILE_PAIRS_LAND: [(u8, u8, u8); 11] = [ (tileset::FOREST, 0x5f, 0x2e), ]; +/// `LedgeTiles` at the pinned pokered commit, as `(facing, the tile stood on, the ledge tile)`. +/// +/// `data/tilesets/ledge_tiles.asm`, read by `HandleLedges` (`engine/overworld/ledges.asm`) on the +/// OVERWORLD tileset only (`wCurMapTileset` is 0 or it returns): when the player faces one of +/// these ledge tiles from one of these tiles with that direction held, the cartridge takes the +/// joypad and hops the player **two** tiles that way. Both tiles are the ones +/// `_GetTileAndCoordsInFrontOfPlayer` reads -- screen `(8, 9)` for the player's own and `(8, 11)`, +/// `(8, 7)`, `(6, 9)` or `(10, 9)` for the one in front -- which is the lower-left corner of each +/// map tile's quadrant, the same corner [`ANCHOR_ROW`] decodes. The input column of the table is +/// the facing again, so it is not repeated. +/// +/// The ledge tile is absent from every passable list, which is why a ledge read as a wall in both +/// directions before row 64 and why nothing east of Mt. Moon could be walked to from its exit: +/// Route 4's road down to Cerulean is three ledges, and every one of them faces away from the cave. +pub const LEDGE_TILES: [(Facing, u8, u8); 8] = [ + (Facing::Down, 0x2c, 0x37), + (Facing::Down, 0x39, 0x36), + (Facing::Down, 0x39, 0x37), + (Facing::Left, 0x2c, 0x27), + (Facing::Left, 0x39, 0x27), + (Facing::Right, 0x2c, 0x0d), + (Facing::Right, 0x2c, 0x1d), + (Facing::Right, 0x39, 0x0d), +]; + /// The tileset's two tables, as the decoder needs them. /// /// Gathered by [`super::state::map_grid`] from WRAM and ROM; separate from the decoding so that @@ -178,9 +206,40 @@ pub fn decode(map: u8, width_blocks: u8, height_blocks: u8, blocks: &[u8], tiles } } add_pair_walls(&mut grid, tiles.id); + add_ledge_hops(&mut grid, tiles.id); grid } +/// Mark every ledge the loaded tileset has as a hop out of the tile in front of it ([`LEDGE_TILES`]). +/// +/// Only where the cartridge would take it: the OVERWORLD tileset, a ledge tile in front, and a +/// landing two tiles away that is still on the map. Whether the landing is ground is the route +/// search's question, as it is for every step. +fn add_ledge_hops(grid: &mut MapGrid, tileset: u8) { + if tileset != tileset::OVERWORLD { + return; + } + for y in 0..grid.height() { + for x in 0..grid.width() { + let Some(here) = grid.tile_id(x, y) else { continue }; + for (facing, stood, ledge) in LEDGE_TILES { + if here != stood { + continue; + } + let (dx, dy) = facing.delta(); + let (Some(nx), Some(ny)) = (checked_step(x, dx), checked_step(y, dy)) else { continue }; + let (Some(lx), Some(ly)) = (checked_step(nx, dx), checked_step(ny, dy)) else { continue }; + if lx >= grid.width() || ly >= grid.height() { + continue; + } + if grid.tile_id(nx, ny) == Some(ledge) { + grid.ledge(x, y, facing); + } + } + } + } +} + /// Turn every tile-pair collision the loaded tileset has into two directed walls. fn add_pair_walls(grid: &mut MapGrid, tileset: u8) { let pairs: Vec<(u8, u8)> = TILE_PAIRS_LAND diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid/tests.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid/tests.rs index 4ce210a..0b6c3a8 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid/tests.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid/tests.rs @@ -162,3 +162,37 @@ fn the_cache_holds_one_map_and_drops_it_on_arrival_somewhere_else() { assert_eq!(grids.held(), Some(4)); assert!(grids.get(3, 4, 4).is_none()); } + +#[test] +fn a_ledge_is_a_hop_from_above_on_the_overworld_tileset_only() { + // `LedgeTiles`: facing down from `$2C` onto `$37` hops two tiles down. Row 64, Route 4. + let mut grid = MapGrid::new(0x0f, 2, 5); + for y in 0..5 { + grid.set(0, y, 0x2c, Walkable::Yes); + } + grid.set(1, 0, 0x2c, Walkable::Yes); + grid.set(1, 1, 0x37, Walkable::No); + grid.set(1, 2, 0x2c, Walkable::Yes); + grid.set(1, 3, 0x2c, Walkable::Yes); + grid.set(1, 4, 0x2c, Walkable::Yes); + add_ledge_hops(&mut grid, tileset::OVERWORLD); + assert!(grid.hops(1, 0, Facing::Down), "down over the ledge from above"); + assert!(!grid.hops(1, 2, Facing::Up), "never up it from below"); + assert!(!grid.hops(0, 0, Facing::Down), "plain ground is not a ledge"); + assert!(!grid.hops(1, 0, Facing::Right), "only the direction the table names"); + + // `HandleLedges` returns at once on any other tileset. + let mut plain = MapGrid::new(0x3d, 2, 5); + for y in 0..5 { + plain.set(1, y, grid.tile_id(1, y).unwrap_or(0), grid.walkable(1, y)); + } + add_ledge_hops(&mut plain, tileset::CAVERN); + assert!(!plain.hops(1, 0, Facing::Down), "no ledges in a cave"); + + // A ledge whose landing would be off the map is not a hop the table can promise. + let mut edge = MapGrid::new(0x0f, 1, 2); + edge.set(0, 0, 0x2c, Walkable::Yes); + edge.set(0, 1, 0x37, Walkable::No); + add_ledge_hops(&mut edge, tileset::OVERWORLD); + assert!(!edge.hops(0, 0, Facing::Down)); +} diff --git a/services/flysim/crates/flysim/tests/rom_macros_mode.rs b/services/flysim/crates/flysim/tests/rom_macros_mode.rs index 38ba60e..c0fe434 100644 --- a/services/flysim/crates/flysim/tests/rom_macros_mode.rs +++ b/services/flysim/crates/flysim/tests/rom_macros_mode.rs @@ -3806,3 +3806,165 @@ fn a_trainers_challenge_does_not_wall_the_road_to_the_forests_north_gate() { assert!(route_2_north.is_some(), "nor Route 2 through it: {arrivals:?}"); assert!(pewter.is_some(), "nor Pewter City: {arrivals:?}"); } + +fn row64_checkpoint() -> Option { + std::env::var_os("FLY_ROW64_CHECKPOINT").map(|path| { + flysim::store::load(std::path::Path::new(&path)) + .expect("the checkpoint should be a FLYSIM01 envelope") + }) +} + +/// Mt. Moon's far side, from the checkpoint pulled during the two-day ring. +/// +/// **What was live** (2026-09-26 to 09-28, v0.6.2/v0.6.4, rank 12 MT. MOON, the objective Cerulean +/// City): about 750 macros per ten brain minutes, every one `done`, no reward, no new ground -- +/// `GO OBJECTIVE` and `GO WARP`, 27 frames each. Forty-eight hourly flysim restarts did not clear +/// it and a milestone reset bought hours (`infra/docs/macros-traps.md` row 64). The fly stands on +/// B2F (5, 7), the ladder up to B1F's exit chamber, which is the one road on. Two things stacked: +/// +/// - a warp whose exit has no press fires at the end of a **step onto it** +/// (`CheckWarpsNoCollision`), and both buttons aimed at the tile underfoot, settled on it and +/// reported `done` without a press -- section 12.2's trap with no ledger in it, so a restore +/// restores it; +/// - off the ladder, the road reaches Route 4's east side, where Cerulean is three **ledges** down. +/// The route search read a ledge as a wall both ways, so `GO OBJECTIVE` refused `no route`, the +/// edge rested in the blocked ledger, and the other walks took the fly back into the cave -- +/// onto B1F's exit (27, 3), the same trap one floor up. +/// +/// The driver is the real palette with the live brain's measured favourites pressed whenever they +/// are dealt (`GO OBJECTIVE`, then `GO WARP`) and one xorshift choice per hold otherwise: a harness +/// choice, not the fly's. On the base it never leaves (5, 7). The claims: +/// +/// - **the first `GO OBJECTIVE`, started on the ladder, takes it**: the map has changed when it ends; +/// - **the fly hops a ledge on Route 4** under a walk (`wMovementFlags` bit 6 with a macro running), +/// and **no tile enters the pushed ledger on the way down**: a hop the walk asked for is not a push-back; +/// - **the fly reaches Cerulean City** inside the budget. +/// +/// ```sh +/// FLY_ROM=/path/to/pokemon-red.gb \ +/// FLY_ROW64_CHECKPOINT= \ +/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture mt_moons_far_side +/// ``` +#[test] +fn the_fly_takes_the_ladder_it_stands_on_and_hops_down_to_cerulean_from_mt_moons_far_side() { + use flybrain_gb::pokemon_red::macros::PokemonPalette; + use flybrain_gb::pokemon_red::state; + use flybrain_gb::{MacroPalette, MemoryReader, Outcome, Started}; + const MT_MOON_B2F: u8 = 0x3d; + const ROUTE_4: u8 = 0x0f; + const CERULEAN: u8 = 0x03; + const LEDGE_OR_FISHING: u8 = 1 << 6; + let rom = skip_without_rom!(); + let Some(checkpoint) = row64_checkpoint() else { + eprintln!("skipped: no FLY_ROW64_CHECKPOINT"); + return; + }; + let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint); + let start = state::player(&mut run.gb).expect("a loaded map"); + assert_eq!((start.map, start.x, start.y), (MT_MOON_B2F, 5, 7), "the checkpoint is on B2F's exit ladder"); + + let budget = 8_000u32; + let hold_frames = 48u32; + let mut palette = PokemonPalette::new(SEED); + let mut rng = 20_260_928u32 | 1; + let mut running = false; + let mut since_decision = hold_frames; + let mut ms = run.ms; + let mut arrivals: Vec<(u32, u8)> = Vec::new(); + let mut last = None; + let mut first_objective: Option<(u8, u8)> = None; + let mut first_started_on: Option = None; + let mut hop_frames = 0u32; + let mut done_in_place = 0u32; + // The pushed ledger as it stood when the fly first arrived in Cerulean City: the road from the + // ladder over the ledges. + let mut pushed_on_the_way: Option = None; + let mut walled = false; + for frame in 0..budget { + palette.clock(ms); + let observed = { + let ledger = AdapterLedger(&run.adapter); + palette.observe(&mut run.gb, &ledger) + }; + let before = state::player(&mut run.gb).map(|player| (player.map, player.x, player.y)); + let mut mask = 0u8; + { + let ledger = AdapterLedger(&run.adapter); + if running { + match palette.step(&mut run.gb, &ledger) { + Some(held) => mask = held, + None => running = false, + } + } else if since_decision >= hold_frames && !observed.bindings.is_empty() { + since_decision = 0; + rng ^= rng << 13; + rng ^= rng >> 17; + rng ^= rng << 5; + let binding = ["GO OBJECTIVE", "GO WARP"] + .iter() + .find_map(|want| observed.bindings.iter().find(|binding| binding.name == *want)) + .unwrap_or(&observed.bindings[rng as usize % observed.bindings.len()]); + if let Started::Running(_) = palette.start(binding.slot, &mut run.gb, &ledger) { + if first_started_on.is_none() && binding.name == "GO OBJECTIVE" { + first_started_on = before.map(|(map, _, _)| map); + } + running = true; + match palette.step(&mut run.gb, &ledger) { + Some(held) => mask = held, + None => running = false, + } + } + } + } + since_decision += 1; + run.gb.set_buttons(mask); + run.gb.run_frame().expect("a frame should complete"); + ms += MS_PER_FRAME; + run.adapter.sample(&mut run.gb, ms); + if let Some((name, outcome)) = palette.take_finished() { + let after = state::player(&mut run.gb).map(|player| player.map); + if name == "GO OBJECTIVE" && first_objective.is_none() { + first_objective = first_started_on.zip(after); + } + if matches!(outcome, Outcome::Done) + && matches!(name, "GO OBJECTIVE" | "GO WARP") + && after == Some(MT_MOON_B2F) + && state::player(&mut run.gb).is_some_and(|player| (player.x, player.y) == (5, 7)) + { + done_in_place += 1; + } + } + if running + && state::player(&mut run.gb).is_some_and(|player| player.map == ROUTE_4) + && run.gb.read8(flybrain_gb::pokemon_red::symbols::ram::wMovementFlags) & LEDGE_OR_FISHING != 0 + { + hop_frames += 1; + } + if let Some(player) = state::player(&mut run.gb) + && last != Some(player.map) + { + last = Some(player.map); + arrivals.push((frame, player.map)); + if player.map == CERULEAN && pushed_on_the_way.is_none() { + pushed_on_the_way = Some(format!("{:?}", palette.fences().0)); + walled = !palette.fences().0.is_empty(); + } + } + } + let cerulean = arrivals.iter().find(|(_, map)| *map == CERULEAN).map(|(frame, _)| *frame); + let route_4_pushed = pushed_on_the_way.unwrap_or_else(|| format!("{:?}", palette.fences().0)); + eprintln!( + "{:.1} brain minutes: first GO OBJECTIVE {first_objective:?}, done on the ladder in place \ + {done_in_place}, hop frames under a walk on Route 4 {hop_frames}, Cerulean City at \ + {cerulean:?}, pushed on the way {route_4_pushed}, rank {}, arrivals {arrivals:?}", + (ms - run.ms) / 60_000.0, + run.adapter.progress().rank, + ); + assert_eq!(done_in_place, 0, "a walk reported done on the ladder it had not taken"); + let (from, to) = first_objective.expect("GO OBJECTIVE was never started and finished"); + assert_eq!(from, MT_MOON_B2F, "the first GO OBJECTIVE started on B2F's ladder"); + assert_ne!(to, MT_MOON_B2F, "the first GO OBJECTIVE ended where it began: {arrivals:?}"); + assert!(hop_frames > 0, "no ledge was hopped under a walk on Route 4: {arrivals:?}"); + assert!(!walled, "a tile was walled on the way down to Cerulean City: {route_4_pushed}"); + assert!(cerulean.is_some(), "the fly never reached Cerulean City: {arrivals:?}"); +}