Skip to main content

pebble/wgpu/
backend.rs

1use crate::{
2    app::App,
3    ecs::plugin::Plugin,
4    rendering::{
5        backend::{Backend, ColorTarget, FrameOperations, Pass},
6        errors::AcquireError,
7        sync::InitSender,
8        window::{GPUSurfaceHandle, WindowConfig},
9    },
10    wgpu::window::WinitWindow,
11};
12
13pub struct WGPUBackend {
14    pub device: wgpu::Device,
15    pub queue: wgpu::Queue,
16    pub surface: wgpu::Surface<'static>,
17    pub config: wgpu::SurfaceConfiguration,
18}
19
20pub struct WGPUFrame {
21    encoder: wgpu::CommandEncoder,
22    view: wgpu::TextureView,
23    surface_texture: wgpu::SurfaceTexture,
24}
25
26impl FrameOperations for WGPUFrame {
27    type Context<'a> = wgpu::RenderPass<'a>;
28    type Attachment = wgpu::TextureView;
29    type DepthAttachment = wgpu::TextureView;
30
31    fn begin(&mut self, pass: Pass<'_, Self>) -> Self::Context<'_> {
32        let color_attachments: Vec<_> = pass
33            .colors
34            .iter()
35            .map(|target| {
36                let (view, clear) = match target {
37                    ColorTarget::Default { clear } => (&self.view, clear),
38                    ColorTarget::Custom { attachment, clear } => (*attachment, clear),
39                };
40                Some(wgpu::RenderPassColorAttachment {
41                    view,
42                    depth_slice: None,
43                    resolve_target: None,
44                    ops: wgpu::Operations {
45                        load: clear
46                            .map(|[r, g, b, a]| {
47                                wgpu::LoadOp::Clear(wgpu::Color {
48                                    r: r as f64,
49                                    g: g as f64,
50                                    b: b as f64,
51                                    a: a as f64,
52                                })
53                            })
54                            .unwrap_or(wgpu::LoadOp::Load),
55                        store: wgpu::StoreOp::Store,
56                    },
57                })
58            })
59            .collect();
60
61        let depth_stencil_attachment =
62            pass.depth
63                .as_ref()
64                .map(|d| wgpu::RenderPassDepthStencilAttachment {
65                    view: d.attachment,
66                    depth_ops: Some(wgpu::Operations {
67                        load: d
68                            .clear
69                            .map(wgpu::LoadOp::Clear)
70                            .unwrap_or(wgpu::LoadOp::Load),
71                        store: wgpu::StoreOp::Store,
72                    }),
73                    stencil_ops: None,
74                });
75
76        self.encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
77            label: None,
78            color_attachments: &color_attachments,
79            depth_stencil_attachment,
80            timestamp_writes: None,
81            occlusion_query_set: None,
82            multiview_mask: None,
83        })
84    }
85}
86
87impl Backend for WGPUBackend {
88    type Frame = WGPUFrame;
89
90    fn init(handle: impl GPUSurfaceHandle, width: u32, height: u32, sender: InitSender<Self>) {
91        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
92            display: None,
93            backends: wgpu::Backends::default(),
94            flags: wgpu::InstanceFlags::default(),
95            memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
96            backend_options: wgpu::BackendOptions::default(),
97        });
98
99        let surface = instance.create_surface(handle).unwrap();
100
101        let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
102            power_preference: wgpu::PowerPreference::HighPerformance,
103            force_fallback_adapter: false,
104            compatible_surface: Some(&surface),
105        }))
106        .unwrap();
107
108        let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
109            label: None,
110            required_features: wgpu::Features::default(),
111            required_limits: wgpu::Limits::default(),
112            ..Default::default()
113        }))
114        .unwrap();
115
116        let caps = surface.get_capabilities(&adapter);
117        let config = wgpu::SurfaceConfiguration {
118            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
119            format: caps.formats[0],
120            present_mode: caps.present_modes[0],
121            alpha_mode: caps.alpha_modes[0],
122            width,
123            height,
124            desired_maximum_frame_latency: 2,
125            view_formats: vec![],
126        };
127        surface.configure(&device, &config);
128
129        sender.send(WGPUBackend {
130            device,
131            queue,
132            surface,
133            config,
134        });
135    }
136
137    fn resize(&mut self, width: u32, height: u32) {
138        if width == 0 || height == 0 {
139            return; // minimized — don't reconfigure to a degenerate size
140        }
141        self.config.width = width;
142        self.config.height = height;
143        self.surface.configure(&self.device, &self.config);
144    }
145
146    fn acquire(&mut self) -> Result<Self::Frame, AcquireError> {
147        let surface_texture = match self.surface.get_current_texture() {
148            wgpu::CurrentSurfaceTexture::Success(texture) => texture,
149            wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
150            wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Outdated => {
151                return Err(AcquireError::Transient);
152            }
153            other => {
154                return Err(AcquireError::Fatal(format!(
155                    "unexpected surface state: {other:?}"
156                )));
157            }
158        };
159
160        let view = surface_texture
161            .texture
162            .create_view(&wgpu::TextureViewDescriptor::default());
163        let encoder = self
164            .device
165            .create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
166
167        Ok(WGPUFrame {
168            encoder,
169            view,
170            surface_texture,
171        })
172    }
173
174    fn present(&mut self, frame: Self::Frame) {
175        self.queue.submit(std::iter::once(frame.encoder.finish()));
176        frame.surface_texture.present();
177    }
178}
179
180pub struct WGPUPlugin {
181    config: WindowConfig,
182}
183
184impl WGPUPlugin {
185    pub fn new(config: WindowConfig) -> Self {
186        Self { config }
187    }
188}
189
190impl Plugin for WGPUPlugin {
191    fn build(&self, app: &mut App) {
192        app.add_plugin(crate::prelude::WindowPlugin::<WinitWindow>::new(
193            WindowConfig {
194                title: self.config.title,
195                width: self.config.width,
196                height: self.config.height,
197            },
198        ))
199        .add_plugin(crate::prelude::GraphicsPlugin::<WGPUBackend, WinitWindow>::new())
200        .add_plugin(crate::prelude::RenderPlugin::<WGPUBackend>::new())
201        .add_plugin(crate::wgpu::textures::TexturePlugin)
202        .add_plugin(crate::wgpu::texture_array::TextureArrayPlugin)
203        .add_plugin(crate::wgpu::cubemap::CubemapPlugin)
204        .add_plugin(crate::wgpu::mesh::MeshPlugin::new())
205        .add_plugin(crate::wgpu::material::MaterialPlugin::new())
206        .add_plugin(crate::wgpu::material_instance::MaterialInstancePlugin::new())
207        .add_plugin(crate::prelude::LazyResourcePlugin::<
208            WGPUBackend,
209            crate::wgpu::samplers::GlobalSamplers,
210        >::new());
211    }
212}