diff --git a/Cargo.lock b/Cargo.lock index 8f3e15a..19c991f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -220,6 +220,19 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hidapi" +version = "2.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "818c0e1d27887aaf76fe737042e27a66b796a7b099e6d2e1a72d106c2dff3fa6" +dependencies = [ + "cc", + "cfg-if", + "libc", + "pkg-config", + "windows-sys", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -317,6 +330,12 @@ version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "proc-macro2" version = "1.0.107" @@ -689,6 +708,7 @@ dependencies = [ name = "victory-hle" version = "0.1.0" dependencies = [ + "hidapi", "opus-pure", "tempfile", "tracing", diff --git a/Cargo.toml b/Cargo.toml index 2e721fc..a576aea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,6 +35,7 @@ object = { version = "0.41.0", default-features = false, features = ["read_core" windows-sys = "0.61.2" windows = "0.62.2" windows-core = "0.62.2" +hidapi = { version = "2.6.7", default-features = false } blake3 = "1.8.7" memchr = "2.8.3" # SIMD-accelerated pure-Rust zlib/deflate (Zlib license, runtime AVX2/SSE4.2 dispatch). diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index d91f14f..25f734a 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -17,6 +17,7 @@ zlib-rs.workspace = true tracing.workspace = true [target.'cfg(windows)'.dependencies] +hidapi.workspace = true windows-sys = { workspace = true, features = [ "Win32_Foundation", "Win32_Globalization", diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index d8e7056..be4e943 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -1,8 +1,6 @@ -//! `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 -//! too. A poll thread turns host state into readings (a new one per change) -//! and runs device callbacks on connect and disconnect. +//! `gameinput.dll`: XInput pads, DualSense HID gamepads and the keyboard. +//! By default they feed one gamepad. The keyboard is also a separate device. +//! A poll thread turns host state into readings and runs device callbacks. #![allow(non_snake_case)] // Title code calls these through the objects, passing pointers the real API // would trust. @@ -21,6 +19,9 @@ use super::xasync::{E_INVALIDARG, E_NOTIMPL}; use super::xgameruntime::{HRESULT, S_OK}; use crate::{HleExport, HleModule}; +#[cfg(windows)] +mod dualsense; + /// The documented errors. pub const DEVICE_DISCONNECTED: HRESULT = 0x838A_0001_u32 as i32; pub const DEVICE_NOT_FOUND: HRESULT = 0x838A_0002_u32 as i32; @@ -52,7 +53,9 @@ const LEFT_STICK: u32 = 0x1000; const RIGHT_STICK: u32 = 0x2000; /// Devices: host pad slots, the keyboard's stand-in pad, the keyboard. -const PADS: usize = 4; +const XINPUT_PADS: usize = 4; +const DUALSENSE_PADS: usize = 4; +const PADS: usize = XINPUT_PADS + DUALSENSE_PADS; const FALLBACK: usize = PADS; const KEYBOARD: usize = PADS + 1; const DEVICES: usize = PADS + 2; @@ -107,6 +110,8 @@ const _: () = assert!(size_of::() == 12 && size_of::() == 28 /// Host input, or a fake in tests. trait Source: Send { + /// Sample buffered devices on the input poll, independent of rumble requests. + fn refresh(&mut self) {} /// The pad in host slot `slot`, `None` when the slot is empty. fn pad(&mut self, slot: usize) -> Option; /// Keys held down; none while the title's window lacks focus. @@ -221,7 +226,14 @@ impl Device { fn new(index: usize) -> Device { let mut id = [0; 32]; id[..7].copy_from_slice(b"victory"); - id[31] = index as u8 + 1; + // Keep the IDs already saved for XInput (1-4), the stand-in (5) + // and the keyboard (6). Native DualSense pads start at 7. + id[31] = match index { + FALLBACK => 5, + KEYBOARD => 6, + i if i < XINPUT_PADS => (i + 1) as u8, + _ => (index + 3) as u8, + }; let info = DeviceInfo { size: size_of::() as u32, id, @@ -432,6 +444,7 @@ impl Hub { fn poll(&self) { let (pads, keys) = { let mut source = lock(&self.source); + source.refresh(); let pads: [_; PADS] = std::array::from_fn(|slot| source.pad(slot)); (pads, source.keys()) }; @@ -1114,7 +1127,7 @@ pub(crate) fn module() -> HleModule { } } -/// Host input: XInput pads, the keyboard while our process has focus. +/// Host gamepads and the keyboard while our process has focus. #[cfg(windows)] mod host { use std::time::{Duration, Instant}; @@ -1176,11 +1189,19 @@ mod host { #[derive(Default)] pub(super) struct Host { - empty_until: [Option; PADS], + empty_until: [Option; XINPUT_PADS], + dualsense: dualsense::Controllers, } impl Source for Host { + fn refresh(&mut self) { + self.dualsense.poll(); + } + fn pad(&mut self, slot: usize) -> Option { + if slot >= XINPUT_PADS { + return self.dualsense.state(slot - XINPUT_PADS); + } if self.empty_until[slot].is_some_and(|until| Instant::now() < until) { return None; } @@ -1232,6 +1253,10 @@ mod host { } fn rumble(&mut self, slot: usize, low: u16, high: u16) { + if slot >= XINPUT_PADS { + self.dualsense.rumble(slot - XINPUT_PADS, low, high); + return; + } let speeds = XINPUT_VIBRATION { wLeftMotorSpeed: low, wRightMotorSpeed: high, @@ -1536,6 +1561,39 @@ mod tests { release(rest); } + #[cfg(windows)] + #[test] + #[ignore = "requires a Sony DualSense connected over USB or Bluetooth"] + fn connected_dualsense_delivers_a_gameinput_reading() { + let hub = Hub::new(host(), false); + let start = Instant::now(); + let slot = loop { + hub.poll(); + if let Some(slot) = (XINPUT_PADS..PADS).find(|&slot| hub.state().slots[slot].connected) + { + break slot; + } + assert!( + start.elapsed() < Duration::from_secs(8), + "no report from a connected DualSense" + ); + std::thread::sleep(POLL); + }; + // Keep the same device through another HID enumeration. + let until = Instant::now() + Duration::from_secs(3); + loop { + hub.poll(); + let reading = current(hub, GAMEPAD_KIND, slot).expect("DualSense lost its reading"); + let state = pad(reading); + release(reading); + if Instant::now() >= until { + println!("DualSense GameInput reading: {state:?}"); + break; + } + std::thread::sleep(POLL); + } + } + #[test] fn keys_feed_the_keyboard_and_the_stand_in_pad() { let (hub, host) = fake(); @@ -1588,14 +1646,26 @@ mod tests { // A pad is switched on, in any slot: its input arrives, beside the // keyboard's, and no device comes or goes. host.lock().unwrap().pads[2] = Some(PadState { buttons: A, left_y: -0.5, ..Default::default() }); + host.lock().unwrap().pads[XINPUT_PADS] = Some(PadState { + buttons: MENU, + right_trigger: 0.75, + ..Default::default() + }); hub.poll(); let p = pad(hub); - assert_eq!((p.buttons, p.left_x, p.left_y), (A, 1.0, -0.5)); + assert_eq!( + (p.buttons, p.left_x, p.left_y, p.right_trigger), + (A | MENU, 1.0, -0.5, 0.75) + ); let device: *const Device = &hub.devices[FALLBACK]; set_rumble(device, &[1.0, 0.0, 0.0, 0.0]); - assert_eq!(host.lock().unwrap().rumble, [(2, u16::MAX, 0)]); + assert_eq!( + host.lock().unwrap().rumble, + [(2, u16::MAX, 0), (XINPUT_PADS, u16::MAX, 0)] + ); // And off again. host.lock().unwrap().pads[2] = None; + host.lock().unwrap().pads[XINPUT_PADS] = None; host.lock().unwrap().keys.clear(); hub.poll(); assert_eq!(pad(hub), PadState::default()); @@ -1683,6 +1753,9 @@ mod tests { #[test] fn devices_are_found_by_id_and_rumble_reaches_the_host() { let (hub, host) = fake(); + assert_eq!(hub.devices[FALLBACK].info.id[31], 5); + assert_eq!(hub.devices[KEYBOARD].info.id[31], 6); + assert_eq!(hub.devices[XINPUT_PADS].info.id[31], 7); host.lock().unwrap().pads[2] = Some(PadState::default()); hub.poll(); let device = &hub.devices[2] as *const Device; diff --git a/crates/victory-hle/src/modules/gameinput/dualsense.rs b/crates/victory-hle/src/modules/gameinput/dualsense.rs new file mode 100644 index 0000000..ebf4f88 --- /dev/null +++ b/crates/victory-hle/src/modules/gameinput/dualsense.rs @@ -0,0 +1,323 @@ +//! Sony DualSense gamepads on the Windows HID gamepad collection. + +use std::ffi::CString; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use hidapi::{HidApi, HidDevice, HidResult}; + +use super::{ + A, B, DOWN, DUALSENSE_PADS, LEFT, LEFT_SHOULDER, LEFT_STICK, MENU, PadState, RIGHT, + RIGHT_SHOULDER, RIGHT_STICK, UP, VIEW, X, Y, +}; + +const SONY: u16 = 0x054c; +const DUALSENSE: u16 = 0x0ce6; +const SCAN_INTERVAL: Duration = Duration::from_secs(2); + +#[derive(Default)] +pub(super) struct Controllers { + slots: [Option; DUALSENSE_PADS], + api: Option, + scan: Option>>, + next_scan: Option, +} + +impl Controllers { + pub(super) fn poll(&mut self) { + if let Some(scan) = self.scan.take_if(|scan| scan.is_finished()) + && let Ok(Ok(api)) = scan.join() + { + self.update_devices(&api); + self.api = Some(api); + } + let now = Instant::now(); + if self.scan.is_none() && self.next_scan.is_none_or(|at| now >= at) { + self.next_scan = Some(now + SCAN_INTERVAL); + // Windows device enumeration can take longer than an input poll. + let api = self.api.take(); + self.scan = std::thread::Builder::new() + .name("DualSense discovery".into()) + .spawn(move || match api { + Some(mut api) => { + api.reset_devices()?; + api.add_devices(SONY, DUALSENSE)?; + Ok(api) + } + None => HidApi::new(), + }) + .ok(); + } + for slot in &mut self.slots { + if let Some(pad) = slot + && pad.poll().is_err() + { + *slot = None; + } + } + } + + fn update_devices(&mut self, api: &HidApi) { + let devices: Vec<_> = api + .device_list() + .filter(|info| { + info.vendor_id() == SONY + && info.product_id() == DUALSENSE + && info.usage_page() == 0x01 + && info.usage() == 0x05 + }) + .collect(); + for slot in &mut self.slots { + if let Some(pad) = slot + && !devices + .iter() + .any(|info| info.path() == pad.path.as_c_str()) + { + *slot = None; + } + } + for info in devices { + if self + .slots + .iter() + .flatten() + .any(|pad| pad.path.as_c_str() == info.path()) + { + continue; + } + let Some(slot) = self.slots.iter_mut().find(|slot| slot.is_none()) else { + break; + }; + if let Ok(device) = info.open_device(api) { + tracing::info!(transport = ?info.bus_type(), "DualSense gamepad connected"); + *slot = Some(Controller { + path: info.path().to_owned(), + device, + state: None, + bluetooth: false, + motors: [0; 2], + sent_motors: Some([0; 2]), + retry_rumble: None, + sequence: 0, + }); + } + } + } + + pub(super) fn state(&self, slot: usize) -> Option { + self.slots[slot].as_ref()?.state + } + + pub(super) fn rumble(&mut self, slot: usize, low: u16, high: u16) { + if let Some(pad) = &mut self.slots[slot] { + pad.motors = [(low >> 8) as u8, (high >> 8) as u8]; + } + } +} + +struct Controller { + path: CString, + device: HidDevice, + state: Option, + bluetooth: bool, + motors: [u8; 2], + sent_motors: Option<[u8; 2]>, + retry_rumble: Option, + sequence: u8, +} + +impl Controller { + fn poll(&mut self) -> HidResult<()> { + let mut report = [0; 78]; + // Drain old readings without waiting for another packet. A poll with + // no new report must keep held buttons and analog positions intact. + for _ in 0..64 { + let len = self.device.read_timeout(&mut report, 0)?; + if len == 0 { + break; + } + if let Some(state) = decode(&report[..len]) { + self.state = Some(state); + self.bluetooth = len != 64; + } + } + if self.state.is_some() + && self.sent_motors != Some(self.motors) + && self.retry_rumble.is_none_or(|at| Instant::now() >= at) + { + let mut output = [0; 78]; + let len = rumble_report(&mut output, self.bluetooth, self.sequence, self.motors); + match self.device.write(&output[..len]) { + Ok(written) if written == len => { + self.sent_motors = Some(self.motors); + self.retry_rumble = None; + } + result => { + // Keep reading input and retry the latest motor command, including a stop. + tracing::debug!(?result, "DualSense rumble write incomplete"); + self.sent_motors = None; + self.retry_rumble = Some(Instant::now() + Duration::from_secs(1)); + } + } + self.sequence = self.sequence.wrapping_add(1); + } + Ok(()) + } +} + +fn decode(report: &[u8]) -> Option { + // Windows pads the 10-byte simple Bluetooth report to 78 bytes. + // Extended Bluetooth adds a tag before the common USB state layout. + let (data, triggers, buttons) = match (report.first()?, report.len()) { + (0x01, 10 | 78) => (&report[1..], 7, 4), + (0x01, 64) => (&report[1..], 4, 7), + (0x31, 78) => (&report[2..], 4, 7), + _ => return None, + }; + const HAT: [u32; 8] = [ + UP, + UP | RIGHT, + RIGHT, + RIGHT | DOWN, + DOWN, + DOWN | LEFT, + LEFT, + LEFT | UP, + ]; + const BUTTONS: [(u16, u32); 10] = [ + (0x0010, X), + (0x0020, A), + (0x0040, B), + (0x0080, Y), + (0x0100, LEFT_SHOULDER), + (0x0200, RIGHT_SHOULDER), + (0x1000, VIEW), + (0x2000, MENU), + (0x4000, LEFT_STICK), + (0x8000, RIGHT_STICK), + ]; + let hat = usize::from(data[buttons] & 0x0f); + let bits = u16::from_le_bytes([data[buttons], data[buttons + 1]]); + let mut pressed = HAT.get(hat).copied().unwrap_or(0); + for (mask, button) in BUTTONS { + if bits & mask != 0 { + pressed |= button; + } + } + let stick = |v: u8| (f32::from(v) - 128.0) / if v < 128 { 128.0 } else { 127.0 }; + Some(PadState { + buttons: pressed, + left_trigger: f32::from(data[triggers]) / 255.0, + right_trigger: f32::from(data[triggers + 1]) / 255.0, + left_x: stick(data[0]), + left_y: -stick(data[1]), + right_x: stick(data[2]), + right_y: -stick(data[3]), + }) +} + +fn rumble_report( + report: &mut [u8; 78], + bluetooth: bool, + sequence: u8, + [low, high]: [u8; 2], +) -> usize { + let offset = if bluetooth { + report[..3].copy_from_slice(&[0x31, sequence << 4, 0x10]); + 3 + } else { + report[0] = 0x02; + 1 + }; + // Enable the two compatibility vibration motors. Other effects stay under their own flags. + report[offset..offset + 4].copy_from_slice(&[0x03, 0, high, low]); + if bluetooth { + use zlib_rs::crc32::crc32; + let crc = crc32(crc32(0, &[0xa2]), &report[..74]); + report[74..].copy_from_slice(&crc.to_le_bytes()); + 78 + } else { + 48 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn usb_and_both_bluetooth_modes_give_the_same_reading() { + let simple = [1, 0, 255, 128, 0, 0x23, 0x11, 0, 64, 255]; + let mut padded = [0; 78]; + padded[..simple.len()].copy_from_slice(&simple); + let mut usb = [0; 64]; + usb[..10].copy_from_slice(&[1, 0, 255, 128, 0, 64, 255, 0x77, 0x23, 0x11]); + let mut extended = [0; 78]; + extended[..2].copy_from_slice(&[0x31, 0x72]); + extended[2..65].copy_from_slice(&usb[1..]); + let expected = PadState { + buttons: A | DOWN | RIGHT | LEFT_SHOULDER | VIEW, + left_x: -1.0, + left_y: -1.0, + right_x: 0.0, + right_y: 1.0, + left_trigger: 64.0 / 255.0, + right_trigger: 1.0, + }; + for report in [simple.as_slice(), &padded, &usb, &extended] { + assert_eq!(decode(report), Some(expected)); + } + for report in [&[][..], &simple[..9], &extended[..64], &[0xff; 78]] { + assert_eq!(decode(report), None); + } + } + + #[test] + fn face_buttons_shoulders_and_stick_clicks_use_xbox_positions() { + let mut simple = [1, 128, 128, 128, 128, 8, 0, 0, 0, 0]; + assert_eq!(decode(&simple), Some(PadState::default())); + for (mask, expected) in [ + (0x10, X), + (0x20, A), + (0x40, B), + (0x80, Y), + (0x100, LEFT_SHOULDER), + (0x200, RIGHT_SHOULDER), + (0x1000, VIEW), + (0x2000, MENU), + (0x4000, LEFT_STICK), + (0x8000, RIGHT_STICK), + ] { + simple[5..7].copy_from_slice(&(mask | 8u16).to_le_bytes()); + assert_eq!(decode(&simple).unwrap().buttons, expected); + } + for (hat, expected) in [ + UP, + UP | RIGHT, + RIGHT, + RIGHT | DOWN, + DOWN, + DOWN | LEFT, + LEFT, + LEFT | UP, + 0, + ] + .into_iter() + .enumerate() + { + simple[5..7].copy_from_slice(&[hat as u8, 0]); + assert_eq!(decode(&simple).unwrap().buttons, expected); + } + } + + #[test] + fn rumble_uses_the_transport_header_motor_order_and_bluetooth_crc() { + let mut usb = [0; 78]; + assert_eq!(rumble_report(&mut usb, false, 3, [0x12, 0x34]), 48); + assert_eq!(&usb[..5], &[2, 3, 0, 0x34, 0x12]); + let mut bt = [0; 78]; + assert_eq!(rumble_report(&mut bt, true, 3, [0x12, 0x34]), 78); + assert_eq!(&bt[..7], &[0x31, 0x30, 0x10, 3, 0, 0x34, 0x12]); + assert_eq!(&bt[74..], &0x98cd22bau32.to_le_bytes()); + } +} diff --git a/docs/README-fxceless.md b/docs/README-fxceless.md index 7e3e64b..ff4ecb1 100644 --- a/docs/README-fxceless.md +++ b/docs/README-fxceless.md @@ -200,7 +200,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, DualSense (USB and Bluetooth), keyboard, keyboard stand-in pad | Trigger rumble | | 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 | The scene is drawn and presented: mesh pipelines, indirect execution, views the shaders pick from the heap themselves, title memory read by address (ray-tracing structures), depth written from compute, pipelines pre-built or made by worker threads and kept on disk | Lighting (surfaces are unlit) and some missing geometry; frames take 1-2 s; draws of untranslated shaders are dropped; real queries, depth bounds, HDR and scaling are missing | @@ -250,8 +250,9 @@ limits them. This scales the displayed image; it does not change the console render resolution or the swap-chain buffers. With the variable unset, window sizing is unchanged. -Input: XInput pads. With none connected the keyboard is a pad while the -title's window has focus: +XInput pads and Sony DualSense controllers feed the same in-game pad by default. +DualSense works over USB and Bluetooth. The keyboard also controls that pad +while the title's window has focus. | Keys | Pad | |------|-----|