diff --git a/crates/xcl/src/gpu/agility.rs b/crates/xcl/src/gpu/agility.rs index f19faa461d..ac998754b2 100644 --- a/crates/xcl/src/gpu/agility.rs +++ b/crates/xcl/src/gpu/agility.rs @@ -24,6 +24,11 @@ use windows::core::{Interface, IUnknown, Param, GUID, PCSTR}; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL; use windows::Win32::Graphics::Direct3D12::*; +/// Exported for `gpu::recomp::runner` to enable the D3D12 debug layer before device creation. +pub use windows::Win32::Graphics::Direct3D12::CLSID_D3D12Debug; +/// Exported for `gpu::recomp::runner` to enable the D3D12 debug layer before device creation. +pub use windows::Win32::Graphics::Direct3D12::ID3D12Debug; + use crate::pe::{Layout, Pe}; /// Environment variable overriding the Agility SDK folder. diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index ed683350f7..1a511afd84 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -16,6 +16,7 @@ use windows::Win32::Graphics::Dxgi::*; use super::{KERNEL_LANES, KERNEL_RES_DWORDS, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_VGPRS}; use crate::gpu::fence; +use crate::gpu::agility::{configuration_interface, CLSID_D3D12Debug, ID3D12Debug}; /// Initial state of a kernel run. #[derive(Clone)] @@ -85,6 +86,12 @@ unsafe fn wait_for_submission( fn init() -> Result { unsafe { + // Enable debug layer BEFORE creating the device if XCL_D3D12_DEBUG is set + if std::env::var_os("XCL_D3D12_DEBUG").is_some() { + if let Ok(debug) = configuration_interface::(&CLSID_D3D12Debug) { + debug.EnableDebugLayer(); + } + } let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(e)?; // `XCL_ADAPTER` picks the adapter (default: the first in high-performance order) let sel = crate::gpu::adapter::Selector::from_env_or("auto"); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 06cca160a5..7628dd4310 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -4133,6 +4133,11 @@ pub(super) unsafe extern "system" fn resolve_query_data_x(this: *mut c_void, hea pc::(this, PC_WRITE_BUFFER_IMMEDIATE)(this, params.len() as u32, params.as_ptr(), modes.as_ptr()); } +/// Serializes tests that create D3D12 devices / access shared GPU state (LISTS, LIVE_QUEUES, +/// SYNC_GRAPH, COPY_SCRATCH, QUEUE_IDS, WRITE_TRACE, MIRRORS, VISIBLE, etc.). Tests that +/// don't touch these can run in parallel. +pub static TEST_LOCK: Mutex<()> = Mutex::new(()); + #[cfg(test)] mod tests { use super::*; @@ -4142,6 +4147,7 @@ mod tests { /// and is gone from it once the fence gets there. #[test] fn an_internal_wait_is_listed_until_its_fence_reaches_the_value() { + let _guard = TEST_LOCK.lock().unwrap(); use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; unsafe { @@ -4164,6 +4170,7 @@ mod tests { #[test] fn copy_scratch_budget_counts_resources_until_gpu_completion() { + let _guard = TEST_LOCK.lock().unwrap(); use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; unsafe { @@ -4212,6 +4219,7 @@ mod tests { /// scratch buffer, which the GPU may still use. #[test] fn a_new_list_takes_no_copy_scratch_of_an_earlier_one() { + let _guard = TEST_LOCK.lock().unwrap(); use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; unsafe { @@ -4548,6 +4556,7 @@ mod tests { #[test] fn depth_bias_native_list9_and_bundle_fallback() { + let _guard = TEST_LOCK.lock().unwrap(); use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::*; @@ -5367,6 +5376,7 @@ mod tests { /// land once the queue completes. Unaligned and unwritable addresses are ignored. #[test] fn timestamps_outside_unified_memory_land_after_the_queue() { + let _guard = TEST_LOCK.lock().unwrap(); use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::*; @@ -5442,6 +5452,7 @@ mod tests { #[test] fn write_buffer_immediate_on_open_existing_heap_visible_to_cpu() { + let _guard = TEST_LOCK.lock().unwrap(); use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::*; use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; @@ -5631,6 +5642,7 @@ mod tests { /// GPU `queue.Wait`/`queue.Signal` without blocking the submitter thread for `WAIT_TIMEOUT`. #[test] fn cross_queue_wait64_before_signal_does_not_deadlock_submit_thread() { + let _guard = TEST_LOCK.lock().unwrap(); use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::*; @@ -5710,6 +5722,7 @@ mod tests { /// complete immediately without stalling CPU or hanging GPU. #[test] fn cross_queue_cycle_and_same_queue_fifo_do_not_deadlock() { + let _guard = TEST_LOCK.lock().unwrap(); use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::*; @@ -5804,6 +5817,7 @@ mod tests { /// pipelined frame N/N+1 or back-to-back cross-queue handshakes (`wait_seq > prod_sig_seq`). #[test] fn pipelined_next_frame_write_is_not_false_cycle() { + let _guard = TEST_LOCK.lock().unwrap(); use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::*; @@ -5971,6 +5985,7 @@ mod tests { /// already has an armed `queue.Wait` on it — must rescue the waiter instead of orphaning it. #[test] fn rotating_queue_self_deadlock_and_non_monotonic_rescue_do_not_hang() { + let _guard = TEST_LOCK.lock().unwrap(); use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::*; @@ -6093,6 +6108,7 @@ mod tests { /// already in flight (watchdog release path) does not hang subsequent queue completions. #[test] fn cpu_watchdog_signal_with_inflight_gpu_signal_completes_cleanly() { + let _guard = TEST_LOCK.lock().unwrap(); use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::*; @@ -6145,6 +6161,7 @@ mod tests { /// completes on GPU with ZERO CPU cycle breaks, and reuses `pc_c1` from the spare pool on Reset. #[test] fn mid_list_write64_wait64_split_avoids_cycle_and_reuses_spares() { + let _guard = TEST_LOCK.lock().unwrap(); use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::*; @@ -6297,6 +6314,7 @@ mod tests { /// title's address back, which the PC's GPU has no address for). #[test] fn a_mirrored_buffer_binds_its_mirror_without_asking_readable() { + let _guard = TEST_LOCK.lock().unwrap(); use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualProtect, MEM_COMMIT, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; if crate::gpu::uma::get().is_none() { crate::gpu::recomp::runner::skip_test("no unified memory"); diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index f3f0357981..261ab61f65 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -22,6 +22,8 @@ pub mod guard; mod late_release; pub mod layout; pub mod list_x; +/// Re-export TEST_LOCK from list_x so tests in sibling modules can use it. +pub use list_x::TEST_LOCK; pub mod null; pub mod present; pub mod pso_async; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9241a3a18d..e17f0bef41 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6593,6 +6593,7 @@ mod readback_routing_tests { /// and state bits before creating the cross-adapter placed resource. #[test] fn coherent_buffer_sanitizes_console_flags_and_state() { + let _guard = crate::hle::d3d12x::TEST_LOCK.lock().unwrap(); let raw_desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Alignment: 0x10_0000, @@ -6735,6 +6736,7 @@ mod readback_routing_tests { /// its entry from `list_x::LISTS`. #[test] fn dma_list_release_cleans_up_list_state() { + let _guard = crate::hle::d3d12x::TEST_LOCK.lock().unwrap(); assert!( overrides(Kind::DmaList).iter().any(|&(name, f)| name == "Release" && f == cl_release as usize), "Kind::DmaList must override Release with cl_release" @@ -6922,6 +6924,7 @@ mod console_format_query_tests { /// PC has no such format. #[test] fn gpu_console_depth_formats_are_supported() { + let _guard = crate::hle::d3d12x::TEST_LOCK.lock().unwrap(); let Some(dev) = device() else { return }; let (this, f) = (dev.as_raw(), pc_check(&dev)); // the gap: the PC's own answer (unless another test adopted a device, and the vtable it @@ -6966,6 +6969,7 @@ mod console_format_query_tests { /// (XG), and the PC's for the resource made of the desc (`pc_resource_desc`), both sane. #[test] fn gpu_console_format_allocation_info_is_sane() { + let _guard = crate::hle::d3d12x::TEST_LOCK.lock().unwrap(); let Some(dev) = device() else { return }; // (bytes a pixel at least, as XG lays them out: 119 alone is a plain 2-byte format, 120 alone // the stencil plane) @@ -6993,6 +6997,7 @@ mod console_format_query_tests { /// the clear value with it (`pc_clear`) – one still in 118 the PC refuses. #[test] fn gpu_placed_console_depth_target_with_clear_value() { + let _guard = crate::hle::d3d12x::TEST_LOCK.lock().unwrap(); let Some(dev) = device() else { crate::gpu::recomp::runner::skip_test("no GPU"); return; @@ -7039,6 +7044,7 @@ mod map_tests { /// or a reserved one gets its title address instead (the PC's Map on it is an invalid call). #[test] fn only_resources_with_cpu_pages_go_to_the_pc_map() { + let _guard = crate::hle::d3d12x::TEST_LOCK.lock().unwrap(); unsafe { let mut dev: Option = None; if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ac38429be7..bc26601395 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1211,6 +1211,7 @@ mod tests { /// texture that was forgotten (released, or its address registered again) is uploaded again. #[test] fn a_texture_with_unchanged_memory_is_left_out_until_it_is_forgotten() { + let _guard = TEST_LOCK.lock().unwrap(); let (a, b) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize); let mut mem = vec![0u8; 3 << 20]; mem[5] = 1; diff --git a/crates/xcl/src/hle/kbm.rs b/crates/xcl/src/hle/kbm.rs index 6d18b1cfbc..85e5d990f8 100644 --- a/crates/xcl/src/hle/kbm.rs +++ b/crates/xcl/src/hle/kbm.rs @@ -72,10 +72,14 @@ pub struct Velocity { impl Velocity { pub fn update(&mut self, dx: i32, dy: i32, dt: f32) { - let dt = dt.clamp(0.001, 0.1); - let a = 1.0 - (-dt / SMOOTHING).exp(); - self.x += a * (dx as f32 / dt - self.x); - self.y += a * (dy as f32 / dt - self.y); + // Use the real dt for rate calculation; only clamp the smoothing factor + // to avoid spikes when the title pauses input for a long time (issue #963). + let dt_clamped = dt.clamp(0.001, 0.1); + let a = 1.0 - (-dt_clamped / SMOOTHING).exp(); + if dt > 0.0 { + self.x += a * (dx as f32 / dt - self.x); + self.y += a * (dy as f32 / dt - self.y); + } } } @@ -223,6 +227,8 @@ struct Mouse { velocity: Velocity, wheel: Wheel, wheel_rest: i32, + /// Last absolute mouse position (for MOUSE_MOVE_ABSOLUTE), None if not yet set or after reset + last_abs: Option<(i32, i32)>, } impl Mouse { @@ -231,6 +237,7 @@ impl Mouse { self.velocity = Velocity::default(); self.wheel = Wheel::default(); self.wheel_rest = 0; + self.last_abs = None; } } @@ -307,8 +314,20 @@ pub unsafe fn on_message(hwnd: *mut c_void, msg: u32, wp: usize, lp: isize) -> b let n = GetRawInputData(lp, RID_INPUT, &mut raw as *mut _ as *mut c_void, &mut size, 24); if n != u32::MAX && n as usize >= std::mem::size_of::() && raw.kind == RIM_TYPEMOUSE && CAPTURED.load(Ordering::Acquire) { if raw.flags & MOUSE_MOVE_ABSOLUTE == 0 { + // Relative movement DX.fetch_add(raw.last_x, Ordering::Relaxed); DY.fetch_add(raw.last_y, Ordering::Relaxed); + } else { + // Absolute movement: compute delta from last absolute position + let mut g = MOUSE.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(|| Mouse { last: Instant::now(), velocity: Velocity::default(), wheel: Wheel::default(), wheel_rest: 0, last_abs: None }); + if let Some((last_x, last_y)) = m.last_abs { + let dx = raw.last_x - last_x; + let dy = raw.last_y - last_y; + DX.fetch_add(dx, Ordering::Relaxed); + DY.fetch_add(dy, Ordering::Relaxed); + } + m.last_abs = Some((raw.last_x, raw.last_y)); } if raw.button_flags & RI_MOUSE_WHEEL != 0 { WHEEL.fetch_add(raw.button_data as i16 as i32, Ordering::Relaxed); @@ -429,7 +448,7 @@ pub fn apply(s: &mut GamepadState) { s.left_trigger = 1.0; } let mut g = MOUSE.lock().unwrap_or_else(|e| e.into_inner()); - let m = g.get_or_insert_with(|| Mouse { last: Instant::now(), velocity: Velocity::default(), wheel: Wheel::default(), wheel_rest: 0 }); + let m = g.get_or_insert_with(|| Mouse { last: Instant::now(), velocity: Velocity::default(), wheel: Wheel::default(), wheel_rest: 0, last_abs: None }); let now = Instant::now(); let dt = now.duration_since(m.last).as_secs_f32(); m.last = now; @@ -549,6 +568,57 @@ mod tests { assert_eq!(scancode_to_vk(0xFFFF, SC_Q.1, layout), SC_Q.1); } + #[test] + fn velocity_update_uses_real_dt_for_rate_clamped_for_smoothing() { + // Issue #963: camera whip on focus regain – the fix uses real dt for rate + // calculation (dx/dt) but clamps dt only for the smoothing factor. + let mut v = Velocity::default(); + + // A long pause (dt = 1.0) followed by a small movement should not spike velocity. + // With the bug: a = 1 - exp(-0.1/0.03) ≈ 0.96, rate = 10/0.1 = 100 → velocity jumps to ~100. + // With the fix: a = 1 - exp(-0.1/0.03) ≈ 0.96, rate = 10/1.0 = 10 → velocity gently moves toward 10. + v.update(10, 0, 1.0); + assert!(v.x < 20.0, "velocity should not spike after a long pause, got {}", v.x); + + // Normal short dt still works: 10 counts in 0.004s = 2500 counts/s. + // Velocity approaches the target rate exponentially; run enough updates to converge. + for _ in 0..50 { + v.update(10, 0, 0.004); + } + assert!((v.x - 2500.0).abs() < 100.0, "velocity should track normal movement, got {}", v.x); + } + + #[test] + fn mouse_struct_has_last_abs_field_for_absolute_coordinates() { + // Issue #962: some Raw Input devices report absolute coordinates (MOUSE_MOVE_ABSOLUTE). + // The Mouse struct needs a last_abs field to track the previous position for delta calculation. + let m = Mouse { + last: Instant::now(), + velocity: Velocity::default(), + wheel: Wheel::default(), + wheel_rest: 0, + last_abs: Some((1000, 500)), + }; + // The field should store the last absolute position + assert_eq!(m.last_abs, Some((1000, 500))); + } + + #[test] + fn mouse_reset_clears_last_abs() { + // Reset must clear last_abs to None, so the first absolute move is handled correctly + // (first move has no previous position to compute delta from) + let mut m = Mouse { + last: Instant::now(), + velocity: Velocity::default(), + wheel: Wheel::default(), + wheel_rest: 0, + last_abs: Some((1000, 500)), + }; + m.reset(Instant::now()); + // After reset, last_abs should be None + assert!(m.last_abs.is_none()); + } + #[test] fn focus_loss_resets_mouse_velocity_and_wheel_state() { // Seed raw deltas and active MOUSE state (velocity, in-flight & pending wheel notches, remainder). @@ -569,6 +639,7 @@ mod tests { velocity: v, wheel: w, wheel_rest: 90, + last_abs: None, }); let m = g.as_ref().unwrap(); assert!(m.velocity.x.abs() > REST_SPEED && m.velocity.y.abs() > REST_SPEED); diff --git a/crates/xcl/src/vfs.rs b/crates/xcl/src/vfs.rs index dd02bcb67a..633d4dcd98 100644 --- a/crates/xcl/src/vfs.rs +++ b/crates/xcl/src/vfs.rs @@ -103,6 +103,11 @@ fn trim_sep(s: &str) -> String { fn strip_verbatim(p: &str) -> String { if let Some(r) = p.strip_prefix("\\\\?\\UNC\\") { + // \\?\UNC\C:\path -> C:\path (local drive via UNC prefix) + let rb = r.as_bytes(); + if rb.len() >= 2 && rb[1] == b':' && rb[0].is_ascii_alphabetic() { + return r.to_string(); + } return format!("\\\\{r}"); } if let Some(r) = p.strip_prefix("\\\\?\\") { @@ -157,7 +162,9 @@ fn logical_drives() -> u32 { impl Vfs { pub fn new(game_root: &Path, data_dir: &Path, mounts: Vec<(String, String)>) -> Vfs { - let game_root = trim_sep(&norm(&game_root.to_string_lossy())); + let game_root = game_root.to_string_lossy(); + let game_root = full_path(&game_root).unwrap_or_else(|| game_root.into_owned()); + let game_root = trim_sep(&strip_verbatim(&norm(&game_root))); let overlay_dir = data_dir.join("overlay"); let whiteout_file = overlay_dir.join(".xcl_whiteouts"); let whiteouts = std::fs::read_to_string(&whiteout_file) @@ -165,7 +172,11 @@ impl Vfs { .unwrap_or_default(); let mut mounts: Vec<(String, String)> = mounts .into_iter() - .map(|(p, t)| (p.to_ascii_lowercase().trim_end_matches(['\\', '/']).to_string(), trim_sep(&norm(&t)))) + .map(|(p, t)| { + let t = full_path(&t).unwrap_or_else(|| t.to_string()); + let t = trim_sep(&strip_verbatim(&norm(&t))); + (p.to_ascii_lowercase().trim_end_matches(['\\', '/']).to_string(), t) + }) .collect(); // longest prefix first ("GAME:" before "G:") mounts.sort_by(|a, b| b.0.len().cmp(&a.0.len())); @@ -788,6 +799,28 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// UNC paths for game_root are canonicalized the same way as data_root (issue #961). + #[test] + fn game_root_unc_is_canonicalized() { + let dir = std::env::temp_dir().join(format!("xcl_vfs_unc_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let game = dir.join("game"); + let data = dir.join("xcldata"); + std::fs::create_dir_all(game.join("data")).unwrap(); + + // Simulate a UNC path for game_root by using the verbatim prefix that GetFullPathNameW + // produces for UNC paths. The fix applies full_path + strip_verbatim + norm to game_root. + let game_unc = format!("\\\\?\\UNC\\{}\\game", dir.display()); + let v = Vfs::new(Path::new(&game_unc), &data, vec![("G:".to_string(), game.to_string_lossy().to_string())]); + + // The game_root should now match the canonical path, so classification works. + assert_eq!(v.classify("G:\\data\\hello.txt"), Target::Game { rel: "data\\hello.txt".into() }); + let real = full_path(&game.to_string_lossy()).unwrap(); + assert_eq!(v.classify(&format!("{real}\\data\\hello.txt")), Target::Game { rel: "data\\hello.txt".into() }); + + let _ = std::fs::remove_dir_all(&dir); + } + /// The shader cache on the drive the console's "D:" mount names: without `own_folder` the /// title's process writes it into the overlay (and reads the game folder) – a cache filled /// outside the title, where no mount applies, is not the one it then uses. diff --git a/scripts/coverage_gate.py b/scripts/coverage_gate.py index e7ed84d66a..9652d2418f 100644 --- a/scripts/coverage_gate.py +++ b/scripts/coverage_gate.py @@ -65,7 +65,7 @@ def main(argv=None): else: if not (args.xcl and args.rpf): ap.error("--xcl and --rpf are required unless --run-json is given") - cmd = [str(args.xcl), "shaders", str(args.rpf), "--direct", "--sample", "0", "--json"] + cmd = [str(args.xcl), "shaders", str(args.rpf), "--direct", "--sample", "0", "--json", "--validate"] if args.threads: cmd += ["--threads", str(args.threads)] proc = subprocess.run(cmd, capture_output=True, text=True)