Skip to main content

manabrew_engine/ability/effects/
copy_permanent_effect.rs

1use forge_foundation::color::ColorSet;
2use forge_foundation::ZoneType;
3
4use super::token_effect_base::{TokenCreateTable, TokenEffectBase, TOKEN_EFFECT_BASE};
5use super::EffectContext;
6use crate::card::card_zone_table::CardZoneTable;
7use crate::card::Card;
8use crate::ids::CardId;
9use crate::spellability::SpellAbility;
10
11/// Struct form of this effect so it can participate in the
12/// `SpellAbilityEffect` trait hierarchy — mirrors Java's
13/// `CopyPermanentEffect` class extending `SpellAbilityEffect`.
14#[manabrew_engine_macros::spell_effect(CopyPermanentEffect)]
15fn resolve(ctx: &mut EffectContext, sa: &crate::spellability::SpellAbility) {
16    let amount = super::resolve_numeric_svar(ctx.game, sa, "NumCopies", 1).max(0) as usize;
17    let controllers = resolve_copy_controllers(ctx, sa);
18    if controllers.is_empty() {
19        return;
20    }
21
22    let mut token_table = TokenCreateTable::default();
23    for controller in controllers {
24        if !ctx.game.player(controller).is_alive() {
25            continue;
26        }
27
28        let originals = resolve_originals(ctx, sa, controller);
29        for original_id in originals {
30            if ctx.game.card(original_id).type_line.is_instant()
31                || ctx.game.card(original_id).type_line.is_sorcery()
32            {
33                continue;
34            }
35            if sa.ir.defined_text.is_none()
36                && sa.ir.choices.is_none()
37                && ctx.game.card(original_id).zone != ZoneType::Battlefield
38            {
39                continue;
40            }
41
42            if let Some(for_each) = sa.ir.for_each_text.as_deref() {
43                let players = crate::ability::ability_utils::resolve_defined_players_with_sa(
44                    for_each,
45                    sa,
46                    sa.activating_player,
47                    ctx.game,
48                );
49                for player in players {
50                    let mut proto = get_proto_type(sa, ctx.game.card(original_id), controller);
51                    proto.copied_permanent = Some(original_id);
52                    proto.add_remembered_player(player);
53                    token_table.put(controller, proto, amount);
54                }
55            } else {
56                let mut proto = get_proto_type(sa, ctx.game.card(original_id), controller);
57                proto.copied_permanent = Some(original_id);
58                token_table.put(controller, proto, amount);
59            }
60        }
61    }
62
63    if token_table.is_empty() {
64        return;
65    }
66
67    let mut trigger_list = CardZoneTable::default();
68    let result = TOKEN_EFFECT_BASE.make_token_table(ctx, token_table, true, &mut trigger_list, sa);
69    if !result.created.is_empty() {
70        trigger_list.trigger_changes_zone_all(ctx.trigger_handler, ctx.game, Some(sa));
71    }
72}
73
74/// Build the in-memory copy of `original` that a Copy/Embalm/Eternalize effect
75/// will place onto the battlefield. Mirrors Java
76/// `CopyPermanentEffect.getProtoType(SpellAbility, Card, Player)`.
77///
78/// Returned `Card` carries a placeholder `CardId(0)`; callers must invoke
79/// `GameState::create_card` to receive the real id. Mana-cost strip,
80/// `SetColor`, `AddTypes`, `SetPower/Toughness`, and `AddKeywords` are applied
81/// here. Shared token lifecycle params such as `PumpKeywords` are applied by
82/// `TokenEffectBase` after the token receives its real id.
83pub fn get_proto_type(sa: &SpellAbility, original: &Card, new_owner: crate::ids::PlayerId) -> Card {
84    let mut copy = Card::new(
85        CardId(0),
86        original.card_name.clone(),
87        new_owner,
88        original.type_line.clone(),
89        original.mana_cost.clone(),
90        original.color,
91        original.base_power,
92        original.base_toughness,
93        original.keywords.as_string_list(),
94        original.abilities.clone(),
95    );
96    copy.full_name.clone_from(&original.full_name);
97    if original.copied_spell && sa.is_spell && sa.source == Some(original.id) {
98        copy.cast_sa = Some(Box::new(sa.clone()));
99    }
100    copy.room_faces.clone_from(&original.room_faces);
101    if copy.room_faces.is_some() {
102        copy.activated_abilities
103            .clone_from(&original.activated_abilities);
104        copy.base_ability_count = copy.activated_abilities.len();
105        if copy.cast_sa.is_some() {
106            copy.room_state = original.room_state;
107        } else {
108            copy.update_rooms();
109        }
110    }
111    copy.set_triggers(original.copiable_triggers());
112    copy.set_svars_map(original.svars.clone());
113    copy.set_static_abilities(original.static_abilities.clone());
114    copy.set_replacement_effects(original.copiable_replacement_effects());
115    copy.set_perpetual(original, false);
116    copy.initial_loyalty = original.initial_loyalty.clone();
117    copy.set_code = original.set_code.clone();
118    // Copies are tokens for zone-change purposes (cease to exist off battlefield).
119    copy.set_is_token(true);
120
121    // Apply SetColor$ (e.g. Embalm sets color to White).
122    if let Some(set_color) = sa.ir.set_color.as_deref() {
123        copy.set_color(ColorSet::from_names(set_color));
124    }
125
126    // Apply AddTypes$ (e.g. Embalm adds "Zombie").
127    if let Some(add_types) = sa.ir.add_types.as_deref() {
128        for t in add_types.split(" & ") {
129            let t = t.trim();
130            if !t.is_empty() {
131                copy.add_type(t);
132            }
133        }
134    }
135
136    // Apply SetPower$/SetToughness$ (e.g. Eternalize sets to 4/4).
137    if let Some(p) = sa
138        .ir
139        .set_power
140        .as_deref()
141        .and_then(|value| value.parse().ok())
142    {
143        copy.set_base_power(Some(p));
144    }
145    if let Some(t) = sa
146        .ir
147        .set_toughness
148        .as_deref()
149        .and_then(|value| value.parse().ok())
150    {
151        copy.set_base_toughness(Some(t));
152    }
153
154    // PumpKeywords$ are NOT applied at the proto stage. Mirrors Java
155    // `TokenEffectBase.java:179-182`, which applies them post-creation via
156    // `addChangedCardKeywords` + `addPumpUntil` so they expire per
157    // `PumpDuration$`. Applying them as intrinsic here would make e.g.
158    // Ashling's "Haste until end of turn" persist forever.
159    // The Rust mirror lives in `token_effect_base.rs::create_single_token`.
160
161    // Apply AddKeywords$ (e.g. additional keywords on the copy).
162    if let Some(add_kws) = sa.ir.add_keywords.as_deref() {
163        for kw in add_kws.split(" & ") {
164            let kw = kw.trim();
165            if !kw.is_empty() {
166                copy.add_intrinsic_keyword(kw);
167            }
168        }
169    }
170
171    // Strip mana cost for Embalm/Eternalize copies (they have no mana cost).
172    if sa
173        .ir
174        .set_mana_cost
175        .as_deref()
176        .is_some_and(|v| v == "0" || v.is_empty())
177    {
178        copy.set_mana_cost(forge_foundation::mana::ManaCost::no_cost());
179    }
180
181    copy
182}
183
184fn resolve_copy_controllers(ctx: &EffectContext, sa: &SpellAbility) -> Vec<crate::ids::PlayerId> {
185    if let Some(controller) = sa.ir.controller_text.as_deref() {
186        let players = crate::ability::ability_utils::resolve_defined_players_with_sa(
187            controller,
188            sa,
189            sa.activating_player,
190            ctx.game,
191        );
192        if !players.is_empty() {
193            return players;
194        }
195    }
196    vec![sa.activating_player]
197}
198
199fn resolve_originals(
200    ctx: &mut EffectContext,
201    sa: &SpellAbility,
202    controller: crate::ids::PlayerId,
203) -> Vec<CardId> {
204    if let Some(choices) = sa.ir.choices.as_deref() {
205        let candidates: Vec<CardId> = ctx
206            .game
207            .cards
208            .iter()
209            .filter(|card| card.zone == ZoneType::Battlefield)
210            .map(|card| card.id)
211            .filter(|&card_id| {
212                let Some(source_id) = sa.source else {
213                    return false;
214                };
215                crate::card::valid_filter::matches_valid(
216                    choices,
217                    Some(ctx.game.card(card_id)),
218                    None,
219                    ctx.game.card(source_id),
220                    sa.activating_player,
221                )
222            })
223            .collect();
224        if candidates.is_empty() {
225            return Vec::new();
226        }
227
228        let chooser = sa
229            .ir
230            .chooser
231            .as_deref()
232            .and_then(|defined| {
233                crate::ability::ability_utils::resolve_defined_players_with_sa(
234                    defined,
235                    sa,
236                    sa.activating_player,
237                    ctx.game,
238                )
239                .into_iter()
240                .next()
241            })
242            .unwrap_or(sa.activating_player);
243        ctx.agents[chooser.index()].snapshot_state(ctx.game, ctx.mana_pools);
244        return ctx.agents[chooser.index()]
245            .choose_single_card_for_zone_change(
246                ctx.game,
247                chooser,
248                &candidates,
249                "Choose a card",
250                false,
251            )
252            .into_iter()
253            .collect();
254    }
255
256    if let Some(defined) = sa.defined() {
257        match defined {
258            "Self" => return sa.source.into_iter().collect(),
259            "ParentTarget" => return sa.target_chosen.target_card.into_iter().collect(),
260            "TriggeredCard" | "TriggeredCardLKICopy" | "TriggeredSacrificedCard" => {
261                return sa
262                    .get_triggering_card(crate::ability::AbilityKey::Card)
263                    .into_iter()
264                    .collect();
265            }
266            _ => {
267                return crate::ability::ability_utils::get_defined_cards(
268                    ctx.game,
269                    sa.source,
270                    defined,
271                    Some(controller),
272                );
273            }
274        }
275    }
276
277    // Check Defined$ parameter first.
278    // Fall back to targeting.
279    sa.target_chosen.target_card.into_iter().collect()
280}