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]>
227 lines
8.1 KiB
Rust
227 lines
8.1 KiB
Rust
//! Process-wide state the implementations need.
|
|
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::Mutex;
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
|
|
static MAIN_IMAGE_BASE: AtomicUsize = AtomicUsize::new(0);
|
|
|
|
/// Records where the title's main image is mapped. The title expects
|
|
/// `GetModuleHandle(NULL)` and friends to return this, not our own exe.
|
|
pub fn set_main_image(base: usize) {
|
|
MAIN_IMAGE_BASE.store(base, Ordering::Release);
|
|
}
|
|
|
|
pub fn main_image() -> Option<usize> {
|
|
match MAIN_IMAGE_BASE.load(Ordering::Acquire) {
|
|
0 => None,
|
|
base => Some(base),
|
|
}
|
|
}
|
|
|
|
/// Original file of each title image we mapped, by base address.
|
|
static IMAGE_PATHS: Mutex<Vec<(usize, PathBuf)>> = Mutex::new(Vec::new());
|
|
|
|
/// Records the file a title image was mapped from: the title asks for its
|
|
/// own path (`GetModuleFileName`) to find its data, and must not get our
|
|
/// cache copy.
|
|
pub fn set_image_path(base: usize, path: &Path) {
|
|
let path = std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
|
|
let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
|
|
paths.retain(|(b, _)| *b != base);
|
|
paths.push((base, path));
|
|
}
|
|
|
|
/// Forgets a title image that was unmapped again.
|
|
pub fn forget_image(base: usize) {
|
|
let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
|
|
paths.retain(|(b, _)| *b != base);
|
|
}
|
|
|
|
pub fn image_path(base: usize) -> Option<PathBuf> {
|
|
let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
|
|
paths
|
|
.iter()
|
|
.find(|(b, _)| *b == base)
|
|
.map(|(_, p)| p.clone())
|
|
}
|
|
|
|
/// The title image whose original file is called `file` (any case).
|
|
pub fn image_named(file: &str) -> Option<usize> {
|
|
let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
|
|
paths
|
|
.iter()
|
|
.find(|(_, p)| p.file_name().is_some_and(|n| n.eq_ignore_ascii_case(file)))
|
|
.map(|(b, _)| *b)
|
|
}
|
|
|
|
/// Maps a title DLL the title loads itself (`LoadLibrary`) and returns its
|
|
/// base; `Ok(None)` if `file` is not one of the title's DLLs.
|
|
pub type TitleDllLoader = Box<dyn Fn(&str) -> Result<Option<usize>, String> + Send + Sync>;
|
|
|
|
static TITLE_DLL_LOADER: std::sync::OnceLock<TitleDllLoader> = std::sync::OnceLock::new();
|
|
|
|
/// Set once, by whoever mapped the title (it knows the folders and the
|
|
/// resolver); later calls are ignored.
|
|
pub fn set_title_dll_loader(loader: TitleDllLoader) {
|
|
let _ = TITLE_DLL_LOADER.set(loader);
|
|
}
|
|
|
|
pub fn load_title_dll(file: &str) -> Result<Option<usize>, String> {
|
|
TITLE_DLL_LOADER.get().map_or(Ok(None), |load| load(file))
|
|
}
|
|
|
|
/// What the title's manifest (`MicrosoftGame.config` beside its executable)
|
|
/// says about it, and where its persistent local storage lives.
|
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
|
pub struct Title {
|
|
pub id: u32,
|
|
/// The store's product id (empty if the manifest has none).
|
|
pub store_id: String,
|
|
/// Persistent local storage: our folder for it and the title's quota.
|
|
/// Game saves live beside it ([`Title::saves`]).
|
|
pub storage: PathBuf,
|
|
pub storage_bytes: u64,
|
|
}
|
|
|
|
impl Title {
|
|
/// Id, store id and storage quota from the manifest (zero or empty
|
|
/// where it has none); the storage folder is left for the caller.
|
|
pub fn from_manifest(text: &str) -> Title {
|
|
let elements = elements(text);
|
|
let get = |path: &str| {
|
|
elements
|
|
.iter()
|
|
.find(|(p, _)| p == path)
|
|
.map(|(_, text)| text.as_str())
|
|
};
|
|
let id = get("Game/TitleId").and_then(|v| u32::from_str_radix(v, 16).ok());
|
|
let storage_mb = get("Game/PersistentLocalStorage/SizeMB").and_then(|v| v.parse().ok());
|
|
Title {
|
|
id: id.unwrap_or(0),
|
|
store_id: get("Game/StoreId").unwrap_or_default().to_owned(),
|
|
storage: PathBuf::new(),
|
|
storage_bytes: storage_mb.unwrap_or(0) << 20,
|
|
}
|
|
}
|
|
|
|
/// Where game saves live: next to persistent local storage, under the
|
|
/// data directory, never the cache.
|
|
pub fn saves(&self) -> PathBuf {
|
|
self.storage.with_file_name("saves")
|
|
}
|
|
}
|
|
|
|
/// Each element of an XML text as its path from the root (`Game/TitleId`)
|
|
/// and its trimmed text up to the first child, the predefined entities
|
|
/// decoded; comments, CDATA sections, declarations and attributes are
|
|
/// skipped.
|
|
fn elements(text: &str) -> Vec<(String, String)> {
|
|
let mut out = Vec::new();
|
|
let mut path: Vec<&str> = Vec::new();
|
|
let mut rest = text;
|
|
while let Some(open) = rest.find('<') {
|
|
rest = &rest[open..];
|
|
let end = if rest.starts_with("<!--") {
|
|
rest.find("-->").map(|e| e + 3)
|
|
} else if rest.starts_with("<![CDATA[") {
|
|
rest.find("]]>").map(|e| e + 3)
|
|
} else {
|
|
rest.find('>').map(|e| e + 1)
|
|
};
|
|
let Some(end) = end else { break };
|
|
let tag = &rest[1..end - 1];
|
|
rest = &rest[end..];
|
|
if tag.starts_with(['!', '?']) {
|
|
continue;
|
|
}
|
|
if let Some(name) = tag.strip_prefix('/') {
|
|
if let Some(at) = path.iter().rposition(|n| *n == name.trim()) {
|
|
path.truncate(at);
|
|
}
|
|
continue;
|
|
}
|
|
let closed = tag.ends_with('/');
|
|
let name = tag
|
|
.trim_end_matches('/')
|
|
.split_whitespace()
|
|
.next()
|
|
.unwrap_or("");
|
|
path.push(name);
|
|
let body = rest[..rest.find('<').unwrap_or(rest.len())].trim();
|
|
let body = [("<", "<"), (">", ">"), (""", "\""), ("'", "'"), ("&", "&")]
|
|
.iter()
|
|
.fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c));
|
|
out.push((path.join("/"), body));
|
|
if closed {
|
|
path.pop();
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
static TITLE: Mutex<Option<Title>> = Mutex::new(None);
|
|
|
|
pub fn set_title(title: Title) {
|
|
*TITLE.lock().unwrap_or_else(|e| e.into_inner()) = Some(title);
|
|
}
|
|
|
|
/// The running title; the default (id 0, no storage) until set.
|
|
pub fn title() -> Title {
|
|
TITLE
|
|
.lock()
|
|
.unwrap_or_else(|e| e.into_inner())
|
|
.clone()
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
/// Gives the process the console's millisecond timers. Titles pace
|
|
/// themselves with short waits (Grand Theft Auto VI's audio mixer sleeps
|
|
/// about 4 ms per 5.3 ms block) and cannot tune the timer on the console;
|
|
/// a desktop process waits in 15.6 ms ticks unless it asks for finer ones,
|
|
/// and Windows 11 drops that request while the window is hidden unless the
|
|
/// process opts out. Process-wide, for the whole run.
|
|
#[cfg(windows)]
|
|
pub fn use_console_timers() {
|
|
use windows_sys::Win32::Media::timeBeginPeriod;
|
|
use windows_sys::Win32::System::Threading::{
|
|
GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION,
|
|
PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE,
|
|
ProcessPowerThrottling, SetProcessInformation,
|
|
};
|
|
let keep = PROCESS_POWER_THROTTLING_STATE {
|
|
Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION,
|
|
ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION,
|
|
StateMask: 0,
|
|
};
|
|
// SAFETY: plain process settings; `keep` outlives the call.
|
|
unsafe {
|
|
SetProcessInformation(
|
|
GetCurrentProcess(),
|
|
ProcessPowerThrottling,
|
|
(&raw const keep).cast(),
|
|
size_of_val(&keep) as u32,
|
|
);
|
|
timeBeginPeriod(1);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn reads_title_id_store_id_and_storage_quota() {
|
|
let text = "\u{feff}<?xml version=\"1.0\"?>\n<Game configVersion=\"1\">\
|
|
<!-- <TitleId>00000000</TitleId> -->\
|
|
<Identity Name=\"x\"/>\n <TitleId>639AA8DD</TitleId>\n\
|
|
<![CDATA[ <TitleId>1</TitleId> ]]> <StoreId>9&C</StoreId><Other><SizeMB>7</SizeMB></Other>\
|
|
<PersistentLocalStorage>\n <SizeMB>1024</SizeMB> <!-- c -->\n\
|
|
</PersistentLocalStorage></Game>";
|
|
let t = Title::from_manifest(text);
|
|
assert_eq!((t.id, t.storage_bytes), (0x639A_A8DD, 1024 << 20));
|
|
assert_eq!(t.store_id, "9&C");
|
|
assert_eq!(Title::from_manifest("").storage_bytes, 0);
|
|
}
|
|
}
|