Non-blocking pipeline creation: a stand-in at once, the real pipeline built in the background

DXC ran in the title's Create*PipelineState call (0.2 s median, seconds for big programs),
so thousands of pipelines meant minutes of stall on a first run. Now each translated path is
first tried without compiling; when a shader is not in the DXIL cache the title gets a
stand-in pipeline at once and the same path runs on a worker over an owned copy of the
description. SetPipelineState on PC lists, console list replay and the two-pass / root
signature lookups use the real pipeline once built (graphics draws nothing until then,
compute is waited for). Tested with an empty cache: the game's VS/PS pipeline built in the
background renders pixel-identical, a mesh pipeline and the game's BVH builder work.
This commit is contained in:
ivall
2026-11-21 16:01:57 +01:00
parent 23e241facd
commit 3235ebe90f
8 changed files with 530 additions and 15 deletions
+20
View File
@@ -536,6 +536,26 @@ Nothing open.
Unexplained: 6 packets per subblock with a table difference of 12·960 – TOC 0xFC is CELT FB 20 ms **stereo**, so the table
probably counts samples × channels.
## Non-blocking pipeline creation (session 5, 2026-11-21)
- **Gap:** DXC ran in the title's `Create*PipelineState` call: 0.2 s median, seconds for big programs – thousands of
pipelines while a title loads meant minutes of stall on the first run (the DXIL disk cache helps only later runs).
- **Now** (`hle/d3d12x/pso_async.rs` + `real.rs`): every translated path is first tried with `dxc::cached_only` (no
compiling; a miss fails at once – `attempt`, translation errors of a missed attempt are dropped). All DXIL cached →
built in the call as before. Otherwise the title gets a **stand-in** at once (dummy shaders, its own description:
`standin_graphics` / `standin_compute` / `standin_stream`; mesh stand-ins are DXIL: `dummy_mesh`, one degenerate
triangle) and the same `translated_*` path runs on a worker (`pso_async::submit`, one thread per core, 64 MB stacks)
on an **owned copy** of the description (`OwnedDesc`: shader blobs, input layout + semantic names, stream subobjects;
stream output / input layout in a stream / view instancing → built in the call).
- **Binding:** `SetPipelineState` on PC command lists (new override), console list replay, `two_pass_of`,
`pso_root_signature` go through `pso_async::resolve` – the real pipeline once built. Graphics draws nothing until then;
compute is waited for at its first bind / replay (`resolve_wait`; a skipped dispatch would corrupt results).
`report.json → d3d12.background_pipelines` = (built, failed, still building). `XCL_ASYNC_PSO=0` turns it off.
- Tests: `retail_pipelines_built_in_the_background_behind_a_stand_in` (empty DXIL cache: the game's VS/PS pipeline built
in the background renders the same triangle pixel for pixel; a mesh pipeline returns after ~0.1 s, real after ~1 s,
two-pass parts found through the stand-in, title's description freed before the worker ran); the game's BVH builder
with an empty cache (52 programs compiled in the background, compute waited for at replay) builds BLAS + TLAS.
- Not yet: releasing a stand-in does not release its real pipeline (pipelines live until the process ends).
## Title memory above 4 GB: UMA windows (session 5, 2026-11-21)
- **Gap:** shaders addressed one `mem` buffer with the low 32 bits of the address, and D3D12 opens a heap from an
address only below 4 GiB (4095 MiB) – so at most 4 GB of title graphics memory, while a Series X title has ~13.5 GB.
+4 -4
View File
@@ -50,7 +50,7 @@ measurements and next steps:
| Feature | State | What it does | Verified by |
|---|---|---|---|
| **Shader recompiler** | ✅ | RDNA2 → HLSL → DXIL: VS, PS, CS, mesh (NGG), GS; atomics, LDS, scratch, images, samplers incl. static ones, wave ops, ray-tracing instructions; structured control flow; parallel DXC, disk cache | 24 064 / 24 064 programs of the retail pack; 0 DXC errors on random samples; per-instruction GPU tests |
| **Pipelines** | ✅ | PSOs from console shaders: VS+PS, CS, MS+PS, VS+GS+PS; root signature with the shaders' static samplers | GPU tests drawing the game's own VS / PS pairs |
| **Pipelines** | ✅ | PSOs from console shaders: VS+PS, CS, MS+PS, VS+GS+PS; root signature with the shaders' static samplers; non-blocking creation – a pipeline whose shaders are not compiled yet gets a stand-in at once and is built in the background | GPU tests drawing the game's own VS / PS pairs, also built in the background |
| **D3D12.X compute** | ✅ | console device slots, console descriptor heaps (T# / V# / S#), buffers at their console addresses, compute command lists recorded in the console format and replayed (tables, barriers, clears, copies) | the game's BVH builder and FSR 4 record and run through XCL |
| **D3D12.X graphics** | 🟡 | device, resources, heaps and pipelines are in place | draw submission and present need the game exe |
| **Textures** | ✅ | GFX10 tiling (all 14 2D swizzle modes), mip chains with mip tail, arrays and cubes → PC textures | 908 / 912 retail textures exact; GPU upload bit exact |
@@ -69,9 +69,9 @@ measurements and next steps:
| Needs a game executable | Not done yet | Not planned |
|---|---|---|
| D3D12.X draw records and `PresentX` / frame pacing | – | Xbox Live, Store licensing (offline by design) |
| root arguments → shader registers for graphics | non-blocking pipeline creation (first run compiles shaders synchronously) | decrypting XVC packages or any DRM |
| texture creation in title memory (binding the detiler) | Opus / XMA2 audio decoding | console SDK headers / binaries in the repository |
| the persistent-local-storage class and `XSystemGetDeviceType` slot of the thunk protocol | hull / domain / amplification shaders (none in the sample game), linear / 3D / MSAA tiled textures | |
| root arguments → shader registers for graphics | Opus / XMA2 audio decoding | decrypting XVC packages or any DRM |
| texture creation in title memory (binding the detiler) | hull / domain / amplification shaders (none in the sample game) | console SDK headers / binaries in the repository |
| the persistent-local-storage class and `XSystemGetDeviceType` slot of the thunk protocol | linear / 3D / MSAA tiled textures | |
| Bink GPU decoding, rehydrating prebuilt BVHs | performance work (GPU buffers live in system memory) | |
Every run writes `report.json` (called stubs, unknown D3D12.X slots and interfaces, XGameRuntime
+24
View File
@@ -204,6 +204,10 @@ pub fn compile_cached_in(dir: &Path, src: &str, entry: &str, profile: &str) -> R
return Ok((b, true));
}
}
if CACHED_ONLY.with(|c| c.get()) {
MISSED.with(|m| m.set(true));
return Err("DXIL not compiled yet".into());
}
let b = compile(src, entry, profile, &[])?;
if std::fs::create_dir_all(dir).is_ok() {
// write to a temporary name first: another thread / process may be reading
@@ -215,6 +219,26 @@ pub fn compile_cached_in(dir: &Path, src: &str, entry: &str, profile: &str) -> R
Ok((b, false))
}
thread_local! {
static CACHED_ONLY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
static MISSED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Run `f` without compiling: a program missing from the disk cache fails at once instead
/// (non-blocking pipeline creation). Returns `f`'s result and whether something was missing.
pub fn cached_only<R>(f: impl FnOnce() -> R) -> (R, bool) {
CACHED_ONLY.with(|c| c.set(true));
MISSED.with(|m| m.set(false));
let r = f();
CACHED_ONLY.with(|c| c.set(false));
(r, MISSED.with(|m| m.replace(false)))
}
/// Inside `cached_only`.
pub fn in_cached_only() -> bool {
CACHED_ONLY.with(|c| c.get())
}
pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec<u8>, bool), String> {
compile_cached_in(&cache_dir(), src, entry, profile)
}
+4 -2
View File
@@ -686,8 +686,10 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> {
io[1] = (table_at >> 32) as u32;
let io_at = uma_copy(st, bytemuck_u32(&io)).ok_or("UMA: io")?;
let res_at = uma_copy(st, &[0u8; 256]).ok_or("UMA: res")?;
// a pipeline still being built in the background is waited for
let real = super::pso_async::resolve_wait((*p).pc);
// the pipeline's own root signature when it has static samplers
let own = ((*p).rs != 0).then(|| (*p).rs as *mut c_void);
let own = super::real::pso_root_signature(real).or(((*p).rs != 0).then_some((*p).rs)).map(|r| r as *mut c_void);
match own.as_ref().and_then(|r| ID3D12RootSignature::from_raw_borrowed(r)) {
Some(r) => list.SetComputeRootSignature(r),
None => list.SetComputeRootSignature(rs.as_ref().ok_or("no XCL ABI root signature")?),
@@ -697,7 +699,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> {
for k in 0..4 {
list.SetComputeRootUnorderedAccessView(2 + k as u32, windows.get(k).copied().unwrap_or(uma_va));
}
let raw = (*p).pc as *mut c_void;
let raw = real as *mut c_void;
let pc = ID3D12PipelineState::from_raw_borrowed(&raw).ok_or("PSO")?;
list.SetPipelineState(pc);
list.Dispatch(x, y, z);
+1
View File
@@ -15,6 +15,7 @@ pub mod guard;
pub mod layout;
pub mod null;
pub mod present;
pub mod pso_async;
pub mod real;
use std::ffi::c_void;
+115
View File
@@ -0,0 +1,115 @@
//! Non-blocking pipeline creation. Translating a console shader takes milliseconds; compiling
//! the HLSL with DXC takes 0.2 s to seconds, and a title creates thousands of pipelines while
//! it loads. When a pipeline's DXIL is not in the disk cache yet, the title gets a stand-in
//! pipeline (shaders that draw nothing) at once and the real one is built on a worker; binding
//! (`SetPipelineState`, console list replay, the two-pass lookups) uses the real one as soon
//! as it is there. A graphics pipeline draws nothing until then; a compute pipeline is waited
//! for at its first bind (a skipped dispatch would corrupt what it computes).
//! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before.
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock};
struct Pending {
/// the real pipeline state (raw pointer), 0 while building or when building failed
real: AtomicUsize,
done: Mutex<bool>,
cv: Condvar,
compute: bool,
}
/// stand-in handed to the title → its real pipeline
static PENDING: Mutex<Option<HashMap<usize, Arc<Pending>>>> = Mutex::new(None);
static BUILT: AtomicUsize = AtomicUsize::new(0);
static FAILED: AtomicUsize = AtomicUsize::new(0);
pub fn enabled() -> bool {
std::env::var("XCL_ASYNC_PSO").map_or(true, |v| v != "0")
}
/// Builds the real pipeline: its raw pointer, 0 = failed.
pub type Job = Box<dyn FnOnce() -> usize + Send>;
fn queue() -> &'static Mutex<mpsc::Sender<(Arc<Pending>, Job)>> {
static Q: OnceLock<Mutex<mpsc::Sender<(Arc<Pending>, Job)>>> = OnceLock::new();
Q.get_or_init(|| {
let (tx, rx) = mpsc::channel::<(Arc<Pending>, Job)>();
let rx = Arc::new(Mutex::new(rx));
// translation recurses deeply on big programs; DXC itself runs on its own pool
let n = std::thread::available_parallelism().map_or(4, |n| n.get());
for k in 0..n {
let rx = rx.clone();
let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop {
let next = rx.lock().unwrap().recv();
let Ok((p, job)) = next else { return };
let real = job();
if real == 0 {
FAILED.fetch_add(1, Ordering::Relaxed);
} else {
BUILT.fetch_add(1, Ordering::Relaxed);
}
p.real.store(real, Ordering::Release);
*p.done.lock().unwrap() = true;
p.cv.notify_all();
});
}
Mutex::new(tx)
})
}
/// `standin` went to the title; `job` builds the real pipeline on a worker.
pub fn submit(standin: usize, compute: bool, job: Job) {
let p = Arc::new(Pending { real: AtomicUsize::new(0), done: Mutex::new(false), cv: Condvar::new(), compute });
PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone());
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background");
});
let _ = queue().lock().unwrap().send((p, job));
}
fn entry(pso: usize) -> Option<Arc<Pending>> {
PENDING.lock().unwrap().as_ref()?.get(&pso).cloned()
}
/// The pipeline to use for `pso` now: the real one once built, else `pso` itself.
pub fn resolve(pso: usize) -> usize {
match entry(pso).map(|p| p.real.load(Ordering::Acquire)) {
Some(r) if r != 0 => r,
_ => pso,
}
}
/// `resolve`, waiting for a pipeline still being built.
pub fn resolve_wait(pso: usize) -> usize {
let Some(p) = entry(pso) else { return pso };
let mut done = p.done.lock().unwrap();
while !*done {
done = p.cv.wait(done).unwrap();
}
match p.real.load(Ordering::Acquire) {
0 => pso,
r => r,
}
}
/// For binding: compute pipelines are waited for, graphics ones are not.
pub fn resolve_for_bind(pso: usize) -> usize {
match entry(pso) {
Some(p) if p.compute => resolve_wait(pso),
Some(_) => resolve(pso),
None => pso,
}
}
/// `pso` is a stand-in whose real pipeline is still being built.
pub fn is_pending(pso: usize) -> bool {
entry(pso).is_some_and(|p| !*p.done.lock().unwrap())
}
/// (built in the background, failed, still building)
pub fn counts() -> (usize, usize, usize) {
let pending = PENDING.lock().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.done.lock().unwrap()).count());
(BUILT.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed), pending)
}
+273 -7
View File
@@ -115,6 +115,9 @@ pub struct D3d12Stats {
/// why console shaders could not be used (first messages)
#[serde(default)]
pub translation_errors: Vec<String>,
/// pipelines built in the background behind a stand-in: built, failed, still building
#[serde(default)]
pub background_pipelines: (usize, usize, usize),
}
static ADAPTER: Mutex<String> = Mutex::new(String::new());
@@ -257,6 +260,7 @@ pub fn stats() -> D3d12Stats {
uma_error: UMA_ERROR.lock().map(|e| e.clone()).unwrap_or_default(),
translated_pipelines: TRANSLATED_PSO.load(Ordering::Relaxed),
translation_errors: TRANSLATE_ERRORS.lock().map(|e| e.clone()).unwrap_or_default(),
background_pipelines: super::pso_async::counts(),
}
}
@@ -1020,7 +1024,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> {
("CreatePlacedResource1", dev_create_placed_resource1 as usize),
("CreateCommandQueue1", dev_create_command_queue1 as usize),
]),
Kind::CommandList => v.push(("OMSetRenderTargets", cl_om_set_render_targets as usize)),
Kind::CommandList => v.extend_from_slice(&[("OMSetRenderTargets", cl_om_set_render_targets as usize), ("SetPipelineState", cl_set_pipeline_state as usize)]),
Kind::CommandQueue => v.push(("ExecuteCommandLists", q_execute_command_lists as usize)),
Kind::CommandAllocator => v.push(("Reset", alloc_reset as usize)),
Kind::Resource => v.push(("Release", res_release as usize)),
@@ -1110,6 +1114,25 @@ struct Dummy {
cs: Vec<u8>,
}
/// Stand-in mesh shader and pixel shader (DXIL, as mesh pipelines need): one degenerate
/// triangle (DXC wants every output written), nothing drawn.
fn dummy_mesh() -> Option<&'static (Vec<u8>, Vec<u8>)> {
static D: OnceLock<Option<(Vec<u8>, Vec<u8>)>> = OnceLock::new();
D.get_or_init(|| {
use crate::gpu::recomp::dxc::compile;
let ms = "struct V { float4 p : SV_Position; };\n[outputtopology(\"triangle\")]\n[numthreads(1, 1, 1)]\nvoid main(out vertices V v[1], out indices uint3 t[1]) { SetMeshOutputCounts(1, 1); v[0].p = float4(0, 0, 0, 1); t[0] = uint3(0, 0, 0); }\n";
let ps = "float4 main() : SV_Target { return float4(1, 0, 1, 1); }\n";
match (compile(ms, "main", "ms_6_5", &[]), compile(ps, "main", "ps_6_0", &[])) {
(Ok(m), Ok(p)) => Some((m, p)),
(m, p) => {
crate::xlog_warn!("D3D12.X: stand-in mesh shaders: {:?} {:?}", m.err(), p.err());
None
}
}
})
.as_ref()
}
fn compile(src: &str, target: &str) -> Vec<u8> {
unsafe {
let mut blob = None;
@@ -1173,7 +1196,27 @@ unsafe fn finish_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *co
hr
}
thread_local! {
/// translation errors noted during a cached-only attempt (`attempt`)
static ATTEMPT_NOTES: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Run a translated-pipeline path without compiling (`dxc::cached_only`): (its result, whether
/// a shader was not compiled yet). Errors it noted count only when nothing was missing.
fn attempt<R>(f: impl FnOnce() -> R) -> (R, bool) {
let (r, missed) = crate::gpu::recomp::dxc::cached_only(f);
let notes = ATTEMPT_NOTES.with(|n| std::mem::take(&mut *n.borrow_mut()));
if !missed {
notes.into_iter().for_each(note_translation_error);
}
(r, missed)
}
fn note_translation_error(e: String) {
if crate::gpu::recomp::dxc::in_cached_only() {
ATTEMPT_NOTES.with(|n| n.borrow_mut().push(e));
return;
}
let mut g = TRANSLATE_ERRORS.lock().unwrap();
if g.len() < 5 {
crate::xlog_warn!("D3D12.X: console shaders in the PSO without a translation: {e}");
@@ -1200,6 +1243,7 @@ fn note_pso_rs(pso: *mut c_void, rs: *mut c_void) {
/// The root signature a translated pipeline state was created with.
pub fn pso_root_signature(pso: usize) -> Option<usize> {
let pso = super::pso_async::resolve(pso);
PSO_RS.lock().unwrap().as_ref()?.get(&pso).copied()
}
@@ -1357,10 +1401,205 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo
Some(hr)
}
// ---------------------------------------------------------------------------------------
// non-blocking pipeline creation (see `pso_async`)
// ---------------------------------------------------------------------------------------
/// A pipeline description that owns what it points to (shader blobs, input layout and its
/// semantic names), so a worker can build the pipeline after the title's memory is gone.
/// The root signature pointer is kept as is (the translated paths replace it).
#[allow(dead_code)] // the vectors only keep the copies alive
enum OwnedDesc {
Compute(Box<D3D12_COMPUTE_PIPELINE_STATE_DESC>, Vec<Vec<u8>>),
Graphics(Box<D3D12_GRAPHICS_PIPELINE_STATE_DESC>, Vec<Vec<u8>>, Vec<D3D12_INPUT_ELEMENT_DESC>, Vec<std::ffi::CString>),
Stream(Box<[usize; 2]>, Vec<u8>, Vec<Vec<u8>>),
}
unsafe impl Send for OwnedDesc {}
impl OwnedDesc {
fn ptr(&self) -> *const c_void {
match self {
OwnedDesc::Compute(d, _) => &**d as *const _ as *const c_void,
OwnedDesc::Graphics(d, ..) => &**d as *const _ as *const c_void,
OwnedDesc::Stream(d, ..) => &**d as *const _ as *const c_void,
}
}
}
/// Copy a shader blob into `blobs` and point `b` at the copy.
unsafe fn own_shader(b: &mut D3D12_SHADER_BYTECODE, blobs: &mut Vec<Vec<u8>>) {
if let Some(bytes) = shader_bytes(b) {
blobs.push(bytes.to_vec());
let v = blobs.last().unwrap();
*b = bytecode(v);
} else {
*b = D3D12_SHADER_BYTECODE::default();
}
}
unsafe fn own_compute(desc: *const c_void) -> Option<OwnedDesc> {
let mut d: Box<D3D12_COMPUTE_PIPELINE_STATE_DESC> = Box::new(std::ptr::read(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC));
let mut blobs = Vec::new();
own_shader(&mut d.CS, &mut blobs);
d.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default();
Some(OwnedDesc::Compute(d, blobs))
}
/// None with stream output (not copied; such pipelines are built in the call).
unsafe fn own_graphics(desc: *const c_void) -> Option<OwnedDesc> {
let mut d: Box<D3D12_GRAPHICS_PIPELINE_STATE_DESC> = Box::new(std::ptr::read(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC));
if d.StreamOutput.NumEntries > 0 {
return None;
}
let mut blobs = Vec::new();
for b in [&mut d.VS, &mut d.PS, &mut d.DS, &mut d.HS, &mut d.GS] {
own_shader(b, &mut blobs);
}
let n = d.InputLayout.NumElements as usize;
let mut elems = Vec::new();
let mut names = Vec::new();
if n > 0 && !d.InputLayout.pInputElementDescs.is_null() {
elems = std::slice::from_raw_parts(d.InputLayout.pInputElementDescs, n).to_vec();
for e in &mut elems {
names.push(std::ffi::CStr::from_ptr(e.SemanticName.0 as *const std::ffi::c_char).to_owned());
e.SemanticName = PCSTR(names.last().unwrap().as_ptr() as *const u8);
}
}
d.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: if elems.is_empty() { std::ptr::null() } else { elems.as_ptr() }, NumElements: elems.len() as u32 };
d.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default();
Some(OwnedDesc::Graphics(d, blobs, elems, names))
}
/// A pipeline state stream with its shaders copied. None when another subobject points at
/// title memory (input layout, stream output, view instancing).
unsafe fn own_stream(desc: *const c_void) -> Option<OwnedDesc> {
let (size, base) = (*(desc as *const usize), *((desc as usize + 8) as *const usize));
if !crate::gpu::shader::readable(base, size) {
return None;
}
let mut buf = std::slice::from_raw_parts(base as *const u8, size).to_vec();
let mut blobs: Vec<Vec<u8>> = Vec::new();
let mut off = 0usize;
while off + 8 <= size {
let ty = u32::from_le_bytes(buf[off..off + 4].try_into().ok()?);
let (psize, palign) = super::null::subobject_payload(ty)?;
let at = off + if palign == 8 { 8 } else { 4 };
let word = |buf: &[u8], k: usize| u64::from_le_bytes(buf[at + 8 * k..at + 8 * k + 8].try_into().unwrap());
match ty {
1..=6 | 24 | 25 => {
let (p, n) = (word(&buf, 0) as usize, word(&buf, 1) as usize);
if p != 0 && n != 0 && crate::gpu::shader::readable(p, n) {
blobs.push(std::slice::from_raw_parts(p as *const u8, n).to_vec());
buf[at..at + 8].copy_from_slice(&(blobs.last().unwrap().as_ptr() as u64).to_le_bytes());
}
}
7 | 12 | 22 if buf[at..at + psize].iter().any(|&b| b != 0) => return None,
19 => buf[at..at + 16].fill(0),
_ => {}
}
off += ((at - off) + psize + 7) & !7;
}
let d = Box::new([buf.len(), buf.as_ptr() as usize]);
Some(OwnedDesc::Stream(d, buf, blobs))
}
/// Raw pointers a worker needs (the device lives for the process).
#[derive(Clone, Copy)]
struct Dev(usize, usize);
unsafe impl Send for Dev {}
/// The stand-in for a pipeline with dummy shaders (draws / computes nothing).
unsafe fn standin_graphics(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
let d = dummy();
let mut copy: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::ptr::read(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC);
copy.VS = bytecode(&d.vs);
copy.PS = bytecode(&d.ps);
copy.DS = D3D12_SHADER_BYTECODE::default();
copy.HS = D3D12_SHADER_BYTECODE::default();
copy.GS = D3D12_SHADER_BYTECODE::default();
copy.StreamOutput = std::mem::zeroed();
copy.InputLayout = D3D12_INPUT_LAYOUT_DESC::default();
copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default();
finish_pso(this, f, &copy as *const _ as *const c_void, riid, ppv)
}
unsafe fn standin_compute(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC);
copy.CS = bytecode(&dummy().cs);
copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default();
finish_pso(this, f, &copy as *const _ as *const c_void, riid, ppv)
}
unsafe fn standin_stream(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
let Some((buf, _)) = fallback_stream(desc as *const u8) else { return E_INVALIDARG };
let new_desc: [usize; 2] = [buf.len(), buf.as_ptr() as usize];
finish_pso(this, f, new_desc.as_ptr() as *const c_void, riid, ppv)
}
/// Hand the title `standin`'s result now and build the real pipeline with `build` on a worker.
unsafe fn go_background(
this: *mut c_void,
f: PsoFn,
desc: *const c_void,
riid: *const GUID,
ppv: *mut *mut c_void,
compute: bool,
owned: OwnedDesc,
standin: unsafe fn(*mut c_void, PsoFn, *const c_void, *const GUID, *mut *mut c_void) -> HRESULT,
build: unsafe fn(Dev, &OwnedDesc, *mut *mut c_void) -> bool,
) -> Option<HRESULT> {
let hr = standin(this, f, desc, riid, ppv);
if hr < 0 || ppv.is_null() || (*ppv).is_null() {
static ONCE: AtomicU64 = AtomicU64::new(0);
if ONCE.fetch_add(1, Ordering::Relaxed) < 3 {
crate::xlog_warn!("D3D12.X: no stand-in pipeline ({hr:#x}) – building this one in the call");
}
return None;
}
let dev = Dev(this as usize, f as usize);
super::pso_async::submit(
*ppv as usize,
compute,
Box::new(move || {
let mut out: *mut c_void = std::ptr::null_mut();
if unsafe { build(dev, &owned, &mut out) } && !out.is_null() {
out as usize
} else {
0
}
}),
);
Some(hr)
}
unsafe fn build_graphics(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool {
let iid = pc_iid(Kind::PipelineState);
matches!(translated_graphics_pso(dev.0 as *mut c_void, std::mem::transmute::<usize, PsoFn>(dev.1), d.ptr(), &iid, out), Some(hr) if hr >= 0)
}
unsafe fn build_compute(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool {
let iid = pc_iid(Kind::PipelineState);
matches!(translated_compute_pso(dev.0 as *mut c_void, std::mem::transmute::<usize, PsoFn>(dev.1), d.ptr(), &iid, out), Some(Ok(hr)) if hr >= 0)
}
unsafe fn build_stream(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool {
let iid = pc_iid(Kind::PipelineState);
matches!(translated_mesh_stream(dev.0 as *mut c_void, d.ptr(), &iid, out), Some(hr) if hr >= 0)
}
unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
super::null::capture_graphics_desc(desc as *const u8);
let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateGraphicsPipelineState")));
if let Some(hr) = translated_graphics_pso(this, f, desc, riid, ppv) {
let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_graphics_pso(this, f, desc, riid, ppv)) } else { (translated_graphics_pso(this, f, desc, riid, ppv), false) };
if missed {
if let Some(hr) = own_graphics(desc).and_then(|o| go_background(this, f, desc, riid, ppv, false, o, standin_graphics, build_graphics)) {
return hr;
}
if let Some(hr) = translated_graphics_pso(this, f, desc, riid, ppv) {
return hr;
}
} else if let Some(hr) = translated {
return hr;
}
let hr = finish_pso(this, f, desc, riid, ppv);
@@ -1389,7 +1628,16 @@ unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void, desc: *cons
unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
super::null::capture_compute_desc(desc as *const u8);
let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState")));
let console = translated_compute_pso(this, f, desc, riid, ppv);
let (mut console, missed) = if super::pso_async::enabled() { attempt(|| translated_compute_pso(this, f, desc, riid, ppv)) } else { (translated_compute_pso(this, f, desc, riid, ppv), false) };
if missed {
if let Some(hr) = own_compute(desc).and_then(|o| go_background(this, f, desc, riid, ppv, true, o, standin_compute, build_compute)) {
// a console program the worker is translating (its root signature comes with it)
LAST_COMPUTE_TRANSLATED.with(|c| c.set(true));
LAST_COMPUTE_RS.with(|c| c.set(0));
return hr;
}
console = translated_compute_pso(this, f, desc, riid, ppv);
}
LAST_COMPUTE_TRANSLATED.with(|c| c.set(matches!(console, Some(Ok(hr)) if hr >= 0)));
if let Some(Ok(hr)) = console {
return hr;
@@ -1436,6 +1684,7 @@ static TWO_PASS: Mutex<Option<HashMap<usize, std::sync::Arc<TwoPassPso>>>> = Mut
/// The compute pass of a pipeline state XCL built from console MS / GS code.
pub fn two_pass_of(pso: usize) -> Option<std::sync::Arc<TwoPassPso>> {
let pso = super::pso_async::resolve(pso);
TWO_PASS.lock().unwrap().as_ref()?.get(&pso).cloned()
}
@@ -1624,6 +1873,8 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec<u8>, [usize; 2])> {
}
let mut buf = std::slice::from_raw_parts(base as *const u8, size).to_vec();
let d = dummy();
let mesh = stream_subobjects(&buf).is_some_and(|subs| subs.iter().any(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32));
let dm = if mesh { Some(dummy_mesh()?) } else { None };
let mut off = 0usize;
while off + 8 <= size {
let ty = u32::from_le_bytes(buf[off..off + 4].try_into().ok()?);
@@ -1636,10 +1887,10 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec<u8>, [usize; 2])> {
};
match ty {
1 => put(&mut buf, &d.vs),
2 => put(&mut buf, &d.ps),
2 => put(&mut buf, dm.map_or(&d.ps[..], |m| &m.1[..])),
6 => put(&mut buf, &d.cs),
3 | 4 | 5 => put(&mut buf, &[]),
24 | 25 => return None, // mesh pipelines need SM6.5 stand-ins
3 | 4 | 5 | 24 => put(&mut buf, &[]),
25 => put(&mut buf, &dm?.0),
12 | 19 => buf[at..at + 16].fill(0), // input layout, cached PSO
7 => buf[at..at + 32].fill(0), // stream output
_ => {}
@@ -1652,7 +1903,15 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec<u8>, [usize; 2])> {
unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
super::null::capture_stream_desc(desc as *const u8);
let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState")));
if let Some(hr) = translated_mesh_stream(this, desc, riid, ppv) {
let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_mesh_stream(this, desc, riid, ppv)) } else { (translated_mesh_stream(this, desc, riid, ppv), false) };
if missed {
if let Some(hr) = own_stream(desc).and_then(|o| go_background(this, f, desc, riid, ppv, false, o, standin_stream, build_stream)) {
return hr;
}
if let Some(hr) = translated_mesh_stream(this, desc, riid, ppv) {
return hr;
}
} else if let Some(hr) = translated {
return hr;
}
let hr = finish_pso(this, f, desc, riid, ppv);
@@ -1729,6 +1988,13 @@ unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rt
}
}
/// A stand-in pipeline is bound as its real pipeline once that is built (compute: waited for).
unsafe extern "system" fn cl_set_pipeline_state(this: *mut c_void, pso: *mut c_void) {
type F = unsafe extern "system" fn(*mut c_void, *mut c_void);
let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "SetPipelineState")));
f(this, super::pso_async::resolve_for_bind(pso as usize) as *mut c_void);
}
unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT {
type F = unsafe extern "system" fn(*mut c_void) -> HRESULT;
let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "Reset")));
+89 -2
View File
@@ -104,6 +104,8 @@ fn pso_through_hook(dev: &ID3D12Device, vs: &[u8], ps: &[u8], layout: &[(&CStr,
let before = real::stats();
let pso: ID3D12PipelineState = unsafe { dev.CreateGraphicsPipelineState(&desc) }.expect("CreateGraphicsPipelineState through the backend hook");
unsafe { std::mem::ManuallyDrop::drop(&mut desc.pRootSignature) };
// built in the background behind a stand-in when its shaders were not compiled yet
xcl::hle::d3d12x::pso_async::resolve_wait(pso.as_raw() as usize);
let after = real::stats();
assert_eq!(after.translated_pipelines, before.translated_pipelines + 1, "PSO was not built from the translated shaders: {:?}", after.translation_errors);
assert_eq!(after.fallback_pipelines, before.fallback_pipelines, "fallback shaders were used");
@@ -116,7 +118,15 @@ fn pso_through_hook(dev: &ID3D12Device, vs: &[u8], ps: &[u8], layout: &[(&CStr,
#[test]
fn retail_vs_ps_through_the_pso_hook_render_and_read_back() {
let Some((blobs, dev, _serial)) = setup(&["VS_Rage_TransformPosCpv_f020b20e_Wrapped", "PS_Rage_Untextured_14f8529b_Wrapped"]) else { return };
let pso = pso_through_hook(&dev, &blobs[0], &blobs[1], &[(c"POSITION", DXGI_FORMAT_R32G32B32_FLOAT, 0), (c"COLOR", DXGI_FORMAT_R32G32B32A32_FLOAT, 12)]);
let pso = pso_through_hook(&dev, &blobs[0], &blobs[1], &UNTEXTURED_LAYOUT);
check_untextured_triangle(&dev, &pso);
}
const UNTEXTURED_LAYOUT: [(&CStr, DXGI_FORMAT, u32); 2] = [(c"POSITION", DXGI_FORMAT_R32G32B32_FLOAT, 0), (c"COLOR", DXGI_FORMAT_R32G32B32A32_FLOAT, 12)];
/// Draw a triangle with the retail untextured VS / PS pipeline `pso` and check every pixel
/// against the same transform and interpolation on the CPU.
fn check_untextured_triangle(dev: &ID3D12Device, pso: &ID3D12PipelineState) {
// the pipeline's own root signature (static samplers from the console code)
let rs_raw = real::pso_root_signature(pso.as_raw() as usize).expect("root signature of the translated PSO") as *mut std::ffi::c_void;
let rs = unsafe { ID3D12RootSignature::from_raw_borrowed(&rs_raw) }.unwrap().clone();
@@ -151,7 +161,7 @@ fn retail_vs_ps_through_the_pso_hook_render_and_read_back() {
vertices.extend_from_slice(p);
vertices.extend_from_slice(c);
}
let px = runner::draw_on(&dev, &pso, &rs, &vertices, 28, &io, &mem, SIZE, CLEAR).expect("draw");
let px = runner::draw_on(dev, pso, &rs, &vertices, 28, &io, &mem, SIZE, CLEAR).expect("draw");
// expected: the same transform on the CPU → pixel-space triangle → interpolated colour
let to_px = |p: [f32; 3]| {
@@ -185,6 +195,83 @@ fn retail_vs_ps_through_the_pso_hook_render_and_read_back() {
assert!(inside > 400 && outside > 2500, "too few checked pixels: {inside} / {outside}");
}
/// Non-blocking pipeline creation with an empty DXIL cache: the call returns a stand-in at
/// once, the real pipeline is built in the background – and it renders exactly like one built
/// in the call; a mesh pipeline's two-pass parts are found through its stand-in once built.
#[test]
fn retail_pipelines_built_in_the_background_behind_a_stand_in() {
use xcl::hle::d3d12x::pso_async;
let Some((blobs, dev, _serial)) = setup(&["VS_Rage_TransformPosCpv_f020b20e_Wrapped", "PS_Rage_Untextured_14f8529b_Wrapped"]) else { return };
let cold = std::env::temp_dir().join(format!("xcl-async-pso-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&cold);
std::env::set_var("XCL_DXIL_CACHE", &cold);
let built_before = pso_async::counts().0;
let pso = pso_through_hook(&dev, &blobs[0], &blobs[1], &UNTEXTURED_LAYOUT); // waits for the real one
let raw = pso.as_raw() as usize;
assert_eq!(pso_async::counts().0, built_before + 1, "built in the background");
let real = pso_async::resolve(raw);
assert_ne!(real, raw, "the real pipeline replaces the stand-in");
assert!(real::pso_root_signature(raw).is_some(), "the stand-in resolves to the real pipeline's root signature");
let real_pso = unsafe { ID3D12PipelineState::from_raw_borrowed(&(real as *mut std::ffi::c_void)) }.unwrap().clone();
check_untextured_triangle(&dev, &real_pso);
// the shaders are in the cache now: the next pipeline is built in the call
let again = pso_through_hook(&dev, &blobs[0], &blobs[1], &UNTEXTURED_LAYOUT);
assert!(!pso_async::is_pending(again.as_raw() as usize) && pso_async::resolve(again.as_raw() as usize) == again.as_raw() as usize);
// a mesh pipeline (MS + PS of one pass) the same way
let data = std::fs::read(std::env::var("XCL_SAMPLE_RPF").unwrap()).unwrap();
let recs = pack::scan(&data, 0x40);
let (ms, ps) = recs
.iter()
.filter(|r| r.name.starts_with("MS"))
.find_map(|r| {
let h = pass_hash(&r.name)?;
let pr = recs.iter().find(|p| p.name.starts_with("PS_") && pass_hash(&p.name) == Some(h))?;
Some((pack::inflate(&data, r)?.to_vec(), pack::inflate(&data, pr)?.to_vec()))
})
.unwrap();
let game_rs: ID3D12RootSignature = unsafe {
let mut ser = None;
D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).unwrap();
let ser = ser.unwrap();
dev.CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())).unwrap()
};
#[repr(C, align(8))]
struct Sub<T> {
ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE,
v: T,
}
#[repr(C)]
struct Stream {
rs: Sub<*mut std::ffi::c_void>,
ms: Sub<D3D12_SHADER_BYTECODE>,
ps: Sub<D3D12_SHADER_BYTECODE>,
rt: Sub<D3D12_RT_FORMAT_ARRAY>,
}
let code = |b: &[u8]| D3D12_SHADER_BYTECODE { pShaderBytecode: b.as_ptr() as _, BytecodeLength: b.len() };
let mut rt = D3D12_RT_FORMAT_ARRAY { NumRenderTargets: 1, ..Default::default() };
rt.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
let st = Stream {
rs: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, v: game_rs.as_raw() },
ms: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, v: code(&ms) },
ps: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, v: code(&ps) },
rt: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, v: rt },
};
let d2: ID3D12Device2 = dev.cast().unwrap();
let desc = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: std::mem::size_of::<Stream>(), pPipelineStateSubobjectStream: &st as *const _ as *mut _ };
let t0 = std::time::Instant::now();
let mesh: ID3D12PipelineState = unsafe { d2.CreatePipelineState(&desc) }.expect("mesh stand-in");
let call = t0.elapsed();
let raw = mesh.as_raw() as usize;
assert!(pso_async::is_pending(raw) && real::two_pass_of(raw).is_none(), "a mesh stand-in, no compute pass yet");
drop(st); // the title's description is gone; the worker builds from its own copy
assert_ne!(pso_async::resolve_wait(raw), raw);
assert!(real::two_pass_of(raw).is_some(), "the two-pass parts through the stand-in");
println!("mesh: the call returned after {call:?}, the real pipeline was ready after {:?}", t0.elapsed());
std::env::remove_var("XCL_DXIL_CACHE");
let _ = std::fs::remove_dir_all(&cold);
}
/// Texel (x, y) of the two test textures, RGBA8.
fn texel_a(x: usize, y: usize) -> [u8; 4] {
[(x * 4) as u8, (y * 4) as u8, if (x / 8 + y / 8) % 2 == 0 { 255 } else { 0 }, 255]