From 4e8aaf4b393ce59d7053de987906a0f8a4aed476 Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:41:20 -0800 Subject: [PATCH 1/5] D3D12.X: the PC desc of a translated VS / PS pipeline in its own function prep_graphics: what translated_graphics_pso did between its checks and the driver call (the translated shaders, XCL's ABI root signature with their static samplers, the rect list GS, PC formats and topology), returned with the DXIL it points at. No change in behaviour; a later change makes the same desc outside the title (xcl pipelines). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/real.rs | 67 +++++++++++++++++++------------ 1 file changed, 42 insertions(+), 25 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ac7ab4c4d..ddfad69f7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3949,32 +3949,19 @@ unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: m.insert(key, std::sync::Arc::new(bytes)); } -unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { - with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv)) -} - -unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { +/// The PC desc of a pipeline with a console VS (and PS) and no GS / HS / DS: the translated +/// shaders, XCL's ABI root signature, PC formats and topology (`translated_graphics_pso`, apart +/// from making the pipeline). +struct GraphicsPrep { + desc: D3D12_GRAPHICS_PIPELINE_STATE_DESC, + rs: *mut c_void, + rect_gs: Option>, + /// the VS / PS DXIL `desc` points at + _dxil: (Vec, Option>), +} + +unsafe fn prep_graphics(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, vs: &[u8]) -> Option { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; - if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { - return None; - } - let d = &*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); - let vs = shader_bytes(&d.VS)?; - if !is_console(vs) { - return None; - } - if shader_bytes(&d.HS).is_some() || shader_bytes(&d.DS).is_some() { - note_translation_error("PSO with HS/DS – not supported yet".into()); - return None; - } - if let Some(gs) = shader_bytes(&d.GS).filter(|g| is_console(g)) { - let _ = f; - return Some(translated_gs_pso(this, d, vs, gs, riid, ppv)); - } - // made when first used (`pso_async::lazy`): not even translated now - if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { - return None; - } // a GPU that can run 32-lane waves may run a wave64 VS / PS in waves of 32 (the driver // picks; RDNA2 does for pixel shaders): the lanes 32..63 it reads come from `upper_lanes` // (split_wave64) @@ -4019,6 +4006,36 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const copy.GS = bytecode(gs); } pc_topology_type(&mut copy); + Some(GraphicsPrep { desc: copy, rs, rect_gs, _dxil: (vs_dxil, ps_dxil) }) +} + +unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { + with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv)) +} + +unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { + use crate::gpu::recomp::pso::is_console; + if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return None; + } + let d = &*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); + let vs = shader_bytes(&d.VS)?; + if !is_console(vs) { + return None; + } + if shader_bytes(&d.HS).is_some() || shader_bytes(&d.DS).is_some() { + note_translation_error("PSO with HS/DS – not supported yet".into()); + return None; + } + if let Some(gs) = shader_bytes(&d.GS).filter(|g| is_console(g)) { + let _ = f; + return Some(translated_gs_pso(this, d, vs, gs, riid, ppv)); + } + // made when first used (`pso_async::lazy`): not even translated now + if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { + return None; + } + let GraphicsPrep { desc: mut copy, rs, rect_gs, _dxil } = prep_graphics(this, d, vs)?; let ps_hash = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); if debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash) { copy.DepthStencilState.StencilEnable = false.into(); From e62643edc429f85ac0525ea10816fe7920293eba Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:43:12 -0800 Subject: [PATCH 2/5] D3D12.X: a journal of the pipelines a title queues (\cache\pipelines.bin) Every pipeline with console shaders that goes to pso_async (its DXIL not in the cache yet, or made lazily: a retail title queues ~58 000 in its first minute) is appended to a journal: its desc field by field (no pointers, no padding: the same pipeline always hashes the same), its input layout and its shaders by hash, each shader once, with the run's memory windows. A pipeline's first build is marked as used. Entries of earlier runs are not written again (found from the frames' headers, the shaders stay on disk); a torn last frame is cut off. One title process writes it at a time (others get none). The reader (replay) gives the desc back with everything it points to owned and no pointer from the file. Another process can compile the title's pipelines from it; XCL_PSO_JOURNAL=0 turns it off. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/pso_journal.rs | 436 +++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/real.rs | 7 + 3 files changed, 444 insertions(+) create mode 100644 crates/xcl/src/hle/d3d12x/pso_journal.rs diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index f3f035798..87c6ca901 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -25,6 +25,7 @@ pub mod list_x; pub mod null; pub mod present; pub mod pso_async; +pub mod pso_journal; pub mod real; mod shader_cache_session; pub mod sparse; diff --git a/crates/xcl/src/hle/d3d12x/pso_journal.rs b/crates/xcl/src/hle/d3d12x/pso_journal.rs new file mode 100644 index 000000000..788dbf87c --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/pso_journal.rs @@ -0,0 +1,436 @@ +//! The pipelines a title asked for, on disk (`\cache\pipelines.bin`), so another process +//! can compile them: `xcl pipelines` reads the journal – during the run (`--watch`) or before +//! the next one – and fills the DXIL cache and the driver's with what the title will ask for. +//! Written for every pipeline with console shaders that goes to `pso_async` (its DXIL was not +//! in the cache, or it is made lazily); a pipeline's first build is marked as used, which the +//! tool compiles first. `XCL_PSO_JOURNAL=0`: off. +//! +//! Append-only frames, little-endian: tag u8, memory windows u8, 0 u16, payload length u32, +//! hash u64, payload. Tags: `S` a shader (its bytes; hash = fnv64 of them), `G` a graphics +//! pipeline, `C` a compute one, `U` (no payload) pipeline `hash` was built. A pipeline's +//! payload names its shaders by hash; each shader is written once, before the first pipeline +//! that uses it. Duplicates of earlier runs are not written again. + +use std::collections::HashSet; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use windows::Win32::Graphics::Direct3D12::*; + +pub const MAGIC: &[u8; 8] = b"XCLPJ001"; +pub const HEAD: usize = 16; + +pub fn path_in(data_dir: &Path) -> PathBuf { + data_dir.join("cache").join("pipelines.bin") +} + +struct Journal { + file: std::fs::File, + seen: HashSet<(u8, u64)>, +} + +static J: Mutex>> = Mutex::new(None); + +fn enabled() -> bool { + std::env::var("XCL_PSO_JOURNAL").map_or(true, |v| v != "0") +} + +fn open() -> Option { + use std::io::{Read, Seek, SeekFrom}; + use std::os::windows::fs::OpenOptionsExt; + if !enabled() { + return None; + } + let path = path_in(&crate::state::data_dir()); + let _ = std::fs::create_dir_all(path.parent()?); + // the only writer: another title process gets no journal (`xcl pipelines` only reads) + const FILE_SHARE_READ: u32 = 1; + let mut file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .share_mode(FILE_SHARE_READ) + .open(&path) + .map_err(|e| crate::xlog_warn!("pipeline journal {}: {e} – none in this run", path.display())) + .ok()?; + let mut seen = HashSet::new(); + let len = file.metadata().map_or(0, |m| m.len()); + let mut magic = [0u8; 8]; + if file.read_exact(&mut magic).is_ok() && &magic == MAGIC { + // the frames' headers only (the shaders' bytes stay on disk); a torn last frame (a + // run killed mid-write) is cut off + let mut at = MAGIC.len() as u64; + let mut head = [0u8; HEAD]; + while file.read_exact(&mut head).is_ok() { + let end = at + HEAD as u64 + u32::from_le_bytes(head[4..8].try_into().unwrap()) as u64; + if end > len { + break; + } + seen.insert((head[0], u64::from_le_bytes(head[8..16].try_into().unwrap()))); + at = end; + if file.seek(SeekFrom::Start(at)).is_err() { + break; + } + } + if at < len { + let _ = file.set_len(at); + } + } else { + let _ = file.set_len(0); + let _ = file.seek(SeekFrom::Start(0)); + let _ = file.write_all(MAGIC); + } + file.seek(SeekFrom::End(0)).ok()?; + crate::xlog_info!("pipeline journal: {} ({} entries from earlier runs) – `xcl pipelines` compiles them outside the title", path.display(), seen.len()); + Some(Journal { file, seen }) +} + +fn with(f: impl FnOnce(&mut Journal)) { + let mut g = J.lock().unwrap(); + if let Some(j) = g.get_or_insert_with(open).as_mut() { + f(j); + } +} + +fn frame(tag: u8, windows: u8, hash: u64, payload: &[u8]) -> Vec { + let mut v = Vec::with_capacity(HEAD + payload.len()); + v.extend_from_slice(&[tag, windows, 0, 0]); + v.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + v.extend_from_slice(&hash.to_le_bytes()); + v.extend_from_slice(payload); + v +} + +/// One frame of the journal. +pub struct Frame<'a> { + pub tag: u8, + pub windows: u8, + pub hash: u64, + pub payload: &'a [u8], +} + +/// Call `f` on each whole frame of `bytes` (a journal from its start); the end of the last whole one. +pub fn for_each_frame<'a>(bytes: &'a [u8], f: impl FnMut(Frame<'a>)) -> usize { + for_each_frame_from(bytes, MAGIC.len(), f) +} + +/// `for_each_frame` from offset `at` (the end of an earlier call: a journal being written). +pub fn for_each_frame_from<'a>(bytes: &'a [u8], mut at: usize, mut f: impl FnMut(Frame<'a>)) -> usize { + while at + HEAD <= bytes.len() { + let n = u32::from_le_bytes(bytes[at + 4..at + 8].try_into().unwrap()) as usize; + if at + HEAD + n > bytes.len() { + break; + } + f(Frame { tag: bytes[at], windows: bytes[at + 1], hash: u64::from_le_bytes(bytes[at + 8..at + 16].try_into().unwrap()), payload: &bytes[at + HEAD..at + HEAD + n] }); + at += HEAD + n; + } + at.min(bytes.len()) +} + +/// Copy each field named into `out` at its offset in `T`: a desc's bytes without its pointers +/// and padding (both stay 0), so the same pipeline always gives the same bytes and hash. +macro_rules! fields { + ($out:expr, $d:expr, $T:ty, $($($f:ident).+),+ $(,)?) => {{ + $(put_at(&mut $out, std::mem::offset_of!($T, $($f).+), &$d.$($f).+);)+ + }}; +} + +fn put_at(out: &mut [u8], off: usize, v: &V) { + let b = unsafe { std::slice::from_raw_parts(v as *const V as *const u8, std::mem::size_of::()) }; + out[off..off + b.len()].copy_from_slice(b); +} + +fn graphics_bytes(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Vec { + type G = D3D12_GRAPHICS_PIPELINE_STATE_DESC; + type R = D3D12_RENDER_TARGET_BLEND_DESC; + let mut out = vec![0u8; std::mem::size_of::()]; + fields!(out, d, G, BlendState.AlphaToCoverageEnable, BlendState.IndependentBlendEnable, SampleMask); + let rt0 = std::mem::offset_of!(G, BlendState.RenderTarget); + for (i, r) in d.BlendState.RenderTarget.iter().enumerate() { + let mut one = vec![0u8; std::mem::size_of::()]; + fields!(one, r, R, BlendEnable, LogicOpEnable, SrcBlend, DestBlend, BlendOp, SrcBlendAlpha, DestBlendAlpha, BlendOpAlpha, LogicOp, RenderTargetWriteMask); + let at = rt0 + i * one.len(); + out[at..at + one.len()].copy_from_slice(&one); + } + fields!( + out, d, G, + RasterizerState.FillMode, RasterizerState.CullMode, RasterizerState.FrontCounterClockwise, RasterizerState.DepthBias, + RasterizerState.DepthBiasClamp, RasterizerState.SlopeScaledDepthBias, RasterizerState.DepthClipEnable, + RasterizerState.MultisampleEnable, RasterizerState.AntialiasedLineEnable, RasterizerState.ForcedSampleCount, + RasterizerState.ConservativeRaster, + DepthStencilState.DepthEnable, DepthStencilState.DepthWriteMask, DepthStencilState.DepthFunc, DepthStencilState.StencilEnable, + DepthStencilState.StencilReadMask, DepthStencilState.StencilWriteMask, + DepthStencilState.FrontFace.StencilFailOp, DepthStencilState.FrontFace.StencilDepthFailOp, + DepthStencilState.FrontFace.StencilPassOp, DepthStencilState.FrontFace.StencilFunc, + DepthStencilState.BackFace.StencilFailOp, DepthStencilState.BackFace.StencilDepthFailOp, + DepthStencilState.BackFace.StencilPassOp, DepthStencilState.BackFace.StencilFunc, + InputLayout.NumElements, IBStripCutValue, PrimitiveTopologyType, NumRenderTargets, RTVFormats, DSVFormat, + SampleDesc.Count, SampleDesc.Quality, NodeMask, Flags, + ); + out +} + +fn compute_bytes(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC) -> Vec { + type C = D3D12_COMPUTE_PIPELINE_STATE_DESC; + let mut out = vec![0u8; std::mem::size_of::()]; + fields!(out, d, C, NodeMask, Flags); + out +} + +unsafe fn bytes_of<'a>(b: &D3D12_SHADER_BYTECODE) -> Option<&'a [u8]> { + (!b.pShaderBytecode.is_null() && b.BytecodeLength != 0).then(|| std::slice::from_raw_parts(b.pShaderBytecode as *const u8, b.BytecodeLength)) +} + +fn put_shader(j: &mut Journal, out: &mut Vec, sh: Option<&[u8]>) -> std::io::Result<()> { + let h = sh.map_or(0, crate::gpu::shader::fnv64); + if let Some(sh) = sh { + if j.seen.insert((b'S', h)) { + j.file.write_all(&frame(b'S', 0, h, sh))?; + } + } + out.extend_from_slice(&h.to_le_bytes()); + Ok(()) +} + +fn finish(j: &mut Journal, tag: u8, mut payload: Vec) -> std::io::Result { + // the memory windows are part of what the pipeline is (its HLSL differs with them) + let windows = crate::gpu::recomp::pso::mem_windows() as u8; + payload.push(windows); + let hash = crate::gpu::shader::fnv64(&payload); + payload.pop(); + if j.seen.insert((tag, hash)) { + j.file.write_all(&frame(tag, windows, hash, &payload))?; + } + Ok(hash) +} + +/// Note a graphics pipeline; its hash for `used`, 0 = not written. +pub unsafe fn graphics(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> u64 { + let mut hash = 0; + with(|j| hash = graphics_in(j, d).unwrap_or(0)); + hash +} + +unsafe fn graphics_in(j: &mut Journal, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> std::io::Result { + let mut p = Vec::new(); + for b in [&d.VS, &d.PS, &d.DS, &d.HS, &d.GS] { + put_shader(j, &mut p, bytes_of(b))?; + } + let desc = graphics_bytes(d); + p.extend_from_slice(&(desc.len() as u32).to_le_bytes()); + p.extend_from_slice(&desc); + let elems = if d.InputLayout.NumElements > 0 && !d.InputLayout.pInputElementDescs.is_null() { + std::slice::from_raw_parts(d.InputLayout.pInputElementDescs, d.InputLayout.NumElements as usize) + } else { + &[] + }; + p.extend_from_slice(&(elems.len() as u32).to_le_bytes()); + for e in elems { + let name = std::ffi::CStr::from_ptr(e.SemanticName.0 as *const std::ffi::c_char).to_bytes(); + p.extend_from_slice(&(name.len() as u32).to_le_bytes()); + p.extend_from_slice(name); + for w in [e.SemanticIndex, e.Format.0 as u32, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0 as u32, e.InstanceDataStepRate] { + p.extend_from_slice(&w.to_le_bytes()); + } + } + finish(j, b'G', p) +} + +/// Note a compute pipeline; its hash for `used`, 0 = not written. +pub unsafe fn compute(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC) -> u64 { + let mut hash = 0; + with(|j| { + let r = (|| { + let mut p = Vec::new(); + put_shader(j, &mut p, bytes_of(&d.CS))?; + let desc = compute_bytes(d); + p.extend_from_slice(&(desc.len() as u32).to_le_bytes()); + p.extend_from_slice(&desc); + finish(j, b'C', p) + })(); + hash = r.unwrap_or(0); + }); + hash +} + +/// Pipeline `hash` was built (the title used it): `xcl pipelines` makes these first. +pub fn used(hash: u64) { + if hash == 0 { + return; + } + with(|j| { + if j.seen.insert((b'U', hash)) { + let _ = j.file.write_all(&frame(b'U', 0, hash, &[])); + } + }); +} + +/// A journal's pipeline, read back with everything it points to owned. +pub enum Replay { + Graphics(Box, Vec>, Vec, Vec), + Compute(Box, Vec>), +} + +unsafe impl Send for Replay {} + +fn read_desc(p: &[u8], at: &mut usize) -> Option> { + let n = u32::from_le_bytes(p.get(*at..*at + 4)?.try_into().ok()?) as usize; + *at += 4; + let bytes = p.get(*at..*at + n)?; + *at += n; + if n != std::mem::size_of::() { + return None; + } + unsafe { + let mut b: Box> = Box::new(std::mem::MaybeUninit::zeroed()); + std::ptr::copy_nonoverlapping(bytes.as_ptr(), b.as_mut_ptr() as *mut u8, n); + Some(Box::from_raw(Box::into_raw(b) as *mut T)) + } +} + +fn u32_at(p: &[u8], at: &mut usize) -> Option { + let v = u32::from_le_bytes(p.get(*at..*at + 4)?.try_into().ok()?); + *at += 4; + Some(v) +} + +/// The pipeline of frame `f` (`G` / `C`), its shaders from `shader` by hash. None: malformed, +/// or a shader not in the journal. +pub fn replay(f: &Frame, shader: impl Fn(u64) -> Option>) -> Option { + let p = f.payload; + let mut at = 0usize; + let sh = |at: &mut usize| -> Option>> { + let h = u64::from_le_bytes(p.get(*at..*at + 8)?.try_into().ok()?); + *at += 8; + if h == 0 { + return Some(None); + } + Some(Some(shader(h)?)) + }; + let code = |b: &Vec| D3D12_SHADER_BYTECODE { pShaderBytecode: b.as_ptr() as *const _, BytecodeLength: b.len() }; + match f.tag { + b'C' => { + let cs = sh(&mut at)??; + let mut d: Box = read_desc(p, &mut at)?; + // (no pointer from the file reaches the driver) + d.pRootSignature = std::mem::ManuallyDrop::new(None); + d.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + d.CS = code(&cs); + Some(Replay::Compute(d, vec![cs])) + } + b'G' => { + let mut blobs = Vec::new(); + let mut slots = [None; 5]; + for s in slots.iter_mut() { + if let Some(b) = sh(&mut at)? { + blobs.push(b); + *s = Some(blobs.len() - 1); + } + } + let mut d: Box = read_desc(p, &mut at)?; + // (no pointer from the file reaches the driver) + d.pRootSignature = std::mem::ManuallyDrop::new(None); + d.StreamOutput = unsafe { std::mem::zeroed() }; + d.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + for b in [&mut d.VS, &mut d.PS, &mut d.DS, &mut d.HS, &mut d.GS] { + *b = D3D12_SHADER_BYTECODE::default(); + } + for (s, b) in slots.iter().zip([&mut d.VS, &mut d.PS, &mut d.DS, &mut d.HS, &mut d.GS]) { + if let Some(i) = s { + *b = code(&blobs[*i]); + } + } + let n = u32_at(p, &mut at)? as usize; + let mut names = Vec::with_capacity(n); + let mut raw = Vec::with_capacity(n); + for _ in 0..n { + let len = u32_at(p, &mut at)? as usize; + names.push(std::ffi::CString::new(p.get(at..at + len)?).ok()?); + at += len; + let mut w = [0u32; 6]; + for x in w.iter_mut() { + *x = u32_at(p, &mut at)?; + } + raw.push(w); + } + let elems: Vec = names + .iter() + .zip(&raw) + .map(|(name, w)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: windows::core::PCSTR(name.as_ptr() as *const u8), + SemanticIndex: w[0], + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(w[1] as i32), + InputSlot: w[2], + AlignedByteOffset: w[3], + InputSlotClass: D3D12_INPUT_CLASSIFICATION(w[4] as i32), + InstanceDataStepRate: w[5], + }) + .collect(); + d.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: if elems.is_empty() { std::ptr::null() } else { elems.as_ptr() }, NumElements: elems.len() as u32 }; + Some(Replay::Graphics(d, blobs, elems, names)) + } + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn graphics_round_trip() { + let vs = vec![1u8, 2, 3, 4]; + let ps = vec![9u8; 40]; + let name = std::ffi::CString::new("TEXCOORD").unwrap(); + let elems = [D3D12_INPUT_ELEMENT_DESC { SemanticName: windows::core::PCSTR(name.as_ptr() as *const u8), SemanticIndex: 3, InputSlot: 1, AlignedByteOffset: 12, ..Default::default() }]; + let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + d.VS = D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as *const _, BytecodeLength: vs.len() }; + d.PS = D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as *const _, BytecodeLength: ps.len() }; + d.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elems.as_ptr(), NumElements: 1 }; + d.NumRenderTargets = 2; + d.SampleMask = 0xffff_ffff; + let mut j = Journal { file: tempfile(), seen: HashSet::new() }; + let h1 = unsafe { graphics_in(&mut j, &d).unwrap() }; + let h2 = unsafe { graphics_in(&mut j, &d).unwrap() }; + assert_eq!(h1, h2, "the same desc made again: the same hash"); + // garbage in the padding after a render target's write mask (a desc built on the stack) + let mut d3: D3D12_GRAPHICS_PIPELINE_STATE_DESC = unsafe { std::ptr::read(&d) }; + let pad = std::mem::offset_of!(D3D12_GRAPHICS_PIPELINE_STATE_DESC, BlendState.RenderTarget) + + std::mem::offset_of!(D3D12_RENDER_TARGET_BLEND_DESC, RenderTargetWriteMask) + + 1; + unsafe { *(&mut d3 as *mut D3D12_GRAPHICS_PIPELINE_STATE_DESC as *mut u8).add(pad) = 0xAA }; + assert_eq!(unsafe { graphics_in(&mut j, &d3).unwrap() }, h1, "padding is not part of the pipeline"); + std::mem::forget(d3); + let mut bytes = MAGIC.to_vec(); + use std::io::{Read, Seek}; + j.file.seek(std::io::SeekFrom::Start(0)).unwrap(); + j.file.read_to_end(&mut bytes).unwrap(); + let mut frames = Vec::new(); + for_each_frame(&bytes, |f| frames.push((f.tag, f.hash, f.payload.to_vec()))); + assert_eq!(frames.iter().filter(|f| f.0 == b'S').count(), 2); + assert_eq!(frames.iter().filter(|f| f.0 == b'G').count(), 1, "written once"); + let g = frames.iter().find(|f| f.0 == b'G').unwrap(); + let shader = |h| frames.iter().find(|f| f.0 == b'S' && f.1 == h).map(|f| f.2.clone()); + let Some(Replay::Graphics(r, blobs, _elems, _names)) = replay(&Frame { tag: b'G', windows: 0, hash: g.1, payload: &g.2 }, shader) else { panic!("no replay") }; + assert_eq!(blobs, vec![vs.clone(), ps.clone()]); + unsafe { + assert_eq!(bytes_of(&r.VS).unwrap(), &vs[..]); + assert_eq!(bytes_of(&r.PS).unwrap(), &ps[..]); + assert!(bytes_of(&r.GS).is_none()); + assert_eq!((r.NumRenderTargets, r.SampleMask, r.InputLayout.NumElements), (2, 0xffff_ffff, 1)); + let e = &*r.InputLayout.pInputElementDescs; + assert_eq!((e.SemanticName.to_string().unwrap().as_str(), e.SemanticIndex, e.InputSlot, e.AlignedByteOffset), ("TEXCOORD", 3, 1, 12)); + } + // a torn tail is not a frame + let whole = for_each_frame(&bytes, |_| {}); + assert_eq!(for_each_frame(&bytes[..bytes.len() - 3], |_| {}) < whole, true); + } + + fn tempfile() -> std::fs::File { + let p = std::env::temp_dir().join(format!("xcl_pso_journal_{}.bin", std::process::id())); + let f = std::fs::OpenOptions::new().create(true).truncate(true).read(true).write(true).open(&p).unwrap(); + let _ = std::fs::remove_file(&p); + f + } +} diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ddfad69f7..77e8e9424 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4309,9 +4309,16 @@ unsafe fn go_background( } let dev = Dev(this as usize, f as usize); let key = owned.shaders_key(); + // for `xcl pipelines`, which compiles them in its own process (`pso_journal`) + let journal = match &owned { + OwnedDesc::Graphics(d, ..) => super::pso_journal::graphics(d), + OwnedDesc::Compute(d, _) => super::pso_journal::compute(d), + OwnedDesc::Stream(..) => 0, + }; let job: super::pso_async::Job = Box::new(move || { let mut out: *mut c_void = std::ptr::null_mut(); if unsafe { build(dev, &owned, &mut out) } && !out.is_null() { + super::pso_journal::used(journal); out as usize } else { 0 From bc5bdc73bdf7dd8b6156e869e8845041af2d19f7 Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:19:57 -0800 Subject: [PATCH 3/5] D3D12.X: a journal write error cuts its frame back and ends the journal for the run A frame is now noted as written only once all of it is on disk; a failed write (a full disk) is cut back to where it started, so later frames stay readable, and the journal is off for the rest of the run. An input layout count read from the file is checked against the bytes there before anything is allocated for it. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/pso_journal.rs | 70 ++++++++++++++---------- 1 file changed, 40 insertions(+), 30 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_journal.rs b/crates/xcl/src/hle/d3d12x/pso_journal.rs index 788dbf87c..835044011 100644 --- a/crates/xcl/src/hle/d3d12x/pso_journal.rs +++ b/crates/xcl/src/hle/d3d12x/pso_journal.rs @@ -12,7 +12,7 @@ //! that uses it. Duplicates of earlier runs are not written again. use std::collections::HashSet; -use std::io::Write; +use std::io::{Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use std::sync::Mutex; use windows::Win32::Graphics::Direct3D12::*; @@ -86,10 +86,17 @@ fn open() -> Option { Some(Journal { file, seen }) } -fn with(f: impl FnOnce(&mut Journal)) { +/// Runs `f` on the journal; a write error turns it off for the rest of the run (0). +fn with(f: impl FnOnce(&mut Journal) -> std::io::Result) -> u64 { let mut g = J.lock().unwrap(); - if let Some(j) = g.get_or_insert_with(open).as_mut() { - f(j); + let Some(j) = g.get_or_insert_with(open).as_mut() else { return 0 }; + match f(j) { + Ok(h) => h, + Err(e) => { + crate::xlog_warn!("pipeline journal: {e}: off for this run"); + *g = Some(None); + 0 + } } } @@ -182,12 +189,25 @@ unsafe fn bytes_of<'a>(b: &D3D12_SHADER_BYTECODE) -> Option<&'a [u8]> { (!b.pShaderBytecode.is_null() && b.BytecodeLength != 0).then(|| std::slice::from_raw_parts(b.pShaderBytecode as *const u8, b.BytecodeLength)) } +/// Writes a frame once: all of it, or (an error) none of it, so later frames stay readable. +fn put(j: &mut Journal, tag: u8, windows: u8, hash: u64, payload: &[u8]) -> std::io::Result<()> { + if j.seen.contains(&(tag, hash)) { + return Ok(()); + } + let at = j.file.stream_position()?; + if let Err(e) = j.file.write_all(&frame(tag, windows, hash, payload)) { + let _ = j.file.set_len(at); + let _ = j.file.seek(SeekFrom::Start(at)); + return Err(e); + } + j.seen.insert((tag, hash)); + Ok(()) +} + fn put_shader(j: &mut Journal, out: &mut Vec, sh: Option<&[u8]>) -> std::io::Result<()> { let h = sh.map_or(0, crate::gpu::shader::fnv64); if let Some(sh) = sh { - if j.seen.insert((b'S', h)) { - j.file.write_all(&frame(b'S', 0, h, sh))?; - } + put(j, b'S', 0, h, sh)?; } out.extend_from_slice(&h.to_le_bytes()); Ok(()) @@ -199,17 +219,13 @@ fn finish(j: &mut Journal, tag: u8, mut payload: Vec) -> std::io::Result u64 { - let mut hash = 0; - with(|j| hash = graphics_in(j, d).unwrap_or(0)); - hash + with(|j| graphics_in(j, d)) } unsafe fn graphics_in(j: &mut Journal, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> std::io::Result { @@ -239,19 +255,14 @@ unsafe fn graphics_in(j: &mut Journal, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) - /// Note a compute pipeline; its hash for `used`, 0 = not written. pub unsafe fn compute(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC) -> u64 { - let mut hash = 0; with(|j| { - let r = (|| { - let mut p = Vec::new(); - put_shader(j, &mut p, bytes_of(&d.CS))?; - let desc = compute_bytes(d); - p.extend_from_slice(&(desc.len() as u32).to_le_bytes()); - p.extend_from_slice(&desc); - finish(j, b'C', p) - })(); - hash = r.unwrap_or(0); - }); - hash + let mut p = Vec::new(); + put_shader(j, &mut p, bytes_of(&d.CS))?; + let desc = compute_bytes(d); + p.extend_from_slice(&(desc.len() as u32).to_le_bytes()); + p.extend_from_slice(&desc); + finish(j, b'C', p) + }) } /// Pipeline `hash` was built (the title used it): `xcl pipelines` makes these first. @@ -259,11 +270,7 @@ pub fn used(hash: u64) { if hash == 0 { return; } - with(|j| { - if j.seen.insert((b'U', hash)) { - let _ = j.file.write_all(&frame(b'U', 0, hash, &[])); - } - }); + with(|j| put(j, b'U', 0, hash, &[]).map(|_| 0)); } /// A journal's pipeline, read back with everything it points to owned. @@ -342,6 +349,9 @@ pub fn replay(f: &Frame, shader: impl Fn(u64) -> Option>) -> Option (p.len() - at) / 28 { + return None; // each element: a name length and six words at least + } let mut names = Vec::with_capacity(n); let mut raw = Vec::with_capacity(n); for _ in 0..n { From 0cc1dee0cef78fb8bb35e9240d41d64b411b3c12 Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:23:07 -0800 Subject: [PATCH 4/5] D3D12.X: the journal keeps a run's heap-window flag Since #680 `pso::mem_windows` carries HEAP_WINDOWS (0x100) when the title's shaders take the memory windows from the descriptor heap (XCL_HEAP_WINDOWS=1). The frame's windows byte cut it off, so a heap-window run's pipelines read as the switch form's. The count stays in the low 7 bits and the flag goes in the top bit (`windows_byte`, `mem_windows_of`). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013hQzywPUY9kSTPQPh31CWh --- crates/xcl/src/hle/d3d12x/pso_journal.rs | 27 +++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_journal.rs b/crates/xcl/src/hle/d3d12x/pso_journal.rs index 835044011..06dc27fba 100644 --- a/crates/xcl/src/hle/d3d12x/pso_journal.rs +++ b/crates/xcl/src/hle/d3d12x/pso_journal.rs @@ -5,7 +5,7 @@ //! in the cache, or it is made lazily); a pipeline's first build is marked as used, which the //! tool compiles first. `XCL_PSO_JOURNAL=0`: off. //! -//! Append-only frames, little-endian: tag u8, memory windows u8, 0 u16, payload length u32, +//! Append-only frames, little-endian: tag u8, memory windows u8 (`windows_byte`), 0 u16, payload length u32, //! hash u64, payload. Tags: `S` a shader (its bytes; hash = fnv64 of them), `G` a graphics //! pipeline, `C` a compute one, `U` (no payload) pipeline `hash` was built. A pipeline's //! payload names its shaders by hash; each shader is written once, before the first pipeline @@ -213,9 +213,21 @@ fn put_shader(j: &mut Journal, out: &mut Vec, sh: Option<&[u8]>) -> std::io: Ok(()) } +/// `pso::mem_windows` in a frame's byte: the count in the low 7 bits, `HEAP_WINDOWS` in the top +/// bit (the shaders take the windows from the descriptor heap: other HLSL than the switch form). +pub fn windows_byte(mem_windows: u32) -> u8 { + (mem_windows & 0x7F) as u8 | if mem_windows & crate::gpu::recomp::HEAP_WINDOWS != 0 { 0x80 } else { 0 } +} + +/// A frame's memory windows as `pso::mem_windows` had them (`windows_byte`). +pub fn mem_windows_of(byte: u8) -> u32 { + (byte & 0x7F) as u32 | if byte & 0x80 != 0 { crate::gpu::recomp::HEAP_WINDOWS } else { 0 } +} + fn finish(j: &mut Journal, tag: u8, mut payload: Vec) -> std::io::Result { - // the memory windows are part of what the pipeline is (its HLSL differs with them) - let windows = crate::gpu::recomp::pso::mem_windows() as u8; + // the memory windows are part of what the pipeline is (its HLSL differs with them, and with + // heap windows) + let windows = windows_byte(crate::gpu::recomp::pso::mem_windows()); payload.push(windows); let hash = crate::gpu::shader::fnv64(&payload); payload.pop(); @@ -388,6 +400,15 @@ pub fn replay(f: &Frame, shader: impl Fn(u64) -> Option>) -> Option Date: Tue, 24 Nov 2026 10:48:13 -0800 Subject: [PATCH 5/5] D3D12.X: the pipeline journal opens off the title's threads, and locks only to append The first pipeline the title noted read the frame headers of every earlier run (about 63 000 for a 123 MB journal) with the journal's lock held, and each later one hashed its shaders and desc under the same lock, so the title's pipeline threads waited on one another. An entry is now built and hashed with no lock held, and the lock covers its append only. The journal is opened on a thread of its own; what is noted meanwhile waits in memory, each frame once (up to 256 MB, past which the journal is off for the run), and is written in order once it is open. `XCL_PSO_JOURNAL` is read once, and a journal turned off stops entries being built at all. A panic on another thread while it held the lock no longer ends the journal. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013hQzywPUY9kSTPQPh31CWh --- crates/xcl/src/hle/d3d12x/pso_journal.rs | 196 +++++++++++++++++++---- 1 file changed, 163 insertions(+), 33 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_journal.rs b/crates/xcl/src/hle/d3d12x/pso_journal.rs index 06dc27fba..651814c42 100644 --- a/crates/xcl/src/hle/d3d12x/pso_journal.rs +++ b/crates/xcl/src/hle/d3d12x/pso_journal.rs @@ -10,11 +10,16 @@ //! pipeline, `C` a compute one, `U` (no payload) pipeline `hash` was built. A pipeline's //! payload names its shaders by hash; each shader is written once, before the first pipeline //! that uses it. Duplicates of earlier runs are not written again. +//! +//! On the title's pipeline threads an entry is built and hashed with no lock held; the lock +//! covers its append only. The journal is opened (the frame headers of earlier runs read) on a +//! thread of its own, and what is noted meanwhile waits in memory (`State::Opening`). use std::collections::HashSet; use std::io::{Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; -use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, MutexGuard}; use windows::Win32::Graphics::Direct3D12::*; pub const MAGIC: &[u8; 8] = b"XCLPJ001"; @@ -29,10 +34,39 @@ struct Journal { seen: HashSet<(u8, u64)>, } -static J: Mutex>> = Mutex::new(None); +/// A frame to append: tag, windows byte, hash, payload. +type Out<'a> = (u8, u8, u64, &'a [u8]); + +enum State { + Closed, + /// being opened (`open_in_background`): the frames noted meanwhile, owned, each once, and + /// their bytes + Opening(Vec<(u8, u8, u64, Vec)>, HashSet<(u8, u64)>, usize), + Open(Journal), + Off, +} + +static J: Mutex = Mutex::new(State::Closed); +/// set with `State::Off`, so that the title's threads stop building entries +static OFF: AtomicBool = AtomicBool::new(false); +/// what may wait in memory while the journal is opened +const OPENING_MAX: usize = 256 << 20; fn enabled() -> bool { - std::env::var("XCL_PSO_JOURNAL").map_or(true, |v| v != "0") + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PSO_JOURNAL").map_or(true, |v| v != "0")) && !OFF.load(Ordering::Relaxed) +} + +/// A panic on another thread while it held the lock does not end the journal (each change of +/// the state is one assignment, so it stays whole). +fn lock() -> MutexGuard<'static, State> { + J.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn turn_off(g: &mut State, why: impl std::fmt::Display) { + crate::xlog_warn!("pipeline journal: {why}: off for this run"); + *g = State::Off; + OFF.store(true, Ordering::Relaxed); } fn open() -> Option { @@ -86,17 +120,60 @@ fn open() -> Option { Some(Journal { file, seen }) } -/// Runs `f` on the journal; a write error turns it off for the rest of the run (0). -fn with(f: impl FnOnce(&mut Journal) -> std::io::Result) -> u64 { - let mut g = J.lock().unwrap(); - let Some(j) = g.get_or_insert_with(open).as_mut() else { return 0 }; - match f(j) { - Ok(h) => h, - Err(e) => { - crate::xlog_warn!("pipeline journal: {e}: off for this run"); - *g = Some(None); - 0 +/// Appends `frames` in order (shaders before the pipeline that names them); a write error turns +/// the journal off for the rest of the run. The first call starts the opening. +fn write(frames: &[Out]) { + if note(&mut lock(), frames) && std::thread::Builder::new().name("xcl-pso-journal".into()).spawn(open_in_background).is_err() { + turn_off(&mut lock(), "no thread to open it"); + } +} + +/// `write` on the state; true: the caller starts the opening. +fn note(g: &mut State, frames: &[Out]) -> bool { + match g { + State::Off => false, + State::Open(j) => { + if let Err(e) = frames.iter().try_for_each(|&(t, w, h, p)| put(j, t, w, h, p)) { + turn_off(g, e); + } + false } + State::Opening(q, kept, bytes) => { + for &(t, w, h, p) in frames { + if kept.insert((t, h)) { + *bytes += p.len(); + q.push((t, w, h, p.to_vec())); + } + } + if *bytes > OPENING_MAX { + turn_off(g, "too much noted while it was opened"); + } + false + } + State::Closed => { + *g = State::Opening(Vec::new(), HashSet::new(), 0); + note(g, frames); + true + } + } +} + +/// Opens the journal with no lock held (the title's threads go on noting), then writes what +/// they noted meanwhile. +fn open_in_background() { + let j = open(); + opened(&mut lock(), j); +} + +fn opened(g: &mut State, j: Option) { + let State::Opening(q, ..) = std::mem::replace(g, State::Off) else { return }; + let Some(mut j) = j else { + OFF.store(true, Ordering::Relaxed); + return; + }; + match q.iter().try_for_each(|(t, w, h, p)| put(&mut j, *t, *w, *h, p)) { + Ok(()) => *g = State::Open(j), + Err(e) => turn_off(g, e), } } @@ -204,13 +281,30 @@ fn put(j: &mut Journal, tag: u8, windows: u8, hash: u64, payload: &[u8]) -> std: Ok(()) } -fn put_shader(j: &mut Journal, out: &mut Vec, sh: Option<&[u8]>) -> std::io::Result<()> { +/// A pipeline's frames, built and hashed with no lock held: its shaders', then its own. +struct Entry<'a> { + shaders: Vec>, + tag: u8, + windows: u8, + hash: u64, + payload: Vec, +} + +impl Entry<'_> { + fn frames(&self) -> Vec> { + let mut f = self.shaders.clone(); + f.push((self.tag, self.windows, self.hash, &self.payload)); + f + } +} + +/// A shader's hash into the pipeline's payload, and its frame (none for an empty slot). +fn add_shader<'a>(shaders: &mut Vec>, out: &mut Vec, sh: Option<&'a [u8]>) { let h = sh.map_or(0, crate::gpu::shader::fnv64); if let Some(sh) = sh { - put(j, b'S', 0, h, sh)?; + shaders.push((b'S', 0, h, sh)); } out.extend_from_slice(&h.to_le_bytes()); - Ok(()) } /// `pso::mem_windows` in a frame's byte: the count in the low 7 bits, `HEAP_WINDOWS` in the top @@ -224,26 +318,34 @@ pub fn mem_windows_of(byte: u8) -> u32 { (byte & 0x7F) as u32 | if byte & 0x80 != 0 { crate::gpu::recomp::HEAP_WINDOWS } else { 0 } } -fn finish(j: &mut Journal, tag: u8, mut payload: Vec) -> std::io::Result { +fn entry(shaders: Vec, tag: u8, mut payload: Vec) -> Entry { // the memory windows are part of what the pipeline is (its HLSL differs with them, and with // heap windows) let windows = windows_byte(crate::gpu::recomp::pso::mem_windows()); payload.push(windows); let hash = crate::gpu::shader::fnv64(&payload); payload.pop(); - put(j, tag, windows, hash, &payload)?; - Ok(hash) + Entry { shaders, tag, windows, hash, payload } +} + +/// Writes the entry; its hash. +fn note_entry(e: Entry) -> u64 { + write(&e.frames()); + e.hash } /// Note a graphics pipeline; its hash for `used`, 0 = not written. pub unsafe fn graphics(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> u64 { - with(|j| graphics_in(j, d)) + if !enabled() { + return 0; + } + note_entry(graphics_entry(d)) } -unsafe fn graphics_in(j: &mut Journal, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> std::io::Result { - let mut p = Vec::new(); +unsafe fn graphics_entry(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Entry<'_> { + let (mut shaders, mut p) = (Vec::new(), Vec::new()); for b in [&d.VS, &d.PS, &d.DS, &d.HS, &d.GS] { - put_shader(j, &mut p, bytes_of(b))?; + add_shader(&mut shaders, &mut p, bytes_of(b)); } let desc = graphics_bytes(d); p.extend_from_slice(&(desc.len() as u32).to_le_bytes()); @@ -262,19 +364,20 @@ unsafe fn graphics_in(j: &mut Journal, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) - p.extend_from_slice(&w.to_le_bytes()); } } - finish(j, b'G', p) + entry(shaders, b'G', p) } /// Note a compute pipeline; its hash for `used`, 0 = not written. pub unsafe fn compute(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC) -> u64 { - with(|j| { - let mut p = Vec::new(); - put_shader(j, &mut p, bytes_of(&d.CS))?; - let desc = compute_bytes(d); - p.extend_from_slice(&(desc.len() as u32).to_le_bytes()); - p.extend_from_slice(&desc); - finish(j, b'C', p) - }) + if !enabled() { + return 0; + } + let (mut shaders, mut p) = (Vec::new(), Vec::new()); + add_shader(&mut shaders, &mut p, bytes_of(&d.CS)); + let desc = compute_bytes(d); + p.extend_from_slice(&(desc.len() as u32).to_le_bytes()); + p.extend_from_slice(&desc); + note_entry(entry(shaders, b'C', p)) } /// Pipeline `hash` was built (the title used it): `xcl pipelines` makes these first. @@ -282,7 +385,7 @@ pub fn used(hash: u64) { if hash == 0 { return; } - with(|j| put(j, b'U', 0, hash, &[]).map(|_| 0)); + write(&[(b'U', 0, hash, &[])]); } /// A journal's pipeline, read back with everything it points to owned. @@ -458,6 +561,33 @@ mod tests { assert_eq!(for_each_frame(&bytes[..bytes.len() - 3], |_| {}) < whole, true); } + /// The entry written straight to `j` (no global state); its hash. + unsafe fn graphics_in(j: &mut Journal, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> std::io::Result { + let e = graphics_entry(d); + e.frames().iter().try_for_each(|&(t, w, h, p)| put(j, t, w, h, p))?; + Ok(e.hash) + } + + #[test] + fn what_is_noted_while_the_journal_opens_is_written_after_in_order() { + let (vs, ps) = (vec![1u8; 8], vec![2u8; 8]); + let mut g = State::Closed; + assert!(note(&mut g, &[(b'S', 0, 11, &vs[..]), (b'G', 0, 21, &[7])]), "the first note starts the opening"); + assert!(!note(&mut g, &[(b'S', 0, 11, &vs[..]), (b'S', 0, 12, &ps[..]), (b'G', 0, 22, &[8])]), "only once"); + assert!(!note(&mut g, &[(b'U', 0, 21, &[])])); + let State::Opening(q, _, bytes) = &g else { panic!("not opening") }; + assert_eq!((q.len(), *bytes), (5, 18), "a shader noted twice is kept once"); + opened(&mut g, Some(Journal { file: tempfile(), seen: HashSet::new() })); + let State::Open(j) = &mut g else { panic!("not open") }; + let mut bytes = MAGIC.to_vec(); + use std::io::{Read, Seek}; + j.file.seek(std::io::SeekFrom::Start(0)).unwrap(); + j.file.read_to_end(&mut bytes).unwrap(); + let mut order = Vec::new(); + for_each_frame(&bytes, |f| order.push((f.tag, f.hash))); + assert_eq!(order, [(b'S', 11), (b'G', 21), (b'S', 12), (b'G', 22), (b'U', 21)]); + } + fn tempfile() -> std::fs::File { let p = std::env::temp_dir().join(format!("xcl_pso_journal_{}.bin", std::process::id())); let f = std::fs::OpenOptions::new().create(true).truncate(true).read(true).write(true).open(&p).unwrap();