diff --git a/crates/xcl/src/config.rs b/crates/xcl/src/config.rs index 23257c0..09bbbdb 100644 --- a/crates/xcl/src/config.rs +++ b/crates/xcl/src/config.rs @@ -43,7 +43,8 @@ pub struct Config { pub stub_returns: BTreeMap, /// "d3d12" (real GPU, default) or "null" (no rendering). pub graphics: String, - /// "auto" (high-performance GPU, then WARP) or "warp". + /// "auto" (high-performance GPU, then WARP), "warp", a number (that hardware adapter in + /// high-performance order) or a part of the adapter's name ("radeon"). `XCL_ADAPTER` overrides. pub d3d12_adapter: String, /// Enable the D3D12 debug layer (needs Graphics Tools). pub d3d12_debug: bool, diff --git a/crates/xcl/src/gpu/adapter.rs b/crates/xcl/src/gpu/adapter.rs new file mode 100644 index 0000000..85a6ded --- /dev/null +++ b/crates/xcl/src/gpu/adapter.rs @@ -0,0 +1,110 @@ +//! Which D3D12 adapter XCL uses: `d3d12_adapter` in `xcl.toml`, overridden by `XCL_ADAPTER`. +//! +//! - `auto` (or empty): the hardware adapters in high-performance order, the first one that +//! creates a device; +//! - `warp`: the software renderer; +//! - a number `N`: the N-th hardware adapter in high-performance order (0 = the first); +//! - anything else: the hardware adapters whose name contains it (case-insensitive), e.g. +//! `radeon` or `rtx 3080`. +//! +//! The same choice drives the title's device (`hle::d3d12x::real`) and the GPU test bench +//! (`gpu::recomp::runner`), so the GPU tests can be run on each adapter of a machine in turn. + +use std::fmt; + +use windows::Win32::Graphics::Dxgi::*; + +/// The environment variable that overrides `d3d12_adapter`. +pub const ENV: &str = "XCL_ADAPTER"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Selector { + Auto, + Warp, + /// Position among the hardware adapters in high-performance order. + Index(usize), + /// Lower-case part of the adapter's name. + Name(String), +} + +impl Selector { + pub fn parse(s: &str) -> Selector { + let s = s.trim(); + if s.is_empty() || s.eq_ignore_ascii_case("auto") { + Selector::Auto + } else if s.eq_ignore_ascii_case("warp") { + Selector::Warp + } else if let Ok(n) = s.parse::() { + Selector::Index(n) + } else { + Selector::Name(s.to_lowercase()) + } + } + + /// `XCL_ADAPTER` if set (and not empty), otherwise `configured`. + pub fn from_env_or(configured: &str) -> Selector { + match std::env::var(ENV) { + Ok(v) if !v.trim().is_empty() => Selector::parse(&v), + _ => Selector::parse(configured), + } + } + + /// Whether the hardware adapter at `index` (high-performance order) named `name` is chosen. + pub fn allows(&self, index: usize, name: &str) -> bool { + match self { + Selector::Auto => true, + Selector::Warp => false, + Selector::Index(n) => *n == index, + Selector::Name(part) => name.to_lowercase().contains(part.as_str()), + } + } +} + +impl fmt::Display for Selector { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Selector::Auto => f.write_str("auto"), + Selector::Warp => f.write_str("warp"), + Selector::Index(n) => write!(f, "{n}"), + Selector::Name(s) => write!(f, "\"{s}\""), + } + } +} + +/// The adapter's name from its description. +pub fn name(desc: &DXGI_ADAPTER_DESC1) -> String { + let n = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); + String::from_utf16_lossy(&desc.Description[..n]) +} + +/// The hardware adapters (software ones skipped) in high-performance order. +pub fn hardware(factory: &IDXGIFactory6) -> Vec<(IDXGIAdapter1, DXGI_ADAPTER_DESC1)> { + let mut out = Vec::new(); + let mut i = 0; + unsafe { + while let Ok(adapter) = factory.EnumAdapterByGpuPreference::(i, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE) { + i += 1; + let Ok(desc) = adapter.GetDesc1() else { continue }; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { + continue; + } + out.push((adapter, desc)); + } + } + out +} + +/// The hardware adapters `sel` allows, in high-performance order (empty for `warp`). +pub fn candidates(factory: &IDXGIFactory6, sel: &Selector) -> Vec<(IDXGIAdapter1, DXGI_ADAPTER_DESC1)> { + hardware(factory).into_iter().enumerate().filter(|(i, (_, d))| sel.allows(*i, &name(d))).map(|(_, a)| a).collect() +} + +/// "`sel` matches no adapter (have: 0 = …, 1 = …)" – for logs and test skips. +pub fn no_match(factory: &IDXGIFactory6, sel: &Selector) -> String { + let have: Vec = hardware(factory).iter().enumerate().map(|(i, (_, d))| format!("{i} = {}", name(d))).collect(); + format!("{ENV} / d3d12_adapter {sel} matches no hardware adapter (have: {})", have.join(", ")) +} + +#[cfg(test)] +#[path = "adapter_tests.rs"] +mod tests; diff --git a/crates/xcl/src/gpu/adapter_tests.rs b/crates/xcl/src/gpu/adapter_tests.rs new file mode 100644 index 0000000..f2fd0e8 --- /dev/null +++ b/crates/xcl/src/gpu/adapter_tests.rs @@ -0,0 +1,23 @@ +use super::Selector; + +#[test] +fn selector_parsing() { + assert_eq!(Selector::parse(""), Selector::Auto); + assert_eq!(Selector::parse(" Auto "), Selector::Auto); + assert_eq!(Selector::parse("WARP"), Selector::Warp); + assert_eq!(Selector::parse("1"), Selector::Index(1)); + assert_eq!(Selector::parse("Radeon"), Selector::Name("radeon".into())); + assert_eq!(Selector::parse(" RTX 3080 "), Selector::Name("rtx 3080".into())); +} + +#[test] +fn selector_matching() { + let nv = "NVIDIA GeForce RTX 3080"; + let amd = "AMD Radeon(TM) Graphics"; + assert!(Selector::Auto.allows(0, nv) && Selector::Auto.allows(1, amd)); + assert!(!Selector::Warp.allows(0, nv)); + assert!(Selector::Index(1).allows(1, amd) && !Selector::Index(1).allows(0, nv)); + let radeon = Selector::parse("radeon"); + assert!(radeon.allows(1, amd) && !radeon.allows(0, nv)); + assert!(Selector::parse("geforce rtx").allows(0, nv)); +} diff --git a/crates/xcl/src/gpu/mod.rs b/crates/xcl/src/gpu/mod.rs index a83d41f..3b6874a 100644 --- a/crates/xcl/src/gpu/mod.rs +++ b/crates/xcl/src/gpu/mod.rs @@ -1,6 +1,7 @@ //! GPU side of XCL: console shader capture and the RDNA2 microcode toolchain //! (decoder / disassembler – the front-end of the shader recompiler). +pub mod adapter; pub mod bvh; pub mod desc; pub mod dxbc; diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index cceffd6..e8898b3 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -61,6 +61,8 @@ struct Gpu { value: u64, adapter: String, wave64: bool, + /// mesh shader tier 1 or higher (`mesh_draw`) + mesh: bool, } // D3D12 objects are free-threaded; access is serialised by the mutex. @@ -75,9 +77,17 @@ fn e(x: windows::core::Error) -> String { fn init() -> Result { unsafe { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(e)?; - let adapter: IDXGIAdapter1 = factory.EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE).map_err(e)?; - let desc = adapter.GetDesc1().map_err(e)?; - let name = String::from_utf16_lossy(&desc.Description).trim_end_matches('\0').to_string(); + // `XCL_ADAPTER` picks the adapter (default: the first in high-performance order) + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + let (adapter, name): (IDXGIAdapter1, String) = if sel == crate::gpu::adapter::Selector::Warp { + (factory.EnumWarpAdapter().map_err(e)?, "WARP (software renderer)".into()) + } else { + let (a, desc) = crate::gpu::adapter::candidates(&factory, &sel) + .into_iter() + .next() + .ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + (a, crate::gpu::adapter::name(&desc)) + }; let mut dev: Option = None; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut dev).map_err(e)?; let dev = dev.ok_or("no device")?; @@ -93,11 +103,14 @@ fn init() -> Result { return Err(format!("{name}: no wave operations/int64")); } let wave64 = o1.WaveLaneCountMin <= 64 && o1.WaveLaneCountMax >= 64; + let mut o7 = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + let mesh = dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &mut o7 as *mut _ as _, std::mem::size_of_val(&o7) as u32).is_ok() + && o7.MeshShaderTier.0 >= D3D12_MESH_SHADER_TIER_1.0; let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(e)?; let rs = root_signature(&dev, false)?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?; - Ok(Gpu { dev, queue, rs, fence, value: 0, adapter: name, wave64 }) + Ok(Gpu { dev, queue, rs, fence, value: 0, adapter: name, wave64, mesh }) } } @@ -337,6 +350,14 @@ pub fn wave64_supported() -> Result { gpu.as_ref().map(|x| x.wave64).map_err(|x| x.clone()) } +/// Whether the adapter runs mesh shaders (`mesh_draw`); an integrated RDNA2 GPU, for one, +/// reports wave64 but no mesh shader tier. +pub fn mesh_shaders_supported() -> Result { + let mut g = GPU.lock().unwrap(); + let gpu = g.get_or_insert_with(init); + gpu.as_ref().map(|x| x.mesh).map_err(|x| x.clone()) +} + /// Run a compiled kernel (DXIL) with `state` and flat memory `mem`. pub fn run(dxil: &[u8], state: &KernelState, mem: &[u32]) -> Result { run_with(dxil, state, mem, &[], &[]) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ddb4275..6090a56 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -303,12 +303,8 @@ fn geometry_wave32_required(device: *mut c_void) -> bool { } } -fn adapter_name(desc: &DXGI_ADAPTER_DESC1) -> String { - let n = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); - String::from_utf16_lossy(&desc.Description[..n]) -} - -/// Create the process-wide D3D12 device (high-performance GPU → WARP); once – later calls +/// Create the process-wide D3D12 device (the adapter `d3d12_adapter` / `XCL_ADAPTER` chooses, +/// by default the high-performance GPU → WARP); once – later calls /// return the existing device's adapter. pub fn init() -> Result { if !device_raw().is_null() { @@ -339,16 +335,16 @@ pub fn init() -> Result { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| format!("DXGI: {e}"))?; let mut device: Option = None; let mut name = String::new(); - if !cfg.d3d12_adapter.eq_ignore_ascii_case("warp") { - let mut i = 0; - while let Ok(adapter) = factory.EnumAdapterByGpuPreference::(i, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE) { - i += 1; - let Ok(desc) = adapter.GetDesc1() else { continue }; - if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { - continue; - } + let sel = crate::gpu::adapter::Selector::from_env_or(&cfg.d3d12_adapter); + if sel != crate::gpu::adapter::Selector::Warp { + let mut list = crate::gpu::adapter::candidates(&factory, &sel); + if list.is_empty() { + crate::xlog_warn!("D3D12: {} – using auto", crate::gpu::adapter::no_match(&factory, &sel)); + list = crate::gpu::adapter::candidates(&factory, &crate::gpu::adapter::Selector::Auto); + } + for (adapter, desc) in list { if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).is_ok() { - name = format!("{} ({} MiB VRAM)", adapter_name(&desc), desc.DedicatedVideoMemory >> 20); + name = format!("{} ({} MiB VRAM)", crate::gpu::adapter::name(&desc), desc.DedicatedVideoMemory >> 20); break; } }