Run Grand Theft Auto VI from first boot into the world

The title now boots through every first-boot and menu screen at its own
30 fps, drawing with translated shaders, with input, sound, saves and
loading served; it reaches the world, where the host GPU path still
fails (see "Not working yet").

Loader and runtime
- Crash reports unwind properly, name C++ throws and host GPU failures,
  carry the title's last debug lines and are appended to crashes.log.
- Thread notices on our own threads, reentrant late DLL loading, exit in
  the console's order, relaunch on a launch-new-game request.
- Offline guard: the title cannot reach the network (sockets, name
  lookups, WinHTTP, the media source resolver); by-name lookups and
  loads follow the import rules.
- Every runtime area the title calls is served (networking hint,
  packages, store, saves, display, UI, speech stubs, user, async pool).
  Saves persist; an update is one rename and survives a kill at any step.
- DirectStorage reads for real: shared worker pool, priorities, zlib and
  BCPack. BCPack is our own decoder; the format's constant tables ship in
  crates/victory-formats/src/bcpack-tables.bin (the asset policy's one
  exception, see docs/asset-policy.md).
- GameInput from XInput pads and the keyboard, with a keyboard stand-in
  pad; console timers (1 ms) for the whole process.
- Audio: XMA2 decoding on the emulated contexts, Opus on the decoder
  queues, the DSP interface as a stub; title memory placed below 2^40.
- Console texture layouts (sizes, tiling, detiling) and the layout
  library's imports.

GPU
- Draws, mesh dispatches and compute dispatches run on the host with
  shaders translated at first use and cached on disk; descriptor heaps,
  views, root signatures, barriers and host texture states; rectangle
  lists; comparison samplers.
- Title memory reaches the host through persistent mirrors that copy
  only pages written since the last copy; shader-written buffers are
  copied back.
- Presentation with frame pacing per event kind; framerate in the window
  caption.

Shaders
- DXIL emission for vertex, pixel, compute and mesh programs from the
  console's native code, with a differential test suite against the PC
  compile. World set: mesh 8,191 of 8,506, vertex/pixel 10,617 of
  12,346, compute 1,643 of 2,539; utility set complete.

Build
- Debugging aids (debug logs, frame capture, stack dumps, scripted keys,
  the host debug layer, the software adapter) exist only with the
  `diagnostics` feature; `[profile.diag]` keeps that build apart.

Not working yet
- In the world the host device is removed within seconds (descriptor
  handling fixes are in, unproven by a surviving run) and frames present
  black.
- 64-bit image atomics, merged geometry stages and the BVH builder's own
  shaders do not translate; reverb is silent.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
MarvisandClaude Fable 5.2 committed 2026-11-23 23:10:01 +01:00
1 parent bc3070991a
commit 2849477415
107 files changed
+42526 -868

No files matched your search

+143 -19
View File
@@ -1,7 +1,8 @@
//! The title's life cycle. A console title is never told it is closing:
//! quitting it first suspends it (its suspend routines run, and it has a
//! second to save) and then ends the process. Closing the title's window
//! does the same here.
//! quitting it or launching a new game first suspends it (its suspend
//! routines run, and it has a second to save) and then ends the process.
//! Closing the title's window does the same here; a new launch then starts
//! `victory` again, which waits for this process to be gone.
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
#![allow(clippy::too_many_arguments)]
@@ -11,7 +12,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Mutex, MutexGuard};
use std::time::Duration;
use windows_sys::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, WPARAM};
use windows_sys::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM};
use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};
use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, HMENU};
use windows_sys::core::{PCSTR, PCWSTR, w};
@@ -72,7 +73,8 @@ pub extern "system" fn CreateWindowExW(
instance: HINSTANCE,
param: *const c_void,
) -> HWND {
// SAFETY: the title's own arguments, forwarded.
let (x, y, width, height) = fit(parent, x, y, width, height);
// SAFETY: the title's own arguments, forwarded (the size fitted).
let hwnd = unsafe {
wm::CreateWindowExW(
ex_style, class, name, style, x, y, width, height, parent, menu, instance, param,
@@ -97,7 +99,8 @@ pub extern "system" fn CreateWindowExA(
instance: HINSTANCE,
param: *const c_void,
) -> HWND {
// SAFETY: the title's own arguments, forwarded.
let (x, y, width, height) = fit(parent, x, y, width, height);
// SAFETY: the title's own arguments, forwarded (the size fitted).
let hwnd = unsafe {
wm::CreateWindowExA(
ex_style, class, name, style, x, y, width, height, parent, menu, instance, param,
@@ -107,6 +110,44 @@ pub extern "system" fn CreateWindowExA(
hwnd
}
/// A console title sizes its window to its render target (Grand Theft
/// Auto VI: 3840x2160 on a Series X), which can exceed the host's screen.
/// A top-level window larger than the work area is shrunk to fit, keeping
/// its proportions, and centred; what it shows is scaled to it (the swap
/// chain stretches).
fn fit(parent: HWND, x: i32, y: i32, width: i32, height: i32) -> (i32, i32, i32, i32) {
let mut area = RECT::default();
// SAFETY: `area` receives the primary monitor's work area.
let known =
unsafe { wm::SystemParametersInfoW(wm::SPI_GETWORKAREA, 0, (&raw mut area).cast(), 0) };
let fitted = fit_into(&area, width, height);
if !parent.is_null() || known == 0 || fitted == (width, height) {
return (x, y, width, height);
}
tracing::info!(width, height, to = ?fitted, "title window fitted to the screen");
let (w, h) = fitted;
let left = area.left + (area.right - area.left - w) / 2;
let top = area.top + (area.bottom - area.top - h) / 2;
(left, top, w, h)
}
/// `width` x `height` scaled down to fit `area`, or unchanged if it fits
/// (or is `CW_USEDEFAULT`).
fn fit_into(area: &RECT, width: i32, height: i32) -> (i32, i32) {
let (aw, ah) = (area.right - area.left, area.bottom - area.top);
if width <= 0 || height <= 0 || aw <= 0 || ah <= 0 || (width <= aw && height <= ah) {
return (width, height);
}
let scale = f64::min(
f64::from(aw) / f64::from(width),
f64::from(ah) / f64::from(height),
);
(
(f64::from(width) * scale) as i32,
(f64::from(height) * scale) as i32,
)
}
/// Puts our procedure in front of the title's.
fn hook(hwnd: HWND) {
if hwnd.is_null() {
@@ -130,7 +171,7 @@ extern "system" fn window_proc(
// A user close (close button, Alt+F4, window or taskbar menu); a
// console title never sees one, nor a WM_CLOSE from it.
if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_CLOSE as usize {
quit();
end_title("window closed", Box::new(|| {}));
return 0;
}
// SAFETY: the procedure `hook` stored, called the way the system would.
@@ -144,30 +185,97 @@ extern "system" fn window_proc(
}
}
/// Suspends the title as the console would on quit, then ends the process.
fn quit() {
static QUITTING: AtomicBool = AtomicBool::new(false);
if QUITTING.swap(true, Ordering::Relaxed) {
/// Suspends the title as the console does when it ends it, runs `then`
/// (once), then ends the process. Returns at once; later calls do nothing.
pub(crate) fn end_title(why: &'static str, then: Box<dyn FnOnce() + Send>) {
static ENDING: AtomicBool = AtomicBool::new(false);
if ENDING.swap(true, Ordering::SeqCst) {
return;
}
let suspend = routines().clone();
tracing::info!(routines = suspend.len(), "window closed: suspending the title");
// Not on the window thread: titles hand the suspend to that thread and
// wait for it inside the routine.
tracing::info!(routines = suspend.len(), "{why}: suspending the title");
// Whoever comes first (the routines or the deadline) runs `then`; the
// other waits for it, so the process never ends halfway through.
let then = std::sync::Arc::new(Mutex::new(Some(then)));
let finish = move |how: &str| {
let mut then = then.lock().unwrap_or_else(|e| e.into_inner());
tracing::info!("{how}; ending the title");
if let Some(then) = then.take() {
then();
}
end();
};
let late = finish.clone();
// Not on the calling thread: titles hand the suspend to their window
// thread and wait for it inside the routine.
std::thread::spawn(move || {
for (_, routine, context) in suspend {
routine(1, context as *mut c_void);
}
tracing::info!("title suspended; ending it");
end();
finish("title suspended");
});
std::thread::spawn(|| {
std::thread::spawn(move || {
std::thread::sleep(SUSPEND_DEADLINE);
tracing::warn!("title did not finish suspending in time; ending it");
end();
late("title did not finish suspending in time");
});
}
/// Set in the environment of a relaunched `victory`: an inherited handle
/// of the process it replaces.
const RELAUNCHED_FROM: &str = "VICTORY_RELAUNCHED_FROM";
/// Starts `victory` again with `args` (after the title has suspended); the
/// new process waits until this one has ended.
pub(crate) fn relaunch(args: Vec<std::ffi::OsString>) {
use windows_sys::Win32::Foundation::{DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE};
let mut me: HANDLE = std::ptr::null_mut();
// SAFETY: an inheritable duplicate of our own process handle.
let duplicated = unsafe {
DuplicateHandle(
GetCurrentProcess(),
GetCurrentProcess(),
GetCurrentProcess(),
&mut me,
0,
1,
DUPLICATE_SAME_ACCESS,
)
} != 0;
let spawned = std::env::current_exe().and_then(|exe| {
let mut command = std::process::Command::new(exe);
command.args(&args);
if duplicated {
command.env(RELAUNCHED_FROM, (me as usize).to_string());
}
command.spawn()
});
match spawned {
Ok(child) => tracing::info!(pid = child.id(), ?args, "relaunched"),
Err(e) => tracing::warn!(%e, "relaunch failed; the title just ends"),
}
}
/// In a relaunched `victory`: waits (30 s at most) for the process it
/// replaces to be gone, so the two never share the title's files.
pub fn wait_for_previous() {
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
use windows_sys::Win32::System::Threading::WaitForSingleObject;
let Some(handle) = std::env::var(RELAUNCHED_FROM)
.ok()
.and_then(|h| h.parse::<usize>().ok())
else {
return;
};
// SAFETY: removing our own variable before any other thread reads it.
unsafe { std::env::remove_var(RELAUNCHED_FROM) };
let handle = handle as HANDLE;
// SAFETY: the inherited process handle the previous process gave us.
unsafe {
WaitForSingleObject(handle, 30_000);
CloseHandle(handle);
}
}
fn end() {
// SAFETY: ends this process, as the console ends a suspended title.
unsafe { TerminateProcess(GetCurrentProcess(), 0) };
@@ -211,6 +319,22 @@ mod tests {
assert_eq!(left, [b]);
}
#[test]
fn oversized_windows_shrink_to_the_screen() {
let area = RECT {
left: 0,
top: 0,
right: 1920,
bottom: 1040,
};
assert_eq!(fit_into(&area, 3840, 2160), (1848, 1040));
assert_eq!(fit_into(&area, 1280, 720), (1280, 720));
assert_eq!(
fit_into(&area, wm::CW_USEDEFAULT, 0),
(wm::CW_USEDEFAULT, 0)
);
}
#[test]
fn hooked_windows_still_reach_the_title_procedure() {
let null = std::ptr::null_mut();