1#![allow(
8 unreachable_patterns,
9 irrefutable_let_patterns,
10 clippy::match_wildcard_for_single_variants,
11 reason = "the backends' variants depend on the build's features and target"
12)]
13
14use std::sync::Arc;
15
16use mln_gfx::Window;
17pub use mln_gfx::backend::Type as BackendType;
18pub use mln_gfx::{
19 ConsumerSync, DepthStencilFormat, DepthStencilFormats, DmaBufFormat, DmaBufPlane, ExportKind, ExportKinds,
20 ExportedImage, ExportedRing, FrameDepth, GpuSync, NativeTexture, SyncKind, SyncKinds,
21};
22use mln_style::error::Error;
23use mln_style::size::Size;
24
25#[cfg(any(has_metal, has_vulkan, has_d3d12, feature = "webgpu", feature = "gl"))]
26use super::backends;
27
28pub type Wake = Arc<dyn Fn() + Send + Sync>;
31
32#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
34pub enum Driver {
35 #[default]
37 CoreWorker,
38 CallerThread,
41}
42
43#[derive(Clone, Default)]
45pub struct AttachOptions {
46 pub driver: Driver,
47 pub frame_wake: Option<Wake>,
51 pub redraw_wake: Option<Wake>,
56 pub driver_work_wake: Option<Wake>,
60 pub producer_sync_kinds: SyncKinds,
64}
65
66impl std::fmt::Debug for AttachOptions {
67 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68 f.debug_struct("AttachOptions")
69 .field("driver", &self.driver)
70 .field("frame_wake", &self.frame_wake.is_some())
71 .field("redraw_wake", &self.redraw_wake.is_some())
72 .field("driver_work_wake", &self.driver_work_wake.is_some())
73 .field("producer_sync_kinds", &self.producer_sync_kinds)
74 .finish()
75 }
76}
77
78#[derive(Debug)]
83pub enum RenderTarget {
84 Offscreen { size: Size, device: Option<Device> },
88 Surface { size: Size, surface: Surface, device: Option<Device> },
103 Borrowed { size: Size, ring: BorrowedRing, device: Device },
110 Exported { size: Size, ring: ExportedRing, device: Option<Device> },
121}
122
123#[derive(Clone, Debug, PartialEq)]
125pub struct BorrowedRing {
126 pub(crate) kind: RingKind,
127}
128
129#[derive(Clone, Debug, PartialEq)]
130pub(crate) enum RingKind {
131 #[cfg(has_vulkan)]
132 Vulkan(mln_vulkan::BorrowedImages),
133 #[cfg(has_metal)]
134 Metal(mln_mtl::BorrowedTextures),
135 #[cfg(feature = "gl")]
136 Gl(mln_gl::BorrowedTextures),
137 #[cfg(feature = "webgpu")]
138 WebGpu(mln_webgpu::BorrowedTextures),
139 #[cfg(has_d3d12)]
140 D3d12(mln_d3d12::BorrowedTextures),
141}
142
143#[derive(Clone, Debug, PartialEq, Eq)]
146pub struct FrameTexture {
147 pub size: mln_gfx::Size,
148 pub kind: FrameTextureKind,
149 pub native: Option<FrameTextureKind>,
152 pub depth: Option<FrameDepth>,
155}
156
157impl FrameTexture {
158 #[must_use]
161 pub fn native_kind(&self) -> Option<&FrameTextureKind> {
162 match &self.kind {
163 FrameTextureKind::Exported(_) => self.native.as_ref(),
164 kind => Some(kind),
165 }
166 }
167
168 pub(crate) fn exported(frame: mln_gfx::ExportedFrame, device: &Device) -> FrameTexture {
170 FrameTexture {
171 size: frame.size,
172 kind: FrameTextureKind::Exported(frame.image),
173 native: native_kind(frame.texture, device),
174 depth: frame.depth,
175 }
176 }
177}
178
179fn native_kind(texture: NativeTexture, device: &Device) -> Option<FrameTextureKind> {
181 match (texture, device) {
182 #[cfg(has_vulkan)]
183 (NativeTexture::Vulkan { image, view, format, layout }, Device::Vulkan(device)) => {
184 Some(backends::vulkan::native_texture(image, view, format, layout, device))
185 }
186 #[cfg(has_metal)]
187 (NativeTexture::Metal { texture, pixel_format }, Device::Metal(device)) => {
188 Some(backends::metal::native_texture(texture, pixel_format, device))
189 }
190 (NativeTexture::OpenGl { texture, target, .. }, _) => Some(FrameTextureKind::OpenGl { texture, target }),
191 #[cfg(has_d3d12)]
192 (NativeTexture::D3d12 { resource, format, state }, Device::D3d12(device)) => {
193 Some(backends::d3d12::native_texture(resource, format, state, device))
194 }
195 _ => None,
196 }
197}
198
199#[derive(Clone, Debug, PartialEq, Eq)]
201#[non_exhaustive]
202pub enum FrameTextureKind {
203 Vulkan { image: u64, view: u64, device: u64, format: i32, layout: i32 },
206 Metal { texture: u64, device: u64, pixel_format: u64 },
208 OpenGl { texture: u32, target: u32 },
210 #[cfg(has_webgl)]
213 WebGl { texture: mln_gl::WebTexture, target: u32, depth: Option<mln_gl::WebTexture> },
214 WebGpu,
216 D3d12 { resource: u64, device: u64, format: u32, state: u32 },
219 Exported(ExportedImage),
221}
222
223impl BorrowedRing {
224 #[must_use]
226 pub fn backend(&self) -> BackendType {
227 match self.kind {
228 #[cfg(has_vulkan)]
229 RingKind::Vulkan(_) => BackendType::Vulkan,
230 #[cfg(has_metal)]
231 RingKind::Metal(_) => BackendType::Metal,
232 #[cfg(feature = "gl")]
233 RingKind::Gl(_) => BackendType::OpenGL,
234 #[cfg(feature = "webgpu")]
235 RingKind::WebGpu(_) => BackendType::WebGPU,
236 #[cfg(has_d3d12)]
237 RingKind::D3d12(_) => BackendType::D3D12,
238 _ => BackendType::WebGPU,
240 }
241 }
242
243 #[must_use]
245 pub fn depth(&self) -> usize {
246 match &self.kind {
247 #[cfg(has_vulkan)]
248 RingKind::Vulkan(images) => images.images.len(),
249 #[cfg(has_metal)]
250 RingKind::Metal(textures) => textures.textures.len(),
251 #[cfg(feature = "gl")]
252 RingKind::Gl(textures) => textures.textures.len(),
253 #[cfg(feature = "webgpu")]
254 RingKind::WebGpu(textures) => textures.textures.len(),
255 #[cfg(has_d3d12)]
256 RingKind::D3d12(textures) => textures.textures.len(),
257 _ => 0,
258 }
259 }
260
261 #[must_use]
263 pub fn physical_size(&self) -> mln_gfx::Size {
264 match &self.kind {
265 #[cfg(has_vulkan)]
266 RingKind::Vulkan(images) => images.size,
267 #[cfg(has_metal)]
268 RingKind::Metal(textures) => textures.size,
269 #[cfg(feature = "gl")]
270 RingKind::Gl(textures) => textures.size,
271 #[cfg(feature = "webgpu")]
272 RingKind::WebGpu(textures) => textures.size,
273 #[cfg(has_d3d12)]
274 RingKind::D3d12(textures) => textures.size,
275 _ => mln_gfx::Size::default(),
276 }
277 }
278
279 #[must_use]
284 pub fn takes_depth_on(&self, device: &Device) -> bool {
285 #[cfg(feature = "gl")]
288 if let RingKind::Gl(_) = self.kind {
289 return true;
290 }
291 !self.has_depth()
292 || self.depth_stencil_format().is_some_and(|format| device.depth_stencil_formats().contains(format))
293 }
294
295 #[must_use]
298 pub fn depth_stencil_format(&self) -> Option<DepthStencilFormat> {
299 match &self.kind {
300 #[cfg(has_vulkan)]
301 RingKind::Vulkan(images) => backends::vulkan::ring_depth_stencil_format(images),
302 #[cfg(has_metal)]
303 RingKind::Metal(textures) => backends::metal::ring_depth_stencil_format(textures),
304 #[cfg(feature = "webgpu")]
305 RingKind::WebGpu(textures) => backends::webgpu::ring_depth_stencil_format(textures),
306 #[cfg(has_d3d12)]
307 RingKind::D3d12(textures) => backends::d3d12::ring_depth_stencil_format(textures),
308 _ => None,
309 }
310 }
311
312 #[must_use]
314 pub fn has_depth(&self) -> bool {
315 match &self.kind {
316 #[cfg(has_vulkan)]
317 RingKind::Vulkan(images) => images.depth.is_some(),
318 #[cfg(has_metal)]
319 RingKind::Metal(textures) => !textures.depth_textures.is_empty(),
320 #[cfg(feature = "gl")]
321 RingKind::Gl(textures) => !textures.depth_textures.is_empty(),
322 #[cfg(feature = "webgpu")]
323 RingKind::WebGpu(textures) => !textures.depth_textures.is_empty(),
324 #[cfg(has_d3d12)]
325 RingKind::D3d12(textures) => !textures.depth_textures.is_empty(),
326 _ => false,
327 }
328 }
329
330 pub(crate) fn same_texture(&self, slot: usize, other: &BorrowedRing, other_slot: usize) -> bool {
332 match (&self.kind, &other.kind) {
333 #[cfg(has_vulkan)]
334 (RingKind::Vulkan(images), RingKind::Vulkan(others)) => {
335 backends::vulkan::ring_same_texture(images, slot, others, other_slot)
336 }
337 #[cfg(has_metal)]
338 (RingKind::Metal(textures), RingKind::Metal(others)) => {
339 backends::metal::ring_same_texture(textures, slot, others, other_slot)
340 }
341 #[cfg(feature = "gl")]
342 (RingKind::Gl(textures), RingKind::Gl(others)) => {
343 backends::gl::ring_same_texture(textures, slot, others, other_slot)
344 }
345 #[cfg(feature = "webgpu")]
346 (RingKind::WebGpu(textures), RingKind::WebGpu(others)) => {
347 backends::webgpu::ring_same_texture(textures, slot, others, other_slot)
348 }
349 #[cfg(has_d3d12)]
350 (RingKind::D3d12(textures), RingKind::D3d12(others)) => {
351 backends::d3d12::ring_same_texture(textures, slot, others, other_slot)
352 }
353 _ => false,
354 }
355 }
356
357 #[must_use]
359 pub fn texture(&self, slot: usize, device: &Device) -> Option<FrameTexture> {
360 match (&self.kind, device) {
361 #[cfg(has_vulkan)]
362 (RingKind::Vulkan(images), Device::Vulkan(device)) => backends::vulkan::ring_texture(images, slot, device),
363 #[cfg(has_metal)]
364 (RingKind::Metal(textures), Device::Metal(device)) => backends::metal::ring_texture(textures, slot, device),
365 #[cfg(has_native_gl)]
366 (RingKind::Gl(textures), Device::Gl(_)) => backends::gl::ring_texture_native(textures, slot),
367 #[cfg(has_webgl)]
368 (RingKind::Gl(textures), Device::WebGl(Some(_))) => backends::gl::ring_texture_webgl(textures, slot),
369 #[cfg(feature = "webgpu")]
370 (RingKind::WebGpu(textures), Device::WebGpu(_)) => backends::webgpu::ring_texture(textures, slot),
371 #[cfg(has_d3d12)]
372 (RingKind::D3d12(textures), Device::D3d12(device)) => backends::d3d12::ring_texture(textures, slot, device),
373 _ => None,
374 }
375 }
376}
377
378pub struct Surface {
383 pub(crate) kind: SurfaceKind,
384 pub(crate) cap_frame_rate: bool,
387}
388
389pub enum SurfaceOverlay {
394 #[cfg(feature = "webgpu")]
395 WebGpu(mln_webgpu::Overlay),
396 #[cfg(has_metal)]
397 Metal(mln_mtl::surface_target::Overlay),
398 #[cfg(has_vulkan)]
399 Vulkan(Box<dyn mln_vulkan::Overlay>),
400 #[cfg(has_d3d12)]
401 D3d12(Box<dyn mln_d3d12::Overlay>),
402 #[cfg(has_gl_window)]
403 Gl(mln_gl::Overlay),
404}
405
406pub(crate) enum SurfaceKind {
407 Window(Arc<dyn Window>),
408 #[cfg(has_metal)]
409 MetalLayer(mln_mtl::Layer),
410 #[cfg(has_native_webgpu)]
411 Wgpu(wgpu::Surface<'static>),
412 #[cfg(has_vulkan)]
414 Vulkan(mln_vulkan::HostSurface),
415 #[cfg(has_native_gl)]
417 Gl(mln_gl::HostSurface),
418 #[cfg(has_d3d12)]
422 D3d12Composition {
423 composition: mln_d3d12::Composition,
424 thread: std::thread::ThreadId,
425 },
426 #[cfg(target_family = "wasm")]
429 WebCanvas {
430 canvas: wasm_bindgen::JsValue,
431 format: Option<CanvasFormat>,
432 },
433}
434
435#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
437pub enum CanvasFormat {
438 Bgra8Unorm,
440 Rgba8Unorm,
442 Rgba16Float,
444}
445
446impl CanvasFormat {
447 #[must_use]
449 pub fn from_name(name: &str) -> Option<CanvasFormat> {
450 match name {
451 "bgra8unorm" => Some(CanvasFormat::Bgra8Unorm),
452 "rgba8unorm" => Some(CanvasFormat::Rgba8Unorm),
453 "rgba16float" => Some(CanvasFormat::Rgba16Float),
454 _ => None,
455 }
456 }
457}
458
459impl Surface {
460 pub(super) fn of(kind: SurfaceKind) -> Surface {
461 Surface { kind, cap_frame_rate: true }
462 }
463
464 #[must_use]
470 pub fn without_frame_rate_cap(self) -> Surface {
471 Surface { cap_frame_rate: false, ..self }
472 }
473
474 pub fn window(window: impl Window + 'static) -> Surface {
485 Surface::of(SurfaceKind::Window(Arc::new(window)))
486 }
487
488 #[cfg(target_family = "wasm")]
510 pub fn web_canvas(canvas: wasm_bindgen::JsValue, format: Option<CanvasFormat>) -> Result<Surface, Error> {
511 use wasm_bindgen::JsCast as _;
512 if !canvas.is_instance_of::<web_sys::OffscreenCanvas>()
513 && !canvas.is_instance_of::<web_sys::HtmlCanvasElement>()
514 {
515 return Err(Error::invalid_argument("a web canvas is an OffscreenCanvas or an HTMLCanvasElement"));
516 }
517 Ok(Surface::of(SurfaceKind::WebCanvas { canvas, format }))
518 }
519
520 #[must_use]
523 pub fn host_backend(&self) -> Option<BackendType> {
524 match self.kind {
525 #[cfg(has_vulkan)]
526 SurfaceKind::Vulkan(_) => Some(BackendType::Vulkan),
527 #[cfg(has_native_gl)]
528 SurfaceKind::Gl(_) => Some(BackendType::OpenGL),
529 _ => None,
530 }
531 }
532
533 pub(crate) fn clone_window(&self) -> Option<Surface> {
536 let kind = match &self.kind {
537 SurfaceKind::Window(window) => SurfaceKind::Window(Arc::clone(window)),
538 #[cfg(has_native_gl)]
539 SurfaceKind::Gl(surface) => SurfaceKind::Gl(*surface),
540 _ => return None,
541 };
542 Some(Surface { kind, cap_frame_rate: self.cap_frame_rate })
543 }
544
545 pub(crate) fn check_area(&self) -> Result<(), Error> {
549 if let SurfaceKind::Window(window) = &self.kind
550 && !mln_gfx::window::has_area(&**window)
551 {
552 return Err(Error::invalid_state("the window is minimized or has no client area"));
553 }
554 Ok(())
555 }
556
557 #[cfg_attr(
564 not(all(feature = "gl", windows)),
565 expect(clippy::unnecessary_wraps, reason = "only OpenGL on Windows checks the window's pixel format")
566 )]
567 pub(crate) fn check_pixel_format(&self, device: Option<&Device>) -> Result<(), Error> {
568 #[cfg(all(feature = "gl", windows))]
569 if let SurfaceKind::Window(window) = &self.kind
570 && device.map_or(cfg!(not(any(has_vulkan, has_d3d12))), |device| device.backend() == BackendType::OpenGL)
571 {
572 backends::gl::check_window_pixel_format(&**window)?;
573 }
574 #[cfg(not(all(feature = "gl", windows)))]
575 let _ = (self, device);
576 Ok(())
577 }
578
579 pub(crate) fn host_window(&self) -> Option<Arc<dyn Window>> {
581 match &self.kind {
582 SurfaceKind::Window(window) => Some(Arc::clone(window)),
583 _ => None,
584 }
585 }
586
587 pub(crate) fn needs_no_device(&self) -> bool {
589 match self.kind {
590 SurfaceKind::Window(_) => true,
591 #[cfg(has_metal)]
592 SurfaceKind::MetalLayer(_) => true,
593 #[cfg(has_native_webgpu)]
594 SurfaceKind::Wgpu(_) => false,
595 #[cfg(has_vulkan)]
596 SurfaceKind::Vulkan(_) => false,
597 #[cfg(has_native_gl)]
598 SurfaceKind::Gl(_) => false,
599 #[cfg(has_d3d12)]
600 SurfaceKind::D3d12Composition { .. } => true,
601 #[cfg(target_family = "wasm")]
602 SurfaceKind::WebCanvas { .. } => true,
603 }
604 }
605}
606
607#[cfg(not(target_family = "wasm"))]
613pub(crate) struct SentSurface(Surface);
614
615#[cfg(target_family = "wasm")]
621pub(crate) enum SentSurface {
622 Window(Arc<dyn Window>),
623 WebCanvas { canvas: crate::web::HandedCanvas, format: Option<CanvasFormat> },
624}
625
626impl SentSurface {
627 pub(crate) fn new(surface: Surface, session: super::SessionId) -> SentSurface {
629 #[cfg(not(target_family = "wasm"))]
630 {
631 let _ = session;
632 SentSurface(surface)
633 }
634 #[cfg(target_family = "wasm")]
635 match surface.kind {
636 SurfaceKind::Window(window) => SentSurface::Window(window),
637 SurfaceKind::WebCanvas { canvas, format } => {
638 SentSurface::WebCanvas { canvas: crate::web::hand_canvas(session, canvas), format }
639 }
640 }
641 }
642
643 #[cfg_attr(
647 not(target_family = "wasm"),
648 expect(clippy::unnecessary_wraps, reason = "only the browser's canvases wait for their session's thread")
649 )]
650 pub(crate) fn receive(self) -> Result<Surface, Error> {
651 #[cfg(not(target_family = "wasm"))]
652 {
653 Ok(self.0)
654 }
655 #[cfg(target_family = "wasm")]
656 match self {
657 SentSurface::Window(window) => Ok(Surface::of(SurfaceKind::Window(window))),
658 SentSurface::WebCanvas { canvas, format } => {
659 let canvas = canvas.take().ok_or_else(|| Error::invalid_state("the surface's canvas is gone"))?;
660 Ok(Surface::of(SurfaceKind::WebCanvas { canvas, format }))
661 }
662 }
663 }
664
665 #[cfg(target_family = "wasm")]
668 pub(crate) fn presents_with_web_gpu(&self) -> bool {
669 matches!(self, SentSurface::WebCanvas { .. }) && cfg!(feature = "webgpu")
670 }
671}
672
673impl std::fmt::Debug for Surface {
674 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
675 f.debug_struct("Surface").finish_non_exhaustive()
676 }
677}
678
679#[derive(Clone, Debug)]
683#[non_exhaustive]
684pub enum Device {
685 #[cfg(feature = "webgpu")]
689 WebGpu(mln_webgpu::Device),
690 #[cfg(has_metal)]
692 Metal(mln_mtl::Device),
693 #[cfg(has_vulkan)]
695 Vulkan(mln_vulkan::Device),
696 #[cfg(has_d3d12)]
698 D3d12(mln_d3d12::Device),
699 #[cfg(has_native_gl)]
702 Gl(mln_gl::Device),
703 #[cfg(has_webgl)]
707 WebGl(Option<mln_gl::WebGlDevice>),
708}
709
710#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
712pub struct DeviceOptions {
713 pub adapter: Option<Adapter>,
715 pub gl_api: GlApi,
719 pub gl_single_context: bool,
722}
723
724#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
727pub enum GlApi {
728 Gles,
730 Gl,
732}
733
734impl Default for GlApi {
735 fn default() -> GlApi {
736 if cfg!(windows) { GlApi::Gl } else { GlApi::Gles }
737 }
738}
739
740#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
742pub enum Adapter {
743 Index(usize),
745 Uuid([u8; 16]),
748 Luid([u8; 8]),
752}
753
754#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
756#[non_exhaustive]
757pub enum SurfaceType {
758 MetalLayer,
760 Win32,
762 Xlib,
764 Xcb,
766 Wayland,
768 AndroidNdk,
770 OhosNdk,
772}
773
774impl SurfaceType {
775 #[must_use]
778 pub fn presents_with(self, backend: BackendType) -> bool {
779 let windowing = match self {
780 SurfaceType::MetalLayer => false,
781 SurfaceType::Win32 => cfg!(windows),
782 SurfaceType::Xlib | SurfaceType::Xcb | SurfaceType::Wayland => {
783 cfg!(all(unix, not(target_vendor = "apple"), not(target_os = "android"), not(target_env = "ohos")))
784 }
785 SurfaceType::AndroidNdk => cfg!(target_os = "android"),
786 SurfaceType::OhosNdk => cfg!(target_env = "ohos"),
787 };
788 match backend {
789 BackendType::Metal => cfg!(has_metal) && self == SurfaceType::MetalLayer,
790 BackendType::Vulkan => cfg!(has_vulkan) && windowing,
791 BackendType::OpenGL => {
794 cfg!(has_gl_window)
795 && windowing
796 && matches!(
797 self,
798 SurfaceType::Win32
799 | SurfaceType::Xlib
800 | SurfaceType::Wayland
801 | SurfaceType::AndroidNdk
802 | SurfaceType::OhosNdk
803 )
804 }
805 BackendType::WebGPU => cfg!(has_native_webgpu) && windowing && self != SurfaceType::OhosNdk,
808 BackendType::D3D12 => cfg!(has_d3d12) && self == SurfaceType::Win32,
809 }
810 }
811
812 #[must_use]
815 pub fn presents_with_any(self) -> bool {
816 [BackendType::Metal, BackendType::Vulkan, BackendType::D3D12, BackendType::OpenGL, BackendType::WebGPU]
817 .into_iter()
818 .any(|backend| self.presents_with(backend))
819 }
820
821 #[must_use]
825 pub fn presents_without_device(self) -> bool {
826 match self {
827 SurfaceType::MetalLayer => self.presents_with(BackendType::Metal),
828 _ => [BackendType::Vulkan, BackendType::D3D12, BackendType::OpenGL, BackendType::WebGPU]
829 .into_iter()
830 .any(|backend| self.presents_with(backend)),
831 }
832 }
833}
834
835#[cfg(not(target_family = "wasm"))]
838fn missing(error: &Error) -> bool {
839 error.kind == mln_style::error::ErrorKind::Unsupported
840}
841
842#[derive(Debug, Default)]
845pub(crate) struct DeviceLease {
846 #[cfg(has_vulkan)]
847 queue: Option<mln_vulkan::QueueLease>,
848}
849
850impl DeviceLease {
851 #[cfg_attr(
854 not(has_vulkan),
855 expect(clippy::unused_self, reason = "only a Vulkan device holds the host's queue lock")
856 )]
857 pub(crate) fn revoke(&self) {
858 #[cfg(has_vulkan)]
859 if let Some(queue) = &self.queue {
860 queue.revoke();
861 }
862 }
863}
864
865impl Device {
866 pub(crate) fn lease(self) -> (Device, DeviceLease) {
871 match self {
872 #[cfg(has_vulkan)]
873 Device::Vulkan(device) => {
874 let (device, queue) = device.lease();
875 (Device::Vulkan(device), DeviceLease { queue: Some(queue) })
876 }
877 device => (device, DeviceLease::default()),
878 }
879 }
880
881 pub(crate) fn lost(&self) -> Option<Error> {
884 match *self {
885 #[cfg(feature = "webgpu")]
886 Device::WebGpu(ref device) => device.lost().map(|message| Error::target_lost(message.to_owned())),
887 _ => None,
888 }
889 }
890
891 pub(crate) fn abandon_keeps_graphics(&self) -> bool {
897 match *self {
898 #[cfg(feature = "webgpu")]
899 Device::WebGpu(_) => true,
900 #[cfg(has_metal)]
901 Device::Metal(_) => false,
902 #[cfg(has_vulkan)]
903 Device::Vulkan(_) => false,
904 #[cfg(has_d3d12)]
905 Device::D3d12(_) => false,
906 #[cfg(has_native_gl)]
907 Device::Gl(_) => true,
908 #[cfg(has_webgl)]
909 Device::WebGl(_) => true,
910 }
911 }
912
913 pub fn new(options: DeviceOptions) -> Result<Device, Error> {
929 #[cfg(target_family = "wasm")]
930 {
931 let _ = options;
932 Err(Error::unsupported("the browser has no library devices"))
933 }
934 #[cfg(not(target_family = "wasm"))]
935 {
936 let mut error = Error::unsupported("this build has no backend");
937 for backend in Self::native_order() {
938 match Self::with_backend(*backend, options) {
939 Ok(device) => return Ok(device),
940 Err(e) if missing(&e) => error = e,
941 Err(e) => return Err(e),
942 }
943 }
944 Err(error)
945 }
946 }
947
948 pub fn with_backend(backend: BackendType, options: DeviceOptions) -> Result<Device, Error> {
957 match backend {
958 #[cfg(has_native_webgpu)]
959 BackendType::WebGPU => backends::webgpu::create_device(options.adapter),
960 #[cfg(has_metal)]
961 BackendType::Metal => backends::metal::create_device(options.adapter),
962 #[cfg(has_vulkan)]
963 BackendType::Vulkan => backends::vulkan::create_device(options.adapter),
964 #[cfg(has_d3d12)]
965 BackendType::D3D12 => backends::d3d12::create_device(options.adapter),
966 #[cfg(has_gl_device)]
967 BackendType::OpenGL => backends::gl::create_device(options),
968 #[cfg(has_webgl)]
969 BackendType::OpenGL if options.adapter.is_none() => Ok(Device::WebGl(None)),
970 _ => {
971 let _ = options;
972 Err(Error::unsupported(format!("this build has no {backend:?} backend")))
973 }
974 }
975 }
976
977 pub fn borrowed_sync_kinds(&self, ring: &BorrowedRing) -> Result<(SyncKinds, SyncKinds), Error> {
985 match (self, &ring.kind) {
986 #[cfg(has_vulkan)]
987 (Device::Vulkan(device), RingKind::Vulkan(images)) => backends::vulkan::borrowed_sync_kinds(device, images),
988 #[cfg(has_metal)]
989 (Device::Metal(device), RingKind::Metal(textures)) => {
990 backends::metal::borrowed_sync_kinds(device, textures)
991 }
992 #[cfg(has_native_gl)]
993 (Device::Gl(device), RingKind::Gl(_)) => backends::gl::borrowed_sync_kinds_native(device),
994 #[cfg(has_webgl)]
995 (Device::WebGl(device), RingKind::Gl(_)) => backends::gl::borrowed_sync_kinds_webgl(device.as_ref()),
996 #[cfg(feature = "webgpu")]
997 (Device::WebGpu(_), RingKind::WebGpu(textures)) => backends::webgpu::borrowed_sync_kinds(textures),
998 #[cfg(has_d3d12)]
999 (Device::D3d12(device), RingKind::D3d12(textures)) => {
1000 backends::d3d12::borrowed_sync_kinds(device, textures)
1001 }
1002 _ => Err(Error::unsupported(format!(
1003 "a {:?} device renders into no ring of {:?} textures",
1004 self.backend(),
1005 ring.backend()
1006 ))),
1007 }
1008 }
1009
1010 #[must_use]
1013 pub fn depth_stencil_formats(&self) -> DepthStencilFormats {
1014 match *self {
1015 #[cfg(has_vulkan)]
1016 Device::Vulkan(ref device) => device.depth_stencil_formats(),
1017 #[cfg(has_d3d12)]
1018 Device::D3d12(_) => mln_d3d12::BorrowedTextures::depth_stencil_formats(),
1019 #[cfg(has_metal)]
1020 Device::Metal(_) => mln_mtl::BorrowedTextures::depth_stencil_formats(),
1021 #[cfg(has_native_gl)]
1022 Device::Gl(_) => mln_gl::BorrowedTextures::depth_stencil_formats(),
1023 #[cfg(has_webgl)]
1024 Device::WebGl(Some(_)) => mln_gl::BorrowedTextures::depth_stencil_formats(),
1025 #[cfg(feature = "webgpu")]
1026 Device::WebGpu(ref device) => mln_webgpu::BorrowedTextures::depth_stencil_formats(device.device()),
1027 #[cfg(target_family = "wasm")]
1028 _ => DepthStencilFormats::NONE,
1029 }
1030 }
1031
1032 #[must_use]
1038 pub fn depth_export_kinds(&self) -> ExportKinds {
1039 match self {
1040 #[cfg(has_vulkan)]
1041 Device::Vulkan(device) => device.depth_export_kinds(),
1042 _ => ExportKinds::NONE,
1043 }
1044 }
1045
1046 #[must_use]
1049 pub fn export_kinds(&self) -> ExportKinds {
1050 match self {
1051 #[cfg(has_vulkan)]
1052 Device::Vulkan(device) => device.export_kinds(),
1053 #[cfg(has_metal)]
1054 Device::Metal(device) => mln_mtl::exported_target::export_kinds(device),
1055 #[cfg(has_gl_exported)]
1056 Device::Gl(device) => mln_gl::exported_target::export_kinds(device),
1057 #[cfg(has_d3d12)]
1058 Device::D3d12(device) => device.export_kinds(),
1059 _ => ExportKinds::NONE,
1060 }
1061 }
1062
1063 pub fn export_plan(&self, ring: &ExportedRing) -> Result<(ExportKind, SyncKinds, SyncKinds), Error> {
1070 match self {
1071 #[cfg(has_vulkan)]
1072 Device::Vulkan(device) => backends::vulkan::export_plan(device, ring),
1073 #[cfg(has_metal)]
1074 Device::Metal(device) => backends::metal::export_plan(device, ring),
1075 #[cfg(has_gl_exported)]
1076 Device::Gl(device) => backends::gl::export_plan(device, ring),
1077 #[cfg(has_d3d12)]
1078 Device::D3d12(device) => backends::d3d12::export_plan(device, ring),
1079 _ => {
1080 let _ = ring;
1081 Err(Error::unsupported(format!("a {:?} device exports no ring", self.backend())))
1082 }
1083 }
1084 }
1085
1086 #[must_use]
1090 pub fn export_sync_kinds(&self) -> (SyncKinds, SyncKinds) {
1091 if self.export_kinds().is_empty() {
1092 return (SyncKinds::NONE, SyncKinds::NONE);
1093 }
1094 match self {
1095 #[cfg(has_vulkan)]
1096 Device::Vulkan(device) => mln_vulkan::exported_target::sync_kinds(device),
1097 #[cfg(has_metal)]
1098 Device::Metal(device) => mln_mtl::exported_target::sync_kinds(device),
1099 #[cfg(has_gl_exported)]
1100 Device::Gl(device) => mln_gl::exported_target::sync_kinds(device),
1101 #[cfg(has_d3d12)]
1102 Device::D3d12(_) => mln_d3d12::exported_target::sync_kinds(),
1103 _ => (SyncKinds::NONE, SyncKinds::NONE),
1104 }
1105 }
1106
1107 pub fn for_exported_ring(ring: &ExportedRing) -> Result<Device, Error> {
1113 #[cfg(target_family = "wasm")]
1114 {
1115 let _ = ring;
1116 Err(Error::unsupported("the browser has no library devices"))
1117 }
1118 #[cfg(not(target_family = "wasm"))]
1119 {
1120 let mut error = Error::unsupported("no backend of this build exports the ring's kinds of image");
1121 for backend in Self::native_order() {
1122 match Self::with_backend(*backend, DeviceOptions::default()) {
1123 Ok(device) => match device.export_plan(ring) {
1124 Ok(_) => return Ok(device),
1125 Err(e) => error = e,
1126 },
1127 Err(e) if missing(&e) => {}
1128 Err(e) => return Err(e),
1129 }
1130 }
1131 Err(error)
1132 }
1133 }
1134
1135 #[must_use]
1139 pub fn presents_to_host_surfaces(&self) -> bool {
1140 match self {
1141 #[cfg(has_vulkan)]
1142 Device::Vulkan(device) => device.presents(),
1143 #[cfg(has_native_gl)]
1144 Device::Gl(device) => device.is_host(),
1145 _ => false,
1146 }
1147 }
1148
1149 #[must_use]
1153 pub fn presents_to(&self, surface: SurfaceType) -> bool {
1154 if !surface.presents_with(self.backend()) {
1155 return false;
1156 }
1157 match self {
1158 #[cfg(has_vulkan)]
1159 Device::Vulkan(device) => {
1160 backends::vulkan::surface_extension(surface).is_some_and(|name| device.presents_through(name))
1161 }
1162 _ => true,
1163 }
1164 }
1165
1166 #[cfg(not(target_family = "wasm"))]
1169 fn native_order() -> &'static [BackendType] {
1170 if cfg!(target_os = "macos") {
1171 &[BackendType::Metal, BackendType::Vulkan, BackendType::OpenGL, BackendType::WebGPU]
1172 } else if cfg!(target_vendor = "apple") {
1173 &[BackendType::Metal, BackendType::WebGPU]
1174 } else if cfg!(windows) {
1175 &[BackendType::Vulkan, BackendType::D3D12, BackendType::OpenGL, BackendType::WebGPU]
1176 } else {
1177 &[BackendType::Vulkan, BackendType::OpenGL, BackendType::WebGPU]
1178 }
1179 }
1180
1181 #[must_use]
1183 pub fn backend(&self) -> BackendType {
1184 match *self {
1185 #[cfg(feature = "webgpu")]
1186 Device::WebGpu(_) => BackendType::WebGPU,
1187 #[cfg(has_metal)]
1188 Device::Metal(_) => BackendType::Metal,
1189 #[cfg(has_vulkan)]
1190 Device::Vulkan(_) => BackendType::Vulkan,
1191 #[cfg(has_d3d12)]
1192 Device::D3d12(_) => BackendType::D3D12,
1193 #[cfg(has_native_gl)]
1194 Device::Gl(_) => BackendType::OpenGL,
1195 #[cfg(has_webgl)]
1196 Device::WebGl(_) => BackendType::OpenGL,
1197 }
1198 }
1199}