use anyhow::{Result, anyhow};
use futures;
use std::sync::Arc;
use winit::event::{Event, WindowEvent};
use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::{Window as WinitWindow, WindowBuilder};
use wgpu::Instance;
pub struct Window {
window: Arc<WinitWindow>,
surface: wgpu::Surface<'static>,
device: wgpu::Device,
queue: wgpu::Queue,
config: Option<wgpu::SurfaceConfiguration>,
surface_format: wgpu::TextureFormat,
surface_caps: wgpu::SurfaceCapabilities,
}
pub struct Application {
event_loop: Option<EventLoop<()>>,
windows: Vec<Window>,
}
impl Application {
pub fn new() -> Result<Self> {
Ok(Self {
event_loop: Some(EventLoop::new()?),
windows: Vec::new(),
})
}
pub fn create_window(&mut self, title: &str, width: u32, height: u32) -> Result<()> {
if let Some(event_loop) = self.event_loop.as_ref() {
let window = WindowBuilder::new()
.with_title(title)
.with_inner_size(winit::dpi::LogicalSize::new(width, height))
.build(event_loop)?;
let window_arc = Arc::new(window);
let instance = Instance::default();
let surface = unsafe {
let static_ref: &Arc<WinitWindow> = &window_arc;
let static_ref_ptr = static_ref as *const Arc<WinitWindow>;
&*static_ref_ptr
};
let surface = instance.create_surface(surface)?;
let adapter = futures::executor::block_on(instance.request_adapter(
&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::default(),
compatible_surface: Some(&surface),
force_fallback_adapter: false,
},
)).ok_or_else(|| anyhow::anyhow!("Failed to find an appropriate adapter"))?;
let (device, queue) = futures::executor::block_on(adapter.request_device(
&wgpu::DeviceDescriptor {
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::default(),
label: Some("Device"),
},
None,
))?;
let surface_caps = surface.get_capabilities(&adapter);
let surface_format = surface_caps.formats.iter()
.copied()
.find(|f| f.is_srgb())
.unwrap_or(surface_caps.formats[0]);
self.windows.push(Window {
window: window_arc,
surface,
device,
queue,
config: None,
surface_format,
surface_caps,
});
}
Ok(())
}
pub fn run(mut self) -> Result<()> {
let event_loop = self.event_loop.take().expect("Event loop already taken");
event_loop.run(move |event, target| {
target.set_control_flow(ControlFlow::Wait);
match event {
Event::WindowEvent { event, window_id } => {
match event {
WindowEvent::CloseRequested => {
target.set_control_flow(ControlFlow::WaitUntil(std::time::Instant::now()));
},
WindowEvent::Resized(new_size) => {
for window in &mut self.windows {
if window.window.id() == window_id {
if new_size.width > 0 && new_size.height > 0 {
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: window.surface_format,
width: new_size.width,
height: new_size.height,
present_mode: window.surface_caps.present_modes[0],
alpha_mode: window.surface_caps.alpha_modes[0],
view_formats: vec![],
desired_maximum_frame_latency: 2,
};
window.surface.configure(&window.device, &config);
window.config = Some(config);
window.window.request_redraw();
}
}
}
},
WindowEvent::RedrawRequested => {
for window in &mut self.windows {
if window.window.id() == window_id {
if let Err(err) = window.render() {
eprintln!("Error during rendering: {:?}", err);
}
}
}
},
_ => {},
}
},
Event::AboutToWait => {
for window in &self.windows {
window.window.request_redraw();
}
},
_ => {},
} }).map_err(|e| anyhow!("Event loop error: {:?}", e))
}
}
impl Window {
pub fn render(&mut self) -> Result<()> {
if self.config.is_none() {
let window_size = self.window.inner_size();
if window_size.width > 0 && window_size.height > 0 {
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: self.surface_format,
width: window_size.width,
height: window_size.height,
present_mode: self.surface_caps.present_modes[0],
alpha_mode: self.surface_caps.alpha_modes[0],
view_formats: vec![],
desired_maximum_frame_latency: 2,
};
self.surface.configure(&self.device, &config);
self.config = Some(config);
} else {
return Ok(());
}
}
let output = match self.surface.get_current_texture() {
Ok(output) => output,
Err(wgpu::SurfaceError::Outdated) | Err(wgpu::SurfaceError::Lost) => {
if let Some(config) = &self.config {
self.surface.configure(&self.device, config);
}
return Ok(());
},
Err(err) => return Err(err.into()),
};
let view = output.texture.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
});
{
let render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Render Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 0.1,
g: 0.2,
b: 0.3,
a: 1.0,
}),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
});
drop(render_pass);
}
self.queue.submit(std::iter::once(encoder.finish()));
output.present();
Ok(())
}
}