state: what the cartridge does with an item from the battle bag, and whether it still holds an A

item_routine reads ItemUsePtrTable ($03:$55E1) by id and checks it by its own shape;
battle_item_use answers each routine's refusal on bytes already in WRAM. a_latched reads
hJoyLast, the reading the joypad edge is made against. MacroState gains item_refused and
a_latched, both off by default.
This commit is contained in:
acamilo 2026-09-24 04:04:08 +00:00
parent 862e343e1c
commit 113970f4e1
4 changed files with 358 additions and 0 deletions

View file

@ -430,6 +430,35 @@ impl Wram {
self self
} }
/// The cartridge's `ItemUsePtrTable`, one pointer per item id, grouped the way the pinned
/// commit groups them: the balls share one routine, the potions, drinks, status heals and
/// revives another, the four X stat items another, the four PP restores another, and every
/// item with no use in a battle points at `UnusableItem` here (the real table spreads those
/// over a dozen routines, all of which refuse inside a battle). The addresses are the
/// cartridge's own; only their grouping is under test.
pub fn item_table(&mut self) -> &mut Self {
use super::state::poke::items::{LAST_ITEM, TABLE_ADDRESS, TABLE_BANK};
for id in 1..=LAST_ITEM {
let routine: u16 = match id {
0x01..=0x04 | 0x08 => 0x5687,
0x0b..=0x14 | 0x34..=0x36 | 0x3c..=0x3e => 0x5abb,
0x2e => 0x6013,
0x33 => 0x60cd,
0x37 => 0x60dc,
0x3a => 0x60f5,
0x41..=0x44 => 0x6104,
0x49 => 0x6140,
0x50..=0x53 => 0x631e,
_ => 0x6476,
};
let at = TABLE_ADDRESS + 2 * u16::from(id - 1);
let [low, high] = routine.to_le_bytes();
self.rom.insert((TABLE_BANK, at), low);
self.rom.insert((TABLE_BANK, at + 1), high);
}
self
}
/// One byte of a fake cartridge bank. /// One byte of a fake cartridge bank.
pub fn rom_byte(&mut self, bank: u8, address: u16, byte: u8) -> &mut Self { pub fn rom_byte(&mut self, bank: u8, address: u16, byte: u8) -> &mut Self {
self.rom.insert((bank, address), byte); self.rom.insert((bank, address), byte);

View file

@ -388,6 +388,26 @@ pub trait MacroState: GameState {
false false
} }
/// Whether the cartridge would refuse bag item `id` if the fly chose it from the battle bag on
/// this frame -- "It won't have any effect.", "This isn't the time to use that!", a ball at a
/// trainer's Pokémon -- and put the fly back in the bag with nothing changed.
///
/// Row 63 (`docs/design/macros.md` 12.27), read from the cartridge's own `ItemUsePtrTable`
/// and the checks each routine makes ([`crate::pokemon_red::state::battle_item_use`]). The
/// default is `false`: a state that cannot read the table has proved nothing.
fn item_refused(&mut self, _id: u8) -> bool {
false
}
/// Whether the cartridge still holds `A` down from the last time it read the joypad, so an
/// `A` pressed now is no edge and is not a press (row 63,
/// [`crate::pokemon_red::state::a_latched`]). A confirming press waits while this holds. The
/// default is `false`: a state that cannot read the latch presses when the list reads open,
/// which is what every script did before.
fn a_latched(&mut self) -> bool {
false
}
/// Whether a `GO FRONTIER` on this map has already proved its frontier unreachable. /// Whether a `GO FRONTIER` on this map has already proved its frontier unreachable.
/// ///
/// [`FrontierLedger`] is the evidence and the measurement. The default is `false`: a state /// [`FrontierLedger`] is the evidence and the measurement. The default is `false`: a state

View file

@ -43,6 +43,13 @@ use super::symbols::ram;
/// `const`s that no symbol table carries, so each one names its file. /// `const`s that no symbol table carries, so each one names its file.
pub mod poke { pub mod poke {
/// `constants/hardware.inc`. /// `constants/hardware.inc`.
/// `ram/hram.asm`: `hJoyLast`, the buttons `_Joypad` saw down the last time the game asked
/// (`engine/joypad.asm`). The first of the seven joypad bytes (`hJoyLast`, `hJoyReleased`,
/// `hJoyPressed`, `hJoyHeld`, `hJoy5`..`hJoy7`) at `$FFB1`: read from the operand of
/// `_Joypad`'s `ldh a, [hJoyLast]` on the cartridge, and pinned by the ROM-gated test that
/// reads it back from there (row 63, `docs/design/macros.md` 12.27).
pub const H_JOY_LAST: u16 = 0xffb1;
pub mod pad { pub mod pad {
pub const A: u8 = 1 << 0; pub const A: u8 = 1 << 0;
pub const B: u8 = 1 << 1; pub const B: u8 = 1 << 1;
@ -285,6 +292,47 @@ pub mod poke {
pub const TYPE_GROUND: u8 = 0x04; pub const TYPE_GROUND: u8 = 0x04;
pub const TYPE_ELECTRIC: u8 = 0x17; pub const TYPE_ELECTRIC: u8 = 0x17;
} }
/// The cartridge's item-use dispatch and the ids that name its routines (row 63,
/// `docs/design/macros.md` 12.27).
pub mod items {
/// `engine/items/item_effects.asm`: `UseItem_` jumps through `ItemUsePtrTable`, one
/// little-endian pointer per item id from `MASTER_BALL` (1) to `MAX_ELIXER` (`$53`), in
/// `SECTION "bank3"`. At the pinned commit the table is at `$03:$55E1`: read from the
/// operand of `UseItem_`'s `ld hl, ItemUsePtrTable` and checked by
/// [`super::super::item_routine`] against the table's own shape on every read.
pub const TABLE_BANK: u8 = 0x03;
pub const TABLE_ADDRESS: u16 = 0x55e1;
pub const LAST_ITEM: u8 = 0x53;
/// `constants/item_constants.asm`. Each id below stands for the routine the table gives
/// it, and every other item is classed by the routine the table gives *it*: an item whose
/// pointer is `POTION`'s is medicine, whatever its id.
pub const MASTER_BALL: u8 = 0x01;
pub const POKE_BALL: u8 = 0x04;
pub const SAFARI_BALL: u8 = 0x08;
pub const ANTIDOTE: u8 = 0x0b;
pub const BURN_HEAL: u8 = 0x0c;
pub const ICE_HEAL: u8 = 0x0d;
pub const AWAKENING: u8 = 0x0e;
pub const PARLYZ_HEAL: u8 = 0x0f;
pub const FULL_RESTORE: u8 = 0x10;
pub const POTION: u8 = 0x14;
pub const HP_UP: u8 = 0x23;
pub const X_ACCURACY: u8 = 0x2e;
pub const POKE_DOLL: u8 = 0x33;
pub const FULL_HEAL: u8 = 0x34;
pub const REVIVE: u8 = 0x35;
pub const MAX_REVIVE: u8 = 0x36;
pub const GUARD_SPEC: u8 = 0x37;
pub const DIRE_HIT: u8 = 0x3a;
pub const X_ATTACK: u8 = 0x41;
pub const POKE_FLUTE: u8 = 0x49;
pub const ETHER: u8 = 0x50;
/// `constants/pokemon_data_constants.asm`: `PARTY_LENGTH`.
pub const PARTY_LENGTH: u8 = 6;
}
} }
fn read(memory: &mut dyn MemoryReader, address: u16) -> u8 { fn read(memory: &mut dyn MemoryReader, address: u16) -> u8 {
@ -786,6 +834,147 @@ pub fn move_without_effect(memory: &mut dyn MemoryReader, id: u8) -> Option<bool
}) })
} }
/// The routine the cartridge's `ItemUsePtrTable` runs for item `id`, as its bank-3 address.
///
/// `None` when the seam has no cartridge behind it, when `id` is not an item the table covers
/// (a TM or an HM goes to `ItemUseTMHM` before the table is asked, and is never usable in a
/// battle), or when the table is not the one the disassembly describes: the five balls share one
/// routine and the potions and status heals share another, so a table where `POKE_BALL` and
/// `SAFARI_BALL` or `POTION` and `ANTIDOTE` part company is somebody else's bytes and answers
/// nothing.
pub fn item_routine(memory: &mut dyn MemoryReader, id: u8) -> Option<u16> {
use poke::items::*;
let entry = |memory: &mut dyn MemoryReader, id: u8| -> Option<u16> {
let at = TABLE_ADDRESS + 2 * u16::from(id - 1);
let low = memory.read_rom(TABLE_BANK, at)?;
let high = memory.read_rom(TABLE_BANK, at + 1)?;
Some(u16::from_le_bytes([low, high])).filter(|address| (0x4000..0x8000).contains(address))
};
if id == 0 || id > LAST_ITEM {
return None;
}
let ball = entry(memory, POKE_BALL)?;
let medicine = entry(memory, POTION)?;
if [MASTER_BALL, SAFARI_BALL].into_iter().any(|other| entry(memory, other) != Some(ball))
|| entry(memory, ANTIDOTE) != Some(medicine)
|| ball == medicine
{
return None;
}
entry(memory, id)
}
/// Whether the cartridge would **take** bag item `id` if the fly chose it from the battle bag on
/// this frame: the item is used and the turn goes on, rather than "This isn't the time to use
/// that!", "It won't have any effect." or a ball thrown at a trainer's Pokémon, after which the
/// fly is back in the bag with nothing changed.
///
/// Row 63 (`docs/design/macros.md` 12.27). Which routine an item runs is the cartridge's own
/// `ItemUsePtrTable` ([`item_routine`]), and each routine's answer is the check it makes before
/// it does anything, on bytes already in WRAM (`engine/items/item_effects.asm`):
///
/// - a **ball** (`ItemUseBall`): a wild battle; against a trainer it is "The trainer blocked the
/// BALL!", the ball spent for nothing. With a full party the box decides, and the box count is
/// not read here, so that answer is `None`;
/// - **medicine** (`ItemUseMedicine`): somebody in the party it would change -- for an HP item a
/// Pokémon neither fainted nor full (a Full Restore also cures a status at full HP), for a
/// Revive a fainted one, for a status heal a Pokémon with that status (a Full Heal any). The
/// Pokémon that is out is read from the battle's own copy, which is the one the engine damages;
/// - `X_ACCURACY`, `GUARD_SPEC`, `DIRE_HIT`, the four X stat items and the `POKE_FLUTE`: any
/// battle;
/// - `POKE_DOLL`: a wild battle;
/// - `ETHER` and its three siblings: a party move below its PP (PP Ups are counted);
/// - every other routine -- a vitamin, a stone, a repel, an Escape Rope, a key item, a badge
/// pseudo-item -- refuses inside a battle.
///
/// `None` outside a battle this module understands, or when the table cannot be read: a refusal
/// this module cannot read is not one it reports.
pub fn battle_item_use(memory: &mut dyn MemoryReader, id: u8) -> Option<bool> {
use poke::items::*;
let kind = in_battle(memory)?;
let routine = item_routine(memory, id)?;
let of = |memory: &mut dyn MemoryReader, anchor: u8| item_routine(memory, anchor);
if Some(routine) == of(memory, POKE_BALL) {
if kind != BattleKind::Wild {
return Some(false);
}
return (read(memory, ram::wPartyCount) < PARTY_LENGTH).then_some(true);
}
if Some(routine) == of(memory, POKE_DOLL) {
return Some(kind == BattleKind::Wild);
}
if [X_ACCURACY, GUARD_SPEC, DIRE_HIT, X_ATTACK, POKE_FLUTE]
.into_iter()
.any(|anchor| of(memory, anchor) == Some(routine))
{
return Some(true);
}
// The party as the item routines see it, with the Pokémon that is out read from the battle's
// copy: `ReadPlayerMonCurHPAndStatus` writes it back to the party struct at the top of every
// turn, and the battle copy is the one the damage went to.
let mut mons = party(memory).mons;
if let Some(out) = own_mon(memory)
&& let Some(mon) = mons.iter_mut().find(|mon| mon.slot == out.slot)
{
mon.hp = out.hp;
mon.status = out.status;
}
if Some(routine) == of(memory, POTION) {
let cures = |status: Status| -> bool {
match id {
ANTIDOTE => status == Status::Poison,
BURN_HEAL => status == Status::Burn,
ICE_HEAL => status == Status::Freeze,
AWAKENING => matches!(status, Status::Sleep(_)),
PARLYZ_HEAL => status == Status::Paralysis,
_ => status != Status::Healthy,
}
};
// `ItemUseMedicine`'s own order: Revive and Max Revive, then Full Heal, then the HP items
// (Full Restore to Potion, and the three drinks past Revive), then the status heals.
let takes = |mon: &Mon| -> bool {
let fainted = mon.hp == 0;
match id {
REVIVE | MAX_REVIVE => fainted,
FULL_HEAL => !fainted && cures(mon.status),
FULL_RESTORE => !fainted && (mon.hp < mon.max_hp || cures(mon.status)),
_ if id > MAX_REVIVE || (FULL_RESTORE..=POTION).contains(&id) => {
!fainted && mon.hp < mon.max_hp
}
_ if id < FULL_RESTORE => !fainted && cures(mon.status),
_ => false,
}
};
return Some(mons.iter().any(takes));
}
if Some(routine) == of(memory, ETHER) {
let spent = |memory: &mut dyn MemoryReader, entry: &Move| -> bool {
let ups = entry.pp_up;
match move_data(memory, entry.id) {
Some(data) => entry.pp < data.pp + (data.pp / 5) * ups,
None => true,
}
};
let moves: Vec<Move> = mons.iter().flat_map(|mon| mon.moves.iter().flatten().copied()).collect();
return Some(moves.iter().any(|entry| spent(memory, entry)));
}
Some(false)
}
/// Whether the cartridge still has `A` down from the last time it read the joypad.
///
/// Row 63 (`docs/design/macros.md` 12.27). `_Joypad` makes a press out of an *edge* --
/// `hJoyPressed` is what is down now and was not down in `hJoyLast` -- and the game only asks
/// while something is reading input. So after the A that confirms a list, the game stops asking
/// while it draws the next one, `hJoyLast` keeps that A, and an A issued before the new list's
/// first read is down on both sides of the comparison: no edge, no press. Measured on the
/// Potion's party list from the row-63 checkpoint: the list's cursor bytes read open at once, an
/// A in the first 22 frames is swallowed every time, and `hJoyLast` separates the refused frames
/// from the answered ones exactly (`infra/docs/macros-traps.md` row 63).
pub fn a_latched(memory: &mut dyn MemoryReader) -> bool {
read(memory, poke::H_JOY_LAST) & poke::pad::A != 0
}
/// Whether a text box is open, and whether the bottom-of-screen dialogue box is the one drawn. /// Whether a text box is open, and whether the bottom-of-screen dialogue box is the one drawn.
/// ///
/// `open` is `wFontLoaded`'s bit 0, which `DisplayTextIDInit` sets for every text display — the /// `open` is `wFontLoaded`'s bit 0, which `DisplayTextIDInit` sets for every text display — the
@ -1974,6 +2163,14 @@ impl MacroState for PokeState<'_> {
move_without_effect(self.memory, id).unwrap_or(false) move_without_effect(self.memory, id).unwrap_or(false)
} }
fn item_refused(&mut self, id: u8) -> bool {
battle_item_use(self.memory, id) == Some(false)
}
fn a_latched(&mut self) -> bool {
a_latched(self.memory)
}
/// The whole loaded map's walkability, from the cache when it is for this map /// The whole loaded map's walkability, from the cache when it is for this map
/// (`docs/design/macros.md` section 15). /// (`docs/design/macros.md` section 15).
/// ///

View file

@ -1253,3 +1253,115 @@ fn a_trainers_challenge_is_the_cartridges_until_its_battle_is_over() {
assert_eq!(PokeState::new(&mut after).scene(), Scene::Overworld); assert_eq!(PokeState::new(&mut after).scene(), Scene::Overworld);
assert!(!PokeState::new(&mut after).scripted()); assert!(!PokeState::new(&mut after).scripted());
} }
// ---------------------------------------------------------------------------------------------
// Row 63: what the cartridge does with an item chosen from the battle bag, and its joypad latch
// ---------------------------------------------------------------------------------------------
const ANTIDOTE: u8 = 0x0b;
const POTION: u8 = 0x14;
const POKE_BALL: u8 = 0x04;
const ESCAPE_ROPE: u8 = 0x1d;
const X_ATTACK: u8 = 0x41;
const POKE_DOLL: u8 = 0x33;
const REVIVE: u8 = 0x35;
const ETHER: u8 = 0x50;
const TM34: u8 = 0xea;
/// The row-63 battle: a wild Geodude, and Wartortle out at 8 of 86 with the bag the live fly
/// carried (an Antidote, a Potion and TM34).
fn bag_battle() -> Wram {
let mut wram = Wram::new();
wram.party_mon(0, 0xb3, 28, 8, 86, 0, &[(44, 0), (55, 25)])
.battle_mon(0, 0xb3, 28, 8, 86, 0, &[(44, 0), (55, 25)])
.enemy_mon(0xa9, 9, 28, 28)
.battle(1)
.bag(&[(ANTIDOTE, 1), (POTION, 1), (TM34, 1)])
.item_table();
wram
}
#[test]
fn the_item_table_is_read_by_id_and_checked_against_its_own_shape() {
let mut wram = bag_battle();
assert_eq!(item_routine(&mut wram, POKE_BALL), item_routine(&mut wram, 0x01));
assert_eq!(item_routine(&mut wram, POTION), item_routine(&mut wram, ANTIDOTE));
assert_ne!(item_routine(&mut wram, POTION), item_routine(&mut wram, POKE_BALL));
assert_eq!(item_routine(&mut wram, 0), None, "no item zero");
assert_eq!(item_routine(&mut wram, TM34), None, "a TM is ItemUseTMHM's, before the table");
assert_eq!(item_routine(&mut Wram::new(), POTION), None, "no cartridge, no answer");
// A table that is not where the disassembly says: the Safari Ball parts company with the
// other balls, and nothing is read from it.
let at = poke::items::TABLE_ADDRESS + 2 * u16::from(poke::items::SAFARI_BALL - 1);
wram.rom_byte(poke::items::TABLE_BANK, at, 0x00);
assert_eq!(item_routine(&mut wram, POTION), None);
}
#[test]
fn the_row_63_bag_holds_one_item_the_cartridge_would_take() {
let mut wram = bag_battle();
assert_eq!(battle_item_use(&mut wram, POTION), Some(true), "8 of 86 is somebody to heal");
assert_eq!(battle_item_use(&mut wram, ANTIDOTE), Some(false), "nobody is poisoned");
assert_eq!(battle_item_use(&mut wram, TM34), None, "the table does not cover it");
assert_eq!(battle_item_use(&mut wram, ESCAPE_ROPE), Some(false), "not inside a battle");
// The battle's copy is the one the damage went to; the party struct catches up at the top of
// the turn. A full party struct under a hurt battler is still somebody to heal.
wram.set_word_be(ram::wPartyMon1 + 1, 86);
assert_eq!(battle_item_use(&mut wram, POTION), Some(true));
wram.set_word_be(ram::wBattleMonHP, 86);
assert_eq!(battle_item_use(&mut wram, POTION), Some(false), "full: no effect");
// A status heal answers the status it cures, and only that one.
wram.set(ram::wBattleMonStatus, 1 << poke::PSN);
assert_eq!(battle_item_use(&mut wram, ANTIDOTE), Some(true));
wram.set(ram::wBattleMonStatus, 1 << poke::PAR);
assert_eq!(battle_item_use(&mut wram, ANTIDOTE), Some(false));
// A Revive wants somebody fainted, and a Potion does not.
wram.set_word_be(ram::wBattleMonHP, 0);
assert_eq!(battle_item_use(&mut wram, POTION), Some(false));
assert_eq!(battle_item_use(&mut wram, REVIVE), Some(true));
// Outside a battle this is not a question this reader answers.
wram.battle(0);
assert_eq!(battle_item_use(&mut wram, POTION), None);
}
#[test]
fn a_ball_and_a_poke_doll_are_for_a_wild_battle_and_the_x_items_for_any() {
let mut wram = bag_battle();
assert_eq!(battle_item_use(&mut wram, POKE_BALL), Some(true));
assert_eq!(battle_item_use(&mut wram, POKE_DOLL), Some(true));
assert_eq!(battle_item_use(&mut wram, X_ATTACK), Some(true));
// A full party leaves the ball to the box, whose count is not read: no answer.
for slot in 1..6 {
wram.party_mon(slot, 0xb3, 5, 10, 10, 0, &[(33, 10)]);
}
assert_eq!(battle_item_use(&mut wram, POKE_BALL), None);
// A trainer blocks the ball and the doll does nothing; an X item still works.
wram.battle(2);
assert_eq!(battle_item_use(&mut wram, POKE_BALL), Some(false));
assert_eq!(battle_item_use(&mut wram, POKE_DOLL), Some(false));
assert_eq!(battle_item_use(&mut wram, X_ATTACK), Some(true));
}
#[test]
fn an_ether_wants_a_move_below_its_pp() {
let mut wram = bag_battle();
wram.move_table(&[(44, 0, 60, 0), (55, 0, 40, 0x15)]);
// Slot one at 0 PP (the fake's move table gives every move 35).
assert_eq!(battle_item_use(&mut wram, ETHER), Some(true));
wram.set(ram::wPartyMon1 + 29, 35).set(ram::wPartyMon1 + 30, 35);
assert_eq!(battle_item_use(&mut wram, ETHER), Some(false), "every move is full");
}
#[test]
fn the_joypad_latch_is_hjoylast_bit_zero() {
let mut wram = Wram::new();
assert!(!a_latched(&mut wram));
wram.set(poke::H_JOY_LAST, poke::pad::A);
assert!(a_latched(&mut wram));
wram.set(poke::H_JOY_LAST, poke::pad::DOWN);
assert!(!a_latched(&mut wram), "a direction down is not an A down");
}