From b04438c7533111277ab2b5b532335682c1989a82 Mon Sep 17 00:00:00 2001 From: CryingLaughing <62956736+CryingLaughing@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:49:45 +0800 Subject: [PATCH 1/6] Shaders: replay compatible two-pass mesh pipelines at startup Record supported console mesh streams with their fixed-function state and source shader keys. Replay through the existing graphics worker and two-pass translator to populate the runtime driver caches. Keep legacy graphics history compatible and leave unsupported streams to the existing runtime path. --- README.md | 8 +- crates/xcl/src/hle/d3d12x/gfx_records.rs | 220 +++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 121 ++++++++++++- crates/xcl/src/shaders.rs | 97 +++++++--- 4 files changed, 398 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index 5d2feb513e..fafec20621 100644 --- a/README.md +++ b/README.md @@ -247,10 +247,10 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. five seconds without progress counts as a stall, and the window shows when the last one ended. XCL prepares supported shader stages and compute pipelines, including split pieces and their whole fallback. Graphics pipelines are created during play the first - time; the ones a run used are recorded with their state (`used-graphics-pipelines.bin` beside - the shader cache, at most `XCL_GFX_RECORDS_MB`, default 64) and built before the title starts - on the next launch, with their driver blobs kept, so the title makes them from those in - milliseconds. `XCL_PREPARE_GRAPHICS=0` leaves that pass out. Later launches reuse matching cache entries. + time. The startup history records supported graphics descriptors and two-pass mesh streams with + their state (`used-graphics-pipelines.bin` beside the shader cache, capped by `XCL_GFX_RECORDS_MB` + at 64 MB by default). On the next launch, XCL builds the recorded pipelines before the title starts + and keeps their driver blobs for reuse. `XCL_PREPARE_GRAPHICS=0` leaves that pass out. Closing the window cancels the launch. A compiler or driver failure stops it and reports the cause. Null-renderer runs skip shader preparation. With presentation disabled, the gate runs without a window. - For compute shaders that XCL can split, the runtime first tries the saved driver blob for diff --git a/crates/xcl/src/hle/d3d12x/gfx_records.rs b/crates/xcl/src/hle/d3d12x/gfx_records.rs index cb4b872354..552e0ecb46 100644 --- a/crates/xcl/src/hle/d3d12x/gfx_records.rs +++ b/crates/xcl/src/hle/d3d12x/gfx_records.rs @@ -11,9 +11,11 @@ //! entry = length u32, check u32 (the low half of fnv64 of the payload), payload //! payload = 1 key u64 shaders [u64; 5] state input* a pipeline //! | 2 key u64 bytes a shader (preparation job files only) -//! key = `real::shaders_key` of the set (as `used-pipelines.txt` has it); in a shader entry +//! | 3 key u64 shaders [u64; 2] layout state a mesh pipeline stream +//! key = `real::shaders_key` of the set, in mesh then PS order for mesh; in a shader entry, //! `real::shader_key` of it -//! shaders = `real::shader_key` of the VS, PS, DS, HS, GS (0: none) +//! shaders = `real::shader_key` of VS, PS, DS, HS, GS, or mesh, PS (0: none) +//! layout = subobject count (u8), then subobject types in stream order (u8 each) //! state = every field of the description but its pointers, in `state`'s order (varints) //! input = count, then each element's semantic name (length, bytes), index, format, slot, //! offset, class, step rate (varints) @@ -34,11 +36,13 @@ use std::path::{Path, PathBuf}; use windows::Win32::Graphics::Direct3D12::*; const MAGIC: &[u8; 8] = b"XCLGFXP\0"; -/// The layout of an entry: a change makes every file of the older one read as none. +/// The file format and existing entry layouts. Optional new tags keep earlier entries readable. const VERSION: u32 = 1; const HEADER: usize = 12; const PIPELINE: u8 = 1; const SHADER: u8 = 2; +const MESH_PIPELINE: u8 = 3; +const MAX_MESH_LAYOUT: usize = 14; // root, mesh (MS or AS), PS, and eleven scalar state types /// The records of this cache (beside the DXIL cache, as `used-pipelines.txt`). pub(crate) fn path() -> PathBuf { @@ -84,6 +88,12 @@ impl Reader<'_> { fn u32var(&mut self) -> Option { self.var().and_then(|v| u32::try_from(v).ok()) } + fn bounded_var(&mut self, max: u32) -> Option { + let before = self.0.len(); + let v = self.u32var()?; + let bits = (u32::BITS - v.leading_zeros()).max(1); + (before - self.0.len() == bits.div_ceil(7) as usize && v <= max).then_some(v) + } fn u64(&mut self) -> Option { let (b, rest) = self.0.split_at_checked(8)?; self.0 = rest; @@ -100,25 +110,25 @@ impl Reader<'_> { /// cached blob), each as a u32 handed to `f`, which may change it: one order for writing and /// reading. What the title's translated pipeline is made of beside its shaders /// (`real::graphics_blob_key` hashes the same). -fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32)) { +fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32, u32)) { macro_rules! int { ($x:expr) => {{ let mut v = $x as u32; - f(&mut v); + f(&mut v, u32::MAX); $x = v as i32; }}; } macro_rules! byte { ($x:expr) => {{ let mut v = $x as u32; - f(&mut v); + f(&mut v, u8::MAX.into()); $x = v as u8; }}; } macro_rules! float { ($x:expr) => {{ let mut v = $x.to_bits(); - f(&mut v); + f(&mut v, u32::MAX); $x = f32::from_bits(v); }}; } @@ -137,7 +147,7 @@ fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32) int!(rt.LogicOp.0); byte!(rt.RenderTargetWriteMask); } - f(&mut d.SampleMask); + f(&mut d.SampleMask, u32::MAX); let r = &mut d.RasterizerState; int!(r.FillMode.0); int!(r.CullMode.0); @@ -148,7 +158,7 @@ fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32) int!(r.DepthClipEnable.0); int!(r.MultisampleEnable.0); int!(r.AntialiasedLineEnable.0); - f(&mut r.ForcedSampleCount); + f(&mut r.ForcedSampleCount, u32::MAX); int!(r.ConservativeRaster.0); let z = &mut d.DepthStencilState; int!(z.DepthEnable.0); @@ -165,14 +175,14 @@ fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32) } int!(d.IBStripCutValue.0); int!(d.PrimitiveTopologyType.0); - f(&mut d.NumRenderTargets); + f(&mut d.NumRenderTargets, 8); for format in &mut d.RTVFormats { int!(format.0); } int!(d.DSVFormat.0); - f(&mut d.SampleDesc.Count); - f(&mut d.SampleDesc.Quality); - f(&mut d.NodeMask); + f(&mut d.SampleDesc.Count, u32::MAX); + f(&mut d.SampleDesc.Quality, u32::MAX); + f(&mut d.NodeMask, u32::MAX); int!(d.Flags.0); } @@ -187,7 +197,7 @@ pub(crate) unsafe fn encode(key: u64, shaders: [u64; 5], d: &D3D12_GRAPHICS_PIPE } // (a copy for `state`, which takes the fields by `&mut`; its pointers are not used) let mut copy: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::ptr::read(d); - state(&mut copy, &mut |v| put_var(&mut out, *v as u64)); + state(&mut copy, &mut |v, _| put_var(&mut out, *v as u64)); let il = &d.InputLayout; let elems = if il.NumElements > 0 && !il.pInputElementDescs.is_null() { std::slice::from_raw_parts(il.pInputElementDescs, il.NumElements as usize) } else { &[] }; put_var(&mut out, elems.len() as u64); @@ -202,6 +212,73 @@ pub(crate) unsafe fn encode(key: u64, shaders: [u64; 5], d: &D3D12_GRAPHICS_PIPE out } +fn valid_mesh_layout(shaders: [u64; 2], layout: &[u32]) -> bool { + if shaders[0] == 0 || layout.len() > MAX_MESH_LAYOUT { + return false; + } + let mut seen = 0u32; + for &id in layout { + match D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(id as i32) { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS => {} + _ => return false, + } + let bit = 1 << id; + if seen & bit != 0 { + return false; + } + seen |= bit; + } + let has = |kind: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE| seen & (1 << kind.0) != 0; + (has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS) != has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS)) + && has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS) == (shaders[1] != 0) +} + +/// A mesh stream entry with shader keys in mesh, PS order and subobjects in their original order. +pub(crate) fn encode_mesh(key: u64, shaders: [u64; 2], layout: &[u32], d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Option> { + if key == 0 || !valid_mesh_layout(shaders, layout) || d.NumRenderTargets > 8 { + return None; + } + let mut values = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + BlendState: d.BlendState, + SampleMask: d.SampleMask, + RasterizerState: d.RasterizerState, + DepthStencilState: d.DepthStencilState, + IBStripCutValue: d.IBStripCutValue, + PrimitiveTopologyType: d.PrimitiveTopologyType, + NumRenderTargets: d.NumRenderTargets, + RTVFormats: d.RTVFormats, + DSVFormat: d.DSVFormat, + SampleDesc: d.SampleDesc, + NodeMask: d.NodeMask, + Flags: d.Flags, + ..Default::default() + }; + let mut out = Vec::with_capacity(256); + out.push(MESH_PIPELINE); + out.extend_from_slice(&key.to_le_bytes()); + for shader in shaders { + out.extend_from_slice(&shader.to_le_bytes()); + } + out.push(layout.len() as u8); + out.extend(layout.iter().map(|&id| id as u8)); + state(&mut values, &mut |v, _| put_var(&mut out, (*v).into())); + Some(out) +} + /// A shader entry (the preparation's job files): `bytes`, of `real::shader_key` `key`. pub(crate) fn shader_entry(key: u64, bytes: &[u8]) -> Vec { let mut out = Vec::with_capacity(9 + bytes.len()); @@ -241,11 +318,48 @@ impl Record { } } +pub(crate) struct MeshRecord { + pub key: u64, + pub shaders: [u64; 2], + pub layout: Vec, + desc: Box, +} + +// The decoder starts with null pointers and only fills scalar fields. The descriptor is immutable. +unsafe impl Send for MeshRecord {} +unsafe impl Sync for MeshRecord {} + +impl MeshRecord { + pub(crate) fn state(&self) -> &D3D12_GRAPHICS_PIPELINE_STATE_DESC { + &self.desc + } +} + pub(crate) enum Entry { Pipeline(Record), + MeshPipeline(MeshRecord), Shader(u64, Vec), } +fn decode_mesh(key: u64, mut r: Reader<'_>) -> Option { + let shaders = [r.u64()?, r.u64()?]; + let n = *r.bytes(1)?.first()? as usize; + if key == 0 || n > MAX_MESH_LAYOUT { + return None; + } + let layout: Vec = r.bytes(n)?.iter().map(|&id| id.into()).collect(); + if !valid_mesh_layout(shaders, &layout) { + return None; + } + let mut desc = Box::::default(); + let mut valid = true; + state(&mut desc, &mut |v, max| match r.bounded_var(max) { + Some(x) => *v = x, + None => valid = false, + }); + (valid && r.0.is_empty()).then_some(MeshRecord { key, shaders, layout, desc }) +} + /// The entry of `payload` (None: not one this version writes). pub(crate) fn decode(payload: &[u8]) -> Option { let (&tag, rest) = payload.split_first()?; @@ -254,6 +368,9 @@ pub(crate) fn decode(payload: &[u8]) -> Option { if tag == SHADER { return Some(Entry::Shader(key, r.0.to_vec())); } + if tag == MESH_PIPELINE { + return decode_mesh(key, r).map(Entry::MeshPipeline); + } if tag != PIPELINE { return None; } @@ -263,7 +380,7 @@ pub(crate) fn decode(payload: &[u8]) -> Option { } let mut desc: Box = Box::new(unsafe { std::mem::zeroed() }); let mut short = false; - state(&mut desc, &mut |v| match r.u32var() { + state(&mut desc, &mut |v, _| match r.u32var() { Some(x) => *v = x, None => short = true, }); @@ -578,7 +695,78 @@ mod tests { let payload = unsafe { encode(9, [9, 0, 0, 0, 0], &described()) }; assert!(decode(&payload[..payload.len() - 1]).is_none(), "cut short"); assert!(decode(&[payload.as_slice(), &[0]].concat()).is_none(), "a byte too many"); - assert!(decode(&[3, 0, 0, 0, 0, 0, 0, 0, 0]).is_none(), "another kind of entry"); + assert!(decode(&[u8::MAX, 0, 0, 0, 0, 0, 0, 0, 0]).is_none(), "another kind of entry"); + } + + #[test] + fn a_mesh_entry_preserves_moved_shader_slot_order_and_state() { + let layout = [ + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, + ].map(|kind| kind.0 as u32); + let shaders = [0x13, 0x27]; + let mut desc = described(); + let ps = b"pixel"; + desc.PS = D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr().cast(), BytecodeLength: ps.len() }; + let payload = encode_mesh(0x1234, shaders, &layout, &desc).unwrap(); + let Some(Entry::MeshPipeline(record)) = decode(&payload) else { panic!("expected a mesh entry") }; + assert_eq!((record.key, record.shaders), (0x1234, shaders)); + assert_eq!(record.layout, layout); + assert_eq!(record.state().RasterizerState.DepthBias, desc.RasterizerState.DepthBias); + assert_eq!(record.state().RTVFormats, desc.RTVFormats); + assert!(record.state().PS.pShaderBytecode.is_null()); + assert_eq!(encode_mesh(record.key, record.shaders, &record.layout, record.state()).unwrap(), payload); + } + + #[test] + fn mesh_entries_require_supported_unique_layout_and_exact_payload() { + let ms = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32; + let moved = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS.0 as u32; + let ps = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32; + let input = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0 as u32; + let d = described(); + for layout in [vec![], vec![ms, moved], vec![ms, ms], vec![ms, ps], vec![ms, input]] { + assert!(encode_mesh(1, [1, 0], &layout, &d).is_none(), "unsupported layout {layout:?}"); + } + assert!(encode_mesh(1, [1, 2], &[ms], &d).is_none()); + assert!(encode_mesh(1, [0, 0], &[ms], &d).is_none()); + let payload = encode_mesh(1, [1, 0], &[ms], &d).unwrap(); + assert!(decode(&payload[..payload.len() - 1]).is_none()); + assert!(decode(&[payload.as_slice(), &[0]].concat()).is_none()); + + let count_at = 1 + 3 * std::mem::size_of::(); + let mut invalid = payload.clone(); + invalid[count_at] = MAX_MESH_LAYOUT as u8 + 1; + assert!(decode(&invalid).is_none()); + invalid[count_at] = 1; + invalid[count_at + 1] = input as u8; + assert!(decode(&invalid).is_none()); + let state_at = count_at + 2; + let overlong = [&payload[..state_at], &[0x81, 0], &payload[state_at + 1..]].concat(); + assert!(decode(&overlong).is_none()); + } + + #[test] + fn legacy_pipeline_and_mesh_entries_share_version_one_history() { + let dir = directory("mesh-version-one"); + let path = dir.0.join("records.bin"); + let legacy = unsafe { encode(3, [3, 0, 0, 0, 0], &described()) }; + let shader = shader_entry(5, b"mesh"); + let mesh = encode_mesh(5, [5, 0], &[D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32], &described()).unwrap(); + let mut writer = Writer::open(&path, 1 << 20).unwrap(); + writer.add(&legacy).unwrap(); + writer.add(&mesh).unwrap(); + writer.add(&shader).unwrap(); + drop(writer); + assert_eq!(&std::fs::read(&path).unwrap()[8..HEADER], &1u32.to_le_bytes()); + assert_eq!(read(&path), vec![legacy.clone(), mesh.clone(), shader.clone()]); + assert_eq!(pipeline(&legacy).key, 3); + assert!(matches!(decode(&mesh), Some(Entry::MeshPipeline(_)))); + assert!(matches!(decode(&shader), Some(Entry::Shader(5, _)))); } /// Written, read back in order, each entry once; a file cut short in its last entry keeps the diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index c12d907e36..7614c96b80 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6378,6 +6378,10 @@ pub(crate) fn shader_key(blob: &[u8]) -> u64 { } pub(crate) fn shaders_key(blobs: &[Vec]) -> u64 { + shader_set_key(blobs.iter().map(Vec::as_slice)) +} + +pub(crate) fn shader_set_key<'a>(blobs: impl IntoIterator) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; for b in blobs { h = (h ^ crate::gpu::shader::fnv64(b)).wrapping_mul(0x0000_0100_0000_01b3); @@ -6423,8 +6427,11 @@ impl OwnedDesc { } /// A graphics pipeline's entry for the next run's preparation (`gfx_records`), of the set - /// `key` whose shaders' keys are `parts`; None for any other. + /// `key` whose shaders' keys are `parts`, or an eligible mesh stream's entry. unsafe fn record(&self, key: u64, parts: &[u64]) -> Option> { + if let OwnedDesc::Stream(_, stream, _) = self { + return record_mesh_stream(stream); + } let OwnedDesc::Graphics(d, ..) = self else { return None }; // (`own_graphics` copied the stages it has, in this order) let mut parts = parts.iter(); @@ -7029,6 +7036,118 @@ unsafe fn payload_shader<'a>(p: &[u8]) -> Option<&'a [u8]> { shader_bytes(&b) } +/// Keep the source states the mesh translator will use again during preparation. +unsafe fn record_mesh_stream(stream: &[u8]) -> Option> { + let subs = stream_subobjects(stream)?; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + let mut layout = Vec::with_capacity(subs.len()); + let (mut ms, mut amplification, mut ps) = (None, None, None); + let (mut seen, mut size) = (0u32, 0usize); + + fn value(payload: &[u8]) -> Option { + (payload.len() == std::mem::size_of::()).then(|| unsafe { std::ptr::read_unaligned(payload.as_ptr().cast()) }) + } + + for (ty, payload) in subs { + let (_, align) = super::null::subobject_payload(ty)?; + size += (align + payload.len() + 7) & !7; + let bit = 1u32 << ty; + if seen & bit != 0 { + return None; + } + seen |= bit; + match ty { + 0 => {} // The translator supplies its own root signature. + 19 => continue, // The title's cache blob is never an input to translation. + 2 | 24 | 25 if payload.iter().all(|&b| b == 0) => continue, + 2 => ps = Some(payload_shader(payload)?), + 24 => amplification = Some(payload_shader(payload)?), + 25 => ms = Some(payload_shader(payload)?), + 8 => desc.BlendState = value(payload)?, + 9 => desc.SampleMask = value(payload)?, + 10 => desc.RasterizerState = value(payload)?, + 11 => desc.DepthStencilState = value(payload)?, + 13 => desc.IBStripCutValue = value(payload)?, + 14 => desc.PrimitiveTopologyType = value(payload)?, + 15 => { + let rt: D3D12_RT_FORMAT_ARRAY = value(payload)?; + if rt.NumRenderTargets > 8 { + return None; + } + desc.NumRenderTargets = rt.NumRenderTargets; + desc.RTVFormats = rt.RTFormats; + } + 16 => desc.DSVFormat = value(payload)?, + 17 => desc.SampleDesc = value(payload)?, + 18 => desc.NodeMask = value(payload)?, + 20 => desc.Flags = value(payload)?, + _ => return None, + } + layout.push(ty); + } + if size != stream.len() || (ms.is_some() && amplification.is_some()) { + return None; + } + let ms = ms.or(amplification)?; + if !crate::gpu::xbox::parse(ms).is_some_and(|shader| shader.stage == "MS") { + return None; + } + let shaders = [shader_key(ms), ps.map_or(0, shader_key)]; + let key = shader_set_key(std::iter::once(ms).chain(ps)); + super::gfx_records::encode_mesh(key, shaders, &layout, &desc) +} + +/// Build both recorded mesh passes on the adopted device from `prepare_device`. +/// +/// # Safety +/// `device` must be the live adopted device returned from `prepare_device`. +pub(crate) unsafe fn replay_mesh_record( + device: usize, + record: &super::gfx_records::MeshRecord, + shaders: [Option<&[u8]>; 2], +) -> Result<(), String> { + let [Some(ms), ps] = shaders else { return Err("mesh shader missing from the job".into()) }; + if record.shaders != [shader_key(ms), ps.map_or(0, shader_key)] || + record.key != shader_set_key(std::iter::once(ms).chain(ps)) + { + return Err("mesh shaders do not match the recorded keys".into()); + } + + let d = record.state(); + let mut stream = StreamOut::default(); + for &ty in &record.layout { + let subobject = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(ty as i32); + match ty { + 0 => stream.put(subobject, &std::ptr::null::()), + 2 => stream.shader(subobject, ps.ok_or("pixel shader missing from the job")?), + 24 | 25 => stream.shader(subobject, ms), + 8 => stream.put(subobject, &d.BlendState), + 9 => stream.put(subobject, &d.SampleMask), + 10 => stream.put(subobject, &d.RasterizerState), + 11 => stream.put(subobject, &d.DepthStencilState), + 13 => stream.put(subobject, &d.IBStripCutValue), + 14 => stream.put(subobject, &d.PrimitiveTopologyType), + 15 => stream.put(subobject, &D3D12_RT_FORMAT_ARRAY { RTFormats: d.RTVFormats, NumRenderTargets: d.NumRenderTargets }), + 16 => stream.put(subobject, &d.DSVFormat), + 17 => stream.put(subobject, &d.SampleDesc), + 18 => stream.put(subobject, &d.NodeMask), + 20 => stream.put(subobject, &d.Flags), + _ => return Err(format!("unsupported mesh subobject {ty}")), + } + } + let desc = [stream.0.len(), stream.0.as_ptr() as usize]; + let mut out = std::ptr::null_mut(); + let hr = unsafe { + translated_mesh_stream(device as *mut c_void, desc.as_ptr().cast(), &pc_iid(Kind::PipelineState), &mut out) + }; + super::pso_async::release(out as usize); + match hr { + Some(hr) if hr >= 0 && !out.is_null() => Ok(()), + Some(hr) => Err(format!("mesh pipeline replay failed ({hr:#x})")), + None => Err("mesh pipeline record could not be translated".into()), + } +} + /// The passthrough mesh shader emits triangles for both translated MS and GS pipelines. fn two_pass_mesh_stream(rs: *mut c_void, ms: &[u8], ps: Option<&[u8]>) -> StreamOut { let mut out = StreamOut::default(); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 67fb3e0dcb..ba27edaca3 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -12,6 +12,7 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use crate::gpu::{dxbc, pack, rdna2, recomp, shader, xbox}; +use crate::hle::d3d12x::gfx_records; /// `--iface`: how console programs connect to their DXBC signatures (hypothesis checks for /// the VS/PS interface of the recompiler). @@ -1906,15 +1907,19 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut /// part (`gfx_records`' format, with the shaders it needs). A failure is noted and the title /// starts all the same: it builds what is missing itself. fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: &LaunchPreparation) -> Result<(), String> { - use crate::hle::d3d12x::gfx_records::{self, Entry}; let t0 = std::time::Instant::now(); let payloads = gfx_records::read(&gfx_records::path()); - let records: Vec<(Vec, gfx_records::Record)> = payloads.into_iter().filter_map(|p| match gfx_records::decode(&p) { Some(Entry::Pipeline(r)) => Some((p, r)), _ => None }).collect(); + let records: Vec<_> = payloads.into_iter().filter_map(|payload| { + let record = GraphicsHistoryRecord::from_entry(gfx_records::decode(&payload)?)?; + Some((payload, record)) + }).collect(); if records.is_empty() { crate::xlog_info!("Shader preparation: no graphics pipelines of an earlier run to build"); return Ok(()); } - let shaders = shaders_by_key(inputs, records.iter().flat_map(|(_, r)| r.shaders).filter(|&k| k != 0).collect(), progress); + let wanted = records.iter().flat_map(|(_, record)| record.identity().1.iter().copied()) + .filter(|&key| key != 0).collect(); + let shaders = shaders_by_key(inputs, wanted, progress); if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } let (buildable, missing) = buildable(records.iter().map(|(_, r)| r), &shaders); if missing != 0 { @@ -1932,7 +1937,7 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: let mut keys = HashSet::new(); for &k in &part { w.add(&records[k].0).map_err(|e| format!("{}: {e}", path.display()))?; - keys.extend(records[k].1.shaders.into_iter().filter(|&s| s != 0)); + keys.extend(records[k].1.identity().1.iter().copied().filter(|&key| key != 0)); } for key in keys { w.add(&gfx_records::shader_entry(key, &shaders[&key])).map_err(|e| format!("{}: {e}", path.display()))?; @@ -1982,14 +1987,37 @@ fn shaders_by_key(inputs: &[Input], wanted: HashSet, progress: &LaunchPrepa found.into_inner().unwrap() } +enum GraphicsHistoryRecord { + Legacy(gfx_records::Record), + Mesh(gfx_records::MeshRecord), +} + +impl GraphicsHistoryRecord { + fn from_entry(entry: gfx_records::Entry) -> Option { + match entry { + gfx_records::Entry::Pipeline(record) => Some(Self::Legacy(record)), + gfx_records::Entry::MeshPipeline(record) => Some(Self::Mesh(record)), + gfx_records::Entry::Shader(..) => None, + } + } + + fn identity(&self) -> (u64, &[u64]) { + match self { + Self::Legacy(record) => (record.key, &record.shaders), + Self::Mesh(record) => (record.key, &record.shaders), + } + } +} + /// The records (by their index) whose shaders are all in `shaders` and make their set's key, and /// how many are not. -fn buildable<'a>(records: impl Iterator, shaders: &std::collections::HashMap>) -> (Vec, usize) { +fn buildable<'a>(records: impl Iterator, shaders: &HashMap>) -> (Vec, usize) { let (mut ok, mut missing) = (Vec::new(), 0); - for (i, r) in records.enumerate() { - let blobs: Option>> = r.shaders.iter().filter(|&&k| k != 0).map(|k| shaders.get(k).cloned()).collect(); + for (i, record) in records.enumerate() { + let (key, keys) = record.identity(); + let blobs: Option> = keys.iter().filter(|&&k| k != 0).map(|k| shaders.get(k).map(Vec::as_slice)).collect(); match blobs { - Some(b) if crate::hle::d3d12x::real::shaders_key(&b) == r.key => ok.push(i), + Some(blobs) if crate::hle::d3d12x::real::shader_set_key(blobs.iter().copied()) == key => ok.push(i), _ => missing += 1, } } @@ -2006,11 +2034,11 @@ fn graphics_summary(line: &str) -> Option<[usize; 4]> { } /// `xcl shaders --graphics-records` (a worker of `graphics_in_workers`): the graphics -/// pipelines of a job file built as the title builds them (`real::prepare_graphics`), with the +/// pipelines of a job file built as the title builds them, with the /// title's memory windows (`windows`) and on its adapter (`XCL_ADAPTER`), `XCL_PIPELINE_THREADS` /// at a time. A progress line a pipeline, then the summary `graphics_summary` reads. fn graphics_worker(job: &Path, windows: u32) -> i32 { - use crate::hle::d3d12x::gfx_records::{self, Entry}; + use crate::hle::d3d12x::real; end_with_parent(); // (no title memory here: its windows are given) crate::gpu::uma::leave_out(); @@ -2020,13 +2048,13 @@ fn graphics_worker(job: &Path, windows: u32) -> i32 { let mut records = Vec::new(); for p in gfx_records::read(job) { match gfx_records::decode(&p) { - Some(Entry::Pipeline(r)) => records.push(r), - Some(Entry::Shader(k, b)) => { shaders.insert(k, b); } + Some(gfx_records::Entry::Shader(key, code)) => { shaders.insert(key, code); } + Some(entry) => records.extend(GraphicsHistoryRecord::from_entry(entry)), None => {} } } let device = match Pipelines::for_adapter("auto") { - Ok(p) => crate::hle::d3d12x::real::prepare_device(p.dev), + Ok(p) => real::prepare_device(p.dev), Err(e) => { eprintln!("xcl shaders: no pipeline device: {e}"); return 2; } }; let n = records.len(); @@ -2038,17 +2066,24 @@ fn graphics_worker(job: &Path, windows: u32) -> i32 { s.spawn(|| loop { let i = next.fetch_add(1, Ordering::Relaxed); let Some(r) = records.get(i) else { break }; - let code = r.shaders.map(|k| shaders.get(&k).map(Vec::as_slice)); - let desc = r.desc(code); + let code = |key| shaders.get(&key).map(Vec::as_slice); // (a pipeline that panics fails; the others are built) - let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { crate::hle::d3d12x::real::prepare_graphics(device, &desc) })).unwrap_or(false); + let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match r { + GraphicsHistoryRecord::Legacy(record) => { + let desc = record.desc(record.shaders.map(code)); + unsafe { real::prepare_graphics(device, &desc) } + } + GraphicsHistoryRecord::Mesh(record) => { + unsafe { real::replay_mesh_record(device, record, record.shaders.map(code)).is_ok() } + } + })).unwrap_or(false); if ok { made.fetch_add(1, Ordering::Relaxed); } else { failed.fetch_add(1, Ordering::Relaxed); } let d = done.fetch_add(1, Ordering::Relaxed) + 1; eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); }); } }); - let (hits, _, stored) = crate::hle::d3d12x::real::driver_cache_stats(); + let (hits, _, stored) = real::driver_cache_stats(); eprintln!("graphics pipelines: {} made, {} failed; driver blobs: {hits} from disk, {stored} kept", made.into_inner(), failed.into_inner()); 0 } @@ -2646,25 +2681,33 @@ mod tests { /// other shaders under its keys, is left out. #[test] fn a_graphics_record_is_built_only_with_its_own_shaders() { - use crate::hle::d3d12x::gfx_records::{decode, encode, Entry}; + use crate::hle::d3d12x::gfx_records::{decode, encode, encode_mesh}; use crate::hle::d3d12x::real::{shader_key, shaders_key}; - let (vs, ps) = (b"vertex".to_vec(), b"pixel".to_vec()); - let record = |key: u64, shaders: [u64; 5]| { - let d = windows::Win32::Graphics::Direct3D12::D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); - match decode(&unsafe { encode(key, shaders, &d) }) { - Some(Entry::Pipeline(r)) => r, - _ => unreachable!(), - } + use windows::Win32::Graphics::Direct3D12::{ + D3D12_GRAPHICS_PIPELINE_STATE_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, + }; + let (vs, ps, ms) = (b"vertex".to_vec(), b"pixel".to_vec(), b"mesh".to_vec()); + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + let record = |key, shaders| { + GraphicsHistoryRecord::from_entry(decode(&unsafe { encode(key, shaders, &desc) }).unwrap()).unwrap() }; let both = [shader_key(&vs), shader_key(&ps), 0, 0, 0]; + let mesh = |key, shaders| { + let layout = [D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32]; + let payload = encode_mesh(key, shaders, &layout, &desc).unwrap(); + GraphicsHistoryRecord::from_entry(decode(&payload).unwrap()).unwrap() + }; let records = [ record(shaders_key(&[vs.clone(), ps.clone()]), both), record(shaders_key(&[vs.clone()]), [shader_key(&vs), 0, 0, 0, 0]), record(shaders_key(&[vs.clone(), b"other".to_vec()]), [shader_key(&vs), shader_key(b"other"), 0, 0, 0]), record(shaders_key(&[ps.clone(), vs.clone()]), both), + mesh(shaders_key(&[ms.clone(), ps.clone()]), [shader_key(&ms), shader_key(&ps)]), + mesh(shaders_key(&[ps.clone(), ms.clone()]), [shader_key(&ms), shader_key(&ps)]), ]; - let shaders = std::collections::HashMap::from([(shader_key(&vs), vs.clone()), (shader_key(&ps), ps.clone())]); - assert_eq!(buildable(records.iter(), &shaders), (vec![0, 1], 2)); + let shaders = HashMap::from([(shader_key(&vs), vs), (shader_key(&ps), ps), (shader_key(&ms), ms)]); + assert_eq!(buildable(records.iter(), &shaders), (vec![0, 1, 4], 3)); } /// `--used-only` keeps a compute program exactly when the runtime noted its pipeline: the From a6fd2c08edee6d16e40fd0da65f40bc2f22a2e9d Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:59:11 -0500 Subject: [PATCH 2/6] Shaders: discover and stage pipeline recipes from offline archives Resolve shader and fixed-state selectors using a local layout profile. Publish a deduplicated native preparation job only after its recipes and shader references have been validated. --- scripts/pso_corpus/archive-profile.md | 21 ++ scripts/pso_corpus/pso_archive.py | 181 +++++++++++++++ scripts/pso_corpus/pso_directory.py | 50 +++++ scripts/pso_corpus/stage.py | 267 +++++++++++++++++++++++ scripts/pso_corpus/test_pso_archive.py | 144 ++++++++++++ scripts/pso_corpus/test_pso_directory.py | 36 +++ scripts/pso_corpus/test_stage.py | 102 +++++++++ 7 files changed, 801 insertions(+) create mode 100644 scripts/pso_corpus/archive-profile.md create mode 100644 scripts/pso_corpus/pso_archive.py create mode 100644 scripts/pso_corpus/pso_directory.py create mode 100644 scripts/pso_corpus/stage.py create mode 100644 scripts/pso_corpus/test_pso_archive.py create mode 100644 scripts/pso_corpus/test_pso_directory.py create mode 100644 scripts/pso_corpus/test_stage.py diff --git a/scripts/pso_corpus/archive-profile.md b/scripts/pso_corpus/archive-profile.md new file mode 100644 index 0000000000..921bc483f0 --- /dev/null +++ b/scripts/pso_corpus/archive-profile.md @@ -0,0 +1,21 @@ +# Preparing a pipeline journal from an archive + +Run `python pso_archive.py profile.json archive.bin pipelines.bin` with Python 3.10 or newer. Use `--records tables.bin` when a locally extracted archive member contains the tables and the shader data remains in the original archive. The command reports the number of distinct sources and recipes. It replaces the destination after every record resolves and the journal has been written. + +A profile describes the local archive layout and how its selectors map to XCL wire records. The profile author must establish these mappings for the archive revision. Include optional `archive_sha256` to check the source archive. When the tables occupy compressed blocks, list their archive ranges in order under optional `record_chunks`, using the same range format as `sources`. Table offsets then address the concatenated decoded blocks. An absent selector raises an error. Use an explicitly empty variant list for an intentionally excluded record type. + +| Version 1 field | Meaning | +|---|---| +| `sources` | Named shader byte ranges with `offset` and `size`. For `encoding` equal to `deflate` (raw) or `zlib`, supply the exact compressed stream length and `raw_size`. | +| `stage_maps` | Named dictionaries mapping a decimal selector string to a named source, or `null` for an absent optional shader stage. | +| `states` | Named dictionaries mapping decimal selector strings to hex-encoded state fragments in XCL wire order. | +| `tables` | A list of fixed-stride tables with `offset`, `count`, `stride`, and named `fields` given as `[byte_offset, width]` within a record. Integers use 1, 2, 4 or 8 little-endian bytes. | +| `variants` | A table's list of wire templates. Optionally use `variant_field` to select between lists keyed by decimal field value. Each variant supplies `kind` (C, G or M), the XCL journal `windows` byte, and an ordered `parts` list. | + +A part is one of `{"hex":"..."}` for a literal, `{"field":["field name","state dictionary"]}` for a selected fragment, or `{"stage":["field name","stage dictionary"]}` for a shader identity computed from the selected local source. Templates must follow XCL's journal wire format, including any required zeroed fields and attachment layouts. The synthetic compute profile in `test_pso_archive.py` shows these parts in descriptor order. + +The generated XCLPJ001 journal carries each required shader source once, followed by unique recipes. The tool enumerates the record tables and variants in the supplied profile. Coverage of gameplay paths depends on what that profile models. + +If the archive contains its own dictionaries, define optional `shader_directories` and `state_directories` instead of listing entries by hand. Both take named directories with `offset`, `count`, `stride`, and an optional integer `id` field (defaults to the row ordinal). Offsets refer to the record file or decoded record chunks. A shader directory requires integer fields `location` and `size`, with optional `data_base`, `encoding` and integer `raw_size` field. Shader locations resolve against the original archive. A state directory requires `fragment: [offset, byte_length]` within the row. The named directory becomes a stage or state dictionary for the existing template operations. Conflicting entries raise an error. + +Run `python -m unittest -v test_pso_archive test_pso_directory` in the script directory. diff --git a/scripts/pso_corpus/pso_archive.py b/scripts/pso_corpus/pso_archive.py new file mode 100644 index 0000000000..23c4b0a785 --- /dev/null +++ b/scripts/pso_corpus/pso_archive.py @@ -0,0 +1,181 @@ +"""Expand archive selector tables into a self-contained XCL pipeline journal.""" + +import argparse +from contextlib import contextmanager +import hashlib +import json +import os +from pathlib import Path +import shutil +import struct +import tempfile +import zlib + +from pso_directory import read_directories + +FRAME = struct.Struct(" len(record): + raise ValueError(f"invalid little-endian selector field {spec}") + return str(int.from_bytes(record[offset:offset + size], "little")) + + +def expand(profile, archive, records, shader_frames, recipe_frames): + if profile["version"] != 1: + raise ValueError("unknown profile version") + read_directories(profile, records) + sources = {} + for table in profile["tables"]: + stride = table["stride"] + if not 0 < stride <= LIMIT or table["count"] < 0 or table["offset"] < 0: + raise ValueError("invalid record table") + for index in range(table["count"]): + record = read_at(records, table["offset"] + stride * index, stride) + ids = {name: field(record, spec) for name, spec in table["fields"].items()} + variants = table["variants"] + if "variant_field" in table: + variants = variants[ids[table["variant_field"]]] + for variant in variants: + pieces = [] + stage_ids = [] + for part in variant["parts"]: + if len(part) != 1: + raise ValueError("wire fragment requires exactly one operation") + op, arg = next(iter(part.items())) + if op == "hex": + value = bytes.fromhex(arg) + elif op == "field": + name, state_map = arg + value = bytes.fromhex(profile["states"][state_map][ids[name]]) + elif op == "stage": + name, stage_map = arg + source = profile["stage_maps"][stage_map][ids[name]] + if source is None: + value = bytes(8) + else: + entry = profile["sources"][source] + region = (entry["offset"], entry["size"], entry.get("encoding", "raw"), entry.get("raw_size")) + if region not in sources: + blob = source_bytes(archive, entry) + key = f"{fnv64(blob):016x}" + shader_frames.add(key, "S", 0, blob) + sources[region] = key + key = sources[region] + value = struct.pack(" len(record): + raise ValueError("invalid directory integer field") + return int.from_bytes(record[offset:offset + width], "little") + + +def directory_entries(stream, directory): + offset, count, stride = (directory[k] for k in ("offset", "count", "stride")) + if offset < 0 or count < 0 or not 0 < stride <= 64 << 20: + raise ValueError("invalid directory range") + stream.seek(offset) + for row in range(count): + record = stream.read(stride) + if len(record) != stride: + raise ValueError(f"truncated directory at row {row}") + key = integer(record, directory["id"]) if "id" in directory else row + yield str(key), record + + +def add_entry(mapping, key, value): + if key in mapping and mapping[key] != value: + raise ValueError(f"ambiguous directory entry {key}") + mapping[key] = value + + +def read_directories(profile, records): + """Populate the maps for the ordinary profile expander from the record file.""" + for name, directory in profile.get("shader_directories", {}).items(): + stages = profile.setdefault("stage_maps", {}).setdefault(name, {}) + sources = profile.setdefault("sources", {}) + for key, record in directory_entries(records, directory): + offset = directory.get("data_base", 0) + integer(record, directory["location"]) + size = integer(record, directory["size"]) + source = f"{name}:{key}" + entry = {"offset": offset, "size": size, "encoding": directory.get("encoding", "raw")} + if "raw_size" in directory: + entry["raw_size"] = integer(record, directory["raw_size"]) + add_entry(sources, source, entry) + add_entry(stages, key, source) + for name, directory in profile.get("state_directories", {}).items(): + states = profile.setdefault("states", {}).setdefault(name, {}) + start, size = directory["fragment"] + if start < 0 or size <= 0 or start + size > directory["stride"]: + raise ValueError("invalid directory state fragment") + for key, record in directory_entries(records, directory): + add_entry(states, key, record[start:start + size].hex()) diff --git a/scripts/pso_corpus/stage.py b/scripts/pso_corpus/stage.py new file mode 100644 index 0000000000..2622477eaa --- /dev/null +++ b/scripts/pso_corpus/stage.py @@ -0,0 +1,267 @@ +"""Stage local XCLPJ001 journals for offline pipeline preparation. + +python scripts/pso_corpus/stage.py --title FOLDER JOURNAL [JOURNAL ...] +Use the same window configuration for all journals. The resulting .xcl/pso-corpus +contains local shader bytes. An existing different corpus is preserved. Compute +node masks 0 and 1 select the first node on the supported single-node adapter. +""" +import argparse +from collections import Counter +import hashlib +import json +from pathlib import Path +import shutil +import struct +import tempfile + +OFFSET, PRIME, MASK = 0xcbf29ce484222325, 0x100000001b3, (1 << 64) - 1 +HEADER = struct.Struct("= 128: + result.append(128 | (value & 127)) + value >>= 7 + result.append(value) + return result + + +class Reader: + def __init__(self, data): + self.data = memoryview(data) + self.pos = 0 + + def take(self, size): + end = self.pos + size + require(end <= len(self.data), "short descriptor") + part = self.data[self.pos:end] + self.pos = end + return part + + def ints(self, fmt): + return struct.unpack(fmt, self.take(struct.calcsize(fmt))) + + def u32(self): + return self.ints(" Date: Thu, 26 Nov 2026 10:59:47 -0500 Subject: [PATCH 3/6] Shaders: prepare known native pipelines before releasing the game window Share native replay between an offline CLI and the launch gate. Count successful recipes, propagate driver failures and cancellation, and scope recorded history to each title. Draw progress in the presentation window while workers prepare graphics, mesh and compute pipelines. --- README.md | 33 ++- crates/xcl/src/hle/d3d12x/gfx_records.rs | 129 +++++++- .../xcl/src/hle/d3d12x/present/preparation.rs | 105 +++++-- crates/xcl/src/hle/d3d12x/real.rs | 116 +++++++- crates/xcl/src/main.rs | 1 + crates/xcl/src/shaders.rs | 278 ++++++++++++++---- crates/xcl/src/shaders/pso_corpus.rs | 186 ++++++++++++ crates/xcl/tests/e2e.rs | 20 ++ 8 files changed, 745 insertions(+), 123 deletions(-) create mode 100644 crates/xcl/src/shaders/pso_corpus.rs diff --git a/README.md b/README.md index fafec20621..93544ac4d3 100644 --- a/README.md +++ b/README.md @@ -240,19 +240,26 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper.
Switches, caches, logs and the files XCL writes -- When a game folder contains a `shaders.rpf` shader pack or loose `.dxbc` files under - `shaders/`, XCL shows shader preparation in the game window before executing title code. - The same window then presents the game. The percentage counts - processed records. The timer counts seconds since one finished (or preparation started); - five seconds without progress counts as a stall, and the window shows when the last one ended. - XCL prepares supported shader stages and compute pipelines, including - split pieces and their whole fallback. Graphics pipelines are created during play the first - time. The startup history records supported graphics descriptors and two-pass mesh streams with - their state (`used-graphics-pipelines.bin` beside the shader cache, capped by `XCL_GFX_RECORDS_MB` - at 64 MB by default). On the next launch, XCL builds the recorded pipelines before the title starts - and keeps their driver blobs for reuse. `XCL_PREPARE_GRAPHICS=0` leaves that pass out. - Closing the window cancels the launch. A compiler or driver failure stops it and reports - the cause. Null-renderer runs skip shader preparation. With presentation disabled, the gate runs without a window. +- XCL uses the game window to show preparation progress before executing title code. It prepares + supported shader packs, supported loose shaders under `shaders/`, recorded graphics history and + staged pipeline recipes. Closing the window cancels launch. A failed staged recipe stops launch. + With presentation disabled, preparation runs without a window. A staged corpus still gates + launch when the null renderer is selected. +- To prepare known graphics, two-pass mesh and compute recipes offline, use a local + [archive layout profile](scripts/pso_corpus/archive-profile.md) with the following commands. + The staging command accepts several journals and deduplicates their recipes. + + ```powershell + python scripts/pso_corpus/pso_archive.py profile.json archive.bin pipelines.bin + python scripts/pso_corpus/stage.py --title pipelines.bin + xcl shaders --prepare-corpus --threads 8 + ``` + + The offline command accepts up to 32 workers. Normal launch also prepares the staged corpus. + Use the same adapter and memory-window + configuration for offline preparation and play so the driver can reuse the results. + Graphics state combinations absent from the supplied recipes and local history can still + require a first-use compile during play. - For compute shaders that XCL can split, the runtime first tries the saved driver blob for the whole shader. A usable blob lets the GPU run it in one dispatch. If the blob is missing or the driver rejects it, XCL builds the split pieces. diff --git a/crates/xcl/src/hle/d3d12x/gfx_records.rs b/crates/xcl/src/hle/d3d12x/gfx_records.rs index 552e0ecb46..74b01fbb24 100644 --- a/crates/xcl/src/hle/d3d12x/gfx_records.rs +++ b/crates/xcl/src/hle/d3d12x/gfx_records.rs @@ -12,6 +12,7 @@ //! payload = 1 key u64 shaders [u64; 5] state input* a pipeline //! | 2 key u64 bytes a shader (preparation job files only) //! | 3 key u64 shaders [u64; 2] layout state a mesh pipeline stream +//! | 4 key u64 shaders [u64; 5] state input* a pipeline with depth bounds enabled //! key = `real::shaders_key` of the set, in mesh then PS order for mesh; in a shader entry, //! `real::shader_key` of it //! shaders = `real::shader_key` of VS, PS, DS, HS, GS, or mesh, PS (0: none) @@ -42,10 +43,16 @@ const HEADER: usize = 12; const PIPELINE: u8 = 1; const SHADER: u8 = 2; const MESH_PIPELINE: u8 = 3; -const MAX_MESH_LAYOUT: usize = 14; // root, mesh (MS or AS), PS, and eleven scalar state types +const DEPTH_BOUNDS_PIPELINE: u8 = 4; +const MAX_MESH_LAYOUT: usize = 19; // includes four inactive shader slots and an empty input layout -/// The records of this cache (beside the DXIL cache, as `used-pipelines.txt`). +/// New records belong to the active title. A shared translation cache can serve unrelated titles. pub(crate) fn path() -> PathBuf { + if let Some(boot) = crate::state::boot() { return boot.cache_dir().join("used-graphics-pipelines.bin"); } + shared_history_path() +} + +pub(crate) fn shared_history_path() -> PathBuf { crate::gpu::recomp::dxc::cache_dir().join("used-graphics-pipelines.bin") } @@ -223,10 +230,16 @@ fn valid_mesh_layout(shaders: [u64; 2], layout: &[u32]) -> bool { | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1 | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS @@ -244,14 +257,17 @@ fn valid_mesh_layout(shaders: [u64; 2], layout: &[u32]) -> bool { } let has = |kind: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE| seen & (1 << kind.0) != 0; (has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS) != has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS)) - && has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS) == (shaders[1] != 0) + && (shaders[1] == 0 || has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS)) + && !(has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL) && has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1)) } /// A mesh stream entry with shader keys in mesh, PS order and subobjects in their original order. -pub(crate) fn encode_mesh(key: u64, shaders: [u64; 2], layout: &[u32], d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Option> { +pub(crate) fn encode_mesh(key: u64, shaders: [u64; 2], layout: &[u32], d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, depth_bounds: bool) -> Option> { if key == 0 || !valid_mesh_layout(shaders, layout) || d.NumRenderTargets > 8 { return None; } + let depth1 = layout.contains(&(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1.0 as u32)); + if depth_bounds && !depth1 { return None; } let mut values = D3D12_GRAPHICS_PIPELINE_STATE_DESC { BlendState: d.BlendState, SampleMask: d.SampleMask, @@ -276,6 +292,7 @@ pub(crate) fn encode_mesh(key: u64, shaders: [u64; 2], layout: &[u32], d: &D3D12 out.push(layout.len() as u8); out.extend(layout.iter().map(|&id| id as u8)); state(&mut values, &mut |v, _| put_var(&mut out, (*v).into())); + if depth1 { put_var(&mut out, u64::from(depth_bounds)); } Some(out) } @@ -291,6 +308,7 @@ pub(crate) fn shader_entry(key: u64, bytes: &[u8]) -> Vec { /// A pipeline as a title described it, but its shaders and root signature (`desc` puts them in). pub(crate) struct Record { pub key: u64, + pub depth_bounds: bool, /// `real::shader_key` of the VS, PS, DS, HS, GS (0: none) pub shaders: [u64; 5], desc: Box, @@ -322,9 +340,18 @@ pub(crate) struct MeshRecord { pub key: u64, pub shaders: [u64; 2], pub layout: Vec, + pub depth_bounds: bool, desc: Box, } +pub(crate) fn depth_stencil1(d: &D3D12_DEPTH_STENCIL_DESC, bounds: bool) -> D3D12_DEPTH_STENCIL_DESC1 { + D3D12_DEPTH_STENCIL_DESC1 { + DepthEnable: d.DepthEnable, DepthWriteMask: d.DepthWriteMask, DepthFunc: d.DepthFunc, + StencilEnable: d.StencilEnable, StencilReadMask: d.StencilReadMask, StencilWriteMask: d.StencilWriteMask, + FrontFace: d.FrontFace, BackFace: d.BackFace, DepthBoundsTestEnable: bounds.into(), + } +} + // The decoder starts with null pointers and only fills scalar fields. The descriptor is immutable. unsafe impl Send for MeshRecord {} unsafe impl Sync for MeshRecord {} @@ -357,7 +384,8 @@ fn decode_mesh(key: u64, mut r: Reader<'_>) -> Option { Some(x) => *v = x, None => valid = false, }); - (valid && r.0.is_empty()).then_some(MeshRecord { key, shaders, layout, desc }) + let depth_bounds = layout.contains(&(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1.0 as u32)) && r.bounded_var(1)? != 0; + (valid && r.0.is_empty()).then_some(MeshRecord { key, shaders, layout, desc, depth_bounds }) } /// The entry of `payload` (None: not one this version writes). @@ -371,7 +399,7 @@ pub(crate) fn decode(payload: &[u8]) -> Option { if tag == MESH_PIPELINE { return decode_mesh(key, r).map(Entry::MeshPipeline); } - if tag != PIPELINE { + if !matches!(tag, PIPELINE | DEPTH_BOUNDS_PIPELINE) { return None; } let mut shaders = [0u64; 5]; @@ -415,7 +443,7 @@ pub(crate) fn decode(payload: &[u8]) -> Option { InstanceDataStepRate: f[5], }) .collect(); - Some(Entry::Pipeline(Record { key, shaders, desc, inputs, _names: names })) + Some(Entry::Pipeline(Record { key, shaders, depth_bounds: tag == DEPTH_BOUNDS_PIPELINE, desc, inputs, _names: names })) } fn header() -> [u8; HEADER] { @@ -454,6 +482,23 @@ pub(crate) fn read(path: &Path) -> Vec> { payloads(&file).map_or_else(Vec::new, |(list, _)| list.into_iter().map(<[u8]>::to_vec).collect()) } +/// A completed worker job must contain only whole, supported records. A history file +/// may be open for appends, so its reader above accepts a trailing partial entry. +fn read_complete(path: &Path, mut take: impl FnMut(&[u8], Entry) -> T) -> Result, String> { + let file = std::fs::read(path).map_err(|e| e.to_string())?; + let (payloads, end) = payloads(&file).ok_or("unrecognized graphics job header")?; + if end != file.len() { return Err(format!("damaged graphics job at byte {end}")); } + payloads.into_iter().enumerate().map(|(i, p)| decode(p).map(|entry| take(p, entry)).ok_or_else(|| format!("invalid graphics job entry {}", i + 1))).collect() +} + +pub(crate) fn read_complete_payloads(path: &Path) -> Result>, String> { + read_complete(path, |bytes, _| bytes.to_vec()) +} + +pub(crate) fn read_job(path: &Path) -> Result, String> { + read_complete(path, |_, entry| entry) +} + /// What became of an entry handed to `Writer::add`. #[derive(Debug, PartialEq, Eq)] pub(crate) enum Added { @@ -655,6 +700,20 @@ mod tests { } } + #[test] + fn classic_depth_bounds_record_keeps_version_one_state() { + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + let mut bytes = unsafe { encode(7, [9, 0, 0, 0, 0], &desc) }; + assert!(!pipeline(&bytes).depth_bounds); + bytes[0] = DEPTH_BOUNDS_PIPELINE; + let record = pipeline(&bytes); + assert!(record.depth_bounds); + assert_eq!(record.shaders, [9, 0, 0, 0, 0]); + assert_eq!(record.key, 7); + bytes.pop(); + assert!(decode(&bytes).is_none()); + } + /// A description comes back with every field (as the key of its translated pipeline's driver /// blob sees them), its input layout and its shaders' keys. #[test] @@ -712,14 +771,14 @@ mod tests { let mut desc = described(); let ps = b"pixel"; desc.PS = D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr().cast(), BytecodeLength: ps.len() }; - let payload = encode_mesh(0x1234, shaders, &layout, &desc).unwrap(); + let payload = encode_mesh(0x1234, shaders, &layout, &desc, false).unwrap(); let Some(Entry::MeshPipeline(record)) = decode(&payload) else { panic!("expected a mesh entry") }; assert_eq!((record.key, record.shaders), (0x1234, shaders)); assert_eq!(record.layout, layout); assert_eq!(record.state().RasterizerState.DepthBias, desc.RasterizerState.DepthBias); assert_eq!(record.state().RTVFormats, desc.RTVFormats); assert!(record.state().PS.pShaderBytecode.is_null()); - assert_eq!(encode_mesh(record.key, record.shaders, &record.layout, record.state()).unwrap(), payload); + assert_eq!(encode_mesh(record.key, record.shaders, &record.layout, record.state(), record.depth_bounds).unwrap(), payload); } #[test] @@ -729,12 +788,13 @@ mod tests { let ps = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32; let input = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0 as u32; let d = described(); - for layout in [vec![], vec![ms, moved], vec![ms, ms], vec![ms, ps], vec![ms, input]] { - assert!(encode_mesh(1, [1, 0], &layout, &d).is_none(), "unsupported layout {layout:?}"); + let stream_output = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT.0 as u32; + for layout in [vec![], vec![ms, moved], vec![ms, ms], vec![ms, ps, ps], vec![ms, stream_output], vec![ms, 11, 21]] { + assert!(encode_mesh(1, [1, 0], &layout, &d, false).is_none(), "unsupported layout {layout:?}"); } - assert!(encode_mesh(1, [1, 2], &[ms], &d).is_none()); - assert!(encode_mesh(1, [0, 0], &[ms], &d).is_none()); - let payload = encode_mesh(1, [1, 0], &[ms], &d).unwrap(); + assert!(encode_mesh(1, [1, 2], &[ms], &d, false).is_none()); + assert!(encode_mesh(1, [0, 0], &[ms], &d, false).is_none()); + let payload = encode_mesh(1, [1, 0], &[ms], &d, false).unwrap(); assert!(decode(&payload[..payload.len() - 1]).is_none()); assert!(decode(&[payload.as_slice(), &[0]].concat()).is_none()); @@ -750,13 +810,52 @@ mod tests { assert!(decode(&overlong).is_none()); } + #[test] + fn mesh_bounds_and_empty_subobjects_survive_the_worker_job() { + let layout = [0, 25, 2, 3, 4, 5, 8, 9, 10, 21, 17, 12, 14, 15, 16]; + let desc = described(); + for bounds in [false, true] { + let job = encode_mesh(1, [1, 0], &layout, &desc, bounds).unwrap(); + let Some(Entry::MeshPipeline(record)) = decode(&job) else { panic!("mesh record missing") }; + assert_eq!(record.layout, layout); + assert_eq!(record.depth_bounds, bounds); + assert_eq!(record.shaders, [1, 0]); + let state = depth_stencil1(&record.state().DepthStencilState, record.depth_bounds); + assert_eq!(state.BackFace, desc.DepthStencilState.BackFace); + assert_eq!(state.DepthBoundsTestEnable.as_bool(), bounds); + assert!(decode(&job[..job.len() - 1]).is_none()); + let mut bad = job; *bad.last_mut().unwrap() = 2; + assert!(decode(&bad).is_none()); + } + assert!(encode_mesh(1, [1, 0], &[25, 11], &desc, true).is_none()); + } + + #[test] + fn complete_jobs_reject_damaged_or_unknown_entries() { + let dir = directory("complete-job"); + let path = dir.0.join("job.bin"); + assert!(read_job(&path).is_err()); + { + let mut writer = Writer::open(&path, u64::MAX).unwrap(); + writer.add(&shader_entry(5, b"shader")).unwrap(); + } + assert_eq!(read_job(&path).unwrap().len(), 1); + let original = std::fs::read(&path).unwrap(); + std::fs::write(&path, [&original[..], &[1, 2]].concat()).unwrap(); + assert!(read_job(&path).is_err()); + assert_eq!(read(&path).len(), 1); + std::fs::write(&path, original).unwrap(); + Writer::open(&path, u64::MAX).unwrap().add(&[0xff]).unwrap(); + assert!(read_job(&path).is_err()); + } + #[test] fn legacy_pipeline_and_mesh_entries_share_version_one_history() { let dir = directory("mesh-version-one"); let path = dir.0.join("records.bin"); let legacy = unsafe { encode(3, [3, 0, 0, 0, 0], &described()) }; let shader = shader_entry(5, b"mesh"); - let mesh = encode_mesh(5, [5, 0], &[D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32], &described()).unwrap(); + let mesh = encode_mesh(5, [5, 0], &[D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32], &described(), false).unwrap(); let mut writer = Writer::open(&path, 1 << 20).unwrap(); writer.add(&legacy).unwrap(); writer.add(&mesh).unwrap(); diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs index 5d468c52d6..baff972a85 100644 --- a/crates/xcl/src/hle/d3d12x/present/preparation.rs +++ b/crates/xcl/src/hle/d3d12x/present/preparation.rs @@ -25,7 +25,8 @@ struct Screen { impl Screen { fn release(&mut self) -> bool { - self.ready = !self.progress.cancel.load(Ordering::Relaxed); + self.ready = !self.progress.cancel.load(Ordering::Relaxed) && + (!self.progress.corpus.load(Ordering::Acquire) || self.progress.check_corpus_complete().is_ok()); self.ready } } @@ -41,26 +42,21 @@ pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { std::env::remove_var("XCL_PREPARATION_PARENT"); std::env::remove_var("XCL_PREPARATION_MENU"); let root = &boot.game_root; - if boot.config.graphics.eq_ignore_ascii_case("null") || - (!root.join("shaders.rpf").try_exists().map_err(|e| e.to_string())? && !root.join("shaders").is_dir()) { + let corpus = root.join(".xcl/pso-corpus").try_exists().map_err(|e| e.to_string())?; + if !corpus && (boot.config.graphics.eq_ignore_ascii_case("null") || + (!root.join("shaders.rpf").try_exists().map_err(|e| e.to_string())? && !root.join("shaders").is_dir() && + !crate::hle::d3d12x::gfx_records::path().try_exists().map_err(|e| e.to_string())?)) { return Ok(()); } - // `XCL_PREPARE=0`: the title starts at once and builds what it uses as it goes (it stands - // still for those builds): for a look at a change without the wait - if std::env::var("XCL_PREPARE").is_ok_and(|v| v.trim() == "0") { - crate::xlog_info!("Shader preparation left out (XCL_PREPARE=0): the title builds what it uses as it goes"); - return Ok(()); - } - let only = Some(crate::hle::d3d12x::pso_async::earlier_used_shaders()) - .filter(|used| !used.is_empty() && !std::env::var("XCL_PREPARE_ALL").is_ok_and(|v| v.trim() == "1")); - if let Some(used) = &only { - crate::xlog_info!("Shader preparation: only the {} shaders earlier runs used (XCL_PREPARE_ALL=1: every record)", used.len()); - } - let progress = Arc::new(LaunchPreparation { adapter: boot.config.d3d12_adapter.clone(), only, ..Default::default() }); + let progress = Arc::new(LaunchPreparation { adapter: boot.config.d3d12_adapter.clone(), ..Default::default() }); let hwnd = if super::enabled() { *SCREEN.lock().unwrap() = Some(Screen { progress: progress.clone(), start: Instant::now(), clock: StallClock::default(), ready: false }); ACTIVE.store(true, Ordering::Release); - let hwnd = super::ensure_window().ok_or("Could not create the presentation window for shader preparation")?; + let Some(hwnd) = super::ensure_window() else { + ACTIVE.store(false, Ordering::Release); + *SCREEN.lock().unwrap() = None; + return Err("Could not create the presentation window for pipeline preparation".into()); + }; crate::xlog_info!("Shader preparation window {:#x}", hwnd.0 as usize); Some(hwnd) } else { None }; @@ -73,12 +69,13 @@ pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { said = Instant::now(); let workers = progress.workers.load(Ordering::Relaxed); let graphics = progress.graphics.load(Ordering::Relaxed); + let corpus = progress.corpus.load(Ordering::Acquire); crate::xlog_info!( "Shader preparation: {} of {} {} {} after {} s", progress.done.load(Ordering::Relaxed), progress.total.load(Ordering::Relaxed), - if graphics { "graphics pipelines" } else { "records" }, - if graphics { format!("built by {workers} workers") } else if workers != 0 { format!("checked for pipelines by {workers} workers") } else { "translated".to_string() }, + if corpus { "pipeline recipes" } else if graphics { "graphics pipelines" } else { "records" }, + if corpus { "confirmed by the graphics driver".into() } else if graphics { format!("processed by {workers} workers") } else if workers != 0 { format!("checked for pipelines by {workers} workers") } else { "processed".into() }, began.elapsed().as_secs() ); } @@ -155,6 +152,38 @@ unsafe fn text(dc: HDC, rect: RECT, value: &str, size: i32, weight: i32, color: DeleteObject(font); } +/// A projected wireframe whose illuminated columns follow confirmed progress. +unsafe fn draw_surface(dc: HDC, rect: RECT, pct: usize) { + use windows_sys::Win32::Foundation::POINT; + const COLS: i32 = 24; + const ROWS: i32 = 8; + let vertex = |col: i32, row: i32| { + let u = col as f64 / COLS as f64; + let v = row as f64 / ROWS as f64; + let hill = |x: f64, z: f64, height: f64| height * (-20.0*(u-x).powi(2) - 6.0*(v-z).powi(2)).exp(); + let elevation = hill(0.35, 0.41, 0.53) + hill(0.68, 0.55, 0.34); + POINT { x: rect.left + ((rect.right-rect.left) as f64*(0.80*u + 0.19*(1.0-v))) as i32, + y: rect.top + ((rect.bottom-rect.top) as f64*(0.42 + 0.55*v - elevation)) as i32 } + }; + let shadow = CreatePen(PS_SOLID, 1, 0x4d4734); + let lit = CreatePen(PS_SOLID, 1, 0x97cc86); + let base = CreateSolidBrush(0x28251b); + let old_pen = SelectObject(dc, shadow); + let old_brush = SelectObject(dc, base); + for row in 0..ROWS { + for col in 0..COLS { + let points = [vertex(col,row),vertex(col+1,row),vertex(col+1,row+1),vertex(col,row+1)]; + SelectObject(dc, if 100*(col+1) as usize <= COLS as usize*pct { lit } else { shadow }); + Polygon(dc, points.as_ptr(), points.len() as i32); + MoveToEx(dc, points[0].x, points[0].y, std::ptr::null_mut()); + LineTo(dc, points[2].x, points[2].y); + } + } + SelectObject(dc, old_brush); + SelectObject(dc, old_pen); + DeleteObject(base); DeleteObject(shadow); DeleteObject(lit); +} + unsafe fn paint(hwnd: HWND, s: &mut Screen) { let mut ps: PAINTSTRUCT = std::mem::zeroed(); let dest = BeginPaint(hwnd.0, &mut ps); @@ -169,28 +198,37 @@ unsafe fn paint(hwnd: HWND, s: &mut Screen) { let scale = |px: i32| (px * GetDeviceCaps(dc, LOGPIXELSY as i32).max(96)) / 96; let width = scale(560).min((rc.right - scale(40)).max(1)); let x = (rc.right - width) / 2; - let y = ((rc.bottom - scale(150)) / 2).max(0); + let art = if rc.bottom >= scale(300) && width >= scale(300) { scale(132) } else { 0 }; + let top = ((rc.bottom - scale(150) - art) / 2).max(0); + let y = top + art; let row = |top, bottom| RECT { left: x, right: x+width, top: y+scale(top), bottom: y+scale(bottom) }; let done = s.progress.done.load(Ordering::Relaxed); let total = s.progress.total.load(Ordering::Relaxed); let pct = percent(done, total, s.ready); + if art != 0 { + draw_surface(dc, RECT { left: x, right: x+width, top, bottom: y-scale(14) }, pct); + } let (quiet, last) = s.clock.sample(done, s.start.elapsed()); let workers = s.progress.workers.load(Ordering::Relaxed); let graphics = workers != 0 && s.progress.graphics.load(Ordering::Relaxed); - let heading = if s.progress.cancel.load(Ordering::Relaxed) { "Cancelling preparation" } else if graphics { "Building graphics pipelines" } else if workers != 0 { "Building pipelines" } else { "Preparing shaders" }; + let corpus = s.progress.corpus.load(Ordering::Acquire); + let heading = if s.progress.cancel.load(Ordering::Relaxed) { "Cancelling preparation" } else if s.ready { "Ready to launch" } + else if corpus { "Preparing pipeline cache" } else if graphics { "Building graphics pipelines" } else if workers != 0 { "Building pipelines" } else { "Preparing shaders" }; let mut title = row(0,48); title.right -= scale(84); text(dc, title, heading, scale(31), 600, 0xf7f5f1, DT_LEFT); text(dc, row(0,48), &format!("{pct}%"), scale(27), 600, 0xdfd09a, DT_RIGHT); - let bar = row(65,72); + let bar = row(62,72); fill(dc, bar, 0x4b4038); fill(dc, RECT {right: x+(width as i64 * pct as i64/100) as i32, ..bar}, 0xbdb458); - let count = if total == 0 { "Reading shader records…".into() } - else if graphics { format!("{done} of {total} graphics pipelines built by {workers} worker processes") } + let count = if corpus { format!("{done} of {total} pipeline recipes confirmed by the driver") } + else if total == 0 { "Reading shader records…".into() } + else if graphics { format!("{done} of {total} graphics pipelines processed by {workers} worker processes") } else if workers != 0 { format!("{done} of {total} records checked by {workers} worker processes") } else { format!("{done} of {total} records processed") }; text(dc, row(87,112), &count, scale(17), 400, 0xe1dcd7, DT_LEFT); - let mut times = if workers != 0 { format!("Large pipelines compile in the driver: {quiet} s since the last record") } else { format!("No shader progress for {quiet} s") }; + let elapsed = s.start.elapsed().as_secs(); + let mut times = format!("Elapsed {}:{:02} · {quiet} s since last progress", elapsed / 60, elapsed % 60); if let Some(ago) = last { times.push_str(&format!(" · Last stall ended {ago} s ago")); } text(dc, row(117,145), ×, scale(14), 400, 0xb4aaa4, DT_LEFT); BitBlt(dest, 0, 0, rc.right, rc.bottom, dc, 0, 0, SRCCOPY); @@ -251,6 +289,25 @@ mod tests { assert!(!screen.ready); } + #[test] + fn corpus_handoff_requires_every_native_completion() { + let progress = Arc::new(LaunchPreparation::default()); + let mut screen = Screen { progress: progress.clone(), start: Instant::now(), clock: StallClock::default(), ready: false }; + assert!(progress.check_corpus_complete().is_err()); + progress.begin_corpus(0); + assert!(!screen.release()); + progress.begin_corpus(3); + progress.complete_corpus(2).unwrap(); + progress.complete_corpus(1).unwrap(); + assert_eq!(progress.done.load(Ordering::Acquire), 2); + assert!(progress.complete_corpus(4).is_err()); + assert!(!screen.release()); + progress.complete_corpus(3).unwrap(); + assert!(screen.release()); + progress.cancel.store(true, Ordering::Release); + assert!(!screen.release()); + } + #[test] fn only_a_successful_join_releases_the_last_percent() { assert_eq!(percent(0, 0, false), 0); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 7614c96b80..c0adc0145f 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5734,6 +5734,23 @@ pub(super) unsafe fn graphics_blob_key( mod graphics_blob_tests { use super::*; + #[test] + fn classic_depth_bounds_record_preserves_native_state_and_cache_identity() { + let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + d.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_GREATER; + d.DepthStencilState.StencilReadMask = 0x5a; + let stream = depth_bounds_stream(&d); + let fields = stream_subobjects(&stream.0).unwrap(); + let (_, bytes) = fields.iter().find(|(ty, _)| *ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1.0 as u32).unwrap(); + let state = unsafe { std::ptr::read_unaligned(bytes.as_ptr().cast::()) }; + assert!(state.DepthBoundsTestEnable.as_bool()); + assert_eq!(state.DepthFunc, d.DepthStencilState.DepthFunc); + assert_eq!(state.StencilReadMask, 0x5a); + let key = (123, 456); + assert_eq!(depth_bounds_key(key, false), key); + assert_ne!(depth_bounds_key(key, true), key); + } + #[test] fn graphics_blob_key_tracks_shaders_samplers_and_state() { unsafe { @@ -6166,10 +6183,10 @@ unsafe fn graphics_pso_through_cache( } 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)) + with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv, false)) } -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 { +unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, depth_bounds: bool) -> 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; @@ -6247,7 +6264,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const copy.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; } let bytes = vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len) + rect_gs.as_ref().map_or(0, Vec::len); - let gkey = graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers); + let gkey = depth_bounds_key(graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers), depth_bounds); // (no file without the adapter's identity: it could be another adapter's) let driver = driver_identity(this); let disk = driver.and_then(|id| driver_cache::graphics_path(driver_cache::graphics_file_hash(gkey, id, crate::gpu::recomp::pso::mem_windows()), bytes)); @@ -6262,7 +6279,12 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const &mut copy, rect_gs.is_some(), ps_hash, - |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv), + |c| if depth_bounds { + let stream = depth_bounds_stream(c); + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: stream.0.len(), pPipelineStateSubobjectStream: stream.0.as_ptr() as _ }; + let create: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); + finish_pso(this, create, &desc as *const _ as _, riid, ppv) + } else { finish_pso(this, f, c as *const _ as *const c_void, riid, ppv) }, || keep_graphics_blob(gkey, *ppv, bytes), ); GRAPHICS_STAGES.with(|s| s.set(None)); @@ -6748,11 +6770,12 @@ pub(crate) fn prepare_device(device: ID3D12Device) -> usize { /// (`prepare_device`) as the title's background build makes it (`build_graphics`): the /// translation, DXC and driver blob caches on disk get what the title will ask for. The pipeline /// is released; false: not made (noted in the log as the title's would be). -pub(crate) unsafe fn prepare_graphics(device: usize, desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> bool { +pub(crate) unsafe fn prepare_graphics(device: usize, desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, depth_bounds: bool) -> bool { let this = device as *mut c_void; let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateGraphicsPipelineState"))); let mut out: *mut c_void = std::ptr::null_mut(); - let made = matches!(translated_graphics_pso(this, f, desc as *const _ as *const c_void, &pc_iid(Kind::PipelineState), &mut out), Some(hr) if hr >= 0) && !out.is_null(); + let hr = with_switch_fallback(|| translated_graphics_pso_once(this, f, desc as *const _ as _, &pc_iid(Kind::PipelineState), &mut out, depth_bounds)); + let made = matches!(hr, Some(hr) if hr >= 0) && !out.is_null(); super::pso_async::release(out as usize); made } @@ -6995,6 +7018,40 @@ impl StreamOut { } } +fn depth_bounds_key(mut key: (u64, usize), enabled: bool) -> (u64, usize) { + if enabled { + for &byte in b"DB01" { key.0 = (key.0 ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3); } + } + key +} + +/// The richer depth-stencil descriptor can only be passed through a pipeline stream. +fn depth_bounds_stream(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> StreamOut { + let mut out = StreamOut::default(); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &d.pRootSignature); + for (stage, code) in [(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &d.VS), + (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, &d.PS), (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS, &d.DS), + (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS, &d.HS), (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, &d.GS)] { + if code.BytecodeLength != 0 { out.put(stage, code); } + } + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, &super::gfx_records::depth_stencil1(&d.DepthStencilState, true)); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, &d.BlendState); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, &d.RasterizerState); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, &d.SampleMask); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, &d.SampleDesc); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + &D3D12_RT_FORMAT_ARRAY { NumRenderTargets: d.NumRenderTargets, RTFormats: d.RTVFormats }); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, &d.DSVFormat); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, &d.PrimitiveTopologyType); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, &d.IBStripCutValue); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, &d.InputLayout); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT, &d.StreamOutput); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK, &d.NodeMask); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, &d.Flags); + if d.CachedPSO.CachedBlobSizeInBytes != 0 { out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO, &d.CachedPSO); } + out +} + /// The subobjects of a stream: (type, payload). fn stream_subobjects(buf: &[u8]) -> Option> { let mut out = Vec::new(); @@ -7042,6 +7099,7 @@ unsafe fn record_mesh_stream(stream: &[u8]) -> Option> { let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); let mut layout = Vec::with_capacity(subs.len()); let (mut ms, mut amplification, mut ps) = (None, None, None); + let mut depth_bounds = false; let (mut seen, mut size) = (0u32, 0usize); fn value(payload: &[u8]) -> Option { @@ -7059,7 +7117,8 @@ unsafe fn record_mesh_stream(stream: &[u8]) -> Option> { match ty { 0 => {} // The translator supplies its own root signature. 19 => continue, // The title's cache blob is never an input to translation. - 2 | 24 | 25 if payload.iter().all(|&b| b == 0) => continue, + 24 | 25 if payload.iter().all(|&b| b == 0) => continue, + 1..=5 if payload.iter().all(|&b| b == 0) => {} 2 => ps = Some(payload_shader(payload)?), 24 => amplification = Some(payload_shader(payload)?), 25 => ms = Some(payload_shader(payload)?), @@ -7067,6 +7126,16 @@ unsafe fn record_mesh_stream(stream: &[u8]) -> Option> { 9 => desc.SampleMask = value(payload)?, 10 => desc.RasterizerState = value(payload)?, 11 => desc.DepthStencilState = value(payload)?, + 12 if value::(payload).is_some_and(|d| d.NumElements == 0 && d.pInputElementDescs.is_null()) => {} + 21 => { + let d = value::(payload)?; + depth_bounds = d.DepthBoundsTestEnable.as_bool(); + desc.DepthStencilState = D3D12_DEPTH_STENCIL_DESC { + DepthEnable: d.DepthEnable, DepthWriteMask: d.DepthWriteMask, DepthFunc: d.DepthFunc, + StencilEnable: d.StencilEnable, StencilReadMask: d.StencilReadMask, StencilWriteMask: d.StencilWriteMask, + FrontFace: d.FrontFace, BackFace: d.BackFace, + }; + } 13 => desc.IBStripCutValue = value(payload)?, 14 => desc.PrimitiveTopologyType = value(payload)?, 15 => { @@ -7094,7 +7163,7 @@ unsafe fn record_mesh_stream(stream: &[u8]) -> Option> { } let shaders = [shader_key(ms), ps.map_or(0, shader_key)]; let key = shader_set_key(std::iter::once(ms).chain(ps)); - super::gfx_records::encode_mesh(key, shaders, &layout, &desc) + super::gfx_records::encode_mesh(key, shaders, &layout, &desc, depth_bounds) } /// Build both recorded mesh passes on the adopted device from `prepare_device`. @@ -7119,12 +7188,18 @@ pub(crate) unsafe fn replay_mesh_record( let subobject = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(ty as i32); match ty { 0 => stream.put(subobject, &std::ptr::null::()), - 2 => stream.shader(subobject, ps.ok_or("pixel shader missing from the job")?), + 2 => match ps { + Some(bytes) => stream.shader(subobject, bytes), + None => stream.put(subobject, &D3D12_SHADER_BYTECODE::default()), + }, + 1 | 3..=5 => stream.put(subobject, &D3D12_SHADER_BYTECODE::default()), 24 | 25 => stream.shader(subobject, ms), 8 => stream.put(subobject, &d.BlendState), 9 => stream.put(subobject, &d.SampleMask), 10 => stream.put(subobject, &d.RasterizerState), 11 => stream.put(subobject, &d.DepthStencilState), + 12 => stream.put(subobject, &D3D12_INPUT_LAYOUT_DESC::default()), + 21 => stream.put(subobject, &super::gfx_records::depth_stencil1(&d.DepthStencilState, record.depth_bounds)), 13 => stream.put(subobject, &d.IBStripCutValue), 14 => stream.put(subobject, &d.PrimitiveTopologyType), 15 => stream.put(subobject, &D3D12_RT_FORMAT_ARRAY { RTFormats: d.RTVFormats, NumRenderTargets: d.NumRenderTargets }), @@ -7519,6 +7594,29 @@ mod mesh_slot_tests { s } + #[test] + fn recorded_mesh_preserves_bounds_and_only_accepts_empty_extra_stages() { + let ms = sample(13, &[fssm(&CODE, &[(8, 13)])]); + let mut stream = sub(25, &bytecode(&ms)); + for kind in [1, 2, 3, 4, 5, 12] { stream.extend(sub(kind, &[0; 16])); } + let mut depth = [0u8; 56]; + depth[52..].copy_from_slice(&1u32.to_le_bytes()); + stream.extend(sub(21, &depth)); + let encoded = unsafe { super::record_mesh_stream(&stream) }.unwrap(); + let Some(super::super::gfx_records::Entry::MeshPipeline(record)) = super::super::gfx_records::decode(&encoded) else { + panic!("expected a mesh pipeline") + }; + assert_eq!(record.layout, [25, 1, 2, 3, 4, 5, 12, 21]); + assert!(record.depth_bounds); + let mut active = sub(25, &bytecode(&ms)); + active.extend(sub(3, &bytecode(&ms))); + assert!(unsafe { super::record_mesh_stream(&active) }.is_none()); + let mut layout = sub(25, &bytecode(&ms)); + let mut input = [0u8; 16]; input[8] = 1; + layout.extend(sub(12, &input)); + assert!(unsafe { super::record_mesh_stream(&layout) }.is_none()); + } + /// The stand-in for a console MS alone in the AS slot is a mesh pipeline: the subobject is /// retyped to MS with the dummy MS (as `translated_mesh_stream` reads the title's stream), /// the PS is the dummy PS. Left an empty AS and a PS, the stream had neither an MS nor a VS diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index 45ce7573b5..be751db426 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -35,6 +35,7 @@ Usage: --recomp: translates every RDNA2 program → HLSL and shows what is missing; --compile N: additionally compiles N complete translations with DXC. --precompile [--only STAGE]: caches compiled shaders before a run (e.g. --only cs). + --prepare-corpus: builds every staged native pipeline recipe for a title folder. --pipelines also builds compute pipelines and caches them for the next run. --used-only skips compute shaders whose pipelines were not used in earlier runs. --export-hlsl DIR [--count N] [--min-kb N] [--record-hash HEX]: writes deterministic diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index ba27edaca3..b193096f2b 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -13,6 +13,7 @@ use std::sync::Mutex; use crate::gpu::{dxbc, pack, rdna2, recomp, shader, xbox}; use crate::hle::d3d12x::gfx_records; +pub(crate) mod pso_corpus; /// `--iface`: how console programs connect to their DXBC signatures (hypothesis checks for /// the VS/PS interface of the recompiler). @@ -814,6 +815,7 @@ struct ShadersOptions { measure_pso: Option, repeat: usize, precompile: bool, + prepare_corpus: bool, limit: usize, only: Option, pipelines: bool, @@ -851,6 +853,7 @@ fn parse_args(args: &[String]) -> Result { measure_pso: None, repeat: 1, precompile: false, + prepare_corpus: false, limit: usize::MAX, only: None, pipelines: false, @@ -890,6 +893,7 @@ fn parse_args(args: &[String]) -> Result { "--measure-pso" => opts.measure_pso = Some(p.parse_hex_u64("--measure-pso")?), "--repeat" => opts.repeat = p.parse_usize("--repeat")?, "--precompile" => opts.precompile = true, + "--prepare-corpus" => opts.prepare_corpus = true, "--limit" => opts.limit = p.parse_usize("--limit")?, "--only" => opts.only = Some(p.value("--only")?.to_ascii_lowercase()), "--pipelines" => opts.pipelines = true, @@ -921,6 +925,17 @@ pub fn run(path: &Path, args: &[String]) -> i32 { return 2; } }; + if opts.prepare_corpus { + let progress = LaunchPreparation { adapter: "auto".into(), ..Default::default() }; + let result = pso_corpus::discover(path) + .and_then(|c| c.ok_or_else(|| "No pipeline corpus found in this title folder".to_string())) + .and_then(|c| c.prepare_with_threads(&progress, opts.threads)) + .and_then(|_| progress.check_corpus_complete()); + return match result { + Ok(()) => { println!("Prepared all {} discovered pipeline recipes", progress.done.load(Ordering::Acquire)); 0 } + Err(e) => { eprintln!("xcl shaders: {e}"); 2 } + }; + } // the runtime's memory windows: as many as a run has (`XCL_UMA_WINDOWS`), from the // descriptor heap with `XCL_HEAP_WINDOWS=1` (`pso::mem_windows`), as `--precompile` let runtime_windows = { @@ -934,7 +949,7 @@ pub fn run(path: &Path, args: &[String]) -> i32 { move || if heap { windows | recomp::HEAP_WINDOWS } else { windows } }; if opts.graphics_records { - return graphics_worker(path, runtime_windows()); + return graphics_worker(path, runtime_windows(), opts.threads); } let top = opts.top; let json = opts.json; @@ -1505,7 +1520,30 @@ impl Pipelines { self.make_one(&c.dxil, &c.samplers, false, path_override); } + fn prepare_compute(&self, blob: &[u8], windows: u32) -> Result<(), String> { + let split = recomp::pso::wave32_only_for_device(&self.dev); + let program = recomp::pso::console_to_dxil_in(blob, recomp::pso::Stage::Compute, 0, split, windows)?; + self.prepare_compiled_compute(&program) + } + + fn prepare_compiled_compute(&self, program: &recomp::pso::Compiled) -> Result<(), String> { + let make = |dxil: &[u8], chained| { + self.make_required(dxil, &program.samplers, chained, None, true) + }; + make(&program.dxil, false)?; + if let Some(chain) = program.dispatch_chain.as_deref().filter(|c| c.pieces.len() >= 2) { + for piece in &chain.pieces { make(piece, true)?; } + make(&program.dxil, true)?; + } + Ok(()) + } + fn make_one(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, path_override: Option) { + let _ = self.make_required(dxil, samplers, chained, path_override, false); + } + + fn make_required(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, + path_override: Option, required: bool) -> Result<(), String> { use windows::Win32::Graphics::Direct3D12::*; let key: (bool, Vec) = (chained, samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect()); let rs = { @@ -1523,9 +1561,9 @@ impl Pipelines { g.insert(key, rs.clone()); rs } - Err(_) => { + Err(e) => { self.refused.fetch_add(1, Ordering::Relaxed); - return; + return Err(format!("Creating compute root signature: {e}")); } } } @@ -1553,7 +1591,7 @@ impl Pipelines { self.capped.fetch_add(1, Ordering::Relaxed); self.capped_bytes.fetch_add(dxil.len(), Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - return; + return Err(format!("Compute DXIL exceeds the native pipeline size limit ({} bytes)", dxil.len())); } { let mut n = self.running.0.lock().unwrap(); @@ -1572,12 +1610,14 @@ impl Pipelines { let claim = match (&cached, path.as_deref()) { (None, Some(path)) => match Claim::take(path) { Some(c) => Some(c), + // A mandatory job needs a native result even if another process owns the cache write. + None if required => None, None => { *self.running.0.lock().unwrap() -= 1; self.running.1.notify_one(); self.elsewhere.fetch_add(1, Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - return; + return Err("Another process is preparing this compute pipeline".into()); } }, _ => None, @@ -1601,7 +1641,7 @@ impl Pipelines { self.capped.fetch_add(1, Ordering::Relaxed); self.capped_bytes.fetch_add(dxil.len(), Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - return; + return Err(format!("The cached compute pipeline was rejected and {} bytes of DXIL exceed the limit", dxil.len())); } let r = if let Some(pso) = from_cache { self.reused.fetch_add(1, Ordering::Relaxed); @@ -1609,7 +1649,7 @@ impl Pipelines { } else { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let pso = unsafe { self.dev.CreateComputePipelineState::(&desc) }; - if let (Some(path), Ok(pso)) = (path.as_deref(), &pso) { + if let (Some(path), Ok(pso)) = (path.as_deref().filter(|_| claim.is_some() || cached.is_some()), &pso) { if let Ok(blob) = unsafe { pso.GetCachedBlob() } { let bytes = unsafe { blob.GetBufferPointer() }.cast::(); let len = unsafe { blob.GetBufferSize() }; @@ -1624,13 +1664,14 @@ impl Pipelines { *self.running.0.lock().unwrap() -= 1; self.running.1.notify_one(); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - let done = match r { + let done = match &r { Ok(_) => self.made.fetch_add(1, Ordering::Relaxed) + 1, Err(_) => self.refused.fetch_add(1, Ordering::Relaxed) + 1, }; if done % 25 == 0 { eprintln!(" pipelines: {} made, {} refused", self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed)); } + r.map(drop).map_err(|e| format!("Creating native compute pipeline ({} bytes of DXIL): {e}", dxil.len())) } } @@ -1651,10 +1692,35 @@ pub(crate) struct LaunchPreparation { pub workers: AtomicUsize, /// The workers build graphics pipelines (`graphics_in_workers`): `done` and `total` count those. pub graphics: std::sync::atomic::AtomicBool, - /// The shaders earlier runs used (`pso_async::earlier_used_shaders`), when there are any: - /// only their records are translated before the title starts, and it translates another - /// when it first uses it. `XCL_PREPARE_ALL=1`: every record, as without the list. - pub only: Option>, + /// While replaying the discovered corpus, only verified native successes advance `done`. + pub corpus: std::sync::atomic::AtomicBool, +} + +impl LaunchPreparation { + pub(crate) fn begin_corpus(&self, total: usize) { + self.done.store(0, Ordering::Relaxed); + self.total.store(total, Ordering::Relaxed); + self.corpus.store(true, Ordering::Release); + } + + pub(crate) fn complete_corpus(&self, count: usize) -> Result<(), String> { + if self.cancel.load(Ordering::Relaxed) { return Err("Pipeline preparation cancelled".into()); } + if !self.corpus.load(Ordering::Acquire) || count > self.total.load(Ordering::Relaxed) { + return Err("Native completion count exceeds the discovered corpus".into()); + } + self.done.fetch_max(count, Ordering::Release); + Ok(()) + } + + pub(crate) fn check_corpus_complete(&self) -> Result<(), String> { + if self.cancel.load(Ordering::Relaxed) { return Err("Pipeline preparation cancelled".into()); } + let done = self.done.load(Ordering::Acquire); + let total = self.total.load(Ordering::Relaxed); + if !self.corpus.load(Ordering::Acquire) || total == 0 || done != total { + return Err(format!("Native pipeline preparation incomplete: {done} of {total} recipes confirmed")); + } + Ok(()) + } } /// Unpacked shader containers in the title's shaders directory. Do not follow directory @@ -1676,6 +1742,16 @@ fn loose_inputs(dir: &Path, files: &mut Vec) -> std::io::Result<()> { } pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> Result<(), String> { + let corpus = pso_corpus::discover(root)?; + prepare_title_inputs(root, progress)?; + if let Some(corpus) = corpus { + corpus.prepare(progress)?; + progress.check_corpus_complete()?; + } + Ok(()) +} + +fn prepare_title_inputs(root: &Path, progress: &LaunchPreparation) -> Result<(), String> { let mut inputs = Vec::new(); let pack = root.join("shaders.rpf"); if pack.try_exists().map_err(|e| e.to_string())? { @@ -1709,11 +1785,6 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R precompile(input, usize::MAX, windows, None, None, true, None, std::time::Instant::now(), Some(progress))?; } if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } - // `XCL_PREPARE_GRAPHICS=0`: the title builds the graphics pipelines it uses as it goes - if std::env::var("XCL_PREPARE_GRAPHICS").is_ok_and(|v| v.trim() == "0") { - crate::xlog_info!("Shader preparation: graphics pipelines left out (XCL_PREPARE_GRAPHICS=0)"); - return Ok(()); - } graphics_in_workers(&inputs, windows, workers, progress) } @@ -1806,17 +1877,17 @@ mod claim_tests { /// what is missing itself. fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usize, progress: &LaunchPreparation) -> Result<(), String> { let me = std::env::current_exe().map_err(|e| e.to_string())?; - let used_only = !crate::hle::d3d12x::pso_async::earlier_used_keys().is_empty(); let t0 = std::time::Instant::now(); - crate::xlog_info!("Shader preparation: compute pipelines in {workers} worker processes{}", if used_only { ", those an earlier run used" } else { "" }); + crate::xlog_info!("Shader preparation: compute pipelines in {workers} worker processes"); let (cancelled, failed, _) = in_workers(workers, records, progress, |i| { let mut c = worker_command(&me); c.arg("shaders").arg(pack).args(["--precompile", "--only", "cs", "--pipelines", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); - if used_only { c.arg("--used-only"); } + if std::env::var_os("XCL_ADAPTER").is_none() && !progress.adapter.is_empty() { c.env("XCL_ADAPTER", &progress.adapter); } c.env("XCL_PRECOMPILE_SLICE", format!("{i}/{workers}")); c }); if cancelled { return Err("Shader preparation cancelled".into()); } + if failed != 0 { return Err(format!("{failed} of {workers} compute pipeline workers failed")); } crate::xlog_info!("Shader preparation: compute pipelines done in {:.0} s ({failed} of {workers} workers failed)", t0.elapsed().as_secs_f64()); Ok(()) } @@ -1884,7 +1955,7 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut std::thread::sleep(std::time::Duration::from_millis(100)); } }); - let mut failed = 0; + let mut failed = workers - children.len(); for (i, child) in children.iter_mut() { match child.wait() { Ok(st) if st.success() => {} @@ -1908,23 +1979,44 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut /// starts all the same: it builds what is missing itself. fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: &LaunchPreparation) -> Result<(), String> { let t0 = std::time::Instant::now(); - let payloads = gfx_records::read(&gfx_records::path()); - let records: Vec<_> = payloads.into_iter().filter_map(|payload| { - let record = GraphicsHistoryRecord::from_entry(gfx_records::decode(&payload)?)?; - Some((payload, record)) - }).collect(); + let path = gfx_records::path(); + let local = if path.try_exists().map_err(|e| e.to_string())? { gfx_records::read_complete_payloads(&path)? } else { Vec::new() }; + let mut records = Vec::new(); + let mut embedded = std::collections::HashMap::new(); + for payload in local { + match gfx_records::decode(&payload).ok_or("Unrecognized graphics history entry")? { + gfx_records::Entry::Shader(key, code) => { + if crate::hle::d3d12x::real::shader_key(&code) != key { + return Err(format!("Graphics history shader {key:016x} failed its identity check")); + } + embedded.insert(key, code); + } + entry => if let Some(record) = GraphicsHistoryRecord::from_entry(entry) { records.push((payload, record)); }, + } + } + let local_count = records.len(); + let legacy = gfx_records::shared_history_path(); + if !inputs.is_empty() && legacy != path { + let scoped: HashSet<_> = records.iter().map(|(bytes, _)| bytes.as_slice()).collect(); + let candidates: Vec<_> = gfx_records::read(&legacy).into_iter().filter(|bytes| !scoped.contains(bytes.as_slice())) + .filter_map(|payload| Some((GraphicsHistoryRecord::from_entry(gfx_records::decode(&payload)?)?, payload))).collect(); + records.extend(candidates.into_iter().map(|(record, payload)| (payload, record))); + } if records.is_empty() { crate::xlog_info!("Shader preparation: no graphics pipelines of an earlier run to build"); return Ok(()); } let wanted = records.iter().flat_map(|(_, record)| record.identity().1.iter().copied()) - .filter(|&key| key != 0).collect(); - let shaders = shaders_by_key(inputs, wanted, progress); + .filter(|&key| key != 0 && !embedded.contains_key(&key)).collect(); + let mut shaders = shaders_by_key(inputs, wanted, progress); + shaders.extend(embedded); if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } let (buildable, missing) = buildable(records.iter().map(|(_, r)| r), &shaders); - if missing != 0 { - crate::xlog_info!("Shader preparation: {missing} of {} graphics pipelines left out (their shaders are not in the title's shader files)", records.len()); + let local_missing = local_count - buildable.iter().take_while(|&&i| i < local_count).count(); + if local_missing != 0 { + return Err(format!("{local_missing} of {local_count} title graphics recipes lack matching shader sources")); } + if missing != 0 { crate::xlog_info!("Shader preparation: {missing} shared graphics recipes have no matching shaders in this title"); } if buildable.is_empty() { return Ok(()); } let workers = workers.clamp(1, buildable.len()); // each worker's part, with the shaders it needs (removed when they are done) @@ -1958,6 +2050,10 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: for (path, _) in &jobs { let _ = std::fs::remove_file(path); } if cancelled { return Err("Shader preparation cancelled".into()); } let sum = summaries.iter().filter_map(|s| graphics_summary(s)).fold([0usize; 4], |a, b| std::array::from_fn(|k| a[k] + b[k])); + if failed != 0 || sum[1] != 0 || sum[0] != buildable.len() { + return Err(format!("Graphics preparation incomplete: {} of {} confirmed, {} refused, {failed} workers failed", + sum[0], buildable.len(), sum[1])); + } crate::xlog_info!( "Shader preparation: graphics pipelines done in {:.0} s: {} made, {} failed; driver blobs: {} from disk, {} kept ({failed} of {workers} workers failed)", t0.elapsed().as_secs_f64(), sum[0], sum[1], sum[2], sum[3] @@ -2033,59 +2129,84 @@ fn graphics_summary(line: &str) -> Option<[usize; 4]> { n.next().is_none().then_some(out) } +fn corpus_threads(requested: Option, default: usize) -> usize { + requested.or_else(|| std::env::var("XCL_PIPELINE_THREADS").ok()?.parse().ok()).unwrap_or(default).clamp(1, 32) +} + /// `xcl shaders --graphics-records` (a worker of `graphics_in_workers`): the graphics /// pipelines of a job file built as the title builds them, with the /// title's memory windows (`windows`) and on its adapter (`XCL_ADAPTER`), `XCL_PIPELINE_THREADS` /// at a time. A progress line a pipeline, then the summary `graphics_summary` reads. -fn graphics_worker(job: &Path, windows: u32) -> i32 { +fn graphics_worker(job: &Path, windows: u32, requested: Option) -> i32 { use crate::hle::d3d12x::real; end_with_parent(); - // (no title memory here: its windows are given) - crate::gpu::uma::leave_out(); - recomp::pso::set_title_windows(windows); - recomp::dxc::set_memory_reserve(2); let mut shaders = std::collections::HashMap::new(); let mut records = Vec::new(); - for p in gfx_records::read(job) { - match gfx_records::decode(&p) { - Some(gfx_records::Entry::Shader(key, code)) => { shaders.insert(key, code); } - Some(entry) => records.extend(GraphicsHistoryRecord::from_entry(entry)), - None => {} + let entries = match gfx_records::read_job(job) { + Ok(entries) => entries, + Err(e) => { eprintln!("xcl shaders: {}: {e}", job.display()); return 2; } + }; + for entry in entries { + match entry { + gfx_records::Entry::Shader(key, code) => { + if real::shader_key(&code) != key || shaders.get(&key).is_some_and(|prior| prior != &code) { + eprintln!("xcl shaders: invalid or conflicting shader {key:016x} in {}", job.display()); + return 2; + } + shaders.insert(key, code); + } + entry => records.extend(GraphicsHistoryRecord::from_entry(entry)), } } + let n = records.len(); + let (ready, missing) = buildable(records.iter(), &shaders); + if missing != 0 { eprintln!("xcl shaders: {missing} graphics records have missing or mismatched shaders"); } + if ready.is_empty() { + eprintln!("graphics pipelines: 0 made, {missing} failed; driver blobs: 0 from disk, 0 kept"); + return if missing == 0 { 0 } else { 2 }; + } + // (no title memory here: its windows are given) + crate::gpu::uma::leave_out(); + recomp::pso::set_title_windows(windows); + recomp::dxc::set_memory_reserve(2); let device = match Pipelines::for_adapter("auto") { Ok(p) => real::prepare_device(p.dev), Err(e) => { eprintln!("xcl shaders: no pipeline device: {e}"); return 2; } }; - let n = records.len(); - let threads = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse::().ok()).unwrap_or(1).clamp(1, 8); - let (next, done, made, failed) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); + let threads = corpus_threads(requested, 1).min(ready.len()); + let (next, made, failed) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(missing)); let t0 = std::time::Instant::now(); std::thread::scope(|s| { for _ in 0..threads { s.spawn(|| loop { let i = next.fetch_add(1, Ordering::Relaxed); - let Some(r) = records.get(i) else { break }; + let Some(&index) = ready.get(i) else { break }; + let r = &records[index]; let code = |key| shaders.get(&key).map(Vec::as_slice); // (a pipeline that panics fails; the others are built) let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match r { GraphicsHistoryRecord::Legacy(record) => { let desc = record.desc(record.shaders.map(code)); - unsafe { real::prepare_graphics(device, &desc) } + unsafe { real::prepare_graphics(device, &desc, record.depth_bounds) } } GraphicsHistoryRecord::Mesh(record) => { unsafe { real::replay_mesh_record(device, record, record.shaders.map(code)).is_ok() } } })).unwrap_or(false); - if ok { made.fetch_add(1, Ordering::Relaxed); } else { failed.fetch_add(1, Ordering::Relaxed); } - let d = done.fetch_add(1, Ordering::Relaxed) + 1; - eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); + if ok { + let d = made.fetch_add(1, Ordering::Relaxed) + 1; + eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); + } else { + failed.fetch_add(1, Ordering::Relaxed); + eprintln!("xcl shaders: failed graphics record {} (shader set {:016x})", index + 1, r.identity().0); + } }); } }); let (hits, _, stored) = real::driver_cache_stats(); - eprintln!("graphics pipelines: {} made, {} failed; driver blobs: {hits} from disk, {stored} kept", made.into_inner(), failed.into_inner()); - 0 + let failed = failed.into_inner(); + eprintln!("graphics pipelines: {} made, {failed} failed; driver blobs: {hits} from disk, {stored} kept", made.into_inner()); + if failed == 0 { 0 } else { 2 } } /// `XCL_PRECOMPILE_PARENT=pid` (set for a title's preparation workers): this process ends when @@ -2109,10 +2230,11 @@ fn end_with_parent() { fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> { if startup.is_none() { end_with_parent(); } + let mandatory = startup.is_some() || std::env::var_os("XCL_PRECOMPILE_PARENT").is_some(); let pipelines = if pipelines { let mut p = Pipelines::for_adapter(startup.map_or("auto", |p| p.adapter.as_str())) .map_err(|e| format!("No pipeline device: {e}"))?; - if startup.is_some() && std::env::var_os("XCL_PIPELINE_MAX_KB").is_none() { + if mandatory && std::env::var_os("XCL_PIPELINE_MAX_KB").is_none() { p.max_dxil = 0; } Some(p) @@ -2187,11 +2309,6 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on record_done(); continue; } - if startup.and_then(|p| p.only.as_ref()).is_some_and(|used| !used.contains(&crate::hle::d3d12x::real::shader_key(&blob))) { - unused.fetch_add(1, Ordering::Relaxed); - record_done(); - continue; - } // a compute program as a title's pipeline translates it (`pso::console_to_dxil_in`): // into the translation cache too, so the title does not translate it again if sh.fssm.iter().any(|f| matches!(recomp::interface(&blob, &sh, f), Some(recomp::Mode::Compute(_)))) { @@ -2203,9 +2320,16 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { if let Some(p) = pipelines { - p.make(&c); - if startup.is_some() && c.dispatch_chain.as_ref().is_some_and(|plan| plan.pieces.len() >= 2) { - p.make_one(&c.dxil, &c.samplers, true, None); + if mandatory { + if let Err(e) = p.prepare_compiled_compute(&c) { + failed.fetch_add(1, Ordering::Relaxed); + let mut logs = errors.lock().unwrap(); + if logs.len() < 10 { logs.push(format!("{name}: {e}")); } + record_done(); + continue; + } + } else { + p.make(&c); } } compiled.fetch_add(1, Ordering::Relaxed) @@ -2301,8 +2425,8 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } let errors = errors.into_inner().unwrap(); for e in &errors { println!(" {e}"); } - if let Some(progress) = startup { - if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + if mandatory { + if startup.is_some_and(|p| p.cancel.load(Ordering::Relaxed)) { return Err("Shader preparation cancelled".into()); } // (no pipelines here when worker processes build them: `pipelines_in_workers`) let refused = pipelines.map_or(0, |p| p.refused.load(Ordering::Relaxed)); let capped = pipelines.map_or(0, |p| p.capped.load(Ordering::Relaxed)); @@ -2695,7 +2819,7 @@ mod tests { let both = [shader_key(&vs), shader_key(&ps), 0, 0, 0]; let mesh = |key, shaders| { let layout = [D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32]; - let payload = encode_mesh(key, shaders, &layout, &desc).unwrap(); + let payload = encode_mesh(key, shaders, &layout, &desc, false).unwrap(); GraphicsHistoryRecord::from_entry(decode(&payload).unwrap()).unwrap() }; let records = [ @@ -2710,6 +2834,36 @@ mod tests { assert_eq!(buildable(records.iter(), &shaders), (vec![0, 1, 4], 3)); } + #[test] + fn a_graphics_job_with_a_missing_or_incorrectly_named_shader_fails() { + use crate::hle::d3d12x::gfx_records::{encode_mesh, shader_entry, Writer}; + use crate::hle::d3d12x::real::shader_key; + let path = std::env::temp_dir().join(format!("xcl-graphics-missing-{}.bin", std::process::id())); + let _ = std::fs::remove_file(&path); + let bytes = b"mesh"; + let key = shader_key(bytes); + { + let mut job = Writer::open(&path, u64::MAX).unwrap(); + job.add(&encode_mesh(key, [key, 0], &[25], &Default::default(), false).unwrap()).unwrap(); + } + assert_eq!(graphics_worker(&path, 1, Some(1)), 2); + { + let mut job = Writer::open(&path, u64::MAX).unwrap(); + job.add(&shader_entry(key, b"different mesh")).unwrap(); + } + assert_eq!(graphics_worker(&path, 1, Some(1)), 2); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn explicit_pipeline_worker_counts_can_use_all_thirty_two_slots() { + for count in [1, 2, 8, 16, 32] { + assert_eq!(corpus_threads(Some(count), 1), count); + } + assert_eq!(corpus_threads(Some(0), 1), 1); + assert_eq!(corpus_threads(Some(33), 1), 32); + } + /// `--used-only` keeps a compute program exactly when the runtime noted its pipeline: the /// key of a pipeline of that one shader, as `real::shaders_key` makes it. #[test] diff --git a/crates/xcl/src/shaders/pso_corpus.rs b/crates/xcl/src/shaders/pso_corpus.rs new file mode 100644 index 0000000000..a2b564fe7b --- /dev/null +++ b/crates/xcl/src/shaders/pso_corpus.rs @@ -0,0 +1,186 @@ +//! A staged set of native graphics and compute recipes, shared by startup and offline preparation. +use super::{gfx_records, graphics_summary, progress_count, recomp, worker_command, LaunchPreparation, Pipelines}; +use std::io::{BufRead, BufReader}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{mpsc, Mutex}; +use std::time::Duration; + +pub(crate) struct Corpus { + graphics: Option<(PathBuf, usize)>, + compute: Vec<(u64, PathBuf)>, + windows: u32, +} + +pub(crate) fn discover(root: &Path) -> Result, String> { + let dir = root.join(".xcl").join("pso-corpus"); + if !dir.try_exists().map_err(|e| e.to_string())? { return Ok(None); } + let marker = std::fs::read_to_string(dir.join("complete")).map_err(|e| format!("Incomplete pipeline corpus: {e}"))?; + let expected = marker.split_whitespace().map(str::parse::).collect::, _>>() + .map_err(|_| "Invalid pipeline corpus counts")?; + if expected.len() != 2 { return Err("Expected graphics and compute counts in the corpus marker".into()); } + let encoded = std::fs::read_to_string(dir.join("windows")).map_err(|e| e.to_string())?; + let encoded = encoded.trim().parse::().map_err(|_| "Invalid corpus memory window count")?; + let count = (encoded & 127) as usize; + let heap = encoded & 128 != 0; + if !recomp::valid_window_count(count, heap) || heap && count <= 1 { + return Err(format!("Invalid corpus memory window configuration {encoded}")); + } + let windows = count as u32 | if heap { recomp::HEAP_WINDOWS } else { 0 }; + let path = dir.join("graphics.bin"); + let graphics = if path.try_exists().map_err(|e| e.to_string())? { + let entries = gfx_records::read_job(&path)?; + let count = entries.iter().filter(|e| !matches!(e, gfx_records::Entry::Shader(..))).count(); + if count == 0 { return Err("Graphics job contains no pipeline records".into()); } + Some((path, count)) + } else { None }; + let mut compute = Vec::new(); + let folder = dir.join("compute"); + if folder.try_exists().map_err(|e| e.to_string())? { + for entry in std::fs::read_dir(&folder).map_err(|e| e.to_string())? { + let entry = entry.map_err(|e| e.to_string())?; + let path = entry.path(); + let name = entry.file_name(); + let key = name.to_str().and_then(|s| s.strip_suffix(".dxbc")) + .filter(|s| s.len() == 16).and_then(|s| u64::from_str_radix(s, 16).ok()); + let key = key.ok_or_else(|| format!("Invalid compute entry {}", path.display()))?; + if !entry.file_type().map_err(|e| e.to_string())?.is_file() { + return Err(format!("Expected a compute file at {}", path.display())); + } + compute.push((key, path)); + } + } + compute.sort_unstable(); + if expected != [graphics.as_ref().map_or(0, |(_, n)| *n), compute.len()] { + return Err("Pipeline corpus is missing records. Restage before launching.".into()); + } + if graphics.is_none() && compute.is_empty() { return Err("Published pipeline corpus is empty".into()); } + Ok(Some(Corpus { graphics, compute, windows })) +} + +impl Corpus { + pub(crate) fn prepare(&self, progress: &LaunchPreparation) -> Result<(), String> { + self.prepare_with_threads(progress, None) + } + + pub(super) fn prepare_with_threads(&self, progress: &LaunchPreparation, requested: Option) -> Result<(), String> { + let graphics_count = self.graphics.as_ref().map_or(0, |(_, n)| *n); + progress.begin_corpus(graphics_count + self.compute.len()); + let count = self.windows & !recomp::HEAP_WINDOWS; + let runtime = crate::gpu::uma::configured_runtime_windows(); + if count as usize != runtime || (self.windows & recomp::HEAP_WINDOWS != 0) != (runtime > 1 && recomp::pso::heap_windows()) { + return Err(format!("Pipeline corpus memory configuration differs from the runtime ({runtime} windows). Restage for the current configuration or select the matching XCL_UMA_WINDOWS and XCL_HEAP_WINDOWS.")); + } + let parallel = super::corpus_threads(requested, super::prepare_workers().min(8)); + if let Some((path, n)) = &self.graphics { + run_graphics(path, *n, count, parallel, progress)?; + } + if self.compute.is_empty() { return progress.check_corpus_complete(); } + let mut pipelines = Pipelines::for_adapter(&progress.adapter)?; + pipelines.max_dxil = 0; + pipelines.most = parallel; + let next = AtomicUsize::new(0); + let completed = Mutex::new(graphics_count); + let error = Mutex::new(None); + std::thread::scope(|scope| { + for _ in 0..parallel.min(self.compute.len()) { + scope.spawn(|| loop { + if progress.cancel.load(Ordering::Acquire) || error.lock().unwrap().is_some() { break; } + let i = next.fetch_add(1, Ordering::Relaxed); + let Some((key,path)) = self.compute.get(i) else { break }; + let result = std::fs::read(path).map_err(|e| e.to_string()).and_then(|code| { + if crate::gpu::shader::fnv64(&code) != *key || !super::is_compute_container(&code) { + return Err("Compute shader identity or stage differs from the staged recipe".into()); + } + pipelines.prepare_compute(&code, self.windows)?; + let mut done = completed.lock().unwrap(); + *done += 1; + progress.complete_corpus(*done) + }); + if let Err(e) = result { + error.lock().unwrap().get_or_insert_with(|| format!("{}: {e}", path.display())); + break; + } + }); + } + }); + if let Some(e) = error.into_inner().unwrap() { return Err(e); } + progress.check_corpus_complete() + } +} + +fn run_graphics(path: &Path, count: usize, windows: u32, parallel: usize, progress: &LaunchPreparation) -> Result<(), String> { + let me = std::env::current_exe().map_err(|e| e.to_string())?; + let mut command = worker_command(&me); + if std::env::var("XCL_ADAPTER").unwrap_or_default().trim().is_empty() && !progress.adapter.is_empty() { + command.env("XCL_ADAPTER", &progress.adapter); + } + let mut child = command.arg("shaders").arg(path).arg("--graphics-records") + .arg("--windows").arg(windows.to_string()).env("XCL_PIPELINE_THREADS", parallel.to_string()) + .spawn().map_err(|e| e.to_string())?; + let stderr = child.stderr.take().expect("worker_command pipes stderr"); + let (tx, rx) = mpsc::channel(); + let reader = std::thread::spawn(move || { + for line in BufReader::new(stderr).lines() { + if tx.send(line).is_err() { break; } + } + }); + let mut summary = None; + let mut last = String::new(); + let mut made = 0; + let result = loop { + if progress.cancel.load(Ordering::Acquire) { break Err("Pipeline preparation cancelled".to_string()); } + match rx.recv_timeout(Duration::from_millis(100)) { + Ok(Ok(line)) => { + if let Some(n) = progress_count(&line) { + // Independent workers can print their completion counters out of order. + made = made.max(n); + if let Err(e) = progress.complete_corpus(made) { break Err(e); } + } else { + if let Some(values) = graphics_summary(&line) { summary = Some(values); } + if !line.trim().is_empty() { last = line; } + } + } + Ok(Err(e)) => break Err(e.to_string()), + Err(mpsc::RecvTimeoutError::Timeout) => continue, + Err(mpsc::RecvTimeoutError::Disconnected) => break Ok(()), + } + }; + if result.is_err() { let _ = child.kill(); } + drop(rx); + let status = child.wait().map_err(|e| e.to_string())?; + reader.join().map_err(|_| "Could not read graphics worker output")?; + result?; + if !status.success() || !matches!(summary, Some([n, 0, _, _]) if n == count) { + return Err(format!("Graphics preparation incomplete ({status}): {last}")); + } + progress.complete_corpus(count) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn discovery_distinguishes_absent_incomplete_and_ready_compute_corpora() { + let root = std::env::temp_dir().join(format!("xcl-corpus-discovery-{}", std::process::id())); + let dir = root.join(".xcl/pso-corpus"); + struct Cleanup(PathBuf); + impl Drop for Cleanup { + fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } + } + let _cleanup = Cleanup(root.clone()); + assert!(discover(&root).unwrap().is_none()); + std::fs::create_dir_all(dir.join("compute")).unwrap(); + assert!(discover(&root).is_err()); + std::fs::write(dir.join("complete"), "0 1\n").unwrap(); + std::fs::write(dir.join("windows"), "1\n").unwrap(); + assert!(discover(&root).is_err()); + std::fs::write(dir.join("compute/0000000000000010.dxbc"), []).unwrap(); + let corpus = discover(&root).unwrap().unwrap(); + assert_eq!(corpus.compute[0].0, 16); + assert_eq!(corpus.windows, 1); + std::fs::write(dir.join("windows"), "255").unwrap(); + assert!(discover(&root).is_err()); + } +} diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index 4f238248a9..aa4964eea1 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -48,6 +48,26 @@ fn copy_dir(src: &Path, dst: &Path) { } } +#[test] +fn incomplete_discovered_corpus_blocks_headless_title_entry() { + let xcl = Path::new(env!("CARGO_BIN_EXE_xcl")); + let root = temp_dir("incomplete-corpus"); + let game = root.join("game"); + let data = root.join("data"); + copy_dir(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/data/testgame"), &game); + std::fs::copy(xcl.parent().unwrap().join("xcl_testtitle.exe"), game.join("xcl_testtitle.exe")).unwrap(); + std::fs::create_dir_all(game.join(".xcl/pso-corpus")).unwrap(); + let settings = data.join("XCL.TestTitle"); + std::fs::create_dir_all(&settings).unwrap(); + std::fs::write(settings.join("xcl.toml"), "graphics='null'\npresent='off'\n").unwrap(); + let out = Command::new(xcl).arg("run").arg(&game).env("XCL_DATA_ROOT", &data) + .env("XCL_PREPARE", "0").env("XCL_PREPARE_GRAPHICS", "0").output().unwrap(); + assert!(!out.status.success(), "An incomplete corpus released the guest"); + let log = std::fs::read_to_string(settings.join("logs/xcl.log")).unwrap(); + assert!(log.contains("Incomplete pipeline corpus"), "{log}"); + assert!(!log.contains("game entry point returned"), "{log}"); +} + struct TempDir(PathBuf); impl std::ops::Deref for TempDir { From 07edd2997ccd557611ba57d0ceed21ba779a3ab1 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:03:25 -0500 Subject: [PATCH 4/6] Shaders: stream staged graphics jobs and preserve mesh cache identities Avoid decoding the entire graphics job in both the launcher and worker. Validate the independent worker completion count and reject incompatible corpus configurations. Preserve cache reuse for inert mesh shader slots and cover the headless launch gate. --- crates/xcl/src/hle/d3d12x/gfx_records.rs | 32 ++++++++++++++++--- .../xcl/src/hle/d3d12x/present/preparation.rs | 6 ++-- .../src/hle/d3d12x/real/two_pass_identity.rs | 24 ++++++++++++++ crates/xcl/src/shaders.rs | 4 +++ crates/xcl/src/shaders/pso_corpus.rs | 17 ++++++---- crates/xcl/tests/e2e.rs | 10 +++++- scripts/pso_corpus/stage.py | 3 +- scripts/pso_corpus/test_stage.py | 1 + 8 files changed, 80 insertions(+), 17 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/gfx_records.rs b/crates/xcl/src/hle/d3d12x/gfx_records.rs index 74b01fbb24..46a8c8f939 100644 --- a/crates/xcl/src/hle/d3d12x/gfx_records.rs +++ b/crates/xcl/src/hle/d3d12x/gfx_records.rs @@ -4,7 +4,7 @@ //! driver's blobs on disk. `used-pipelines.txt` holds only the keys of the shader sets and the //! driver cache only blobs named after the translated DXIL: neither is enough to make one again. //! -//! `used-graphics-pipelines.bin` beside the DXIL cache: +//! `used-graphics-pipelines.bin` in the title's cache (older runs used the shared DXIL cache): //! //! ```text //! file = "XCLGFXP\0", version u32, entry* @@ -485,10 +485,32 @@ pub(crate) fn read(path: &Path) -> Vec> { /// A completed worker job must contain only whole, supported records. A history file /// may be open for appends, so its reader above accepts a trailing partial entry. fn read_complete(path: &Path, mut take: impl FnMut(&[u8], Entry) -> T) -> Result, String> { - let file = std::fs::read(path).map_err(|e| e.to_string())?; - let (payloads, end) = payloads(&file).ok_or("unrecognized graphics job header")?; - if end != file.len() { return Err(format!("damaged graphics job at byte {end}")); } - payloads.into_iter().enumerate().map(|(i, p)| decode(p).map(|entry| take(p, entry)).ok_or_else(|| format!("invalid graphics job entry {}", i + 1))).collect() + use std::io::{BufReader, Read}; + let file = std::fs::File::open(path).map_err(|e| e.to_string())?; + let size = file.metadata().map_err(|e| e.to_string())?.len(); + let mut reader = BufReader::new(file); + let mut magic = [0; HEADER]; + if reader.read_exact(&mut magic).is_err() || magic != header() { + return Err("unrecognized graphics job header".into()); + } + let mut offset = HEADER as u64; + let mut entries = Vec::new(); + let mut payload = Vec::new(); + while offset < size { + let damaged = || format!("damaged graphics job at byte {offset}"); + let mut frame = [0; 8]; + if size - offset < 8 { return Err(damaged()); } + reader.read_exact(&mut frame).map_err(|_| damaged())?; + let len = u32::from_le_bytes(frame[..4].try_into().unwrap()) as usize; + if len as u64 > size - offset - 8 { return Err(damaged()); } + payload.resize(len, 0); + reader.read_exact(&mut payload).map_err(|_| damaged())?; + if check(&payload) != u32::from_le_bytes(frame[4..].try_into().unwrap()) { return Err(damaged()); } + let entry = decode(&payload).ok_or_else(|| format!("invalid graphics job entry {}", entries.len() + 1))?; + entries.push(take(&payload, entry)); + offset += 8 + len as u64; + } + Ok(entries) } pub(crate) fn read_complete_payloads(path: &Path) -> Result>, String> { diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs index baff972a85..bdd52d4ea3 100644 --- a/crates/xcl/src/hle/d3d12x/present/preparation.rs +++ b/crates/xcl/src/hle/d3d12x/present/preparation.rs @@ -43,9 +43,9 @@ pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { std::env::remove_var("XCL_PREPARATION_MENU"); let root = &boot.game_root; let corpus = root.join(".xcl/pso-corpus").try_exists().map_err(|e| e.to_string())?; - if !corpus && (boot.config.graphics.eq_ignore_ascii_case("null") || - (!root.join("shaders.rpf").try_exists().map_err(|e| e.to_string())? && !root.join("shaders").is_dir() && - !crate::hle::d3d12x::gfx_records::path().try_exists().map_err(|e| e.to_string())?)) { + let history = crate::hle::d3d12x::gfx_records::path().try_exists().map_err(|e| e.to_string())?; + if !corpus && !history && (boot.config.graphics.eq_ignore_ascii_case("null") || + (!root.join("shaders.rpf").try_exists().map_err(|e| e.to_string())? && !root.join("shaders").is_dir())) { return Ok(()); } let progress = Arc::new(LaunchPreparation { adapter: boot.config.d3d12_adapter.clone(), ..Default::default() }); diff --git a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs index 6ca0572281..37e6a41c53 100644 --- a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs +++ b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs @@ -206,6 +206,11 @@ pub(super) unsafe fn two_pass_stream_key(stream: &[u8], ps_samplers: &[crate::gp } } 1..=6 | 24 | 25 => { + if matches!(ty, 1..=5) && payload.iter().all(|&byte| byte == 0) { + h.u32(ty); + h.u64(0); + continue; + } let code = payload_shader(payload)?; shader_bytes = shader_bytes.checked_add(code.len())?; h.u32(ty); @@ -256,6 +261,25 @@ mod tests { use super::super::StreamOut; use std::ffi::c_void; + #[test] + fn inactive_shader_stages_keep_a_two_pass_driver_cache_key() { + let ms = [1u8, 2, 3, 4]; + let key = |stages: &[D3D12_PIPELINE_STATE_SUBOBJECT_TYPE]| { + let mut stream = StreamOut::default(); + stream.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, &ms); + for &stage in stages { stream.put(stage, &D3D12_SHADER_BYTECODE::default()); } + unsafe { two_pass_stream_key(&stream.0, &[], 7, 1) } + }; + let ds = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS; + let hs = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS; + let gs = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS; + let tagged = key(&[ds, hs, gs]).unwrap(); + assert_eq!(tagged.1, ms.len()); + assert_eq!(Some(tagged), key(&[gs, ds, hs])); + assert_ne!(Some(tagged), key(&[])); + assert_eq!(key(&[ds, ds]), None); + } + #[test] fn canonical_stream_key_distinguishes_state_samplers_and_driver() { let ms = [1u8, 2, 3, 4]; diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index b193096f2b..9ab11d97a2 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -926,6 +926,10 @@ pub fn run(path: &Path, args: &[String]) -> i32 { } }; if opts.prepare_corpus { + if opts.windows.is_some() || opts.split.is_some() || opts.limit != usize::MAX || opts.only.is_some() || opts.used_only { + eprintln!("xcl shaders: --prepare-corpus requires all staged recipes and their recorded memory configuration"); + return 2; + } let progress = LaunchPreparation { adapter: "auto".into(), ..Default::default() }; let result = pso_corpus::discover(path) .and_then(|c| c.ok_or_else(|| "No pipeline corpus found in this title folder".to_string())) diff --git a/crates/xcl/src/shaders/pso_corpus.rs b/crates/xcl/src/shaders/pso_corpus.rs index a2b564fe7b..9accff8cd2 100644 --- a/crates/xcl/src/shaders/pso_corpus.rs +++ b/crates/xcl/src/shaders/pso_corpus.rs @@ -1,5 +1,5 @@ //! A staged set of native graphics and compute recipes, shared by startup and offline preparation. -use super::{gfx_records, graphics_summary, progress_count, recomp, worker_command, LaunchPreparation, Pipelines}; +use super::{graphics_summary, progress_count, recomp, worker_command, LaunchPreparation, Pipelines}; use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -23,16 +23,16 @@ pub(crate) fn discover(root: &Path) -> Result, String> { let encoded = encoded.trim().parse::().map_err(|_| "Invalid corpus memory window count")?; let count = (encoded & 127) as usize; let heap = encoded & 128 != 0; - if !recomp::valid_window_count(count, heap) || heap && count <= 1 { + if count == 0 || !recomp::valid_window_count(count, heap) || heap && count <= 1 { return Err(format!("Invalid corpus memory window configuration {encoded}")); } let windows = count as u32 | if heap { recomp::HEAP_WINDOWS } else { 0 }; let path = dir.join("graphics.bin"); let graphics = if path.try_exists().map_err(|e| e.to_string())? { - let entries = gfx_records::read_job(&path)?; - let count = entries.iter().filter(|e| !matches!(e, gfx_records::Entry::Shader(..))).count(); - if count == 0 { return Err("Graphics job contains no pipeline records".into()); } - Some((path, count)) + if expected[0] == 0 { return Err("Unexpected graphics job in compute-only corpus".into()); } + // The worker validates and decodes the job. Require its independent native-success + // count to match the marker before handoff, without loading the job twice. + Some((path, expected[0])) } else { None }; let mut compute = Vec::new(); let folder = dir.join("compute"); @@ -65,7 +65,8 @@ impl Corpus { pub(super) fn prepare_with_threads(&self, progress: &LaunchPreparation, requested: Option) -> Result<(), String> { let graphics_count = self.graphics.as_ref().map_or(0, |(_, n)| *n); - progress.begin_corpus(graphics_count + self.compute.len()); + let total = graphics_count.checked_add(self.compute.len()).ok_or("Pipeline corpus count overflow")?; + progress.begin_corpus(total); let count = self.windows & !recomp::HEAP_WINDOWS; let runtime = crate::gpu::uma::configured_runtime_windows(); if count as usize != runtime || (self.windows & recomp::HEAP_WINDOWS != 0) != (runtime > 1 && recomp::pso::heap_windows()) { @@ -182,5 +183,7 @@ mod tests { assert_eq!(corpus.windows, 1); std::fs::write(dir.join("windows"), "255").unwrap(); assert!(discover(&root).is_err()); + std::fs::write(dir.join("windows"), "0").unwrap(); + assert!(discover(&root).is_err()); } } diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index aa4964eea1..75bd96cd81 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -60,12 +60,20 @@ fn incomplete_discovered_corpus_blocks_headless_title_entry() { let settings = data.join("XCL.TestTitle"); std::fs::create_dir_all(&settings).unwrap(); std::fs::write(settings.join("xcl.toml"), "graphics='null'\npresent='off'\n").unwrap(); - let out = Command::new(xcl).arg("run").arg(&game).env("XCL_DATA_ROOT", &data) + let launch = || Command::new(xcl).arg("run").arg(&game).env("XCL_DATA_ROOT", &data) .env("XCL_PREPARE", "0").env("XCL_PREPARE_GRAPHICS", "0").output().unwrap(); + let out = launch(); assert!(!out.status.success(), "An incomplete corpus released the guest"); let log = std::fs::read_to_string(settings.join("logs/xcl.log")).unwrap(); assert!(log.contains("Incomplete pipeline corpus"), "{log}"); assert!(!log.contains("game entry point returned"), "{log}"); + std::fs::remove_dir(game.join(".xcl/pso-corpus")).unwrap(); + std::fs::create_dir_all(settings.join("cache")).unwrap(); + std::fs::write(settings.join("cache/used-graphics-pipelines.bin"), b"bad history").unwrap(); + assert!(!launch().status.success()); + let log = std::fs::read_to_string(settings.join("logs/xcl.log")).unwrap(); + assert!(log.contains("unrecognized graphics job header"), "{log}"); + assert!(!log.contains("game entry point returned"), "{log}"); } struct TempDir(PathBuf); diff --git a/scripts/pso_corpus/stage.py b/scripts/pso_corpus/stage.py index 2622477eaa..6e2723f486 100644 --- a/scripts/pso_corpus/stage.py +++ b/scripts/pso_corpus/stage.py @@ -181,7 +181,8 @@ def build(journals, dest, spool, records): if tag == "S": require(win == 0 and data, "invalid shader frame") else: - require(1 <= (win & 127) <= (16 if win & 128 else 4), "invalid window count") + count = win & 127 + require(count in ((2, 3, 4, 8, 16) if win & 128 else (1, 2, 3, 4)), "invalid window count") digest = hashlib.sha256(data).digest() identity = tag, key if identity in seen: diff --git a/scripts/pso_corpus/test_stage.py b/scripts/pso_corpus/test_stage.py index d89230f3f4..d9259eb4a3 100644 --- a/scripts/pso_corpus/test_stage.py +++ b/scripts/pso_corpus/test_stage.py @@ -87,6 +87,7 @@ def test_invalid_frames_never_publish(self): [self.src, frame("G", overflow)], [self.src, good, frame("G", graphic(self.key), 4)], [self.src[:-1] + b"X", good], [self.src, good[:-1] + b"X"], [self.src, frame("C", compute(self.key, 2))], + [self.src, frame("C", compute(self.key, 0), 133)], [self.src, frame("M", struct.pack(" Date: Thu, 26 Nov 2026 11:15:44 -0500 Subject: [PATCH 5/6] Shaders: prepare exact pack and history overlaps once at startup Match shader bytes and full graphics descriptors against the mandatory staged job. Keep distinct fixed-state variants and resolve their shader inputs from the staged corpus. A 48-recipe overlap fixture removed 48 redundant native submissions before the staged pass. --- README.md | 1 + crates/xcl/src/hle/d3d12x/gfx_records.rs | 27 ++- crates/xcl/src/shaders.rs | 235 +++++++++++++++++++++-- crates/xcl/src/shaders/pso_corpus.rs | 16 ++ 4 files changed, 253 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 93544ac4d3..8bf0e8ada4 100644 --- a/README.md +++ b/README.md @@ -256,6 +256,7 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. ``` The offline command accepts up to 32 workers. Normal launch also prepares the staged corpus. + When a shader pack or local history overlaps the corpus, XCL prepares each exact match once. Use the same adapter and memory-window configuration for offline preparation and play so the driver can reuse the results. Graphics state combinations absent from the supplied recipes and local history can still diff --git a/crates/xcl/src/hle/d3d12x/gfx_records.rs b/crates/xcl/src/hle/d3d12x/gfx_records.rs index 46a8c8f939..da67c08765 100644 --- a/crates/xcl/src/hle/d3d12x/gfx_records.rs +++ b/crates/xcl/src/hle/d3d12x/gfx_records.rs @@ -484,7 +484,7 @@ pub(crate) fn read(path: &Path) -> Vec> { /// A completed worker job must contain only whole, supported records. A history file /// may be open for appends, so its reader above accepts a trailing partial entry. -fn read_complete(path: &Path, mut take: impl FnMut(&[u8], Entry) -> T) -> Result, String> { +pub(crate) fn visit_payloads(path: &Path, mut visit: impl FnMut(&[u8]) -> Result<(), String>) -> Result<(), String> { use std::io::{BufReader, Read}; let file = std::fs::File::open(path).map_err(|e| e.to_string())?; let size = file.metadata().map_err(|e| e.to_string())?.len(); @@ -494,7 +494,6 @@ fn read_complete(path: &Path, mut take: impl FnMut(&[u8], Entry) -> T) -> Res return Err("unrecognized graphics job header".into()); } let mut offset = HEADER as u64; - let mut entries = Vec::new(); let mut payload = Vec::new(); while offset < size { let damaged = || format!("damaged graphics job at byte {offset}"); @@ -506,10 +505,26 @@ fn read_complete(path: &Path, mut take: impl FnMut(&[u8], Entry) -> T) -> Res payload.resize(len, 0); reader.read_exact(&mut payload).map_err(|_| damaged())?; if check(&payload) != u32::from_le_bytes(frame[4..].try_into().unwrap()) { return Err(damaged()); } - let entry = decode(&payload).ok_or_else(|| format!("invalid graphics job entry {}", entries.len() + 1))?; - entries.push(take(&payload, entry)); + visit(&payload)?; offset += 8 + len as u64; } + Ok(()) +} + +pub(crate) fn shader_payload(payload: &[u8]) -> Option<(u64, &[u8])> { + let (&tag, rest) = payload.split_first()?; + if tag != SHADER { return None; } + let mut r = Reader(rest); + Some((r.u64()?, r.0)) +} + +fn read_complete(path: &Path, mut take: impl FnMut(&[u8], Entry) -> T) -> Result, String> { + let mut entries = Vec::new(); + visit_payloads(path, |bytes| { + let entry = decode(bytes).ok_or_else(|| format!("invalid graphics job entry {}", entries.len() + 1))?; + entries.push(take(bytes, entry)); + Ok(()) + })?; Ok(entries) } @@ -607,7 +622,7 @@ pub(crate) fn note(payload: Vec) { let mut w = match Writer::open(&path, cap) { Ok(w) => w, Err(e) => { - crate::xlog_warn!("D3D12.X: {}: {e} – the graphics pipelines of this run are not prepared before the next", path.display()); + crate::xlog_warn!("D3D12.X: {}: {e} – the graphics pipelines of this run are not prepared before the next", path.display()); return; } }; @@ -622,7 +637,7 @@ pub(crate) fn note(payload: Vec) { } Ok(_) => {} Err(e) => { - crate::xlog_warn!("D3D12.X: {}: {e} – no more graphics pipelines are recorded in this run", path.display()); + crate::xlog_warn!("D3D12.X: {}: {e} – no more graphics pipelines are recorded in this run", path.display()); return; } } diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 9ab11d97a2..e01a94fc1e 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1016,7 +1016,11 @@ pub fn run(path: &Path, args: &[String]) -> i32 { let used = opts.used_only.then(crate::hle::d3d12x::pso_async::earlier_used_keys); // the runtime's key: heap windows with `XCL_HEAP_WINDOWS=1` (`pso::mem_windows`) let windows = runtime_windows(); - return match precompile(&input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, used.as_ref(), t0, None) { + let coverage = match ComputeCoverage::worker() { + Ok(coverage) => coverage, + Err(e) => { eprintln!("xcl shaders: {e}"); return 2; } + }; + return match precompile(&input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, used.as_ref(), t0, None, coverage.as_ref()) { Ok(()) => 0, Err(e) => { eprintln!("xcl shaders: {e}"); 2 } }; @@ -1747,7 +1751,7 @@ fn loose_inputs(dir: &Path, files: &mut Vec) -> std::io::Result<()> { pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> Result<(), String> { let corpus = pso_corpus::discover(root)?; - prepare_title_inputs(root, progress)?; + prepare_title_inputs(root, progress, corpus.as_ref())?; if let Some(corpus) = corpus { corpus.prepare(progress)?; progress.check_corpus_complete()?; @@ -1755,7 +1759,7 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R Ok(()) } -fn prepare_title_inputs(root: &Path, progress: &LaunchPreparation) -> Result<(), String> { +fn prepare_title_inputs(root: &Path, progress: &LaunchPreparation, corpus: Option<&pso_corpus::Corpus>) -> Result<(), String> { let mut inputs = Vec::new(); let pack = root.join("shaders.rpf"); if pack.try_exists().map_err(|e| e.to_string())? { @@ -1776,20 +1780,95 @@ fn prepare_title_inputs(root: &Path, progress: &LaunchPreparation) -> Result<(), if windows > 1 && recomp::pso::heap_windows() { windows |= recomp::HEAP_WINDOWS; } let workers = prepare_workers(); for input in &inputs { + let coverage = corpus.filter(|c| c.compute_directory().is_some()) + .map(|corpus| ComputeCoverage::Published(corpus, Mutex::default(), AtomicUsize::new(0))); if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } // a pack: its stages here, its compute pipelines in worker processes (the driver builds // about two pipelines at a time for one process, whatever the processors) if workers > 1 && matches!(input, Input::Pack { .. }) { let n = input.len(); - precompile(input, usize::MAX, windows, None, None, false, None, std::time::Instant::now(), Some(progress))?; + precompile(input, usize::MAX, windows, None, None, false, None, std::time::Instant::now(), Some(progress), coverage.as_ref())?; if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } - pipelines_in_workers(&pack, windows, workers, n, progress)?; + if coverage.as_ref().is_some_and(ComputeCoverage::all_staged) { continue; } + pipelines_in_workers(&pack, windows, workers, n, progress, coverage.as_ref())?; continue; } - precompile(input, usize::MAX, windows, None, None, true, None, std::time::Instant::now(), Some(progress))?; + precompile(input, usize::MAX, windows, None, None, true, None, std::time::Instant::now(), Some(progress), coverage.as_ref())?; } if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } - graphics_in_workers(&inputs, windows, workers, progress) + graphics_in_workers(&inputs, windows, workers, progress, corpus.and_then(|c| c.graphics_path())) +} + +/// Only records verified byte-for-byte against the discovered corpus may leave their native +/// preparation to that pass. A worker also checks the index, key and bytes of its own pack. +enum ComputeCoverage<'a> { + Published(&'a pso_corpus::Corpus, Mutex>, AtomicUsize), + Slice(PathBuf, BTreeMap), +} + +const COVERAGE_MAP: &str = "XCL_PRECOMPILE_COVERAGE_MAP"; +const COVERAGE_DIR: &str = "XCL_PRECOMPILE_COVERAGE_DIR"; + +struct CoverageFile(PathBuf); +impl Drop for CoverageFile { + fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); } +} + +impl ComputeCoverage<'_> { + fn all_staged(&self) -> bool { + matches!(self, Self::Published(_, _, remaining) if remaining.load(Ordering::Relaxed) == 0) + } + + fn covers(&self, index: usize, blob: &[u8]) -> Result { + let key = shader::fnv64(blob); + let path = match self { + Self::Published(corpus, _, remaining) => match corpus.compute_path(key) { + Some(path) => path.to_path_buf(), + None => { remaining.fetch_add(1, Ordering::Relaxed); return Ok(false); } + }, + Self::Slice(dir, keys) if keys.get(&index) == Some(&key) => dir.join(format!("{key:016x}.dxbc")), + Self::Slice(..) => return Ok(false), + }; + let staged = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?; + if blob != staged { + if shader::fnv64(&staged) != key { return Err(format!("Staged compute shader {key:016x} changed")); } + if let Self::Published(_, _, remaining) = self { remaining.fetch_add(1, Ordering::Relaxed); } + return Ok(false); + } + if let Self::Published(_, selected, _) = self { selected.lock().unwrap().insert(index, key); } + Ok(true) + } + + fn slice_file(&self) -> Result, String> { + use std::io::Write; + let Self::Published(corpus, selected, _) = self else { return Ok(None) }; + let Some(dir) = corpus.compute_directory() else { return Ok(None) }; + let selected = selected.lock().unwrap(); + if selected.is_empty() { return Ok(None); } + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|e| e.to_string())?.as_nanos(); + let path = std::env::temp_dir().join(format!("xcl-compute-coverage-{}-{nonce}.bin", std::process::id())); + let mut file = std::fs::File::create_new(&path).map_err(|e| e.to_string())?; + let cleanup = CoverageFile(path); + let mut bytes = Vec::with_capacity(selected.len()*16); + for (&i, &key) in selected.iter() { bytes.extend_from_slice(&(i as u64).to_le_bytes()); bytes.extend_from_slice(&key.to_le_bytes()); } + file.write_all(&bytes).map_err(|e| e.to_string())?; + Ok(Some((cleanup, dir))) + } + + fn worker() -> Result, String> { + if std::env::var_os("XCL_PRECOMPILE_PARENT").is_none() { return Ok(None); } + let Some(path) = std::env::var_os(COVERAGE_MAP) else { return Ok(None) }; + let dir = std::env::var_os(COVERAGE_DIR).ok_or("Missing staged compute directory for worker")?; + Self::read_slice(Path::new(&path), PathBuf::from(dir)).map(Some) + } + + fn read_slice(path: &Path, dir: PathBuf) -> Result { + let bytes = std::fs::read(path).map_err(|e| e.to_string())?; + if bytes.len() % 16 != 0 { return Err("Incomplete compute worker coverage map".into()); } + let keys = bytes.chunks_exact(16).map(|b| (u64::from_le_bytes(b[..8].try_into().unwrap()) as usize, + u64::from_le_bytes(b[8..].try_into().unwrap()))).collect(); + Ok(Self::Slice(dir, keys)) + } } /// `XCL_PREPARE_WORKERS`: the processes that build a pack's compute pipelines before a title @@ -1875,16 +1954,16 @@ mod claim_tests { } /// The compute pipelines of `pack` built by `workers` processes of this program, each on its own -/// slice of the records (`XCL_PRECOMPILE_SLICE`): only the ones an earlier run of the title used -/// when that list exists (the title builds another when it first uses it). Their records count -/// into `progress`. A worker that fails is noted and the title starts all the same: it builds -/// what is missing itself. -fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usize, progress: &LaunchPreparation) -> Result<(), String> { +/// slice of the records (`XCL_PRECOMPILE_SLICE`). A failed worker prevents guest entry. +fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usize, progress: &LaunchPreparation, + coverage: Option<&ComputeCoverage>) -> Result<(), String> { let me = std::env::current_exe().map_err(|e| e.to_string())?; + let map = coverage.map(|c| c.slice_file()).transpose()?.flatten(); let t0 = std::time::Instant::now(); crate::xlog_info!("Shader preparation: compute pipelines in {workers} worker processes"); let (cancelled, failed, _) = in_workers(workers, records, progress, |i| { let mut c = worker_command(&me); + if let Some((file, dir)) = &map { c.env(COVERAGE_MAP, &file.0).env(COVERAGE_DIR, dir); } c.arg("shaders").arg(pack).args(["--precompile", "--only", "cs", "--pipelines", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); if std::env::var_os("XCL_ADAPTER").is_none() && !progress.adapter.is_empty() { c.env("XCL_ADAPTER", &progress.adapter); } c.env("XCL_PRECOMPILE_SLICE", format!("{i}/{workers}")); @@ -1902,7 +1981,7 @@ fn worker_command(me: &Path) -> std::process::Command { use std::os::windows::process::CommandExt; const CREATE_NO_WINDOW: u32 = 0x0800_0000; let mut c = std::process::Command::new(me); - for gone in ["XCL_HOST", "XCL_PREPARATION_PARENT", "XCL_PREPARATION_MENU", "XCL_RUN_SECONDS"] { c.env_remove(gone); } + for gone in ["XCL_HOST", "XCL_PREPARATION_PARENT", "XCL_PREPARATION_MENU", "XCL_RUN_SECONDS", COVERAGE_MAP, COVERAGE_DIR] { c.env_remove(gone); } c.env("XCL_PRECOMPILE_PARENT", std::process::id().to_string()); if std::env::var_os("XCL_DXC_THREADS").is_none() { c.env("XCL_DXC_THREADS", "2"); } if std::env::var_os("XCL_PIPELINE_THREADS").is_none() { c.env("XCL_PIPELINE_THREADS", "1"); } @@ -1979,9 +2058,8 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut /// worker processes as the compute pipelines: the driver builds about two pipelines at a time for /// one process, and a driver that ends a worker ends no title. Their shaders come from the title's /// shader files (`inputs`) by key, as those of `used-shaders.txt`; each worker gets a file of its -/// part (`gfx_records`' format, with the shaders it needs). A failure is noted and the title -/// starts all the same: it builds what is missing itself. -fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: &LaunchPreparation) -> Result<(), String> { +/// part (`gfx_records`' format, with the shaders it needs). A worker must confirm every recipe. +fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: &LaunchPreparation, staged_graphics: Option<&Path>) -> Result<(), String> { let t0 = std::time::Instant::now(); let path = gfx_records::path(); let local = if path.try_exists().map_err(|e| e.to_string())? { gfx_records::read_complete_payloads(&path)? } else { Vec::new() }; @@ -1998,7 +2076,7 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: entry => if let Some(record) = GraphicsHistoryRecord::from_entry(entry) { records.push((payload, record)); }, } } - let local_count = records.len(); + let mut local_count = records.len(); let legacy = gfx_records::shared_history_path(); if !inputs.is_empty() && legacy != path { let scoped: HashSet<_> = records.iter().map(|(bytes, _)| bytes.as_slice()).collect(); @@ -2010,9 +2088,17 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: crate::xlog_info!("Shader preparation: no graphics pipelines of an earlier run to build"); return Ok(()); } - let wanted = records.iter().flat_map(|(_, record)| record.identity().1.iter().copied()) + if let Some(staged) = staged_graphics { + let before = records.len(); + local_count = merge_staged_history(staged, &mut records, local_count, &mut embedded)?; + if before != records.len() { + crate::xlog_info!("Shader preparation: the mandatory staged job covers {} exact graphics history recipes", before - records.len()); + } + if records.is_empty() { return Ok(()); } + } + let wanted: HashSet<_> = records.iter().flat_map(|(_, record)| record.identity().1.iter().copied()) .filter(|&key| key != 0 && !embedded.contains_key(&key)).collect(); - let mut shaders = shaders_by_key(inputs, wanted, progress); + let mut shaders = if wanted.is_empty() { HashMap::new() } else { shaders_by_key(inputs, wanted, progress) }; shaders.extend(embedded); if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } let (buildable, missing) = buildable(records.iter().map(|(_, r)| r), &shaders); @@ -2065,6 +2151,33 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: Ok(()) } +/// Only identical serialized descriptors can be left for the subsequent mandatory staged job. +fn merge_staged_history( + staged: &Path, records: &mut Vec<(Vec, GraphicsHistoryRecord)>, local_count: usize, + embedded: &mut HashMap>, +) -> Result { + let mut covered: HashMap<&[u8], bool> = records.iter().map(|(p, _)| (p.as_slice(), false)).collect(); + let wanted: HashSet = records.iter().flat_map(|(_, r)| r.identity().1.iter().copied()).filter(|k| *k != 0).collect(); + gfx_records::visit_payloads(staged, |payload| { + if let Some((key, code)) = gfx_records::shader_payload(payload) { + if wanted.contains(&key) { + if crate::hle::d3d12x::real::shader_key(code) != key || embedded.get(&key).is_some_and(|prior| prior.as_slice() != code) { + return Err(format!("Staged graphics shader {key:016x} failed its identity check")); + } + embedded.entry(key).or_insert_with(|| code.to_vec()); + } + } else if let Some(present) = covered.get_mut(payload) { + *present = true; + } + Ok(()) + })?; + let keep: Vec = records.iter().map(|(p, _)| !covered[p.as_slice()]).collect(); + let remaining_local = keep[..local_count].iter().filter(|&&k| k).count(); + let mut keep = keep.into_iter(); + records.retain(|_| keep.next().unwrap()); + Ok(remaining_local) +} + /// The bytes of the shaders `wanted` (`real::shader_key`) in the title's shader files, looked /// for on every processor. fn shaders_by_key(inputs: &[Input], wanted: HashSet, progress: &LaunchPreparation) -> std::collections::HashMap> { @@ -2232,7 +2345,7 @@ fn end_with_parent() { }); } -fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> { +fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant, startup: Option<&LaunchPreparation>, coverage: Option<&ComputeCoverage>) -> Result<(), String> { if startup.is_none() { end_with_parent(); } let mandatory = startup.is_some() || std::env::var_os("XCL_PRECOMPILE_PARENT").is_some(); let pipelines = if pipelines { @@ -2316,6 +2429,19 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on // a compute program as a title's pipeline translates it (`pso::console_to_dxil_in`): // into the translation cache too, so the title does not translate it again if sh.fssm.iter().any(|f| matches!(recomp::interface(&blob, &sh, f), Some(recomp::Mode::Compute(_)))) { + if let Some(coverage) = coverage { + match coverage.covers(i, &blob) { + Ok(true) => { record_done(); continue; } + Err(e) => { + failed.fetch_add(1, Ordering::Relaxed); + let mut logs = errors.lock().unwrap(); + if logs.len() < 10 { logs.push(format!("{name}: {e}")); } + record_done(); + continue; + } + Ok(false) => {} + } + } if used.is_some_and(|u| !used_compute(&blob, u)) { unused.fetch_add(1, Ordering::Relaxed); record_done(); @@ -2403,6 +2529,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on }); let failed = failed.into_inner(); let skipped_reason = if startup.is_some() { "runtime pairing or unsupported translation" } else { "GS – paired at pipeline creation" }; + if let Some(ComputeCoverage::Published(_, selected, _)) = coverage { + let count = selected.lock().unwrap().len(); + if count != 0 { crate::xlog_info!("Shader preparation: {count} byte-matched compute records will be built by the staged corpus"); } + } println!( "compiled {}, already cached {}, errors {}, skipped ({skipped_reason}) {}, time {:.1} s", compiled.into_inner(), @@ -2838,6 +2968,40 @@ mod tests { assert_eq!(buildable(records.iter(), &shaders), (vec![0, 1, 4], 3)); } + #[test] + fn staged_history_defers_exact_recipes_and_supplies_sources_for_other_variants() { + use crate::hle::d3d12x::real::shader_key; + use windows::Win32::Graphics::Direct3D12::D3D12_GRAPHICS_PIPELINE_STATE_DESC; + let path = std::env::temp_dir().join(format!("xcl-staged-history-{}.bin", std::process::id())); + let _ = std::fs::remove_file(&path); + let code = b"vertex source"; + let key = shader_key(code); + let pipeline = |mask| { + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { SampleMask: mask, ..Default::default() }; + let payload = unsafe { gfx_records::encode(key, [key, 0, 0, 0, 0], &desc) }; + let record = GraphicsHistoryRecord::from_entry(gfx_records::decode(&payload).unwrap()).unwrap(); + (payload, record) + }; + let mut records = vec![pipeline(1), pipeline(2), pipeline(1), pipeline(3)]; + { + let mut staged = gfx_records::Writer::open(&path, u64::MAX).unwrap(); + staged.add(&records[0].0).unwrap(); + staged.add(&gfx_records::shader_entry(key, code)).unwrap(); + } + let mut sources = HashMap::new(); + assert_eq!(merge_staged_history(&path, &mut records, 2, &mut sources).unwrap(), 1); + assert_eq!(records.len(), 2); + assert_eq!(records[0].0, pipeline(2).0); + assert_eq!(records[1].0, pipeline(3).0); + assert_eq!(buildable(records.iter().map(|(_, r)| r), &sources), (vec![0, 1], 0)); + { + let mut staged = gfx_records::Writer::open(&path, u64::MAX).unwrap(); + staged.add(&gfx_records::shader_entry(key, b"wrong")).unwrap(); + } + assert!(merge_staged_history(&path, &mut records, 1, &mut sources).unwrap_err().contains("identity check")); + std::fs::remove_file(path).unwrap(); + } + #[test] fn a_graphics_job_with_a_missing_or_incorrectly_named_shader_fails() { use crate::hle::d3d12x::gfx_records::{encode_mesh, shader_entry, Writer}; @@ -2894,6 +3058,37 @@ mod tests { sample(5, &[compute]) } + #[test] + fn staged_compute_covers_only_its_exact_sources_in_loose_and_pack_passes() { + let name = format!("xcl-compute-membership-{}-{}", std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()); + let root = std::env::temp_dir().join(name); + let base = root.join(".xcl/pso-corpus"); + let dir = base.join("compute"); + std::fs::create_dir_all(&dir).unwrap(); + let blob = compute_sample(); + let file = dir.join(format!("{:016x}.dxbc", shader::fnv64(&blob))); + std::fs::write(&file, &blob).unwrap(); + std::fs::write(base.join("windows"), "4").unwrap(); + std::fs::write(base.join("complete"), "0 1").unwrap(); + let corpus = pso_corpus::discover(&root).unwrap().unwrap(); + let parent = ComputeCoverage::Published(&corpus, Mutex::default(), AtomicUsize::new(0)); + assert!(parent.covers(3, &blob).unwrap()); + assert!(parent.all_staged(), "no compute slice workers needed"); + assert!(!parent.covers(6, b"different source").unwrap()); + assert!(!parent.all_staged(), "uncovered compute records still need the slice"); + let (map, directory) = parent.slice_file().unwrap().unwrap(); + let child = ComputeCoverage::read_slice(&map.0, directory.to_owned()).unwrap(); + assert!(child.covers(3, &blob).unwrap()); + assert!(!child.covers(7, &blob).unwrap(), "index absent from the checked pack"); + assert!(!child.covers(3, b"changed input").unwrap(), "parent and child pack differ"); + std::fs::write(&file, b"changed after discovery").unwrap(); + assert!(child.covers(3, &blob).is_err(), "corrupt staged data cannot satisfy a recipe"); + std::fs::remove_file(&file).unwrap(); + assert!(parent.covers(3, &blob).is_err(), "missing staged data cannot satisfy a recipe"); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] fn record_hash_is_strict_hex() { assert_eq!(parse_record_hash("0x0123aB").unwrap(), 0x123AB); diff --git a/crates/xcl/src/shaders/pso_corpus.rs b/crates/xcl/src/shaders/pso_corpus.rs index 9accff8cd2..bb361f2c35 100644 --- a/crates/xcl/src/shaders/pso_corpus.rs +++ b/crates/xcl/src/shaders/pso_corpus.rs @@ -59,6 +59,19 @@ pub(crate) fn discover(root: &Path) -> Result, String> { } impl Corpus { + pub(super) fn graphics_path(&self) -> Option<&Path> { + self.graphics.as_ref().map(|(path, _)| path.as_path()) + } + + pub(super) fn compute_path(&self, key: u64) -> Option<&Path> { + let i = self.compute.binary_search_by_key(&key, |(key, _)| *key).ok()?; + Some(self.compute[i].1.as_path()) + } + + pub(super) fn compute_directory(&self) -> Option<&Path> { + self.compute.first().and_then(|(_, path)| path.parent()) + } + pub(crate) fn prepare(&self, progress: &LaunchPreparation) -> Result<(), String> { self.prepare_with_threads(progress, None) } @@ -180,6 +193,9 @@ mod tests { std::fs::write(dir.join("compute/0000000000000010.dxbc"), []).unwrap(); let corpus = discover(&root).unwrap().unwrap(); assert_eq!(corpus.compute[0].0, 16); + assert_eq!(corpus.compute_path(16), Some(dir.join("compute/0000000000000010.dxbc").as_path())); + assert!(corpus.compute_path(17).is_none()); + assert!(corpus.graphics_path().is_none()); assert_eq!(corpus.windows, 1); std::fs::write(dir.join("windows"), "255").unwrap(); assert!(discover(&root).is_err()); From 1eb656b4b1af9daa9c71a612bd84995f2b8d9c3c Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:19:32 -0500 Subject: [PATCH 6/6] Shaders: keep the launch owner responsible for the whole input Limit record slicing to offline workers. An inherited slice from an earlier CLI run must not make the launch gate overlook an unstaged shader. --- crates/xcl/src/shaders.rs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index e01a94fc1e..6855d39435 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -2345,6 +2345,12 @@ fn end_with_parent() { }); } +fn precompile_slice(startup_owner: bool, value: Option<&str>) -> Option<(usize, usize)> { + if startup_owner { return None; } + let (i, n) = value?.split_once('/')?; + Some((i.trim().parse().ok()?, n.trim().parse::().ok().filter(|n| *n > 0)?)) +} + fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant, startup: Option<&LaunchPreparation>, coverage: Option<&ComputeCoverage>) -> Result<(), String> { if startup.is_none() { end_with_parent(); } let mandatory = startup.is_some() || std::env::var_os("XCL_PRECOMPILE_PARENT").is_some(); @@ -2362,10 +2368,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on let n = input.len().min(limit); // `XCL_PRECOMPILE_SLICE=i/n` (experiment): this process takes only every n-th shader, from the // i-th, so n processes share the work and each has its own driver compiler - let slice: Option<(usize, usize)> = std::env::var("XCL_PRECOMPILE_SLICE").ok().and_then(|v| { - let (i, n) = v.split_once('/')?; - Some((i.trim().parse().ok()?, n.trim().parse::().ok().filter(|n| *n > 0)?)) - }); + let slice = precompile_slice(startup.is_some(), std::env::var("XCL_PRECOMPILE_SLICE").ok().as_deref()); // a progress line every 200 records; every record for a title waiting on this builder // (`pipelines_in_workers` shows the count) let every = if std::env::var_os("XCL_PRECOMPILE_PARENT").is_some() { 1 } else { 200 }; @@ -3089,6 +3092,16 @@ mod tests { std::fs::remove_dir_all(root).unwrap(); } + #[test] + fn launch_owner_ignores_inherited_slices_and_workers_drop_foreign_coverage() { + assert_eq!(precompile_slice(true, Some("1/2")), None); + assert_eq!(precompile_slice(false, Some("1/2")), Some((1, 2))); + let command = worker_command(Path::new("xcl.exe")); + for name in [COVERAGE_MAP, COVERAGE_DIR] { + assert!(command.get_envs().any(|(key, value)| key == name && value.is_none())); + } + } + #[test] fn record_hash_is_strict_hex() { assert_eq!(parse_record_hash("0x0123aB").unwrap(), 0x123AB);