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:
1 parent
bc3070991a
commit
2849477415
107 files changed
+42526
-868
No files matched your search
@@ -1,15 +1,24 @@
|
||||
//! Pipeline states. Both descriptions start as on PC: the root signature,
|
||||
//! then the shader stages (five for graphics, one for compute); only those
|
||||
//! are read so far.
|
||||
//! then the shader stages (five for graphics, one for compute); streams
|
||||
//! carry the rest of the graphics state as subobjects of the standard
|
||||
//! types.
|
||||
//!
|
||||
//! shortcut: the console shader containers are kept, not translated, and
|
||||
//! the rest of the description is ignored. Translate through the cache
|
||||
//! here (TODO.md, GPU: pipeline creation, decision 0003). The 32-byte
|
||||
//! Host pipelines are made on a pipeline's first draw, not at creation:
|
||||
//! Grand Theft Auto VI creates some 60,000 pipelines in its first 20
|
||||
//! seconds and draws with a few dozen (decision 0007, step 3). Shader
|
||||
//! containers are shared by content hash and translated once, on first
|
||||
//! use (decision 0003).
|
||||
//!
|
||||
//! shortcut: only vertex plus pixel pipelines from streams and compute
|
||||
//! pipelines get host pipelines; mesh, tessellation and geometry stages,
|
||||
//! and the plain graphics description, keep their containers only. The 32-byte
|
||||
//! packet after the header stays zero: titles only copy it inline, which
|
||||
//! our null command-list limits keep from running.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::mem::offset_of;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, PIPELINE, Table, This, guid};
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
@@ -45,30 +54,183 @@ pub(crate) struct ComputeHead {
|
||||
stage: Bytecode,
|
||||
}
|
||||
|
||||
/// A shader container a title passed, shared by every pipeline with the
|
||||
/// same bytes.
|
||||
pub(crate) struct Shader {
|
||||
pub(crate) stage: &'static str,
|
||||
/// The first 8 bytes of its BLAKE3, as logged.
|
||||
pub(crate) hash: String,
|
||||
container: Vec<u8>,
|
||||
#[cfg(windows)]
|
||||
translated: OnceLock<Option<Translated>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Shader {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{} {}", self.stage, self.hash)
|
||||
}
|
||||
}
|
||||
|
||||
/// Every container seen, by full content hash.
|
||||
static SHADERS: Mutex<Option<HashMap<[u8; 32], Arc<Shader>>>> = Mutex::new(None);
|
||||
|
||||
/// The shared container for `bytes`.
|
||||
fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> {
|
||||
let full = blake3::hash(bytes);
|
||||
let mut shaders = SHADERS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
shaders
|
||||
.get_or_insert_with(HashMap::new)
|
||||
.entry(*full.as_bytes())
|
||||
.or_insert_with(|| {
|
||||
Arc::new(Shader {
|
||||
stage,
|
||||
hash: full.to_hex()[..16].to_owned(),
|
||||
container: bytes.to_vec(),
|
||||
#[cfg(windows)]
|
||||
translated: OnceLock::new(),
|
||||
})
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// A translated shader and the console resources its code reads.
|
||||
#[cfg(windows)]
|
||||
pub(crate) struct Translated {
|
||||
pub(crate) host: victory_shader::emit::HostShader,
|
||||
pub(crate) used: Vec<victory_shader::UsedResource>,
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl Shader {
|
||||
/// The translation, made on first use; a shader that does not
|
||||
/// translate is logged once.
|
||||
pub(crate) fn translated(&self) -> Option<&Translated> {
|
||||
self.translated
|
||||
.get_or_init(|| {
|
||||
let done = translate(&self.container);
|
||||
match &done {
|
||||
Ok(t) => tracing::info!(
|
||||
stage = self.stage,
|
||||
hash = %self.hash,
|
||||
user_data = t.host.user_data.len(),
|
||||
samplers = t.host.samplers.len(),
|
||||
"shader translated"
|
||||
),
|
||||
Err(e) => tracing::warn!(
|
||||
stage = self.stage,
|
||||
hash = %self.hash,
|
||||
error = %e,
|
||||
"shader does not translate; its pipelines' draws are dropped"
|
||||
),
|
||||
}
|
||||
done.ok()
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn translate(container: &[u8]) -> Result<Translated, String> {
|
||||
use victory_shader::{Container, FourCC, HwStage};
|
||||
let host = crate::shader_cache::host_shader(container)?;
|
||||
let c = Container::parse(container).map_err(|e| e.to_string())?;
|
||||
let used = match c.part(FourCC::DXIL) {
|
||||
Some(part) => victory_shader::native_programs(part.data)
|
||||
.map_err(|e| e.to_string())?
|
||||
.into_iter()
|
||||
.find(|p| {
|
||||
matches!(
|
||||
p.stage,
|
||||
HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs
|
||||
)
|
||||
})
|
||||
.map(|p| p.used)
|
||||
.unwrap_or_default(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
Ok(Translated { host, used })
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Pipeline {
|
||||
object: Object,
|
||||
packet: [u32; 8],
|
||||
/// Each stage's container, empty when the stage is unused.
|
||||
shaders: Vec<Vec<u8>>,
|
||||
/// Each used stage's container.
|
||||
shaders: Vec<Arc<Shader>>,
|
||||
/// Whether a list has bound it yet (its shaders are logged then).
|
||||
bound: std::sync::atomic::AtomicBool,
|
||||
/// The rest of a stream's graphics state, for the host pipeline.
|
||||
#[cfg(windows)]
|
||||
graphics: Option<Box<host::GraphicsState>>,
|
||||
#[cfg(windows)]
|
||||
host: OnceLock<Option<host::HostPipeline>>,
|
||||
}
|
||||
const _: () = assert!(offset_of!(Pipeline, packet) == 0x10);
|
||||
|
||||
fn copy(stage: &Bytecode) -> Vec<u8> {
|
||||
if stage.code.is_null() || stage.size == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
// SAFETY: the title passes `size` bytes of shader code.
|
||||
unsafe { std::slice::from_raw_parts(stage.code, stage.size) }.to_vec()
|
||||
/// Stage names, in description order.
|
||||
const GRAPHICS_STAGES: [&str; 5] = ["vertex", "pixel", "domain", "hull", "geometry"];
|
||||
|
||||
fn pipeline<'a>(this: This) -> &'a Pipeline {
|
||||
// SAFETY: the title passes one of our pipelines.
|
||||
unsafe { &*this.cast::<Pipeline>() }
|
||||
}
|
||||
|
||||
fn hand_out(shaders: Vec<Vec<u8>>, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let sizes: Vec<usize> = shaders.iter().map(Vec::len).collect();
|
||||
tracing::debug!(?sizes, "pipeline state");
|
||||
/// List method: logs each pipeline's shaders the first time a list binds
|
||||
/// it, so a run lists the shaders its frames need first.
|
||||
pub(crate) fn bound(this: This) {
|
||||
if this.is_null() {
|
||||
return;
|
||||
}
|
||||
let p = pipeline(this);
|
||||
if p.bound.swap(true, std::sync::atomic::Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let frame = crate::frame::current();
|
||||
for shader in &p.shaders {
|
||||
tracing::info!(pipeline = ?this, frame, stage = shader.stage, size = shader.container.len(), hash = %shader.hash, "first bind");
|
||||
}
|
||||
}
|
||||
|
||||
/// The host pipeline of a title pipeline, made on first use; `None` if one
|
||||
/// of its shaders does not translate or the host refuses it.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn host_pipeline<'a>(this: This) -> Option<&'a host::HostPipeline> {
|
||||
if this.is_null() {
|
||||
return None;
|
||||
}
|
||||
let p = pipeline(this);
|
||||
p.host
|
||||
.get_or_init(|| host::HostPipeline::new(&p.shaders, p.graphics.as_deref()))
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// The stage's container, if it has one.
|
||||
fn copy(stage: &'static str, code: &Bytecode) -> Option<Arc<Shader>> {
|
||||
if code.code.is_null() || code.size == 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the title passes `size` bytes of shader code.
|
||||
Some(shader(stage, unsafe {
|
||||
std::slice::from_raw_parts(code.code, code.size)
|
||||
}))
|
||||
}
|
||||
|
||||
fn hand_out(
|
||||
shaders: Vec<Arc<Shader>>,
|
||||
#[cfg(windows)] graphics: Option<Box<host::GraphicsState>>,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
tracing::trace!(?shaders, "pipeline state");
|
||||
let pipeline = Box::new(Pipeline {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
packet: [0; 8],
|
||||
shaders,
|
||||
bound: std::sync::atomic::AtomicBool::new(false),
|
||||
#[cfg(windows)]
|
||||
graphics,
|
||||
#[cfg(windows)]
|
||||
host: OnceLock::new(),
|
||||
});
|
||||
object::hand_out(PIPELINE, pipeline, iid, &PIPELINE_IIDS, out)
|
||||
}
|
||||
@@ -84,7 +246,15 @@ pub(crate) extern "system" fn create_graphics(
|
||||
let Some(desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
hand_out(desc.stages.iter().map(copy).collect(), iid, out)
|
||||
let stages = GRAPHICS_STAGES.iter().zip(&desc.stages);
|
||||
let shaders = stages.filter_map(|(s, c)| copy(s, c)).collect();
|
||||
hand_out(
|
||||
shaders,
|
||||
#[cfg(windows)]
|
||||
None,
|
||||
iid,
|
||||
out,
|
||||
)
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
@@ -98,7 +268,115 @@ pub(crate) extern "system" fn create_compute(
|
||||
let Some(desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
hand_out(vec![copy(&desc.stage)], iid, out)
|
||||
hand_out(
|
||||
copy("compute", &desc.stage).into_iter().collect(),
|
||||
#[cfg(windows)]
|
||||
None,
|
||||
iid,
|
||||
out,
|
||||
)
|
||||
}
|
||||
|
||||
/// Device method 0x1f0: the plain compute description plus console
|
||||
/// extensions `(desc, extension count, extensions, iid, out)`.
|
||||
/// shortcut: the extensions (console shader settings) are ignored, as is
|
||||
/// the rest of the description.
|
||||
pub(crate) extern "system" fn create_compute_x(
|
||||
this: This,
|
||||
desc: *const ComputeHead,
|
||||
_extensions: u32,
|
||||
_extended: *const u8,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
create_compute(this, desc, iid, out)
|
||||
}
|
||||
|
||||
/// A pipeline described as a stream: its size and the subobjects, each a
|
||||
/// type then its data, padded to 8 bytes.
|
||||
#[repr(C)]
|
||||
pub(crate) struct StreamDesc {
|
||||
size: usize,
|
||||
stream: *const u8,
|
||||
}
|
||||
|
||||
/// A subobject type's size (type included), and the stage it is if it is a
|
||||
/// shader. The console numbers amplification and mesh shaders 23 and 24
|
||||
/// (PC: 24 and 25); its own types from 25 on are not sized yet.
|
||||
fn subobject(kind: u32) -> Option<(usize, Option<&'static str>)> {
|
||||
let stage = |name| Some((24, Some(name)));
|
||||
match kind {
|
||||
1 => stage("vertex"),
|
||||
2 => stage("pixel"),
|
||||
3 => stage("domain"),
|
||||
4 => stage("hull"),
|
||||
5 => stage("geometry"),
|
||||
6 => stage("compute"),
|
||||
23 => stage("amplification"),
|
||||
24 => stage("mesh"),
|
||||
0 => Some((16, None)),
|
||||
12 | 19 => Some((24, None)),
|
||||
7 | 15 => Some((40, None)),
|
||||
8 => Some((336, None)),
|
||||
10 => Some((48, None)),
|
||||
11 => Some((56, None)),
|
||||
17 => Some((16, None)),
|
||||
21 => Some((64, None)),
|
||||
22 => Some((32, None)),
|
||||
9 | 13 | 14 | 16 | 18 | 20 => Some((8, None)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Device method: a pipeline from a stream; the shaders are kept, and the
|
||||
/// graphics state for the host pipeline.
|
||||
pub(crate) extern "system" fn create_stream(
|
||||
_: This,
|
||||
desc: *const StreamDesc,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if desc.stream.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let mut shaders = Vec::new();
|
||||
#[cfg(windows)]
|
||||
let mut graphics = host::GraphicsState::default();
|
||||
let mut at = 0;
|
||||
while at + 8 <= desc.size {
|
||||
// SAFETY: inside the stream the title passes.
|
||||
let kind = unsafe { desc.stream.add(at).cast::<u32>().read_unaligned() };
|
||||
let Some((size, stage)) = subobject(kind) else {
|
||||
tracing::warn!(
|
||||
kind,
|
||||
at,
|
||||
"pipeline subobject of unknown size; the rest is ignored"
|
||||
);
|
||||
break;
|
||||
};
|
||||
if let Some(stage) = stage {
|
||||
// SAFETY: a shader subobject has its bytecode at +8.
|
||||
let code = unsafe { &*desc.stream.add(at + 8).cast::<Bytecode>() };
|
||||
shaders.extend(copy(stage, code));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
// SAFETY: a whole subobject of this kind lies at `at`.
|
||||
unsafe {
|
||||
graphics.read(kind, desc.stream.add(at))
|
||||
};
|
||||
at += size;
|
||||
}
|
||||
hand_out(
|
||||
shaders,
|
||||
#[cfg(windows)]
|
||||
Some(Box::new(graphics)),
|
||||
iid,
|
||||
out,
|
||||
)
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
@@ -110,19 +388,30 @@ extern "system" fn release(this: This) -> u32 {
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, pipeline 3.
|
||||
static FUNCTIONS: Table<11> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<PIPELINE, 11>());
|
||||
static FUNCTIONS: Table<24> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<PIPELINE, 24>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) mod host;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::{S_OK, slot};
|
||||
|
||||
fn shaders(p: This) -> Vec<(&'static str, Vec<u8>)> {
|
||||
pipeline(p)
|
||||
.shaders
|
||||
.iter()
|
||||
.map(|s| (s.stage, s.container.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipelines_keep_their_shaders() {
|
||||
let (vs, ps) = ([1u8, 2, 3], [4u8; 5]);
|
||||
@@ -151,11 +440,71 @@ mod tests {
|
||||
create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p),
|
||||
S_OK
|
||||
);
|
||||
// SAFETY: one of our pipelines.
|
||||
let shaders = unsafe { &(*p.cast::<Pipeline>()).shaders };
|
||||
assert_eq!(shaders[0], vs);
|
||||
assert_eq!(shaders[1], ps);
|
||||
assert!(shaders[2].is_empty());
|
||||
assert_eq!(
|
||||
shaders(p),
|
||||
[("vertex", vs.to_vec()), ("pixel", ps.to_vec())]
|
||||
);
|
||||
// A second pipeline with the same pixel shader shares its container.
|
||||
let mut q = std::ptr::null();
|
||||
create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut q);
|
||||
assert!(Arc::ptr_eq(
|
||||
&pipeline(p).shaders[1],
|
||||
&pipeline(q).shaders[1]
|
||||
));
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(p, 0x10)(p), 0);
|
||||
}
|
||||
|
||||
/// The stream layout Grand Theft Auto VI builds (title+0x86f090): root
|
||||
/// signature, five shader slots (the first a mesh shader), blend, sample
|
||||
/// mask, rasterizer, depth-stencil 1, sample description, input layout,
|
||||
/// topology, render target and depth formats: 0x2b0 bytes.
|
||||
#[test]
|
||||
fn streams_yield_their_shaders() {
|
||||
let (ms, ps) = ([9u8; 7], [4u8; 5]);
|
||||
let mut stream = vec![0u8; 0x2b0];
|
||||
let mut put = |at: usize, v: u64| stream[at..at + 8].copy_from_slice(&v.to_le_bytes());
|
||||
for (at, kind) in [
|
||||
(0x10, 24),
|
||||
(0x28, 2),
|
||||
(0x40, 3),
|
||||
(0x58, 4),
|
||||
(0x70, 5),
|
||||
(0x88, 8),
|
||||
(0x1d8, 9),
|
||||
(0x1e0, 10),
|
||||
(0x210, 21),
|
||||
(0x250, 17),
|
||||
(0x260, 12),
|
||||
(0x278, 14),
|
||||
(0x280, 15),
|
||||
(0x2a8, 16),
|
||||
] {
|
||||
put(at, kind);
|
||||
}
|
||||
put(0x18, ms.as_ptr() as u64);
|
||||
put(0x20, ms.len() as u64);
|
||||
put(0x30, ps.as_ptr() as u64);
|
||||
put(0x38, ps.len() as u64);
|
||||
// Topology type 3 (triangles), one render target of format 28.
|
||||
put(0x278, 14 | 3 << 32);
|
||||
put(0x280, 15 | 28 << 32);
|
||||
put(0x2a0, 1 << 32);
|
||||
let desc = StreamDesc {
|
||||
size: stream.len(),
|
||||
stream: stream.as_ptr(),
|
||||
};
|
||||
let mut p = std::ptr::null();
|
||||
let hr = create_stream(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p);
|
||||
assert_eq!(hr, S_OK);
|
||||
assert_eq!(shaders(p), [("mesh", ms.to_vec()), ("pixel", ps.to_vec())]);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let g = pipeline(p).graphics.as_deref().unwrap();
|
||||
assert_eq!(g.topology.0, 3);
|
||||
assert_eq!(
|
||||
(g.targets.NumRenderTargets, g.targets.RTFormats[0].0),
|
||||
(1, 28)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user