issun 0.10.0

A mini game engine for logic-focused games - Build games in ISSUN (一寸) of time
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
//! Scene Director - Manages scene lifecycle and transitions
//!
//! The SceneDirector handles:
//! - Scene lifecycle (on_enter, on_update, on_exit, on_suspend, on_resume)
//! - Scene transitions (switching, pushing, popping)
//! - Scene stack management
//! - Quit state management
//! - Ownership and distribution of Service/System/Resource contexts
//!
//! # Example
//!
//! ```ignore
//! use issun::prelude::*;
//!
//! #[derive(Scene)]
//! enum GameScene {
//!     Title(TitleData),
//!     Combat(CombatData),
//!     PauseMenu(PauseData),
//! }
//!
//! let game = GameBuilder::new().build().await?;
//! let mut director = SceneDirector::new(
//!     GameScene::Title(TitleData::new()),
//!     game.services,
//!     game.systems,
//!     game.resources,
//! ).await;
//!
//! loop {
//!     let transition = director.update().await;
//!
//!     match transition {
//!         SceneTransition::Quit => break,
//!         _ => {}
//!     }
//!
//!     if director.should_quit() {
//!         break;
//!     }
//! }
//!
//! // Push a pause menu on top
//! director.push(GameScene::PauseMenu(PauseData::new())).await;
//!
//! // Pop back to previous scene
//! director.pop().await;
//! ```

use super::{Scene, SceneTransition};
use crate::context::{ResourceContext, ServiceContext, SystemContext};
use crate::error::Result;
use std::{future::Future, pin::Pin};

/// Scene Director manages scene lifecycle and transitions
///
/// Phase 2+3: Stack-based scene management with full lifecycle hooks
pub struct SceneDirector<S> {
    /// Scene stack (top is the active scene)
    stack: Vec<S>,
    /// Whether the application should quit
    should_quit: bool,
    services: ServiceContext,
    systems: SystemContext,
    resources: ResourceContext,
}

impl<S: Scene> SceneDirector<S> {
    /// Create a new SceneDirector with an initial scene
    ///
    /// The initial scene's `on_enter()` will be called immediately.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let director = SceneDirector::new(
    ///     GameScene::Title(TitleData::new()),
    ///     ServiceContext::new(),
    ///     SystemContext::new(),
    ///     ResourceContext::new(),
    /// ).await;
    /// ```
    pub async fn new(
        mut initial_scene: S,
        services: ServiceContext,
        mut systems: SystemContext,
        mut resources: ResourceContext,
    ) -> Self {
        // Call on_enter for the initial scene
        initial_scene
            .on_enter(&services, &mut systems, &mut resources)
            .await;

        Self {
            stack: vec![initial_scene],
            should_quit: false,
            services,
            systems,
            resources,
        }
    }

    /// Update the current scene (top of stack)
    ///
    /// Calls `on_update()` on the current scene and returns the transition result.
    ///
    /// # Returns
    ///
    /// The SceneTransition<S> indicating what should happen next.
    pub async fn update(&mut self) -> SceneTransition<S> {
        if let Some(current) = self.stack.last_mut() {
            current
                .on_update(&self.services, &mut self.systems, &mut self.resources)
                .await
        } else {
            SceneTransition::Quit // Empty stack = quit
        }
    }

    /// Switch to a new scene (replaces current scene)
    ///
    /// This will:
    /// 1. Call `on_exit()` on the current scene
    /// 2. Replace the current scene with the new scene
    /// 3. Call `on_enter()` on the new scene
    ///
    /// # Example
    ///
    /// ```ignore
    /// director.switch_to(GameScene::Combat(CombatData::new())).await;
    /// ```
    pub async fn switch_to(&mut self, mut next: S) {
        if let Some(mut current) = self.stack.pop() {
            // Exit current scene
            current
                .on_exit(&self.services, &mut self.systems, &mut self.resources)
                .await;
        }

        // Enter new scene
        next.on_enter(&self.services, &mut self.systems, &mut self.resources)
            .await;

        // Push new scene onto stack
        self.stack.push(next);
    }

    /// Push a new scene on top of the stack
    ///
    /// This will:
    /// 1. Call `on_suspend()` on the current scene
    /// 2. Call `on_enter()` on the new scene
    /// 3. Push the new scene onto the stack
    ///
    /// Use this for temporary overlays like pause menus or dialogs.
    ///
    /// # Example
    ///
    /// ```ignore
    /// director.push(GameScene::PauseMenu(PauseData::new())).await;
    /// ```
    pub async fn push(&mut self, mut next: S) {
        // Suspend current scene (if any)
        if let Some(current) = self.stack.last_mut() {
            current
                .on_suspend(&self.services, &mut self.systems, &mut self.resources)
                .await;
        }

        // Enter new scene
        next.on_enter(&self.services, &mut self.systems, &mut self.resources)
            .await;

        // Push onto stack
        self.stack.push(next);
    }

    /// Pop the current scene from the stack
    ///
    /// This will:
    /// 1. Call `on_exit()` on the current scene
    /// 2. Pop the scene from the stack
    /// 3. Call `on_resume()` on the now-current scene (if any)
    ///
    /// Returns `true` if a scene was popped, `false` if stack was empty.
    ///
    /// # Example
    ///
    /// ```ignore
    /// if director.pop().await {
    ///     // Successfully popped back to previous scene
    /// }
    /// ```
    pub async fn pop(&mut self) -> bool {
        if let Some(mut popped) = self.stack.pop() {
            // Exit popped scene
            popped
                .on_exit(&self.services, &mut self.systems, &mut self.resources)
                .await;

            // Resume scene below (if any)
            if let Some(current) = self.stack.last_mut() {
                current
                    .on_resume(&self.services, &mut self.systems, &mut self.resources)
                    .await;
            }

            true
        } else {
            false
        }
    }

    /// Transition to a new scene (deprecated in favor of switch_to)
    ///
    /// This is kept for backward compatibility with Phase 1 code.
    ///
    /// # Example
    ///
    /// ```ignore
    /// director.transition_to(GameScene::Combat(CombatData::new())).await;
    /// ```
    pub async fn transition_to(&mut self, next: S) {
        self.switch_to(next).await;
    }

    /// Request application quit
    ///
    /// This will:
    /// 1. Call `on_exit()` on all scenes in the stack (from top to bottom)
    /// 2. Set the quit flag to true
    pub async fn quit(&mut self) {
        // Exit all scenes in reverse order (top to bottom)
        while let Some(mut scene) = self.stack.pop() {
            scene
                .on_exit(&self.services, &mut self.systems, &mut self.resources)
                .await;
        }

        self.should_quit = true;
    }

    /// Check if the application should quit
    ///
    /// # Returns
    ///
    /// `true` if `quit()` has been called, `false` otherwise.
    pub fn should_quit(&self) -> bool {
        self.should_quit
    }

    /// Get a reference to the current scene (top of stack)
    ///
    /// Returns `None` if the stack is empty.
    ///
    /// Useful for rendering or inspecting scene state.
    pub fn current(&self) -> Option<&S> {
        self.stack.last()
    }

    /// Get a mutable reference to the current scene (top of stack)
    ///
    /// Returns `None` if the stack is empty.
    ///
    /// Useful for direct scene manipulation.
    pub fn current_mut(&mut self) -> Option<&mut S> {
        self.stack.last_mut()
    }

    /// Apply a closure to the current scene together with contexts
    pub fn with_current_mut<R>(
        &mut self,
        f: impl FnOnce(&mut S, &ServiceContext, &mut SystemContext, &mut ResourceContext) -> R,
    ) -> Option<R> {
        if let Some(scene) = self.stack.last_mut() {
            let services = &self.services;
            let systems = &mut self.systems;
            let resources = &mut self.resources;
            Some(f(scene, services, systems, resources))
        } else {
            None
        }
    }

    /// Apply an async handler to the current scene with contexts
    pub async fn with_current_async<R>(
        &mut self,
        mut handler: impl for<'a> FnMut(
            &'a mut S,
            &'a ServiceContext,
            &'a mut SystemContext,
            &'a mut ResourceContext,
        ) -> Pin<Box<dyn Future<Output = R> + 'a>>,
    ) -> Option<R> {
        if let Some(scene) = self.stack.last_mut() {
            Some(
                handler(
                    scene,
                    &self.services,
                    &mut self.systems,
                    &mut self.resources,
                )
                .await,
            )
        } else {
            None
        }
    }

    /// Get the depth of the scene stack
    ///
    /// # Returns
    ///
    /// The number of scenes in the stack.
    pub fn depth(&self) -> usize {
        self.stack.len()
    }

    /// Check if the stack is empty
    pub fn is_empty(&self) -> bool {
        self.stack.is_empty()
    }

    /// Iterate over all scenes in the stack (bottom to top)
    ///
    /// Useful for transparent rendering where you want to draw
    /// background scenes before foreground scenes.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Render all scenes with transparency
    /// for (depth, scene) in director.iter_scenes().enumerate() {
    ///     scene.render(frame, depth);
    /// }
    /// ```
    pub fn iter_scenes(&self) -> impl Iterator<Item = &S> {
        self.stack.iter()
    }

    /// Iterate over all scenes in the stack (top to bottom)
    ///
    /// Useful when you need to process scenes from foreground to background.
    pub fn iter_scenes_rev(&self) -> impl Iterator<Item = &S> {
        self.stack.iter().rev()
    }

    /// Iterate over scenes with their depth index
    ///
    /// Returns (depth, scene) where depth=0 is bottom, depth=n-1 is top.
    ///
    /// # Example
    ///
    /// ```ignore
    /// for (depth, scene) in director.iter_with_depth() {
    ///     if depth < 2 {  // Only render bottom 2 layers
    ///         scene.render(frame);
    ///     }
    /// }
    /// ```
    pub fn iter_with_depth(&self) -> impl Iterator<Item = (usize, &S)> {
        self.stack.iter().enumerate()
    }

    /// Access immutable service context
    pub fn services(&self) -> &ServiceContext {
        &self.services
    }

    /// Access immutable system context
    pub fn systems(&self) -> &SystemContext {
        &self.systems
    }

    /// Access mutable system context
    pub fn systems_mut(&mut self) -> &mut SystemContext {
        &mut self.systems
    }

    /// Access immutable resource context
    pub fn resources(&self) -> &ResourceContext {
        &self.resources
    }

    /// Access mutable resource context
    pub fn resources_mut(&mut self) -> &mut ResourceContext {
        &mut self.resources
    }

    /// Handle a scene transition returned from update()
    ///
    /// This is the primary method for processing scene transitions.
    /// It automatically calls the appropriate lifecycle methods based on the transition type.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Simple one-liner usage
    /// let transition = director.update().await;
    /// director.handle(transition).await?;
    ///
    /// // Or in a single call
    /// let transition = scene.handle_input(input);
    /// director.handle(transition).await?;
    /// ```
    pub async fn handle(&mut self, transition: SceneTransition<S>) -> Result<()> {
        match transition {
            SceneTransition::Stay => {
                // Do nothing
            }
            SceneTransition::Switch(next) => {
                self.switch_to(next).await;
            }
            SceneTransition::Push(next) => {
                self.push(next).await;
            }
            SceneTransition::Pop => {
                self.pop().await;
            }
            SceneTransition::Quit => {
                self.quit().await;
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::context::{ResourceContext, ServiceContext, SystemContext};
    use async_trait::async_trait;

    // Test scene that tracks lifecycle calls
    #[derive(Debug, Clone, PartialEq)]
    struct TestScene {
        name: String,
        enter_count: usize,
        update_count: usize,
        exit_count: usize,
        suspend_count: usize,
        resume_count: usize,
        should_transition: bool,
        should_quit: bool,
    }

    impl TestScene {
        fn new(name: &str) -> Self {
            Self {
                name: name.to_string(),
                enter_count: 0,
                update_count: 0,
                exit_count: 0,
                suspend_count: 0,
                resume_count: 0,
                should_transition: false,
                should_quit: false,
            }
        }

        #[allow(dead_code)]
        fn with_transition(mut self) -> Self {
            self.should_transition = true;
            self
        }

        fn with_quit(mut self) -> Self {
            self.should_quit = true;
            self
        }
    }

    #[async_trait]
    impl Scene for TestScene {
        async fn on_enter(
            &mut self,
            _services: &ServiceContext,
            _systems: &mut SystemContext,
            _resources: &mut ResourceContext,
        ) {
            self.enter_count += 1;
        }

        async fn on_update(
            &mut self,
            _services: &ServiceContext,
            _systems: &mut SystemContext,
            _resources: &mut ResourceContext,
        ) -> SceneTransition<Self> {
            self.update_count += 1;

            if self.should_quit {
                SceneTransition::Quit
            } else if self.should_transition {
                SceneTransition::Switch(TestScene::new("next"))
            } else {
                SceneTransition::Stay
            }
        }

        async fn on_exit(
            &mut self,
            _services: &ServiceContext,
            _systems: &mut SystemContext,
            _resources: &mut ResourceContext,
        ) {
            self.exit_count += 1;
        }

        async fn on_suspend(
            &mut self,
            _services: &ServiceContext,
            _systems: &mut SystemContext,
            _resources: &mut ResourceContext,
        ) {
            self.suspend_count += 1;
        }

        async fn on_resume(
            &mut self,
            _services: &ServiceContext,
            _systems: &mut SystemContext,
            _resources: &mut ResourceContext,
        ) {
            self.resume_count += 1;
        }
    }

    async fn director_with_scene(scene: TestScene) -> SceneDirector<TestScene> {
        SceneDirector::new(
            scene,
            ServiceContext::new(),
            SystemContext::new(),
            ResourceContext::new(),
        )
        .await
    }

    #[tokio::test]
    async fn test_new_calls_on_enter() {
        let scene = TestScene::new("test");
        let director = director_with_scene(scene).await;

        assert_eq!(director.depth(), 1);
        assert_eq!(director.current().unwrap().enter_count, 1);
        assert_eq!(director.current().unwrap().update_count, 0);
        assert_eq!(director.current().unwrap().exit_count, 0);
    }

    #[tokio::test]
    async fn test_update_calls_on_update() {
        let scene = TestScene::new("test");
        let mut director = director_with_scene(scene).await;

        let transition = director.update().await;
        assert_eq!(transition, SceneTransition::Stay);
        assert_eq!(director.current().unwrap().update_count, 1);
    }

    #[tokio::test]
    async fn test_switch_to_calls_lifecycle() {
        let scene1 = TestScene::new("scene1");
        let mut director = director_with_scene(scene1).await;

        // Switch to scene2
        let scene2 = TestScene::new("scene2");
        director.switch_to(scene2).await;

        // scene1 should have exited (but we can't check it anymore)
        // scene2 should have entered
        assert_eq!(director.depth(), 1);
        assert_eq!(director.current().unwrap().name, "scene2");
        assert_eq!(director.current().unwrap().enter_count, 1);
        assert_eq!(director.current().unwrap().exit_count, 0);
    }

    #[tokio::test]
    async fn test_push_calls_suspend_and_enter() {
        let scene1 = TestScene::new("scene1");
        let mut director = director_with_scene(scene1).await;

        // Push scene2 on top
        let scene2 = TestScene::new("scene2");
        director.push(scene2).await;

        assert_eq!(director.depth(), 2);
        assert_eq!(director.current().unwrap().name, "scene2");
        assert_eq!(director.current().unwrap().enter_count, 1);

        // Can't check scene1's suspend_count from here, but it should be 1
    }

    #[tokio::test]
    async fn test_pop_calls_exit_and_resume() {
        let scene1 = TestScene::new("scene1");
        let mut director = director_with_scene(scene1).await;

        let scene2 = TestScene::new("scene2");
        director.push(scene2).await;

        assert_eq!(director.depth(), 2);

        // Pop scene2
        let popped = director.pop().await;
        assert!(popped);

        assert_eq!(director.depth(), 1);
        assert_eq!(director.current().unwrap().name, "scene1");
        assert_eq!(director.current().unwrap().resume_count, 1);
    }

    #[tokio::test]
    async fn test_quit_calls_on_exit_for_all() {
        let scene1 = TestScene::new("scene1");
        let mut director = director_with_scene(scene1).await;

        let scene2 = TestScene::new("scene2");
        director.push(scene2).await;

        assert_eq!(director.depth(), 2);
        assert!(!director.should_quit());

        director.quit().await;

        assert!(director.should_quit());
        assert_eq!(director.depth(), 0);
        assert!(director.current().is_none());
    }

    #[tokio::test]
    async fn test_should_quit_returns_transition() {
        let scene = TestScene::new("test").with_quit();
        let mut director = director_with_scene(scene).await;

        let transition = director.update().await;
        assert!(matches!(transition, SceneTransition::Quit));
    }

    #[tokio::test]
    async fn test_handle_switch() {
        let scene1 = TestScene::new("scene1");
        let mut director = director_with_scene(scene1).await;

        let transition = SceneTransition::Switch(TestScene::new("scene2"));
        director.handle(transition).await.unwrap();

        assert_eq!(director.depth(), 1);
        assert_eq!(director.current().unwrap().name, "scene2");
    }

    #[tokio::test]
    async fn test_handle_push_pop() {
        let scene1 = TestScene::new("scene1");
        let mut director = director_with_scene(scene1).await;

        // Push scene2
        let transition = SceneTransition::Push(TestScene::new("scene2"));
        director.handle(transition).await.unwrap();
        assert_eq!(director.depth(), 2);
        assert_eq!(director.current().unwrap().name, "scene2");

        // Pop back to scene1
        let transition = SceneTransition::Pop;
        director.handle(transition).await.unwrap();
        assert_eq!(director.depth(), 1);
        assert_eq!(director.current().unwrap().name, "scene1");
    }

    #[tokio::test]
    async fn test_handle_quit() {
        let scene1 = TestScene::new("scene1");
        let mut director = director_with_scene(scene1).await;

        let transition = SceneTransition::Quit;
        director.handle(transition).await.unwrap();

        assert!(director.should_quit());
        assert_eq!(director.depth(), 0);
    }

    #[tokio::test]
    async fn test_multiple_pushes_and_pops() {
        let scene1 = TestScene::new("scene1");
        let mut director = director_with_scene(scene1).await;

        // Push scene2, scene3
        director.push(TestScene::new("scene2")).await;
        director.push(TestScene::new("scene3")).await;

        assert_eq!(director.depth(), 3);
        assert_eq!(director.current().unwrap().name, "scene3");

        // Pop back to scene2
        director.pop().await;
        assert_eq!(director.depth(), 2);
        assert_eq!(director.current().unwrap().name, "scene2");

        // Pop back to scene1
        director.pop().await;
        assert_eq!(director.depth(), 1);
        assert_eq!(director.current().unwrap().name, "scene1");
    }

    #[tokio::test]
    async fn test_empty_stack_after_pop() {
        let scene1 = TestScene::new("scene1");
        let mut director = director_with_scene(scene1).await;

        director.pop().await;

        assert_eq!(director.depth(), 0);
        assert!(director.current().is_none());
    }

    #[tokio::test]
    async fn test_backward_compatibility_transition_to() {
        let scene1 = TestScene::new("scene1");
        let mut director = director_with_scene(scene1).await;

        // transition_to should work like switch_to
        director.transition_to(TestScene::new("scene2")).await;

        assert_eq!(director.depth(), 1);
        assert_eq!(director.current().unwrap().name, "scene2");
    }

    #[tokio::test]
    async fn test_iter_scenes() {
        let scene1 = TestScene::new("scene1");
        let mut director = director_with_scene(scene1).await;
        director.push(TestScene::new("scene2")).await;
        director.push(TestScene::new("scene3")).await;

        let names: Vec<_> = director.iter_scenes().map(|s| s.name.as_str()).collect();
        assert_eq!(names, vec!["scene1", "scene2", "scene3"]);
    }

    #[tokio::test]
    async fn test_iter_scenes_rev() {
        let scene1 = TestScene::new("scene1");
        let mut director = director_with_scene(scene1).await;
        director.push(TestScene::new("scene2")).await;
        director.push(TestScene::new("scene3")).await;

        let names: Vec<_> = director
            .iter_scenes_rev()
            .map(|s| s.name.as_str())
            .collect();
        assert_eq!(names, vec!["scene3", "scene2", "scene1"]);
    }

    #[tokio::test]
    async fn test_iter_with_depth() {
        let scene1 = TestScene::new("scene1");
        let mut director = director_with_scene(scene1).await;
        director.push(TestScene::new("scene2")).await;

        let items: Vec<_> = director
            .iter_with_depth()
            .map(|(depth, scene)| (depth, scene.name.as_str()))
            .collect();

        assert_eq!(items, vec![(0, "scene1"), (1, "scene2")]);
    }
}