Skip to main content

lactea_host/
vulkan.rs

1//! Vulkan interop: run lactea on the host's own `VkDevice` and render into host `VkImage`s.
2//!
3//! wgpu cannot adopt a foreign image on a device of its own, so the engine has to *be* on the host's
4//! device. The host keeps creating the `VkInstance` and `VkDevice`; lactea only wraps the handles
5//! through `wgpu::hal::vulkan` and never destroys them. Only raw Vulkan handles cross this API, so the
6//! host may use any Vulkan binding, or a wgpu of another major version (its `as_hal::<Vulkan>()`
7//! gives the handles).
8//!
9//! The contract, in order:
10//!
11//! 1. Create the `VkInstance` with `apiVersion` >= 1.1 *and* >= the version the physical device
12//!    reports (`vkEnumerateInstanceVersion` is always safe: wgpu assumes the device exposes every
13//!    core version it reports, and a lower instance version hides those functions; [`open_device`]
14//!    checks this and refuses), plus the extension `VK_KHR_get_physical_device_properties2` (wgpu
15//!    assumes it is on whenever it exists).
16//! 2. [`requirements`] lists the device extensions wgpu needs and a `VkPhysicalDeviceFeatures` +
17//!    `pNext` feature chain. Create the `VkDevice` with them (add your own extensions and features;
18//!    chain your own structs in front of the `pNext` chain). A device created by wgpu itself already
19//!    has them unless that wgpu needs fewer extensions than this one: [`open_device`] names the
20//!    first one missing.
21//! 3. [`open_device`] wraps the device as a `wgpu::Device` + `wgpu::Queue` for `lactea::Engine`.
22//! 4. Every frame, [`wrap_image`] turns the host's `VkImage` into a `wgpu::Texture` to render into.
23//!
24//! Layout and synchronisation: lactea submits to the host's queue (`queue_family_index` /
25//! `queue_index`, externally synchronised like any queue: do not submit to it from another thread at
26//! the same time). The image may be in any layout and its contents are discarded; after the
27//! submission it is in `VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL` with the colour writes finished
28//! once the work has executed. On the same queue a pipeline barrier (`COLOR_ATTACHMENT_OUTPUT` ->
29//! whatever comes next) is enough. Drop the engine and the wrapped device before the `VkDevice`, and
30//! keep each image alive until the work rendering into it has executed.
31//!
32//! Present where wgpu has a Vulkan backend: Windows and non-Apple Unix.
33
34use std::ffi::{CStr, c_void};
35
36use ash::vk::{self, Handle};
37use wgpu::hal::api::Vulkan;
38use wgpu::hal::vulkan as hal;
39
40/// `VK_FORMAT_R8G8B8A8_UNORM`.
41pub const VK_FORMAT_R8G8B8A8_UNORM: u32 = 37;
42/// `VK_FORMAT_B8G8R8A8_UNORM`.
43pub const VK_FORMAT_B8G8R8A8_UNORM: u32 = 44;
44
45/// The image formats lactea renders into, by `VkFormat`; `None` for any other.
46pub fn format_from_vk(vk_format: u32) -> Option<wgpu::TextureFormat> {
47    match vk_format {
48        VK_FORMAT_R8G8B8A8_UNORM => Some(wgpu::TextureFormat::Rgba8Unorm),
49        VK_FORMAT_B8G8R8A8_UNORM => Some(wgpu::TextureFormat::Bgra8Unorm),
50        _ => None,
51    }
52}
53
54/// The host's Vulkan objects. Dispatchable handles are pointers, extension names exactly as given
55/// to `vkCreateInstance` / `vkCreateDevice`.
56#[derive(Clone, Copy, Debug)]
57pub struct VulkanHost<'a> {
58    /// `vkGetInstanceProcAddr` of the loader the host uses, cast to a data pointer.
59    pub get_instance_proc_addr: *const c_void,
60    /// `VkInstance`.
61    pub instance: *mut c_void,
62    /// `VkPhysicalDevice` the device was (or will be) created on.
63    pub physical_device: *mut c_void,
64    /// `VkDevice`. Not read by [`requirements`].
65    pub device: *mut c_void,
66    /// Queue family and index lactea submits to (a family with graphics support, requested in
67    /// `vkCreateDevice`). Not read by [`requirements`].
68    pub queue_family_index: u32,
69    pub queue_index: u32,
70    /// `VkApplicationInfo::apiVersion` the instance was created with (0 = 1.0).
71    pub api_version: u32,
72    /// Instance extensions enabled by the host.
73    pub instance_extensions: &'a [&'a CStr],
74    /// Device extensions enabled by the host. Not read by [`requirements`].
75    pub device_extensions: &'a [&'a CStr],
76}
77
78/// What `vkCreateDevice` needs for lactea; the pointers stay valid as long as this value.
79pub struct VulkanRequirements {
80    device_extensions: Vec<&'static CStr>,
81    enabled_features: *const c_void,
82    device_pnext: *const c_void,
83    /// Owns the structs both pointers point into (boxed: their address must not move).
84    _features: Box<hal::PhysicalDeviceFeatures>,
85}
86
87impl VulkanRequirements {
88    /// Device extension names to enable (drop the ones already on your list: Vulkan forbids
89    /// listing one twice).
90    pub fn device_extensions(&self) -> &[&'static CStr] {
91        &self.device_extensions
92    }
93
94    /// `const VkPhysicalDeviceFeatures *` for `VkDeviceCreateInfo::pEnabledFeatures`.
95    pub fn enabled_features(&self) -> *const c_void {
96        self.enabled_features
97    }
98
99    /// `const void *` feature-struct chain for `VkDeviceCreateInfo::pNext`; null when empty. Do not
100    /// combine [`Self::enabled_features`] with a `VkPhysicalDeviceFeatures2` of your own.
101    pub fn device_pnext(&self) -> *const c_void {
102        self.device_pnext
103    }
104}
105
106/// The host's instance as a wgpu-hal instance (never destroyed by lactea) and its adapter.
107unsafe fn open_instance(
108    host: &VulkanHost<'_>,
109) -> Result<(hal::Instance, wgpu::hal::ExposedAdapter<Vulkan>), String> {
110    if host.get_instance_proc_addr.is_null()
111        || host.instance.is_null()
112        || host.physical_device.is_null()
113    {
114        return Err("get_instance_proc_addr, instance and physical_device must be set".into());
115    }
116    // SAFETY: the host promises `get_instance_proc_addr` is a valid `PFN_vkGetInstanceProcAddr`;
117    // data and function pointers have the same size on every platform with a Vulkan loader.
118    let get_instance_proc_addr = unsafe {
119        std::mem::transmute::<*const c_void, vk::PFN_vkGetInstanceProcAddr>(
120            host.get_instance_proc_addr,
121        )
122    };
123    let static_fn = || ash::StaticFn {
124        get_instance_proc_addr,
125    };
126    let entry = unsafe { ash::Entry::from_static_fn(static_fn()) };
127    let raw_instance = unsafe {
128        ash::Instance::load(
129            &static_fn(),
130            vk::Instance::from_raw(host.instance as usize as u64),
131        )
132    };
133    let api_version = if host.api_version == 0 {
134        vk::API_VERSION_1_0
135    } else {
136        host.api_version
137    };
138    // wgpu-hal wants `&'static CStr` names and only ever looks for the ones it knows: hand it its own
139    // list of what it would enable, restricted to what the host enabled.
140    let flags = wgpu::InstanceFlags::empty();
141    let mut extensions = hal::Instance::desired_extensions(&entry, api_version, flags)
142        .map_err(|e| format!("enumerating instance extensions: {e}"))?;
143    extensions.retain(|e| host.instance_extensions.contains(e));
144    let instance = unsafe {
145        hal::Instance::from_raw(
146            entry,
147            raw_instance,
148            api_version,
149            0,
150            None,
151            extensions,
152            flags,
153            wgpu::MemoryBudgetThresholds::default(),
154            false,
155            // The engine renders off-screen and never creates a swapchain.
156            wgpu::VulkanSwapchainKind::Native,
157            None,
158            // The host owns the VkInstance.
159            Some(Box::new(|| {})),
160        )
161    }
162    .map_err(|e| format!("wrapping the VkInstance: {e}"))?;
163    let phd = vk::PhysicalDevice::from_raw(host.physical_device as usize as u64);
164    // wgpu-hal assumes the device exposes every version the physical device reports; a lower
165    // instance apiVersion hides the newer core functions (the loader returns NULL for them).
166    let device_version = unsafe {
167        instance
168            .shared_instance()
169            .raw_instance()
170            .get_physical_device_properties(phd)
171    }
172    .api_version;
173    let have = (
174        vk::api_version_major(api_version),
175        vk::api_version_minor(api_version),
176    );
177    let need = (
178        vk::api_version_major(device_version),
179        vk::api_version_minor(device_version),
180    );
181    if have < need {
182        return Err(format!(
183            "the VkInstance was created with apiVersion {}.{} but the physical device is {}.{}: create it with \
184             apiVersion >= {}.{} (e.g. the value of vkEnumerateInstanceVersion)",
185            have.0, have.1, need.0, need.1, need.0, need.1
186        ));
187    }
188    let adapter = instance
189        .expose_adapter(phd)
190        .ok_or("wgpu cannot use this VkPhysicalDevice (below its minimum requirements)")?;
191    Ok((instance, adapter))
192}
193
194/// Which device extensions and features wgpu needs on `host`'s physical device. Reads only
195/// `get_instance_proc_addr`, `instance`, `physical_device`, `api_version` and the instance
196/// extensions.
197///
198/// # Safety
199/// The handles in `host` are valid Vulkan objects.
200pub unsafe fn requirements(host: &VulkanHost<'_>) -> Result<VulkanRequirements, String> {
201    let (_instance, adapter) = unsafe { open_instance(host) }?;
202    let features = wgpu::Features::empty();
203    let device_extensions = adapter.adapter.required_device_extensions(features);
204    let mut phd_features = Box::new(
205        adapter
206            .adapter
207            .physical_device_features(&device_extensions, features),
208    );
209    let (enabled_features, device_pnext) = {
210        let info = phd_features.add_to_device_create(vk::DeviceCreateInfo::default());
211        (info.p_enabled_features.cast::<c_void>(), info.p_next)
212    };
213    Ok(VulkanRequirements {
214        device_extensions,
215        enabled_features,
216        device_pnext,
217        _features: phd_features,
218    })
219}
220
221/// Wrap the host's `VkDevice` as the device and queue to build a `lactea::Engine` on. Uses wgpu's
222/// default limits and no optional features.
223///
224/// # Safety
225/// All handles in `host` are valid Vulkan objects; the device was created with at least the
226/// extensions and features of [`requirements`], and outlives the returned device, its queue and
227/// everything created from them.
228pub unsafe fn open_device(host: &VulkanHost<'_>) -> Result<(wgpu::Device, wgpu::Queue), String> {
229    if host.device.is_null() {
230        return Err("device is NULL".into());
231    }
232    let (instance, exposed) = unsafe { open_instance(host) }?;
233    let features = wgpu::Features::empty();
234    // Exactly what wgpu itself enables on a device it opens for these features.
235    let enabled = exposed.adapter.required_device_extensions(features);
236    if let Some(missing) = enabled.iter().find(|e| !host.device_extensions.contains(e)) {
237        return Err(format!(
238            "the VkDevice must enable {} (see the Vulkan interop requirements)",
239            missing.to_string_lossy()
240        ));
241    }
242    let raw_device = unsafe {
243        ash::Device::load(
244            instance.shared_instance().raw_instance().fp_v1_0(),
245            vk::Device::from_raw(host.device as usize as u64),
246        )
247    };
248    let open = unsafe {
249        exposed.adapter.device_from_raw(
250            raw_device,
251            // The host owns the VkDevice.
252            Some(Box::new(|| {})),
253            &enabled,
254            features,
255            &wgpu::Limits::default(),
256            &wgpu::MemoryHints::default(),
257            host.queue_family_index,
258            host.queue_index,
259        )
260    }
261    .map_err(|e| format!("wrapping the VkDevice: {e}"))?;
262    let wgpu_instance = unsafe { wgpu::Instance::from_hal::<Vulkan>(instance) };
263    let adapter = unsafe { wgpu_instance.create_adapter_from_hal::<Vulkan>(exposed) };
264    unsafe { adapter.create_device_from_hal::<Vulkan>(open, &wgpu::DeviceDescriptor::default()) }
265        .map_err(|e| format!("create_device_from_hal: {e}"))
266}
267
268/// The host's `VkImage` (a non-dispatchable handle, as `u64`) as a render attachment of `device`.
269/// `format` is one [`format_from_vk`] accepts and the image's own; the image was created with
270/// `VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT` at `width` x `height`.
271///
272/// Wrap the image again for every frame and drop the texture after submitting: a fresh wrapper makes
273/// wgpu assume an undefined layout and discard the old contents, so it never relies on a layout the
274/// host moved the image to in between.
275///
276/// # Safety
277/// `device` comes from [`open_device`]; `image` is a valid image of that `VkDevice` matching the
278/// description above, alive until the work rendering into it has executed.
279pub unsafe fn wrap_image(
280    device: &wgpu::Device,
281    image: u64,
282    width: u32,
283    height: u32,
284    format: wgpu::TextureFormat,
285) -> Result<wgpu::Texture, String> {
286    if image == 0 {
287        return Err("image is VK_NULL_HANDLE".into());
288    }
289    let size = wgpu::Extent3d {
290        width,
291        height,
292        depth_or_array_layers: 1,
293    };
294    let hal_desc = wgpu::hal::TextureDescriptor {
295        label: Some("lactea host image"),
296        size,
297        mip_level_count: 1,
298        sample_count: 1,
299        dimension: wgpu::TextureDimension::D2,
300        format,
301        usage: wgpu::TextureUses::COLOR_TARGET,
302        memory_flags: wgpu::hal::MemoryFlags::empty(),
303        view_formats: Vec::new(),
304        texture_binding_view_dimension: None,
305    };
306    let hal_texture = {
307        let Some(hal_device) = (unsafe { device.as_hal::<Vulkan>() }) else {
308            return Err("the device is not a Vulkan device".into());
309        };
310        unsafe {
311            hal_device.texture_from_raw(
312                vk::Image::from_raw(image),
313                &hal_desc,
314                // The host owns the VkImage.
315                Some(Box::new(|| {})),
316                hal::TextureMemory::External,
317            )
318        }
319    };
320    Ok(unsafe {
321        device.create_texture_from_hal::<Vulkan>(
322            hal_texture,
323            &wgpu::TextureDescriptor {
324                label: Some("lactea host image"),
325                size,
326                mip_level_count: 1,
327                sample_count: 1,
328                dimension: wgpu::TextureDimension::D2,
329                format,
330                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
331                view_formats: &[],
332                texture_binding_view_dimension: None,
333            },
334            wgpu::TextureUses::UNINITIALIZED,
335            // The host's image holds defined contents: no lazy clear (wgpu 30 behaviour).
336            true,
337        )
338    })
339}