Skip to main content

mln_runtime/render/
target.rs

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