Skip to main content

manabrew_engine/replacement/
replace_moved.rs

1//! Replacement logic for `Event$ Moved`.
2//!
3//! Mirrors Java `ReplaceMoved.java` in `forge/game/replacement/`.
4
5use std::collections::HashMap;
6
7use forge_foundation::ZoneType;
8
9use crate::ability::effects::{self, EffectContext};
10use crate::agent::{PassAgent, PlayerAgent};
11use crate::card::Card;
12use crate::game::GameState;
13use crate::game_rng::ThreadRngAdapter;
14use crate::ids::CardId;
15use crate::mana::ManaPool;
16use crate::spellability::build_spell_ability;
17use crate::trigger::TriggerHandler;
18
19use super::replacement_effect::{zone_matches, ReplacementEffect};
20use super::replacement_handler::{ReplacementEvent, ReplacementRuntime};
21use super::replacement_result::ReplacementResult;
22use super::replacement_type::ReplacementType;
23use crate::card_trait_base::CardTrait;
24
25/// Mirrors Java `ReplaceMoved.canReplace()`.
26pub fn can_replace(
27    effect: &ReplacementEffect,
28    event: &ReplacementEvent,
29    game: &GameState,
30    source_card: &Card,
31) -> bool {
32    if effect.event != ReplacementType::Moved {
33        return false;
34    }
35    let (moving_id, origin, destination, is_discard) = match event {
36        ReplacementEvent::Moved {
37            card,
38            origin,
39            destination,
40            is_discard,
41            ..
42        } => (*card, *origin, *destination, *is_discard),
43        _ => return false,
44    };
45    // Discard$ True — only match when the move is from a discard action.
46    // Mirrors Java ReplaceMoved.canReplace() Discard$ check.
47    if let Some(requires_discard) = effect.ir.discard {
48        if requires_discard != is_discard {
49            return false;
50        }
51    }
52    if let Some(dest) = effect.ir.destination_text.as_deref() {
53        if !zone_matches(dest, destination) {
54            return false;
55        }
56    }
57    if let Some(exclude) = effect.ir.exclude_destination_text.as_deref() {
58        if zone_matches(exclude, destination) {
59            return false;
60        }
61    }
62    if let Some(orig) = effect.ir.origin_text.as_deref() {
63        if !zone_matches(orig, origin) {
64            return false;
65        }
66    }
67    let moving_card = &game.cards[moving_id.index()];
68    if let Some(fizzle) = effect.ir.fizzle {
69        if game.stack.resolving_fizzle(moving_id) != Some(fizzle) {
70            return false;
71        }
72    }
73    if let Some(valid) = effect.ir.valid_stack_sa_text.as_deref() {
74        if !moving_card.cast_sa.as_deref().is_some_and(|sa| {
75            crate::spellability::matches_valid_sa(valid, sa, source_card, Some(moving_card))
76        }) {
77            return false;
78        }
79    }
80    if let Some(valid) = effect.ir.valid_card_selector.as_ref() {
81        if !effect.matches_compiled_valid_card(valid, moving_card, source_card) {
82            return false;
83        }
84    }
85    // FlashbackCast$ True — only match when the card was cast via Flashback.
86    if effect.ir.flashback_cast == Some(true) && !moving_card.cast_with_flashback {
87        return false;
88    }
89    // HarmonizeCast$ True — only match when the card was cast via Harmonize.
90    if effect.ir.harmonize_cast == Some(true) && !moving_card.cast_with_harmonize {
91        return false;
92    }
93    if let Some(valid_lki) = effect.ir.valid_lki_text.as_deref() {
94        if !effect.matches_valid_card(valid_lki, moving_card, source_card) {
95            return false;
96        }
97    }
98    // Mirrors Java `ReplaceMoved.canReplace()` L103: only gate ETB chains.
99    if destination == ZoneType::Battlefield && !effect.can_replace_etb(source_card, moving_card) {
100        return false;
101    }
102    true
103}
104
105/// Mirrors Java `ReplacementHandler.executeReplacement()` for Moved.
106pub fn execute(
107    effect: &ReplacementEffect,
108    event: &mut ReplacementEvent,
109    game: &mut GameState,
110    source_card_id: CardId,
111    agents: Option<&mut [Box<dyn PlayerAgent>]>,
112    runtime: Option<&mut ReplacementRuntime<'_>>,
113) -> ReplacementResult {
114    let (moving_id, _destination) = match event {
115        ReplacementEvent::Moved {
116            card, destination, ..
117        } => (*card, destination),
118        _ => return ReplacementResult::NotReplaced,
119    };
120    // Check NewDestination$ first (explicit redirect), then ReplaceWith$ (common alias).
121    // Rest in Peace uses "ReplaceWith$ Exile", while other cards use "NewDestination$ Exile".
122    let redirect = effect
123        .ir
124        .new_destination_text
125        .as_deref()
126        .or(effect.replace_with());
127
128    if let Some(new_dest) = redirect {
129        let new_zone = match new_dest.trim() {
130            "Exile" => Some(ZoneType::Exile),
131            "Graveyard" => Some(ZoneType::Graveyard),
132            "Hand" => Some(ZoneType::Hand),
133            "Library" => Some(ZoneType::Library),
134            "Battlefield" => Some(ZoneType::Battlefield),
135            "Command" => Some(ZoneType::Command),
136            _ => None,
137        };
138        if let Some(z) = new_zone {
139            if let ReplacementEvent::Moved { destination, .. } = event {
140                *destination = z;
141            }
142            if effect.ir.valid_stack_sa_text.as_deref() == Some("Spell.Adventure")
143                && z == ZoneType::Exile
144                && !game.card(moving_id).is_token
145            {
146                game.card_mut(moving_id).on_adventure = true;
147            }
148            if z == ZoneType::Exile && effect.ir.exiled_with_effect_source {
149                let exile_source = game
150                    .card(source_card_id)
151                    .effect_source
152                    .unwrap_or(source_card_id);
153                game.card_mut(moving_id).set_exiled_by(Some(exile_source));
154                game.card_mut(exile_source).add_remembered_card(moving_id);
155            }
156            return ReplacementResult::Updated;
157        }
158    }
159    // If the redirect value wasn't a zone name, try executing it as an SVar spell ability.
160    if let Some(replace_with_key) = effect.replace_with() {
161        let succeeded = execute_replace_with(
162            effect,
163            replace_with_key,
164            game,
165            source_card_id,
166            event,
167            agents,
168            runtime,
169        );
170        if !succeeded {
171            return ReplacementResult::NotReplaced;
172        }
173    }
174    if let Some(result) = effect.ir.replacement_result.as_deref() {
175        return match result {
176            "Updated" => ReplacementResult::Updated,
177            "Replaced" => ReplacementResult::Replaced,
178            "Skipped" => ReplacementResult::Skipped,
179            "Prevented" => ReplacementResult::Prevented,
180            _ => ReplacementResult::Replaced,
181        };
182    }
183    ReplacementResult::Replaced
184}
185
186fn execute_replace_with(
187    effect: &ReplacementEffect,
188    replace_with: &str,
189    game: &mut GameState,
190    source_card_id: CardId,
191    event: &ReplacementEvent,
192    agents: Option<&mut [Box<dyn PlayerAgent>]>,
193    mut runtime: Option<&mut ReplacementRuntime<'_>>,
194) -> bool {
195    let Some(raw) = game.card(source_card_id).svars.get(replace_with).cloned() else {
196        return false;
197    };
198    let controller = game.card(source_card_id).controller;
199    let mut sa = build_spell_ability(game, source_card_id, &raw, controller);
200    effect.set_replacing_objects(event, &mut sa);
201
202    // `local_agents_storage` keeps the fallback Vec alive when the caller
203    // didn't provide agents; we hand back a borrow into it.
204    #[allow(unused_assignments)]
205    let mut local_agents_storage: Option<Vec<Box<dyn PlayerAgent>>> = None;
206    let agents: &mut [Box<dyn PlayerAgent>] = if let Some(agents) = agents {
207        agents
208    } else {
209        local_agents_storage = Some(
210            (0..game.players.len())
211                .map(|_| Box::new(PassAgent) as Box<dyn PlayerAgent>)
212                .collect(),
213        );
214        local_agents_storage.as_mut().unwrap().as_mut_slice()
215    };
216
217    let mut local_mana_pools: Vec<ManaPool> =
218        (0..game.players.len()).map(|_| ManaPool::new()).collect();
219    let mana_pools_for_targets: &[ManaPool] = if let Some(rt) = runtime.as_ref() {
220        rt.mana_pools.as_slice()
221    } else {
222        local_mana_pools.as_slice()
223    };
224    if sa.uses_targeting() && !sa.setup_targets(game, agents, mana_pools_for_targets) {
225        return false;
226    }
227
228    let mut local_trigger_handler = TriggerHandler::new();
229    let local_token_templates: HashMap<String, Card> = HashMap::new();
230    let local_token_art_variants: HashMap<(String, String), usize> = HashMap::new();
231    let local_token_fallback: HashMap<String, String> = HashMap::new();
232    let local_edition_dates: HashMap<String, String> = HashMap::new();
233    let mut local_rng = ThreadRngAdapter;
234
235    let mut parent_target_card: Option<CardId> = None;
236    let mut parent_target_player = None;
237    let mut current_sa: Option<&crate::spellability::SpellAbility> = Some(&sa);
238    while let Some(cur) = current_sa {
239        let mut sa_with_ctx;
240        let sa_ref = if parent_target_player.is_some() && cur.target_chosen.target_player.is_none()
241        {
242            sa_with_ctx = cur.clone();
243            sa_with_ctx.target_chosen.target_player = parent_target_player;
244            &sa_with_ctx
245        } else {
246            cur
247        };
248
249        let (
250            trigger_handler_ref,
251            token_templates_ref,
252            token_art_ref,
253            token_fb_ref,
254            edition_dates_ref,
255            mana_pools_ref,
256            rng_ref,
257        ): (
258            &mut TriggerHandler,
259            &HashMap<String, Card>,
260            &HashMap<(String, String), usize>,
261            &HashMap<String, String>,
262            &HashMap<String, String>,
263            &mut Vec<ManaPool>,
264            &mut dyn crate::game_rng::GameRng,
265        ) = if let Some(rt) = runtime.as_deref_mut() {
266            (
267                rt.trigger_handler,
268                rt.token_templates,
269                rt.token_art_variants,
270                rt.token_fallback,
271                rt.edition_dates,
272                rt.mana_pools,
273                rt.rng,
274            )
275        } else {
276            (
277                &mut local_trigger_handler,
278                &local_token_templates,
279                &local_token_art_variants,
280                &local_token_fallback,
281                &local_edition_dates,
282                &mut local_mana_pools,
283                &mut local_rng,
284            )
285        };
286
287        let mut ctx = EffectContext {
288            game,
289            combat: None,
290            agents,
291            trigger_handler: trigger_handler_ref,
292            token_templates: token_templates_ref,
293            token_art_variants: token_art_ref,
294            token_fallback: token_fb_ref,
295            edition_dates: edition_dates_ref,
296            mana_pools: mana_pools_ref,
297            parent_target_card,
298            rng: rng_ref,
299        };
300        effects::resolve_effect(&mut ctx, sa_ref);
301        parent_target_card = sa_ref.target_chosen.target_card;
302        parent_target_player = sa_ref.target_chosen.target_player;
303        current_sa = cur.get_sub_ability();
304    }
305    true
306}
307
308// `set_replacing_objects_for_moved` was inlined into the cross-event
309// `ReplacementEffect::set_replacing_objects` dispatcher in `replacement_effect.rs`
310// to mirror Java's polymorphic `setReplacingObjects` hook.