Skip to main content

manabrew_engine/zone/
magic_stack.rs

1//! MagicStack — the game stack for spells and abilities.
2//!
3//! Mirrors Java's `MagicStack.java` from `forge.game.zone`.
4//! Spells and abilities are pushed onto the stack and resolve LIFO.
5
6use forge_foundation::ZoneType;
7use serde::{Deserialize, Serialize};
8
9use crate::game::GameState;
10use crate::ids::{CardId, PlayerId};
11use crate::spellability::SpellAbility;
12
13// ── StackEntry (mirrors Java's SpellAbilityStackInstance) ────────────
14
15/// An entry on the game stack (spell or ability waiting to resolve).
16/// Mirrors Java's `SpellAbilityStackInstance` which wraps a `SpellAbility`.
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct StackEntry {
19    pub id: u32,
20    /// The spell ability with its full sub-ability chain and targets.
21    pub spell_ability: SpellAbility,
22    /// True while a spell has been announced and moved to the stack, but its
23    /// modes/targets/costs/payment have not finished yet. Pending entries are
24    /// visible for casting prompts but must never resolve or receive priority.
25    #[serde(default)]
26    pub is_pending_cast: bool,
27    /// Whether this is a creature spell (goes to battlefield on resolve).
28    pub is_creature_spell: bool,
29    /// Whether this is a non-creature permanent spell.
30    pub is_permanent_spell: bool,
31    /// The zone the spell was cast from (for Flashback exile-on-resolve).
32    pub cast_from_zone: Option<ZoneType>,
33    /// If this is an optional trigger, the player who decides whether to
34    /// accept or decline.  Mirrors Java's WrappedAbility `decider` field.
35    #[serde(default)]
36    pub optional_trigger_decider: Option<PlayerId>,
37    /// Description text shown to the deciding player for optional triggers.
38    #[serde(default)]
39    pub optional_trigger_description: Option<String>,
40    /// Source card name for optional trigger prompts.
41    #[serde(default)]
42    pub optional_trigger_source_name: Option<String>,
43}
44
45impl StackEntry {
46    /// Get the next unique ID for a stack entry.
47    /// Mirrors Java's `SpellAbilityStackInstance.nextId()`.
48    pub fn next_id() -> u64 {
49        use std::sync::atomic::{AtomicU64, Ordering};
50        static COUNTER: AtomicU64 = AtomicU64::new(1);
51        COUNTER.fetch_add(1, Ordering::Relaxed)
52    }
53
54    /// Update a target card in this stack entry's spell ability.
55    /// Mirrors Java's `SpellAbilityStackInstance.updateTarget(Card, Card)`.
56    pub fn update_target(&mut self, old: CardId, new: CardId) {
57        self.spell_ability.update_target(old, new);
58    }
59
60    /// Set a triggering object on this stack entry's spell ability.
61    /// Mirrors Java's `SpellAbilityStackInstance.setTriggeringObject(String, Object)`.
62    pub fn set_triggering_object<K: crate::spellability::TriggerKeyInput>(
63        &mut self,
64        key: K,
65        value: &str,
66    ) {
67        self.spell_ability.set_triggering_object(key, value);
68    }
69
70    /// Update a triggering object in this stack entry's spell ability.
71    /// Mirrors Java's `SpellAbilityStackInstance.updateTriggeringObject(String, Object)`.
72    pub fn update_triggering_object<K: crate::spellability::TriggerKeyInput>(
73        &mut self,
74        key: K,
75        value: &str,
76    ) {
77        self.spell_ability.update_triggering_object(key, value);
78    }
79}
80
81/// The game stack. Spells and abilities are added to the top and resolve LIFO.
82/// Mirrors Java's `MagicStack` class.
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct MagicStack {
85    entries: Vec<StackEntry>,
86    next_id: u32,
87
88    /// Whether the stack is frozen (during declare attackers/blockers).
89    /// While frozen, new non-mana abilities are queued in `frozen_stack`.
90    #[serde(default)]
91    frozen: bool,
92
93    /// Entries queued while the stack is frozen (combat declarations).
94    #[serde(default)]
95    frozen_stack: Vec<StackEntry>,
96
97    /// Whether the stack is currently resolving an entry.
98    #[serde(default)]
99    resolving: bool,
100    #[serde(default)]
101    resolving_fizzled: bool,
102
103    /// The card currently being resolved (if any).
104    #[serde(default)]
105    cur_resolving_card: Option<CardId>,
106
107    #[serde(default, skip)]
108    resolving_entry: Option<StackEntry>,
109
110    /// Short-lived LKI cache of entries that were removed from the stack
111    /// during the current resolution cycle (e.g. by Counter effects). Used
112    /// by `find_by_id` so sub-abilities like An Offer You Can't Refuse's
113    /// "its controller creates two Treasure tokens" can still look up the
114    /// countered spell's controller after it's left the stack.
115    #[serde(default, skip)]
116    recently_removed: Vec<StackEntry>,
117
118    /// Cards (by ID) of spells cast this turn — for storm count, etc.
119    #[serde(default)]
120    this_turn_cast: Vec<CardId>,
121
122    /// Cards cast last turn (rotated from this_turn_cast on turn change).
123    #[serde(default)]
124    last_turn_cast: Vec<CardId>,
125
126    /// Abilities activated this turn.
127    #[serde(default)]
128    this_turn_activated: Vec<CardId>,
129
130    /// Maximum distinct sources that have been on the stack simultaneously.
131    #[serde(default)]
132    max_distinct_sources: usize,
133
134    /// Undo stack — tracks undoable spell abilities and their owner.
135    #[serde(default)]
136    undo_stack: Vec<UndoEntry>,
137
138    /// Player who owns the current undo stack.
139    #[serde(default)]
140    undo_stack_owner: Option<PlayerId>,
141
142    /// Simultaneous stack entries waiting to be added (triggers that fire
143    /// at the same time and need ordering by the active player).
144    #[serde(default)]
145    simultaneous_entries: Vec<StackEntry>,
146
147    /// Cast commands keyed by card name — callbacks to run when a spell resolves.
148    #[serde(default)]
149    cast_commands: std::collections::HashMap<String, Vec<String>>,
150}
151
152/// An undo entry tracking a spell that can be undone.
153#[derive(Debug, Clone, Serialize, Deserialize)]
154pub struct UndoEntry {
155    pub source_card: Option<CardId>,
156    pub activating_player: PlayerId,
157}
158
159impl MagicStack {
160    pub fn new() -> Self {
161        MagicStack {
162            entries: Vec::new(),
163            next_id: 0,
164            frozen: false,
165            frozen_stack: Vec::new(),
166            resolving: false,
167            resolving_fizzled: false,
168            cur_resolving_card: None,
169            resolving_entry: None,
170            this_turn_cast: Vec::new(),
171            last_turn_cast: Vec::new(),
172            this_turn_activated: Vec::new(),
173            max_distinct_sources: 0,
174            undo_stack: Vec::new(),
175            undo_stack_owner: None,
176            simultaneous_entries: Vec::new(),
177            cast_commands: std::collections::HashMap::new(),
178            recently_removed: Vec::new(),
179        }
180    }
181
182    pub fn push(&mut self, mut entry: StackEntry) -> u32 {
183        let id = self.next_id;
184        self.next_id += 1;
185        entry.is_pending_cast = false;
186        entry.id = id;
187        self.entries.push(entry);
188        self.update_max_distinct_sources();
189        id
190    }
191
192    pub fn begin_pending_cast(&mut self, mut entry: StackEntry) -> u32 {
193        let id = self.next_id;
194        self.next_id += 1;
195        entry.id = id;
196        entry.is_pending_cast = true;
197        self.entries.push(entry);
198        self.update_max_distinct_sources();
199        id
200    }
201
202    pub fn complete_pending_cast(&mut self, id: u32, mut entry: StackEntry) -> Option<&StackEntry> {
203        let pending = self
204            .entries
205            .iter_mut()
206            .find(|existing| existing.id == id && existing.is_pending_cast)?;
207        entry.id = id;
208        entry.is_pending_cast = false;
209        *pending = entry;
210        self.update_max_distinct_sources();
211        self.entries.iter().find(|existing| existing.id == id)
212    }
213
214    pub fn remove_pending_cast(&mut self, id: u32) -> Option<StackEntry> {
215        let index = self
216            .entries
217            .iter()
218            .position(|entry| entry.id == id && entry.is_pending_cast)?;
219        let entry = self.entries.remove(index);
220        self.update_max_distinct_sources();
221        Some(entry)
222    }
223
224    fn update_max_distinct_sources(&mut self) {
225        let distinct: std::collections::HashSet<_> = self
226            .entries
227            .iter()
228            .filter_map(|e| e.spell_ability.source)
229            .collect();
230        if distinct.len() > self.max_distinct_sources {
231            self.max_distinct_sources = distinct.len();
232        }
233    }
234
235    pub fn pop(&mut self) -> Option<StackEntry> {
236        self.entries.pop()
237    }
238
239    pub fn peek(&self) -> Option<&StackEntry> {
240        self.entries.last()
241    }
242
243    pub fn is_empty(&self) -> bool {
244        self.entries.is_empty()
245    }
246
247    pub fn len(&self) -> usize {
248        self.entries.len()
249    }
250
251    pub fn iter(&self) -> impl Iterator<Item = &StackEntry> {
252        self.entries.iter()
253    }
254
255    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut StackEntry> {
256        self.entries.iter_mut()
257    }
258
259    /// Find a stack entry by ID without removing it. Also searches the
260    /// short-lived LKI cache populated by Counter effects so that follow-up
261    /// sub-abilities can still resolve `Defined$ TargetedController` after
262    /// the target spell has been pulled off the stack.
263    pub fn find_by_id(&self, id: u32) -> Option<&StackEntry> {
264        self.entries
265            .iter()
266            .find(|e| e.id == id)
267            .or_else(|| self.recently_removed.iter().find(|e| e.id == id))
268    }
269
270    /// Remove and return the stack entry with the given ID (for Counter effects).
271    /// The removed entry is kept in a short-lived LKI cache so follow-up
272    /// sub-abilities can still observe its metadata (see `find_by_id`).
273    pub fn remove_by_id(&mut self, id: u32) -> Option<StackEntry> {
274        if let Some(pos) = self.entries.iter().position(|e| e.id == id) {
275            let entry = self.entries.remove(pos);
276            self.recently_removed.push(entry.clone());
277            Some(entry)
278        } else {
279            None
280        }
281    }
282
283    /// Clear the LKI cache of recently-removed entries. Called at the end of
284    /// each stack-resolution cycle so the cache doesn't leak state.
285    pub fn clear_recently_removed(&mut self) {
286        self.recently_removed.clear();
287    }
288
289    /// Find a stack entry by its source card ID (for Ward — finding the targeting spell).
290    pub fn find_by_source_card(&self, card_id: CardId) -> Option<&StackEntry> {
291        self.entries
292            .iter()
293            .find(|e| e.spell_ability.source == Some(card_id))
294    }
295
296    /// Number of items on the stack. Mirrors Java's `MagicStack.size()`.
297    pub fn size(&self) -> usize {
298        self.entries.len()
299    }
300
301    /// Add a stack entry. Mirrors Java's `MagicStack.add()`.
302    pub fn add(&mut self, entry: StackEntry) -> u32 {
303        self.push(entry)
304    }
305
306    /// Remove a specific entry by ID. Mirrors Java's `MagicStack.remove()`.
307    pub fn remove(&mut self, id: u32) -> Option<StackEntry> {
308        self.remove_by_id(id)
309    }
310
311    /// Clear all entries from the stack. Mirrors Java's underlying `clear()`.
312    pub fn clear(&mut self) {
313        self.entries.clear();
314    }
315
316    /// Reset the stack completely. Mirrors Java's `MagicStack.reset()`.
317    pub fn reset(&mut self) {
318        self.entries.clear();
319        self.next_id = 0;
320        self.frozen = false;
321        self.frozen_stack.clear();
322        self.resolving = false;
323        self.cur_resolving_card = None;
324        self.resolving_entry = None;
325        self.last_turn_cast.clear();
326        self.this_turn_cast.clear();
327        self.simultaneous_entries.clear();
328        self.undo_stack.clear();
329        self.undo_stack_owner = None;
330        self.cast_commands.clear();
331    }
332
333    /// Peek at the top ability. Mirrors Java's `MagicStack.peekAbility()`.
334    pub fn peek_ability(&self) -> Option<&SpellAbility> {
335        self.entries.last().map(|e| &e.spell_ability)
336    }
337
338    /// Check if any entry has the given source card.
339    /// Mirrors Java's `MagicStack.hasSourceOnStack()`.
340    pub fn has_source_on_stack(&self, card_id: CardId) -> bool {
341        let matches = |entry: &StackEntry| entry.spell_ability.source == Some(card_id);
342        self.entries.iter().any(&matches)
343            || self.frozen_stack.iter().any(&matches)
344            || self.simultaneous_entries.iter().any(&matches)
345            || self.resolving_entry.as_ref().is_some_and(matches)
346    }
347
348    pub fn has_source_chapter_on_stack(&self, game: &GameState, card_id: CardId) -> bool {
349        let matches = |entry: &StackEntry| {
350            entry.spell_ability.is_trigger
351                && entry.spell_ability.source == Some(card_id)
352                && entry
353                    .spell_ability
354                    .source_trigger_id
355                    .is_some_and(|trigger_id| {
356                        game.card(card_id)
357                            .triggers
358                            .iter()
359                            .any(|trigger| trigger.id == trigger_id && trigger.is_chapter())
360                    })
361        };
362
363        self.entries.iter().any(&matches)
364            || self.frozen_stack.iter().any(&matches)
365            || self.simultaneous_entries.iter().any(&matches)
366            || self.resolving_entry.as_ref().is_some_and(matches)
367    }
368
369    /// Check if the top entry has legal targeting (at least one target chosen).
370    /// Mirrors Java's `MagicStack.hasLegalTargeting()`.
371    pub fn has_legal_targeting(&self) -> bool {
372        match self.entries.last() {
373            Some(entry) => {
374                let tc = &entry.spell_ability.target_chosen;
375                // No targeting required = always legal
376                if entry.spell_ability.target_restrictions.is_none() {
377                    return true;
378                }
379                // Has at least one target chosen
380                tc.target_card.is_some()
381                    || tc.target_player.is_some()
382                    || tc.target_stack_entry.is_some()
383            }
384            None => false,
385        }
386    }
387
388    /// Remove all entries controlled by the given player.
389    /// Mirrors Java's `MagicStack.removeInstancesControlledBy()`.
390    pub fn remove_instances_controlled_by(&mut self, player: PlayerId) {
391        self.entries
392            .retain(|e| e.spell_ability.activating_player != player);
393    }
394
395    /// Forward iterator. Mirrors Java's `MagicStack.iterator()`.
396    pub fn iterator(&self) -> impl Iterator<Item = &StackEntry> {
397        self.entries.iter()
398    }
399
400    /// Reverse iterator (top to bottom). Mirrors Java's `MagicStack.reverseIterator()`.
401    pub fn reverse_iterator(&self) -> impl Iterator<Item = &StackEntry> {
402        self.entries.iter().rev()
403    }
404
405    // ── Frozen stack (for declare attackers/blockers) ────────────────
406
407    /// Whether the stack is currently frozen.
408    pub fn is_frozen(&self) -> bool {
409        self.frozen
410    }
411
412    /// Freeze the stack. While frozen, new entries go to the frozen queue.
413    /// Mirrors Java's `MagicStack.freezeStack()`.
414    pub fn freeze_stack(&mut self) {
415        self.frozen = true;
416    }
417
418    /// Add an entry and unfreeze, flushing any queued frozen entries.
419    /// Mirrors Java's `MagicStack.addAndUnfreeze()`.
420    pub fn add_and_unfreeze(&mut self, entry: StackEntry) -> u32 {
421        let id = self.push(entry);
422        self.unfreeze_stack();
423        id
424    }
425
426    /// Unfreeze the stack and flush all frozen entries onto the real stack.
427    /// Mirrors Java's `MagicStack.unfreezeStack()`.
428    pub fn unfreeze_stack(&mut self) {
429        self.frozen = false;
430        // Move frozen entries onto the real stack
431        let frozen = std::mem::take(&mut self.frozen_stack);
432        for entry in frozen.into_iter().rev() {
433            self.push(entry);
434        }
435    }
436
437    /// Clear all frozen entries without processing them.
438    /// Mirrors Java's `MagicStack.clearFrozen()`.
439    pub fn clear_frozen(&mut self) {
440        self.frozen = false;
441        self.frozen_stack.clear();
442    }
443
444    // ── Resolution state ─────────────────────────────────────────────
445
446    /// Whether the stack is currently resolving.
447    pub fn is_resolving(&self) -> bool {
448        self.resolving
449    }
450
451    pub fn set_resolving(&mut self, resolving: bool) {
452        self.resolving = resolving;
453    }
454    pub fn set_resolving_fizzled(&mut self, fizzled: bool) {
455        self.resolving_fizzled = fizzled;
456    }
457
458    pub fn resolving_fizzle(&self, card: CardId) -> Option<bool> {
459        (self.resolving && self.cur_resolving_card == Some(card)).then_some(self.resolving_fizzled)
460    }
461
462    pub fn set_cur_resolving_card(&mut self, card: Option<CardId>) {
463        self.cur_resolving_card = card;
464    }
465
466    pub fn cur_resolving_card(&self) -> Option<CardId> {
467        self.cur_resolving_card
468    }
469
470    pub fn set_resolving_entry(&mut self, entry: Option<StackEntry>) {
471        self.resolving_entry = entry;
472    }
473
474    // ── Undo stack ───────────────────────────────────────────────────
475
476    /// Check if undo is available for the given player.
477    /// Mirrors Java's `MagicStack.canUndo()`.
478    pub fn can_undo(&self, player: PlayerId) -> bool {
479        self.undo_stack_owner == Some(player) && !self.undo_stack.is_empty()
480    }
481
482    /// Undo the last undoable action. Returns true if successful.
483    /// Mirrors Java's `MagicStack.undo()`.
484    pub fn undo(&mut self) -> bool {
485        if self.undo_stack.is_empty() {
486            return false;
487        }
488        self.undo_stack.pop();
489        if self.undo_stack.is_empty() {
490            self.undo_stack_owner = None;
491        }
492        true
493    }
494
495    /// Clear the undo stack entirely.
496    /// Mirrors Java's `MagicStack.clearUndoStack()`.
497    pub fn clear_undo_stack(&mut self) {
498        self.undo_stack.clear();
499        self.undo_stack_owner = None;
500    }
501
502    /// Remove undo entries whose source matches the given card.
503    /// Mirrors Java's `MagicStack.filterUndoStackByHost()`.
504    pub fn filter_undo_stack_by_host(&mut self, card_id: CardId) {
505        self.undo_stack.retain(|e| e.source_card != Some(card_id));
506        if self.undo_stack.is_empty() {
507            self.undo_stack_owner = None;
508        }
509    }
510
511    /// Record an undoable action on the undo stack.
512    pub fn record_undoable(&mut self, source: Option<CardId>, player: PlayerId) {
513        self.undo_stack_owner = Some(player);
514        self.undo_stack.push(UndoEntry {
515            source_card: source,
516            activating_player: player,
517        });
518    }
519
520    // ── Simultaneous stack entries (triggers) ────────────────────────
521
522    /// Check if there are simultaneous stack entries waiting to be added.
523    /// Mirrors Java's `MagicStack.hasSimultaneousStackEntries()`.
524    pub fn has_simultaneous_stack_entries(&self) -> bool {
525        !self.simultaneous_entries.is_empty()
526    }
527
528    /// Clear all simultaneous stack entries.
529    /// Mirrors Java's `MagicStack.clearSimultaneousStack()`.
530    pub fn clear_simultaneous_stack(&mut self) {
531        self.simultaneous_entries.clear();
532    }
533
534    /// Queue a simultaneous stack entry (trigger) for later addition.
535    /// Mirrors Java's `MagicStack.addSimultaneousStackEntry()`.
536    pub fn add_simultaneous_stack_entry(&mut self, entry: StackEntry) {
537        self.simultaneous_entries.push(entry);
538    }
539
540    /// Move all queued simultaneous entries onto the real stack.
541    /// Returns true if any were added.
542    /// Mirrors Java's `MagicStack.addAllTriggeredAbilitiesToStack()`.
543    pub fn add_all_triggered_abilities_to_stack(&mut self) -> bool {
544        if self.simultaneous_entries.is_empty() {
545            return false;
546        }
547        let entries = std::mem::take(&mut self.simultaneous_entries);
548        for entry in entries {
549            self.push(entry);
550        }
551        true
552    }
553
554    /// Check if there's a state trigger waiting in the simultaneous queue.
555    /// Mirrors Java's `MagicStack.hasStateTrigger()`.
556    pub fn has_state_trigger(&self) -> bool {
557        self.simultaneous_entries
558            .iter()
559            .any(|e| e.spell_ability.is_trigger)
560    }
561
562    /// Check if a specific trigger id already exists in pending/active stack entries.
563    /// Mirrors Java's `MagicStack.hasStateTrigger(triggerId)` behavior.
564    pub fn has_state_trigger_id(&self, trigger_id: u32) -> bool {
565        let matches = |e: &StackEntry| {
566            e.spell_ability.is_trigger && e.spell_ability.source_trigger_id == Some(trigger_id)
567        };
568        self.entries.iter().any(matches)
569            || self.frozen_stack.iter().any(matches)
570            || self.simultaneous_entries.iter().any(matches)
571    }
572
573    // ── Cast commands ────────────────────────────────────────────────
574
575    /// Register a command to run when a spell with the given key resolves.
576    /// Mirrors Java's `MagicStack.addCastCommand()`.
577    pub fn add_cast_command(&mut self, key: &str, command: String) {
578        self.cast_commands
579            .entry(key.to_string())
580            .or_default()
581            .push(command);
582    }
583
584    /// Take and return any cast commands registered for the given key.
585    pub fn take_cast_commands(&mut self, key: &str) -> Vec<String> {
586        self.cast_commands.remove(key).unwrap_or_default()
587    }
588
589    // ── Stack resolution ─────────────────────────────────────────────
590
591    /// Pop the top entry and begin resolution.
592    /// Sets `resolving` state and tracks the resolving card.
593    /// The actual effect resolution is driven by `GameLoop::resolve_stack()`
594    /// which calls this to get the entry, then resolves it with full game context.
595    /// Mirrors Java's `MagicStack.resolveStack()`.
596    pub fn resolve_stack(&mut self) -> Option<StackEntry> {
597        if self
598            .entries
599            .last()
600            .map(|entry| entry.is_pending_cast)
601            .unwrap_or(false)
602        {
603            return None;
604        }
605        let entry = self.entries.pop()?;
606        self.resolving = true;
607        self.cur_resolving_card = entry.spell_ability.source;
608        self.resolving_entry = Some(entry.clone());
609        self.resolving_fizzled = false;
610        Some(entry)
611    }
612
613    /// Mark resolution as complete.
614    pub fn finish_resolving(&mut self) {
615        self.resolving = false;
616        self.cur_resolving_card = None;
617        self.resolving_entry = None;
618        self.resolving_fizzled = false;
619    }
620
621    // ── Turn tracking ────────────────────────────────────────────────
622
623    /// Called when a new turn begins. Rotates cast/activated tracking.
624    /// Mirrors Java's `MagicStack.onNextTurn()`.
625    pub fn on_next_turn(&mut self) {
626        self.last_turn_cast = std::mem::take(&mut self.this_turn_cast);
627        self.this_turn_activated.clear();
628    }
629
630    /// Record that a spell was cast this turn (for storm count, etc.).
631    pub fn record_spell_cast(&mut self, card_id: CardId) {
632        self.this_turn_cast.push(card_id);
633    }
634
635    /// Get the number of spells cast this turn (storm count).
636    pub fn spells_cast_this_turn(&self) -> usize {
637        self.this_turn_cast.len()
638    }
639
640    /// Get the list of spells cast this turn.
641    pub fn get_spells_cast_this_turn(&self) -> &[CardId] {
642        &self.this_turn_cast
643    }
644
645    /// Get the list of spells cast last turn.
646    pub fn get_spells_cast_last_turn(&self) -> &[CardId] {
647        &self.last_turn_cast
648    }
649
650    /// Track an ability activation this turn.
651    /// Mirrors Java's `MagicStack.addAbilityActivatedThisTurn()`.
652    pub fn add_ability_activated_this_turn(&mut self, sa: &SpellAbility) {
653        if let Some(source) = sa.source {
654            self.this_turn_activated.push(source);
655        }
656    }
657
658    /// Reset max distinct sources counter.
659    /// Mirrors Java's `MagicStack.resetMaxDistinctSources()`.
660    pub fn reset_max_distinct_sources(&mut self) {
661        self.max_distinct_sources = 0;
662    }
663
664    /// Get the max distinct sources seen on the stack this turn.
665    pub fn get_max_distinct_sources(&self) -> usize {
666        self.max_distinct_sources
667    }
668
669    /// Find a stack entry whose spell ability ID matches the given stack entry ID.
670    /// Mirrors Java's `MagicStack.getInstanceMatchingSpellAbilityID()`.
671    pub fn get_instance_matching_spell_ability_id(&self, id: u32) -> Option<&StackEntry> {
672        self.entries.iter().find(|si| si.id == id)
673    }
674
675    /// Find a spell on the stack whose host card matches the given card.
676    /// Returns the spell ability if found.
677    /// Mirrors Java's `MagicStack.getSpellMatchingHost()`.
678    pub fn get_spell_matching_host(&self, host: CardId) -> Option<&SpellAbility> {
679        for si in &self.entries {
680            if si.spell_ability.is_spell && si.spell_ability.source == Some(host) {
681                return Some(&si.spell_ability);
682            }
683        }
684        None
685    }
686}
687
688impl Default for MagicStack {
689    fn default() -> Self {
690        Self::new()
691    }
692}