diff --git a/Cargo.lock b/Cargo.lock index 29bab8c72..380aae0ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -690,7 +690,9 @@ name = "victory-hle" version = "0.1.0" dependencies = [ "opus-pure", + "serde", "tempfile", + "toml", "tracing", "victory-formats", "victory-gpu", diff --git a/README.md b/README.md index 7dc43e245..3951f0b88 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,7 @@ What each part does today and what it still needs: | Runtime services | One signed-in offline user, licences, packages, saves that survive a kill at any step, text entry dialog | Speech is silent; the dialog and relaunch are untested live | | Network | Offline by design: the title cannot reach the network | – | | Files and streaming | Archives and streamed data read, zlib and BCPack decoded in parallel | Loading is limited by writes into title memory | -| Input | XInput pads, keyboard, keyboard stand-in pad | Trigger rumble | +| Input | XInput pads, keyboard and mouse as a pad (rebindable) | Trigger rumble; keyboard prompts | | Audio | Menu, video and loading sound; XMA voices and Opus streams decode | Reverb is silent; Opus results unverified against the title | | GPU: menus | Draws, compute and presentation on host D3D12; only changed title memory is copied | Frame pacing drifts on one screen in release builds | | GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes, indirect execution (arguments clamped), pipelines made by worker threads and kept on disk | Most of the scene is still missing (untranslated shaders drop draws); frames take seconds; real queries, depth bounds, HDR and scaling are missing | @@ -153,17 +153,29 @@ The window caption shows the framerate. Saves, settings and `crashes.log` are kept under the data folder (default `%LOCALAPPDATA%\victory\data`), derived data under the cache folder. -Input: XInput pads. With none connected the keyboard is a pad while the -title's window has focus: - -| Keys | Pad | -|------|-----| -| W A S D / I J K L | left / right stick | -| arrows | D-pad | -| Enter, Backspace, X, Y | A, B, X, Y | -| Q / E, Z / C | shoulders, triggers | -| F / H | stick clicks | -| Esc, Tab | Menu, View | +Input: XInput pads, and keyboard and mouse played like a PC game. The title +reads pads only, so the keyboard and mouse act on the first connected pad (or +a stand-in pad when none is): both work at once, each stick follows whichever +moved it last. The mouse turns the camera through the right stick, its motion +turned into a rate at each read of the title so the same movement turns the +same angle at any frame rate. While the window has focus the cursor is hidden +and held in it; Alt-Tab or Esc frees it, a click or Esc captures it again. + +| Keys (on foot) | Pad | Keys (in a vehicle) | Pad | +|------|-----|------|-----| +| W A S D, Left Alt | left stick, walk | W / S, A D | RT / LT, steer | +| mouse, left / right button | right stick, RT / LT | Space, E | RB, LS | +| Left Shift, Space, F, R | A, X, Y, B | F, G | Y + vehicle layout off, layout only | +| Q, E, Left Ctrl, C | RB, D-pad right, LS, RS | | | +| Tab, V or M, wheel | LB, View, D-pad left / right | | | +| arrows, Enter, Backspace, Esc or P | D-pad, A, B, Menu | | | + +The letters are the keys at those places on a US keyboard, so the left stick +is Z Q S D on an AZERTY keyboard (`keys_by_position = false`: by letter). +F (enter a vehicle) also switches to the vehicle layout and back; G switches +it alone when it is out of step. Rebind everything in `[controls]` of +`victory.toml` (see `victory.example.toml`); `enabled = false` brings back the +old fixed stand-in pad (W A S D / I J K L sticks, Enter, Backspace, X, Y). ## Commands diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index dc5bf7156..23bc067fd 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -19,6 +19,8 @@ pub fn run( // A title that relaunched itself: the old process must be gone first. victory_hle::modules::lifecycle::wait_for_previous(); let cfg = victory_core::Config::load()?; + victory_hle::modules::controls::configure(cfg.controls.as_ref()) + .map_err(anyhow::Error::msg)?; let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?; let prepared = victory_loader::prepare(&original)?; let hash = prepared.original_hash.to_hex(); diff --git a/crates/victory-core/src/config.rs b/crates/victory-core/src/config.rs index b65014e7e..0b75066db 100644 --- a/crates/victory-core/src/config.rs +++ b/crates/victory-core/src/config.rs @@ -24,6 +24,8 @@ pub struct Config { pub test_titles: Vec, /// The config file that was read, if any. pub source: Option, + /// `[controls]`: keyboard and mouse bindings, read by `victory-hle`. + pub controls: Option, } #[derive(Debug, Default, Deserialize)] @@ -31,6 +33,7 @@ pub struct Config { struct FileConfig { #[serde(default)] paths: FilePaths, + controls: Option, } #[derive(Debug, Default, Deserialize)] @@ -70,7 +73,9 @@ impl Config { } None => (None, FileConfig::default()), }; - Self::resolve(parsed.paths, source, |k| std::env::var_os(k)) + let mut cfg = Self::resolve(parsed.paths, source, |k| std::env::var_os(k))?; + cfg.controls = parsed.controls; + Ok(cfg) } fn resolve( @@ -97,6 +102,7 @@ impl Config { data_dir, test_titles, source, + controls: None, }) } diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index a2fa943c5..384ae8b35 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -15,11 +15,14 @@ victory-formats.workspace = true opus-pure.workspace = true zlib-rs.workspace = true tracing.workspace = true +serde.workspace = true +toml.workspace = true [target.'cfg(windows)'.dependencies] windows-sys = { workspace = true, features = [ "Win32_Foundation", "Win32_Globalization", + "Win32_Graphics_Gdi", "Win32_Media", "Win32_Security", "Win32_Storage_FileSystem", @@ -29,6 +32,7 @@ windows-sys = { workspace = true, features = [ "Win32_System_Power", "Win32_System_ProcessStatus", "Win32_System_Threading", + "Win32_UI_Input", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_XboxController", "Win32_UI_WindowsAndMessaging", diff --git a/crates/victory-hle/src/modules/controls.rs b/crates/victory-hle/src/modules/controls.rs new file mode 100644 index 000000000..896191f09 --- /dev/null +++ b/crates/victory-hle/src/modules/controls.rs @@ -0,0 +1,1145 @@ +//! Keyboard and mouse played the way PC games are: keys to pad buttons and +//! sticks, the mouse to the right stick, mouse buttons to the triggers. +//! +//! The title reads gamepads and keyboards only (it registers no +//! mouse), and turns its right stick into a turn rate. Mouse counts are a +//! distance, so they become a rate when the title reads the pad: the counts +//! since its last read over the time since then. The camera then turns the +//! same angle for the same hand movement at any frame rate. +//! +//! All of this is plain data: the host side of `gameinput` feeds it and the +//! title's reads drain it. `[controls]` in victory.toml sets and rebinds it. + +use std::collections::{BTreeMap, VecDeque}; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicI32, AtomicI64, Ordering}; + +use serde::Deserialize; + +use super::gameinput::{ + A, B, DOWN, LEFT, LEFT_SHOULDER, LEFT_STICK, MENU, PadState, RIGHT, RIGHT_SHOULDER, + RIGHT_STICK, UP, VIEW, X, Y, +}; + +/// Key codes are Windows virtual keys; mouse buttons are theirs too (1, 2, +/// 4, 5, 6) and the wheel takes two codes Windows leaves unassigned. +pub(super) const WHEEL_UP: u8 = 0x0E; +pub(super) const WHEEL_DOWN: u8 = 0x0F; +/// Mouse buttons by virtual key: left, right, middle, back, forward. +pub(super) const MOUSE_BUTTONS: [u8; 5] = [0x01, 0x02, 0x04, 0x05, 0x06]; + +/// Mouse counts per second that make a full stick at sensitivity 1. +const FULL_RATE: f64 = 2000.0; +/// Title reads closer together than this see the same mouse stick. +const MIN_TAKE_US: u64 = 2_000; +/// The first read's time span, and the longest one (a title that paused; +/// the title's world frames take 1-2 s here for now, measured). +const FIRST_TAKE_US: u64 = 16_667; +const MAX_TAKE_US: u64 = 1_000_000; +/// Counts past a full stick wait at most this long (seconds of full stick). +const CARRY_S: f64 = 0.1; +/// A pad stick past this takes its stick back from the keyboard and mouse. +/// Detection only: the pad's own value is passed on as it is. +const PAD_TAKES_OVER: f32 = 0.2; +/// Wheel steps waiting to be pressed. +const WHEEL_QUEUE: usize = 8; + +/// What a key does. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Output { + Button(u32), + LeftTrigger, + RightTrigger, + /// One stick direction. + Stick { + right: bool, + x: bool, + positive: bool, + }, + /// While held, the left stick moves at the walk speed. + Walk, + /// Switches between the on-foot and the vehicle layout. + ToggleVehicle, + /// Frees the mouse cursor, or captures it again. + ReleaseCursor, +} + +const fn stick(right: bool, x: bool, positive: bool) -> Output { + Output::Stick { right, x, positive } +} + +const OUTPUTS: [(&str, Output); 27] = [ + ("A", Output::Button(A)), + ("B", Output::Button(B)), + ("X", Output::Button(X)), + ("Y", Output::Button(Y)), + ("LB", Output::Button(LEFT_SHOULDER)), + ("RB", Output::Button(RIGHT_SHOULDER)), + ("LT", Output::LeftTrigger), + ("RT", Output::RightTrigger), + ("LS", Output::Button(LEFT_STICK)), + ("RS", Output::Button(RIGHT_STICK)), + ("View", Output::Button(VIEW)), + ("Menu", Output::Button(MENU)), + ("DpadUp", Output::Button(UP)), + ("DpadDown", Output::Button(DOWN)), + ("DpadLeft", Output::Button(LEFT)), + ("DpadRight", Output::Button(RIGHT)), + ("LeftUp", stick(false, false, true)), + ("LeftDown", stick(false, false, false)), + ("LeftLeft", stick(false, true, false)), + ("LeftRight", stick(false, true, true)), + ("RightUp", stick(true, false, true)), + ("RightDown", stick(true, false, false)), + ("RightLeft", stick(true, true, false)), + ("RightRight", stick(true, true, true)), + ("Walk", Output::Walk), + ("ToggleVehicle", Output::ToggleVehicle), + ("ReleaseCursor", Output::ReleaseCursor), +]; + +/// Key names besides single letters and digits, `F1`-`F24` and `Num0`-`Num9`. +const KEYS: [(&str, u8); 48] = [ + ("MouseLeft", 0x01), + ("MouseRight", 0x02), + ("MouseMiddle", 0x04), + ("Mouse4", 0x05), + ("Mouse5", 0x06), + ("WheelUp", WHEEL_UP), + ("WheelDown", WHEEL_DOWN), + ("Backspace", 0x08), + ("Tab", 0x09), + ("Enter", 0x0D), + ("Pause", 0x13), + ("CapsLock", 0x14), + ("Esc", 0x1B), + ("Space", 0x20), + ("PageUp", 0x21), + ("PageDown", 0x22), + ("End", 0x23), + ("Home", 0x24), + ("Left", 0x25), + ("Up", 0x26), + ("Right", 0x27), + ("Down", 0x28), + ("Insert", 0x2D), + ("Delete", 0x2E), + ("NumMultiply", 0x6A), + ("NumAdd", 0x6B), + ("NumSubtract", 0x6D), + ("NumDecimal", 0x6E), + ("NumDivide", 0x6F), + ("LShift", 0xA0), + ("RShift", 0xA1), + ("LCtrl", 0xA2), + ("RCtrl", 0xA3), + ("LAlt", 0xA4), + ("RAlt", 0xA5), + ("Semicolon", 0xBA), + ("Equals", 0xBB), + ("Comma", 0xBC), + ("Minus", 0xBD), + ("Period", 0xBE), + ("Slash", 0xBF), + ("Grave", 0xC0), + ("LBracket", 0xDB), + ("Backslash", 0xDC), + ("RBracket", 0xDD), + ("Quote", 0xDE), + ("Shift", 0xA0), + ("Ctrl", 0xA2), +]; + +/// The virtual key a key name stands for (case does not matter). +pub(super) fn key_code(name: &str) -> Option { + let name = name.trim(); + if let [c] = name.as_bytes() + && c.is_ascii_alphanumeric() + { + return Some(c.to_ascii_uppercase()); + } + if let Some((_, vk)) = KEYS.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)) { + return Some(*vk); + } + if name.eq_ignore_ascii_case("Alt") { + return Some(0xA4); + } + let numbered = |prefix: &str, first: u8, count: u8| { + let rest = name.get(prefix.len()..)?; + if !name.get(..prefix.len())?.eq_ignore_ascii_case(prefix) { + return None; + } + let n: u8 = rest.parse().ok()?; + (n < count).then(|| first + n) + }; + numbered("Num", 0x60, 10).or_else(|| { + numbered("F", 0x6F, 25).filter(|&vk| vk > 0x6F) // F1 = 0x70 + }) +} + +/// The key a US keyboard has at the place of scan code `scan` (letters, +/// digits and punctuation; `None` for keys that sit at the same place on +/// every layout, which keep their virtual key). Bindings name keys by that +/// place, so the hand position is the same on every layout: the keys of +/// W A S D are Z Q S D on an AZERTY keyboard. +pub(super) fn us_key(scan: u32) -> Option { + // Rows of a US keyboard from their first scan code: digits to `=`, + // Q to `]`, A to the grave accent, `\` to `/`. + const ROWS: [(u32, &[u8]); 4] = [ + (0x02, &[b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'0', 0xBD, 0xBB]), + (0x10, &[b'Q', b'W', b'E', b'R', b'T', b'Y', b'U', b'I', b'O', b'P', 0xDB, 0xDD]), + (0x1E, &[b'A', b'S', b'D', b'F', b'G', b'H', b'J', b'K', b'L', 0xBA, 0xDE, 0xC0]), + (0x2B, &[0xDC, b'Z', b'X', b'C', b'V', b'B', b'N', b'M', 0xBC, 0xBE, 0xBF]), + ]; + ROWS.iter().find_map(|&(first, keys)| { + let at = scan.checked_sub(first)?; + keys.get(at as usize).copied() + }) +} + +/// A key's name, for messages. +pub(super) fn key_name(vk: u8) -> String { + if vk.is_ascii_uppercase() || vk.is_ascii_digit() { + return char::from(vk).to_string(); + } + match vk { + 0x60..=0x69 => format!("Num{}", vk - 0x60), + 0x70..=0x87 => format!("F{}", vk - 0x6F), + _ => KEYS + .iter() + .find(|(_, k)| *k == vk) + .map_or_else(|| format!("{vk:#04x}"), |(n, _)| (*n).to_string()), + } +} + +fn output(name: &str) -> Option { + OUTPUTS + .iter() + .find(|(n, _)| n.eq_ignore_ascii_case(name.trim())) + .map(|(_, o)| *o) +} + +/// Keys and what each does, for one situation (on foot, in a vehicle). +#[derive(Clone, Debug, Default, PartialEq)] +pub(super) struct Layout(BTreeMap>); + +impl Layout { + fn outputs(&self, vk: u8) -> &[Output] { + self.0.get(&vk).map_or(&[], Vec::as_slice) + } + + /// Binds `key` to `outputs` (none: unbinds it). + fn bind(&mut self, key: &str, outputs: &[&str]) -> Result<(), String> { + let vk = key_code(key).ok_or_else(|| format!("unknown key `{key}`"))?; + let outs = outputs + .iter() + .filter(|o| !o.trim().is_empty()) + .map(|o| output(o).ok_or_else(|| format!("unknown pad output `{o}` for key `{key}`"))) + .collect::, _>>()?; + if outs.is_empty() { + self.0.remove(&vk); + } else { + self.0.insert(vk, outs); + } + Ok(()) + } + + fn of(table: &[(&str, &[&str])]) -> Layout { + let mut layout = Layout::default(); + for (key, outs) in table { + layout.bind(key, outs).expect("default bindings use known names"); + } + layout + } +} + +/// On foot: the series' usual PC keys, each on the pad button that does the +/// same on a console (the previous game's console layout; this title's is +/// unverified). +const ON_FOOT: &[(&str, &[&str])] = &[ + ("W", &["LeftUp"]), + ("S", &["LeftDown"]), + ("A", &["LeftLeft"]), + ("D", &["LeftRight"]), + ("LAlt", &["Walk"]), + ("LShift", &["A"]), + ("Space", &["X"]), + ("F", &["Y", "ToggleVehicle"]), + ("G", &["ToggleVehicle"]), + ("R", &["B"]), + ("Q", &["RB"]), + ("E", &["DpadRight"]), + ("LCtrl", &["LS"]), + ("C", &["RS"]), + ("V", &["View"]), + ("M", &["View"]), + ("Tab", &["LB"]), + ("WheelUp", &["DpadLeft"]), + ("WheelDown", &["DpadRight"]), + ("MouseLeft", &["RT"]), + ("MouseRight", &["LT"]), + ("MouseMiddle", &["RS"]), + ("Up", &["DpadUp"]), + ("Down", &["DpadDown"]), + ("Left", &["DpadLeft"]), + ("Right", &["DpadRight"]), + ("Enter", &["A"]), + ("Backspace", &["B"]), + ("Esc", &["Menu", "ReleaseCursor"]), + ("P", &["Menu"]), +]; + +/// In a vehicle: W/S throttle and brake on the triggers, A/D steer. +const VEHICLE: &[(&str, &[&str])] = &[ + ("W", &["RT"]), + ("S", &["LT"]), + ("A", &["LeftLeft"]), + ("D", &["LeftRight"]), + ("LShift", &["A"]), + ("Space", &["RB"]), + ("E", &["LS"]), + ("F", &["Y", "ToggleVehicle"]), + ("G", &["ToggleVehicle"]), + ("R", &["B"]), + ("C", &["RS"]), + ("V", &["View"]), + ("M", &["View"]), + ("Tab", &["LB"]), + ("WheelUp", &["DpadLeft"]), + ("WheelDown", &["DpadRight"]), + ("MouseLeft", &["RT"]), + ("MouseRight", &["LT"]), + ("MouseMiddle", &["RS"]), + ("Up", &["DpadUp"]), + ("Down", &["DpadDown"]), + ("Left", &["DpadLeft"]), + ("Right", &["DpadRight"]), + ("Enter", &["A"]), + ("Backspace", &["B"]), + ("Esc", &["Menu", "ReleaseCursor"]), + ("P", &["Menu"]), +]; + +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Settings { + /// Off: the old stand-in pad (README's table) and nothing else. + pub enabled: bool, + pub sensitivity: f32, + /// Vertical sensitivity relative to horizontal. + pub y_scale: f32, + pub invert_y: bool, + /// Capture (hide and hold) the cursor while the title window has focus. + pub capture: bool, + /// Counts past a full stick are turned later instead of dropped. + pub carry: bool, + /// The title's own stick dead zone and response exponent, undone so the + /// smallest movement turns and the response is linear. + pub deadzone: f32, + pub curve: f32, + pub walk_speed: f32, + /// Letters, digits and punctuation are the keys at those places on a + /// US keyboard ([`us_key`]), whatever the layout prints on them. + pub by_position: bool, + pub on_foot: Layout, + pub vehicle: Layout, +} + +impl Default for Settings { + fn default() -> Settings { + Settings { + enabled: true, + sensitivity: 1.0, + y_scale: 1.0, + invert_y: false, + capture: true, + carry: true, + deadzone: 0.3, + curve: 1.0, + walk_speed: 0.5, + by_position: true, + on_foot: Layout::of(ON_FOOT), + vehicle: Layout::of(VEHICLE), + } + } +} + +#[derive(Deserialize)] +#[serde(untagged)] +enum Binding { + One(String), + Many(Vec), +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct File { + enabled: Option, + mouse_sensitivity: Option, + mouse_y_scale: Option, + mouse_invert_y: Option, + mouse_capture: Option, + mouse_carry: Option, + stick_deadzone: Option, + stick_curve: Option, + walk_speed: Option, + keys_by_position: Option, + #[serde(default)] + on_foot: BTreeMap, + #[serde(default)] + vehicle: BTreeMap, +} + +impl Settings { + /// The defaults with `[controls]` applied; a layout table replaces only + /// the keys it names. + pub(super) fn parse(table: &toml::Table) -> Result { + let file: File = toml::Value::Table(table.clone()) + .try_into() + .map_err(|e| format!("[controls]: {e}"))?; + let mut s = Settings::default(); + let range = |name: &str, v: Option, lo: f32, hi: f32, into: &mut f32| match v { + Some(v) if !(lo..=hi).contains(&v) => { + Err(format!("[controls] {name} = {v} is outside {lo} to {hi}")) + } + Some(v) => { + *into = v; + Ok(()) + } + None => Ok(()), + }; + range("mouse_sensitivity", file.mouse_sensitivity, 0.01, 100.0, &mut s.sensitivity)?; + range("mouse_y_scale", file.mouse_y_scale, 0.01, 100.0, &mut s.y_scale)?; + range("stick_deadzone", file.stick_deadzone, 0.0, 0.9, &mut s.deadzone)?; + range("stick_curve", file.stick_curve, 0.2, 5.0, &mut s.curve)?; + range("walk_speed", file.walk_speed, 0.05, 1.0, &mut s.walk_speed)?; + s.enabled = file.enabled.unwrap_or(s.enabled); + s.invert_y = file.mouse_invert_y.unwrap_or(s.invert_y); + s.capture = file.mouse_capture.unwrap_or(s.capture); + s.carry = file.mouse_carry.unwrap_or(s.carry); + s.by_position = file.keys_by_position.unwrap_or(s.by_position); + for (layout, binds, name) in [ + (&mut s.on_foot, &file.on_foot, "on_foot"), + (&mut s.vehicle, &file.vehicle, "vehicle"), + ] { + for (key, binding) in binds { + let outs: Vec<&str> = match binding { + Binding::One(o) => vec![o.as_str()], + Binding::Many(os) => os.iter().map(String::as_str).collect(), + }; + layout + .bind(key, &outs) + .map_err(|e| format!("[controls.{name}]: {e}"))?; + } + } + Ok(s) + } +} + +static SETTINGS: OnceLock = OnceLock::new(); + +/// Takes `[controls]` from the config file (none: the defaults). Call it +/// before the title starts; later calls change nothing. +pub fn configure(table: Option<&toml::Table>) -> Result<(), String> { + let s = match table { + Some(t) => Settings::parse(t)?, + None => Settings::default(), + }; + tracing::info!( + enabled = s.enabled, + sensitivity = s.sensitivity, + invert_y = s.invert_y, + capture = s.capture, + deadzone = s.deadzone, + curve = s.curve, + "keyboard and mouse controls" + ); + let _ = SETTINGS.set(s); + Ok(()) +} + +pub(super) fn settings() -> Settings { + SETTINGS.get_or_init(Settings::default).clone() +} + +/// Mouse motion and wheel steps since they were last drained, added from +/// the host's raw input thread (only while the cursor is captured). +#[derive(Default)] +pub(super) struct Counts { + x: AtomicI64, + y: AtomicI64, + wheel: AtomicI32, +} + +impl Counts { + pub(super) fn add(&self, dx: i64, dy: i64) { + self.x.fetch_add(dx, Ordering::Relaxed); + self.y.fetch_add(dy, Ordering::Relaxed); + } + /// Steps away from the user are positive, as Windows reports them. + pub(super) fn add_wheel(&self, steps: i32) { + self.wheel.fetch_add(steps, Ordering::Relaxed); + } + fn drain(&self) -> (i64, i64) { + ( + self.x.swap(0, Ordering::Relaxed), + self.y.swap(0, Ordering::Relaxed), + ) + } + fn drain_wheel(&self) -> i32 { + self.wheel.swap(0, Ordering::Relaxed) + } +} + +/// Which device moved a stick last, or was used last. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Owner { + Pad, + Kbm, +} + +/// What a set of held keys does. +#[derive(Clone, Copy, Default, PartialEq)] +struct Derived { + buttons: u32, + left_trigger: bool, + right_trigger: bool, + left: (f32, f32), + right: (f32, f32), + left_moved: bool, + right_moved: bool, +} + +/// A wheel step is a press the title has read once, then a release it has +/// read once, so steps survive any frame rate. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Pulse { + Idle, + Down(u8), + Gap, +} + +/// The mouse as a right stick. +#[derive(Default)] +struct Look { + /// Counts not yet turned (y as Windows reports it: down positive). + pending: (f64, f64), + last_take: Option, + value: (f32, f32), + moved: bool, +} + +impl Look { + fn take(&mut self, now: u64, (dx, dy): (i64, i64), s: &Settings) -> (f32, f32) { + self.pending.0 += dx as f64; + self.pending.1 += dy as f64; + if let Some(last) = self.last_take + && now.saturating_sub(last) < MIN_TAKE_US + { + return self.value; + } + let span = self + .last_take + .map_or(FIRST_TAKE_US, |last| now.saturating_sub(last).min(MAX_TAKE_US)); + self.last_take = Some(now); + let dt = span as f64 / 1e6; + let full = FULL_RATE / f64::from(s.sensitivity); + let mut ux = self.pending.0 / dt / full; + let mut uy = -self.pending.1 * f64::from(s.y_scale) / dt / full; + let mut m = ux.hypot(uy); + self.moved = m > 0.0; + if m <= 1.0 { + self.pending = (0.0, 0.0); + } else { + // Full stick in the direction moved; the rest waits (capped). + let keep = if s.carry { 1.0 - 1.0 / m } else { 0.0 }; + self.pending.0 *= keep; + self.pending.1 *= keep; + let cap = CARRY_S * full; + let left = self.pending.0.hypot(self.pending.1); + if left > cap { + self.pending.0 *= cap / left; + self.pending.1 *= cap / left; + } + ux /= m; + uy /= m; + m = 1.0; + } + if m > 0.0 { + let d = f64::from(s.deadzone); + let shaped = d + (1.0 - d) * m.powf(1.0 / f64::from(s.curve)); + ux *= shaped / m; + uy *= shaped / m; + } + if s.invert_y { + uy = -uy; + } + self.value = (ux as f32, uy as f32); + self.value + } +} + +/// Keyboard and mouse state between host polls and title reads. +pub(super) struct Controls { + pub(super) s: Settings, + vehicle: bool, + held: Vec, + derived: Derived, + /// Buttons and triggers pressed since the title's last read: they stay + /// down until it has read them, so a tap shorter than a frame counts. + latched: u32, + latched_triggers: (bool, bool), + wheel: VecDeque, + pulse: Pulse, + look: Look, + left_owner: Owner, + right_owner: Owner, + last_used: Option, + /// The release key was pressed: the host frees or captures the cursor. + pub(super) toggle_capture: bool, +} + +impl Controls { + pub(super) fn new(s: Settings) -> Controls { + Controls { + s, + vehicle: false, + held: Vec::new(), + derived: Derived::default(), + latched: 0, + latched_triggers: (false, false), + wheel: VecDeque::new(), + pulse: Pulse::Idle, + look: Look::default(), + left_owner: Owner::Kbm, + right_owner: Owner::Kbm, + last_used: None, + toggle_capture: false, + } + } + + fn layout(&self) -> &Layout { + if self.vehicle { + &self.s.vehicle + } else { + &self.s.on_foot + } + } + + #[cfg(test)] + fn in_vehicle(&self) -> bool { + self.vehicle + } + + fn derive(&self, keys: impl Iterator) -> Derived { + let mut d = Derived::default(); + let (mut l, mut r) = ((0.0f32, 0.0f32), (0.0f32, 0.0f32)); + let mut walk = false; + for vk in keys { + for out in self.layout().outputs(vk) { + match *out { + Output::Button(b) => d.buttons |= b, + Output::LeftTrigger => d.left_trigger = true, + Output::RightTrigger => d.right_trigger = true, + Output::Stick { right, x, positive } => { + let stick = if right { &mut r } else { &mut l }; + let axis = if x { &mut stick.0 } else { &mut stick.1 }; + *axis += if positive { 1.0 } else { -1.0 }; + if right { + d.right_moved = true; + } else { + d.left_moved = true; + } + } + Output::Walk => walk = true, + Output::ToggleVehicle | Output::ReleaseCursor => {} + } + } + } + let round = |(x, y): (f32, f32)| { + let (x, y) = (x.clamp(-1.0, 1.0), y.clamp(-1.0, 1.0)); + let m = x.hypot(y); + if m > 1.0 { (x / m, y / m) } else { (x, y) } + }; + let speed = if walk { self.s.walk_speed } else { 1.0 }; + let (lx, ly) = round(l); + Derived { + left: (lx * speed, ly * speed), + right: round(r), + ..d + } + } + + /// A host poll: the keys and mouse buttons held now, wheel steps since + /// the last poll. + pub(super) fn feed(&mut self, held: &[u8], counts: &Counts) { + let steps = counts.drain_wheel(); + let key = if steps > 0 { WHEEL_UP } else { WHEEL_DOWN }; + for _ in 0..steps.unsigned_abs() { + if self.wheel.len() < WHEEL_QUEUE { + self.wheel.push_back(key); + } + } + let pressed: Vec = held + .iter() + .copied() + .filter(|vk| !self.held.contains(vk)) + .collect(); + for &vk in &pressed { + let outs = self.layout().outputs(vk).to_vec(); + if outs.contains(&Output::ToggleVehicle) { + self.vehicle = !self.vehicle; + tracing::info!(vehicle = self.vehicle, key = %key_name(vk), "controls layout"); + } + if outs.contains(&Output::ReleaseCursor) { + self.toggle_capture = true; + } + } + let before = self.derived; + self.held = held.to_vec(); + self.derived = self.derive(self.held.iter().copied()); + self.latched |= self.derived.buttons & !before.buttons; + self.latched_triggers.0 |= self.derived.left_trigger && !before.left_trigger; + self.latched_triggers.1 |= self.derived.right_trigger && !before.right_trigger; + if self.pulse == Pulse::Idle + && let Some(key) = self.wheel.pop_front() + { + self.pulse = Pulse::Down(key); + } + } + + /// The keyboard and mouse pad as it is now (a host poll's reading). + fn kbm(&self) -> PadState { + let mut d = self.derived; + if let Pulse::Down(key) = self.pulse { + let p = self.derive(std::iter::once(key)); + d.buttons |= p.buttons; + d.left_trigger |= p.left_trigger; + d.right_trigger |= p.right_trigger; + } + let on = |b: bool| if b { 1.0 } else { 0.0 }; + let (rx, ry) = ( + d.right.0 + self.look.value.0, + d.right.1 + self.look.value.1, + ); + let m = rx.hypot(ry); + let (rx, ry) = if m > 1.0 { (rx / m, ry / m) } else { (rx, ry) }; + PadState { + buttons: d.buttons | self.latched, + left_trigger: on(d.left_trigger || self.latched_triggers.0), + right_trigger: on(d.right_trigger || self.latched_triggers.1), + left_x: d.left.0, + left_y: d.left.1, + right_x: rx, + right_y: ry, + } + } + + /// The pad a host poll publishes: `pad` (a host pad, if any) with the + /// keyboard and mouse on it. + pub(super) fn peek(&mut self, pad: Option) -> PadState { + self.merge(pad) + } + + /// The pad the title reads now: the mouse counts since its last read + /// become the right stick, and what it has now seen is let go. + pub(super) fn take(&mut self, now: u64, pad: Option, counts: &Counts) -> PadState { + let before = self.look.last_take; + self.look.take(now, counts.drain(), &self.s); + let state = self.merge(pad); + if self.look.last_take != before { + self.latched = 0; + self.latched_triggers = (false, false); + self.pulse = match self.pulse { + Pulse::Down(_) => Pulse::Gap, + Pulse::Gap | Pulse::Idle => Pulse::Idle, + }; + } + state + } + + fn merge(&mut self, pad: Option) -> PadState { + let kbm = self.kbm(); + let kbm_used = !self.held.is_empty() || self.look.moved || self.pulse != Pulse::Idle; + let Some(pad) = pad else { + self.used(kbm_used.then_some(Owner::Kbm)); + return kbm; + }; + let pushed = |x: f32, y: f32| x.hypot(y) > PAD_TAKES_OVER; + let pad_left = pushed(pad.left_x, pad.left_y); + let pad_right = pushed(pad.right_x, pad.right_y); + if self.derived.left_moved { + self.left_owner = Owner::Kbm; + } else if pad_left { + self.left_owner = Owner::Pad; + } + if self.derived.right_moved || self.look.moved { + self.right_owner = Owner::Kbm; + } else if pad_right { + self.right_owner = Owner::Pad; + } + let pad_used = pad.buttons != 0 + || pad_left + || pad_right + || pad.left_trigger > 0.1 + || pad.right_trigger > 0.1; + self.used(if kbm_used { + Some(Owner::Kbm) + } else { + pad_used.then_some(Owner::Pad) + }); + let (lx, ly) = match self.left_owner { + Owner::Kbm => (kbm.left_x, kbm.left_y), + Owner::Pad => (pad.left_x, pad.left_y), + }; + let (rx, ry) = match self.right_owner { + Owner::Kbm => (kbm.right_x, kbm.right_y), + Owner::Pad => (pad.right_x, pad.right_y), + }; + PadState { + buttons: pad.buttons | kbm.buttons, + left_trigger: pad.left_trigger.max(kbm.left_trigger), + right_trigger: pad.right_trigger.max(kbm.right_trigger), + left_x: lx, + left_y: ly, + right_x: rx, + right_y: ry, + } + } + + fn used(&mut self, now: Option) { + if let Some(owner) = now + && self.last_used != Some(owner) + { + self.last_used = Some(owner); + tracing::info!( + device = match owner { + Owner::Pad => "gamepad", + Owner::Kbm => "keyboard and mouse", + }, + "input: now using" + ); + } + } + + /// The device used last (for prompts, once they can change). + #[allow(dead_code)] + pub(super) fn last_used(&self) -> Option { + self.last_used + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn vk(name: &str) -> u8 { + key_code(name).unwrap() + } + + fn linear() -> Settings { + Settings { + deadzone: 0.0, + curve: 1.0, + ..Settings::default() + } + } + + fn controls() -> Controls { + Controls::new(linear()) + } + + fn held(c: &mut Controls, keys: &[&str]) -> PadState { + let keys: Vec = keys.iter().map(|k| vk(k)).collect(); + c.feed(&keys, &Counts::default()); + c.peek(None) + } + + #[test] + fn key_names_round_trip() { + for (name, code) in [ + ("w", b'W'), + ("7", b'7'), + ("Space", 0x20), + ("lshift", 0xA0), + ("F1", 0x70), + ("F24", 0x87), + ("Num5", 0x65), + ("MouseLeft", 0x01), + ("WheelDown", WHEEL_DOWN), + ("Alt", 0xA4), + ] { + assert_eq!(key_code(name), Some(code), "{name}"); + } + assert_eq!(key_code("F0"), None); + assert_eq!(key_code("F25"), None); + assert_eq!(key_code("Num10"), None); + assert_eq!(key_code("Banana"), None); + assert_eq!(key_name(0x70), "F1"); + assert_eq!(key_name(0xA0), "LShift"); + assert_eq!(key_name(b'Q'), "Q"); + } + + #[test] + fn letters_are_named_by_their_place_on_a_us_keyboard() { + for (scan, key) in [ + (0x11, b'W'), + (0x1E, b'A'), + (0x1F, b'S'), + (0x20, b'D'), + (0x10, b'Q'), + (0x2C, b'Z'), + (0x32, b'M'), + (0x02, b'1'), + (0x0B, b'0'), + (0x29, 0xC0), + (0x2B, 0xDC), + (0x35, 0xBF), + ] { + assert_eq!(us_key(scan), Some(key), "{scan:#x}"); + } + // Esc, Tab, Enter, Left Ctrl, Space, Left Shift, the extended keys. + for scan in [0x01, 0x0F, 0x1C, 0x1D, 0x39, 0x2A, 0xE035, 0xE048] { + assert_eq!(us_key(scan), None, "{scan:#x}"); + } + let off: toml::Table = toml::from_str("keys_by_position = false").unwrap(); + assert!(Settings::default().by_position); + assert!(!Settings::parse(&off).unwrap().by_position); + } + + #[test] + fn wasd_moves_the_left_stick_round_and_walk_slows_it() { + let mut c = controls(); + let p = held(&mut c, &["W"]); + assert_eq!((p.left_x, p.left_y), (0.0, 1.0)); + let p = held(&mut c, &["W", "D"]); + let r = std::f32::consts::FRAC_1_SQRT_2; + assert!((p.left_x - r).abs() < 1e-6 && (p.left_y - r).abs() < 1e-6); + let p = held(&mut c, &["A", "D"]); + assert_eq!((p.left_x, p.left_y), (0.0, 0.0)); + let p = held(&mut c, &["S", "LAlt"]); + assert_eq!((p.left_x, p.left_y), (0.0, -0.5)); + } + + #[test] + fn keys_and_mouse_buttons_press_pad_buttons_and_triggers() { + let mut c = controls(); + let p = held(&mut c, &["Space", "LShift", "MouseLeft", "MouseRight", "Tab"]); + assert_eq!(p.buttons, X | A | LEFT_SHOULDER); + assert_eq!((p.left_trigger, p.right_trigger), (1.0, 1.0)); + let p = held(&mut c, &["Esc"]); + assert!(p.buttons & MENU != 0); + assert!(c.toggle_capture, "Esc frees the cursor"); + } + + #[test] + fn f_switches_to_the_vehicle_layout_and_g_puts_it_right() { + let mut c = controls(); + held(&mut c, &["F"]); + assert!(c.in_vehicle()); + held(&mut c, &[]); + let p = held(&mut c, &["W", "A"]); + assert_eq!(p.right_trigger, 1.0, "W is throttle"); + assert_eq!((p.left_x, p.left_y), (-1.0, 0.0), "A steers, W does not move the stick"); + // Holding F does not switch again. + held(&mut c, &["F"]); + held(&mut c, &["F"]); + assert!(!c.in_vehicle()); + held(&mut c, &[]); + held(&mut c, &["G"]); + assert!(c.in_vehicle()); + } + + #[test] + fn a_tap_between_two_reads_is_read_once() { + let mut c = controls(); + let counts = Counts::default(); + c.take(0, None, &counts); + c.feed(&[vk("Space")], &counts); + c.feed(&[], &counts); + assert_eq!(c.peek(None).buttons, X, "held for the title until it reads"); + assert_eq!(c.take(10_000, None, &counts).buttons, X); + assert_eq!(c.take(20_000, None, &counts).buttons, 0); + // A quick click shoots once. + c.feed(&[vk("MouseLeft")], &counts); + c.feed(&[], &counts); + assert_eq!(c.take(30_000, None, &counts).right_trigger, 1.0); + assert_eq!(c.take(40_000, None, &counts).right_trigger, 0.0); + } + + #[test] + fn wheel_steps_are_each_a_press_the_title_reads() { + let mut c = controls(); + let counts = Counts::default(); + counts.add_wheel(2); + let mut seen = Vec::new(); + for i in 0..6 { + c.feed(&[], &counts); + seen.push(c.take(i * 10_000, None, &counts).buttons); + } + assert_eq!(seen, [LEFT, 0, LEFT, 0, 0, 0]); + counts.add_wheel(-1); + c.feed(&[], &counts); + assert_eq!(c.take(100_000, None, &counts).buttons, RIGHT); + } + + #[test] + fn mouse_counts_become_a_rate_at_each_read() { + let mut c = controls(); + let counts = Counts::default(); + c.take(0, None, &counts); + // 2,000 counts/s = full stick at sensitivity 1: 10 counts in 10 ms is half. + counts.add(10, 0); + let p = c.take(10_000, None, &counts); + assert!((p.right_x - 0.5).abs() < 1e-6, "{}", p.right_x); + // The same distance over a 4x longer frame is a 4x smaller rate: the + // title turns rate x frame time, so the same angle. + counts.add(10, 0); + let p = c.take(50_000, None, &counts); + assert!((p.right_x - 0.125).abs() < 1e-6, "{}", p.right_x); + // Mouse up looks up; no motion lets go. + counts.add(0, -5); + let p = c.take(60_000, None, &counts); + assert!((p.right_y - 0.25).abs() < 1e-6 && p.right_x == 0.0); + assert_eq!(c.take(70_000, None, &counts).right_y, 0.0); + } + + #[test] + fn slow_frames_get_the_rate_over_their_whole_span() { + let mut c = controls(); + let counts = Counts::default(); + c.take(0, None, &counts); + // 1,000 counts over an 800 ms frame: half a stick, not saturated. + counts.add(1000, 0); + let p = c.take(800_000, None, &counts); + assert!((p.right_x - 0.625).abs() < 1e-6, "{}", p.right_x); + // Past the longest span the title counts as paused. + counts.add(1000, 0); + let p = c.take(3_800_000, None, &counts); + assert!((p.right_x - 0.5).abs() < 1e-6, "{}", p.right_x); + } + + #[test] + fn reads_close_together_see_the_same_mouse_stick() { + let mut c = controls(); + let counts = Counts::default(); + c.take(0, None, &counts); + counts.add(10, 0); + let a = c.take(10_000, None, &counts); + let b = c.take(10_500, None, &counts); + assert_eq!(a, b); + counts.add(4, 0); + let p = c.take(11_000, None, &counts); + assert_eq!(p, a, "counts wait for the next read"); + let p = c.take(20_000, None, &counts); + assert!((p.right_x - 0.2).abs() < 1e-6, "{}", p.right_x); + } + + #[test] + fn dead_zone_curve_and_inversion_shape_the_mouse_stick() { + let s = Settings { + deadzone: 0.2, + curve: 2.0, + invert_y: true, + ..Settings::default() + }; + let mut c = Controls::new(s); + let counts = Counts::default(); + c.take(0, None, &counts); + counts.add(0, -5); // a quarter stick up + let p = c.take(10_000, None, &counts); + // 0.2 + 0.8 * sqrt(0.25) = 0.6, then inverted. + assert!((p.right_y + 0.6).abs() < 1e-6, "{}", p.right_y); + // One count still clears the dead zone. + counts.add(1, 0); + let p = c.take(20_000, None, &counts); + assert!(p.right_x > 0.2); + } + + #[test] + fn a_fast_flick_is_turned_in_full_later() { + let mut c = controls(); + let counts = Counts::default(); + c.take(0, None, &counts); + counts.add(50, 0); // 2.5 full sticks in 10 ms + let xs: Vec = (1..=4) + .map(|i| c.take(i * 10_000, None, &counts).right_x) + .collect(); + assert_eq!(&xs[..2], &[1.0, 1.0]); + assert!((xs[2] - 0.5).abs() < 1e-6, "{xs:?}"); + assert_eq!(xs[3], 0.0); + let mut c = Controls::new(Settings { + carry: false, + ..linear() + }); + c.take(0, None, &counts); + counts.add(50, 0); + assert_eq!(c.take(10_000, None, &counts).right_x, 1.0); + assert_eq!(c.take(20_000, None, &counts).right_x, 0.0); + } + + #[test] + fn a_resting_pad_never_overrides_the_mouse_and_a_pushed_one_does() { + let mut c = controls(); + let counts = Counts::default(); + let drift = PadState { + right_x: 0.1, + left_y: -0.05, + buttons: B, + right_trigger: 0.4, + ..Default::default() + }; + c.take(0, Some(drift), &counts); + counts.add(10, 0); + c.feed(&[vk("W"), vk("MouseLeft")], &counts); + let p = c.take(10_000, Some(drift), &counts); + assert!((p.right_x - 0.5).abs() < 1e-6); + assert_eq!((p.left_y, p.buttons, p.right_trigger), (1.0, B, 1.0)); + c.feed(&[], &counts); + assert_eq!(c.take(20_000, Some(drift), &counts).right_x, 0.0, "drift stays out"); + let pushed = PadState { + right_x: 0.7, + left_x: -0.9, + ..Default::default() + }; + let p = c.take(30_000, Some(pushed), &counts); + assert_eq!((p.right_x, p.left_x), (0.7, -0.9)); + assert_eq!(c.last_used(), Some(Owner::Pad)); + } + + #[test] + fn config_rebinds_unbinds_and_refuses_typos() { + let table: toml::Table = toml::from_str( + r#" + mouse_sensitivity = 2.5 + mouse_invert_y = true + stick_deadzone = 0.24 + [on_foot] + Space = "A" + LShift = "" + Mouse4 = ["LB", "RB"] + [vehicle] + W = "RightTrigger_typo" + "#, + ) + .unwrap(); + let e = Settings::parse(&table).unwrap_err(); + assert!(e.contains("RightTrigger_typo"), "{e}"); + let mut table = table; + table.remove("vehicle"); + let s = Settings::parse(&table).unwrap(); + assert_eq!((s.sensitivity, s.invert_y, s.deadzone), (2.5, true, 0.24)); + assert_eq!(s.on_foot.outputs(0x20), &[Output::Button(A)]); + assert!(s.on_foot.outputs(0xA0).is_empty()); + assert_eq!( + s.on_foot.outputs(0x05), + &[Output::Button(LEFT_SHOULDER), Output::Button(RIGHT_SHOULDER)] + ); + assert_eq!(s.on_foot.outputs(b'W'), Settings::default().on_foot.outputs(b'W')); + for bad in ["mouse_sensitivty = 1.0", "stick_deadzone = 1.5", "[on_foot]\nBanana = \"A\""] { + let t: toml::Table = toml::from_str(bad).unwrap(); + assert!(Settings::parse(&t).is_err(), "{bad}"); + } + let off: toml::Table = toml::from_str("enabled = false").unwrap(); + assert!(!Settings::parse(&off).unwrap().enabled); + } +} diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index 6cb89fa83..92e9756af 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -1,8 +1,11 @@ //! `gameinput.dll`: input devices from the host. Gamepads come from XInput -//! (host slots 0-3); while none is connected, the keyboard drives one -//! stand-in gamepad (`FALLBACK_BUTTONS`). The keyboard is a device of its own +//! (host slots 0-3). The keyboard and mouse play as a pad (`controls`): on +//! the first connected host pad, or on one stand-in gamepad while none is +//! connected. With `[controls] enabled = false` the stand-in pad is the old +//! fixed layout (`FALLBACK_BUTTONS`). The keyboard is a device of its own //! too. A poll thread turns host state into readings (a new one per change) -//! and runs device callbacks on connect and disconnect. +//! and runs device callbacks on connect and disconnect; a title's pad read +//! makes one too, carrying the mouse motion since its last read. #![allow(non_snake_case)] // Title code calls these through the objects, passing pointers the real API // would trust. @@ -13,10 +16,11 @@ use std::ffi::c_void; use std::ops::Deref; use std::ptr::NonNull; use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; -use std::sync::{Condvar, LazyLock, Mutex, MutexGuard, PoisonError}; +use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard, PoisonError}; use std::thread::ThreadId; use std::time::{Duration, Instant}; +use super::controls::{Controls, Counts}; use super::xasync::{E_INVALIDARG, E_NOTIMPL}; use super::xgameruntime::{HRESULT, S_OK}; use crate::{HleExport, HleModule}; @@ -36,20 +40,20 @@ const STATUS_CONNECTED: u32 = 0x3; const ASYNC_ENUMERATION: u32 = 1; /// Gamepad buttons; the title maps each bit to one of its pad buttons. -const MENU: u32 = 0x1; -const VIEW: u32 = 0x2; -const A: u32 = 0x4; -const B: u32 = 0x8; -const X: u32 = 0x10; -const Y: u32 = 0x20; -const UP: u32 = 0x40; -const DOWN: u32 = 0x80; -const LEFT: u32 = 0x100; -const RIGHT: u32 = 0x200; -const LEFT_SHOULDER: u32 = 0x400; -const RIGHT_SHOULDER: u32 = 0x800; -const LEFT_STICK: u32 = 0x1000; -const RIGHT_STICK: u32 = 0x2000; +pub(super) const MENU: u32 = 0x1; +pub(super) const VIEW: u32 = 0x2; +pub(super) const A: u32 = 0x4; +pub(super) const B: u32 = 0x8; +pub(super) const X: u32 = 0x10; +pub(super) const Y: u32 = 0x20; +pub(super) const UP: u32 = 0x40; +pub(super) const DOWN: u32 = 0x80; +pub(super) const LEFT: u32 = 0x100; +pub(super) const RIGHT: u32 = 0x200; +pub(super) const LEFT_SHOULDER: u32 = 0x400; +pub(super) const RIGHT_SHOULDER: u32 = 0x800; +pub(super) const LEFT_STICK: u32 = 0x1000; +pub(super) const RIGHT_STICK: u32 = 0x2000; /// Devices: host pad slots, the keyboard's stand-in pad, the keyboard. const PADS: usize = 4; @@ -83,14 +87,14 @@ const FALLBACK_BUTTONS: [(u8, u32); 14] = [ /// A gamepad reading: triggers 0 to 1, sticks -1 to 1 (up positive). #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] -struct PadState { - buttons: u32, - left_trigger: f32, - right_trigger: f32, - left_x: f32, - left_y: f32, - right_x: f32, - right_y: f32, +pub(super) struct PadState { + pub(super) buttons: u32, + pub(super) left_trigger: f32, + pub(super) right_trigger: f32, + pub(super) left_x: f32, + pub(super) left_y: f32, + pub(super) right_x: f32, + pub(super) right_y: f32, } /// One key held down: scan code (0xE0xx when extended), character, key. @@ -111,6 +115,11 @@ trait Source: Send { fn pad(&mut self, slot: usize) -> Option; /// Keys held down; none while the title's window lacks focus. fn keys(&mut self) -> Vec; + /// Mouse buttons held down (`controls::MOUSE_BUTTONS`); none while the + /// cursor is not captured. + fn mouse_buttons(&mut self) -> Vec { + Vec::new() + } /// Motor speeds: low frequency (left), high frequency (right). fn rumble(&mut self, slot: usize, low: u16, high: u16); } @@ -236,6 +245,12 @@ pub struct Reading { } impl Reading { + /// The index of the device it is from. + fn hub_index(&self) -> usize { + // SAFETY: readings point at one of their hub's devices. + unsafe { (*self.device).index } + } + fn kind(&self) -> u32 { match self.value { Value::Pad(_) => GAMEPAD_KIND, @@ -325,6 +340,11 @@ struct State { pending: Vec, /// Device callbacks running now: token and thread. running: Vec<(u64, ThreadId)>, + /// The keyboard and mouse as a pad; `None`: the old stand-in pad. + controls: Option, + /// The last poll's host pads and keys, for pad reads in between. + host_pads: [Option; PADS], + keys: Vec, } pub struct Hub { @@ -333,6 +353,8 @@ pub struct Hub { /// Apart from the state: XInput can be slow, and the title reads /// readings every frame. source: Mutex>, + /// Mouse motion and wheel steps, added by the host's raw input thread. + counts: Arc, state: Mutex, /// A device callback returned. returned: Condvar, @@ -356,7 +378,12 @@ fn now() -> u64 { } impl Hub { - fn new(source: Box) -> &'static Hub { + fn new( + source: Box, + counts: Arc, + settings: super::controls::Settings, + ) -> &'static Hub { + cursor::ENABLED.store(settings.enabled && settings.capture, Ordering::Relaxed); let hub = Box::into_raw(Box::new(Hub { object: Object { vtable: &INPUT, @@ -364,11 +391,15 @@ impl Hub { }, devices: std::array::from_fn(Device::new), source: Mutex::new(source), + counts, state: Mutex::new(State { slots: Default::default(), callbacks: Vec::new(), pending: Vec::new(), running: Vec::new(), + controls: settings.enabled.then(|| Controls::new(settings)), + host_pads: [None; PADS], + keys: Vec::new(), }), returned: Condvar::new(), })); @@ -383,8 +414,12 @@ impl Hub { } /// A hub over the host's input, polled from now on. - fn start(source: Box) -> &'static Hub { - let hub = Hub::new(source); + fn start( + source: Box, + counts: Arc, + settings: super::controls::Settings, + ) -> &'static Hub { + let hub = Hub::new(source, counts, settings); hub.poll(); std::thread::spawn(move || { loop { @@ -401,12 +436,21 @@ impl Hub { /// Reads the host once; device callbacks run on the calling thread. fn poll(&self) { - let (pads, keys) = { + let (pads, keys, buttons) = { let mut source = lock(&self.source); let pads: [_; PADS] = std::array::from_fn(|slot| source.pad(slot)); - (pads, source.keys()) + (pads, source.keys(), source.mouse_buttons()) + }; + let events = { + let mut state = self.state(); + let events = state.poll(&self.devices, pads, keys, &buttons, &self.counts); + if let Some(c) = &mut state.controls + && std::mem::take(&mut c.toggle_capture) + { + cursor::toggle(); + } + events }; - let events = self.state().poll(&self.devices, pads, keys); self.deliver(events); } @@ -451,19 +495,75 @@ impl State { devices: &[Device; DEVICES], pads: [Option; PADS], keys: Vec, + mouse_buttons: &[u8], + counts: &Counts, ) -> Vec { let now = now(); let mut events = std::mem::take(&mut self.pending); - let any_pad = pads.iter().any(Option::is_some); - for (slot, pad) in pads.into_iter().enumerate() { - self.update(devices, slot, pad.map(Value::Pad), now, &mut events); + if let Some(c) = &mut self.controls { + let by_position = c.s.by_position; + let held: Vec = keys + .iter() + .map(|k| { + by_position + .then(|| super::controls::us_key(k.scan_code)) + .flatten() + .unwrap_or(k.virtual_key) + }) + .chain(mouse_buttons.iter().copied()) + .collect(); + c.feed(&held, counts); } - let fallback = (!any_pad).then(|| Value::Pad(fallback(&keys))); - self.update(devices, FALLBACK, fallback, now, &mut events); + self.host_pads = pads; + self.keys.clone_from(&keys); + self.publish(devices, now, None, &mut events); self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events); events } + /// The pad devices' readings: the host pads, the keyboard and mouse on + /// the first connected one or else on the stand-in pad. `take`: a title + /// read, which drains the mouse counts. + fn publish( + &mut self, + devices: &[Device; DEVICES], + now: u64, + take: Option<&Counts>, + events: &mut Vec, + ) { + let pads = self.host_pads; + let first = pads.iter().position(Option::is_some); + let mut values = [None; PADS + 1]; + values[..PADS].copy_from_slice(&pads); + let target = first.unwrap_or(FALLBACK); + match &mut self.controls { + Some(c) => { + let base = first.and_then(|i| pads[i]); + values[target] = Some(match take { + Some(counts) => c.take(now, base, counts), + None => c.peek(base), + }); + } + None if first.is_none() => values[FALLBACK] = Some(fallback(&self.keys)), + None => {} + } + for (index, value) in values.into_iter().enumerate() { + self.update(devices, index, value.map(Value::Pad), now, events); + } + } + + /// A title read of a pad: with keyboard and mouse, a new reading with the + /// mouse motion since the last read. + fn title_read(&mut self, devices: &[Device; DEVICES], counts: &Counts) { + if self.controls.is_none() { + return; + } + let mut events = Vec::new(); + self.publish(devices, now(), Some(counts), &mut events); + // Connections only change on host polls; keep anything for the next. + self.pending.append(&mut events); + } + /// Records a device's state: a reading when it changed, callbacks when /// the device came or went. fn update( @@ -511,12 +611,15 @@ impl State { } #[cfg(windows)] -fn host() -> Box { - Box::new(host::Host::default()) +fn host(counts: &Arc, settings: &super::controls::Settings) -> Box { + if settings.enabled { + host::raw_mouse(counts.clone()); + } + Box::new(host::Host::new(counts.clone())) } #[cfg(not(windows))] -fn host() -> Box { +fn host(_: &Arc, _: &super::controls::Settings) -> Box { struct Nothing; impl Source for Nothing { fn pad(&mut self, _: usize) -> Option { @@ -530,7 +633,99 @@ fn host() -> Box { Box::new(Nothing) } -static HUB: LazyLock<&'static Hub> = LazyLock::new(|| Hub::start(host())); +static HUB: LazyLock<&'static Hub> = LazyLock::new(|| { + let settings = super::controls::settings(); + let counts = Arc::new(Counts::default()); + Hub::start(host(&counts, &settings), counts, settings) +}); + +/// The mouse cursor while the title window has focus: captured (hidden, +/// held inside the window, its motion turns the camera) or free. The host +/// poll and the title window's procedure (`lifecycle`) keep it. +pub(crate) mod cursor { + use std::sync::atomic::{AtomicBool, Ordering}; + + /// Capture is wanted at all (`[controls]` on, `mouse_capture`). + pub(crate) static ENABLED: AtomicBool = AtomicBool::new(false); + pub(crate) static CAPTURED: AtomicBool = AtomicBool::new(false); + /// The title window has focus (kept by the host poll). + pub(crate) static FOCUSED: AtomicBool = AtomicBool::new(false); + /// The user is sizing or moving the window (between `WM_ENTERSIZEMOVE` + /// and `WM_EXITSIZEMOVE`): the cursor is theirs. + static SIZING: AtomicBool = AtomicBool::new(false); + /// How far inside the client area a captured cursor is held, so it + /// cannot reach the window's borders and start a size loop. + const INSET: i32 = 16; + + pub(crate) fn sizing() -> bool { + SIZING.load(Ordering::Relaxed) + } + + /// The window entered (`true`) or left a size or move loop. A captured + /// cursor is freed first: clipped to a client area that shrinks under + /// it, it would drag the window down to its title bar. Afterwards a + /// click in the window captures it again. + pub(crate) fn size_move(entered: bool) { + if entered { + release(); + } + SIZING.store(entered, Ordering::Relaxed); + } + + /// Whether the window gaining focus captures the cursor: not when the + /// focus came from a mouse click (a click in the client area captures by + /// itself; one on a border or the title bar starts a size or move loop + /// and must not), and not during such a loop. + pub(crate) fn captures_on_focus(was_focused: bool, focused: bool, button_down: bool) -> bool { + focused && !was_focused && !button_down && !sizing() + } + + /// Whether the cursor is held in the window now. + pub(crate) fn clips(focused: bool) -> bool { + focused && captured() && !sizing() + } + + /// Where a captured cursor is held: the client rectangle (left, top, + /// right, bottom) shrunk by [`INSET`]; `None` for one too small for that. + pub(crate) fn clip_rect(client: (i32, i32, i32, i32)) -> Option<(i32, i32, i32, i32)> { + let (l, t, r, b) = client; + let rect = (l + INSET, t + INSET, r - INSET, b - INSET); + (rect.2 > rect.0 && rect.3 > rect.1).then_some(rect) + } + + pub(crate) fn captured() -> bool { + CAPTURED.load(Ordering::Relaxed) + } + + /// Whether a capture may happen now: when capture is wanted at all + /// (`enabled`) and the window is not being sized or moved. + pub(crate) fn may_capture(enabled: bool) -> bool { + enabled && !sizing() + } + + pub(crate) fn capture() { + if may_capture(ENABLED.load(Ordering::Relaxed)) && !CAPTURED.swap(true, Ordering::Relaxed) { + tracing::info!("mouse cursor captured"); + } + } + + pub(crate) fn release() { + if CAPTURED.swap(false, Ordering::Relaxed) { + tracing::info!("mouse cursor released"); + } + } + + /// A click in the title window captures. Buttons held while it is + /// captured are no shots until they are let go (`host`). + pub(crate) fn click() { + capture(); + } + + /// The release key. + pub(crate) fn toggle() { + if captured() { release() } else { capture() } + } +} type This = *const Object; type Out = *mut *const c_void; @@ -593,7 +788,11 @@ extern "system" fn current_reading( out: Out, ) -> HRESULT { let hub = hub(this); - let state = hub.state(); + let mut state = hub.state(); + if kind & GAMEPAD_KIND != 0 { + state.title_read(&hub.devices, &hub.counts); + } + let state = state; let newest = |i: usize| { state.slots[i] .history @@ -1015,6 +1214,7 @@ extern "system" fn key_state(this: *const Reading, count: u32, out: *mut KeyStat extern "system" fn gamepad_state(this: *const Reading, out: *mut PadState) -> bool { match &reading(this).value { Value::Pad(state) if !out.is_null() => { + log_title_read(reading(this), state); // SAFETY: checked non-null. unsafe { out.write(*state) }; true @@ -1022,6 +1222,29 @@ extern "system" fn gamepad_state(this: *const Reading, out: *mut PadState) -> bo _ => false, } } +/// What the title reads, when it differs from what it read before: +/// `VICTORY_LOG=victory_hle::modules::gameinput=debug`. +fn log_title_read(reading: &Reading, state: &PadState) { + if !tracing::enabled!(tracing::Level::DEBUG) { + return; + } + static LAST: Mutex> = Mutex::new(None); + let mut last = lock(&LAST); + if *last != Some(*state) { + *last = Some(*state); + tracing::debug!( + device = reading.hub_index(), + sequence = reading.sequence, + buttons = format_args!("{:#06x}", state.buttons), + lt = state.left_trigger, + rt = state.right_trigger, + left = format_args!("{:+.3} {:+.3}", state.left_x, state.left_y), + right = format_args!("{:+.3} {:+.3}", state.right_x, state.right_y), + "title read pad" + ); + } +} + /// Kinds our devices do not have: no count, no state. extern "system" fn nothing(_: *const c_void) -> usize { 0 @@ -1072,10 +1295,19 @@ pub(crate) fn module() -> HleModule { mod host { use std::time::{Duration, Instant}; + use std::sync::atomic::Ordering; + + use windows_sys::Win32::Foundation::{POINT, RECT}; + use windows_sys::Win32::Graphics::Gdi::ClientToScreen; + use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; use windows_sys::Win32::System::Threading::GetCurrentProcessId; use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ GetAsyncKeyState, MAPVK_VK_TO_VSC_EX, MapVirtualKeyW, }; + use windows_sys::Win32::UI::Input::{ + GetRawInputData, HRAWINPUT, RAWINPUT, RAWINPUTDEVICE, RAWINPUTHEADER, RID_INPUT, + RIDEV_INPUTSINK, RIM_TYPEMOUSE, RegisterRawInputDevices, + }; use windows_sys::Win32::UI::Input::XboxController::{ XINPUT_GAMEPAD, XINPUT_GAMEPAD_A, XINPUT_GAMEPAD_B, XINPUT_GAMEPAD_BACK, XINPUT_GAMEPAD_DPAD_DOWN, XINPUT_GAMEPAD_DPAD_LEFT, XINPUT_GAMEPAD_DPAD_RIGHT, @@ -1085,9 +1317,12 @@ mod host { XInputSetState, }; use windows_sys::Win32::UI::WindowsAndMessaging::{ - GetForegroundWindow, GetWindowThreadProcessId, + ClipCursor, CreateWindowExW, DefWindowProcW, DispatchMessageW, GetClientRect, + GetForegroundWindow, GetMessageW, GetWindowThreadProcessId, HWND_MESSAGE, MSG, + RegisterClassW, WM_INPUT, WNDCLASSW, }; + use crate::modules::controls::MOUSE_BUTTONS; use super::*; /// Asking XInput about an empty slot is slow; look again this often. @@ -1127,9 +1362,203 @@ mod host { } } - #[derive(Default)] pub(super) struct Host { empty_until: [Option; PADS], + /// Where scripted mouse motion goes (diagnostics). + #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] + counts: Arc, + was_focused: bool, + was_captured: bool, + clipped: bool, + /// Mouse buttons held when the cursor was captured (the click that + /// captured it): no shots until let go. + swallowed: Vec, + #[cfg(feature = "diagnostics")] + kbm: kbm::Script, + } + + impl Host { + pub(super) fn new(counts: Arc) -> Host { + Host { + empty_until: [None; PADS], + counts, + was_focused: false, + was_captured: false, + clipped: false, + swallowed: Vec::new(), + #[cfg(feature = "diagnostics")] + kbm: kbm::Script::from_env(), + } + } + + /// Captures the cursor when the title window gets focus, frees it + /// when it loses it, and holds a captured one inside the window. + fn cursor(&mut self, focus: bool) { + cursor::FOCUSED.store(focus, Ordering::Relaxed); + if !focus { + cursor::release(); + } else if !self.was_focused { + // SAFETY: plain queries. + let button_down = MOUSE_BUTTONS + .into_iter() + .any(|vk| unsafe { GetAsyncKeyState(i32::from(vk)) } < 0); + if cursor::captures_on_focus(self.was_focused, focus, button_down) { + cursor::capture(); + } + } + self.was_focused = focus; + if cursor::clips(focus) { + // SAFETY: plain queries on the foreground window, ours. + unsafe { + let hwnd = GetForegroundWindow(); + let mut client = RECT::default(); + GetClientRect(hwnd, &mut client); + let mut corners = [ + POINT { + x: client.left, + y: client.top, + }, + POINT { + x: client.right, + y: client.bottom, + }, + ]; + ClientToScreen(hwnd, &mut corners[0]); + ClientToScreen(hwnd, &mut corners[1]); + let [a, b] = corners; + if let Some((left, top, right, bottom)) = + cursor::clip_rect((a.x, a.y, b.x, b.y)) + { + let rect = RECT { + left, + top, + right, + bottom, + }; + ClipCursor(&rect); + self.clipped = true; + } else if self.clipped { + ClipCursor(std::ptr::null()); + self.clipped = false; + } + } + } else if self.clipped { + // SAFETY: lets go of the clip we set. + unsafe { ClipCursor(std::ptr::null()) }; + self.clipped = false; + } + } + } + + /// Mouse motion and the wheel from raw input (no pointer acceleration), + /// on a thread and message-only window of its own. Counted only while the + /// cursor is captured in the focused title window. + pub(super) fn raw_mouse(counts: Arc) { + let spawned = std::thread::Builder::new() + .name("victory-mouse".into()) + .spawn(move || { + let class: Vec = "victory.mouse\0".encode_utf16().collect(); + // SAFETY: a window class and a message-only window of this + // thread; the registration names that window. + let hwnd = unsafe { + let instance = GetModuleHandleW(std::ptr::null()); + let wc = WNDCLASSW { + lpfnWndProc: Some(DefWindowProcW), + hInstance: instance, + lpszClassName: class.as_ptr(), + ..std::mem::zeroed() + }; + RegisterClassW(&wc); + CreateWindowExW( + 0, + class.as_ptr(), + std::ptr::null(), + 0, + 0, + 0, + 0, + 0, + HWND_MESSAGE, + std::ptr::null_mut(), + instance, + std::ptr::null(), + ) + }; + let device = RAWINPUTDEVICE { + usUsagePage: 1, // generic desktop + usUsage: 2, // mouse + dwFlags: RIDEV_INPUTSINK, + hwndTarget: hwnd, + }; + // SAFETY: one valid device description. + let ok = !hwnd.is_null() + && unsafe { + RegisterRawInputDevices(&device, 1, size_of::() as u32) + } != 0; + if !ok { + tracing::warn!("raw mouse input unavailable: no mouse look"); + return; + } + tracing::info!("raw mouse input on"); + let mut wheel = 0; + // SAFETY: the standard message loop of this thread's window. + unsafe { + let mut msg: MSG = std::mem::zeroed(); + while GetMessageW(&mut msg, std::ptr::null_mut(), 0, 0) > 0 { + if msg.message == WM_INPUT { + raw_input(msg.lParam as HRAWINPUT, &counts, &mut wheel); + } + DispatchMessageW(&msg); + } + } + }); + if spawned.is_err() { + tracing::warn!("no raw mouse thread: no mouse look"); + } + } + + /// One raw input event; `wheel` keeps the part of a step a fine-grained + /// wheel has turned. + fn raw_input(handle: HRAWINPUT, counts: &Counts, wheel: &mut i32) { + /// Relative motion is the default; absolute comes from tablets, + /// remote desktops and virtual machines. + const MOUSE_MOVE_ABSOLUTE: u16 = 0x1; + const RI_MOUSE_WHEEL: u16 = 0x0400; + // SAFETY: zeroed is a valid RAWINPUT; `size` is its room. + let mut raw: RAWINPUT = unsafe { std::mem::zeroed() }; + let mut size = size_of::() as u32; + // SAFETY: the handle of a WM_INPUT this thread received. + let got = unsafe { + GetRawInputData( + handle, + RID_INPUT, + (&raw mut raw).cast(), + &mut size, + size_of::() as u32, + ) + }; + if got == u32::MAX || raw.header.dwType != RIM_TYPEMOUSE { + return; + } + if !(cursor::FOCUSED.load(Ordering::Relaxed) && cursor::captured()) { + *wheel = 0; + return; + } + // SAFETY: a mouse event, so the mouse member is the one written. + let mouse = unsafe { raw.data.mouse }; + if mouse.usFlags & MOUSE_MOVE_ABSOLUTE == 0 { + counts.add(i64::from(mouse.lLastX), i64::from(mouse.lLastY)); + } + // SAFETY: both members of the button union are plain integers. + let buttons = unsafe { mouse.Anonymous.Anonymous }; + if buttons.usButtonFlags & RI_MOUSE_WHEEL != 0 { + *wheel += i32::from(buttons.usButtonData as i16); + let steps = *wheel / 120; + *wheel -= steps * 120; + if steps != 0 { + counts.add_wheel(steps); + } + } } impl Source for Host { @@ -1162,11 +1591,17 @@ mod host { } fn keys(&mut self) -> Vec { + let focus = focused(); + self.cursor(focus); #[cfg(feature = "diagnostics")] - let mut down = scripted(); + let mut down = { + let mut down = scripted(); + down.extend(self.kbm.keys(&self.counts)); + down + }; #[cfg(not(feature = "diagnostics"))] let mut down = Vec::new(); - if focused() { + if focus { // Left/right modifier keys only, as devices report them; no // mouse buttons (below 0x08). let held: Vec = (0x08..=0xFE_u8) @@ -1188,6 +1623,30 @@ mod host { .collect() } + fn mouse_buttons(&mut self) -> Vec { + let captured = cursor::FOCUSED.load(Ordering::Relaxed) && cursor::captured(); + let mut down = Vec::new(); + if captured { + let held: Vec = MOUSE_BUTTONS + .into_iter() + // SAFETY: plain queries. + .filter(|&vk| unsafe { GetAsyncKeyState(i32::from(vk)) } < 0) + .collect(); + if !self.was_captured { + self.swallowed.clone_from(&held); + } + self.swallowed.retain(|b| held.contains(b)); + down = held + .into_iter() + .filter(|b| !self.swallowed.contains(b)) + .collect(); + } + self.was_captured = captured; + #[cfg(feature = "diagnostics")] + down.extend(self.kbm.buttons()); + down + } + fn rumble(&mut self, slot: usize, low: u16, high: u16) { let speeds = XINPUT_VIBRATION { wLeftMotorSpeed: low, @@ -1237,6 +1696,121 @@ mod host { .collect() } + /// Debugging aid: `VICTORY_KBM=:[*],...` + /// plays keyboard and mouse input into the controls layer as if held + /// (with or without focus or capture). A key is a `[controls]` key name + /// (`W`, `LShift`, `MouseLeft`...) held 0.2 s unless a hold is given; + /// `MouseX=` / `MouseY=` move the mouse that far, spread + /// over the hold; `Wheel=` turns the wheel (up positive). + #[cfg(feature = "diagnostics")] + mod kbm { + use std::time::{Duration, Instant}; + + use super::super::Counts; + use crate::modules::controls::key_code; + + enum What { + Key(u8), + Mouse(f64, f64), + Wheel(i32), + } + + pub(super) struct Script { + start: Instant, + last: Duration, + entries: Vec<(Duration, Duration, What)>, + buttons: Vec, + } + + impl Script { + pub(super) fn from_env() -> Script { + let list = std::env::var("VICTORY_KBM").unwrap_or_default(); + let entries = list + .split(',') + .filter(|e| !e.trim().is_empty()) + .filter_map(|entry| { + let parsed = parse(entry); + if parsed.is_none() { + tracing::warn!(entry, "VICTORY_KBM entry not understood"); + } + parsed + }) + .collect(); + Script { + start: Instant::now(), + last: Duration::ZERO, + entries, + buttons: Vec::new(), + } + } + + /// Keys held now; adds the mouse motion since the last poll. + pub(super) fn keys(&mut self, counts: &Counts) -> Vec { + let now = self.start.elapsed(); + let last = std::mem::replace(&mut self.last, now); + let mut keys = Vec::new(); + self.buttons.clear(); + for (at, hold, what) in &self.entries { + let end = *at + *hold; + match *what { + What::Key(vk) if (*at..end).contains(&now) => { + if vk <= 0x06 { + self.buttons.push(vk); + } else { + keys.push(vk); + } + } + What::Key(_) => {} + What::Mouse(x, y) => { + let from = last.max(*at); + let to = now.min(end); + if to > from && !hold.is_zero() { + let part = (to - from).as_secs_f64() / hold.as_secs_f64(); + counts.add((x * part).round() as i64, (y * part).round() as i64); + } + } + What::Wheel(steps) => { + if last < *at && *at <= now { + counts.add_wheel(steps); + } + } + } + } + keys + } + + /// Mouse buttons held now (from the last `keys`). + pub(super) fn buttons(&self) -> Vec { + self.buttons.clone() + } + } + + fn parse(entry: &str) -> Option<(Duration, Duration, What)> { + let (at, rest) = entry.split_once(':')?; + let (what, hold) = match rest.split_once('*') { + Some((what, hold)) => (what, hold.trim().parse::().ok()?), + None => (rest, 0.2), + }; + let what = match what.trim().split_once('=') { + Some((axis, n)) => { + let n: f64 = n.trim().parse().ok()?; + match axis.trim() { + "MouseX" => What::Mouse(n, 0.0), + "MouseY" => What::Mouse(0.0, n), + "Wheel" => What::Wheel(n as i32), + _ => return None, + } + } + None => What::Key(key_code(what)?), + }; + Some(( + Duration::try_from_secs_f64(at.trim().parse().ok()?).ok()?, + Duration::try_from_secs_f64(hold).ok()?, + what, + )) + } + } + /// The foreground window is one of ours (the title's or our fallback). fn focused() -> bool { let mut process = 0; @@ -1284,6 +1858,7 @@ mod tests { struct FakeHost { pads: [Option; PADS], keys: Vec, + buttons: Vec, rumble: Vec<(usize, u16, u16)>, } @@ -1296,14 +1871,36 @@ mod tests { fn keys(&mut self) -> Vec { self.0.lock().unwrap().keys.clone() } + fn mouse_buttons(&mut self) -> Vec { + self.0.lock().unwrap().buttons.clone() + } fn rumble(&mut self, slot: usize, low: u16, high: u16) { self.0.lock().unwrap().rumble.push((slot, low, high)); } } + /// A hub with the old stand-in pad (`[controls] enabled = false`). fn fake() -> (&'static Hub, Arc>) { + fake_with(super::super::controls::Settings { + enabled: false, + ..Default::default() + }) + } + + /// A hub with keyboard and mouse controls (the defaults). + fn fake_kbm() -> (&'static Hub, Arc>) { + fake_with(super::super::controls::Settings { + deadzone: 0.0, + ..Default::default() + }) + } + + fn fake_with( + settings: super::super::controls::Settings, + ) -> (&'static Hub, Arc>) { let host = Arc::new(Mutex::new(FakeHost::default())); - let hub = Hub::new(Box::new(Fake(Arc::clone(&host)))); + let counts = Arc::new(Counts::default()); + let hub = Hub::new(Box::new(Fake(Arc::clone(&host))), counts, settings); hub.poll(); (hub, host) } @@ -1523,6 +2120,132 @@ mod tests { assert_eq!(current(hub, GAMEPAD_KIND, KEYBOARD), Err(READING_NOT_FOUND)); } + #[test] + fn keyboard_and_mouse_drive_the_stand_in_pad_without_a_host_pad() { + let (hub, host) = fake_kbm(); + { + let mut h = host.lock().unwrap(); + h.keys = vec![key(b'W'), key(0x20)]; // W, Space + h.buttons = vec![0x01]; // left mouse + } + hub.poll(); + let r = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + let p = pad(r); + assert_eq!((p.buttons, p.left_y, p.right_trigger), (X, 1.0, 1.0)); + release(r); + // The keyboard device still has its keys. + let r = current(hub, KEYBOARD_KIND, KEYBOARD).unwrap(); + let count = slot:: u32, _>(r, 0x70); + assert_eq!(count(r), 2); + release(r); + } + + /// An AZERTY keyboard: the key at the US W place types Z. It moves the + /// stick as W does (by its place), and as nothing when keys go by letter. + #[test] + fn keys_go_by_their_place_whatever_the_layout_prints() { + let azerty_z = KeyState { + scan_code: 0x11, + virtual_key: b'Z', + ..Default::default() + }; + let (hub, host) = fake_kbm(); + host.lock().unwrap().keys = vec![azerty_z]; + hub.poll(); + let r = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + assert_eq!(pad(r).left_y, 1.0, "the W place walks forward"); + release(r); + let (hub, host) = fake_with(super::super::controls::Settings { + by_position: false, + ..Default::default() + }); + host.lock().unwrap().keys = vec![azerty_z]; + hub.poll(); + let r = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + assert_eq!(pad(r).left_y, 0.0, "by letter, Z is not bound"); + release(r); + } + + /// The cursor's rules around a size or move loop (PR feedback: dragging + /// a border with a captured cursor collapsed the window, the clip + /// following the shrinking client area). + #[test] + fn a_size_or_move_loop_frees_the_cursor_and_border_clicks_do_not_capture() { + // Focus from Alt-Tab captures; focus from a click does not (the + // click captures if it lands in the client area). + assert!(cursor::captures_on_focus(false, true, false)); + assert!(!cursor::captures_on_focus(false, true, true)); + assert!(!cursor::captures_on_focus(true, true, false)); + assert!(!cursor::captures_on_focus(false, false, false)); + // The clip stays inside the client area, away from the borders. + assert_eq!(cursor::clip_rect((100, 50, 900, 650)), Some((116, 66, 884, 634))); + assert_eq!(cursor::clip_rect((0, 0, 1339, 30)), None, "a strip: no clip"); + // A size loop frees a captured cursor, holds off captures and + // clipping, and leaves the cursor free when it ends. (The capture + // flag is set directly: other tests' hubs set whether capture is + // wanted at all.) + cursor::CAPTURED.store(true, Ordering::Relaxed); + assert!(cursor::clips(true) && cursor::may_capture(true)); + cursor::size_move(true); + assert!(!cursor::captured() && !cursor::clips(true)); + assert!(!cursor::may_capture(true), "no capture during the loop"); + assert!(!cursor::captures_on_focus(false, true, false)); + cursor::size_move(false); + assert!(!cursor::captured(), "still free after the loop"); + assert!(cursor::may_capture(true), "a click in the window captures again"); + assert!(!cursor::may_capture(false)); + } + + #[test] + fn keyboard_and_mouse_ride_on_a_connected_host_pad() { + let (hub, host) = fake_kbm(); + { + let mut h = host.lock().unwrap(); + h.pads[1] = Some(PadState { + buttons: B, + left_trigger: 0.5, + ..Default::default() + }); + h.keys = vec![key(b'D'), key(0x20)]; + h.buttons = vec![0x02]; // right mouse: aim + } + hub.poll(); + let r = current(hub, GAMEPAD_KIND, 1).unwrap(); + let p = pad(r); + assert_eq!( + (p.buttons, p.left_x, p.left_trigger), + (B | X, 1.0, 1.0), + "pad and keyboard together" + ); + release(r); + assert_eq!( + current(hub, GAMEPAD_KIND, FALLBACK), + Err(DEVICE_DISCONNECTED), + "no stand-in pad beside a host pad" + ); + } + + #[test] + fn a_title_pad_read_carries_the_mouse_motion_since_its_last_read() { + let (hub, _host) = fake_kbm(); + let r = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + let first = stamp(r).0; + release(r); + std::thread::sleep(Duration::from_millis(5)); + // Below a full stick (no carry into the next read). + hub.counts.add(4, -2); + let r = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + let p = pad(r); + assert!(stamp(r).0 > first, "a new reading at the read"); + assert!(p.right_x > 0.0 && p.right_y > 0.0, "{p:?}"); + assert!((p.right_x - 2.0 * p.right_y).abs() < 1e-4, "{p:?}"); + release(r); + std::thread::sleep(Duration::from_millis(5)); + let r = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + assert_eq!(pad(r).right_x, 0.0, "no motion, no turn"); + release(r); + } + #[test] fn async_enumeration_waits_for_the_poll_and_unregistering_stops_callbacks() { let (hub, host) = fake(); diff --git a/crates/victory-hle/src/modules/lifecycle.rs b/crates/victory-hle/src/modules/lifecycle.rs index f1b577719..2757b0c9f 100644 --- a/crates/victory-hle/src/modules/lifecycle.rs +++ b/crates/victory-hle/src/modules/lifecycle.rs @@ -183,6 +183,27 @@ extern "system" fn window_proc( if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_KEYMENU as usize { return 0; } + // The mouse cursor for keyboard and mouse play (`gameinput::cursor`): + // hidden over the window while captured, captured by a click, freed when + // the window loses focus. The title still sees every message. + match message { + wm::WM_SETCURSOR + if super::gameinput::cursor::captured() && lparam as u32 & 0xFFFF == wm::HTCLIENT => + { + // SAFETY: no cursor while it is over our client area. + unsafe { wm::SetCursor(std::ptr::null_mut()) }; + return 1; + } + wm::WM_LBUTTONDOWN | wm::WM_RBUTTONDOWN | wm::WM_MBUTTONDOWN => { + super::gameinput::cursor::click(); + } + wm::WM_KILLFOCUS => super::gameinput::cursor::release(), + // Sizing or moving the window: the cursor is the user's until the + // loop ends (a clip following a shrinking client area collapses it). + wm::WM_ENTERSIZEMOVE => super::gameinput::cursor::size_move(true), + wm::WM_EXITSIZEMOVE => super::gameinput::cursor::size_move(false), + _ => {} + } // SAFETY: the procedure `hook` stored, called the way the system would. unsafe { let title = wm::GetPropW(hwnd, TITLE_PROC); diff --git a/crates/victory-hle/src/modules/mod.rs b/crates/victory-hle/src/modules/mod.rs index 51e3590bf..a1f4200cf 100644 --- a/crates/victory-hle/src/modules/mod.rs +++ b/crates/victory-hle/src/modules/mod.rs @@ -18,6 +18,7 @@ pub mod dsp; pub mod dstorage; #[cfg(windows)] pub mod files; +pub mod controls; pub mod gameinput; pub mod kernel; #[cfg(windows)] diff --git a/victory.example.toml b/victory.example.toml index 6aa1afe46..59092dd79 100644 --- a/victory.example.toml +++ b/victory.example.toml @@ -17,3 +17,29 @@ game_dir = 'D:\victory-data\game' # Other Xbox Series titles used to test platform-level code. # env: VICTORY_TEST_TITLES (separated by ';') test_titles = [] + +# Keyboard and mouse, played like a PC game (see README "Input"). Every +# entry is optional; the values shown are the defaults. +[controls] +# enabled = true # false: the old fixed stand-in pad only +# mouse_sensitivity = 1.0 # 1.0: 2,000 mouse counts/s = a full right stick +# mouse_y_scale = 1.0 # vertical sensitivity relative to horizontal +# mouse_invert_y = false +# mouse_capture = true # hide and hold the cursor while the window has focus +# mouse_carry = true # a flick past full stick is turned in full, later +# stick_deadzone = 0.3 # the title's stick dead zone, skipped over (measured) +# stick_curve = 1.0 # the title's stick response exponent, undone +# walk_speed = 0.5 # left stick while the walk key is held +# keys_by_position = true # letters = the keys at those places on a US keyboard +# # (W A S D are Z Q S D on AZERTY); false: by letter + +# Rebind keys; a table replaces only the keys it names. A value is a pad +# output (A B X Y LB RB LT RT LS RS View Menu DpadUp DpadDown DpadLeft +# DpadRight LeftUp LeftDown LeftLeft LeftRight RightUp RightDown RightLeft +# RightRight), an action (Walk ToggleVehicle ReleaseCursor), a list of +# them, or "" to unbind. +# [controls.on_foot] +# Space = "X" +# MouseLeft = "RT" +# [controls.vehicle] +# W = "RT"