Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 72 additions & 4 deletions crates/xcl/src/hle/kbm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}

Expand Down Expand Up @@ -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 {
Expand All @@ -231,6 +237,7 @@ impl Mouse {
self.velocity = Velocity::default();
self.wheel = Wheel::default();
self.wheel_rest = 0;
self.last_abs = None;
}
}

Expand Down Expand Up @@ -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::<RawMouseInput>() && 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 });
if let Some((last_x, last_y)) = m.last_abs {
let dx = raw.last_x - last_x;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could the absolute coordinates be converted to display coordinates before these differences are added to DX/DY? For MOUSE_MOVE_ABSOLUTE, lLastX/lLastY are normalized to 0–65535, not pixel deltas; Windows also uses MOUSE_VIRTUAL_DESKTOP to select the coordinate surface. Treating these values as relative counts makes sensitivity depend heavily on display resolution and can produce a huge velocity when the pointer moves across the surface. Please map absolute positions to screen coordinates before computing deltas and add tests for both coordinate surfaces. AI-assisted review: I checked the Windows RAWMOUSE definition, but I did not run tests.

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);
Expand Down Expand Up @@ -549,6 +568,55 @@ 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
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).
Expand Down
26 changes: 25 additions & 1 deletion crates/xcl/src/vfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,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)
Expand Down Expand Up @@ -788,6 +790,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.
Expand Down
Loading