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