Skip to main content

ssplayer_wgpu/
surface.rs

1//! The swapchain the two faces that own their surface keep alike: the C face's
2//! [`crate::host::NativeHost`] and each canvas of the web face.
3//!
4//! Configuring it, resizing it together with its stencil buffer, acquiring a
5//! frame and drawing a scene into it are the same steps on both, and a fix
6//! that reached one of two copies and not the other is what this module stops.
7//! What does differ is passed in: the alpha mode, the clear colour, and whether
8//! a zero size is ignored, which each face decides before calling
9//! [`Swapchain::resize`].
10
11use crate::renderer::SSRenderer;
12use crate::scene::SSScene;
13
14/// Depth/stencil format allocated when masking is enabled; the depth aspect is
15/// unused. Matches the native viewer.
16pub const STENCIL_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24PlusStencil8;
17
18/// `width` x `height`, brought inside what `device` can configure a surface or a
19/// stencil buffer at: at least 1, at most `max_texture_dimension_2d`.
20///
21/// A window or canvas past the limit then draws at the largest size the device
22/// has, stretched by the compositor; configuring it at its own size is a
23/// validation error and a panic.
24pub(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
29/// A surface, its configuration, and the stencil buffer sized with it.
30pub(crate) struct Swapchain {
31    surface: wgpu::Surface<'static>,
32    config: wgpu::SurfaceConfiguration,
33    /// `None` when built without masking.
34    stencil_view: Option<wgpu::TextureView>,
35    /// The alpha mode to configure with, or `None` for the first the surface
36    /// reports — kept so a restore picks it the same way.
37    alpha_mode: Option<wgpu::CompositeAlphaMode>,
38}
39
40impl Swapchain {
41    /// Configure `surface` for `device` at `width` x `height`, brought inside
42    /// what the device can hold, with a stencil buffer when `stencil` is set.
43    /// `None` when `adapter` cannot present to it at all.
44    ///
45    /// A non-sRGB format is preferred: the atlases are sRGB-encoded bytes
46    /// sampled as UNORM and the pipeline composites premultiplied as authored,
47    /// so an sRGB target would encode them a second time.
48    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    /// The surface itself, for the native host to ask for an adapter that can
70    /// present to it; the web face asks for one before it has a canvas.
71    #[cfg(feature = "ffi")]
72    pub fn surface(&self) -> &wgpu::Surface<'static> {
73        &self.surface
74    }
75
76    /// The colour format the scene drawing into this must be built for.
77    pub fn format(&self) -> wgpu::TextureFormat {
78        self.config.format
79    }
80
81    /// The configured size in pixels — or, while the device is lost, the size
82    /// the next [`Swapchain::restore`] configures.
83    pub fn size(&self) -> (u32, u32) {
84        (self.config.width, self.config.height)
85    }
86
87    /// Take a new drawable size, brought inside what `device` can hold. While
88    /// the device is `lost` the size is only recorded, and
89    /// [`Swapchain::restore`] applies it.
90    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    /// Whether `adapter` can present the format this was configured with. The
98    /// scene's pipelines are baked against that format, so one that cannot is
99    /// a rebuild, not a restore.
100    pub fn presents_on(&self, adapter: &wgpu::Adapter) -> bool {
101        self.surface.get_capabilities(adapter).formats.contains(&self.config.format)
102    }
103
104    /// Configure again on the device that replaced a lost one, at the size last
105    /// recorded. Ask [`Swapchain::presents_on`] first.
106    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    /// Acquire this frame's texture, draw `scene` into it over `clear`, and
119    /// present it. What the scene draws offscreen goes first, on the same
120    /// encoder.
121    ///
122    /// A lost, outdated or timed-out surface is configured again and the frame
123    /// skipped; an occluded one, which is still valid, skips the frame alone.
124    /// Both are success, since the next frame draws. Only a configuration the
125    /// surface rejects is an error.
126    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            // The size has not changed, so the stencil buffer still fits.
133            _ => {
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}