1use mln_gfx::frame::{FrameImage, FrameTarget, Handoff};
6use mln_gfx::gpu::{Gpu as _, ReadbackId, ResourceId, TargetFormats, TextureId, TextureRegion, destroy_unused};
7use mln_util::error::Error;
8use mln_util::image::PremultipliedImage;
9use mln_util::logging::{Event, Log};
10use mln_util::size::Size;
11
12use crate::device::Device;
13use crate::gpu::{WebGpu, from_wgpu_format};
14use crate::renderer_backend::RendererBackend;
15
16const ALPHA_MODE: wgpu::CompositeAlphaMode =
21 if cfg!(target_family = "wasm") { wgpu::CompositeAlphaMode::PreMultiplied } else { wgpu::CompositeAlphaMode::Auto };
22
23pub struct OverlayTarget<'a> {
26 pub device: &'a wgpu::Device,
27 pub queue: &'a wgpu::Queue,
28 pub view: &'a wgpu::TextureView,
29 pub format: wgpu::TextureFormat,
30 pub size: Size,
32}
33
34pub type Overlay = Box<dyn FnMut(&OverlayTarget<'_>)>;
37
38#[derive(Clone, Copy, Debug)]
40pub struct SurfaceOptions {
41 pub cap_frame_rate: bool,
44 pub usages: Option<wgpu::TextureUsages>,
49 pub format: Option<wgpu::TextureFormat>,
52}
53
54impl Default for SurfaceOptions {
55 fn default() -> Self {
56 SurfaceOptions { cap_frame_rate: true, usages: None, format: None }
57 }
58}
59
60pub struct SurfaceTarget {
67 state: Box<State>,
68}
69
70struct State {
71 current: Option<wgpu::SurfaceTexture>,
73 depth_stencil: Option<wgpu::Texture>,
75 overlay: Option<Overlay>,
76 surface: wgpu::Surface<'static>,
77
78 format: wgpu::TextureFormat,
79 usage: wgpu::TextureUsages,
80 present_mode: wgpu::PresentMode,
81 depth_stencil_format: wgpu::TextureFormat,
82 size: Size,
84 configured: Option<Size>,
87
88 color_import: Option<TextureId>,
92 depth_import: Option<TextureId>,
93
94 readback_requested: bool,
95 pending_readback: Option<(ReadbackId, Size)>,
98 readback: Option<PremultipliedImage>,
99 device: Device,
100}
101
102impl SurfaceTarget {
103 pub fn new(
116 backend: &RendererBackend,
117 surface: wgpu::Surface<'static>,
118 framebuffer_size: Size,
119 options: SurfaceOptions,
120 ) -> Result<SurfaceTarget, Error> {
121 let device = backend.device();
122 let (format, mut usage, vsync_present_mode) = if let Some(adapter) = device.adapter() {
123 let capabilities = surface.get_capabilities(adapter);
124 if capabilities.formats.is_empty() {
125 return Err(Error::unsupported("The WebGPU adapter can't present to the surface"));
126 }
127 let format = match options.format.or(device.surface_format()) {
128 Some(format) if capabilities.formats.contains(&format) => format,
129 Some(format) => {
130 return Err(Error::unsupported(format!("The surface does not take the {format:?} format")));
131 }
132 None => {
133 const RENDERED: [wgpu::TextureFormat; 4] = [
134 wgpu::TextureFormat::Bgra8Unorm,
135 wgpu::TextureFormat::Bgra8UnormSrgb,
136 wgpu::TextureFormat::Rgba8Unorm,
137 wgpu::TextureFormat::Rgba8UnormSrgb,
138 ];
139 let format = if cfg!(target_family = "wasm") {
143 capabilities.formats.iter().copied().find(|f| RENDERED.contains(f))
144 } else {
145 RENDERED.into_iter().find(|f| capabilities.formats.contains(f))
146 };
147 format
148 .ok_or_else(|| Error::unsupported("The surface takes none of the formats the map renders in"))?
149 }
150 };
151 let usage = wgpu::TextureUsages::RENDER_ATTACHMENT | (capabilities.usages & wgpu::TextureUsages::COPY_SRC);
152 let present_mode = if capabilities.present_modes.contains(&wgpu::PresentMode::Mailbox) {
156 wgpu::PresentMode::Mailbox
157 } else {
158 wgpu::PresentMode::Fifo
159 };
160 (format, usage, present_mode)
161 } else {
162 let format = options.format.or(device.surface_format()).ok_or_else(|| {
163 Error::invalid_argument("A surface on a device without an adapter needs the device's surface format")
164 })?;
165 (format, wgpu::TextureUsages::RENDER_ATTACHMENT, wgpu::PresentMode::Fifo)
166 };
167 if let Some(usages) = options.usages {
168 usage = wgpu::TextureUsages::RENDER_ATTACHMENT | (usages & wgpu::TextureUsages::COPY_SRC);
169 }
170 let depth_stencil_format = if device.device().features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
171 wgpu::TextureFormat::Depth32FloatStencil8
172 } else {
173 wgpu::TextureFormat::Depth24PlusStencil8
174 };
175
176 Ok(SurfaceTarget {
177 state: Box::new(State {
178 current: None,
179 depth_stencil: None,
180 overlay: None,
181 surface,
182 format,
183 usage,
184 present_mode: if options.cap_frame_rate { vsync_present_mode } else { wgpu::PresentMode::Immediate },
185 depth_stencil_format,
186 size: framebuffer_size,
187 configured: None,
188 color_import: None,
189 depth_import: None,
190 readback_requested: false,
191 pending_readback: None,
192 readback: None,
193 device: device.clone(),
194 }),
195 })
196 }
197
198 #[must_use]
200 pub fn format(&self) -> wgpu::TextureFormat {
201 self.state.format
202 }
203
204 #[must_use]
206 pub fn size(&self) -> Size {
207 self.state.size
208 }
209
210 pub fn request_readback(&mut self) {
212 self.state.readback_requested = true;
213 }
214
215 #[must_use]
219 pub fn take_readback(&mut self, gpu: &mut WebGpu) -> Option<PremultipliedImage> {
220 self.state.finish_readback(gpu, false);
221 self.state.readback.take()
222 }
223
224 pub fn set_overlay(&mut self, overlay: Option<Overlay>) {
227 self.state.overlay = overlay;
228 }
229}
230
231impl State {
232 fn acquire(&mut self) -> Option<Size> {
236 let size_of = |texture: &wgpu::SurfaceTexture| Size::new(texture.texture.width(), texture.texture.height());
237 if let Some(current) = &self.current {
238 return Some(size_of(current));
239 }
240 let size = self.size;
241 if self.configured != Some(size) && size.width != 0 && size.height != 0 {
244 self.surface.configure(
245 self.device.device(),
246 &wgpu::SurfaceConfiguration {
247 usage: self.usage,
248 format: self.format,
249 width: size.width,
250 height: size.height,
251 present_mode: self.present_mode,
252 desired_maximum_frame_latency: 2,
253 alpha_mode: ALPHA_MODE,
254 view_formats: vec![self.format],
255 color_space: wgpu::SurfaceColorSpace::Auto,
256 },
257 );
258 self.configured = Some(size);
259 }
260 self.configured?;
261 let texture = match self.surface.get_current_texture() {
262 wgpu::CurrentSurfaceTexture::Success(texture) | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
263 wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
264 self.configured = None;
265 return None;
266 }
267 wgpu::CurrentSurfaceTexture::Timeout
268 | wgpu::CurrentSurfaceTexture::Occluded
269 | wgpu::CurrentSurfaceTexture::Validation => return None,
270 };
271 Some(size_of(self.current.insert(texture)))
272 }
273
274 fn depth_stencil_import(&mut self, gpu: &mut WebGpu, size: Size) -> TextureId {
276 let texture = match self.depth_stencil.take() {
277 Some(texture) if (texture.width(), texture.height()) == (size.width, size.height) => texture,
278 _ => {
279 if let Some(import) = self.depth_import.take() {
280 destroy_unused(gpu, [ResourceId::Texture(import)]);
281 }
282 self.device.device().create_texture(&wgpu::TextureDescriptor {
283 label: Some("surface depth and stencil"),
284 size: wgpu::Extent3d { width: size.width, height: size.height, depth_or_array_layers: 1 },
285 mip_level_count: 1,
286 sample_count: 1,
287 dimension: wgpu::TextureDimension::D2,
288 format: self.depth_stencil_format,
289 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
290 view_formats: &[],
291 })
292 }
293 };
294 let import = *self.depth_import.get_or_insert_with(|| gpu.import_texture(&texture));
295 self.depth_stencil = Some(texture);
296 import
297 }
298
299 fn read_back(&mut self, gpu: &mut WebGpu, texture: &wgpu::Texture) {
301 if !self.usage.contains(wgpu::TextureUsages::COPY_SRC) {
302 Log::warning(Event::Render, "WebGPU: the surface does not support readback (no COPY_SRC)");
303 return;
304 }
305 let size = Size::new(texture.width(), texture.height());
306 let imported = gpu.import_texture(texture);
307 let readback = gpu.read_texture(imported, TextureRegion::whole(size));
308 destroy_unused(gpu, [ResourceId::Texture(imported)]);
309 match readback {
310 Ok(readback) => {
311 if let Some((stale, _)) = self.pending_readback.replace((readback, size)) {
312 destroy_unused(gpu, [ResourceId::Readback(stale)]);
313 }
314 }
315 Err(error) => Log::error(Event::Render, format!("WebGPU: reading the frame back failed: {error}")),
316 }
317 }
318
319 fn finish_readback(&mut self, gpu: &mut WebGpu, wait: bool) {
322 let Some((readback, size)) = self.pending_readback.take() else {
323 return;
324 };
325 let mut texels = match gpu.take_readback(readback, wait) {
326 Ok(Some(texels)) => texels,
327 Ok(None) => {
328 self.pending_readback = Some((readback, size));
329 return;
330 }
331 Err(error) => {
332 return Log::error(Event::Render, format!("WebGPU: reading the frame back failed: {error}"));
333 }
334 };
335 if matches!(self.format, wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb) {
336 for texel in texels.as_chunks_mut::<4>().0 {
337 texel.swap(0, 2);
338 }
339 }
340 self.readback = Some(PremultipliedImage::from_vec(size, texels));
341 }
342}
343
344impl FrameTarget for SurfaceTarget {
345 type Gpu = WebGpu;
346
347 fn resize(&mut self, _gpu: &mut WebGpu, size: Size) {
349 self.state.size = size;
350 }
351
352 fn begin_frame(&mut self, gpu: &mut WebGpu) -> Option<FrameImage> {
355 self.state.begin_frame(gpu)
356 }
357
358 fn end_frame(&mut self, gpu: &mut WebGpu) -> Handoff {
361 self.state.end_frame(gpu)
362 }
363
364 fn tear_down(&mut self, gpu: &mut WebGpu) {
365 let state = &mut *self.state;
366 if let Some((readback, _)) = state.pending_readback.take() {
367 destroy_unused(gpu, [ResourceId::Readback(readback)]);
368 }
369 let imports = [state.color_import.take(), state.depth_import.take()].into_iter().flatten();
370 destroy_unused(gpu, imports.map(ResourceId::Texture));
371 }
372}
373
374impl State {
375 fn begin_frame(&mut self, gpu: &mut WebGpu) -> Option<FrameImage> {
376 let size = self.acquire()?;
377 let depth_stencil = self.depth_stencil_import(gpu, size);
378 let current = self.current.as_ref()?;
379 let color = *self.color_import.get_or_insert_with(|| gpu.import_texture(¤t.texture));
380 let targets = TargetFormats {
381 color: from_wgpu_format(self.format),
382 depth_stencil: from_wgpu_format(self.depth_stencil_format),
383 };
384 Some(FrameImage { size, color, depth_stencil: Some(depth_stencil), targets })
385 }
386
387 fn end_frame(&mut self, gpu: &mut WebGpu) -> Handoff {
388 if let Some(color) = self.color_import.take() {
389 destroy_unused(gpu, [ResourceId::Texture(color)]);
390 }
391 let Some(current) = self.current.take() else {
392 return Handoff::Dropped;
393 };
394 if let Some(overlay) = self.overlay.as_mut() {
395 let view = current.texture.create_view(&wgpu::TextureViewDescriptor::default());
396 overlay(&OverlayTarget {
397 device: self.device.device(),
398 queue: self.device.queue(),
399 view: &view,
400 format: self.format,
401 size: Size::new(current.texture.width(), current.texture.height()),
402 });
403 }
404 if std::mem::take(&mut self.readback_requested) {
405 self.read_back(gpu, ¤t.texture);
406 self.finish_readback(gpu, true);
409 }
410 self.device.queue().present(current);
411 Handoff::Presented
412 }
413}
414
415impl Drop for State {
416 fn drop(&mut self) {
417 drop(self.current.take());
419 drop(self.depth_stencil.take());
420 drop(self.overlay.take());
421 let _ = self.device.device().poll(wgpu::PollType::Poll);
423 }
424}