manabrew_engine/lki.rs
1//! Last-Known Information (LKI) system.
2//!
3//! Mirrors Java's `Game.copyLastState()` + `Game.lastStateBattlefield`.
4//!
5//! ## Overview
6//!
7//! The LKI system maintains two types of snapshots to resolve trigger SVars
8//! (e.g. `TriggeredCard$CardPower`) using a card's state at the time it was
9//! last on the battlefield:
10//!
11//! 1. **Periodic snapshots** (`GameState.last_state_battlefield`):
12//! - Captured by `copy_last_state()` at key checkpoints (phase transitions,
13//! before SBAs, before combat)
14//! - Lightweight `CardSnapshot` structs for all battlefield cards
15//! - Stale snapshots persist after cards leave (for LKI lookups)
16//!
17//! 2. **Per-card LKI** (`Card.lki_power` / `lki_toughness`):
18//! - Saved in `action.rs::change_zone()` when a card leaves the battlefield
19//! - Captures the exact power/toughness at zone-change time
20//! - Primary source for trigger SVars
21//!
22//! ## Resolution hierarchy
23//!
24//! When resolving `TriggeredCard$CardPower` / `TriggeredCard$CardToughness`:
25//! 1. Check `card.lki_power` / `card.lki_toughness` (captured at zone change)
26//! 2. If zero, check periodic snapshot (in case card entered after last checkpoint)
27//! 3. Fall back to zero if neither source has data
28//!
29//! ## Lifecycle
30//!
31//! ```text
32//! Card enters battlefield
33//! → assign zone timestamp
34//! → update_lki_snapshot() creates/updates periodic snapshot
35//!
36//! Phase transition / SBA check
37//! → copy_last_state() refreshes all battlefield snapshots
38//!
39//! Card leaves battlefield (dies, exiled, etc.)
40//! → action.rs captures lki_power/lki_toughness
41//! → periodic snapshot remains (stale but valid for LKI)
42//!
43//! Trigger fires (e.g. "When ~ dies, deal damage equal to its power")
44//! → resolve_lki_power() checks lki_power, then periodic snapshot
45//! → SpellAbility resolves with correct LKI value
46//! ```
47//!
48//! ## Java equivalents
49//!
50//! - `Game.copyLastState()` → `GameState::copy_last_state()`
51//! - `Game.lastStateBattlefield` → `GameState.last_state_battlefield`
52//! - `Card.getPower()` (during trigger) → `resolve_lki_power()`
53
54use crate::card::{Card, CounterType};
55use crate::ids::{CardId, PlayerId};
56use crate::spellability::SpellAbility;
57use forge_foundation::ZoneType;
58use std::collections::BTreeMap;
59
60/// Lightweight snapshot of a card's state on the battlefield.
61/// Captured by `GameState::copy_last_state()` at key checkpoints.
62#[derive(Debug, Clone)]
63pub struct CardSnapshot {
64 pub id: CardId,
65 pub controller: PlayerId,
66 pub owner: PlayerId,
67 pub power: i32,
68 pub toughness: i32,
69 pub counters: BTreeMap<CounterType, i32>,
70 pub tapped: bool,
71 pub zone: ZoneType,
72 pub card_name: String,
73 pub room_unlocked_doors: Option<[bool; 2]>,
74}
75
76impl CardSnapshot {
77 /// Create a snapshot from a live card.
78 pub fn from_card(card: &Card) -> Self {
79 Self {
80 id: card.id,
81 controller: card.controller,
82 owner: card.owner,
83 power: card.power(),
84 toughness: card.toughness(),
85 counters: card.counters.clone(),
86 tapped: card.tapped,
87 zone: card.zone,
88 card_name: card.card_name.clone(),
89 room_unlocked_doors: card.room_faces.as_ref().map(|_| {
90 [
91 !card.face_down
92 && card.is_door_unlocked(forge_foundation::CardStateName::LeftSplit),
93 !card.face_down
94 && card.is_door_unlocked(forge_foundation::CardStateName::RightSplit),
95 ]
96 }),
97 }
98 }
99}
100
101/// LKI methods for `GameState`.
102/// Implemented in this module to keep all LKI logic centralized.
103impl crate::game::GameState {
104 /// Snapshot all battlefield cards for LKI.
105 /// Mirrors Java's `Game.copyLastState()`.
106 /// Called at phase transitions, before SBAs, before combat.
107 pub fn copy_last_state(&mut self) {
108 // Update existing snapshots for cards still on the battlefield.
109 // Add new snapshots for cards that entered since last checkpoint.
110 // Keep stale snapshots for cards that left — they serve as LKI
111 // for trigger SVars like TriggeredCard$CardPower.
112 // This matches Java's behavior where lastStateBattlefield is only
113 // fully cleared at major checkpoints but individual entries persist
114 // through resolution chains.
115 for card in self.cards.iter() {
116 if card.zone == ZoneType::Battlefield {
117 if let Some(existing) = self
118 .last_state_battlefield
119 .iter_mut()
120 .find(|s| s.id == card.id)
121 {
122 *existing = CardSnapshot::from_card(card);
123 } else {
124 self.last_state_battlefield
125 .push(CardSnapshot::from_card(card));
126 }
127 }
128 }
129 }
130
131 /// Look up a card's LKI snapshot from the last battlefield state.
132 /// Returns None if the card wasn't on the battlefield at the last checkpoint.
133 pub fn get_lki_snapshot(&self, card_id: CardId) -> Option<&CardSnapshot> {
134 self.last_state_battlefield.iter().find(|s| s.id == card_id)
135 }
136
137 /// Update the LKI snapshot for a specific card on the battlefield.
138 /// If the card is already in the snapshot, update it. Otherwise, add it.
139 /// Called when a card enters the battlefield or its state changes significantly.
140 /// Mirrors Java's incremental LKI updates between full copyLastState() calls.
141 pub fn update_lki_snapshot(&mut self, card_id: CardId) {
142 let card = &self.cards[card_id.index()];
143 if card.zone != ZoneType::Battlefield {
144 return;
145 }
146 let snapshot = CardSnapshot::from_card(card);
147 if let Some(existing) = self
148 .last_state_battlefield
149 .iter_mut()
150 .find(|s| s.id == card_id)
151 {
152 *existing = snapshot;
153 } else {
154 self.last_state_battlefield.push(snapshot);
155 }
156 }
157}
158
159/// Resolve LKI power for a trigger source card.
160///
161/// Checks `card.lki_power` (captured at zone-change time) first, then falls
162/// back to the periodic snapshot if `lki_power` is zero and a snapshot exists
163/// with non-zero power.
164///
165/// This handles the edge case where a card dies/leaves after entering the
166/// battlefield but before the next `copy_last_state()` checkpoint — the
167/// per-card LKI captures the correct value at zone-change time.
168///
169/// Returns 0 if no LKI data exists.
170pub fn resolve_lki_power(game: &crate::game::GameState, trigger_src: CardId) -> i32 {
171 // Check per-card LKI captured at zone-change time (most accurate).
172 // Some(0) is a valid LKI value (e.g. creature with -1/-1 counters reducing power to 0).
173 if let Some(lki) = game.card(trigger_src).lki_power {
174 return lki;
175 }
176 // No per-card LKI — fall back to periodic snapshot.
177 if let Some(snapshot) = game.get_lki_snapshot(trigger_src) {
178 return snapshot.power;
179 }
180 0
181}
182
183/// Resolve LKI toughness for a trigger source card.
184///
185/// Checks `card.lki_toughness` (captured at zone-change time) first, then
186/// falls back to the periodic snapshot if `lki_toughness` is zero and a
187/// snapshot exists.
188///
189/// Returns 0 if no LKI data exists.
190pub fn resolve_lki_toughness(game: &crate::game::GameState, trigger_src: CardId) -> i32 {
191 // Check per-card LKI captured at zone-change time (most accurate).
192 if let Some(lki) = game.card(trigger_src).lki_toughness {
193 return lki;
194 }
195 // No per-card LKI — fall back to periodic snapshot.
196 if let Some(snapshot) = game.get_lki_snapshot(trigger_src) {
197 return snapshot.toughness;
198 }
199 0
200}
201
202/// Resolve LKI counter count for a trigger source card.
203///
204/// Used by death triggers that reference `TriggeredCard$CardCounters.TYPE`
205/// (e.g. Servant of the Scale, Modular).
206///
207/// Checks the per-card LKI counters first, then falls back to the periodic
208/// snapshot's counter map.
209///
210/// Returns 0 if no LKI data or no counters of the given type exist.
211pub fn resolve_lki_counter_count(
212 game: &crate::game::GameState,
213 trigger_src: CardId,
214 counter_type: &crate::card::CounterType,
215) -> i32 {
216 // Check per-card LKI counters captured at zone-change time.
217 let card = game.card(trigger_src);
218 if let Some(&count) = card.lki_counters.as_ref().and_then(|c| c.get(counter_type)) {
219 return count;
220 }
221 // Fall back to periodic snapshot.
222 if let Some(snapshot) = game.get_lki_snapshot(trigger_src) {
223 return snapshot.counters.get(counter_type).copied().unwrap_or(0);
224 }
225 0
226}
227
228fn trigger_card_object(sa: &SpellAbility, key: &str) -> Option<CardId> {
229 crate::ability::ability_key::from_string(key)
230 .and_then(|ability_key| sa.get_triggering_card(ability_key))
231}
232
233fn trigger_int_object(sa: &SpellAbility, key: &str) -> Option<i32> {
234 crate::ability::ability_key::from_string(key)
235 .and_then(|ability_key| sa.get_triggering_value(ability_key))
236 .and_then(|value| value.trim().parse::<i32>().ok())
237}
238
239/// Resolve SVar properties that explicitly ask for triggered-card LKI.
240///
241/// Handles the Forge patterns used by death/leaves triggers:
242/// `TriggeredCard$CardPower`, `TriggeredCard$CardToughness`, and
243/// `TriggeredCard$CardCounters.TYPE`.
244pub fn resolve_triggered_card_lki_svar(
245 game: &crate::game::GameState,
246 sa: &SpellAbility,
247 svar_expr: &str,
248) -> Option<i32> {
249 let property = svar_expr.strip_prefix("TriggeredCard$")?;
250 resolve_triggered_card_lki_property(game, sa, property)
251}
252
253pub fn resolve_triggered_card_lki_property(
254 game: &crate::game::GameState,
255 sa: &SpellAbility,
256 property: &str,
257) -> Option<i32> {
258 if property == "CardPower" {
259 if let Some(power) = trigger_int_object(sa, "TriggeredCardPower") {
260 return Some(power);
261 }
262 return trigger_card_object(sa, "Card")
263 .or(sa.trigger_source)
264 .map(|trigger_src| resolve_lki_power(game, trigger_src));
265 }
266
267 if property == "CardToughness" {
268 if let Some(toughness) = trigger_int_object(sa, "TriggeredCardToughness") {
269 return Some(toughness);
270 }
271 return trigger_card_object(sa, "Card")
272 .or(sa.trigger_source)
273 .map(|trigger_src| resolve_lki_toughness(game, trigger_src));
274 }
275
276 if let Some(counter_name) = property.strip_prefix("CardCounters.") {
277 let counter_type = crate::ability::effects::parse_counter_type(counter_name);
278 return trigger_card_object(sa, "Card")
279 .or(sa.trigger_source)
280 .map(|trigger_src| resolve_lki_counter_count(game, trigger_src, &counter_type));
281 }
282
283 if let Some(filter) = property.strip_prefix("Valid ") {
284 let card_id = trigger_card_object(sa, "Card").or(sa.trigger_source)?;
285 let source_id = sa.source?;
286 let selector = crate::parsing::cached_compiled_selector(filter);
287 let matched = crate::card::valid_filter::matches_valid_card_selector_with_context(
288 &selector,
289 game.card(card_id),
290 crate::card::valid_filter::MatchContext::from_source(game.card(source_id))
291 .with_game(game)
292 .with_spell_ability(sa),
293 );
294 return Some(i32::from(matched));
295 }
296
297 None
298}