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