diff --git a/PLAY_FRAMEGEN.bat b/PLAY_FRAMEGEN.bat new file mode 100644 index 0000000..f55ef11 --- /dev/null +++ b/PLAY_FRAMEGEN.bat @@ -0,0 +1,45 @@ +@echo off +rem One-click GTA VI on VIctory-NVIDIA (DLSS + frame generation). ASCII only. +rem PLAY_FRAMEGEN.bat menu +rem PLAY_FRAMEGEN.bat 1..6 start that mode directly +rem PLAY_FRAMEGEN.bat check only show paths and what is ready +setlocal +set "PS1=%~dp0scripts\play-gta6-framegen.ps1" +set "PSH=powershell" +where pwsh >nul 2>nul && set "PSH=pwsh" +if not exist "%PS1%" ( + echo Not found: %PS1% + pause + exit /b 1 +) +if /i "%~1"=="check" ( + %PSH% -NoProfile -File "%PS1%" -Check + pause + exit /b 0 +) +set "PICK=%~1" +if not "%PICK%"=="" goto :run + +echo ================================================ +echo GTA VI - VIctory-NVIDIA, DLSS + frame generation +echo (RTX 50: frame generation 4x automatically) +echo ================================================ +echo 1. Series X 1440p + DLSS Quality + frame gen (recommended) +echo 2. Series X 1440p + DLSS Quality, no frame gen +echo 3. Series S + DLSS Quality + frame gen (faster, softer) +echo 4. Series X 1440p + DLSS Performance + frame gen +echo 5. EXTREME Series S: DLSS Performance + frame gen + big pools + High priority +echo 6. EXTREME Series X: 1440p DLSS Performance + frame gen + big pools + High priority +echo Q. Quit +echo. +choice /c 123456Q /n /m "Choose 1-6 or Q: " +if errorlevel 7 goto :end +if errorlevel 6 (set "PICK=6") else if errorlevel 5 (set "PICK=5") else if errorlevel 4 (set "PICK=4") else if errorlevel 3 (set "PICK=3") else if errorlevel 2 (set "PICK=2") else (set "PICK=1") + +:run +echo. +%PSH% -NoProfile -File "%PS1%" -Mode %PICK% + +:end +echo. +pause diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index 6d86b03..9262b6c 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -18,6 +18,8 @@ tracing.workspace = true [target.'cfg(windows)'.dependencies] windows-sys = { workspace = true, features = [ + "Win32_Devices_DeviceAndDriverInstallation", + "Win32_Devices_HumanInterfaceDevice", "Win32_Foundation", "Win32_Globalization", "Win32_Graphics_Gdi", diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index d09ebc0..3ef9c47 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -21,6 +21,10 @@ use super::xasync::{E_INVALIDARG, E_NOTIMPL}; use super::xgameruntime::{HRESULT, S_OK}; use crate::{HleExport, HleModule}; +// PS5 pads (DualSense, DualSense Edge) read straight from HID, USB or Bluetooth (from AnyXboxX's VIctory copy). +#[cfg(any(windows, test))] +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; @@ -1207,6 +1211,25 @@ mod host { pub(super) struct Host { empty_until: [Option; PADS], mouse: MouseState, + /// The input snapshot for this poll and the HID connection owning each slot. + pads: [Option; PADS], + hid_slots: [Option; PADS], + } + + impl Host { + fn xinput(&mut self, slot: usize) -> Option { + if self.empty_until[slot].is_some_and(|until| Instant::now() < until) { + return None; + } + let mut state = XINPUT_STATE::default(); + // SAFETY: room for the state. + if unsafe { XInputGetState(slot as u32, &mut state) } != 0 { + self.empty_until[slot] = Some(Instant::now() + EMPTY_SLOT_RECHECK); + return None; + } + self.empty_until[slot] = None; + Some(convert(&state.Gamepad)) + } } impl Source for Host { @@ -1220,18 +1243,18 @@ mod host { Some(self.mouse) } fn pad(&mut self, slot: usize) -> Option { - if self.empty_until[slot].is_some_and(|until| Instant::now() < until) { - return None; + // XInput first; HID PS5 pads take the slots XInput leaves free (`VICTORY_DUALSENSE`: 0 off, 1 both). + if slot == 0 { + let xinput = std::array::from_fn(|slot| self.xinput(slot)); + self.pads = super::dualsense::slots( + super::dualsense::mode(), + xinput, + &mut self.hid_slots, + super::dualsense::pads, + ); } - let mut state = XINPUT_STATE::default(); - // SAFETY: room for the state. - if unsafe { XInputGetState(slot as u32, &mut state) } != 0 { - self.empty_until[slot] = Some(Instant::now() + EMPTY_SLOT_RECHECK); - return None; - } - self.empty_until[slot] = None; #[allow(unused_mut)] - let mut pad = convert(&state.Gamepad); + let mut pad = self.pads[slot]?; // The scripted keys (`VICTORY_KEYS`) also press the first // pad's buttons, by the stand-in pad's table: with a real pad // connected the stand-in is not there, and a title that listens 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..568cb3b --- /dev/null +++ b/crates/victory-hle/src/modules/gameinput/dualsense.rs @@ -0,0 +1,670 @@ +//! PlayStation 5 pads (DualSense, DualSense Edge) read straight from HID: +//! they are not XInput devices, so without a remapper (Steam Input, +//! DS4Windows) XInput never lists them. Reports can be USB or Bluetooth. A scan +//! thread looks for new pads every [`SCAN`]; each pad has a reader thread +//! that keeps its latest state until the pad goes away. By default XInput +//! has priority over HID, since a remapper can present the same pad twice. + +use super::{ + A, B, DOWN, LEFT, LEFT_SHOULDER, LEFT_STICK, MENU, PadState, RIGHT, RIGHT_SHOULDER, + RIGHT_STICK, UP, VIEW, X, Y, +}; + +#[cfg(windows)] +const SONY: u16 = 0x054C; +/// DualSense, DualSense Edge. +#[cfg(windows)] +const PRODUCTS: [u16; 2] = [0x0CE6, 0x0DF2]; + +/// The D-pad hat (low nibble of the first button byte): 0 up, clockwise in +/// eighths, 8 and above centred. +fn hat(value: u8) -> u32 { + match value & 0xF { + 0 => UP, + 1 => UP | RIGHT, + 2 => RIGHT, + 3 => RIGHT | DOWN, + 4 => DOWN, + 5 => DOWN | LEFT, + 6 => LEFT, + 7 => LEFT | UP, + _ => 0, + } +} + +/// Face buttons in the first button byte, the rest in the second and third +/// (the PS button and the mute button have no console pad button). +const BUTTONS: [(usize, u8, u32); 11] = [ + (0, 0x10, X), // square + (0, 0x20, A), // cross + (0, 0x40, B), // circle + (0, 0x80, Y), // triangle + (1, 0x01, LEFT_SHOULDER), + (1, 0x02, RIGHT_SHOULDER), + (1, 0x10, VIEW), // create + (1, 0x20, MENU), // options + (1, 0x40, LEFT_STICK), + (1, 0x80, RIGHT_STICK), + (2, 0x02, VIEW), // touchpad click +]; + +/// The pad in one input report, `None` for a report of another kind. +/// `bluetooth`: the pad is connected over Bluetooth, where the full report +/// is 0x31 (one byte further in) and 0x01 is the short report the pad sends +/// before it was asked for the full one. +pub(super) fn parse(report: &[u8], bluetooth: bool) -> Option { + // Offsets of the sticks (LX LY RX RY), the triggers (L2 R2) and the + // three button bytes. + let (sticks, triggers, buttons) = match (report.first()?, bluetooth) { + (0x01, false) => (1, 5, 8), + (0x31, true) => (2, 6, 9), + (0x01, true) => (1, 8, 5), + _ => return None, + }; + if report.len() < sticks + 4 || report.len() < triggers + 2 || report.len() < buttons + 3 { + return None; + } + let bytes = &report[buttons..buttons + 3]; + // 0 to 255 with 128 centred; down is positive on the pad, up here. + let axis = |v: u8| ((f32::from(v) - 127.5) / 127.5).clamp(-1.0, 1.0); + Some(PadState { + buttons: BUTTONS + .iter() + .filter(|&&(byte, mask, _)| bytes[byte] & mask != 0) + .fold(hat(bytes[0]), |all, &(_, _, bit)| all | bit), + left_trigger: f32::from(report[triggers]) / 255.0, + right_trigger: f32::from(report[triggers + 1]) / 255.0, + left_x: axis(report[sticks]), + left_y: -axis(report[sticks + 1]), + right_x: axis(report[sticks + 2]), + right_y: -axis(report[sticks + 3]), + }) +} + +/// The Bluetooth address in a pairing feature report (0x09, the address at +/// 1..7 on both transports), `None` when it is too short or all zeros. +fn mac(pairing: &[u8]) -> Option<[u8; 6]> { + let mac: [u8; 6] = pairing.get(1..7)?.try_into().ok()?; + (mac != [0; 6]).then_some(mac) +} + +#[cfg(windows)] +pub(super) use host::pads; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum Mode { + Off, + Auto, + Both, +} + +#[cfg(windows)] +pub(super) fn mode() -> Mode { + static MODE: std::sync::LazyLock = + std::sync::LazyLock::new(|| match std::env::var("VICTORY_DUALSENSE").as_deref() { + Ok("0") => Mode::Off, + Ok("1") => Mode::Both, + _ => Mode::Auto, + }); + *MODE +} + +/// XInput does not identify the corresponding physical HID device. Prefer +/// it in automatic mode. If both sources are requested, retain the slot of +/// every connected HID pad unless that slot has been claimed by XInput. +pub(super) fn slots( + mode: Mode, + mut xinput: [Option; super::PADS], + assigned: &mut [Option; super::PADS], + hid: impl FnOnce() -> Vec<(u64, PadState)>, +) -> [Option; super::PADS] { + if mode == Mode::Off || mode == Mode::Auto && xinput.iter().any(Option::is_some) { + assigned.fill(None); + return xinput; + } + let pads = hid(); + for (slot, owner) in xinput.iter_mut().zip(assigned.iter_mut()) { + if slot.is_none() + && let Some((_, state)) = pads.iter().find(|(id, _)| Some(*id) == *owner) + { + *slot = Some(*state); + } else { + *owner = None; + } + } + for (id, state) in pads { + if assigned.contains(&Some(id)) { + continue; + } + let Some(slot) = xinput.iter().position(Option::is_none) else { + break; + }; + xinput[slot] = Some(state); + assigned[slot] = Some(id); + } + xinput +} + +#[cfg(windows)] +mod host { + use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::{LazyLock, Mutex, PoisonError}; + use std::time::Duration; + + use windows_sys::Win32::Devices::DeviceAndDriverInstallation::{ + DIGCF_DEVICEINTERFACE, DIGCF_PRESENT, SP_DEVICE_INTERFACE_DATA, + SP_DEVICE_INTERFACE_DETAIL_DATA_W, SetupDiDestroyDeviceInfoList, + SetupDiEnumDeviceInterfaces, SetupDiGetClassDevsW, SetupDiGetDeviceInterfaceDetailW, + }; + use windows_sys::Win32::Devices::HumanInterfaceDevice::{ + HIDD_ATTRIBUTES, HIDP_CAPS, HIDP_STATUS_SUCCESS, HidD_FreePreparsedData, + HidD_GetAttributes, HidD_GetFeature, HidD_GetHidGuid, HidD_GetPreparsedData, HidP_GetCaps, + }; + use windows_sys::Win32::Foundation::{ + CloseHandle, ERROR_IO_PENDING, GENERIC_READ, GENERIC_WRITE, GetLastError, HANDLE, + INVALID_HANDLE_VALUE, WAIT_TIMEOUT, + }; + use windows_sys::Win32::Storage::FileSystem::{ + CreateFileW, FILE_FLAG_OVERLAPPED, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, + ReadFile, + }; + use windows_sys::Win32::System::IO::{ + CancelIoEx, GetOverlappedResult, GetOverlappedResultEx, OVERLAPPED, + }; + use windows_sys::Win32::System::Threading::CreateEventW; + + use super::{PRODUCTS, PadState, SONY, mac, parse}; + + /// How often to look for newly connected pads. + const SCAN: Duration = Duration::from_secs(2); + + /// A pad in full-report mode sends reports all the time (hundreds a + /// second); this long without one and we ask it whether it is still + /// there. Over Bluetooth Windows can keep the device after the pad is + /// switched off or out of range, and a read then waits for ever. + const QUIET_MS: u32 = 500; + + struct Pad { + /// This connection's: a pad that reconnects gets a new one. + id: u64, + path: Vec, + /// The pad's Bluetooth address, the same over USB and Bluetooth: + /// one pad seen through both is opened once. + mac: Option<[u8; 6]>, + /// `None` until the first report, and while the pad is silent. + state: Option, + } + + /// The open pads, in the order they were found. + static PADS: Mutex> = Mutex::new(Vec::new()); + + fn lock() -> std::sync::MutexGuard<'static, Vec> { + PADS.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Paths found to be a pad already open over its other transport, with + /// its address: not opened again on every scan (two feature reports + /// and a log line each time) while that pad stays open. + static TWINS: Mutex, [u8; 6])>> = Mutex::new(Vec::new()); + + /// The open pads' latest states with their connection ids, oldest + /// connection first, without the pads that are silent or yet to report; + /// the first call starts looking for them. + pub(in super::super) fn pads() -> Vec<(u64, PadState)> { + static STARTED: LazyLock<()> = LazyLock::new(|| { + std::thread::spawn(|| { + loop { + scan(); + std::thread::sleep(SCAN); + } + }); + }); + LazyLock::force(&STARTED); + lock() + .iter() + .filter_map(|pad| Some((pad.id, pad.state?))) + .collect() + } + + /// Windows sizes each report buffer for its top-level HID collection. + /// The calibration and pairing reports use the same feature buffer. + struct Reports { + input: Vec, + feature: Vec, + } + + impl Reports { + fn for_device(handle: HANDLE) -> Option { + let mut data = 0; + // SAFETY: the device is open and the output is writable. + if !unsafe { HidD_GetPreparsedData(handle, &mut data) } { + return None; + } + let mut caps = HIDP_CAPS::default(); + // SAFETY: `data` was obtained above and is released after its last use. + let status = unsafe { HidP_GetCaps(data, &mut caps) }; + unsafe { HidD_FreePreparsedData(data) }; + if status != HIDP_STATUS_SUCCESS + || caps.InputReportByteLength == 0 + || caps.FeatureReportByteLength == 0 + { + return None; + } + Some(Self { + input: vec![0; usize::from(caps.InputReportByteLength)], + feature: vec![0; usize::from(caps.FeatureReportByteLength)], + }) + } + } + + /// Feature report `id` into `buffer` (its first byte), `false` when the + /// pad did not answer. A round trip to the pad, so over Bluetooth it also + /// tells whether the pad is still there. + fn feature(handle: HANDLE, id: u8, buffer: &mut [u8]) -> bool { + buffer.fill(0); + buffer[0] = id; + // SAFETY: the buffer is as long as we say. + unsafe { HidD_GetFeature(handle, buffer.as_mut_ptr().cast(), buffer.len() as u32) } + } + + /// Asks for the calibration report: it switches a pad on Bluetooth to + /// full reports (0x31), again after it reconnected; over USB it changes + /// nothing. `false` when the pad did not answer. + fn full_reports(handle: HANDLE, buffer: &mut [u8]) -> bool { + feature(handle, 0x05, buffer) + } + + /// Opens the pads not open yet, each with a reader thread. + fn scan() { + let paths = hid_paths(); + { + let pads = lock(); + // A twin whose pad went away is opened again: over USB, say, + // after the Bluetooth link dropped with the cable still in. + TWINS + .lock() + .unwrap_or_else(PoisonError::into_inner) + .retain(|(path, mac)| { + paths.contains(path) && pads.iter().any(|pad| pad.mac == Some(*mac)) + }); + } + for path in paths { + // Cheap filter before opening anything: Sony's vendor id is in + // the path, as `vid_054c` (USB) or `vid&0002054c` (Bluetooth). + let lower = String::from_utf16_lossy(&path).to_ascii_lowercase(); + if !lower.contains("054c") { + continue; + } + if lock().iter().any(|pad| pad.path == path) + || TWINS + .lock() + .unwrap_or_else(PoisonError::into_inner) + .iter() + .any(|(twin, _)| *twin == path) + { + continue; + } + let Some((handle, mut reports)) = open(&path) else { + continue; + }; + let bluetooth = lower.contains("{00001124-"); + // A paired pad that is switched off can still be listed over + // Bluetooth: it does not answer. + if !full_reports(handle, &mut reports.feature) { + tracing::debug!(path = %lower, "DualSense listed but not answering"); + // SAFETY: just opened, nothing else has it. + unsafe { CloseHandle(handle) }; + continue; + } + let mac = if feature(handle, 0x09, &mut reports.feature) { + mac(&reports.feature) + } else { + None + }; + static NEXT_ID: AtomicU64 = AtomicU64::new(0); + let id = { + let mut pads = lock(); + let twin = mac.is_some() && pads.iter().any(|pad| pad.mac == mac); + (!twin).then(|| { + let id = NEXT_ID.fetch_add(1, Ordering::Relaxed); + pads.push(Pad { + id, + path: path.clone(), + mac, + state: None, + }); + id + }) + }; + let Some(id) = id else { + tracing::info!(path = %lower, bluetooth, "DualSense already open over the other transport"); + if let Some(mac) = mac { + TWINS + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push((path, mac)); + } + // SAFETY: just opened, nothing else has it. + unsafe { CloseHandle(handle) }; + continue; + }; + tracing::info!(path = %lower, bluetooth, "DualSense connected"); + let raw = handle as usize; + if let Err(error) = std::thread::Builder::new() + .name("DualSense reader".into()) + .spawn(move || read(raw as HANDLE, id, bluetooth, reports)) + { + lock().retain(|pad| pad.id != id); + // SAFETY: just opened, and no reader has it. + unsafe { CloseHandle(handle) }; + tracing::warn!(%error, "could not start a DualSense reader"); + } + } + } + + /// Reads reports until the pad goes away, then forgets it. + fn read(handle: HANDLE, id: u64, bluetooth: bool, mut reports: Reports) { + let set = |state: Option| { + if let Some(pad) = lock().iter_mut().find(|pad| pad.id == id) { + pad.state = state; + } + }; + // SAFETY: an unnamed manual-reset event; no security attributes. + let event = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) }; + let why = 'pad: loop { + if event.is_null() { + break 'pad "no event"; + } + // SAFETY: plain data; only the event is set. + let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() }; + overlapped.hEvent = event; + let mut got = 0; + // SAFETY: the buffer and `overlapped` outlive the read: every way + // out below waits for it to end first. + let started = unsafe { + ReadFile( + handle, + reports.input.as_mut_ptr(), + reports.input.len() as u32, + std::ptr::null_mut(), + &mut overlapped, + ) + }; + // SAFETY: plain query. + if started == 0 && unsafe { GetLastError() } != ERROR_IO_PENDING { + break 'pad "read failed"; + } + loop { + // SAFETY: the read started above. + let done = + unsafe { GetOverlappedResultEx(handle, &overlapped, &mut got, QUIET_MS, 0) }; + if done != 0 { + if got == 0 { + break 'pad "read nothing"; + } + break; + } + // SAFETY: plain query. + if unsafe { GetLastError() } != WAIT_TIMEOUT { + break 'pad "read failed"; + } + // Silent: whatever was held is not held any more, and the + // pad may be gone without the read failing. + set(None); + if !full_reports(handle, &mut reports.feature) { + // SAFETY: cancel the read and wait for it to end, so + // nothing writes into the input buffer once we return. + unsafe { + CancelIoEx(handle, &overlapped); + GetOverlappedResult(handle, &overlapped, &mut got, 1); + } + break 'pad "not answering"; + } + } + if let Some(state) = parse(&reports.input[..got as usize], bluetooth) { + set(Some(state)); + } + }; + tracing::info!(why, bluetooth, "DualSense disconnected"); + lock().retain(|pad| pad.id != id); + // SAFETY: ours, and nothing uses them any more. + unsafe { + if !event.is_null() { + CloseHandle(event); + } + CloseHandle(handle); + } + } + + /// The pad at `path` opened for reading, `None` when it is something else + /// or cannot be opened. + fn open(path: &[u16]) -> Option<(HANDLE, Reports)> { + let mut name = path.to_vec(); + name.push(0); + // SAFETY: a terminated path; no security attributes or template. + let handle = unsafe { + CreateFileW( + name.as_ptr(), + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + std::ptr::null(), + OPEN_EXISTING, + FILE_FLAG_OVERLAPPED, + std::ptr::null_mut(), + ) + }; + if handle == INVALID_HANDLE_VALUE { + return None; + } + let mut attributes = HIDD_ATTRIBUTES { + Size: size_of::() as u32, + ..Default::default() + }; + // SAFETY: an open device and room for its attributes. + let ours = unsafe { HidD_GetAttributes(handle, &mut attributes) } + && attributes.VendorID == SONY + && PRODUCTS.contains(&attributes.ProductID); + if ours && let Some(reports) = Reports::for_device(handle) { + return Some((handle, reports)); + } + // SAFETY: just opened. + unsafe { CloseHandle(handle) }; + None + } + + /// The device paths of the HID devices present, without terminators. + fn hid_paths() -> Vec> { + let mut paths = Vec::new(); + // SAFETY: plain queries into buffers we own; the list is destroyed + // before returning. + unsafe { + let mut guid = std::mem::zeroed(); + HidD_GetHidGuid(&mut guid); + let set = SetupDiGetClassDevsW( + &guid, + std::ptr::null(), + std::ptr::null_mut(), + DIGCF_PRESENT | DIGCF_DEVICEINTERFACE, + ); + if set == INVALID_HANDLE_VALUE as isize { + return paths; + } + for index in 0.. { + let mut interface = SP_DEVICE_INTERFACE_DATA { + cbSize: size_of::() as u32, + ..std::mem::zeroed() + }; + if SetupDiEnumDeviceInterfaces(set, std::ptr::null(), &guid, index, &mut interface) + == 0 + { + break; + } + let mut size = 0; + SetupDiGetDeviceInterfaceDetailW( + set, + &interface, + std::ptr::null_mut(), + 0, + &mut size, + std::ptr::null_mut(), + ); + if size == 0 { + continue; + } + // u64s keep the detail's alignment. + let mut buffer = vec![0u64; (size as usize).div_ceil(8)]; + let detail = buffer + .as_mut_ptr() + .cast::(); + (*detail).cbSize = size_of::() as u32; + if SetupDiGetDeviceInterfaceDetailW( + set, + &interface, + detail, + size, + std::ptr::null_mut(), + std::ptr::null_mut(), + ) == 0 + { + continue; + } + let start = std::ptr::addr_of!((*detail).DevicePath).cast::(); + let room = (size as usize + - std::mem::offset_of!(SP_DEVICE_INTERFACE_DETAIL_DATA_W, DevicePath)) + / 2; + let wide = std::slice::from_raw_parts(start, room); + let end = wide.iter().position(|&c| c == 0).unwrap_or(room); + paths.push(wide[..end].to_vec()); + } + SetupDiDestroyDeviceInfoList(set); + } + paths + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn automatic_input_prefers_the_remapper_in_any_slot_and_falls_back_to_hid() { + let physical = PadState { + buttons: A, + ..PadState::default() + }; + let remapped = PadState { + buttons: Y, + ..PadState::default() + }; + let mut assigned = [None; super::super::PADS]; + let none = [None; super::super::PADS]; + let xinput = [None, None, Some(remapped), None]; + + assert_eq!( + slots(Mode::Auto, none, &mut assigned, || vec![(1, physical)])[0], + Some(physical) + ); + assert_eq!( + slots(Mode::Auto, xinput, &mut assigned, || panic!( + "HID not needed" + )), + xinput + ); + assert_eq!( + slots(Mode::Off, none, &mut assigned, || panic!("HID disabled")), + none + ); + assert_eq!( + slots(Mode::Auto, none, &mut assigned, || vec![(2, physical)])[0], + Some(physical) + ); + } + + #[test] + fn a_surviving_hid_pad_keeps_its_slot_through_disconnect_and_reconnect() { + let a = PadState { + buttons: A, + ..PadState::default() + }; + let b = PadState { + buttons: B, + ..PadState::default() + }; + let x = PadState { + buttons: X, + ..PadState::default() + }; + let xinput = [None, Some(x), None, None]; + let mut assigned = [None; super::super::PADS]; + assert_eq!( + slots(Mode::Both, xinput, &mut assigned, || vec![(7, a), (8, b)]), + [Some(a), Some(x), Some(b), None] + ); + assert_eq!( + slots(Mode::Both, xinput, &mut assigned, || vec![(8, b)]), + [None, Some(x), Some(b), None] + ); + assert_eq!( + slots(Mode::Both, xinput, &mut assigned, || vec![(8, b), (9, a)]), + [Some(a), Some(x), Some(b), None] + ); + } + + #[test] + fn the_pairing_report_holds_the_address() { + let mut pairing = [0u8; 20]; + pairing[0] = 0x09; + pairing[1..7].copy_from_slice(&[1, 2, 3, 4, 5, 6]); + assert_eq!(mac(&pairing), Some([1, 2, 3, 4, 5, 6])); + // a pad that answered with nothing cannot be told apart + assert_eq!(mac(&[0x09; 1]), None); + assert_eq!(mac(&[0x09, 0, 0, 0, 0, 0, 0]), None); + } + + #[test] + fn a_usb_report_reads_as_a_pad() { + let mut report = [0u8; 64]; + report[0] = 0x01; + report[1..5].copy_from_slice(&[0, 255, 128, 128]); // left stick: left, down + report[5] = 255; // L2 + report[8] = 0x20 | 2; // cross, D-pad right + report[9] = 0x20 | 0x01; // options, L1 + let pad = parse(&report, false).unwrap(); + assert_eq!(pad.buttons, A | RIGHT | MENU | LEFT_SHOULDER); + assert_eq!( + (pad.left_x, pad.left_y, pad.left_trigger), + (-1.0, -1.0, 1.0) + ); + assert!(pad.right_x.abs() < 0.01 && pad.right_y.abs() < 0.01); + } + + #[test] + fn bluetooth_reports_read_one_byte_further_in() { + let mut report = [0u8; 78]; + report[0] = 0x31; + report[2..6].copy_from_slice(&[128, 0, 255, 128]); // left up, right right + report[7] = 255; // R2 + report[9] = 0x80 | 8; // triangle, D-pad centred + let pad = parse(&report, true).unwrap(); + assert_eq!(pad.buttons, Y); + assert_eq!( + (pad.left_y, pad.right_x, pad.right_trigger), + (1.0, 1.0, 1.0) + ); + // the same bytes over USB are not a pad report + assert_eq!(parse(&report, false), None); + } + + #[test] + fn the_short_bluetooth_report_reads_too() { + let mut report = [0u8; 78]; + report[0] = 0x01; + report[1..5].copy_from_slice(&[128; 4]); + report[5] = 0x40 | 4; // circle, D-pad down + report[7] = 0x02; // touchpad click + report[8] = 128; // L2 halfway + let pad = parse(&report, true).unwrap(); + assert_eq!(pad.buttons, B | DOWN | VIEW); + assert!((pad.left_trigger - 0.5).abs() < 0.01); + } +} diff --git a/scripts/play-gta6-framegen.ps1 b/scripts/play-gta6-framegen.ps1 new file mode 100644 index 0000000..7520a66 --- /dev/null +++ b/scripts/play-gta6-framegen.ps1 @@ -0,0 +1,137 @@ +# One-click GTA VI on trustno1-coder/VIctory-NVIDIA (foxhound base): DLSS Super Resolution + DLSS frame generation. +# PLAY_FRAMEGEN.bat runs this. What it does, in order: +# 1. finds the game folder (game_dir.txt in the repository folder, else a search of every drive) +# 2. backs up the saves (%LOCALAPPDATA%\victory\data\7952987A) and checks every file by SHA-256 +# 3. gets NVIDIA's DLSS files once (scripts\get-nvidia-sdks.ps1, from github.com/NVIDIA-RTX/Streamline) +# 4. starts scripts\play-foxhound.ps1, which builds the layer the first time (a few minutes) +# Modes: 1 Series X 1440p + DLSS Quality + frame generation 2x (default) +# 2 same without frame generation +# 3 Series S + DLSS Quality + frame generation 2x (faster, softer) +# 4 Series X 1440p + DLSS Performance + frame generation 2x +param( + [ValidateSet('1', '2', '3', '4', '5', '6')][string]$Mode = '1', + [string]$GameDir = '', + [switch]$Check, + [switch]$NoBackup +) +$ErrorActionPreference = 'Stop' +$repo = Split-Path $PSScriptRoot -Parent + +# A game folder holds the executable and its data (a lone copy of the exe does not count). +function Test-GameDir([string]$d) { + if (-not $d -or -not (Test-Path (Join-Path $d 'game_scarlett_master.exe'))) { return $false } + return (Test-Path (Join-Path $d 'shaders.rpf')) -or (Test-Path (Join-Path $d 'MicrosoftGame.config')) +} +function Find-GameDir { + $txt = Join-Path $repo 'game_dir.txt' + if (Test-Path $txt) { + $d = (Get-Content $txt -Encoding UTF8 -TotalCount 1).Trim().Trim('"') + if (Test-GameDir $d) { return $d } + } + foreach ($drive in (Get-PSDrive -PSProvider FileSystem | Where-Object { $null -ne $_.Free })) { + $cands = @(Get-ChildItem $drive.Root -Directory -ErrorAction SilentlyContinue) + $cands += @($cands | ForEach-Object { Get-ChildItem $_.FullName -Directory -ErrorAction SilentlyContinue }) + foreach ($c in $cands) { if (Test-GameDir $c.FullName) { return $c.FullName } } + } + return $null +} + +if (-not $GameDir) { $GameDir = Find-GameDir } +if (-not (Test-GameDir $GameDir)) { + Write-Host 'Game folder not found. Put its full path on the first line of game_dir.txt in this folder.' + exit 1 +} +$gameExe = Join-Path $GameDir 'game_scarlett_master.exe' + +switch ($Mode) { + '1' { $opts = @{ FrameGen = $true }; $what = 'Series X 2560x1440, DLSS Quality, frame generation 2x' } + '2' { $opts = @{}; $what = 'Series X 2560x1440, DLSS Quality, no frame generation' } + '3' { $opts = @{ SeriesS = $true; FrameGen = $true }; $what = 'Series S, DLSS Quality, frame generation 2x' } + '4' { $opts = @{ Dlss = 'performance'; FrameGen = $true }; $what = 'Series X 2560x1440, DLSS Performance, frame generation 2x' } + '5' { $opts = @{ SeriesS = $true; Dlss = 'performance'; FrameGen = $true; Fps = 1000 }; $what = 'EXTREME: Series S, DLSS Performance, frame generation 2x, no cap, big pools, High priority' } + '6' { $opts = @{ Dlss = 'performance'; FrameGen = $true; Fps = 1000 }; $what = 'EXTREME: Series X 2560x1440, DLSS Performance, frame generation 2x, no cap, big pools, High priority' } +} +$sl = Join-Path $repo 'nvidia-sdk\Streamline\bin\x64' +$victory = Join-Path $repo 'target\release\victory.exe' +$hags = (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\GraphicsDrivers' -Name HwSchMode -ErrorAction SilentlyContinue).HwSchMode + +if ($Check) { + Write-Host "repo: $repo" + Write-Host "game: $gameExe" + Write-Host "mode: $Mode ($what)" + Write-Host "DLSS: $(if (Test-Path (Join-Path $sl 'sl.interposer.dll')) { 'present' } else { 'not yet (downloaded at first start)' })" + Write-Host "built: $(if (Test-Path $victory) { 'yes' } else { 'no (built at first start)' })" + Write-Host "HAGS: $(if ($hags -eq 2) { 'on' } else { 'off: frame generation needs it (Settings > Display > Graphics)' })" + exit 0 +} +if (Get-Process victory -ErrorAction SilentlyContinue) { Write-Host 'The game is already running. Close it first.'; exit 1 } + +# 2. Saves backup, verified file by file. +if (-not $NoBackup) { + $src = Join-Path $env:LOCALAPPDATA 'victory\data\7952987A' + if (Test-Path $src) { + $root = if (Test-Path 'D:\') { 'D:\victory-save-backups' } else { Join-Path $env:USERPROFILE 'victory-save-backups' } + $dst = Join-Path $root ('7952987A-{0:yyyyMMdd-HHmmss}-before-nvidia' -f (Get-Date)) + New-Item -ItemType Directory -Force $root | Out-Null + Copy-Item $src $dst -Recurse -Force + $files = @(Get-ChildItem $src -Recurse -File) + $bad = 0 + foreach ($f in $files) { + $t = Join-Path $dst $f.FullName.Substring($src.Length) + try { + if (-not (Test-Path $t) -or (Get-FileHash $f.FullName).Hash -ne (Get-FileHash $t).Hash) { $bad++ } + } catch { $bad++ } + } + if ($bad) { Write-Host "Save backup check failed ($bad of $($files.Count) files). Not starting."; exit 1 } + Write-Host "Saves backed up and checked: $dst ($($files.Count) files)" + } +} + +# 3. NVIDIA's DLSS and frame generation files, once. +if (-not (Test-Path (Join-Path $sl 'sl.interposer.dll'))) { + Write-Host 'Getting NVIDIA DLSS files (about 70 MB, once) ...' + try { & (Join-Path $PSScriptRoot 'get-nvidia-sdks.ps1') } + catch { Write-Host "Could not get them ($($_.Exception.Message)): the game runs without DLSS and frame generation." } +} +if ($hags -ne 2) { Write-Host 'Hardware-accelerated GPU scheduling is off: frame generation will not work until it is on.' } + +# 4. Start (play-foxhound.ps1 builds target\release\victory.exe the first time). +if (-not (Test-Path $victory)) { Write-Host 'First start: building the layer, a few minutes ...' } +Write-Host "Starting GTA VI: $what" +Write-Host 'In the game: F1 settings menu, F3 stats panel. Keep this window open while playing.' +$env:VICTORY_GAME_DIR = $GameDir +$ErrorActionPreference = 'Continue' +# foxhound reads these but play-foxhound.ps1 does not set them: AnyXboxX's worker pools for 16/24+ logical CPUs +# (measured on an RTX 4070 SUPER: heavy scenes +22-29 %) and Vice-Tay's placed order. GTA6_NO_TUNE=1: leave them out. +$cpus = [Environment]::ProcessorCount +$more = @{ VICTORY_PLACED_ORDER = '1' } +if ($cpus -ge 24) { $more.VICTORY_THIN_THREADS = '12'; $more.VICTORY_UNDER_THREADS = '8'; $more.VICTORY_LAND_THREADS = '8' } +elseif ($cpus -ge 16) { $more.VICTORY_THIN_THREADS = '12'; $more.VICTORY_UNDER_THREADS = '8'; $more.VICTORY_LAND_THREADS = '6' } +# Extreme: the landing pool sat full at 8 (x6.1-6.6 of 8 in AnyXboxX's heavy scenes), one more pipeline worker. +if (($Mode -in @('5', '6')) -and $cpus -ge 24) { $more.VICTORY_LAND_THREADS = '12'; $more.VICTORY_PIPELINE_WORKERS = '4' } +if ($env:GTA6_NO_TUNE -eq '1') { $more = @{}; Write-Host 'GTA6_NO_TUNE=1: foxhound defaults (no pool or placed-order tuning).' } +else { Write-Host ("Tuning for {0} logical CPUs: {1}" -f $cpus, (($more.GetEnumerator() | Sort-Object Name | ForEach-Object { "$($_.Name)=$($_.Value)" }) -join ' ')) } +$opts.More = $more +# RTX 50 cards do multi frame generation: 4x there (the layer asks the driver and gives no more than it does). +# GTA6_FRAMEGEN_X=2..6 overrides. RTX 40 stays at 2x. +$gpuName = (Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue | Where-Object { $_.Name -match 'NVIDIA' } | Select-Object -First 1).Name +if ($opts.FrameGen) { + if ($env:GTA6_FRAMEGEN_X -match '^[2-6]$') { $opts.FrameGenX = [int]$env:GTA6_FRAMEGEN_X } + elseif ($gpuName -match 'RTX\s*50\d\d') { $opts.FrameGenX = 4 } + $fgx = if ($opts.FrameGenX) { $opts.FrameGenX } else { 2 } + Write-Host ('GPU: {0}; frame generation {1}x' -f $gpuName, $fgx) +} +if ($Mode -in @('5', '6')) { + # Raise the game to High priority once it is up (the submitting thread is the limit). + $null = Start-Job -ArgumentList $repo -ScriptBlock { + param($r) + $end = (Get-Date).AddMinutes(15) + while ((Get-Date) -lt $end) { + $p = Get-Process victory -ErrorAction SilentlyContinue | Where-Object { $_.Path -like "$r*" } + if ($p) { $p | ForEach-Object { $_.PriorityClass = 'High' }; break } + Start-Sleep -Seconds 2 + } + } + Write-Host 'Extreme: the game process goes to High priority once it starts.' +} +& (Join-Path $PSScriptRoot 'play-foxhound.ps1') -Exe $gameExe -Build release @opts