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