spottedcat 0.5.1

Rusty SpottedCat simple game engine
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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
//! Spot - A simple 2D graphics library for drawing images.
//!
//! # Example
//! ```no_run
//! use spottedcat::{Context, Spot, Image, DrawOption, switch_scene};
//!
//! struct MyApp {
//!     image: Image,
//! }
//!
//! impl Spot for MyApp {
//!     fn initialize(_context: &mut Context) -> Self {
//!         let rgba = vec![255u8; 256 * 256 * 4];
//!         let image = Image::new_from_rgba8(256u32.into(), 256u32.into(), &rgba).unwrap();
//!         Self { image }
//!     }
//!
//!     fn draw(&mut self, context: &mut Context) {
//!         let opts = DrawOption::default()
//!             .with_position([spottedcat::Pt::from(100.0), spottedcat::Pt::from(100.0)])
//!             .with_scale([0.78125, 0.78125]);
//!         self.image.draw(context, opts);
//!     }
//!
//!     fn update(&mut self, _context: &mut Context, _dt: std::time::Duration) {}
//!     fn remove(&self) {}
//! }
//!
//! fn main() {
//!     spottedcat::run::<MyApp>(spottedcat::WindowConfig::default());
//! }
//!
//! // Scene switching example:
//! // switch_scene::<NewScene>();  // Switches to NewScene
//! ```

mod audio;
#[cfg(target_os = "android")]
pub mod android;
mod drawable;
mod glyph_cache;
pub mod graphics;
mod image;
mod image_raw;
pub mod model;
mod input;
mod key;
mod mouse;
mod packer;
mod platform;
mod pt;
mod shader_opts;
mod text;
mod texture;
mod touch;
mod window;

use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::rc::Rc;
use std::time::Duration;
#[cfg(not(target_os = "android"))]
use winit::event_loop::EventLoop;

#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
use console_error_panic_hook;

use crate::graphics::Graphics;

use crate::drawable::{DrawCommand, DrawCommand3D};
pub use drawable::{DrawOption, DrawOption3D};
pub use image::{Bounds, Image};
pub use model::Model;
pub use input::InputManager;
pub use key::Key;
pub use mouse::MouseButton;
pub use pt::Pt;
pub use shader_opts::ShaderOpts;
pub use text::Text;
pub use touch::{TouchInfo, TouchPhase};
#[cfg(target_os = "android")]
pub use android_activity::AndroidApp;

#[derive(Debug, Clone)]
pub struct SoundOptions {
    pub volume: f32,
    pub fade_in: Duration,
    pub fade_out: Option<Duration>,
    pub start_paused: bool,
}

impl Default for SoundOptions {
    fn default() -> Self {
        Self {
            volume: 1.0,
            fade_in: Duration::ZERO,
            fade_out: None,
            start_paused: false,
        }
    }
}

#[derive(Debug, Clone)]
pub struct WindowConfig {
    pub title: String,
    pub width: Pt,
    pub height: Pt,
    pub resizable: bool,
    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
    pub canvas_id: Option<String>,
}

impl Default for WindowConfig {
    fn default() -> Self {
        Self {
            title: "spot".to_string(),
            width: Pt(800.0),
            height: Pt(600.0),
            resizable: true,
            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
            canvas_id: None,
        }
    }
}


#[derive(Debug, Clone, Copy)]
pub(crate) struct DrawState {
    pub position: [Pt; 2],
    pub clip: Option<[Pt; 4]>,
    pub shader_id: Option<u32>,
    pub shader_opts: Option<ShaderOpts>,
}

impl Default for DrawState {
    fn default() -> Self {
        Self {
            position: [Pt(0.0), Pt(0.0)],
            clip: None,
            shader_id: None,
            shader_opts: None,
        }
    }
}

/// Drawing context for managing render commands.
///
/// The context accumulates drawing commands during a frame and is used by the
/// graphics system to render the scene.
#[derive(Debug)]
pub struct Context {
    draw_list: Vec<DrawCommand>,
    draw_list_3d: Vec<DrawCommand3D>,
    input: InputManager,
    scale_factor: f64,
    window_logical_size: (Pt, Pt),
    resources: ResourceMap,
    state_stack: Vec<DrawState>,
    current_state: DrawState,
    last_image_opts: HashMap<u32, LastImageDrawInfo>,
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct LastImageDrawInfo {
    pub(crate) opts: DrawOption,
}

#[derive(Default)]
struct ResourceMap {
    inner: HashMap<TypeId, Rc<dyn Any>>,
}

impl std::fmt::Debug for ResourceMap {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ResourceMap")
            .field("len", &self.inner.len())
            .finish()
    }
}

impl Context {
    /// Creates a new drawing context.
    ///
    /// This is typically done automatically by the `run` function, but can be
    /// used to create a new context manually if needed.
    pub fn new() -> Self {
        Self {
            draw_list: Vec::new(),
            draw_list_3d: Vec::new(),
            input: InputManager::new(),
            scale_factor: 1.0,
            window_logical_size: (Pt(0.0), Pt(0.0)),
            resources: ResourceMap::default(),
            state_stack: Vec::new(),
            current_state: DrawState::default(),
            last_image_opts: HashMap::new(),
        }
    }

    pub fn set_window_logical_size(&mut self, width: Pt, height: Pt) {
        let w = Pt(width.0.max(0.0));
        let h = Pt(height.0.max(0.0));
        self.window_logical_size = (w, h);
    }

    pub fn window_logical_size(&self) -> (Pt, Pt) {
        self.window_logical_size
    }

    pub fn vw(&self, percent: f32) -> Pt {
        let (w, _) = self.window_logical_size;
        let p = if percent.is_finite() { percent } else { 0.0 };
        Pt::from((w.as_f32() * (p / 100.0)) as f32)
    }

    pub fn vh(&self, percent: f32) -> Pt {
        let (_, h) = self.window_logical_size;
        let p = if percent.is_finite() { percent } else { 0.0 };
        Pt::from((h.as_f32() * (p / 100.0)) as f32)
    }

    pub fn insert_resource<T: Any>(&mut self, value: Rc<T>) {
        self.resources
            .inner
            .insert(TypeId::of::<T>(), value as Rc<dyn Any>);
    }

    pub fn get_resource<T: Any>(&self) -> Option<Rc<T>> {
        self.resources
            .inner
            .get(&TypeId::of::<T>())
            .cloned()
            .and_then(|v| Rc::downcast::<T>(v).ok())
    }

    // Assuming `process_registrations` is a new method to be added here,
    // based on the provided diff's context.
    // The `dirty_assets` field is not present in `Context`, so it's commented out.
    // The `flush_font_queue` method is also not present, so it's commented out.
    // This method's body is reconstructed from the diff, correcting the apparent copy-paste error.

    pub fn remove_resource<T: Any>(&mut self) -> Option<Rc<T>> {
        self.resources
            .inner
            .remove(&TypeId::of::<T>())
            .and_then(|v| Rc::downcast::<T>(v).ok())
    }

    pub fn set_ambient_light(&mut self, color: [f32; 4]) {
        crate::with_graphics(|g| {
            g.scene_globals.ambient_color = color;
        });
    }

    pub fn set_light(&mut self, index: usize, position: [f32; 4], color: [f32; 4]) {
        crate::with_graphics(|g| {
            if index < 4 {
                g.scene_globals.lights[index] = crate::graphics::Light {
                    position,
                    color,
                };
            }
        });
    }

    pub fn set_camera_pos(&mut self, pos: [f32; 3]) {
        crate::with_graphics(|g| {
            g.scene_globals.camera_pos = [pos[0], pos[1], pos[2], 1.0];
        });
    }

    pub(crate) fn insert_resource_dyn(&mut self, type_id: TypeId, value: Rc<dyn Any>) {
        self.resources.inner.insert(type_id, value);
    }

    pub(crate) fn remove_resource_dyn(&mut self, type_id: TypeId) {
        self.resources.inner.remove(&type_id);
    }

    /// Creates a skeletal skin with the specified bone hierarchy and initial matrices.
    pub fn create_skin(&self, bones: Vec<crate::graphics::Bone>, matrices: Vec<[[f32; 4]; 4]>) -> u32 {
        crate::with_graphics(|g| g.create_skin(bones, matrices)).unwrap_or(0)
    }

    /// Updates the bone matrices for a specific skin.
    pub fn update_bone_matrices(&self, skin_id: u32, matrices: &[[[f32; 4]; 4]]) {
        crate::with_graphics(|g| g.update_bone_matrices(skin_id, matrices));
    }

    /// Clears all drawing commands from the previous frame.
    ///
    /// This is called automatically at the start of each frame, but can be used
    /// manually if needed.
    pub(crate) fn begin_frame(&mut self) {
        self.draw_list.clear();
        self.draw_list_3d.clear();
        self.state_stack.clear();
        self.current_state = DrawState::default();
        self.last_image_opts.clear();
    }

    pub(crate) fn input(&self) -> &InputManager {
        &self.input
    }

    pub(crate) fn input_mut(&mut self) -> &mut InputManager {
        &mut self.input
    }

    pub(crate) fn set_scale_factor(&mut self, scale_factor: f64) {
        self.scale_factor = scale_factor;
    }

    pub fn scale_factor(&self) -> f64 {
        self.scale_factor
    }

    /// Adds a drawable item to the draw list.
    ///
    /// This is used internally by Image::draw() and other drawing methods.
    pub(crate) fn push(&mut self, mut drawable: DrawCommand) {
        // Apply current state to the drawable
        match &mut drawable {
            DrawCommand::Image(_id, opts, shader_id, shader_opts, _) => {
                *opts = opts.apply_state(&self.current_state);
                // Inherit shader if not explicitly set
                if *shader_id == 0 {
                    if let Some(parent_shader_id) = self.current_state.shader_id {
                        // eprintln!("Inheriting shader {} from state", parent_shader_id);
                        *shader_id = parent_shader_id;
                        if let Some(parent_shader_opts) = self.current_state.shader_opts {
                            *shader_opts = parent_shader_opts;
                        }
                    }
                }
            }
            DrawCommand::Text(_, opts) => {
                *opts = opts.apply_state(&self.current_state);
            }
        }
        if let DrawCommand::Image(id, opts, _, _, size) = &drawable {
            // Culling check
            let pos = opts.position();
            let scale = opts.scale();
            let rot = opts.rotation();
            let w = size[0].as_f32() * scale[0];
            let h = size[1].as_f32() * scale[1];

            let (vw, vh) = self.window_logical_size;
            let screen_w = vw.as_f32();
            let screen_h = vh.as_f32();

            let is_visible = if rot == 0.0 {
                let x0 = pos[0].as_f32();
                let y0 = pos[1].as_f32();
                let x1 = x0 + w;
                let y1 = y0 + h;

                let min_x = x0.min(x1);
                let max_x = x0.max(x1);
                let min_y = y0.min(y1);
                let max_y = y0.max(y1);

                !(max_x < 0.0 || min_x > screen_w || max_y < 0.0 || min_y > screen_h)
            } else {
                let c = rot.cos();
                let s = rot.sin();
                let x2 = w * c;
                let y2 = w * s;
                let x3 = -h * s;
                let y3 = h * c;
                let x4 = x2 + x3;
                let y4 = y2 + y3;

                let min_x = 0.0f32.min(x2).min(x3).min(x4);
                let max_x = 0.0f32.max(x2).max(x3).max(x4);
                let min_y = 0.0f32.min(y2).min(y3).min(y4);
                let max_y = 0.0f32.max(y2).max(y3).max(y4);

                !(pos[0].as_f32() + max_x < 0.0
                    || pos[0].as_f32() + min_x > screen_w
                    || pos[1].as_f32() + max_y < 0.0
                    || pos[1].as_f32() + min_y > screen_h)
            };

            if !is_visible {
                if std::env::var("SPOT_DEBUG_CULL").is_ok() {
                    eprintln!(
                        "[spot][cull] image id={} at {:?} (size {:?}) is culled (screen: {:?})",
                        id,
                        pos,
                        [w, h],
                        self.window_logical_size
                    );
                }
                return;
            }

            self.last_image_opts
                .insert(*id, LastImageDrawInfo { opts: *opts });
        }
        if std::env::var("SPOT_DEBUG_DRAW").is_ok() {
            match &drawable {
                DrawCommand::Image(id, opts, shader_id, _shader_opts, _) => {
                    eprintln!(
                        "[spot][debug] draw image id={} shader_id={} pos={:?} clip={:?}",
                        id,
                        shader_id,
                        opts.position(),
                        opts.get_clip()
                    );
                }
                DrawCommand::Text(_text, opts) => {
                    eprintln!(
                        "[spot][debug] draw text pos={:?} clip={:?}",
                        opts.position(),
                        opts.get_clip()
                    );
                }
            }
        }
        self.draw_list.push(drawable);
    }

    pub(crate) fn push_3d(&mut self, drawable: DrawCommand3D) {
        self.draw_list_3d.push(drawable);
    }

    fn current_draw_state(&self) -> DrawState {
        self.current_state
    }

    pub(crate) fn last_image_draw_info(&self, image_id: u32) -> Option<LastImageDrawInfo> {
        self.last_image_opts.get(&image_id).copied()
    }

    fn push_state(&mut self, state: DrawState) {
        self.state_stack.push(self.current_state);

        // Accumulate position correctly:
        // state.position passed from draw_image is the LOCAL relative position of the parent.
        // We add it to the current absolute position to get the new origin for children.
        self.current_state.position[0] += state.position[0];
        self.current_state.position[1] += state.position[1];

        // Merge clip: clip in state is already absolute screen-space bounds
        if let Some(new_clip_abs) = state.clip {
            let merged_clip = if let Some(old_clip_abs) = self.current_state.clip {
                // Intersect absolute clips
                let x = old_clip_abs[0].as_f32().max(new_clip_abs[0].as_f32());
                let y = old_clip_abs[1].as_f32().max(new_clip_abs[1].as_f32());
                let right = (old_clip_abs[0].as_f32() + old_clip_abs[2].as_f32())
                    .min(new_clip_abs[0].as_f32() + new_clip_abs[2].as_f32());
                let bottom = (old_clip_abs[1].as_f32() + old_clip_abs[3].as_f32())
                    .min(new_clip_abs[1].as_f32() + new_clip_abs[3].as_f32());

                let w = (right - x).max(0.0);
                let h = (bottom - y).max(0.0);
                Some([Pt::from(x), Pt::from(y), Pt::from(w), Pt::from(h)])
            } else {
                Some(new_clip_abs)
            };
            self.current_state.clip = merged_clip;
        }

        // Apply shader state if provided in the new state
        if let Some(sid) = state.shader_id {
            self.current_state.shader_id = Some(sid);
        }
        if let Some(sopts) = state.shader_opts {
            self.current_state.shader_opts = Some(sopts);
        }
    }

    fn pop_state(&mut self) {
        if let Some(prev_state) = self.state_stack.pop() {
            self.current_state = prev_state;
        }
    }

    /// Returns the list of drawing commands accumulated so far.
    ///
    /// This is used internally by the graphics system to render the scene.
    pub(crate) fn draw_list(&self) -> &[DrawCommand] {
        &self.draw_list
    }

    pub(crate) fn draw_list_3d(&self) -> &[DrawCommand3D] {
        &self.draw_list_3d
    }
}

pub fn key_down(context: &Context, key: Key) -> bool {
    context.input().key_down(key)
}

pub fn key_pressed(context: &Context, key: Key) -> bool {
    context.input().key_pressed(key)
}

pub fn key_released(context: &Context, key: Key) -> bool {
    context.input().key_released(key)
}

pub fn mouse_button_down(context: &Context, button: MouseButton) -> bool {
    context.input().mouse_down(button)
}

pub fn mouse_button_pressed(context: &Context, button: MouseButton) -> bool {
    context.input().mouse_pressed(button)
}

pub fn mouse_button_released(context: &Context, button: MouseButton) -> bool {
    context.input().mouse_released(button)
}

pub fn mouse_button_pressed_position(context: &Context, button: MouseButton) -> Option<(Pt, Pt)> {
    if mouse_button_pressed(context, button) {
        cursor_position(context)
    } else {
        None
    }
}

pub fn window_size(context: &Context) -> (Pt, Pt) {
    context.window_logical_size()
}

pub fn cursor_position(context: &Context) -> Option<(Pt, Pt)> {
    context.input().cursor_position()
}

pub fn text_input_enabled(context: &Context) -> bool {
    context.input().text_input_enabled()
}

pub fn set_text_input_enabled(context: &mut Context, enabled: bool) {
    context.input_mut().set_text_input_enabled(enabled);
}

pub fn text_input(context: &Context) -> &str {
    context.input().text_input()
}

pub fn get_input(context: &Context) -> &str {
    context.input().text_input()
}

pub fn touches(context: &Context) -> &[TouchInfo] {
    context.input().touches()
}

#[cfg(feature = "sensors")]
pub fn gyroscope(context: &Context) -> Option<[f32; 3]> {
    context.input().gyroscope()
}

#[cfg(feature = "sensors")]
pub fn accelerometer(context: &Context) -> Option<[f32; 3]> {
    context.input().accelerometer()
}

#[cfg(feature = "sensors")]
pub fn magnetometer(context: &Context) -> Option<[f32; 3]> {
    context.input().magnetometer()
}

#[cfg(feature = "sensors")]
pub fn rotation(context: &Context) -> Option<[f32; 4]> {
    context.input().rotation()
}

pub fn touch_down(context: &Context) -> bool {
    !context.input().touches().is_empty()
}

pub fn ime_preedit(context: &Context) -> Option<&str> {
    context.input().ime_preedit()
}

pub fn register_image_shader(wgsl_source: &str) -> u32 {
    with_graphics(|g| g.register_image_shader(wgsl_source)).unwrap_or(0)
}

pub fn register_model_shader(wgsl_source: &str) -> u32 {
    with_graphics(|g| g.register_model_shader(wgsl_source)).unwrap_or(0)
}

pub fn register_font(font_data: Vec<u8>) -> u32 {
    with_graphics(|g| g.register_font(font_data)).unwrap_or(0)
}

pub fn get_registered_font(font_id: u32) -> Option<Vec<u8>> {
    with_graphics(|g| g.get_font(font_id).cloned()).flatten()
}

pub fn unregister_font(font_id: u32) {
    with_graphics(|g| g.unregister_font(font_id));
}

/// Manually compresses GPU assets to reclaim memory.
///
/// This will rebuild the texture atlases if any assets have been unregistered,
/// defragmenting GPU memory and physically releasing unused space.
pub fn compress_assets() {
    with_graphics(|g| {
        let _ = g.compress_assets();
    });
}

pub fn register_sound(bytes: Vec<u8>) -> u32 {
    platform::with_audio(|a| a.register_sound(bytes)).unwrap_or(0)
}

pub fn play_sound(sound_id: u32, options: SoundOptions) -> Option<u64> {
    let opts = audio::PlayOptions {
        volume: options.volume,
        fade_in: options.fade_in,
        fade_out: options.fade_out,
        start_paused: options.start_paused,
    };
    platform::with_audio(|a| a.play_registered_sound_with_options(sound_id, opts)).flatten()
}

pub fn play_sound_simple(sound_id: u32) -> Option<u64> {
    platform::with_audio(|a| {
        a.play_registered_sound_with_options(sound_id, audio::PlayOptions::default())
    })
    .flatten()
}

pub fn pause_sound(play_id: u64) {
    platform::with_audio(|a| a.pause_play_id(play_id));
}

pub fn resume_sound(play_id: u64) {
    platform::with_audio(|a| a.resume_play_id(play_id));
}

pub fn stop_sound(play_id: u64) {
    platform::with_audio(|a| a.stop_play_id(play_id));
}

pub fn fade_in_sound(play_id: u64, duration: Duration) {
    platform::with_audio(|a| a.fade_in_play_id(play_id, duration));
}

pub fn fade_out_sound(play_id: u64, duration: Duration) {
    platform::with_audio(|a| a.fade_out_play_id(play_id, duration));
}

pub fn set_sound_volume(play_id: u64, volume: f32) {
    platform::with_audio(|a| a.set_volume_play_id(play_id, volume));
}

pub fn is_sound_playing(play_id: u64) -> bool {
    platform::with_audio(|a| a.is_playing_play_id(play_id)).unwrap_or(false)
}

pub fn unregister_sound(sound_id: u32) {
    platform::with_audio(|a| a.unregister_sound(sound_id));
}

pub fn play_sine(freq: f32, volume: f32) -> Option<u64> {
    platform::with_audio(|a| a.play_sine(freq, volume)).flatten()
}

type SceneFactory = Box<dyn Fn(&mut Context) -> Box<dyn Spot> + Send + Sync>;

pub(crate) struct ScenePayload {
    pub(crate) type_id: TypeId,
    pub(crate) value: Rc<dyn Any>,
}

pub(crate) struct ScenePayloadTypeId(pub(crate) TypeId);

pub(crate) struct SceneSwitchRequest {
    pub(crate) factory: SceneFactory,
    pub(crate) payload: Option<ScenePayload>,
}

use std::cell::RefCell;

thread_local! {
    static SCENE_SWITCH_REQUEST: RefCell<Option<SceneSwitchRequest>> = const { RefCell::new(None) };
    static QUIT_REQUEST: RefCell<bool> = const { RefCell::new(false) };
}

pub fn with_graphics<R>(f: impl FnOnce(&mut Graphics) -> R) -> Option<R> {
    platform::with_graphics(f)
}

fn request_scene_switch<F>(factory: F)
where
    F: Fn(&mut Context) -> Box<dyn Spot> + Send + Sync + 'static,
{
    SCENE_SWITCH_REQUEST.with(|request| {
        *request.borrow_mut() = Some(SceneSwitchRequest {
            factory: Box::new(factory),
            payload: None,
        });
    });
}

fn request_scene_switch_with<F>(factory: F, payload: ScenePayload)
where
    F: Fn(&mut Context) -> Box<dyn Spot> + Send + Sync + 'static,
{
    SCENE_SWITCH_REQUEST.with(|request| {
        *request.borrow_mut() = Some(SceneSwitchRequest {
            factory: Box::new(factory),
            payload: Some(payload),
        });
    });
}

pub(crate) fn take_scene_switch_request() -> Option<SceneSwitchRequest> {
    SCENE_SWITCH_REQUEST.with(|request| request.borrow_mut().take())
}

pub fn quit() {
    QUIT_REQUEST.with(|request| *request.borrow_mut() = true);
}

pub(crate) fn take_quit_request() -> bool {
    QUIT_REQUEST.with(|request| request.replace(false))
}

/// Runs the application with the specified Spot type.
///
/// This is the main entry point for Spot applications. It creates a window,
/// initializes the graphics system, runs the event loop, and initializes your application.
///
/// # Type Parameters
/// * `T` - Your application type that implements the `Spot` trait
///
/// # Example
/// ```no_run
/// # use spottedcat::{Context, Spot};
/// # struct MyApp;
/// # impl Spot for MyApp {
/// #     fn initialize(_: &mut Context) -> Self { MyApp }
/// #     fn draw(&mut self, _: &mut Context) {}
/// #     fn update(&mut self, _: &mut Context, _dt: std::time::Duration) {}
/// #     fn remove(&self) {}
/// # }
/// spottedcat::run::<MyApp>(spottedcat::WindowConfig::default());
/// ```
#[cfg(not(target_os = "android"))]
pub fn run<T: Spot + 'static>(window: WindowConfig) {
    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
    {
        console_error_panic_hook::set_once();
    }

    let event_loop = EventLoop::new().expect("failed to create winit EventLoop");
    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
    let mut app = window::App::new_wasm::<T>(window.clone(), window.canvas_id.clone());
    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
    let mut app = window::App::new::<T>(window);
    event_loop.run_app(&mut app).expect("event loop error");
}

#[cfg(target_os = "android")]
pub fn run<T: Spot + 'static>(
    window: WindowConfig,
    app: AndroidApp,
) {
    let mut app_impl = window::App::new::<T>(window);
    app_impl.run(app);
}

/// Switches to a new scene of the specified type.
///
/// This function requests a scene change that will take effect at the end of the current frame.
/// The old scene's `remove()` method will be called automatically, and the new scene will be
/// initialized with a fresh context.
///
/// # Type Parameters
/// * `T` - The new scene type to switch to
///
/// # Example
/// ```no_run
/// # use spottedcat::{Context, Spot, switch_scene};
/// # struct MenuScene;
/// # struct GameScene;
/// # impl Spot for MenuScene {
/// #     fn initialize(_: &mut Context) -> Self { MenuScene }
/// #     fn draw(&mut self, _: &mut Context) {}
/// #     fn update(&mut self, _: &mut Context, _dt: std::time::Duration) {}
/// #     fn remove(&self) {}
/// # }
/// # impl Spot for GameScene {
/// #     fn initialize(_: &mut Context) -> Self { GameScene }
/// #     fn draw(&mut self, _: &mut Context) {}
/// #     fn update(&mut self, _: &mut Context, _dt: std::time::Duration) {}
/// #     fn remove(&self) {}
/// # }
/// // In your scene's draw or update method:
/// // if some_condition {
/// //     switch_scene::<GameScene>();
/// // }
/// ```
pub fn switch_scene<T: Spot + 'static>() {
    request_scene_switch(|ctx| Box::new(T::initialize(ctx)));
}

/// Switches to a new scene and provides a payload for the next scene to read.
///
/// The payload can be retrieved in the new scene via `Context::take_resource::<T>()`.
pub fn switch_scene_with<T: Spot + 'static, P: Any>(payload: P) {
    request_scene_switch_with(
        |ctx| Box::new(T::initialize(ctx)),
        ScenePayload {
            type_id: TypeId::of::<P>(),
            value: Rc::new(payload),
        },
    );
}

/// Main application trait that must be implemented by your application.
///
/// This trait defines the lifecycle of a Spot application.
pub trait Spot {
    /// Initializes the application.
    ///
    /// Called once when the application starts. Use this to load resources
    /// and set up initial state.
    ///
    /// # Arguments
    /// * `context` - Initial drawing context
    fn initialize(context: &mut Context) -> Self
    where
        Self: Sized;

    /// Draws the current frame.
    ///
    /// Called every frame. Use the context to issue drawing commands.
    ///
    /// # Arguments
    /// * `context` - Drawing context to add render commands to
    fn draw(&mut self, context: &mut Context);

    fn update(&mut self, context: &mut Context, dt: Duration);

    fn resumed(&mut self, _context: &mut Context) {}

    fn suspended(&mut self, _context: &mut Context) {}

    /// Cleanup when the application is shutting down.
    fn remove(&self);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_image_culling_flip() {
        let mut context = Context::new();
        context.set_window_logical_size(Pt::from(800.0), Pt::from(600.0));

        let img_id = 1u32;
        let img_size = [Pt::from(100.0), Pt::from(100.0)];

        // 1. Normal visible
        let opts = DrawOption::default().with_position([Pt::from(100.0), Pt::from(100.0)]);
        context.push(DrawCommand::Image(
            img_id,
            opts,
            0,
            ShaderOpts::default(),
            img_size,
        ));
        assert_eq!(context.draw_list.len(), 1, "Normal image should be visible");
        context.draw_list.clear();

        // 2. Flip H, should be visible at (100, 100) (covers 0 to 100)
        let opts = DrawOption::default()
            .with_position([Pt::from(100.0), Pt::from(100.0)])
            .with_scale([-1.0, 1.0]);
        context.push(DrawCommand::Image(
            img_id,
            opts,
            0,
            ShaderOpts::default(),
            img_size,
        ));
        assert_eq!(
            context.draw_list.len(),
            1,
            "Flipped H image at 100 should be visible (covers 0-100)"
        );
        context.draw_list.clear();

        // 3. Flip H, culled at (0, 100) (covers -100 to 0)
        let opts = DrawOption::default()
            .with_position([Pt::from(-0.1), Pt::from(100.0)])
            .with_scale([-1.0, 1.0]);
        context.push(DrawCommand::Image(
            img_id,
            opts,
            0,
            ShaderOpts::default(),
            img_size,
        ));
        assert_eq!(
            context.draw_list.len(),
            0,
            "Flipped H image at -0.1 should be culled (covers -100 to -0.1)"
        );
        context.draw_list.clear();

        // 4. Flip V, should be visible at (100, 100) (covers 0 to 100 in Y)
        let opts = DrawOption::default()
            .with_position([Pt::from(100.0), Pt::from(100.0)])
            .with_scale([1.0, -1.0]);
        context.push(DrawCommand::Image(
            img_id,
            opts,
            0,
            ShaderOpts::default(),
            img_size,
        ));
        assert_eq!(
            context.draw_list.len(),
            1,
            "Flipped V image at 100 should be visible (covers 0-100 in Y)"
        );
        context.draw_list.clear();

        // 5. Flip Both, visible at (100, 100)
        let opts = DrawOption::default()
            .with_position([Pt::from(100.0), Pt::from(100.0)])
            .with_scale([-1.0, -1.0]);
        context.push(DrawCommand::Image(
            img_id,
            opts,
            0,
            ShaderOpts::default(),
            img_size,
        ));
        assert_eq!(
            context.draw_list.len(),
            1,
            "Both-flipped image at 100,100 should be visible"
        );
        context.draw_list.clear();
    }
}