Skip to main content

mln_runtime/render/backends/
vulkan.rs

1//! Vulkan backend glue for targets, rings, surfaces, and devices.
2
3use std::ffi::CStr;
4use std::sync::Arc;
5
6use mln_gfx::{ExportKind, ExportedRing, RendererBackend as _, SyncKind, SyncKinds, Window};
7use mln_style::error::Error;
8
9use crate::render::gfx_error;
10use crate::render::local::{
11    BackendRef, Borrowed, Exported, FramesInit, Gfx, LocalBackend, Target, gfx, no_surface, overlay_of, presenting,
12};
13use crate::render::target::{
14    Adapter, BorrowedRing, DepthStencilFormat, Device, FrameDepth, FrameTexture, FrameTextureKind, NativeTexture,
15    RingKind, Surface, SurfaceKind, SurfaceOverlay, SurfaceType,
16};
17
18impl BorrowedRing {
19    /// A ring of the host's Vulkan images.
20    #[must_use]
21    pub fn vulkan(images: mln_vulkan::BorrowedImages) -> BorrowedRing {
22        BorrowedRing { kind: RingKind::Vulkan(images) }
23    }
24}
25
26impl Surface {
27    /// The host's `VkSurfaceKHR`, which a session on the Vulkan device
28    /// whose instance made it presents to. The surface stays the host's.
29    #[must_use]
30    pub fn vulkan(surface: mln_vulkan::HostSurface) -> Surface {
31        Surface::of(SurfaceKind::Vulkan(surface))
32    }
33}
34
35pub(in super::super) fn native_texture(
36    image: u64,
37    view: u64,
38    format: i32,
39    layout: i32,
40    device: &mln_vulkan::Device,
41) -> FrameTextureKind {
42    use mln_vulkan::ash::vk::Handle as _;
43    FrameTextureKind::Vulkan { image, view, device: device.raw().device.as_raw(), format, layout }
44}
45
46pub(in super::super) fn ring_depth_stencil_format(images: &mln_vulkan::BorrowedImages) -> Option<DepthStencilFormat> {
47    let depth = images.depth.as_ref()?;
48    mln_vulkan::device::depth_stencil_format(depth.format)
49}
50
51pub(in super::super) fn ring_same_texture(
52    images: &mln_vulkan::BorrowedImages,
53    slot: usize,
54    others: &mln_vulkan::BorrowedImages,
55    other_slot: usize,
56) -> bool {
57    images.images.get(slot).zip(others.images.get(other_slot)).is_some_and(|(image, other)| image.image == other.image)
58}
59
60pub(in super::super) fn ring_texture(
61    images: &mln_vulkan::BorrowedImages,
62    slot: usize,
63    device: &mln_vulkan::Device,
64) -> Option<FrameTexture> {
65    use mln_vulkan::ash::vk::Handle as _;
66    let depth = images.depth.as_ref().and_then(|depth| {
67        depth.images.get(slot).map(|image| FrameDepth {
68            texture: NativeTexture::Vulkan {
69                image: image.image.as_raw(),
70                view: image.view.as_raw(),
71                format: depth.format.as_raw(),
72                layout: depth.final_layout.as_raw(),
73            },
74            export: None,
75        })
76    });
77    images.images.get(slot).map(|image| FrameTexture {
78        size: images.size,
79        kind: FrameTextureKind::Vulkan {
80            image: image.image.as_raw(),
81            view: image.view.as_raw(),
82            device: device.raw().device.as_raw(),
83            format: images.format.as_raw(),
84            layout: images.final_layout.as_raw(),
85        },
86        native: None,
87        depth,
88    })
89}
90
91/// The Vulkan instance extension that makes the surfaces of `surface`'s type.
92pub(in super::super) fn surface_extension(surface: SurfaceType) -> Option<&'static CStr> {
93    use mln_vulkan::ash::khr;
94    match surface {
95        SurfaceType::MetalLayer => None,
96        SurfaceType::Win32 => Some(khr::win32_surface::NAME),
97        SurfaceType::Xlib => Some(khr::xlib_surface::NAME),
98        SurfaceType::Xcb => Some(khr::xcb_surface::NAME),
99        SurfaceType::Wayland => Some(khr::wayland_surface::NAME),
100        SurfaceType::AndroidNdk => Some(khr::android_surface::NAME),
101        SurfaceType::OhosNdk => Some(mln_vulkan::device::OHOS_SURFACE),
102    }
103}
104
105pub(in super::super) fn create_device(adapter: Option<Adapter>) -> Result<Device, Error> {
106    match adapter {
107        None => mln_vulkan::Device::new(None),
108        Some(Adapter::Index(index)) => mln_vulkan::Device::new(Some(index)),
109        Some(Adapter::Uuid(uuid)) => mln_vulkan::Device::with_adapter_id(mln_vulkan::AdapterId::Uuid(uuid)),
110        Some(Adapter::Luid(luid)) => mln_vulkan::Device::with_adapter_id(mln_vulkan::AdapterId::Luid(luid)),
111    }
112    .map(Device::Vulkan)
113    .map_err(gfx_error)
114}
115
116pub(in super::super) fn borrowed_sync_kinds(
117    device: &mln_vulkan::Device,
118    images: &mln_vulkan::BorrowedImages,
119) -> Result<(SyncKinds, SyncKinds), Error> {
120    images.check(device).map_err(gfx_error)?;
121    Ok(device.sync_kinds())
122}
123
124pub(in super::super) fn export_plan(
125    device: &mln_vulkan::Device,
126    ring: &ExportedRing,
127) -> Result<(ExportKind, SyncKinds, SyncKinds), Error> {
128    let kind = mln_vulkan::exported_target::plan(device, ring).map_err(gfx_error)?;
129    let (producer, consumer) = mln_vulkan::exported_target::sync_kinds(device);
130    Ok((kind, producer, consumer))
131}
132
133fn overlay(overlay: Option<SurfaceOverlay>) -> Result<Option<Box<dyn mln_vulkan::Overlay>>, Error> {
134    overlay_of(overlay, |overlay| match overlay {
135        SurfaceOverlay::Vulkan(overlay) => Ok(overlay),
136        other => Err(other),
137    })
138}
139
140impl LocalBackend for mln_vulkan::RendererBackend {
141    type RingTextures = mln_vulkan::BorrowedImages;
142
143    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures> {
144        if let RingKind::Vulkan(images) = ring { Some(images) } else { None }
145    }
146
147    fn by_type(&self) -> BackendRef<'_> {
148        BackendRef::Vulkan(self)
149    }
150
151    fn borrowed(&mut self, textures: Self::RingTextures, producer: SyncKind) -> Result<Box<dyn Borrowed<Self>>, Error> {
152        Ok(Box::new(mln_vulkan::BorrowedTarget::new(self, textures, producer).map_err(gfx_error)?))
153    }
154
155    fn exported(
156        &mut self,
157        _device: &Device,
158        ring: &ExportedRing,
159        kind: ExportKind,
160        size: mln_gfx::Size,
161        producer: SyncKind,
162    ) -> Result<Box<dyn Exported<Self>>, Error> {
163        Ok(Box::new(mln_vulkan::ExportedTarget::new(self, ring, kind, size, producer).map_err(gfx_error)?))
164    }
165
166    fn surface(
167        &mut self,
168        surface: Surface,
169        surface_overlay: Option<SurfaceOverlay>,
170        size: mln_gfx::Size,
171    ) -> Result<Target<Self>, Error> {
172        let surface_overlay = overlay(surface_overlay)?;
173        let mut target = match surface.kind {
174            SurfaceKind::Window(window) => {
175                mln_vulkan::SurfaceTarget::new(self, window, size, surface.cap_frame_rate).map_err(gfx_error)?
176            }
177            SurfaceKind::Vulkan(host) => {
178                mln_vulkan::SurfaceTarget::on_host_surface(self, host, size, surface.cap_frame_rate)
179                    .map_err(gfx_error)?
180            }
181            _ => return Err(no_surface()),
182        };
183        target.set_overlay(self.gpu(), surface_overlay);
184        Ok(Box::new(target))
185    }
186}
187
188pub(in super::super) fn new_gfx(device: &mln_vulkan::Device, init: FramesInit<'_>) -> Result<Box<dyn Gfx>, Error> {
189    gfx(mln_vulkan::RendererBackend::new(device).map_err(gfx_error)?, init)
190}
191
192pub(in super::super) fn window_surface_gfx(
193    device: &mln_vulkan::Device,
194    window: Arc<dyn Window>,
195    surface_overlay: Option<SurfaceOverlay>,
196    size: mln_gfx::Size,
197    cap_frame_rate: bool,
198) -> Result<Box<dyn Gfx>, Error> {
199    let surface_overlay = overlay(surface_overlay)?;
200    let (mut backend, mut target) =
201        mln_vulkan::SurfaceTarget::with_backend(device, window, size, cap_frame_rate).map_err(gfx_error)?;
202    target.set_overlay(backend.gpu(), surface_overlay);
203    Ok(presenting(backend, target))
204}
205
206pub(in super::super) fn host_surface_gfx(
207    device: &mln_vulkan::Device,
208    kind: SurfaceKind,
209    surface_overlay: Option<SurfaceOverlay>,
210    size: mln_gfx::Size,
211    cap_frame_rate: bool,
212) -> Result<Box<dyn Gfx>, Error> {
213    gfx(
214        mln_vulkan::RendererBackend::presenting(device).map_err(gfx_error)?,
215        FramesInit::Surface(Surface { kind, cap_frame_rate }, surface_overlay, size),
216    )
217}