Battle engine
Overview
Section titled “Overview”pl-battle is pure logic: no graphics, no audio, no platform, no_std, integer only.
A battle takes choices and produces a log of events. The presentation (battle screen,
animations, AI) lives in pl-game and reads that log; it never reaches inside.
Its control flow follows Pokémon Showdown’s simulator step for step, because the same
seed must give the same battle in both. Each function names the Showdown function it
ports (reference: sim/battle.ts, sim/battle-queue.ts, sim/battle-actions.ts,
sim/pokemon.ts, sim/side.ts, sim/field.ts). Why port rather than design:
Showdown is the most complete open description of the rules, and it is the test
reference. A port can be checked line by line against a running reference; a design
cannot. How the check works is in
Showdown conformance.
Interface
Section titled “Interface”let mut battle = Battle::new(&dex, [team_a, team_b], rng);battle.start();loop { match battle.request() { Request::TeamPreview => { /* battle.choose_team(...) */ } Request::Move | Request::Switch { .. } => battle.choose(side, &choices)?, Request::Done { winner } => break, } for event in battle.drain_log() { /* present it */ }}Dex(data.rs) is read-only data: species, moves, abilities, items, the type chart.pl_data::battle::BattleDataimplements it over a pack, loading only the creatures taking part before the battle starts; tests implement it in memory.Dexcannot fail or read files: everything a battle may need is resident first.Requestsays exactly what is legal, so the interface and the AI never guess.Choiceis a move (Move,MoveAtwith a target,MoveWithwith a gimmick), a switch,PassorWait.ChoiceErrornames why a choice was refused.Event(log.rs) is what happened. A few events have their own shape (a switch-in, a move used, a turn starting); everything else isEvent::Line, a kind and up to five arguments, which is how Showdown’s own effects report. The log does not grow a variant per effect.
Modules
Section titled “Modules”The core, by concern:
| File | Ports |
|---|---|
battle.rs |
The battle’s state and interface; who may Mega Evolve or Terastallize |
queue.rs |
The action queue and action speed |
order.rs |
comparePriority and speedSort: ties broken by the RNG exactly as Showdown breaks them |
turn.rs |
The turn loop, fainting, winning |
dispatch.rs |
runEvent, singleEvent, findEventHandlers, resolvePriority |
moves.rs |
The move pipeline: runMove, useMove, the hit steps, secondaries |
damage.rs |
Stats, types, the damage formula, damage, healing, stat stages |
apply.rs |
Statuses, volatiles, side, slot and field conditions, weather, terrain, items, abilities |
switching.rs |
Switching in, dragging in, Pursuit |
targets.rs |
Positions and targets, written for any number of creatures a side |
forms.rs |
Species and form changes |
gimmicks.rs |
Mega Evolution and Terastallization |
math.rs |
Showdown’s truncation points with integers |
state.rs |
Effect state blocks |
hash.rs, mirror.rs |
A digest of the whole battle, and the battle seen from the other side, for link battles |
The effects are under effects/ (moves, abilities, items, conditions, field) and the
mechanics Showdown does not simulate under extras/ (catching, experience, effort
values, growth, running, obedience, payout, friendship): pure functions that take
what they need and a &mut Rng and return a result the game applies.
- One choice for each active place.
- The queue sorts actions by class (switch, gimmick, move), then priority, then speed; ties are shuffled with the battle’s RNG. Speed is worked out again when it changes during the turn.
- Each action runs. A move goes through the pipeline: can it be used, targets and redirection, accuracy, immunity and protection, the hit loop, damage, secondary effects, after-move effects.
- Residual effects at the end of the turn, in their order; then replacements.
- Is there a winner.
Every random number comes from one pl_core RNG, Showdown’s “gen5” generator, asked
for the same values in the same order as Showdown asks. Where Showdown’s order of
random calls is an accident of its code, the port copies the accident (plan 08).
Events and effects
Section titled “Events and effects”Everything interesting happens through events that effects answer. An effect (a
move’s callbacks, an ability, an item, a status, a volatile, a field condition) is a
static table of Handler rows:
pub type HandlerFn = fn(&mut Battle<'_>, &mut EventCtx) -> Relay;
pub struct Handler { pub event: EventId, pub scope: Scope, // own, ally, foe, any, source pub order: u16, // Showdown's onXOrder pub priority: i16, // Showdown's onXPriority pub sub_order: i8, // Showdown's onXSubOrder pub run: Run, // Run::Native(fn) or Run::Timer}For each event the dispatcher gathers the handlers of everything that could respond,
sorts them by Showdown’s key and runs them. A handler returns a Relay: carry on,
replace the value, or stop. Which handlers an event gathers and how they sort decides
which random numbers are drawn to break ties, so each effect registers exactly the
events its Showdown definition registers, even ones that look as if they do
nothing. Suppression (abilities that ignore abilities, items that are suppressed) is
done once, in the dispatcher.
Each effect file has a registry! of rows: a constant, the identifier, the display
name and the definition. A row’s position is its number; numbers are not stable and
nothing stores one. The data reaches an effect by its identifier (Showdown’s,
lower case), which the pack records beside each move, ability and item.
What an active effect remembers lives in a fixed-size state block (state.rs),
not a heap object, so nothing is allocated when an effect starts.
Why plain functions in static tables
Section titled “Why plain functions in static tables”- Code size. A battle library with every modern effect is the largest thing in
the DS binary. A trait object adds a vtable per type; a closure or a generic per
effect adds a copy of code per effect. A
fnpointer in astaticrow costs a few bytes. Measured on the DS target: about 100 to 150 bytes an ability or item, 300 a condition (docs/battle-effects.md, “Size”). - One way to call. A handler is reached only through
Battle::call_handler. A later kind of row (a bytecode blob loaded for one battle, or a script procedure) needs only another case there (dispatch.rs). - It mirrors Showdown’s shape. Showdown’s effects are objects of named callbacks with priorities; a table of rows is the same thing without a runtime.
How to write an effect, step by step, is in docs/battle-effects.md in the
repository; how a game adds its own is in custom mechanics.
Formats and gimmicks
Section titled “Formats and gimmicks”- Singles are complete against Showdown at the last count (above).
- Doubles are in the core:
MoveAtchooses a target, spread moves, redirection, ally abilities. Multi, tag and wild doubles give each place an owner. The battle screen draws doubles. - Triples are prepared:
targets.rsalready takes Showdown’s branches for three a side. Not written. - Rotation has no Showdown reference; it waits for the owner (decision 177).
- Mega Evolution and Terastallization follow Showdown (
gimmicks.rs,effects/items/mega.rs,effects/moves_tera.rs). A game turns Terastallization on with the ruletera. - Planned (plan 36): Z-Moves and Dynamax, against Showdown’s generation 7 and 8 modes. The rules when a game enables several gimmicks are plan 08’s: each side once per gimmick, each creature at most one.
Extensions
Section titled “Extensions”A game may add effects and replace built-in ones from its own Rust crate (plan 34,
decisions 230 and 235). The seam is pl_battle::ext:
- A game gives one
static BattleExt: tables of the engine’s own definition types (AbilityDef,ItemDef,MoveDef, volatiles, field conditions), names for them, and overrides.impl Extension for MyGame { const BATTLE: &'static BattleExt = ...; }. - A game row’s number has bit 15 set (
ext::game(row)). The dispatcher gathers, sorts and calls game rows exactly as it does the engine’s. - An override points an identifier the engine implements at a game row. The engine’s row is never edited, so the conformance runs and other games still reach it. The build lists every override (“this game changes: …”).
- A pack records the content version: the engine’s
CONTENT_VERSIONmixed with the game’s names and overrides. A pack built for another game crate, or for none, is refused. NoExtis the empty extension; the engine’s own conformance never links a game crate.
templates/game-crate shows it with an invented ability, an invented move of an
invented type, and an override; its tests/scenarios.rs plays each battle with and
without the game’s tables.
Planned (plan 46): the running game links a game crate’s tables on desktop and DS. Today a game’s tables are used by its own tests and named in its pack by the build.
Planned (plan 34): the other two routes to a custom mechanic. Data primitives cover
most custom moves, abilities and items as records read by parameterised handlers.
Script hooks run battle procedures of the script language inside the dispatcher.
Arenas are field effects as first-class state. Bosses with several health bars,
scripted mid-battle events and new formats follow, and creators get a scenario-test
format and ploom test --official, which proves a build changes nothing it did not
declare.
- All of
pl-battlewith its content has a 900 KB share of the 1.5 MB code budget (plan 09). Effects call shared helpers, prefer a data field or a flag to a handler, and share functions between effects that differ in a constant. - A battle’s data in RAM is what its creatures need: at most 12 species and 48 moves.
- No floats, no
core::fmt, no allocation per event, no random numbers but the battle’s. - Planned (plan 09, relief valve 2): if code size runs short, the function-code parameter table and bespoke effects move into the pack and load per battle, for the participants only. Not needed so far: see budgets.
Link battles
Section titled “Link battles”Two machines run the same battle from the same seed and the same choices
(lockstep, pl_net::Lockstep). Battle::state_hash digests every field that can
change, independent of word size and addresses, so a desynchronisation is found at
the turn it happens. mirror.rs shows the battle from seat 1’s side without playing a
copy. See the server.