#![allow(
unreachable_patterns,
irrefutable_let_patterns,
clippy::match_wildcard_for_single_variants,
reason = "the backends' variants depend on the build's features and target"
)]
use std::sync::Arc;
use mln_gfx::Window;
pub use mln_gfx::backend::Type as BackendType;
pub use mln_gfx::{
ConsumerSync, DepthStencilFormat, DepthStencilFormats, DmaBufFormat, DmaBufPlane, ExportKind, ExportKinds,
ExportedImage, ExportedRing, FrameDepth, GpuSync, NativeTexture, SyncKind, SyncKinds,
};
use mln_util::error::Error;
use mln_util::size::Size;
pub type Wake = Arc<dyn Fn() + Send + Sync>;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Driver {
#[default]
CoreWorker,
CallerThread,
}
#[derive(Clone, Default)]
pub struct AttachOptions {
pub driver: Driver,
pub frame_wake: Option<Wake>,
pub redraw_wake: Option<Wake>,
pub driver_work_wake: Option<Wake>,
pub producer_sync_kinds: SyncKinds,
}
impl std::fmt::Debug for AttachOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AttachOptions")
.field("driver", &self.driver)
.field("frame_wake", &self.frame_wake.is_some())
.field("redraw_wake", &self.redraw_wake.is_some())
.field("driver_work_wake", &self.driver_work_wake.is_some())
.field("producer_sync_kinds", &self.producer_sync_kinds)
.finish()
}
}
#[derive(Debug)]
pub enum RenderTarget {
Offscreen { size: Size, device: Option<Device> },
Surface { size: Size, surface: Surface, device: Option<Device> },
Borrowed { size: Size, ring: BorrowedRing, device: Device },
Exported { size: Size, ring: ExportedRing, device: Option<Device> },
}
#[derive(Clone, Debug, PartialEq)]
pub struct BorrowedRing {
pub(crate) kind: RingKind,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum RingKind {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Vulkan(mln_vulkan::BorrowedImages),
#[cfg(all(feature = "metal", target_vendor = "apple"))]
Metal(mln_mtl::BorrowedTextures),
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
Gl(mln_gl::BorrowedTextures),
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
WebGpu(mln_webgpu::BorrowedTextures),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FrameTexture {
pub size: Size,
pub kind: FrameTextureKind,
pub native: Option<FrameTextureKind>,
pub depth: Option<FrameDepth>,
}
impl FrameTexture {
#[must_use]
pub fn native_kind(&self) -> Option<&FrameTextureKind> {
match &self.kind {
FrameTextureKind::Exported(_) => self.native.as_ref(),
kind => Some(kind),
}
}
pub(crate) fn exported(frame: mln_gfx::ExportedFrame, device: &Device) -> FrameTexture {
FrameTexture {
size: frame.size,
kind: FrameTextureKind::Exported(frame.image),
native: native_kind(frame.texture, device),
depth: frame.depth,
}
}
}
fn native_kind(texture: NativeTexture, device: &Device) -> Option<FrameTextureKind> {
match (texture, device) {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
(NativeTexture::Vulkan { image, view, format, layout }, Device::Vulkan(device)) => {
use mln_vulkan::ash::vk::Handle as _;
Some(FrameTextureKind::Vulkan { image, view, device: device.raw().device.as_raw(), format, layout })
}
#[cfg(all(feature = "metal", target_vendor = "apple"))]
(NativeTexture::Metal { texture, pixel_format }, Device::Metal(device)) => Some(FrameTextureKind::Metal {
texture,
device: mln_mtl::objc2::rc::Retained::as_ptr(device.device()) as usize as u64,
pixel_format,
}),
(NativeTexture::OpenGl { texture, target, .. }, _) => Some(FrameTextureKind::OpenGl { texture, target }),
_ => None,
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FrameTextureKind {
Vulkan { image: u64, view: u64, device: u64, format: i32, layout: i32 },
Metal { texture: u64, device: u64, pixel_format: u64 },
OpenGl { texture: u32, target: u32 },
WebGpu,
Exported(ExportedImage),
}
impl BorrowedRing {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
#[must_use]
pub fn vulkan(images: mln_vulkan::BorrowedImages) -> BorrowedRing {
BorrowedRing { kind: RingKind::Vulkan(images) }
}
#[cfg(all(feature = "metal", target_vendor = "apple"))]
#[must_use]
pub fn metal(textures: mln_mtl::BorrowedTextures) -> BorrowedRing {
BorrowedRing { kind: RingKind::Metal(textures) }
}
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
#[must_use]
pub fn gl(textures: mln_gl::BorrowedTextures) -> BorrowedRing {
BorrowedRing { kind: RingKind::Gl(textures) }
}
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
#[must_use]
pub fn webgpu(textures: mln_webgpu::BorrowedTextures) -> BorrowedRing {
BorrowedRing { kind: RingKind::WebGpu(textures) }
}
#[must_use]
pub fn backend(&self) -> BackendType {
match self.kind {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
RingKind::Vulkan(_) => BackendType::Vulkan,
#[cfg(all(feature = "metal", target_vendor = "apple"))]
RingKind::Metal(_) => BackendType::Metal,
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
RingKind::Gl(_) => BackendType::OpenGL,
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
RingKind::WebGpu(_) => BackendType::WebGPU,
_ => BackendType::WebGPU,
}
}
#[must_use]
pub fn depth(&self) -> usize {
match &self.kind {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
RingKind::Vulkan(images) => images.images.len(),
#[cfg(all(feature = "metal", target_vendor = "apple"))]
RingKind::Metal(textures) => textures.textures.len(),
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
RingKind::Gl(textures) => textures.textures.len(),
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
RingKind::WebGpu(textures) => textures.textures.len(),
_ => 0,
}
}
#[must_use]
pub fn physical_size(&self) -> Size {
match &self.kind {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
RingKind::Vulkan(images) => images.size,
#[cfg(all(feature = "metal", target_vendor = "apple"))]
RingKind::Metal(textures) => textures.size,
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
RingKind::Gl(textures) => textures.size,
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
RingKind::WebGpu(textures) => textures.size,
_ => Size::default(),
}
}
#[must_use]
pub fn takes_depth_on(&self, device: &Device) -> bool {
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
if let RingKind::Gl(_) = self.kind {
return true;
}
!self.has_depth()
|| self.depth_stencil_format().is_some_and(|format| device.depth_stencil_formats().contains(format))
}
#[must_use]
pub fn depth_stencil_format(&self) -> Option<DepthStencilFormat> {
match &self.kind {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
RingKind::Vulkan(images) => {
images.depth.as_ref().and_then(|depth| mln_vulkan::device::depth_stencil_format(depth.format))
}
#[cfg(all(feature = "metal", target_vendor = "apple"))]
RingKind::Metal(textures) => (textures.depth_pixel_format()
== Some(mln_mtl::objc2_metal::MTLPixelFormat::Depth32Float_Stencil8))
.then_some(DepthStencilFormat::Depth32FloatStencil8),
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
RingKind::WebGpu(textures) => {
textures.depth_textures.first().and_then(|texture| mln_webgpu::depth_stencil_format(texture.format()))
}
_ => None,
}
}
#[must_use]
pub fn has_depth(&self) -> bool {
match &self.kind {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
RingKind::Vulkan(images) => images.depth.is_some(),
#[cfg(all(feature = "metal", target_vendor = "apple"))]
RingKind::Metal(textures) => !textures.depth_textures.is_empty(),
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
RingKind::Gl(textures) => !textures.depth_textures.is_empty(),
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
RingKind::WebGpu(textures) => !textures.depth_textures.is_empty(),
_ => false,
}
}
#[cfg_attr(target_family = "wasm", expect(unused_variables, reason = "the browser build borrows no ring"))]
pub(crate) fn same_texture(&self, slot: usize, other: &BorrowedRing, other_slot: usize) -> bool {
match (&self.kind, &other.kind) {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
(RingKind::Vulkan(images), RingKind::Vulkan(others)) => images
.images
.get(slot)
.zip(others.images.get(other_slot))
.is_some_and(|(image, other)| image.image == other.image),
#[cfg(all(feature = "metal", target_vendor = "apple"))]
(RingKind::Metal(textures), RingKind::Metal(others)) => {
textures.textures.get(slot).zip(others.textures.get(other_slot)).is_some_and(|(texture, other)| {
std::ptr::eq(
mln_mtl::objc2::rc::Retained::as_ptr(texture),
mln_mtl::objc2::rc::Retained::as_ptr(other),
)
})
}
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
(RingKind::Gl(textures), RingKind::Gl(others)) => {
textures.textures.get(slot).is_some_and(|texture| others.textures.get(other_slot) == Some(texture))
}
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
(RingKind::WebGpu(textures), RingKind::WebGpu(others)) => {
textures.textures.get(slot).is_some_and(|texture| others.textures.get(other_slot) == Some(texture))
}
_ => false,
}
}
#[cfg_attr(target_family = "wasm", expect(unused_variables, reason = "the browser build borrows no ring"))]
#[must_use]
pub fn texture(&self, slot: usize, device: &Device) -> Option<FrameTexture> {
match (&self.kind, device) {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
(RingKind::Vulkan(images), Device::Vulkan(device)) => {
use mln_vulkan::ash::vk::Handle as _;
let depth = images.depth.as_ref().and_then(|depth| {
depth.images.get(slot).map(|image| FrameDepth {
texture: NativeTexture::Vulkan {
image: image.image.as_raw(),
view: image.view.as_raw(),
format: depth.format.as_raw(),
layout: depth.final_layout.as_raw(),
},
export: None,
})
});
images.images.get(slot).map(|image| FrameTexture {
size: images.size,
kind: FrameTextureKind::Vulkan {
image: image.image.as_raw(),
view: image.view.as_raw(),
device: device.raw().device.as_raw(),
format: images.format.as_raw(),
layout: images.final_layout.as_raw(),
},
native: None,
depth,
})
}
#[cfg(all(feature = "metal", target_vendor = "apple"))]
(RingKind::Metal(textures), Device::Metal(device)) => {
use mln_mtl::objc2::rc::Retained;
textures.textures.get(slot).map(|texture| FrameTexture {
size: textures.size,
kind: FrameTextureKind::Metal {
texture: Retained::as_ptr(texture) as usize as u64,
device: Retained::as_ptr(device.device()) as usize as u64,
pixel_format: textures.pixel_format().0 as u64,
},
native: None,
depth: textures.depth_textures.get(slot).zip(textures.depth_pixel_format()).map(
|(depth, pixel_format)| FrameDepth {
texture: NativeTexture::Metal {
texture: Retained::as_ptr(depth) as usize as u64,
pixel_format: pixel_format.0 as u64,
},
export: None,
},
),
})
}
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
(RingKind::Gl(textures), Device::Gl(_)) => textures.textures.get(slot).map(|&texture| FrameTexture {
size: textures.size,
kind: FrameTextureKind::OpenGl { texture, target: 0x0DE1 },
native: None,
depth: textures.depth_textures.get(slot).map(|&depth| FrameDepth {
texture: NativeTexture::OpenGl { texture: depth, target: 0x0DE1, internal_format: 0 },
export: None,
}),
}),
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
(RingKind::WebGpu(textures), Device::WebGpu(_)) => textures.textures.get(slot).map(|_| FrameTexture {
size: textures.size,
kind: FrameTextureKind::WebGpu,
native: None,
depth: (!textures.depth_textures.is_empty())
.then_some(FrameDepth { texture: NativeTexture::WebGpu, export: None }),
}),
_ => None,
}
}
}
pub struct Surface {
pub(crate) kind: SurfaceKind,
pub(crate) overlay: Option<mln_actor::LocalObject<std::cell::Cell<Option<SurfaceOverlay>>>>,
}
pub enum SurfaceOverlay {
#[cfg(feature = "webgpu")]
WebGpu(mln_webgpu::Overlay),
#[cfg(all(feature = "metal", target_vendor = "apple"))]
Metal(mln_mtl::surface_target::Overlay),
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Vulkan(Box<dyn mln_vulkan::Overlay>),
#[cfg(all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))))]
Gl(mln_gl::Overlay),
}
pub(crate) enum SurfaceKind {
Window(Arc<dyn Window>),
#[cfg(all(feature = "metal", target_vendor = "apple"))]
MetalLayer(mln_mtl::Layer),
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
Wgpu(wgpu::Surface<'static>),
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Vulkan(mln_vulkan::HostSurface),
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
Gl(mln_gl::HostSurface),
#[cfg(target_family = "wasm")]
WebCanvas {
canvas: mln_actor::LocalObject<wasm_bindgen::JsValue>,
#[cfg_attr(not(feature = "webgpu"), expect(dead_code, reason = "only WebGPU configures the canvas's format"))]
format: Option<CanvasFormat>,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CanvasFormat {
Bgra8Unorm,
Rgba8Unorm,
Rgba16Float,
}
impl CanvasFormat {
#[must_use]
pub fn from_name(name: &str) -> Option<CanvasFormat> {
match name {
"bgra8unorm" => Some(CanvasFormat::Bgra8Unorm),
"rgba8unorm" => Some(CanvasFormat::Rgba8Unorm),
"rgba16float" => Some(CanvasFormat::Rgba16Float),
_ => None,
}
}
}
impl Surface {
pub fn window(window: impl Window + 'static) -> Surface {
Surface { kind: SurfaceKind::Window(Arc::new(window)), overlay: None }
}
#[cfg(target_family = "wasm")]
pub fn web_canvas(canvas: wasm_bindgen::JsValue, format: Option<CanvasFormat>) -> Result<Surface, Error> {
use wasm_bindgen::JsCast as _;
if !canvas.is_instance_of::<web_sys::OffscreenCanvas>()
&& !canvas.is_instance_of::<web_sys::HtmlCanvasElement>()
{
return Err(Error::invalid_argument("a web canvas is an OffscreenCanvas or an HTMLCanvasElement"));
}
Ok(Surface {
kind: SurfaceKind::WebCanvas { canvas: mln_actor::LocalObject::new(canvas), format },
overlay: None,
})
}
#[cfg(target_family = "wasm")]
pub(crate) fn presents_with_web_gpu(&self) -> bool {
matches!(self.kind, SurfaceKind::WebCanvas { .. }) && cfg!(feature = "webgpu")
}
#[cfg(all(feature = "metal", target_vendor = "apple"))]
#[must_use]
pub fn metal_layer(layer: mln_mtl::Layer) -> Surface {
Surface { kind: SurfaceKind::MetalLayer(layer), overlay: None }
}
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
pub fn wgpu(surface: wgpu::Surface<'static>) -> Surface {
Surface { kind: SurfaceKind::Wgpu(surface), overlay: None }
}
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
#[must_use]
pub fn vulkan(surface: mln_vulkan::HostSurface) -> Surface {
Surface { kind: SurfaceKind::Vulkan(surface), overlay: None }
}
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
#[must_use]
pub fn gl(surface: mln_gl::HostSurface) -> Surface {
Surface { kind: SurfaceKind::Gl(surface), overlay: None }
}
#[must_use]
pub fn with_overlay(self, overlay: SurfaceOverlay) -> Surface {
Surface { overlay: Some(mln_actor::LocalObject::new(std::cell::Cell::new(Some(overlay)))), ..self }
}
pub(crate) fn take_overlay(&mut self) -> Result<Option<SurfaceOverlay>, Error> {
let Some(overlay) = self.overlay.take() else { return Ok(None) };
let overlay = overlay
.take()
.ok_or_else(|| Error::unsupported("a surface's overlay draws only on the thread that made it"))?;
Ok(overlay.take())
}
#[must_use]
pub fn host_backend(&self) -> Option<BackendType> {
match self.kind {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
SurfaceKind::Vulkan(_) => Some(BackendType::Vulkan),
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
SurfaceKind::Gl(_) => Some(BackendType::OpenGL),
_ => None,
}
}
pub(crate) fn clone_window(&self) -> Option<Surface> {
match &self.kind {
SurfaceKind::Window(window) => {
Some(Surface { kind: SurfaceKind::Window(Arc::clone(window)), overlay: None })
}
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
SurfaceKind::Gl(surface) => Some(Surface { kind: SurfaceKind::Gl(*surface), overlay: None }),
_ => None,
}
}
pub(crate) fn check_area(&self) -> Result<(), Error> {
if let SurfaceKind::Window(window) = &self.kind
&& !mln_gfx::window::has_area(&**window)
{
return Err(Error::invalid_state("the window is minimized or has no client area"));
}
Ok(())
}
#[cfg_attr(
not(all(feature = "gl", windows)),
expect(clippy::unnecessary_wraps, reason = "only OpenGL on Windows checks the window's pixel format")
)]
pub(crate) fn check_pixel_format(&self, device: Option<&Device>) -> Result<(), Error> {
#[cfg(all(feature = "gl", windows))]
if let SurfaceKind::Window(window) = &self.kind
&& device.map_or(cfg!(not(feature = "vulkan")), |device| device.backend() == BackendType::OpenGL)
{
mln_gl::SurfaceTarget::check_window(&**window)?;
}
#[cfg(not(all(feature = "gl", windows)))]
let _ = (self, device);
Ok(())
}
pub(crate) fn host_window(&self) -> Option<Arc<dyn Window>> {
match &self.kind {
SurfaceKind::Window(window) => Some(Arc::clone(window)),
_ => None,
}
}
pub(crate) fn needs_no_device(&self) -> bool {
match self.kind {
SurfaceKind::Window(_) => true,
#[cfg(all(feature = "metal", target_vendor = "apple"))]
SurfaceKind::MetalLayer(_) => true,
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
SurfaceKind::Wgpu(_) => false,
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
SurfaceKind::Vulkan(_) => false,
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
SurfaceKind::Gl(_) => false,
#[cfg(target_family = "wasm")]
SurfaceKind::WebCanvas { .. } => true,
}
}
}
impl std::fmt::Debug for Surface {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Surface").finish_non_exhaustive()
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Device {
#[cfg(feature = "webgpu")]
WebGpu(mln_webgpu::Device),
#[cfg(all(feature = "metal", target_vendor = "apple"))]
Metal(mln_mtl::Device),
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Vulkan(mln_vulkan::Device),
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
Gl(mln_gl::Device),
#[cfg(all(feature = "gl", target_family = "wasm"))]
WebGl(WebGlContext),
}
#[cfg(all(feature = "gl", target_family = "wasm"))]
#[derive(Clone, Default)]
pub struct WebGlContext(pub(crate) Option<Arc<mln_actor::LocalObject<wasm_bindgen::JsValue>>>);
#[cfg(all(feature = "gl", target_family = "wasm"))]
impl std::fmt::Debug for WebGlContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("WebGlContext").field(&self.0.is_some()).finish()
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct DeviceOptions {
pub adapter: Option<Adapter>,
pub gl_api: GlApi,
pub gl_single_context: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum GlApi {
Gles,
Gl,
}
impl Default for GlApi {
fn default() -> GlApi {
if cfg!(windows) { GlApi::Gl } else { GlApi::Gles }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Adapter {
Index(usize),
Uuid([u8; 16]),
Luid([u8; 8]),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SurfaceType {
MetalLayer,
Win32,
Xlib,
Xcb,
Wayland,
AndroidNdk,
OhosNdk,
}
impl SurfaceType {
#[must_use]
pub fn presents_with(self, backend: BackendType) -> bool {
let windowing = match self {
SurfaceType::MetalLayer => false,
SurfaceType::Win32 => cfg!(windows),
SurfaceType::Xlib | SurfaceType::Xcb | SurfaceType::Wayland => {
cfg!(all(unix, not(target_vendor = "apple"), not(target_os = "android"), not(target_env = "ohos")))
}
SurfaceType::AndroidNdk => cfg!(target_os = "android"),
SurfaceType::OhosNdk => cfg!(target_env = "ohos"),
};
match backend {
BackendType::Metal => {
cfg!(all(feature = "metal", target_vendor = "apple")) && self == SurfaceType::MetalLayer
}
BackendType::Vulkan => {
cfg!(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm")))) && windowing
}
BackendType::OpenGL => {
cfg!(all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))))
&& windowing
&& matches!(
self,
SurfaceType::Win32
| SurfaceType::Xlib
| SurfaceType::Wayland
| SurfaceType::AndroidNdk
| SurfaceType::OhosNdk
)
}
BackendType::WebGPU => {
cfg!(all(feature = "webgpu", not(target_family = "wasm"))) && windowing && self != SurfaceType::OhosNdk
}
_ => false,
}
}
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
fn vulkan_extension(self) -> Option<&'static std::ffi::CStr> {
use mln_vulkan::ash::khr;
match self {
SurfaceType::MetalLayer => None,
SurfaceType::Win32 => Some(khr::win32_surface::NAME),
SurfaceType::Xlib => Some(khr::xlib_surface::NAME),
SurfaceType::Xcb => Some(khr::xcb_surface::NAME),
SurfaceType::Wayland => Some(khr::wayland_surface::NAME),
SurfaceType::AndroidNdk => Some(khr::android_surface::NAME),
SurfaceType::OhosNdk => Some(mln_vulkan::device::OHOS_SURFACE),
}
}
#[must_use]
pub fn presents_with_any(self) -> bool {
[BackendType::Metal, BackendType::Vulkan, BackendType::OpenGL, BackendType::WebGPU]
.into_iter()
.any(|backend| self.presents_with(backend))
}
#[must_use]
pub fn presents_without_device(self) -> bool {
match self {
SurfaceType::MetalLayer => self.presents_with(BackendType::Metal),
_ if cfg!(target_vendor = "apple") => self.presents_with(BackendType::WebGPU),
_ => [BackendType::Vulkan, BackendType::OpenGL, BackendType::WebGPU]
.into_iter()
.any(|backend| self.presents_with(backend)),
}
}
}
#[cfg(not(target_family = "wasm"))]
fn missing(error: &Error) -> bool {
error.kind == mln_util::ErrorKind::Unsupported
}
#[derive(Debug, Default)]
pub(crate) struct DeviceLease {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
queue: Option<mln_vulkan::QueueLease>,
}
impl DeviceLease {
#[cfg_attr(
not(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm")))),
expect(clippy::unused_self, reason = "only a Vulkan device holds the host's queue lock")
)]
pub(crate) fn revoke(&self) {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
if let Some(queue) = &self.queue {
queue.revoke();
}
}
}
impl Device {
pub(crate) fn lease(self) -> (Device, DeviceLease) {
match self {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Device::Vulkan(device) => {
let (device, queue) = device.lease();
(Device::Vulkan(device), DeviceLease { queue: Some(queue) })
}
device => (device, DeviceLease::default()),
}
}
pub(crate) fn lost(&self) -> Option<Error> {
match *self {
#[cfg(feature = "webgpu")]
Device::WebGpu(ref device) => device.lost().map(|message| Error::target_lost(message.to_owned())),
_ => None,
}
}
pub(crate) fn abandon_keeps_graphics(&self) -> bool {
match *self {
#[cfg(feature = "webgpu")]
Device::WebGpu(_) => true,
#[cfg(all(feature = "metal", target_vendor = "apple"))]
Device::Metal(_) => false,
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Device::Vulkan(_) => false,
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
Device::Gl(_) => true,
#[cfg(all(feature = "gl", target_family = "wasm"))]
Device::WebGl(_) => true,
}
}
pub fn new(options: DeviceOptions) -> Result<Device, Error> {
#[cfg(target_family = "wasm")]
{
let _ = options;
Err(Error::unsupported("the browser has no library devices"))
}
#[cfg(not(target_family = "wasm"))]
{
let mut error = Error::unsupported("this build has no backend");
for backend in Self::native_order() {
match Self::with_backend(*backend, options) {
Ok(device) => return Ok(device),
Err(e) if missing(&e) => error = e,
Err(e) => return Err(e),
}
}
Err(error)
}
}
pub fn with_backend(backend: BackendType, options: DeviceOptions) -> Result<Device, Error> {
let DeviceOptions { adapter, gl_api, gl_single_context } = options;
let index = |adapter: Option<Adapter>| match adapter {
None => Ok(None),
Some(Adapter::Index(index)) => Ok(Some(index)),
Some(_) => Err(Error::unsupported(format!("{backend:?} names no GPU by UUID or LUID"))),
};
match backend {
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
BackendType::WebGPU => mln_webgpu::Device::new(index(adapter)?).map(Device::WebGpu),
#[cfg(all(feature = "metal", target_vendor = "apple"))]
BackendType::Metal => mln_mtl::Device::new(index(adapter)?).map(Device::Metal),
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
BackendType::Vulkan => match adapter {
Some(Adapter::Uuid(uuid)) => mln_vulkan::Device::with_adapter_id(mln_vulkan::AdapterId::Uuid(uuid)),
Some(Adapter::Luid(luid)) => mln_vulkan::Device::with_adapter_id(mln_vulkan::AdapterId::Luid(luid)),
_ => mln_vulkan::Device::new(index(adapter)?),
}
.map(Device::Vulkan),
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
BackendType::OpenGL => {
match index(adapter)? {
None | Some(0) => {}
Some(index) => {
return Err(Error::not_found(format!("adapter_index {index} is past OpenGL's one GPU")));
}
}
let api = match gl_api {
GlApi::Gles => mln_gl::Api::Gles,
GlApi::Gl => mln_gl::Api::Gl,
};
let options = mln_gl::DeviceOptions { api, single_context: gl_single_context };
mln_gl::Device::with_options(options).map(Device::Gl)
}
#[cfg(all(feature = "gl", target_family = "wasm"))]
BackendType::OpenGL if adapter.is_none() => Ok(Device::WebGl(WebGlContext::default())),
_ => {
let _ = (index, adapter, gl_api, gl_single_context);
Err(Error::unsupported(format!("this build has no {backend:?} backend")))
}
}
}
pub fn borrowed_sync_kinds(&self, ring: &BorrowedRing) -> Result<(SyncKinds, SyncKinds), Error> {
match (self, &ring.kind) {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
(Device::Vulkan(device), RingKind::Vulkan(images)) => {
images.check(device)?;
Ok(device.sync_kinds())
}
#[cfg(all(feature = "metal", target_vendor = "apple"))]
(Device::Metal(device), RingKind::Metal(textures)) => {
textures.check(device)?;
Ok(mln_mtl::BorrowedTextures::sync_kinds(device))
}
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
(Device::Gl(device), RingKind::Gl(_)) => {
if !device.is_host() {
return Err(Error::unsupported(
"an OpenGL ring renders on a device in the share group of the host's context",
));
}
Ok(mln_gl::BorrowedTextures::sync_kinds())
}
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
(Device::WebGpu(_), RingKind::WebGpu(textures)) => {
textures.check()?;
Ok(mln_webgpu::BorrowedTextures::sync_kinds())
}
_ => Err(Error::unsupported(format!(
"a {:?} device renders into no ring of {:?} textures",
self.backend(),
ring.backend()
))),
}
}
#[must_use]
pub fn depth_stencil_formats(&self) -> DepthStencilFormats {
match *self {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Device::Vulkan(ref device) => device.depth_stencil_formats(),
#[cfg(all(feature = "metal", target_vendor = "apple"))]
Device::Metal(_) => mln_mtl::BorrowedTextures::depth_stencil_formats(),
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
Device::Gl(_) => mln_gl::BorrowedTextures::depth_stencil_formats(),
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
Device::WebGpu(ref device) => mln_webgpu::BorrowedTextures::depth_stencil_formats(device.device()),
#[cfg(target_family = "wasm")]
_ => DepthStencilFormats::NONE,
}
}
#[must_use]
pub fn depth_export_kinds(&self) -> ExportKinds {
match self {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Device::Vulkan(device) => device.depth_export_kinds(),
_ => ExportKinds::NONE,
}
}
#[must_use]
pub fn export_kinds(&self) -> ExportKinds {
match self {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Device::Vulkan(device) => device.export_kinds(),
#[cfg(all(feature = "metal", target_vendor = "apple"))]
Device::Metal(device) => mln_mtl::exported_target::export_kinds(device),
#[cfg(all(feature = "gl", unix, not(target_vendor = "apple")))]
Device::Gl(device) => mln_gl::exported_target::export_kinds(device),
_ => ExportKinds::NONE,
}
}
pub fn export_plan(&self, ring: &ExportedRing) -> Result<(ExportKind, SyncKinds, SyncKinds), Error> {
match self {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Device::Vulkan(device) => {
let kind = mln_vulkan::exported_target::plan(device, ring)?;
let (producer, consumer) = mln_vulkan::exported_target::sync_kinds(device);
Ok((kind, producer, consumer))
}
#[cfg(all(feature = "metal", target_vendor = "apple"))]
Device::Metal(device) => {
let kind = mln_mtl::exported_target::plan(device, ring)?;
let (producer, consumer) = mln_mtl::exported_target::sync_kinds(device);
Ok((kind, producer, consumer))
}
#[cfg(all(feature = "gl", unix, not(target_vendor = "apple")))]
Device::Gl(device) => {
let kind = mln_gl::exported_target::plan(device, ring)?;
let (producer, consumer) = mln_gl::exported_target::sync_kinds(device);
Ok((kind, producer, consumer))
}
_ => {
let _ = ring;
Err(Error::unsupported(format!("a {:?} device exports no ring", self.backend())))
}
}
}
#[must_use]
pub fn export_sync_kinds(&self) -> (SyncKinds, SyncKinds) {
if self.export_kinds().is_empty() {
return (SyncKinds::NONE, SyncKinds::NONE);
}
match self {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Device::Vulkan(device) => mln_vulkan::exported_target::sync_kinds(device),
#[cfg(all(feature = "metal", target_vendor = "apple"))]
Device::Metal(device) => mln_mtl::exported_target::sync_kinds(device),
#[cfg(all(feature = "gl", unix, not(target_vendor = "apple")))]
Device::Gl(device) => mln_gl::exported_target::sync_kinds(device),
_ => (SyncKinds::NONE, SyncKinds::NONE),
}
}
pub fn for_exported_ring(ring: &ExportedRing) -> Result<Device, Error> {
#[cfg(target_family = "wasm")]
{
let _ = ring;
Err(Error::unsupported("the browser has no library devices"))
}
#[cfg(not(target_family = "wasm"))]
{
let mut error = Error::unsupported("no backend of this build exports the ring's kinds of image");
for backend in Self::native_order() {
match Self::with_backend(*backend, DeviceOptions::default()) {
Ok(device) => match device.export_plan(ring) {
Ok(_) => return Ok(device),
Err(e) => error = e,
},
Err(e) if missing(&e) => {}
Err(e) => return Err(e),
}
}
Err(error)
}
}
#[must_use]
pub fn presents_to_host_surfaces(&self) -> bool {
match self {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Device::Vulkan(device) => device.presents(),
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
Device::Gl(device) => device.is_host(),
_ => false,
}
}
#[must_use]
pub fn presents_to(&self, surface: SurfaceType) -> bool {
if !surface.presents_with(self.backend()) {
return false;
}
match self {
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Device::Vulkan(device) => surface.vulkan_extension().is_some_and(|name| device.presents_through(name)),
_ => true,
}
}
#[cfg(not(target_family = "wasm"))]
fn native_order() -> &'static [BackendType] {
if cfg!(target_vendor = "apple") {
&[BackendType::Metal, BackendType::WebGPU]
} else {
&[BackendType::Vulkan, BackendType::OpenGL, BackendType::WebGPU]
}
}
#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
#[must_use]
pub fn webgpu(
instance: wgpu::Instance,
device: wgpu::Device,
queue: wgpu::Queue,
format: wgpu::TextureFormat,
) -> Device {
Device::WebGpu(mln_webgpu::Device::from_wgpu(Some(instance), device, queue, Some(format)))
}
#[must_use]
pub fn backend(&self) -> BackendType {
match *self {
#[cfg(feature = "webgpu")]
Device::WebGpu(_) => BackendType::WebGPU,
#[cfg(all(feature = "metal", target_vendor = "apple"))]
Device::Metal(_) => BackendType::Metal,
#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
Device::Vulkan(_) => BackendType::Vulkan,
#[cfg(all(feature = "gl", not(target_family = "wasm")))]
Device::Gl(_) => BackendType::OpenGL,
#[cfg(all(feature = "gl", target_family = "wasm"))]
Device::WebGl(_) => BackendType::OpenGL,
}
}
#[cfg(all(feature = "gl", target_family = "wasm"))]
pub fn web_gl(context: wasm_bindgen::JsValue) -> Result<Device, Error> {
if !wasm_bindgen::JsCast::is_instance_of::<web_sys::WebGl2RenderingContext>(&context) {
return Err(Error::invalid_argument("a WebGL device wraps a WebGL2RenderingContext"));
}
Ok(Device::WebGl(WebGlContext(Some(Arc::new(mln_actor::LocalObject::new(context))))))
}
#[cfg(all(feature = "webgpu", target_family = "wasm"))]
pub async fn request_web_gpu() -> Result<Device, Error> {
mln_webgpu::Device::request().await.map(Device::WebGpu)
}
}