1use crate::renderer::SSRenderer;
12use crate::scene::SSScene;
13
14pub const STENCIL_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24PlusStencil8;
17
18pub(crate) fn surface_extent(device: &wgpu::Device, width: u32, height: u32) -> (u32, u32) {
25 let max = device.limits().max_texture_dimension_2d;
26 (width.clamp(1, max), height.clamp(1, max))
27}
28
29pub(crate) struct Swapchain {
31 surface: wgpu::Surface<'static>,
32 config: wgpu::SurfaceConfiguration,
33 stencil_view: Option<wgpu::TextureView>,
35 alpha_mode: Option<wgpu::CompositeAlphaMode>,
38}
39
40impl Swapchain {
41 pub fn new(device: &wgpu::Device, adapter: &wgpu::Adapter, surface: wgpu::Surface<'static>, (width, height): (u32, u32), alpha_mode: Option<wgpu::CompositeAlphaMode>, stencil: bool) -> Option<Self> {
49 let caps = surface.get_capabilities(adapter);
50 let &first = caps.formats.first()?;
51 let format = caps.formats.iter().copied().find(|f| !f.is_srgb()).unwrap_or(first);
52 let (width, height) = surface_extent(device, width, height);
53 let config = wgpu::SurfaceConfiguration {
54 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
55 format,
56 color_space: wgpu::SurfaceColorSpace::Auto,
57 width,
58 height,
59 present_mode: wgpu::PresentMode::Fifo,
60 alpha_mode: alpha_mode.unwrap_or(caps.alpha_modes[0]),
61 view_formats: vec![],
62 desired_maximum_frame_latency: 2,
63 };
64 surface.configure(device, &config);
65 let stencil_view = stencil.then(|| create_stencil_view(device, width, height));
66 Some(Self { surface, config, stencil_view, alpha_mode })
67 }
68
69 #[cfg(feature = "ffi")]
72 pub fn surface(&self) -> &wgpu::Surface<'static> {
73 &self.surface
74 }
75
76 pub fn format(&self) -> wgpu::TextureFormat {
78 self.config.format
79 }
80
81 pub fn size(&self) -> (u32, u32) {
84 (self.config.width, self.config.height)
85 }
86
87 pub fn resize(&mut self, device: &wgpu::Device, width: u32, height: u32, lost: bool) {
91 (self.config.width, self.config.height) = surface_extent(device, width, height);
92 if !lost {
93 self.configure(device);
94 }
95 }
96
97 pub fn presents_on(&self, adapter: &wgpu::Adapter) -> bool {
101 self.surface.get_capabilities(adapter).formats.contains(&self.config.format)
102 }
103
104 pub fn restore(&mut self, device: &wgpu::Device, adapter: &wgpu::Adapter) {
107 self.config.alpha_mode = self.alpha_mode.unwrap_or_else(|| self.surface.get_capabilities(adapter).alpha_modes[0]);
108 self.configure(device);
109 }
110
111 fn configure(&mut self, device: &wgpu::Device) {
112 self.surface.configure(device, &self.config);
113 if self.stencil_view.is_some() {
114 self.stencil_view = Some(create_stencil_view(device, self.config.width, self.config.height));
115 }
116 }
117
118 pub fn render(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, renderer: &mut SSRenderer, scene: &mut SSScene, clear: wgpu::Color, label: &'static str) -> Result<(), &'static str> {
127 use wgpu::CurrentSurfaceTexture;
128 let frame = match self.surface.get_current_texture() {
129 CurrentSurfaceTexture::Success(frame) | CurrentSurfaceTexture::Suboptimal(frame) => frame,
130 CurrentSurfaceTexture::Occluded => return Ok(()),
131 CurrentSurfaceTexture::Validation => return Err("surface configuration is invalid"),
132 _ => {
134 self.surface.configure(device, &self.config);
135 return Ok(());
136 }
137 };
138 let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default());
139 let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some(label) });
140 scene.encode_offscreen(renderer, device, &mut encoder);
141 {
142 let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
143 label: Some(label),
144 color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(clear), store: wgpu::StoreOp::Store }, depth_slice: None })],
145 depth_stencil_attachment: self.stencil_view.as_ref().map(|stencil| wgpu::RenderPassDepthStencilAttachment {
146 view: stencil,
147 depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Store }),
148 stencil_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0), store: wgpu::StoreOp::Store }),
149 }),
150 timestamp_writes: scene.timestamp_writes(),
151 occlusion_query_set: None,
152 multiview_mask: None,
153 });
154 scene.draw(renderer, &mut pass);
155 }
156 scene.resolve_timestamps(&mut encoder);
157 queue.submit(std::iter::once(encoder.finish()));
158 queue.present(frame);
159 Ok(())
160 }
161}
162
163fn create_stencil_view(device: &wgpu::Device, width: u32, height: u32) -> wgpu::TextureView {
164 let texture = device.create_texture(&wgpu::TextureDescriptor {
165 label: Some("SpriteStudio Stencil"),
166 size: wgpu::Extent3d { width: width.max(1), height: height.max(1), depth_or_array_layers: 1 },
167 mip_level_count: 1,
168 sample_count: 1,
169 dimension: wgpu::TextureDimension::D2,
170 format: STENCIL_FORMAT,
171 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
172 view_formats: &[],
173 });
174 texture.create_view(&wgpu::TextureViewDescriptor::default())
175}