Skip to main content

game_toolkit_core/
context.rs

1use std::sync::Arc;
2
3use anyhow::Result;
4use winit::event_loop::ActiveEventLoop;
5use winit::window::Window;
6
7use crate::time::Time;
8
9pub enum GameEvent {
10    Resized { width: u32, height: u32 },
11    FocusChanged(bool),
12    CloseRequested,
13}
14
15pub struct Context {
16    pub gfx: game_toolkit_gfx::Graphics,
17    pub audio: Option<game_toolkit_audio::Audio>,
18    pub input: game_toolkit_input::Input,
19    pub assets: game_toolkit_assets::Assets,
20    pub time: Time,
21    pub window: Arc<Window>,
22    pub(crate) quit_requested: bool,
23}
24
25impl Context {
26    #[allow(clippy::too_many_arguments)]
27    pub(crate) fn new(
28        event_loop: &ActiveEventLoop,
29        title: &str,
30        width: u32,
31        height: u32,
32        vsync: bool,
33        asset_root: std::path::PathBuf,
34        depth_format: Option<wgpu::TextureFormat>,
35        msaa_samples: u32,
36    ) -> Result<Self> {
37        let attrs = Window::default_attributes()
38            .with_title(title)
39            .with_inner_size(winit::dpi::LogicalSize::new(width, height));
40        let window = Arc::new(event_loop.create_window(attrs)?);
41        let gfx = pollster::block_on(game_toolkit_gfx::Graphics::new(
42            window.clone(),
43            vsync,
44            depth_format,
45            msaa_samples,
46        ))?;
47        let audio = match game_toolkit_audio::Audio::new() {
48            Ok(a) => Some(a),
49            Err(e) => {
50                log::warn!("audio init failed, continuing muted: {e}");
51                None
52            }
53        };
54        let input = game_toolkit_input::Input::new();
55        let assets = game_toolkit_assets::Assets::new(&asset_root).unwrap_or_else(|e| {
56            log::warn!(
57                "asset root {} unusable ({e}); falling back to cwd",
58                asset_root.display()
59            );
60            game_toolkit_assets::Assets::new(".").expect("cwd should resolve")
61        });
62        Ok(Self {
63            gfx,
64            audio,
65            input,
66            assets,
67            time: Time::new(),
68            window,
69            quit_requested: false,
70        })
71    }
72
73    pub fn quit(&mut self) {
74        self.quit_requested = true;
75    }
76}