DX12 device_from_raw (#10662)

This commit is contained in:
Roberto De Ioris authored and GitHub committed 2026-11-02 19:18:03 +00:00
1 parent 97474455ba
commit 985ce0ff88
6 files changed
+308 -33

No files matched your search

+1
View File
@@ -153,6 +153,7 @@ By @sagudev in [#10307](https://github.com/gfx-rs/wgpu/pull/10307).
- Add `wgpu_hal::vulkan::Surface::set_next_present_chain`, which attaches a caller-provided `pNext` chain to the `VkPresentInfoKHR` of the surface's next presentation. With `Adapter::open_with_callback` to enable the device extension, this supports presentation extensions wgpu has no dedicated support for, such as [VK_NV_present_metering](https://registry.khronos.org/vulkan/specs/latest/man/html/VK_NV_present_metering.html) for metering the display timing of frame-generation frames. By @stuartparmenter in [#9847](https://github.com/gfx-rs/wgpu/pull/9847).
- Add `wgpu_hal::vulkan::AccelerationStructure::raw_handle`, which returns the underlying `VkAccelerationStructureKHR`. Use it with `Adapter::open_with_callback` to record acceleration structure commands from extensions wgpu doesn't support, such as [VK_NV_cluster_acceleration_structure](https://registry.khronos.org/vulkan/specs/latest/man/html/VK_NV_cluster_acceleration_structure.html). Mark the result with `CommandEncoder::mark_acceleration_structures_built`. By @stuartparmenter in [#10187](https://github.com/gfx-rs/wgpu/pull/10187).
- Add `wgpu_hal::vulkan::Surface::set_next_swapchain_create_chain` and `wgpu_hal::vulkan::Queue::set_next_submit_chain`. The first attaches a caller-provided `pNext` chain to the `VkSwapchainCreateInfoKHR` of the surface's next configuration. The second attaches one to the `VkSubmitInfo` of the queue's next submission. Together with `set_next_present_chain` and the existing raw-handle accessors, this makes [VK_NV_low_latency2](https://registry.khronos.org/vulkan/specs/latest/man/html/VK_NV_low_latency2.html) usable on a wgpu swapchain. That extension is the Vulkan interface for NVIDIA Reflex. By @stuartparmenter in [#10095](https://github.com/gfx-rs/wgpu/pull/10095).
- Add `wgpu_hal::dx12::Adapter::device_from_raw` to create a device from an existing `ID3D12Device` and `ID3D12CommandQueue`. By @rdeioris in [#10662](https://github.com/gfx-rs/wgpu/pull/10662).
#### DX12
Generated
+1
View File
@@ -5163,6 +5163,7 @@ dependencies = [
"wgpu-hal",
"wgpu-sync",
"wgpu-types",
"windows",
]
[[package]]
+9
View File
@@ -119,6 +119,15 @@ web-sys = { workspace = true, features = [
# Cargo-metadata doesn't compile on wasm due to old cargo-util-schemas dependency.
cargo_metadata.workspace = true
[target.'cfg(windows)'.dev-dependencies]
windows = { workspace = true, features = [
"Win32_Foundation",
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D12",
"Win32_Graphics_Dxgi",
"Win32_Graphics_Dxgi_Common",
] }
[lints.clippy]
bool_assert_comparison = "allow"
disallowed_types = "allow"
@@ -0,0 +1,200 @@
use wgpu::*;
use wgpu_test::{
apply, gpu_test, FailureCase, GpuTestConfiguration, GpuTestInitializer, TestParameters,
};
pub fn all_tests(vec: &mut Vec<GpuTestInitializer>) {
vec.push(DX12_DEVICE_FROM_RAW);
}
#[apply(gpu_test!)]
static DX12_DEVICE_FROM_RAW: GpuTestConfiguration = GpuTestConfiguration::new()
.parameters(
TestParameters::default().skip(FailureCase::backend(Backends::all() - Backends::DX12)),
)
.run_sync(|ctx| match ctx.adapter_info.backend {
#[cfg(windows)]
wgpu::Backend::Dx12 => windows_impl::device_from_raw(&ctx),
other => unreachable!(
"test is configured to skip all backends except DX12, but ran on {other:?}"
),
});
#[cfg(windows)]
mod windows_impl {
use wgpu::hal::dx12;
use windows::{
core::Interface as _,
Win32::{
Foundation::HANDLE,
Graphics::{Direct3D::D3D_FEATURE_LEVEL_11_0, Direct3D12::*, Dxgi::*},
},
};
fn native_ref_count(object: &impl windows::core::Interface) -> u32 {
let raw = object.as_raw();
// SAFETY: `raw` is a live COM object, and the AddRef is balanced by the Release.
unsafe {
let vtable = *(raw as *const *const windows::core::IUnknown_Vtbl);
((*vtable).AddRef)(raw);
((*vtable).Release)(raw)
}
}
fn native_create_device(adapter: &impl windows::core::Interface) -> ID3D12Device {
let mut device: Option<ID3D12Device> = None;
unsafe {
D3D12CreateDevice(
&adapter.cast::<IDXGIAdapter>().unwrap(),
D3D_FEATURE_LEVEL_11_0,
&mut device,
)
}
.expect("D3D12CreateDevice failed");
device.unwrap()
}
fn native_create_queue(
device: &ID3D12Device,
ty: D3D12_COMMAND_LIST_TYPE,
) -> ID3D12CommandQueue {
unsafe {
device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
Type: ty,
..Default::default()
})
}
.expect("CreateCommandQueue failed")
}
pub fn device_from_raw(ctx: &wgpu_test::TestingContext) {
let limits = wgpu::Limits::downlevel_defaults();
let hal_adapter = unsafe { ctx.adapter.as_hal::<dx12::Api>() }.unwrap();
let adapter_luid = unsafe { hal_adapter.as_raw().GetDesc2() }
.unwrap()
.AdapterLuid;
// Use the device created by wgpu, so it comes from the same D3D12 runtime as the adapter.
let raw_device = unsafe { ctx.device.as_hal::<dx12::Api>() }
.unwrap()
.raw_device()
.clone();
let raw_queue = native_create_queue(&raw_device, D3D12_COMMAND_LIST_TYPE_DIRECT);
// A queue that is not a direct queue is rejected.
let compute_queue = native_create_queue(&raw_device, D3D12_COMMAND_LIST_TYPE_COMPUTE);
assert!(unsafe {
hal_adapter.device_from_raw(
raw_device.clone(),
compute_queue,
wgpu::Features::empty(),
&limits,
&wgpu::MemoryHints::Performance,
)
}
.is_err());
// Check a second adapter is available, and if so, check that a device or queue from that adapter is rejected.
let factory: IDXGIFactory4 =
unsafe { CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)) }.unwrap();
let other_adapter = (0..)
.map_while(|i| unsafe { factory.EnumAdapters1(i) }.ok())
.chain(unsafe { factory.EnumWarpAdapter::<IDXGIAdapter1>() }.ok())
.find(|adapter| unsafe { adapter.GetDesc1() }.unwrap().AdapterLuid != adapter_luid);
match other_adapter {
Some(other_adapter) => {
let other_device = native_create_device(&other_adapter);
let other_queue =
native_create_queue(&other_device, D3D12_COMMAND_LIST_TYPE_DIRECT);
// A device of another adapter is rejected.
assert!(unsafe {
hal_adapter.device_from_raw(
other_device,
other_queue.clone(),
wgpu::Features::empty(),
&limits,
&wgpu::MemoryHints::Performance,
)
}
.is_err());
// A queue of another adapter is rejected too.
assert!(unsafe {
hal_adapter.device_from_raw(
raw_device.clone(),
other_queue,
wgpu::Features::empty(),
&limits,
&wgpu::MemoryHints::Performance,
)
}
.is_err());
}
None => log::warn!("no second adapter, skipping the mismatched adapter checks"),
}
let queue_refs = native_ref_count(&raw_queue);
let hal_device = unsafe {
hal_adapter.device_from_raw(
raw_device.clone(),
raw_queue.clone(),
wgpu::Features::empty(),
&limits,
&wgpu::MemoryHints::Performance,
)
}
.unwrap();
drop(hal_adapter);
let (device, queue) = unsafe {
ctx.adapter.create_device_from_hal(
hal_device,
&wgpu::DeviceDescriptor {
required_limits: limits,
..Default::default()
},
)
}
.unwrap();
// Check .as_hal returns the same raw device and queue
assert_eq!(
unsafe { device.as_hal::<dx12::Api>() }
.unwrap()
.raw_device()
.as_raw(),
raw_device.as_raw()
);
assert_eq!(
unsafe { queue.as_hal::<dx12::Api>() }
.unwrap()
.as_raw()
.as_raw(),
raw_queue.as_raw()
);
queue.submit([device.create_command_encoder(&Default::default()).finish()]);
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
drop(queue);
drop(device);
assert_eq!(
native_ref_count(&raw_queue),
queue_refs,
"wgpu leaked or over-released the queue"
);
// The device and queue still work after wgpu is done with them.
let fence: ID3D12Fence =
unsafe { raw_device.CreateFence(0, D3D12_FENCE_FLAG_NONE) }.unwrap();
unsafe {
raw_queue.Signal(&fence, 1).unwrap();
// A null event makes this call block until the fence is signaled.
fence.SetEventOnCompletion(1, HANDLE::default()).unwrap();
raw_device.GetDeviceRemovedReason().unwrap();
}
}
}
+2
View File
@@ -36,6 +36,7 @@ mod dispatch_workgroups_indirect;
mod draw_index;
mod draw_indirect;
mod dual_source_blending;
mod dx12_device_from_raw;
mod encoder;
mod external_image_copy;
mod external_texture;
@@ -114,6 +115,7 @@ fn all_tests() -> Vec<wgpu_test::GpuTestInitializer> {
draw_index::all_tests(&mut tests);
draw_indirect::all_tests(&mut tests);
dual_source_blending::all_tests(&mut tests);
dx12_device_from_raw::all_tests(&mut tests);
encoder::all_tests(&mut tests);
external_texture::all_tests(&mut tests);
float32_filterable::all_tests(&mut tests);
+95 -33
View File
@@ -61,6 +61,100 @@ impl super::Adapter {
&self.raw
}
/// # Safety
///
/// - `raw_device` must be created from this adapter, using the same D3D12 runtime
/// that wgpu uses (for example, the same Agility SDK).
/// - `features` and `limits` must be supported by this adapter.
///
/// wgpu-hal takes ownership of the `raw_device` and `raw_queue` references and
/// releases them when the device is dropped.
pub unsafe fn device_from_raw(
&self,
raw_device: Direct3D12::ID3D12Device,
raw_queue: Direct3D12::ID3D12CommandQueue,
features: wgt::Features,
limits: &wgt::Limits,
memory_hints: &wgt::MemoryHints,
) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> {
let adapter_luid = unsafe { self.raw.GetDesc2() }
.into_device_result("Adapter description")?
.AdapterLuid;
let device_luid = unsafe { raw_device.GetAdapterLuid() };
if device_luid != adapter_luid {
log::error!(
"device_from_raw: device adapter LUID {device_luid:?} does not match adapter LUID {adapter_luid:?}"
);
return Err(crate::DeviceError::Unexpected);
}
let queue_type = unsafe { raw_queue.GetDesc() }.Type;
if queue_type != Direct3D12::D3D12_COMMAND_LIST_TYPE_DIRECT {
log::error!("device_from_raw: queue type {queue_type:?} is not a direct queue");
return Err(crate::DeviceError::Unexpected);
}
let mut queue_device: Option<Direct3D12::ID3D12Device> = None;
unsafe { raw_queue.GetDevice(&mut queue_device) }
.into_device_result("Queue device query")?;
let as_unknown =
|device: &Direct3D12::ID3D12Device| device.cast::<windows::core::IUnknown>().ok();
let same_device = queue_device
.as_ref()
.and_then(as_unknown)
.is_some_and(|queue_device| Some(queue_device) == as_unknown(&raw_device));
if !same_device {
log::error!("device_from_raw: queue was not created on the given device");
return Err(crate::DeviceError::Unexpected);
}
unsafe { self.open_with_raw(raw_device, raw_queue, features, limits, memory_hints) }
}
/// # Safety
///
/// See [`Self::device_from_raw`].
unsafe fn open_with_raw(
&self,
raw_device: Direct3D12::ID3D12Device,
raw_queue: Direct3D12::ID3D12CommandQueue,
features: wgt::Features,
limits: &wgt::Limits,
memory_hints: &wgt::MemoryHints,
) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> {
let device = super::Device::new(
self.raw.clone(),
raw_device,
raw_queue.clone(),
features,
limits,
memory_hints,
self.private_caps,
&self.library,
&self.dcomp_lib,
self.memory_budget_thresholds,
self.compiler_container.clone(),
self.options.clone(),
)?;
let idle_fence: Direct3D12::ID3D12Fence =
unsafe { device.raw.CreateFence(0, Direct3D12::D3D12_FENCE_FLAG_NONE) }
.into_device_result("Queue idle fence creation")?;
let idle_event = super::Event::create(false, false)?;
Ok(crate::OpenDevice {
device,
queue: super::Queue {
raw: raw_queue,
temp_lists: Mutex::new(Vec::new()),
idle_fence,
idle_event,
idle_fence_value: AtomicU64::new(0),
pending_waits: Mutex::new(Vec::new()),
pending_signals: Mutex::new(Vec::new()),
},
})
}
#[allow(clippy::too_many_arguments)]
pub(super) fn expose(
adapter: DxgiAdapter,
@@ -1085,39 +1179,7 @@ impl crate::Adapter for super::Adapter {
.into_device_result("Queue creation")?
};
let device = super::Device::new(
self.raw.clone(),
self.device.clone(),
queue.clone(),
features,
limits,
memory_hints,
self.private_caps,
&self.library,
&self.dcomp_lib,
self.memory_budget_thresholds,
self.compiler_container.clone(),
self.options.clone(),
)?;
let idle_fence: Direct3D12::ID3D12Fence = unsafe {
self.device
.CreateFence(0, Direct3D12::D3D12_FENCE_FLAG_NONE)
}
.into_device_result("Queue idle fence creation")?;
let idle_event = super::Event::create(false, false)?;
Ok(crate::OpenDevice {
device,
queue: super::Queue {
raw: queue,
temp_lists: Mutex::new(Vec::new()),
idle_fence,
idle_event,
idle_fence_value: AtomicU64::new(0),
pending_waits: Mutex::new(Vec::new()),
pending_signals: Mutex::new(Vec::new()),
},
})
unsafe { self.open_with_raw(self.device.clone(), queue, features, limits, memory_hints) }
}
unsafe fn texture_format_capabilities(