Skip to main content

manabrew_engine/ability/effects/
effect_context.rs

1//! `EffectContext` — bundle of subsystem refs threaded through effect resolution.
2//!
3//! Rust-specific concession: Java reaches `Game.getTriggerHandler()`, agents,
4//! combat, mana pools via chained getters from `SpellAbility.getHostCard()`.
5//! The Rust engine deliberately owns those subsystems outside `GameState`
6//! (see `trigger_handler.rs` top comment), so every resolver needs a handful
7//! of mutable references. This struct packs them.
8
9use std::collections::HashMap;
10
11use forge_foundation::ZoneType;
12
13use crate::agent::GameEntity;
14use crate::agent::PlayerAgent;
15use crate::card::{Card, CounterType};
16use crate::event::RunParams;
17use crate::game::GameState;
18use crate::game_entity_counter_table::GameEntityCounterTable;
19use crate::ids::{CardId, PlayerId};
20use crate::mana::ManaPool;
21use crate::spellability::SpellAbility;
22use crate::trigger::handler::TriggerHandler;
23
24/// Everything an effect needs to resolve.
25pub struct EffectContext<'a> {
26    pub game: &'a mut GameState,
27    pub combat: Option<&'a mut crate::combat::CombatState>,
28    pub agents: &'a mut [Box<dyn PlayerAgent>],
29    pub trigger_handler: &'a mut TriggerHandler,
30    pub token_templates: &'a HashMap<String, Card>,
31    /// Token art variant counts for game-RNG parity with Java.
32    pub token_art_variants: &'a HashMap<(String, String), usize>,
33    /// Token fallback codes: edition_code → fallback_edition_code.
34    pub token_fallback: &'a HashMap<String, String>,
35    /// Edition release dates: edition_code → "YYYY-MM-DD". Used to sort
36    /// editions newest-first for token fallback (Java parity).
37    pub edition_dates: &'a HashMap<String, String>,
38    pub mana_pools: &'a mut Vec<ManaPool>,
39    /// CardId of the parent SA's chosen target card, propagated through the
40    /// sub-ability chain so that `Defined$ ParentTarget` effects can resolve it.
41    /// Mirrors Java's `SpellAbility.getParentTargetCard()` (via getRootAbility()).
42    pub parent_target_card: Option<CardId>,
43    /// Pluggable RNG for game effects (shuffles, coin flips, dice rolls).
44    /// Parity tests inject a JavaRandom-backed implementation; normal gameplay
45    /// uses the default ThreadRngAdapter.
46    pub rng: &'a mut dyn crate::game_rng::GameRng,
47}
48
49pub(crate) fn add_counter_with_context(
50    game: &mut GameState,
51    trigger_handler: Option<&mut TriggerHandler>,
52    agents: Option<&mut [Box<dyn PlayerAgent>]>,
53    card_id: CardId,
54    counter_type: &CounterType,
55    amount: i32,
56    params: RunParams,
57    is_effect: bool,
58) -> i32 {
59    let source = params.source_player.or(params.cause_player);
60    let cause = params.cause.clone();
61    let mut table = GameEntityCounterTable::default();
62    table.put(
63        source,
64        GameEntity::Card(card_id),
65        counter_type.clone(),
66        amount,
67    );
68    table
69        .replace_counter_effect(
70            game,
71            trigger_handler,
72            agents,
73            cause.as_ref(),
74            is_effect,
75            params,
76        )
77        .get(source, GameEntity::Card(card_id), counter_type)
78}
79
80pub(crate) fn remove_counter_with_context(
81    game: &mut GameState,
82    trigger_handler: &mut TriggerHandler,
83    card_id: CardId,
84    counter_type: &CounterType,
85    amount: i32,
86    params: RunParams,
87) -> i32 {
88    remove_counter(
89        game,
90        Some(trigger_handler),
91        card_id,
92        counter_type,
93        amount,
94        params,
95    )
96    .0
97}
98
99pub(crate) fn pay_remove_counter_cost(
100    game: &mut GameState,
101    trigger_handler: Option<&mut TriggerHandler>,
102    card_id: CardId,
103    counter_type: &CounterType,
104    amount: i32,
105    params: RunParams,
106) -> bool {
107    if amount <= 0 {
108        return true;
109    }
110    if game.card(card_id).counter_count(counter_type) < amount
111        || !crate::replacement::replace_remove_counter::can_remove_counters(
112            game,
113            card_id,
114            counter_type,
115        )
116    {
117        return false;
118    }
119    let (removed, result) =
120        remove_counter(game, trigger_handler, card_id, counter_type, amount, params);
121    result != crate::replacement::ReplacementResult::NotReplaced || removed == amount
122}
123
124fn remove_counter(
125    game: &mut GameState,
126    trigger_handler: Option<&mut TriggerHandler>,
127    card_id: CardId,
128    counter_type: &CounterType,
129    amount: i32,
130    mut params: RunParams,
131) -> (i32, crate::replacement::ReplacementResult) {
132    use crate::replacement::replacement_handler::{apply_replacements, ReplacementEvent};
133    use crate::replacement::ReplacementResult;
134    if amount <= 0 || game.card(card_id).phased_out {
135        return (0, ReplacementResult::Prevented);
136    }
137    let mut event = ReplacementEvent::RemoveCounter {
138        target: card_id,
139        counter_type: counter_type.clone(),
140        count: amount,
141    };
142    let result = apply_replacements(game, &mut event);
143    if matches!(
144        result,
145        ReplacementResult::Skipped | ReplacementResult::Replaced | ReplacementResult::Prevented
146    ) {
147        return (0, result);
148    }
149    let ReplacementEvent::RemoveCounter { count, .. } = event else {
150        return (0, result);
151    };
152    let current = game.card(card_id).counter_count(counter_type);
153    let actual = count.min(current).max(0);
154    if actual == 0 {
155        return (0, result);
156    }
157    game.card_mut(card_id).remove_counter(counter_type, actual);
158    let Some(trigger_handler) = trigger_handler else {
159        return (actual, result);
160    };
161    params.card = Some(card_id);
162    params.counter_type = Some(format!("{counter_type:?}"));
163    params.counter_amount = Some(1);
164    for removed in 1..=actual {
165        params.new_counter_amount = Some(current - removed);
166        trigger_handler.run_trigger(
167            crate::trigger::TriggerType::CounterRemoved,
168            params.clone(),
169            false,
170        );
171    }
172    params.counter_amount = Some(actual);
173    trigger_handler.run_trigger(
174        crate::trigger::TriggerType::CounterRemovedOnce,
175        params,
176        false,
177    );
178    (actual, result)
179}
180
181impl EffectContext<'_> {
182    /// Get the number of art variants for a token in a given edition,
183    /// following TokenFallbackCode chains. Returns 1 if not found.
184    /// When edition_code is empty, scans all editions and returns the first
185    /// match (mirrors Java's `fallbackToken` which iterates all editions).
186    pub fn token_art_variant_count(&self, token_script: &str, edition_code: &str) -> usize {
187        let script_lower = token_script.to_lowercase();
188        if !edition_code.is_empty() {
189            let key = (script_lower.clone(), edition_code.to_uppercase());
190            if let Some(&count) = self.token_art_variants.get(&key) {
191                return count;
192            }
193            if let Some(fallback) = self.token_fallback.get(&edition_code.to_uppercase()) {
194                return self.token_art_variant_count(token_script, fallback);
195            }
196        }
197        // Fallback: host edition doesn't have this token. Java's
198        // `fallbackToken` iterates editions in a specific order that's
199        // hard to reproduce exactly. In practice Java almost always
200        // resolves to an edition with 1 art variant for common tokens.
201        // Default to 1 to match the typical Java behavior.
202        1
203    }
204
205    /// Consume game-RNG calls to match Java's token prototype creation.
206    /// Java calls Aggregates.random(Set) which does nextInt() per element,
207    /// plus PaperToken.getImageKey() which does nextInt(artIndex).
208    pub fn sync_token_art_rng(&mut self, token_script: &str, sa: &SpellAbility) {
209        // Java's TokenDb caches token prototypes globally. The first creation
210        // of a token type consumes game RNG (Aggregates.random + getImageKey);
211        // subsequent creations reuse the cached prototype without RNG.
212        let host_edition = sa
213            .source
214            .and_then(|cid| self.game.card(cid).set_code.as_deref())
215            .unwrap_or("");
216        let art_count = self.token_art_variant_count(token_script, host_edition);
217        // Java's Aggregates.random(Collection<PaperToken>) uses min-random
218        // selection: for each element, call nextInt() (unbounded). Collection
219        // size = number of art variants in the resolved edition.
220        for _ in 0..art_count {
221            self.rng.next_int(1);
222        }
223        // PaperToken.getImageKey(): nextInt(artIndex)
224        self.rng.next_int(1);
225    }
226
227    pub fn move_card(&mut self, card_id: CardId, dest_zone: ZoneType, dest_owner: PlayerId) {
228        let mut runtime = crate::replacement::replacement_handler::ReplacementRuntime {
229            trigger_handler: self.trigger_handler,
230            token_templates: self.token_templates,
231            token_art_variants: self.token_art_variants,
232            token_fallback: self.token_fallback,
233            edition_dates: self.edition_dates,
234            mana_pools: self.mana_pools,
235            rng: self.rng,
236        };
237        self.game.move_card_with_agents_and_replacement_runtime(
238            card_id,
239            dest_zone,
240            dest_owner,
241            self.agents,
242            &mut runtime,
243        );
244    }
245
246    pub(crate) fn add_counter(
247        &mut self,
248        card_id: CardId,
249        counter_type: &CounterType,
250        amount: i32,
251        sa: &SpellAbility,
252        mut params: RunParams,
253    ) -> i32 {
254        params.source_player.get_or_insert(sa.activating_player);
255        params.cause.get_or_insert_with(|| sa.clone());
256        add_counter_with_context(
257            self.game,
258            Some(self.trigger_handler),
259            Some(self.agents),
260            card_id,
261            counter_type,
262            amount,
263            params,
264            true,
265        )
266    }
267
268    pub(crate) fn add_player_counter(
269        &mut self,
270        player: PlayerId,
271        counter_type: &CounterType,
272        amount: i32,
273        sa: &SpellAbility,
274        mut params: RunParams,
275    ) -> i32 {
276        params.source_player.get_or_insert(sa.activating_player);
277        params.cause.get_or_insert_with(|| sa.clone());
278        let source = params.source_player;
279        let mut table = GameEntityCounterTable::default();
280        table.put(
281            source,
282            GameEntity::Player(player),
283            counter_type.clone(),
284            amount,
285        );
286        table
287            .replace_counter_effect(
288                self.game,
289                Some(self.trigger_handler),
290                Some(self.agents),
291                Some(sa),
292                true,
293                params,
294            )
295            .get(source, GameEntity::Player(player), counter_type)
296    }
297}