Skip to main content

mln_runtime/render/
target.rs

1//! What a render session renders into, and how it attaches.
2
3// The matches over the backends' enums list a variant per backend that the
4// build's features and target have, so whether their `_` arm is unreachable,
5// or matches a single variant, and whether a `let` of one variant is
6// irrefutable, depends on the build.
7#![allow(
8    unreachable_patterns,
9    irrefutable_let_patterns,
10    clippy::match_wildcard_for_single_variants,
11    reason = "the backends' variants depend on the build's features and target"
12)]
13
14use std::sync::Arc;
15
16use mln_gfx::Window;
17pub use mln_gfx::backend::Type as BackendType;
18pub use mln_gfx::{
19    ConsumerSync, DepthStencilFormat, DepthStencilFormats, DmaBufFormat, DmaBufPlane, ExportKind, ExportKinds,
20    ExportedImage, ExportedRing, FrameDepth, GpuSync, NativeTexture, SyncKind, SyncKinds,
21};
22use mln_style::error::Error;
23use mln_style::size::Size;
24
25#[cfg(any(has_metal, has_vulkan, has_d3d12, feature = "webgpu", feature = "gl"))]
26use super::backends;
27
28/// A callback that tells the host about something it should act on, such as
29/// frame results to drain. It runs on a library thread and must not block.
30pub type Wake = Arc<dyn Fn() + Send + Sync>;
31
32/// The thread that runs a render session's graphics work.
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
34pub enum Driver {
35    /// A thread of the session's own.
36    #[default]
37    CoreWorker,
38    /// The host's graphics thread, which runs the work through the session's
39    /// [`DriverWork`](crate::DriverWork).
40    CallerThread,
41}
42
43/// How a session attaches to its map.
44#[derive(Clone, Default)]
45pub struct AttachOptions {
46    pub driver: Driver,
47    /// Runs when frame results wait for
48    /// [`drain_frame_results`](crate::RenderSession::drain_frame_results),
49    /// and not again until a drain takes them.
50    pub frame_wake: Option<Wake>,
51    /// Runs when the map has something new to draw, and not again until the
52    /// host demands a frame, or while the session has no target. A session
53    /// without one can have a frame pacer demand its frames instead
54    /// ([`RenderSession::set_frame_pacer`](crate::RenderSession::set_frame_pacer)).
55    pub redraw_wake: Option<Wake>,
56    /// Runs when a [`Driver::CallerThread`] session has work for
57    /// [`DriverWork::service`](crate::DriverWork::service), and not again
58    /// until a service starts.
59    pub driver_work_wake: Option<Wake>,
60    /// The kinds of sync that the host can wait for before it reads a
61    /// borrowed ring's frame. The session picks the one of them that its
62    /// target supports and that waits least: see [`SyncKinds::pick`].
63    pub producer_sync_kinds: SyncKinds,
64}
65
66impl std::fmt::Debug for AttachOptions {
67    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        f.debug_struct("AttachOptions")
69            .field("driver", &self.driver)
70            .field("frame_wake", &self.frame_wake.is_some())
71            .field("redraw_wake", &self.redraw_wake.is_some())
72            .field("driver_work_wake", &self.driver_work_wake.is_some())
73            .field("producer_sync_kinds", &self.producer_sync_kinds)
74            .finish()
75    }
76}
77
78/// What a render session renders into. The session builds it into the
79/// backend's objects on the thread that renders, on `device`, or on a device
80/// that [`Device::new`] makes when that is `None`. The device's backend is
81/// the session's.
82#[derive(Debug)]
83pub enum RenderTarget {
84    /// An image of `size` logical pixels, rendered at the map's pixel ratio,
85    /// whose pixels [`read_texture`](crate::RenderSession::read_texture)
86    /// reads.
87    Offscreen { size: Size, device: Option<Device> },
88    /// A surface of `size` logical pixels, rendered at the map's pixel ratio,
89    /// that shows each frame that the session renders. Without a device, a
90    /// window renders on the platform's native backend where that takes
91    /// windows, and on WebGPU otherwise (on Apple's platforms, whose Metal
92    /// takes a layer); a Metal layer renders on Metal.
93    ///
94    /// A frame finishes as
95    /// [`TargetNotReady`](crate::FrameDisposition::TargetNotReady) while the
96    /// surface can't show it: while a window is minimized or has no client
97    /// area, or the surface has an empty extent or gives no image for it.
98    ///
99    /// [`release_target`](crate::RenderSession::release_target) lets go of
100    /// the surface, and [`set_surface`](crate::RenderSession::set_surface)
101    /// gives the session another one.
102    Surface { size: Size, surface: Surface, device: Option<Device> },
103    /// A ring of the host's textures of `size` logical pixels, on `device`,
104    /// whose backend is the ring's. Each frame goes to the host, which
105    /// takes it with [`acquire_frame`](crate::RenderSession::acquire_frame)
106    /// and gives it back once it has read it. The ring's textures set the
107    /// size in pixels, and [`set_ring`](crate::RenderSession::set_ring)
108    /// gives the session new ones.
109    Borrowed { size: Size, ring: BorrowedRing, device: Device },
110    /// A ring of images of `size` logical pixels, rendered at the map's
111    /// pixel ratio, that the session allocates on `device` and shares with
112    /// the host in a kind of `ring.kinds`: the first, by
113    /// [`ExportKind::BY_PREFERENCE`], that the device exports. Without a
114    /// device, the session renders on the first of [`Device::new`]'s
115    /// backends whose device exports one. Each frame goes to the host, which
116    /// takes it with [`acquire_frame`](crate::RenderSession::acquire_frame)
117    /// and gives it back once it has read it.
118    /// [`resize`](crate::RenderSession::resize) gives the ring images of a
119    /// new size, and the frames that the host holds keep theirs.
120    Exported { size: Size, ring: ExportedRing, device: Option<Device> },
121}
122
123/// A ring of the host's textures, of one backend.
124#[derive(Clone, Debug, PartialEq)]
125pub struct BorrowedRing {
126    pub(crate) kind: RingKind,
127}
128
129#[derive(Clone, Debug, PartialEq)]
130pub(crate) enum RingKind {
131    #[cfg(has_vulkan)]
132    Vulkan(mln_vulkan::BorrowedImages),
133    #[cfg(has_metal)]
134    Metal(mln_mtl::BorrowedTextures),
135    #[cfg(feature = "gl")]
136    Gl(mln_gl::BorrowedTextures),
137    #[cfg(feature = "webgpu")]
138    WebGpu(mln_webgpu::BorrowedTextures),
139    #[cfg(has_d3d12)]
140    D3d12(mln_d3d12::BorrowedTextures),
141}
142
143/// The host's texture that an acquired frame was rendered into, of `size`
144/// pixels.
145#[derive(Clone, Debug, PartialEq, Eq)]
146pub struct FrameTexture {
147    pub size: mln_gfx::Size,
148    pub kind: FrameTextureKind,
149    /// An exported ring's image as the API of the session's device names it,
150    /// for a host on the device, or `None` for a borrowed ring's texture.
151    pub native: Option<FrameTextureKind>,
152    /// The texture that holds the frame's depth and stencil: a borrowed
153    /// ring's depth texture, or an exported ring's that keeps depth.
154    pub depth: Option<FrameDepth>,
155}
156
157impl FrameTexture {
158    /// The frame's texture as the API of the session's device names it: a
159    /// borrowed ring's, or an exported ring's on its device.
160    #[must_use]
161    pub fn native_kind(&self) -> Option<&FrameTextureKind> {
162        match &self.kind {
163            FrameTextureKind::Exported(_) => self.native.as_ref(),
164            kind => Some(kind),
165        }
166    }
167
168    /// An exported ring's frame, of the session's `device`.
169    pub(crate) fn exported(frame: mln_gfx::ExportedFrame, device: &Device) -> FrameTexture {
170        FrameTexture {
171            size: frame.size,
172            kind: FrameTextureKind::Exported(frame.image),
173            native: native_kind(frame.texture, device),
174            depth: frame.depth,
175        }
176    }
177}
178
179/// `texture`, which `device` drew into, with the device.
180fn native_kind(texture: NativeTexture, device: &Device) -> Option<FrameTextureKind> {
181    match (texture, device) {
182        #[cfg(has_vulkan)]
183        (NativeTexture::Vulkan { image, view, format, layout }, Device::Vulkan(device)) => {
184            Some(backends::vulkan::native_texture(image, view, format, layout, device))
185        }
186        #[cfg(has_metal)]
187        (NativeTexture::Metal { texture, pixel_format }, Device::Metal(device)) => {
188            Some(backends::metal::native_texture(texture, pixel_format, device))
189        }
190        (NativeTexture::OpenGl { texture, target, .. }, _) => Some(FrameTextureKind::OpenGl { texture, target }),
191        #[cfg(has_d3d12)]
192        (NativeTexture::D3d12 { resource, format, state }, Device::D3d12(device)) => {
193            Some(backends::d3d12::native_texture(resource, format, state, device))
194        }
195        _ => None,
196    }
197}
198
199/// A [`FrameTexture`]'s backend objects.
200#[derive(Clone, Debug, PartialEq, Eq)]
201#[non_exhaustive]
202pub enum FrameTextureKind {
203    /// A `VkImage` and its `VkImageView` of a `VkDevice`, in a `VkFormat`,
204    /// left in a `VkImageLayout`.
205    Vulkan { image: u64, view: u64, device: u64, format: i32, layout: i32 },
206    /// An `id<MTLTexture>` of an `id<MTLDevice>`, in an `MTLPixelFormat`.
207    Metal { texture: u64, device: u64, pixel_format: u64 },
208    /// An OpenGL texture name, of a texture target.
209    OpenGl { texture: u32, target: u32 },
210    /// A WebGL2 `WebGLTexture`, of a texture target, with an optional depth
211    /// and stencil texture.
212    #[cfg(has_webgl)]
213    WebGl { texture: mln_gl::WebTexture, target: u32, depth: Option<mln_gl::WebTexture> },
214    /// A WebGPU texture: the host's at the frame's slot of its ring.
215    WebGpu,
216    /// An `ID3D12Resource*` of an `ID3D12Device*`, in a `DXGI_FORMAT`, left
217    /// in a `D3D12_RESOURCE_STATES`.
218    D3d12 { resource: u64, device: u64, format: u32, state: u32 },
219    /// An image of an exported ring, and its shared memory.
220    Exported(ExportedImage),
221}
222
223impl BorrowedRing {
224    /// The backend whose device renders into the ring.
225    #[must_use]
226    pub fn backend(&self) -> BackendType {
227        match self.kind {
228            #[cfg(has_vulkan)]
229            RingKind::Vulkan(_) => BackendType::Vulkan,
230            #[cfg(has_metal)]
231            RingKind::Metal(_) => BackendType::Metal,
232            #[cfg(feature = "gl")]
233            RingKind::Gl(_) => BackendType::OpenGL,
234            #[cfg(feature = "webgpu")]
235            RingKind::WebGpu(_) => BackendType::WebGPU,
236            #[cfg(has_d3d12)]
237            RingKind::D3d12(_) => BackendType::D3D12,
238            // A build without a backend renders into no ring.
239            _ => BackendType::WebGPU,
240        }
241    }
242
243    /// How many textures the ring has.
244    #[must_use]
245    pub fn depth(&self) -> usize {
246        match &self.kind {
247            #[cfg(has_vulkan)]
248            RingKind::Vulkan(images) => images.images.len(),
249            #[cfg(has_metal)]
250            RingKind::Metal(textures) => textures.textures.len(),
251            #[cfg(feature = "gl")]
252            RingKind::Gl(textures) => textures.textures.len(),
253            #[cfg(feature = "webgpu")]
254            RingKind::WebGpu(textures) => textures.textures.len(),
255            #[cfg(has_d3d12)]
256            RingKind::D3d12(textures) => textures.textures.len(),
257            _ => 0,
258        }
259    }
260
261    /// The textures' size in pixels.
262    #[must_use]
263    pub fn physical_size(&self) -> mln_gfx::Size {
264        match &self.kind {
265            #[cfg(has_vulkan)]
266            RingKind::Vulkan(images) => images.size,
267            #[cfg(has_metal)]
268            RingKind::Metal(textures) => textures.size,
269            #[cfg(feature = "gl")]
270            RingKind::Gl(textures) => textures.size,
271            #[cfg(feature = "webgpu")]
272            RingKind::WebGpu(textures) => textures.size,
273            #[cfg(has_d3d12)]
274            RingKind::D3d12(textures) => textures.size,
275            _ => mln_gfx::Size::default(),
276        }
277    }
278
279    /// Whether `device` draws into the ring's depth textures: true for a ring
280    /// without them, or of OpenGL textures, whose names say no format, and
281    /// otherwise whether their format is one of the device's
282    /// [`depth_stencil_formats`](Device::depth_stencil_formats).
283    #[must_use]
284    pub fn takes_depth_on(&self, device: &Device) -> bool {
285        // Irrefutable in a build with OpenGL alone, and refutable in one
286        // with other backends.
287        #[cfg(feature = "gl")]
288        if let RingKind::Gl(_) = self.kind {
289            return true;
290        }
291        !self.has_depth()
292            || self.depth_stencil_format().is_some_and(|format| device.depth_stencil_formats().contains(format))
293    }
294
295    /// The format of the ring's depth textures, when it has them and their
296    /// format is a depth and stencil one that an API names.
297    #[must_use]
298    pub fn depth_stencil_format(&self) -> Option<DepthStencilFormat> {
299        match &self.kind {
300            #[cfg(has_vulkan)]
301            RingKind::Vulkan(images) => backends::vulkan::ring_depth_stencil_format(images),
302            #[cfg(has_metal)]
303            RingKind::Metal(textures) => backends::metal::ring_depth_stencil_format(textures),
304            #[cfg(feature = "webgpu")]
305            RingKind::WebGpu(textures) => backends::webgpu::ring_depth_stencil_format(textures),
306            #[cfg(has_d3d12)]
307            RingKind::D3d12(textures) => backends::d3d12::ring_depth_stencil_format(textures),
308            _ => None,
309        }
310    }
311
312    /// Whether the ring has depth textures.
313    #[must_use]
314    pub fn has_depth(&self) -> bool {
315        match &self.kind {
316            #[cfg(has_vulkan)]
317            RingKind::Vulkan(images) => images.depth.is_some(),
318            #[cfg(has_metal)]
319            RingKind::Metal(textures) => !textures.depth_textures.is_empty(),
320            #[cfg(feature = "gl")]
321            RingKind::Gl(textures) => !textures.depth_textures.is_empty(),
322            #[cfg(feature = "webgpu")]
323            RingKind::WebGpu(textures) => !textures.depth_textures.is_empty(),
324            #[cfg(has_d3d12)]
325            RingKind::D3d12(textures) => !textures.depth_textures.is_empty(),
326            _ => false,
327        }
328    }
329
330    /// Whether the texture at `slot` is the one at `other`'s `other_slot`.
331    pub(crate) fn same_texture(&self, slot: usize, other: &BorrowedRing, other_slot: usize) -> bool {
332        match (&self.kind, &other.kind) {
333            #[cfg(has_vulkan)]
334            (RingKind::Vulkan(images), RingKind::Vulkan(others)) => {
335                backends::vulkan::ring_same_texture(images, slot, others, other_slot)
336            }
337            #[cfg(has_metal)]
338            (RingKind::Metal(textures), RingKind::Metal(others)) => {
339                backends::metal::ring_same_texture(textures, slot, others, other_slot)
340            }
341            #[cfg(feature = "gl")]
342            (RingKind::Gl(textures), RingKind::Gl(others)) => {
343                backends::gl::ring_same_texture(textures, slot, others, other_slot)
344            }
345            #[cfg(feature = "webgpu")]
346            (RingKind::WebGpu(textures), RingKind::WebGpu(others)) => {
347                backends::webgpu::ring_same_texture(textures, slot, others, other_slot)
348            }
349            #[cfg(has_d3d12)]
350            (RingKind::D3d12(textures), RingKind::D3d12(others)) => {
351                backends::d3d12::ring_same_texture(textures, slot, others, other_slot)
352            }
353            _ => false,
354        }
355    }
356
357    /// The texture at `slot`, which sessions on `device` render into.
358    #[must_use]
359    pub fn texture(&self, slot: usize, device: &Device) -> Option<FrameTexture> {
360        match (&self.kind, device) {
361            #[cfg(has_vulkan)]
362            (RingKind::Vulkan(images), Device::Vulkan(device)) => backends::vulkan::ring_texture(images, slot, device),
363            #[cfg(has_metal)]
364            (RingKind::Metal(textures), Device::Metal(device)) => backends::metal::ring_texture(textures, slot, device),
365            #[cfg(has_native_gl)]
366            (RingKind::Gl(textures), Device::Gl(_)) => backends::gl::ring_texture_native(textures, slot),
367            #[cfg(has_webgl)]
368            (RingKind::Gl(textures), Device::WebGl(Some(_))) => backends::gl::ring_texture_webgl(textures, slot),
369            #[cfg(feature = "webgpu")]
370            (RingKind::WebGpu(textures), Device::WebGpu(_)) => backends::webgpu::ring_texture(textures, slot),
371            #[cfg(has_d3d12)]
372            (RingKind::D3d12(textures), Device::D3d12(device)) => backends::d3d12::ring_texture(textures, slot, device),
373            _ => None,
374        }
375    }
376}
377
378/// What a surface session presents to.
379///
380/// In the browser, a canvas's surface stays on the instance's thread, as
381/// its canvas does.
382pub struct Surface {
383    pub(crate) kind: SurfaceKind,
384    /// Whether presenting waits for the display: see
385    /// [`without_frame_rate_cap`](Self::without_frame_rate_cap).
386    pub(crate) cap_frame_rate: bool,
387}
388
389/// What a host draws over each frame that a surface session presents, after
390/// the map and before the frame is presented (and read back): the overlay
391/// of the backend that the session presents with
392/// ([`DriverWork::set_overlay`](crate::DriverWork::set_overlay)).
393pub enum SurfaceOverlay {
394    #[cfg(feature = "webgpu")]
395    WebGpu(mln_webgpu::Overlay),
396    #[cfg(has_metal)]
397    Metal(mln_mtl::surface_target::Overlay),
398    #[cfg(has_vulkan)]
399    Vulkan(Box<dyn mln_vulkan::Overlay>),
400    #[cfg(has_d3d12)]
401    D3d12(Box<dyn mln_d3d12::Overlay>),
402    #[cfg(has_gl_window)]
403    Gl(mln_gl::Overlay),
404}
405
406pub(crate) enum SurfaceKind {
407    Window(Arc<dyn Window>),
408    #[cfg(has_metal)]
409    MetalLayer(mln_mtl::Layer),
410    #[cfg(has_native_webgpu)]
411    Wgpu(wgpu::Surface<'static>),
412    /// The host's `VkSurfaceKHR`, of the instance of the session's device.
413    #[cfg(has_vulkan)]
414    Vulkan(mln_vulkan::HostSurface),
415    /// The host's `EGLSurface`, of the display of the session's device.
416    #[cfg(has_native_gl)]
417    Gl(mln_gl::HostSurface),
418    /// What shows a D3D12 composition swap chain: a `DirectComposition`
419    /// visual or a XAML `SwapChainPanel`, and the thread that made the
420    /// surface, which a `SwapChainPanel` takes its swap chain on.
421    #[cfg(has_d3d12)]
422    D3d12Composition {
423        composition: mln_d3d12::Composition,
424        thread: std::thread::ThreadId,
425    },
426    /// In the browser, an `OffscreenCanvas` or an `HTMLCanvasElement`, on
427    /// the instance's one thread.
428    #[cfg(target_family = "wasm")]
429    WebCanvas {
430        canvas: wasm_bindgen::JsValue,
431        format: Option<CanvasFormat>,
432    },
433}
434
435/// A `GPUTextureFormat` that a WebGPU canvas takes.
436#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
437pub enum CanvasFormat {
438    /// `bgra8unorm`.
439    Bgra8Unorm,
440    /// `rgba8unorm`.
441    Rgba8Unorm,
442    /// `rgba16float`.
443    Rgba16Float,
444}
445
446impl CanvasFormat {
447    /// The format by its `GPUTextureFormat` name, if a canvas takes it.
448    #[must_use]
449    pub fn from_name(name: &str) -> Option<CanvasFormat> {
450        match name {
451            "bgra8unorm" => Some(CanvasFormat::Bgra8Unorm),
452            "rgba8unorm" => Some(CanvasFormat::Rgba8Unorm),
453            "rgba16float" => Some(CanvasFormat::Rgba16Float),
454            _ => None,
455        }
456    }
457}
458
459impl Surface {
460    pub(super) fn of(kind: SurfaceKind) -> Surface {
461        Surface { kind, cap_frame_rate: true }
462    }
463
464    /// The surface, presenting frames as they finish instead of one per
465    /// refresh of the display, where the backend and the surface can: a
466    /// benchmark's way to measure frame times. Metal on macOS, Vulkan,
467    /// WebGPU outside the browser and OpenGL on a window take it; the
468    /// others keep the display's pace.
469    #[must_use]
470    pub fn without_frame_rate_cap(self) -> Surface {
471        Surface { cap_frame_rate: false, ..self }
472    }
473
474    /// A window, which the session makes its surface on. The window must
475    /// outlive the session's use of it: until a
476    /// [`set_surface`](crate::RenderSession::set_surface) or
477    /// [`release_target`](crate::RenderSession::release_target) replaces it,
478    /// or the session detaches or is abandoned.
479    ///
480    /// On Apple platforms, the session presents to a `CAMetalLayer` that it
481    /// puts in the window's view, which only the main thread may do: attach
482    /// the window with [`Driver::CallerThread`], serviced there, or make the
483    /// layer yourself and attach `Surface::metal_layer`.
484    pub fn window(window: impl Window + 'static) -> Surface {
485        Surface::of(SurfaceKind::Window(Arc::new(window)))
486    }
487
488    /// In the browser, a canvas that the session presents to with its
489    /// device's backend: an `OffscreenCanvas`, such as one that the page
490    /// transferred to the instance's Web Worker, or an `HTMLCanvasElement`
491    /// when the instance runs on the page's thread. The session makes the
492    /// canvas's "webgpu" or "webgl2" context, and sizes the canvas to the
493    /// target's size at the map's scale factor. Without a device, it renders
494    /// with the browser's WebGPU where the build has it, and with WebGL2
495    /// otherwise.
496    ///
497    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for
498    /// anything else.
499    ///
500    /// A WebGPU session configures the canvas with `format`, or else with a
501    /// format that its device's adapter prefers. Other backends ignore it.
502    ///
503    /// When the browser loses a WebGPU session's device, the session fails
504    /// with [`ErrorKind::TargetLost`](mln_style::error::ErrorKind), and once it is
505    /// released, a new session can attach to the canvas. After Chromium's GPU
506    /// process restarts, though, an `OffscreenCanvas` in a Web Worker shows no
507    /// new frames, and the worker gets no more animation frames: the page has
508    /// to load again.
509    #[cfg(target_family = "wasm")]
510    pub fn web_canvas(canvas: wasm_bindgen::JsValue, format: Option<CanvasFormat>) -> Result<Surface, Error> {
511        use wasm_bindgen::JsCast as _;
512        if !canvas.is_instance_of::<web_sys::OffscreenCanvas>()
513            && !canvas.is_instance_of::<web_sys::HtmlCanvasElement>()
514        {
515            return Err(Error::invalid_argument("a web canvas is an OffscreenCanvas or an HTMLCanvasElement"));
516        }
517        Ok(Surface::of(SurfaceKind::WebCanvas { canvas, format }))
518    }
519
520    /// The backend of the device whose instance or share group a host's
521    /// surface is of, or `None` for a window or layer.
522    #[must_use]
523    pub fn host_backend(&self) -> Option<BackendType> {
524        match self.kind {
525            #[cfg(has_vulkan)]
526            SurfaceKind::Vulkan(_) => Some(BackendType::Vulkan),
527            #[cfg(has_native_gl)]
528            SurfaceKind::Gl(_) => Some(BackendType::OpenGL),
529            _ => None,
530        }
531    }
532
533    /// The surface again, if it is a window, or a surface that a new
534    /// backend presents to.
535    pub(crate) fn clone_window(&self) -> Option<Surface> {
536        let kind = match &self.kind {
537            SurfaceKind::Window(window) => SurfaceKind::Window(Arc::clone(window)),
538            #[cfg(has_native_gl)]
539            SurfaceKind::Gl(surface) => SurfaceKind::Gl(*surface),
540            _ => return None,
541        };
542        Some(Surface { kind, cap_frame_rate: self.cap_frame_rate })
543    }
544
545    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a
546    /// window that has no area to present to: a minimized Win32 window, or
547    /// one whose client area is empty ([`mln_gfx::window::has_area`]).
548    pub(crate) fn check_area(&self) -> Result<(), Error> {
549        if let SurfaceKind::Window(window) = &self.kind
550            && !mln_gfx::window::has_area(&**window)
551        {
552            return Err(Error::invalid_state("the window is minimized or has no client area"));
553        }
554        Ok(())
555    }
556
557    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
558    /// Win32 window whose pixel format isn't the library's when OpenGL
559    /// presents to it: on `device`, or without a device, in a build whose
560    /// first backend is OpenGL. Windows doesn't let a pixel format change.
561    /// A session that falls back to OpenGL because Vulkan and D3D12 are
562    /// missing finds out as it starts.
563    #[cfg_attr(
564        not(all(feature = "gl", windows)),
565        expect(clippy::unnecessary_wraps, reason = "only OpenGL on Windows checks the window's pixel format")
566    )]
567    pub(crate) fn check_pixel_format(&self, device: Option<&Device>) -> Result<(), Error> {
568        #[cfg(all(feature = "gl", windows))]
569        if let SurfaceKind::Window(window) = &self.kind
570            && device.map_or(cfg!(not(any(has_vulkan, has_d3d12))), |device| device.backend() == BackendType::OpenGL)
571        {
572            backends::gl::check_window_pixel_format(&**window)?;
573        }
574        #[cfg(not(all(feature = "gl", windows)))]
575        let _ = (self, device);
576        Ok(())
577    }
578
579    /// The window, for a surface of one.
580    pub(crate) fn host_window(&self) -> Option<Arc<dyn Window>> {
581        match &self.kind {
582            SurfaceKind::Window(window) => Some(Arc::clone(window)),
583            _ => None,
584        }
585    }
586
587    /// Whether the session can make the surface without the host's device.
588    pub(crate) fn needs_no_device(&self) -> bool {
589        match self.kind {
590            SurfaceKind::Window(_) => true,
591            #[cfg(has_metal)]
592            SurfaceKind::MetalLayer(_) => true,
593            #[cfg(has_native_webgpu)]
594            SurfaceKind::Wgpu(_) => false,
595            #[cfg(has_vulkan)]
596            SurfaceKind::Vulkan(_) => false,
597            #[cfg(has_native_gl)]
598            SurfaceKind::Gl(_) => false,
599            #[cfg(has_d3d12)]
600            SurfaceKind::D3d12Composition { .. } => true,
601            #[cfg(target_family = "wasm")]
602            SurfaceKind::WebCanvas { .. } => true,
603        }
604    }
605}
606
607/// A surface on its way to the worker of a session, which takes it on the
608/// session's thread.
609///
610/// In the browser, a canvas waits on the instance's thread, in the
611/// session's side there (`crate::web`), and the surface carries its key.
612#[cfg(not(target_family = "wasm"))]
613pub(crate) struct SentSurface(Surface);
614
615/// A surface on its way to the worker of a session, which takes it on the
616/// session's thread.
617///
618/// In the browser, a canvas waits on the instance's thread, in the
619/// session's side there (`crate::web`), and the surface carries its key.
620#[cfg(target_family = "wasm")]
621pub(crate) enum SentSurface {
622    Window(Arc<dyn Window>),
623    WebCanvas { canvas: crate::web::HandedCanvas, format: Option<CanvasFormat> },
624}
625
626impl SentSurface {
627    /// `surface`, on its way to the worker of session `session`.
628    pub(crate) fn new(surface: Surface, session: super::SessionId) -> SentSurface {
629        #[cfg(not(target_family = "wasm"))]
630        {
631            let _ = session;
632            SentSurface(surface)
633        }
634        #[cfg(target_family = "wasm")]
635        match surface.kind {
636            SurfaceKind::Window(window) => SentSurface::Window(window),
637            SurfaceKind::WebCanvas { canvas, format } => {
638                SentSurface::WebCanvas { canvas: crate::web::hand_canvas(session, canvas), format }
639            }
640        }
641    }
642
643    /// The surface, on the session's thread. In the browser, fails with
644    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when its canvas no
645    /// longer waits there.
646    #[cfg_attr(
647        not(target_family = "wasm"),
648        expect(clippy::unnecessary_wraps, reason = "only the browser's canvases wait for their session's thread")
649    )]
650    pub(crate) fn receive(self) -> Result<Surface, Error> {
651        #[cfg(not(target_family = "wasm"))]
652        {
653            Ok(self.0)
654        }
655        #[cfg(target_family = "wasm")]
656        match self {
657            SentSurface::Window(window) => Ok(Surface::of(SurfaceKind::Window(window))),
658            SentSurface::WebCanvas { canvas, format } => {
659                let canvas = canvas.take().ok_or_else(|| Error::invalid_state("the surface's canvas is gone"))?;
660                Ok(Surface::of(SurfaceKind::WebCanvas { canvas, format }))
661            }
662        }
663    }
664
665    /// In the browser, whether a session without a device presents to the
666    /// surface with WebGPU.
667    #[cfg(target_family = "wasm")]
668    pub(crate) fn presents_with_web_gpu(&self) -> bool {
669        matches!(self, SentSurface::WebCanvas { .. }) && cfg!(feature = "webgpu")
670    }
671}
672
673impl std::fmt::Debug for Surface {
674    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
675        f.debug_struct("Surface").finish_non_exhaustive()
676    }
677}
678
679/// A GPU that sessions on many maps and threads share: one backend's
680/// device. Sessions on it keep working after the last handle drops, until
681/// they detach.
682#[derive(Clone, Debug)]
683#[non_exhaustive]
684pub enum Device {
685    /// A WebGPU device: the library's, through wgpu, or the host's
686    /// (`Device::webgpu`). In the browser, the browser's
687    /// (`Device::request_web_gpu`).
688    #[cfg(feature = "webgpu")]
689    WebGpu(mln_webgpu::Device),
690    /// A Metal device and command queue.
691    #[cfg(has_metal)]
692    Metal(mln_mtl::Device),
693    /// A Vulkan GPU.
694    #[cfg(has_vulkan)]
695    Vulkan(mln_vulkan::Device),
696    /// A D3D12 device and its direct queue.
697    #[cfg(has_d3d12)]
698    D3d12(mln_d3d12::Device),
699    /// An OpenGL share group, or the one context that its sessions take
700    /// turns in.
701    #[cfg(has_native_gl)]
702    Gl(mln_gl::Device),
703    /// In the browser, WebGL2: each session renders with the context of its
704    /// canvas, or with the host's wrapped `WebGL2RenderingContext`
705    /// ([`Device::web_gl`]).
706    #[cfg(has_webgl)]
707    WebGl(Option<mln_gl::WebGlDevice>),
708}
709
710/// How to create a [`Device`].
711#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
712pub struct DeviceOptions {
713    /// The GPU to use. `None` picks the default one.
714    pub adapter: Option<Adapter>,
715    /// The API that an OpenGL device renders with. Only Linux's and
716    /// FreeBSD's EGL renders desktop OpenGL, and Windows' WGL renders it
717    /// only. Other backends ignore it.
718    pub gl_api: GlApi,
719    /// Whether the sessions of an OpenGL device take turns in one context
720    /// instead of having one each. Other backends ignore it.
721    pub gl_single_context: bool,
722}
723
724/// The OpenGL API that an OpenGL device renders with. By default the
725/// platform's: desktop OpenGL on Windows, and OpenGL ES elsewhere.
726#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
727pub enum GlApi {
728    /// OpenGL ES 3.0 or later.
729    Gles,
730    /// Desktop OpenGL 3.3 or later.
731    Gl,
732}
733
734impl Default for GlApi {
735    fn default() -> GlApi {
736        if cfg!(windows) { GlApi::Gl } else { GlApi::Gles }
737    }
738}
739
740/// A GPU, by what names it to a backend.
741#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
742pub enum Adapter {
743    /// An index into the backend's list of GPUs.
744    Index(usize),
745    /// The GPU's 16-byte UUID, as Vulkan's
746    /// `VkPhysicalDeviceIDProperties.deviceUUID` reports it.
747    Uuid([u8; 16]),
748    /// The GPU's 8-byte LUID, as Vulkan's
749    /// `VkPhysicalDeviceIDProperties.deviceLUID` reports it: on Windows, its
750    /// DXGI adapter's.
751    Luid([u8; 8]),
752}
753
754/// A kind of window or layer that a session presents to.
755#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
756#[non_exhaustive]
757pub enum SurfaceType {
758    /// A `CAMetalLayer`.
759    MetalLayer,
760    /// A Win32 window.
761    Win32,
762    /// An X11 window, through Xlib.
763    Xlib,
764    /// An X11 window, through XCB.
765    Xcb,
766    /// A Wayland surface.
767    Wayland,
768    /// An Android `ANativeWindow`.
769    AndroidNdk,
770    /// An `OpenHarmony` `OHNativeWindow`.
771    OhosNdk,
772}
773
774impl SurfaceType {
775    /// Whether a device of `backend` presents to the surfaces of this type
776    /// on this platform, in this build.
777    #[must_use]
778    pub fn presents_with(self, backend: BackendType) -> bool {
779        let windowing = match self {
780            SurfaceType::MetalLayer => false,
781            SurfaceType::Win32 => cfg!(windows),
782            SurfaceType::Xlib | SurfaceType::Xcb | SurfaceType::Wayland => {
783                cfg!(all(unix, not(target_vendor = "apple"), not(target_os = "android"), not(target_env = "ohos")))
784            }
785            SurfaceType::AndroidNdk => cfg!(target_os = "android"),
786            SurfaceType::OhosNdk => cfg!(target_env = "ohos"),
787        };
788        match backend {
789            BackendType::Metal => cfg!(has_metal) && self == SurfaceType::MetalLayer,
790            BackendType::Vulkan => cfg!(has_vulkan) && windowing,
791            // EGL presents to these windows, and on Windows WGL to Win32
792            // windows.
793            BackendType::OpenGL => {
794                cfg!(has_gl_window)
795                    && windowing
796                    && matches!(
797                        self,
798                        SurfaceType::Win32
799                            | SurfaceType::Xlib
800                            | SurfaceType::Wayland
801                            | SurfaceType::AndroidNdk
802                            | SurfaceType::OhosNdk
803                    )
804            }
805            // wgpu's Vulkan backend makes no OpenHarmony surface, and this
806            // build has no wgpu GLES backend.
807            BackendType::WebGPU => cfg!(has_native_webgpu) && windowing && self != SurfaceType::OhosNdk,
808            BackendType::D3D12 => cfg!(has_d3d12) && self == SurfaceType::Win32,
809        }
810    }
811
812    /// Whether a device of any backend of this build presents to the
813    /// surfaces of this type.
814    #[must_use]
815    pub fn presents_with_any(self) -> bool {
816        [BackendType::Metal, BackendType::Vulkan, BackendType::D3D12, BackendType::OpenGL, BackendType::WebGPU]
817            .into_iter()
818            .any(|backend| self.presents_with(backend))
819    }
820
821    /// Whether a session of this build presents to the surfaces of this
822    /// type without the host's device: on the device that a surface session
823    /// makes when it gets none.
824    #[must_use]
825    pub fn presents_without_device(self) -> bool {
826        match self {
827            SurfaceType::MetalLayer => self.presents_with(BackendType::Metal),
828            _ => [BackendType::Vulkan, BackendType::D3D12, BackendType::OpenGL, BackendType::WebGPU]
829                .into_iter()
830                .any(|backend| self.presents_with(backend)),
831        }
832    }
833}
834
835/// Whether a backend that failed with `error` is missing, so the next one
836/// may take its place.
837#[cfg(not(target_family = "wasm"))]
838fn missing(error: &Error) -> bool {
839    error.kind == mln_style::error::ErrorKind::Unsupported
840}
841
842/// A session's hold on what its [`Device`] shares with the host: a Vulkan
843/// device's hold on the host's queue lock. [`DeviceLease::revoke`] ends it.
844#[derive(Debug, Default)]
845pub(crate) struct DeviceLease {
846    #[cfg(has_vulkan)]
847    queue: Option<mln_vulkan::QueueLease>,
848}
849
850impl DeviceLease {
851    /// Ends the hold: the leased device calls the host's queue lock no more,
852    /// and lets go of it.
853    #[cfg_attr(
854        not(has_vulkan),
855        expect(clippy::unused_self, reason = "only a Vulkan device holds the host's queue lock")
856    )]
857    pub(crate) fn revoke(&self) {
858        #[cfg(has_vulkan)]
859        if let Some(queue) = &self.queue {
860            queue.revoke();
861        }
862    }
863}
864
865impl Device {
866    /// The device for one session, and the session's lease on it, which
867    /// ends the session's hold on what the device shares with the host when
868    /// the session lets go of the device without dropping it: an abandon
869    /// that keeps its graphics objects.
870    pub(crate) fn lease(self) -> (Device, DeviceLease) {
871        match self {
872            #[cfg(has_vulkan)]
873            Device::Vulkan(device) => {
874                let (device, queue) = device.lease();
875                (Device::Vulkan(device), DeviceLease { queue: Some(queue) })
876            }
877            device => (device, DeviceLease::default()),
878        }
879    }
880
881    /// Why the device was lost, once the library's WebGPU device is: the
882    /// failure of the sessions that render on it.
883    pub(crate) fn lost(&self) -> Option<Error> {
884        match *self {
885            #[cfg(feature = "webgpu")]
886            Device::WebGpu(ref device) => device.lost().map(|message| Error::target_lost(message.to_owned())),
887            _ => None,
888        }
889    }
890
891    /// Whether an abandon keeps a session's graphics objects on the device
892    /// until the process exits, which only a detach frees: OpenGL's and
893    /// WebGPU's, as the C API promises, since only the session's own thread
894    /// may destroy them, and the host's graphics objects behind them may be
895    /// going away.
896    pub(crate) fn abandon_keeps_graphics(&self) -> bool {
897        match *self {
898            #[cfg(feature = "webgpu")]
899            Device::WebGpu(_) => true,
900            #[cfg(has_metal)]
901            Device::Metal(_) => false,
902            #[cfg(has_vulkan)]
903            Device::Vulkan(_) => false,
904            #[cfg(has_d3d12)]
905            Device::D3d12(_) => false,
906            #[cfg(has_native_gl)]
907            Device::Gl(_) => true,
908            #[cfg(has_webgl)]
909            Device::WebGl(_) => true,
910        }
911    }
912
913    /// The library's device, on the platform's native backend: Metal on
914    /// Apple's platforms, and Vulkan elsewhere, then D3D12 on Windows, or
915    /// OpenGL where there is neither, and last WebGPU (wgpu) in a build with
916    /// the `webgpu` feature. A backend that can't name the GPU that
917    /// `options` names is skipped: only Vulkan names one by UUID, and only
918    /// Vulkan and D3D12 by LUID. OpenGL lists one GPU, the one its
919    /// display renders on, at index 0.
920    /// So is OpenGL where it can't render with `options.gl_api`.
921    ///
922    /// Fails with [`ErrorKind::NotFound`](mln_style::error::ErrorKind) when
923    /// the options name no GPU, with
924    /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when no backend has a
925    /// GPU or in the browser, where a session renders on the page's device,
926    /// and with [`ErrorKind::Failed`](mln_style::error::ErrorKind) when the GPU
927    /// can't create the device.
928    pub fn new(options: DeviceOptions) -> Result<Device, Error> {
929        #[cfg(target_family = "wasm")]
930        {
931            let _ = options;
932            Err(Error::unsupported("the browser has no library devices"))
933        }
934        #[cfg(not(target_family = "wasm"))]
935        {
936            let mut error = Error::unsupported("this build has no backend");
937            for backend in Self::native_order() {
938                match Self::with_backend(*backend, options) {
939                    Ok(device) => return Ok(device),
940                    Err(e) if missing(&e) => error = e,
941                    Err(e) => return Err(e),
942                }
943            }
944            Err(error)
945        }
946    }
947
948    /// The library's device on `backend`.
949    ///
950    /// Fails as [`new`](Self::new) does, and with
951    /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a backend that
952    /// isn't in this build or on this platform.
953    ///
954    /// In the browser, only OpenGL's: `Device::WebGl`. The browser makes
955    /// a WebGPU device asynchronously (`Device::request_web_gpu`).
956    pub fn with_backend(backend: BackendType, options: DeviceOptions) -> Result<Device, Error> {
957        match backend {
958            #[cfg(has_native_webgpu)]
959            BackendType::WebGPU => backends::webgpu::create_device(options.adapter),
960            #[cfg(has_metal)]
961            BackendType::Metal => backends::metal::create_device(options.adapter),
962            #[cfg(has_vulkan)]
963            BackendType::Vulkan => backends::vulkan::create_device(options.adapter),
964            #[cfg(has_d3d12)]
965            BackendType::D3D12 => backends::d3d12::create_device(options.adapter),
966            #[cfg(has_gl_device)]
967            BackendType::OpenGL => backends::gl::create_device(options),
968            #[cfg(has_webgl)]
969            BackendType::OpenGL if options.adapter.is_none() => Ok(Device::WebGl(None)),
970            _ => {
971                let _ = options;
972                Err(Error::unsupported(format!("this build has no {backend:?} backend")))
973            }
974        }
975    }
976
977    /// The kinds of sync with which the host can wait for a frame of `ring`
978    /// on the device (the producer's), and with which a session waits for
979    /// the host's reads (the consumer's).
980    ///
981    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when the
982    /// device can't render into the ring: one of another backend, or one the
983    /// device lacks a feature for.
984    pub fn borrowed_sync_kinds(&self, ring: &BorrowedRing) -> Result<(SyncKinds, SyncKinds), Error> {
985        match (self, &ring.kind) {
986            #[cfg(has_vulkan)]
987            (Device::Vulkan(device), RingKind::Vulkan(images)) => backends::vulkan::borrowed_sync_kinds(device, images),
988            #[cfg(has_metal)]
989            (Device::Metal(device), RingKind::Metal(textures)) => {
990                backends::metal::borrowed_sync_kinds(device, textures)
991            }
992            #[cfg(has_native_gl)]
993            (Device::Gl(device), RingKind::Gl(_)) => backends::gl::borrowed_sync_kinds_native(device),
994            #[cfg(has_webgl)]
995            (Device::WebGl(device), RingKind::Gl(_)) => backends::gl::borrowed_sync_kinds_webgl(device.as_ref()),
996            #[cfg(feature = "webgpu")]
997            (Device::WebGpu(_), RingKind::WebGpu(textures)) => backends::webgpu::borrowed_sync_kinds(textures),
998            #[cfg(has_d3d12)]
999            (Device::D3d12(device), RingKind::D3d12(textures)) => {
1000                backends::d3d12::borrowed_sync_kinds(device, textures)
1001            }
1002            _ => Err(Error::unsupported(format!(
1003                "a {:?} device renders into no ring of {:?} textures",
1004                self.backend(),
1005                ring.backend()
1006            ))),
1007        }
1008    }
1009
1010    /// The formats of the depth textures that a borrowed ring takes on the
1011    /// device.
1012    #[must_use]
1013    pub fn depth_stencil_formats(&self) -> DepthStencilFormats {
1014        match *self {
1015            #[cfg(has_vulkan)]
1016            Device::Vulkan(ref device) => device.depth_stencil_formats(),
1017            #[cfg(has_d3d12)]
1018            Device::D3d12(_) => mln_d3d12::BorrowedTextures::depth_stencil_formats(),
1019            #[cfg(has_metal)]
1020            Device::Metal(_) => mln_mtl::BorrowedTextures::depth_stencil_formats(),
1021            #[cfg(has_native_gl)]
1022            Device::Gl(_) => mln_gl::BorrowedTextures::depth_stencil_formats(),
1023            #[cfg(has_webgl)]
1024            Device::WebGl(Some(_)) => mln_gl::BorrowedTextures::depth_stencil_formats(),
1025            #[cfg(feature = "webgpu")]
1026            Device::WebGpu(ref device) => mln_webgpu::BorrowedTextures::depth_stencil_formats(device.device()),
1027            #[cfg(target_family = "wasm")]
1028            _ => DepthStencilFormats::NONE,
1029        }
1030    }
1031
1032    /// The kinds of [`export_kinds`](Self::export_kinds) whose rings also
1033    /// share each frame's depth texture, when they keep depth: only
1034    /// [`ExportKind::OpaqueFd`], since an `IOSurface`, a dmabuf or an Android
1035    /// hardware buffer holds no depth format. A ring of those keeps its depth
1036    /// on the device.
1037    #[must_use]
1038    pub fn depth_export_kinds(&self) -> ExportKinds {
1039        match self {
1040            #[cfg(has_vulkan)]
1041            Device::Vulkan(device) => device.depth_export_kinds(),
1042            _ => ExportKinds::NONE,
1043        }
1044    }
1045
1046    /// The kinds of exported ring that sessions on the device share their
1047    /// images in: those that the device has exported an image of.
1048    #[must_use]
1049    pub fn export_kinds(&self) -> ExportKinds {
1050        match self {
1051            #[cfg(has_vulkan)]
1052            Device::Vulkan(device) => device.export_kinds(),
1053            #[cfg(has_metal)]
1054            Device::Metal(device) => mln_mtl::exported_target::export_kinds(device),
1055            #[cfg(has_gl_exported)]
1056            Device::Gl(device) => mln_gl::exported_target::export_kinds(device),
1057            #[cfg(has_d3d12)]
1058            Device::D3d12(device) => device.export_kinds(),
1059            _ => ExportKinds::NONE,
1060        }
1061    }
1062
1063    /// The kind that a session on the device shares `ring`'s images in, and
1064    /// the kinds of sync with which the host can wait for a frame (the
1065    /// producer's) and a session for the host's reads (the consumer's).
1066    ///
1067    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when the
1068    /// device exports none of the ring's kinds.
1069    pub fn export_plan(&self, ring: &ExportedRing) -> Result<(ExportKind, SyncKinds, SyncKinds), Error> {
1070        match self {
1071            #[cfg(has_vulkan)]
1072            Device::Vulkan(device) => backends::vulkan::export_plan(device, ring),
1073            #[cfg(has_metal)]
1074            Device::Metal(device) => backends::metal::export_plan(device, ring),
1075            #[cfg(has_gl_exported)]
1076            Device::Gl(device) => backends::gl::export_plan(device, ring),
1077            #[cfg(has_d3d12)]
1078            Device::D3d12(device) => backends::d3d12::export_plan(device, ring),
1079            _ => {
1080                let _ = ring;
1081                Err(Error::unsupported(format!("a {:?} device exports no ring", self.backend())))
1082            }
1083        }
1084    }
1085
1086    /// The kinds of sync with which the host can wait for an exported
1087    /// ring's frame (the producer's) and a session for the host's reads (the
1088    /// consumer's), on a device that exports a ring.
1089    #[must_use]
1090    pub fn export_sync_kinds(&self) -> (SyncKinds, SyncKinds) {
1091        if self.export_kinds().is_empty() {
1092            return (SyncKinds::NONE, SyncKinds::NONE);
1093        }
1094        match self {
1095            #[cfg(has_vulkan)]
1096            Device::Vulkan(device) => mln_vulkan::exported_target::sync_kinds(device),
1097            #[cfg(has_metal)]
1098            Device::Metal(device) => mln_mtl::exported_target::sync_kinds(device),
1099            #[cfg(has_gl_exported)]
1100            Device::Gl(device) => mln_gl::exported_target::sync_kinds(device),
1101            #[cfg(has_d3d12)]
1102            Device::D3d12(_) => mln_d3d12::exported_target::sync_kinds(),
1103            _ => (SyncKinds::NONE, SyncKinds::NONE),
1104        }
1105    }
1106
1107    /// The library's device for `ring`: on the first of [`new`](Self::new)'s
1108    /// backends whose device exports one of the ring's kinds.
1109    ///
1110    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when no
1111    /// backend's device does, and as [`new`](Self::new) does.
1112    pub fn for_exported_ring(ring: &ExportedRing) -> Result<Device, Error> {
1113        #[cfg(target_family = "wasm")]
1114        {
1115            let _ = ring;
1116            Err(Error::unsupported("the browser has no library devices"))
1117        }
1118        #[cfg(not(target_family = "wasm"))]
1119        {
1120            let mut error = Error::unsupported("no backend of this build exports the ring's kinds of image");
1121            for backend in Self::native_order() {
1122                match Self::with_backend(*backend, DeviceOptions::default()) {
1123                    Ok(device) => match device.export_plan(ring) {
1124                        Ok(_) => return Ok(device),
1125                        Err(e) => error = e,
1126                    },
1127                    Err(e) if missing(&e) => {}
1128                    Err(e) => return Err(e),
1129                }
1130            }
1131            Err(error)
1132        }
1133    }
1134
1135    /// Whether sessions on the device present to the host's own surfaces:
1136    /// a Vulkan device's `VkSurfaceKHR`s, or the `EGLSurface`s of an OpenGL
1137    /// device that wraps the host's context.
1138    #[must_use]
1139    pub fn presents_to_host_surfaces(&self) -> bool {
1140        match self {
1141            #[cfg(has_vulkan)]
1142            Device::Vulkan(device) => device.presents(),
1143            #[cfg(has_native_gl)]
1144            Device::Gl(device) => device.is_host(),
1145            _ => false,
1146        }
1147    }
1148
1149    /// Whether sessions on the device present to the surfaces of
1150    /// `surface`'s type: a Vulkan device's instance needs the type's surface
1151    /// extension, which the loader may lack.
1152    #[must_use]
1153    pub fn presents_to(&self, surface: SurfaceType) -> bool {
1154        if !surface.presents_with(self.backend()) {
1155            return false;
1156        }
1157        match self {
1158            #[cfg(has_vulkan)]
1159            Device::Vulkan(device) => {
1160                backends::vulkan::surface_extension(surface).is_some_and(|name| device.presents_through(name))
1161            }
1162            _ => true,
1163        }
1164    }
1165
1166    /// The backends [`new`](Self::new) tries, in order. Vulkan comes before
1167    /// D3D12 on Windows, as it renders frames faster on the GPUs measured.
1168    #[cfg(not(target_family = "wasm"))]
1169    fn native_order() -> &'static [BackendType] {
1170        if cfg!(target_os = "macos") {
1171            &[BackendType::Metal, BackendType::Vulkan, BackendType::OpenGL, BackendType::WebGPU]
1172        } else if cfg!(target_vendor = "apple") {
1173            &[BackendType::Metal, BackendType::WebGPU]
1174        } else if cfg!(windows) {
1175            &[BackendType::Vulkan, BackendType::D3D12, BackendType::OpenGL, BackendType::WebGPU]
1176        } else {
1177            &[BackendType::Vulkan, BackendType::OpenGL, BackendType::WebGPU]
1178        }
1179    }
1180
1181    /// The backend the device is of.
1182    #[must_use]
1183    pub fn backend(&self) -> BackendType {
1184        match *self {
1185            #[cfg(feature = "webgpu")]
1186            Device::WebGpu(_) => BackendType::WebGPU,
1187            #[cfg(has_metal)]
1188            Device::Metal(_) => BackendType::Metal,
1189            #[cfg(has_vulkan)]
1190            Device::Vulkan(_) => BackendType::Vulkan,
1191            #[cfg(has_d3d12)]
1192            Device::D3d12(_) => BackendType::D3D12,
1193            #[cfg(has_native_gl)]
1194            Device::Gl(_) => BackendType::OpenGL,
1195            #[cfg(has_webgl)]
1196            Device::WebGl(_) => BackendType::OpenGL,
1197        }
1198    }
1199}