1use forge_foundation::ZoneType;
7use serde::{Deserialize, Serialize};
8
9use crate::game::GameState;
10use crate::ids::{CardId, PlayerId};
11use crate::spellability::SpellAbility;
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct StackEntry {
19 pub id: u32,
20 pub spell_ability: SpellAbility,
22 #[serde(default)]
26 pub is_pending_cast: bool,
27 pub is_creature_spell: bool,
29 pub is_permanent_spell: bool,
31 pub cast_from_zone: Option<ZoneType>,
33 #[serde(default)]
36 pub optional_trigger_decider: Option<PlayerId>,
37 #[serde(default)]
39 pub optional_trigger_description: Option<String>,
40 #[serde(default)]
42 pub optional_trigger_source_name: Option<String>,
43}
44
45impl StackEntry {
46 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 pub fn update_target(&mut self, old: CardId, new: CardId) {
57 self.spell_ability.update_target(old, new);
58 }
59
60 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct MagicStack {
85 entries: Vec<StackEntry>,
86 next_id: u32,
87
88 #[serde(default)]
91 frozen: bool,
92
93 #[serde(default)]
95 frozen_stack: Vec<StackEntry>,
96
97 #[serde(default)]
99 resolving: bool,
100 #[serde(default)]
101 resolving_fizzled: bool,
102
103 #[serde(default)]
105 cur_resolving_card: Option<CardId>,
106
107 #[serde(default, skip)]
108 resolving_entry: Option<StackEntry>,
109
110 #[serde(default, skip)]
116 recently_removed: Vec<StackEntry>,
117
118 #[serde(default)]
120 this_turn_cast: Vec<CardId>,
121
122 #[serde(default)]
124 last_turn_cast: Vec<CardId>,
125
126 #[serde(default)]
128 this_turn_activated: Vec<CardId>,
129
130 #[serde(default)]
132 max_distinct_sources: usize,
133
134 #[serde(default)]
136 undo_stack: Vec<UndoEntry>,
137
138 #[serde(default)]
140 undo_stack_owner: Option<PlayerId>,
141
142 #[serde(default)]
145 simultaneous_entries: Vec<StackEntry>,
146
147 #[serde(default)]
149 cast_commands: std::collections::HashMap<String, Vec<String>>,
150}
151
152#[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 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 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 pub fn clear_recently_removed(&mut self) {
286 self.recently_removed.clear();
287 }
288
289 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 pub fn size(&self) -> usize {
298 self.entries.len()
299 }
300
301 pub fn add(&mut self, entry: StackEntry) -> u32 {
303 self.push(entry)
304 }
305
306 pub fn remove(&mut self, id: u32) -> Option<StackEntry> {
308 self.remove_by_id(id)
309 }
310
311 pub fn clear(&mut self) {
313 self.entries.clear();
314 }
315
316 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 pub fn peek_ability(&self) -> Option<&SpellAbility> {
335 self.entries.last().map(|e| &e.spell_ability)
336 }
337
338 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 pub fn has_legal_targeting(&self) -> bool {
372 match self.entries.last() {
373 Some(entry) => {
374 let tc = &entry.spell_ability.target_chosen;
375 if entry.spell_ability.target_restrictions.is_none() {
377 return true;
378 }
379 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 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 pub fn iterator(&self) -> impl Iterator<Item = &StackEntry> {
397 self.entries.iter()
398 }
399
400 pub fn reverse_iterator(&self) -> impl Iterator<Item = &StackEntry> {
402 self.entries.iter().rev()
403 }
404
405 pub fn is_frozen(&self) -> bool {
409 self.frozen
410 }
411
412 pub fn freeze_stack(&mut self) {
415 self.frozen = true;
416 }
417
418 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 pub fn unfreeze_stack(&mut self) {
429 self.frozen = false;
430 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 pub fn clear_frozen(&mut self) {
440 self.frozen = false;
441 self.frozen_stack.clear();
442 }
443
444 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 pub fn can_undo(&self, player: PlayerId) -> bool {
479 self.undo_stack_owner == Some(player) && !self.undo_stack.is_empty()
480 }
481
482 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 pub fn clear_undo_stack(&mut self) {
498 self.undo_stack.clear();
499 self.undo_stack_owner = None;
500 }
501
502 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 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 pub fn has_simultaneous_stack_entries(&self) -> bool {
525 !self.simultaneous_entries.is_empty()
526 }
527
528 pub fn clear_simultaneous_stack(&mut self) {
531 self.simultaneous_entries.clear();
532 }
533
534 pub fn add_simultaneous_stack_entry(&mut self, entry: StackEntry) {
537 self.simultaneous_entries.push(entry);
538 }
539
540 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 pub fn has_state_trigger(&self) -> bool {
557 self.simultaneous_entries
558 .iter()
559 .any(|e| e.spell_ability.is_trigger)
560 }
561
562 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 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 pub fn take_cast_commands(&mut self, key: &str) -> Vec<String> {
586 self.cast_commands.remove(key).unwrap_or_default()
587 }
588
589 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 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 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 pub fn record_spell_cast(&mut self, card_id: CardId) {
632 self.this_turn_cast.push(card_id);
633 }
634
635 pub fn spells_cast_this_turn(&self) -> usize {
637 self.this_turn_cast.len()
638 }
639
640 pub fn get_spells_cast_this_turn(&self) -> &[CardId] {
642 &self.this_turn_cast
643 }
644
645 pub fn get_spells_cast_last_turn(&self) -> &[CardId] {
647 &self.last_turn_cast
648 }
649
650 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 pub fn reset_max_distinct_sources(&mut self) {
661 self.max_distinct_sources = 0;
662 }
663
664 pub fn get_max_distinct_sources(&self) -> usize {
666 self.max_distinct_sources
667 }
668
669 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 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}