Skip to main content

pebble/rendering/
graphics_plugin.rs

1use crate::prelude::{
2    Backend, Commands, GPUSurfaceHandle, Plugin, PresentableWindow, Res, ResMut, SystemStage,
3    WindowResource,
4};
5
6pub struct GraphicsPlugin<B, W> {
7    _marker: std::marker::PhantomData<(B, W)>,
8}
9
10impl<B: Backend, W: PresentableWindow> GraphicsPlugin<B, W>
11where
12    W::Handle: GPUSurfaceHandle,
13{
14    pub fn new() -> Self {
15        Self {
16            _marker: std::marker::PhantomData,
17        }
18    }
19}
20
21impl<B: Backend, W: PresentableWindow> Plugin for GraphicsPlugin<B, W>
22where
23    W::Handle: GPUSurfaceHandle,
24{
25    fn build(&self, app: &mut crate::prelude::App) {
26        app.add_system(SystemStage::Startup, setup_gpu::<B, W>)
27            .add_resource(LastWindowSize(0, 0))
28            .add_system(SystemStage::PreRender, handle_resize::<B, W>);
29    }
30}
31
32fn setup_gpu<B: Backend, W: PresentableWindow>(
33    mut commands: Commands,
34    window: Res<WindowResource<W>>,
35) where
36    W::Handle: GPUSurfaceHandle,
37{
38    let (w, h) = W::size(&window.handle);
39
40    tracing::info!("Initializing Graphics Backend");
41    let backend = B::init(window.handle.clone(), w, h);
42    commands.insert_resource(backend);
43}
44
45struct LastWindowSize(u32, u32);
46
47fn handle_resize<B: Backend, W: PresentableWindow>(
48    mut backend: Option<ResMut<B>>,
49    mut last_size: ResMut<LastWindowSize>,
50    window: Res<WindowResource<W>>,
51) where
52    W::Handle: GPUSurfaceHandle,
53{
54    if let Some(backend) = &mut backend {
55        let (w, h) = W::size(&window.handle);
56        if (w, h) != (last_size.0, last_size.1) && w > 0 && h > 0 {
57            backend.resize(w, h);
58            *last_size = LastWindowSize(w, h);
59
60            tracing::info!("Window Resized");
61        }
62    } else {
63        tracing::warn!("Attempted Window Resized, Backend Resource Missing?");
64    }
65}