diff --git a/HANDOFF.md b/HANDOFF.md index 1ea85d8..aafe48d 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1151,6 +1151,17 @@ of the title (it writes to address 0 after a failed D3D12 call: `call 0x14068c76 helper lanes, so they never stop. Ballots (v_cmp) still leave helper lanes out (matters for branches inside whole-quad sections). The console sets IASetPrimitiveTopology 17 (rectangle lists) for these quads; the AMD driver draws them as two triangles here – rectangle lists are not modelled otherwise. +- **Helper lanes of other quads (fixed, 2026-11-22)**: Minecraft's Ore UI (create-world screen) had white dashed + bands along the shared diagonal and the edges of its image and text quads, in runs as wide as a wave. Its UI pixel + shader (Renoir) reads the draw type with `v_readfirstlane` after `s_wqm`; the first lane of EXEC is often a helper + lane on a primitive's edge, and a wave read of another quad's helper lane is undefined before SM 6.7 (0 in + practice): the wave's other quads took the type-0 branch (a solid quad in the vertex colour). `rla` now takes + such a lane's value with a quad read inside its own quad and a wave read from a live lane of that quad. Also from + this work: an ISG1 input the VS never reads gets no fetch-shader VGPRs (`fetched_registers` – the create-world + screen drew nothing); a placed texture larger on the PC than its console size gets memory of its own (Minecraft + ended with 0xC0000409); PLS is a drive root (`S:\`) and the disk-space APIs answer for console paths ("very little + free space"). Diagnostics: `XCL_TRACE_SHADERS`, `XCL_TRACE_MANY`, `XCL_FRAME_DUMP_FULL`, `XCL_DEBUG_PS_SUB`, + `XCL_DEBUG_PS_EXPR`, `XCL_DEBUG_MAGENTA`, `XCL_DEBUG_LOD0`, `XCL_DEBUG_NO_STENCIL` / `NO_CULL`, `XCL_PRESS_AT`. - **Why every frame was black: descriptors are values.** XDefiant makes its views in a CPU-only heap (131 072 slots) and copies them into its shader-visible heap (442 368 slots) as memory – the console header's inline CopyDescriptorsSimple; only sampler copies reach the device. T# word 0 was an index into each heap's own PC heap, diff --git a/README.md b/README.md index 0bb6701..0c73a0a 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,28 @@ # XCL – Xbox Series X|S → Windows compatibility layer +[![Discord](https://img.shields.io/badge/Discord-join%20the%20server-5865F2?logo=discord&logoColor=white)](https://discord.gg/yB5tstRHrn) +**Discord: ** + XCL runs Xbox Series X|S (GDK) game files on a Windows PC **without CPU emulation**: the game's x64 code runs natively and XCL stands in for the console libraries the PC does not have (`kernelx.dll`, XGameRuntime, `d3d12_xs.dll`, …) – in the spirit of Wine/Proton. The console's GPU code (RDNA2 machine code) is recompiled into PC shaders (HLSL → DXIL). -**Project state:** the foundation is in place and tested against real data from a retail game -(its shader pack, texture archive, movies and the 16 console DLLs it ships). What remains before a -game shows its first frame is the graphics submission path – draws and present use the console's -own D3D12.X command format, which can only be worked out from a game executable. Details, -measurements and next steps: +**Project state:** retail games run their menus – see [Games](#games). The foundation is tested +against real data from retail games (shader packs, texture archives, movies and the console DLLs +they ship). Details, measurements and next steps: [`HANDOFF.md`](HANDOFF.md); design: [`docs/specs/2026-11-20-xcl-design.md`](docs/specs/2026-11-20-xcl-design.md). +## Games + +| Game | Package (version) | State | What works | Limits | +|---|---|---|---|---| +| **Minecraft Preview** | `Microsoft.MinecraftBeta` 1.18.3064.0 | ✅ menus | the whole menu, sound and controller input – fully | offline: no Xbox Live sign-in, Realms or Marketplace | +| **Fortnite** | `436609B6.FortniteClient` 2.0.1461.7919 | ✅ menus | everything up to the point where the game needs its online services – fully | the game itself needs multiplayer (online servers), so it cannot be tested further | +| **XDefiant** | `Ubisoft.XDefiant-Game` 1.0.0.186 | ✅ menus | the menu – fully | the game's servers are shut down, so it cannot be tested further | + +XCL stays offline: no fake Xbox Live, sign-in, game backends or licences. + ## Highlights - **100 % of a retail game's shaders translate** – all 26 698 RDNA2 programs (26 503 records) of its shader pack diff --git a/crates/xcl/src/config.rs b/crates/xcl/src/config.rs index 5eeaad5..242650f 100644 --- a/crates/xcl/src/config.rs +++ b/crates/xcl/src/config.rs @@ -109,6 +109,22 @@ impl Config { } } +/// Mount target of the persistent local storage drive (`XPersistentLocalStorageGetPath`). +pub const PLS_MOUNT_TARGET: &str = "{data}\\pls"; + +impl Config { + /// The console drive the title is given as its persistent local storage root ("S:\"): + /// the drive-letter mount onto `{data}\pls`. None when the mounts have no such drive. + pub fn pls_drive(&self) -> Option { + self.mounts.iter().find_map(|(prefix, target)| { + let b = prefix.as_bytes(); + let target = target.replace('/', "\\"); + let is_drive = b.len() == 2 && b[0].is_ascii_alphabetic() && b[1] == b':'; + (is_drive && target.trim_end_matches('\\').eq_ignore_ascii_case(PLS_MOUNT_TARGET)).then(|| format!("{}\\", prefix.to_ascii_uppercase())) + }) + } +} + impl Default for Config { fn default() -> Self { let mut mounts = BTreeMap::new(); @@ -117,6 +133,8 @@ impl Default for Config { // the package drive of the XDK days, still used by GDK titles (XDefiant: d:\hunter\...) mounts.insert("D:".into(), "{game}".into()); mounts.insert("T:".into(), "{data}\\temp".into()); + // persistent local storage: on the console a folder mounted at the root of a drive + mounts.insert("S:".into(), PLS_MOUNT_TARGET.into()); Config { device_type: "anaconda".into(), console_type_raw: 6, @@ -250,6 +268,21 @@ mod tests { assert_eq!(c.raytracing, "auto"); } + #[test] + fn pls_drive_is_the_mount_onto_the_pls_folder() { + let mut c = Config::default(); + assert_eq!(c.pls_drive().as_deref(), Some("S:\\")); + // a user-moved drive (any spelling of the target) is followed + c.mounts.remove("S:"); + assert_eq!(c.pls_drive(), None); + c.mounts.insert("p:".into(), "{data}/PLS\\".into()); + assert_eq!(c.pls_drive().as_deref(), Some("P:\\")); + // directory-style prefixes are not drives + c.mounts.remove("p:"); + c.mounts.insert("PLS:".into(), PLS_MOUNT_TARGET.into()); + assert_eq!(c.pls_drive(), None); + } + #[test] fn raytracing_tier_parsing() { assert_eq!(parse_raytracing_tier("auto"), None); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index f73ed17..7b96f2b 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -3556,8 +3556,8 @@ else {{ mem.{neg}({t}_a, {v}, {t}_old); }}" h.push_str(" uint scc = 0u;\n { uint2 e0 = ballot(true); exec_lo = e0.x; exec_hi = e0.y; }\n"); for &v in &self.vgprs { // SV_VertexID / SV_InstanceID listed in ISG1 come through the fetch shader like an - // attribute: v[base + 4r] (retail VInstanced* read the instance id in v8 = r1) - let sv_at = vs.inputs.iter().find(|e| matches!(e.system_value, 6 | 8) && v == vs.attr_base + 4 * e.register as u64); + // attribute (retail VInstanced* read the instance id in v8 = r1) + let sv_at = vs.inputs.iter().find(|e| matches!(e.system_value, 6 | 8) && vs.input_vgpr(e.register) == Some(v)); let init = if v == 0 { "xi.xcl_vid".to_string() } else if v == 3 { @@ -3565,10 +3565,10 @@ else {{ mem.{neg}({t}_a, {v}, {t}_old); }}" } else if let Some(e) = sv_at { if e.system_value == 6 { "xi.xcl_vid" } else { "xi.xcl_iid" }.to_string() } else { + // the fetch shader's VGPRs: four per register the program reads (`fetched_registers`) inputs .iter() - .find(|e| v >= vs.attr_base + 4 * e.register as u64 && v < vs.attr_base + 4 * e.register as u64 + 4) - .map(|e| format!("asuint(xi.a{}[{}])", e.register, v - vs.attr_base - 4 * e.register as u64)) + .find_map(|e| vs.input_vgpr(e.register).filter(|&b| v >= b && v < b + 4).map(|b| format!("asuint(xi.a{}[{}])", e.register, v - b))) .unwrap_or_else(|| "0u".into()) }; let _ = writeln!(h, " uint v{v} = {init};"); @@ -3647,6 +3647,7 @@ else {{ mem.{neg}({t}_a, {v}, {t}_old); }}" let (maxv, maxp) = (rec.max_vertices, rec.max_primitives); let maxt = g.max_vertex_count.saturating_sub(2).max(1); let nreg = g.input_registers(); + let fetched = super::fetched_registers(&g.es_inputs); h.push_str("groupshared uint xcl_lds[8192]; // D3D12 limit: 32 KB (the console allows 64 KB)\n"); h.push_str("[WaveSize(64)]\n[numthreads(64, 1, 1)]\nvoid main(uint gi : SV_GroupIndex, uint3 gid : SV_GroupID)\n{\n"); h.push_str(" lane_id = WaveGetLaneIndex();\n"); @@ -3669,8 +3670,10 @@ else {{ mem.{neg}({t}_a, {v}, {t}_old); }}" 1 => format!("(lane_id < xcl_np) ? ((lane_id * 3u + 2u) * {item}u) : 0u"), 2 => "xcl_p0 + lane_id".to_string(), 5 => "xcl_p0 * 3u + lane_id".to_string(), - v if v >= 9 && v < 9 + 4 * nreg as u64 => { - let (r, c) = ((v - 9) / 4, (v - 9) % 4); + // the fetch shader's VGPRs: four per register the ES reads (`fetched_registers`); + // the pre-fetched vertices hold one float4 per register + v if v >= 9 && ((v - 9) / 4) < fetched.len() as u64 && fetched[((v - 9) / 4) as usize] < nreg => { + let (r, c) = (fetched[((v - 9) / 4) as usize], (v - 9) % 4); format!("(lane_id < xcl_nv) ? mem.Load(xcl_vin + ((xcl_p0 * 3u + lane_id) * {nreg}u + {r}u) * 16u + {}u) : 0u", c * 4) } _ => "0u".to_string(), @@ -3705,6 +3708,7 @@ else {{ mem.{neg}({t}_a, {v}, {t}_old); }}" let (maxv, maxp) = (rec.max_vertices, rec.max_primitives); let maxt = g.max_vertex_count.saturating_sub(2).max(1); let nreg = g.input_registers(); + let fetched = super::fetched_registers(&g.es_inputs); let native_lanes = if self.opt.geometry_wave32 { 32 } else { 64 }; h.push_str("groupshared uint xcl_lds[8192]; // D3D12 limit: 32 KB (the console allows 64 KB)\n"); let _ = writeln!(h, "[WaveSize({native_lanes})]\n[numthreads(64, 1, 1)]\nvoid main(uint gi : SV_GroupIndex, uint3 gid : SV_GroupID)\n{{"); @@ -3738,8 +3742,10 @@ else {{ mem.{neg}({t}_a, {v}, {t}_old); }}" 1 => format!("(lane_id < xcl_np) ? ((lane_id * 3u + 2u) * {item}u) : 0u"), 2 => "xcl_p0 + lane_id".to_string(), 5 => "xcl_p0 * 3u + lane_id".to_string(), - v if v >= 9 && v < 9 + 4 * nreg as u64 => { - let (r, c) = ((v - 9) / 4, (v - 9) % 4); + // the fetch shader's VGPRs: four per register the ES reads (`fetched_registers`); + // the pre-fetched vertices hold one float4 per register + v if v >= 9 && ((v - 9) / 4) < fetched.len() as u64 && fetched[((v - 9) / 4) as usize] < nreg => { + let (r, c) = (fetched[((v - 9) / 4) as usize], (v - 9) % 4); format!("(lane_id < xcl_nv) ? mem.Load(xcl_vin + ((xcl_p0 * 3u + lane_id) * {nreg}u + {r}u) * 16u + {}u) : 0u", c * 4) } _ => "0u".to_string(), @@ -4455,6 +4461,19 @@ uint rla(uint v, uint l) { // helper pixels of a quad a primitive's edge splits. uint q0 = QuadReadLaneAt(v, 0u), q1 = QuadReadLaneAt(v, 1u), q2 = QuadReadLaneAt(v, 2u), q3 = QuadReadLaneAt(v, 3u); uint q = (l & 2u) != 0u ? ((l & 1u) != 0u ? q3 : q2) : ((l & 1u) != 0u ? q1 : q0); + // A helper lane of another quad: after s_wqm the console's v_readfirstlane often picks + // one (the first lane of EXEC on a primitive's edge), and a wave read of it is undefined + // here (0 in practice: every other quad of the wave got the wrong value, e.g. a shader's + // draw type, and took the wrong branch). Its own quad sees it through a quad read; the + // reader takes that from a live lane of the same quad. + uint h = xcl_logical_wave64 ? (l & 31u) : l + 32u * xcl_half; + uint4 xcl_lv = WaveActiveBallot(true); + uint nib = (xcl_lv[min(h >> 5, 3u)] >> (h & 28u)) & 15u; + uint src = (h & ~3u) + firstbitlow(nib); + uint r0 = WaveReadLaneAt(q0, src), r1 = WaveReadLaneAt(q1, src), r2 = WaveReadLaneAt(q2, src), r3 = WaveReadLaneAt(q3, src); + uint r = (l & 2u) != 0u ? ((l & 1u) != 0u ? r3 : r2) : ((l & 1u) != 0u ? r1 : r0); + bool same_half = !xcl_logical_wave64 || (l >> 5) == xcl_half; + if (same_half && nib != 0u && ((nib >> (h & 3u)) & 1u) == 0u) w = r; if ((l >> 2) == (lane_id >> 2)) w = q; #endif return w; diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index becc840..77d6d87 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -88,6 +88,28 @@ pub struct VsInterface { pub params: Option>, } +impl VsInterface { + /// The first VGPR the fetch shader puts ISG1 register `register` in (None: not fetched). + pub fn input_vgpr(&self, register: u32) -> Option { + fetched_registers(&self.inputs).iter().position(|&r| r == register).map(|k| self.attr_base + 4 * k as u64) + } +} + +/// The ISG1 registers the console's fetch shader loads, in the order of their VGPRs (four +/// each from the first attribute VGPR): those the program reads (an element's ReadWriteMask). +/// An input the program never reads gets no VGPRs – Minecraft's UI vertex shader declares +/// COLOR0 r0, NORMAL0 r1 (unread), POSITION0 r2, TEXCOORD0 r3 and reads POSITION in v8, not +/// in v[4 + 4·2]: counting the unread register put NORMAL where the position is read, and +/// every vertex of those draws on one point (the create-world screen drew nothing). A +/// signature that marks nothing as read (no such information) keeps every register. +pub fn fetched_registers(inputs: &[SigElement]) -> Vec { + let any_read = inputs.iter().any(|e| e.rw_mask != 0); + let mut regs: Vec = inputs.iter().filter(|e| !any_read || e.rw_mask != 0).map(|e| e.register).collect(); + regs.sort_unstable(); + regs.dedup(); + regs +} + /// Pixel shader interface. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct PsInterface { @@ -1378,6 +1400,22 @@ mod attribute_tests { assert_eq!(ps_attribute_slot(&ps, 1, 0), Some(1)); } + /// Minecraft's UI vertex shader: an ISG1 input the program never reads (NORMAL0, r1) gets + /// no fetch-shader VGPRs – POSITION0 (r2) is read in v8, TEXCOORD0 (r3) in v12. + #[test] + fn unread_inputs_take_no_fetch_vgprs() { + let inputs = vec![input("COLOR", 0, 0, 0xF), input("NORMAL", 0, 1, 0), input("POSITION", 0, 2, 7), input("TEXCOORD", 0, 3, 3)]; + assert_eq!(fetched_registers(&inputs), [0, 2, 3]); + let vs = VsInterface { inputs: inputs.clone(), attr_base: 4, ..Default::default() }; + assert_eq!([0, 1, 2, 3].map(|r| vs.input_vgpr(r)), [Some(4), None, Some(8), Some(12)]); + // the ES variant starts at v9 + let es = VsInterface { inputs, attr_base: 9, ..Default::default() }; + assert_eq!(es.input_vgpr(3), Some(17)); + // a signature without read masks keeps every register (v[base + 4r]) + let unmarked = vec![input("COLOR", 0, 0, 0), input("NORMAL", 0, 1, 0), input("POSITION", 0, 2, 0)]; + assert_eq!(fetched_registers(&unmarked), [0, 1, 2]); + } + /// Elements packed into one register (XDefiant: UV1 in .xy, UV0 in .zw) share a param / /// attribute; channel c is read from the element declaring it. #[test] diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index edabbb1..b889db5 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -41,11 +41,93 @@ pub struct Compiled { /// samplers take registers from `sampler_base` (space 1). /// Fails when the blob is not a console shader or the program is not fully translated. pub fn console_to_dxil(blob: &[u8], stage: Stage, sampler_base: u32) -> Result { - let (t, profile) = console_translation(blob, stage, sampler_base)?; + let (mut t, profile) = console_translation(blob, stage, sampler_base)?; + if let Some([r, g, b]) = (stage == Stage::Pixel).then(|| debug_color(blob)).flatten() { + t.hlsl = t.hlsl.replacen(" return xo;\n}", &format!(" xo.t0 = float4({r:.3}, {g:.3}, {b:.3}, 1.0);\n return xo;\n}}"), 1); + } + // `XCL_DEBUG_LOD0=hash,…`: those pixel shaders sample at LOD 0 instead of with implicit + // derivatives – tells derivative (helper lane) trouble apart from the rest + if stage == Stage::Pixel && std::env::var("XCL_DEBUG_LOD0").is_ok_and(|v| v.split(',').filter_map(|h| u64::from_str_radix(h.trim(), 16).ok()).any(|h| h == crate::gpu::shader::fnv64(blob))) { + t.hlsl = sample_at_lod0(&t.hlsl); + } + // `XCL_DEBUG_PS_SUB=hash:from=>to||from=>to…` (one pixel shader): every `from` in its HLSL + // becomes `to` + if let Some(subs) = (stage == Stage::Pixel).then(|| std::env::var("XCL_DEBUG_PS_SUB").ok()).flatten().and_then(|v| { + let (h, rest) = v.split_once(':')?; + (u64::from_str_radix(h.trim(), 16).ok()? == crate::gpu::shader::fnv64(blob)).then(|| rest.to_string()) + }) { + for sub in subs.split("||") { + let Some((from, to)) = sub.split_once("=>") else { continue }; + let n = t.hlsl.matches(from).count(); + crate::xlog_info!("[SHADER] XCL_DEBUG_PS_SUB: {n} occurrence(s) of {from:?} replaced"); + t.hlsl = t.hlsl.replace(from, to); + } + } + // `XCL_DEBUG_PS_EXPR=hash:expression` (one pixel shader): its target 0 gets that HLSL + // expression, e.g. `float4(xi.a1.rgb, 1)` – an input or a register made visible + if let Some(expr) = (stage == Stage::Pixel).then(|| std::env::var("XCL_DEBUG_PS_EXPR").ok()).flatten().and_then(|v| { + let (h, e) = v.split_once(':')?; + (u64::from_str_radix(h.trim(), 16).ok()? == crate::gpu::shader::fnv64(blob)).then(|| e.to_string()) + }) { + t.hlsl = t.hlsl.replacen(" if (!xcl_live) discard;\n return xo;\n}", &format!(" xo.t0 = {expr};\n return xo;\n}}"), 1); + } let dxil = dxc::compile_cached(&t.hlsl, "main", profile)?.0; Ok(Compiled { dxil, samplers: t.static_samplers }) } +/// Every `X_T.Sample(args)` of generated HLSL as `X_T.SampleLevel(args, 0.0f)`. +fn sample_at_lod0(hlsl: &str) -> String { + let mut out = String::with_capacity(hlsl.len()); + let mut rest = hlsl; + while let Some(at) = rest.find("_T.Sample(") { + let open = at + "_T.Sample(".len(); + out.push_str(&rest[..at]); + out.push_str("_T.SampleLevel("); + let mut depth = 1; + let mut end = open; + for (k, ch) in rest[open..].char_indices() { + match ch { + '(' => depth += 1, + ')' => { + depth -= 1; + if depth == 0 { + end = open + k; + break; + } + } + _ => {} + } + } + out.push_str(&rest[open..end]); + out.push_str(", 0.0f)"); + rest = &rest[end + 1..]; + } + out.push_str(rest); + out +} + +/// `XCL_DEBUG_MAGENTA=hash[:rrggbb],…` (dump hashes, hex; magenta without a colour): those +/// pixel shaders write that opaque colour to target 0 wherever they run – where a draw lands, +/// told apart from what it shades (a colour per shader: which one drew a pixel). +fn debug_color(blob: &[u8]) -> Option<[f32; 3]> { + static S: std::sync::OnceLock> = std::sync::OnceLock::new(); + let wanted = S.get_or_init(|| { + std::env::var("XCL_DEBUG_MAGENTA") + .unwrap_or_default() + .split(',') + .filter_map(|item| { + let item = item.trim(); + let (h, c) = item.split_once(':').unwrap_or((item, "ff00ff")); + let c = u32::from_str_radix(c, 16).ok()?; + let ch = |shift: u32| ((c >> shift) & 0xFF) as f32 / 255.0; + Some((u64::from_str_radix(h, 16).ok()?, [ch(16), ch(8), ch(0)])) + }) + .collect() + }); + let h = crate::gpu::shader::fnv64(blob); + wanted.iter().find(|(w, _)| *w == h).map(|(_, c)| *c) +} + /// The HLSL (and its DXC profile) `console_to_dxil` compiles. pub fn console_to_hlsl(blob: &[u8], stage: Stage) -> Result<(String, &'static str), String> { console_translation(blob, stage, 0).map(|(t, p)| (t.hlsl, p)) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 3852903..0c0ed51 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -192,13 +192,20 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us /// #12 DrawInstanced pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) { + DRAW_ARGS.with(|d| d.set((false, vertices, instances, first_vertex, 0))); if let Some(list) = graphics_bound(this) { list.DrawInstanced(vertices, instances, first_vertex, first_instance); } } +thread_local! { + /// the draw being bound: (indexed, count, instances, first index / vertex, base vertex) – for the frame trace + static DRAW_ARGS: std::cell::Cell<(bool, u32, u32, u32, i32)> = const { std::cell::Cell::new((false, 0, 0, 0, 0)) }; +} + /// #13 DrawIndexedInstanced pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) { + DRAW_ARGS.with(|d| d.set((true, indices, instances, first_index, base_vertex))); if let Some(list) = graphics_bound(this) { list.DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance); } @@ -255,20 +262,23 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option /// `XCL_TRACE_FRAME`, after 300 presents: one line per distinct (VS, PS, render target) drawn – /// the shaders' dump hashes, the target and the textures of the first descriptor table. unsafe fn trace_draw_kinds(this: *mut c_void, pso: usize) { - static SEEN: Mutex> = Mutex::new(Vec::new()); + // keyed by the target's shape, not the object: a UI library's transient targets (Renoir's + // layers) are new objects every frame and would fill the list at once + static SEEN: Mutex)>> = Mutex::new(Vec::new()); if super::present::activity().0 < 300 { return; } let Some((vs, ps)) = super::real::pso_shaders(super::pso_async::resolve(pso)) else { return }; let rt = super::present::rt0_resource(this as usize).unwrap_or(0); + let desc = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0, d.SampleDesc.Count) }); { let mut g = SEEN.lock().unwrap(); - if g.len() >= 80 || g.contains(&(vs, ps, rt)) { + let key = (vs, ps, desc(rt)); + if g.len() >= 160 || g.contains(&key) { return; } - g.push((vs, ps, rt)); + g.push(key); } - let desc = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0, d.SampleDesc.Count) }); let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); let mut tex = Vec::new(); @@ -296,29 +306,147 @@ unsafe fn trace_draw_kinds(this: *mut c_void, pso: usize) { ); } -unsafe fn trace_ui_draw(this: *mut c_void, pso: usize) { - trace_draw_kinds(this, pso); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if super::present::activity().0 < 300 || N.load(std::sync::atomic::Ordering::Relaxed) >= 24 { - return; - } - // draws into a presented target, or – `XCL_TRACE_UI_ANY` – into any target - let Some(rt) = super::present::rt0_resource(this as usize) else { return }; - if !super::present::is_presented(rt) && std::env::var_os("XCL_TRACE_UI_ANY").is_none() { - return; - } - N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); +/// `XCL_TRACE_SHADERS=hash,…` (dump hashes, hex): the draws traced with their root arguments +/// are those whose vertex or pixel shader is listed – into any target, at any time (the first +/// 24); without it, draws into a presented target (or any – `XCL_TRACE_UI_ANY`) after 300 +/// presents. +fn traced_shaders() -> &'static [u64] { + static S: std::sync::OnceLock> = std::sync::OnceLock::new(); + S.get_or_init(|| std::env::var("XCL_TRACE_SHADERS").unwrap_or_default().split(',').filter_map(|h| u64::from_str_radix(h.trim(), 16).ok()).collect()) +} + +/// `XCL_TRACE_FRAME` with a watched target (`present::watch_rt`): draws whose descriptor +/// tables name it – that object, or another at its title address (the first 16). +unsafe fn trace_reads_of_watched(this: *mut c_void, pso: usize) { + let Some(w) = super::present::watched_rt() else { return }; + let w_addr = super::real::title_address(w).or_else(|| super::title_textures::address(w)); let Some(u) = crate::gpu::uma::get() else { return }; let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); let Some(layout) = layout else { return }; let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); + for p in layout.params.iter() { + let Param::Table { at } = *p else { continue }; + let t = word(at as usize) as usize; + for k in 0..16usize { + let Some(r) = super::console_heap::resource_at(u.base() + t + 32 * k) else { continue }; + let addr = super::real::title_address(r).or_else(|| super::title_textures::address(r)); + if super::present::is_watched(r) || (addr.is_some() && addr == w_addr) { + let rt = super::present::rt0_resource(this as usize).unwrap_or(0); + // each (source, target, shaders) once + static SEEN: Mutex> = Mutex::new(Vec::new()); + { + let mut g = SEEN.lock().unwrap(); + if g.len() >= 32 || g.contains(&(r, rt, pso)) { + return; + } + g.push((r, rt, pso)); + } + if !super::present::is_presented(rt) { + super::present::follow(rt); + } + if let Some(dsv) = super::list_x::bound_dsv(this) { + super::list_x::watch_dsv(dsv); + } + let d = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0, d.Flags.0) }); + crate::xlog_info!( + "frame trace: a draw (shaders {:x?}, {}) reads a watched target {r:#x} {:?} at {addr:x?} (slot {k}), drawing into {rt:#x} {:?}{} – {}", + super::real::pso_shaders(super::pso_async::resolve(pso)), + super::list_x::state_summary(this), + d(r), + d(rt), + if super::present::is_presented(rt) { " (presented)" } else { "" }, + root_args_summary(this, 32) + ); + let args = DRAW_ARGS.with(|d| d.get()); + crate::xlog_info!( + "frame trace: … that draw: {args:?} (indexed, count, instances, first, base vertex); input layout [{}]; {}", + super::real::pso_layout(super::pso_async::resolve(pso)).unwrap_or_default(), + super::list_x::geometry_summary(this, args) + ); + return; + } + } + } +} + +/// `XCL_TRACE_FRAME`: render targets a draw into the watched target samples (a UI library's +/// layers) are dumped with it (`present::follow`). +unsafe fn follow_layer_sources(this: *mut c_void) { + let (Some(w), Some(rt)) = (super::present::watched_rt(), super::present::rt0_resource(this as usize)) else { return }; + if rt != w { + return; + } + let Some(u) = crate::gpu::uma::get() else { return }; + let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); + let Some(layout) = layout else { return }; + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); + for p in layout.params.iter() { + let Param::Table { at } = *p else { continue }; + let t = word(at as usize) as usize; + for k in 0..4usize { + let Some(r) = super::console_heap::resource_at(u.base() + t + 32 * k) else { continue }; + let layer = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).is_some_and(|x| { + let d = x.GetDesc(); + d.Flags.0 & 1 != 0 && d.Width >= 64 && d.Height >= 32 && d.SampleDesc.Count == 1 + }); + if layer && r != w { + super::present::follow(r); + } + } + } +} + +unsafe fn trace_ui_draw(this: *mut c_void, pso: usize) { + trace_draw_kinds(this, pso); + trace_reads_of_watched(this, pso); + follow_layer_sources(this); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + // `XCL_TRACE_MANY=n`: n draws instead of 24 (a whole frame of a UI) + static CAP: std::sync::OnceLock = std::sync::OnceLock::new(); + let cap = *CAP.get_or_init(|| std::env::var("XCL_TRACE_MANY").ok().and_then(|v| v.parse().ok()).unwrap_or(24)); + if N.load(std::sync::atomic::Ordering::Relaxed) >= cap { + return; + } + let Some(rt) = super::present::rt0_resource(this as usize) else { return }; + let wanted = traced_shaders(); + if wanted.is_empty() { + // draws into a presented target, or – `XCL_TRACE_UI_ANY` – into any target + if super::present::activity().0 < 300 || (!super::present::is_presented(rt) && std::env::var_os("XCL_TRACE_UI_ANY").is_none()) { + return; + } + } else if !super::real::pso_shaders(super::pso_async::resolve(pso)).is_some_and(|(v, p)| wanted.contains(&v) || wanted.contains(&p)) { + return; + } else { + super::present::watch_rt(rt); + } + N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let sh = super::real::pso_shaders(super::pso_async::resolve(pso)).map(|(v, p)| format!("vs {v:016x} ps {p:016x}")); + crate::xlog_info!("frame trace: UI draw (pipeline {pso:#x}, {}): {}", sh.unwrap_or_default(), root_args_summary(this, 16)); + if !wanted.is_empty() { + // the picked shaders' geometry too (vertices dumped at the next present) + let args = DRAW_ARGS.with(|d| d.get()); + crate::xlog_info!( + "frame trace: … that draw: {args:?} (indexed, count, instances, first, base vertex); input layout [{}]; {}", + super::real::pso_layout(super::pso_async::resolve(pso)).unwrap_or_default(), + super::list_x::geometry_summary(this, args) + ); + } +} + +/// A draw's root arguments for the frame trace: constants, root buffers (their first words, as +/// the CPU sees them), the first slots of descriptor tables (the PC resources they name). +unsafe fn root_args_summary(this: *mut c_void, buffer_words: usize) -> String { + let Some(u) = crate::gpu::uma::get() else { return String::new() }; + let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); + let Some(layout) = layout else { return String::new() }; + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); let mut what = Vec::new(); for (i, p) in layout.params.iter().enumerate() { match *p { Param::Constants { at, count } => what.push(format!("p{i} constants {:x?}", (0..count.min(8) as usize).map(|k| word(at as usize + 4 * k)).collect::>())), Param::Descriptor { at } => { let va = (word(at as usize) as u64 | (word(at as usize + 4) as u64) << 32) as usize; - let w: Vec = if va != 0 && crate::gpu::shader::readable(va, 32) { (0..8).map(|k| ((va + 4 * k) as *const u32).read_unaligned()).collect() } else { Vec::new() }; + let w: Vec = if va != 0 && crate::gpu::shader::readable(va, 4 * buffer_words) { (0..buffer_words).map(|k| ((va + 4 * k) as *const u32).read_unaligned()).collect() } else { Vec::new() }; what.push(format!("p{i} buffer {va:#x} {w:x?}")); } Param::Table { at } => { @@ -343,8 +471,7 @@ unsafe fn trace_ui_draw(this: *mut c_void, pso: usize) { } } } - let sh = super::real::pso_shaders(super::pso_async::resolve(pso)).map(|(v, p)| format!("vs {v:016x} ps {p:016x}")); - crate::xlog_info!("frame trace: UI draw (pipeline {pso:#x}, {}): {}", sh.unwrap_or_default(), what.join("; ")); + what.join("; ") } /// #33 SetComputeRootSignature (PC #29) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 38b69c5..e2f74e6 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -243,6 +243,10 @@ struct Bindings { vertex_buffers: std::collections::BTreeMap, /// (handles, single range, depth-stencil handle) render_targets: Option<(Vec, i32, Option)>, + /// slot → the title's (address, bytes, stride) of the vertex buffer (`XCL_TRACE_FRAME`) + vertex_titles: std::collections::BTreeMap, + /// the title's (address, bytes, format) of the index buffer (`XCL_TRACE_FRAME`) + index_title: Option<(u64, u32, i32)>, } /// `XCL_TRACE_FRAME`: the fixed-function state a list last set (topology, first viewport and @@ -253,17 +257,120 @@ pub(super) fn state_summary(list: *mut c_void) -> String { let vp = b.viewports.first().map(|v| (v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth)); let sc = b.scissors.first().map(|r| (r.left, r.top, r.right, r.bottom)); out = format!( - "topology {:?}, stencil ref {:?}, viewport {vp:?} ({} set), scissor {sc:?} ({} set), render targets {:?}", + "topology {:?}, stencil ref {:?}, viewport {vp:?} ({} set), scissor {sc:?} ({} set), render targets {:?}{}", b.topology, b.stencil, b.viewports.len(), b.scissors.len(), - b.render_targets.as_ref().map(|(h, _, d)| (h.len(), d.is_some())) + b.render_targets.as_ref().map(|(h, _, d)| (h.len(), d.is_some())), + b.render_targets.as_ref().and_then(|(_, _, d)| *d).map_or(String::new(), |d| format!(", DSV {d:#x}")) ); }); out } +/// `XCL_TRACE_FRAME`: the vertex and index buffers a list binds, with their first vertices +/// and indices as the CPU sees the title's memory. +pub(super) unsafe fn geometry_summary(list: *mut c_void, draw: (bool, u32, u32, u32, i32)) -> String { + let (vbs, ib) = { + let mut out = (Vec::new(), None); + with_bindings(list, |b| out = (b.vertex_titles.iter().map(|(&k, &v)| (k, v)).collect::>(), b.index_title)); + out + }; + let words = |a: u64, n: usize| -> Option> { + (a != 0 && crate::gpu::shader::readable(a as usize, 4 * n)).then(|| (0..n).map(|k| ((a as usize + 4 * k) as *const u32).read_unaligned()).collect()) + }; + let mut out = Vec::new(); + for (slot, (a, size, stride)) in vbs { + let per = (stride as usize / 4).clamp(1, 12); + let verts: Vec = (0..4u64).filter_map(|i| words(a + i * stride as u64, per).map(|w| format!("{w:x?}"))).collect(); + out.push(format!("VB{slot} {a:#x} ({size} bytes, stride {stride}): {}", verts.join(" "))); + } + // the vertices the draw names: through its indices (indexed) or from its first vertex + let (indexed, count, _, first, base) = draw; + let n = count.min(6) as usize; + let names: Option> = if indexed { + ib.and_then(|(a, _, fmt)| { + let w = if fmt == 57 { 2 } else { 4 }; + let at = a as usize + w * first as usize; + (a != 0 && crate::gpu::shader::readable(at, w * n)).then(|| { + (0..n).map(|k| if w == 2 { ((at + 2 * k) as *const u16).read_unaligned() as u64 } else { ((at + 4 * k) as *const u32).read_unaligned() as u64 }).map(|i| (i as i64 + base as i64) as u64).collect() + }) + }) + } else { + Some((0..n as u64).map(|k| first as u64 + k).collect()) + }; + out.push(format!("IB {:x?}; the draw's vertices (as indexed now) {names:?}", ib.map(|(a, size, fmt)| (a, size, fmt)))); + // the title fills ring buffers after recording a draw: the vertices are read again when + // the list is executed (`dump_pending_geometry`) + if let Some((_, vb)) = vbs_first(list) { + PENDING_GEOMETRY.lock().unwrap().push((list as usize, vb, ib, draw)); + } + out.join("; ") +} + +/// draws whose vertices are dumped when their list runs: (list, (VB address, bytes, stride), +/// (IB address, bytes, format), draw arguments) +#[allow(clippy::type_complexity)] +static PENDING_GEOMETRY: Mutex, (bool, u32, u32, u32, i32))>> = Mutex::new(Vec::new()); + +/// `XCL_TRACE_FRAME`: the vertices of traced draws as the title's memory holds them at the +/// next present (the CPU has written the frame's vertices by then). +pub(super) unsafe fn dump_pending_geometry() { + let mine: Vec<_> = std::mem::take(&mut *PENDING_GEOMETRY.lock().unwrap()); + for (_, (a, _, stride), ib, (indexed, count, _, first, base)) in mine { + let n = count.min(48) as usize; + let names: Vec = match (indexed, ib) { + (true, Some((ia, _, fmt))) => { + let w = if fmt == 57 { 2 } else { 4 }; + let at = ia as usize + w * first as usize; + if !crate::gpu::shader::readable(at, w * n) { + continue; + } + (0..n).map(|k| if w == 2 { ((at + 2 * k) as *const u16).read_unaligned() as u64 } else { ((at + 4 * k) as *const u32).read_unaligned() as u64 }).map(|i| (i as i64 + base as i64) as u64).collect() + } + _ => (0..n as u64).map(|k| first as u64 + k).collect(), + }; + let per = (stride as usize / 4).clamp(1, 12); + let mut unique = names.clone(); + unique.sort_unstable(); + unique.dedup(); + let verts: Vec = unique + .iter() + .take(24) + .map(|&i| { + let at = (a + i * stride as u64) as usize; + let w: Option> = crate::gpu::shader::readable(at, 4 * per).then(|| (0..per).map(|k| ((at + 4 * k) as *const u32).read_unaligned()).collect()); + format!("v{i}: {w:x?}") + }) + .collect(); + crate::xlog_info!("frame trace: … its vertices at the present (VB {a:#x}, stride {stride}, indices {names:?}): {}", verts.join("; ")); + } +} + +fn vbs_first(list: *mut c_void) -> Option<(u32, (u64, u32, u32))> { + let mut first = None; + with_bindings(list, |b| first = b.vertex_titles.iter().next().map(|(&k, &v)| (k, v))); + first +} + +/// The depth-stencil view handle a list last bound (`XCL_TRACE_FRAME`). +pub(super) fn bound_dsv(list: *mut c_void) -> Option { + let mut d = None; + with_bindings(list, |b| d = b.render_targets.as_ref().and_then(|(_, _, h)| *h)); + d +} + +/// depth-stencil views bound by draws that read a watched target: their clears are traced +static WATCHED_DSVS: Mutex> = Mutex::new(Vec::new()); + +pub(super) fn watch_dsv(dsv: usize) { + let mut g = WATCHED_DSVS.lock().unwrap(); + if !g.contains(&dsv) && g.len() < 8 { + g.push(dsv); + } +} + fn with_bindings(list: *mut c_void, f: impl FnOnce(&mut Bindings)) { let mut g = LISTS.lock().unwrap(); f(&mut g.get_or_insert_with(HashMap::new).entry(list as usize).or_default().bindings); @@ -1379,9 +1486,11 @@ pub(super) unsafe extern "system" fn ia_set_vertex_buffers_x(this: *mut c_void, }) .collect(); let kept = v.clone(); + let titles: Vec<(u64, u32, u32)> = (0..n as usize).map(|k| { let t = views.add(k).read_unaligned(); (t.BufferLocation, t.SizeInBytes, t.StrideInBytes) }).collect(); with_bindings(this, |b| { for (k, view) in kept.into_iter().enumerate() { b.vertex_buffers.insert(start + k as u32, view); + b.vertex_titles.insert(start + k as u32, titles[k]); } }); f(this, start, n, v.as_ptr()) @@ -1397,6 +1506,7 @@ pub(super) unsafe extern "system" fn ia_set_index_buffer_x(this: *mut c_void, vi return set_index_buffer(this, None); } let mut v = view.read_unaligned(); + s.bindings.index_title = Some((v.BufferLocation, v.SizeInBytes, v.Format.0)); v.BufferLocation = pc_va(v.BufferLocation); s.index_buffer = Some(v); drop(g); @@ -1493,6 +1603,15 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 for k in 0..n as usize { let mut b = barriers.add(k).read_unaligned(); let (ty, flags) = (b[0], b[1]); + if super::present::trace_frame() && ty == 0 { + let r = (b[2] as u64 | (b[3] as u64) << 32) as usize; + if super::present::is_watched(r) { + static W: AtomicU64 = AtomicU64::new(0); + if W.fetch_add(1, Ordering::Relaxed) < 24 { + crate::xlog_info!("frame trace: ResourceBarrier on a watched target {r:#x}: subresource {:#x}, {:#x} → {:#x}, flags {flags:#x}", b[4], b[5], b[6]); + } + } + } if ty > 2 || flags > 3 { if N.fetch_add(1, Ordering::Relaxed) < 16 { crate::xlog_warn!("D3D12.X: ResourceBarrier: console barrier type {ty} flags {flags:#x} dropped ({:x?})", b); @@ -1586,6 +1705,30 @@ pub(super) unsafe extern "system" fn copy_buffer_region_x(this: *mut c_void, dst pc::(this, PC_COPY_BUFFER_REGION)(this, dst, dst_off + real::buffer_delta(dst), src, src_off + real::buffer_delta(src), n) } +/// `XCL_TRACE_FRAME` with a watched target (`present::watch_rt`): copies out of it – that +/// object, or another at its title address (the first 16) +unsafe fn trace_watched_copy(what: &str, dst: usize, src: usize) { + let Some(w) = super::present::watched_rt() else { return }; + let addr = |r: usize| real::title_address(r).or_else(|| super::title_textures::address(r)); + if !super::present::is_watched(src) && (addr(src).is_none() || addr(src) != addr(w)) { + return; + } + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) >= 16 { + return; + } + if !super::present::is_presented(dst) { + super::present::follow(dst); + } + let d = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Dimension.0, d.Width, d.Height, d.Format.0, d.Flags.0) }); + crate::xlog_info!( + "frame trace: {what} out of a watched target {src:#x} {:?} into {dst:#x} {:?}{}", + d(src), + d(dst), + if super::present::is_presented(dst) { " (presented)" } else { "" } + ); +} + /// CopyTextureRegion(dst, x, y, z, src, box) (PC #16; DMA list #12) pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, dst: *const D3D12_TEXTURE_COPY_LOCATION, x: u32, y: u32, z: u32, src: *const D3D12_TEXTURE_COPY_LOCATION, bx: *const D3D12_BOX) { if let Some(d) = dst.as_ref() { @@ -1624,6 +1767,40 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds } } } + if super::present::trace_frame() { + if let (Some(d), Some(sl)) = (dst.as_ref(), src.as_ref()) { + trace_watched_copy("CopyTextureRegion", transmute_copy(&d.pResource), transmute_copy(&sl.pResource)); + // footprints the PC's copy rules do not allow (row pitch: 256 bytes, offset: 512) + if sl.Type == D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT { + let f = sl.Anonymous.PlacedFootprint; + if f.Footprint.RowPitch % 256 != 0 || f.Offset % 512 != 0 { + // each (format, pitch alignment, offset alignment) once + static SEEN: Mutex> = Mutex::new(Vec::new()); + let key = (f.Footprint.Format.0, f.Footprint.RowPitch % 256, f.Offset % 512); + let new = { + let mut g = SEEN.lock().unwrap(); + let n = !g.contains(&key) && g.len() < 24; + if n { + g.push(key); + } + n + }; + if new { + crate::xlog_info!( + "frame trace: CopyTextureRegion from a footprint the PC does not take: offset {:#x}, format {}, {}x{}x{}, row pitch {} (box {:?}, to ({x}, {y}, {z}))", + f.Offset, + f.Footprint.Format.0, + f.Footprint.Width, + f.Footprint.Height, + f.Footprint.Depth, + f.Footprint.RowPitch, + bx.as_ref().map(|b| (b.left, b.top, b.right, b.bottom)) + ); + } + } + } + } + } let (Some(d), Some(s)) = (pc_location(dst), pc_location(src)) else { return }; pc::(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx); std::mem::forget((d, s)); // borrowed resource pointers @@ -1641,9 +1818,14 @@ const PC_CLEAR_DEPTH_STENCIL_VIEW: usize = 47; pub(super) unsafe extern "system" fn clear_depth_stencil_x(this: *mut c_void, dsv: usize, flags: u32, depth: f32, stencil: u8, n: u32, rects: *const windows::Win32::Foundation::RECT) { if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); + static W: AtomicU64 = AtomicU64::new(0); let k = N.fetch_add(1, Ordering::Relaxed); - if k < 8 || k.is_power_of_two() { - crate::xlog_info!("frame trace: ClearDepthStencilView #{k} {dsv:#x}: flags {flags:#x} (1 depth, 2 stencil), depth {depth}, stencil {stencil}, {n} rects"); + let watched = WATCHED_DSVS.lock().unwrap().contains(&dsv); + if k < 8 || k.is_power_of_two() || (watched && W.fetch_add(1, Ordering::Relaxed) < 12) { + crate::xlog_info!( + "frame trace: ClearDepthStencilView #{k} {dsv:#x}{}: flags {flags:#x} (1 depth, 2 stencil), depth {depth}, stencil {stencil}, {n} rects", + if watched { " (bound by a draw reading a watched target)" } else { "" } + ); } } pc::(this, PC_CLEAR_DEPTH_STENCIL_VIEW)(this, dsv, flags, depth, stencil, n, rects) @@ -1700,6 +1882,9 @@ pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_v pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usize, src: usize) { super::present::note_use(dst, super::present::USE_COPY); super::title_textures::note_gpu_write(dst); + if super::present::trace_frame() { + trace_watched_copy("CopyResource", dst, src); + } let (dd, sd) = (real::buffer_delta(dst), real::buffer_delta(src)); if dd == 0 && sd == 0 { return pc::(this, PC_COPY_RESOURCE)(this, dst, src); diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d0cb776..f9e4aaf 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -54,6 +54,16 @@ pub unsafe extern "system" fn present_x(queue: *mut c_void, plane_count: u32, pl if !PRESENTX.swap(true, Ordering::Relaxed) { crate::xlog_info!("D3D12.X: PresentX – the title presents its own frames ({plane_count} plane(s))"); } + { + // a change in the number of planes (the console's display composes them – a UI + // plane over the game's): logged with the planes' raw words + static LAST: AtomicU64 = AtomicU64::new(1); + if LAST.swap(plane_count as u64, Ordering::Relaxed) != plane_count as u64 { + let n = 8 * plane_count as usize; + let words: Vec = if crate::gpu::shader::readable(planes as usize, 8 * n) { (0..n).map(|k| (planes as *const u64).add(k).read_unaligned()).collect() } else { Vec::new() }; + crate::xlog_info!("D3D12.X: PresentX now with {plane_count} plane(s): {words:x?}"); + } + } let count = (planes.add(8) as *const u32).read_unaligned(); let list = (planes.add(0x10) as *const usize).read_unaligned(); if count == 0 || !crate::gpu::shader::readable(list, 8) || !enabled() { @@ -69,6 +79,9 @@ pub unsafe extern "system" fn present_x(queue: *mut c_void, plane_count: u32, pl p.push(res); } } + if trace_frame() { + super::list_x::dump_pending_geometry(); + } if trace_frame() { static K: AtomicU64 = AtomicU64::new(0); let k = K.fetch_add(1, Ordering::Relaxed); @@ -500,15 +513,20 @@ unsafe fn present_now(min_interval: Duration) { let due = frame_dump_due(); let dump = due.then(|| readback_copy(&p.list, src, &desc)).flatten(); // with `XCL_TRACE_FRAME`: also the render target the title binds most (its scene / UI) - let rt_dump = if due && trace_frame() { - busiest_rt().and_then(|r| { - let rr = r as *mut c_void; - let res = ID3D12Resource::from_raw_borrowed(&rr)?.clone(); - let d = res.GetDesc(); - readback_copy(&p.list, &res, &d).map(|x| (x, d.Format)) - }) + // (and the targets the watched one's contents went on to: rt__) + let rt_dump: Vec<_> = if due && trace_frame() { + busiest_rt() + .into_iter() + .chain(FOLLOWED.lock().unwrap().iter().copied()) + .filter_map(|r| { + let rr = r as *mut c_void; + let res = ID3D12Resource::from_raw_borrowed(&rr)?.clone(); + let d = res.GetDesc(); + (d.SampleDesc.Count <= 1).then(|| readback_copy(&p.list, &res, &d).map(|x| (x, d.Format))).flatten() + }) + .collect() } else { - None + Vec::new() }; let b2 = [transition(&bb, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT)]; p.list.ResourceBarrier(&b2); @@ -530,8 +548,8 @@ unsafe fn present_now(min_interval: Duration) { } write_frame(&rb, &fp, desc.Format, "frame"); } - if let Some(((rb, fp), f)) = rt_dump { - write_frame(&rb, &fp, f, "rt"); + for (k, ((rb, fp), f)) in rt_dump.into_iter().enumerate() { + write_frame(&rb, &fp, f, &if k == 0 { "rt".to_string() } else { format!("rt{k}") }); } let n = PRESENTS.fetch_add(1, Ordering::Relaxed); if n == 0 { @@ -540,7 +558,7 @@ unsafe fn present_now(min_interval: Duration) { } /// `XCL_FRAME_DUMP=1`: every 120th shown frame is written to the logs folder -/// (`frame_.bmp`, a quarter of each side) – what the title presented, before the window. +/// (`frame_.bmp`, a quarter of each side; `XCL_FRAME_DUMP_FULL=1`: full size) – what the title presented, before the window. fn frame_dump_due() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("XCL_FRAME_DUMP").is_some()) && PRESENTS.load(Ordering::Relaxed) % 120 == 20 @@ -597,9 +615,52 @@ fn rgb(format: DXGI_FORMAT, t: u32) -> Option<[u8; 3]> { }) } +/// the largest render target the draws `XCL_TRACE_SHADERS` picked drew into (AddRef'd): the +/// one the `XCL_TRACE_FRAME` dumps show instead of the busiest +static WATCHED_RT: Mutex> = Mutex::new(None); +/// targets that what the watched one holds went on to (drawn or copied from it; AddRef'd) +static FOLLOWED: Mutex> = Mutex::new(Vec::new()); + +pub fn watched_rt() -> Option { + *WATCHED_RT.lock().unwrap() +} + +/// The watched target or one its contents went on to. +pub fn is_watched(r: usize) -> bool { + watched_rt() == Some(r) || FOLLOWED.lock().unwrap().contains(&r) +} + +/// `r` now holds (some of) what the watched target held: its readers are traced too. +pub unsafe fn follow(r: usize) { + let mut g = FOLLOWED.lock().unwrap(); + if r == 0 || g.contains(&r) || g.len() >= 6 || watched_rt() == Some(r) { + return; + } + add_ref(r); + g.push(r); +} + +pub unsafe fn watch_rt(rt: usize) { + let area = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map_or(0, |x| { + let d = x.GetDesc(); + if d.SampleDesc.Count > 1 { 0 } else { d.Width * d.Height as u64 } + }); + let mut g = WATCHED_RT.lock().unwrap(); + if *g == Some(rt) || area(rt) <= g.map_or(0, area) { + return; + } + add_ref(rt); + if let Some(old) = g.replace(rt) { + release(old); + } +} + /// the single-sampled resource bound as a render target most often (`XCL_TRACE_FRAME`; a /// multisampled one cannot be copied to a buffer – the present list would not close) fn busiest_rt() -> Option { + if let Some(r) = *WATCHED_RT.lock().unwrap() { + return Some(r); + } let single = |r: usize| unsafe { ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).is_some_and(|x| x.GetDesc().SampleDesc.Count <= 1) }; USES.lock().unwrap().as_ref()?.iter().filter(|(&r, u)| u[USE_RT] > 0 && single(r)).max_by_key(|(_, u)| u[USE_RT]).map(|(&r, _)| r) } @@ -621,7 +682,9 @@ unsafe fn write_frame(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRI return; } let (w, h, pitch) = (fp.Footprint.Width as usize, fp.Footprint.Height as usize, fp.Footprint.RowPitch as usize); - let (ow, oh) = ((w / 4).max(1), (h / 4).max(1)); + // every 4th texel of every 4th row; `XCL_FRAME_DUMP_FULL=1`: every texel (1-pixel detail) + let step = if std::env::var_os("XCL_FRAME_DUMP_FULL").is_some() { 1 } else { 4 }; + let (ow, oh) = ((w / step).max(1), (h / step).max(1)); let row = (ow * 3).div_ceil(4) * 4; let mut bmp = Vec::with_capacity(54 + row * oh); let size = (54 + row * oh) as u32; @@ -639,7 +702,7 @@ unsafe fn write_frame(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRI for y in (0..oh).rev() { let start = bmp.len(); for x in 0..ow { - let t = ((p as *const u8).add(fp.Offset as usize + 4 * y * pitch + 16 * x) as *const u32).read_unaligned(); + let t = ((p as *const u8).add(fp.Offset as usize + step * y * pitch + 4 * step * x) as *const u32).read_unaligned(); *raw.entry(t).or_default() += 1; let c = rgb(format, t).unwrap_or_else(|| { decoded = false; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 3dedbc2..53dc806 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1113,6 +1113,27 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v } } +/// WriteToSubresource(subresource, box, data, row pitch, depth pitch): the CPU writing texels. +/// Every console resource is CPU-visible memory, a PC texture only in a CPU-visible heap. +unsafe extern "system" fn res_write_to_subresource(this: *mut c_void, sub: u32, dst_box: *const D3D12_BOX, data: *const c_void, row_pitch: u32, depth_pitch: u32) -> HRESULT { + type F = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_BOX, *const c_void, u32, u32) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "WriteToSubresource"))); + let hr = f(this, sub, dst_box, data, row_pitch, depth_pitch); + static CALLS: AtomicU64 = AtomicU64::new(0); + static FAILED: AtomicU64 = AtomicU64::new(0); + let n = CALLS.fetch_add(1, Ordering::Relaxed); + if hr < 0 && FAILED.fetch_add(1, Ordering::Relaxed) < 8 { + let d = ID3D12Resource::from_raw_borrowed(&this).map(|r| r.GetDesc()); + let b = dst_box.as_ref().map(|b| (b.left, b.top, b.right, b.bottom)); + crate::xlog_warn!( + "D3D12.X: WriteToSubresource({sub}, box {b:?}, row pitch {row_pitch}) of {:?} → {:#x} (call #{n})", + d.map(|d| (d.Dimension.0, d.Width, d.Height, d.Format.0, d.Layout.0, d.Flags.0)), + hr as u32 + ); + } + hr +} + /// resources the title placed at its own address that got a PC resource of their own: on the /// console Map gives that address (the CPU's view of the resource) static TITLE_ADDRESS: Mutex>> = Mutex::new(None); @@ -1183,6 +1204,13 @@ static TRANSLATED_GRAPHICS: Mutex>> = Mutex::new(None); /// `XCL_TRACE_FRAME`: the console VS and PS (their dump names' hashes) of a translated PSO. static PSO_SHADERS: Mutex>> = Mutex::new(None); +/// translated pipeline → its input layout as text (`XCL_TRACE_FRAME`) +static PSO_LAYOUTS: Mutex>> = Mutex::new(None); + +pub fn pso_layout(pso: usize) -> Option { + PSO_LAYOUTS.lock().unwrap().as_ref()?.get(&pso).cloned() +} + pub fn pso_shaders(pso: usize) -> Option<(u64, u64)> { PSO_SHADERS.lock().unwrap().as_ref()?.get(&pso).copied() } @@ -1592,7 +1620,12 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ]), Kind::CommandQueue => v.extend_from_slice(&[("Release", q_release as usize), ("ExecuteCommandLists", q_execute_command_lists as usize)]), Kind::CommandAllocator => v.extend_from_slice(&[("Release", alloc_release as usize), ("Reset", alloc_reset as usize)]), - Kind::Resource => v.extend_from_slice(&[("Release", res_release as usize), ("Map", res_map as usize), ("Unmap", res_unmap as usize)]), + Kind::Resource => v.extend_from_slice(&[ + ("Release", res_release as usize), + ("Map", res_map as usize), + ("Unmap", res_unmap as usize), + ("WriteToSubresource", res_write_to_subresource as usize), + ]), Kind::PipelineState => v.push(("Release", pso_release as usize)), Kind::DescriptorHeap => v.push(("Release", heap_release as usize)), Kind::Heap => v.push(("Release", mem_heap_release as usize)), @@ -1792,15 +1825,61 @@ pub(super) unsafe extern "system" fn dev_create_placed_resource_x(this: *mut c_v let d = super::device_x::pc_resource_desc(&x); let st = state as u32 & PC_RESOURCE_STATES; let hr2 = dev_create_placed_resource(this, heap, offset, d.as_ptr() as usize, st as usize, clear, riid, ppv); + let heap_desc = pc_heap_desc(heap); + let pc_size = pc_allocation_size(this, &d); + // A texture the title placed by the console's size (`get_resource_allocation_info_x` + // answers with XG's) can be larger on the PC and run past the end of its heap, which the + // PC refuses – Minecraft then ended (0xC0000409). It gets memory of its own, of the + // heap's kind; the console's aliasing of that one placement is lost. + let is_texture = u32::from_le_bytes(x[0..4].try_into().unwrap()) != D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32; + let hr3 = match heap_desc { + Some(h) if hr2 < 0 && is_texture => Some(dev_create_committed_resource(this, &h.Properties as *const _ as usize, 0, d.as_ptr() as usize, st as usize, clear, riid, ppv)), + _ => None, + }; static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 8 { let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); + let sizes = format!( + "heap {:#x} bytes, PC size {:#x}{}", + heap_desc.map_or(0, |h| h.SizeInBytes), + pc_size, + if heap_desc.is_some_and(|h| offset as u64 + pc_size > h.SizeInBytes) { " – past the heap's end" } else { "" } + ); + let own = hr3.map_or(String::new(), |h| format!("; memory of its own: {h:#x}")); crate::xlog_info!( - "D3D12.X: CreatePlacedResource(dimension {}, {}x{}, format {}, layout {:#x}, flags {:#x}, state {state:#x}) at {offset:#x} refused ({hr:#x}); the PC's way: {hr2:#x}", + "D3D12.X: CreatePlacedResource(dimension {}, {}x{}, format {}, layout {:#x}, flags {:#x}, state {state:#x}) at {offset:#x} refused ({hr:#x}); the PC's way: {hr2:#x} ({sizes}){own}", u(0), u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), u(0x18), u(0x20), u(0x2C), u(0x30) ); } - hr2 + hr3.unwrap_or(hr2) +} + +/// `XCL_DEBUG_NO_STENCIL` / `XCL_DEBUG_NO_CULL` `=hash,…` (pixel shader dump hashes, hex): +/// pipelines with those pixel shaders draw without their stencil test / culling – diagnostics +/// for draws the fixed-function stages reject. +fn debug_pso_switch(var: &str, ps: u64) -> bool { + ps != 0 && std::env::var(var).is_ok_and(|v| v.split(',').filter_map(|h| u64::from_str_radix(h.trim(), 16).ok()).any(|h| h == ps)) +} + +/// The PC description of a heap XCL adopted (ID3D12Heap::GetDesc, slot 8). +unsafe fn pc_heap_desc(heap: usize) -> Option { + if !is_adopted(heap as *mut c_void) { + return None; + } + type F = unsafe extern "system" fn(*mut c_void, *mut D3D12_HEAP_DESC) -> *mut D3D12_HEAP_DESC; + let f: F = std::mem::transmute(orig_fn(heap as *mut c_void, 8)); + let mut h = D3D12_HEAP_DESC::default(); + f(heap as *mut c_void, &mut h); + Some(h) +} + +/// The PC driver's size for a (PC) resource description (GetResourceAllocationInfo, slot 25). +unsafe fn pc_allocation_size(device: *mut c_void, d: &[u8; 0x38]) -> u64 { + type F = unsafe extern "system" fn(*mut c_void, *mut [u64; 2], u32, u32, *const [u8; 0x38]) -> *mut [u64; 2]; + let f: F = std::mem::transmute(orig_fn(device, 25)); + let mut r = [0u64; 2]; + f(device, &mut r, 0, 1, d); + r[0] } creator!(dev_create_placed_resource1, "CreatePlacedResource1", Kind::Resource, [a1, a2, a3, a4, a5]); creator!(dev_create_reserved_resource, "CreateReservedResource", Kind::Resource, [a1, a2, a3]); @@ -2278,6 +2357,13 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo copy.VS = bytecode(&vs_dxil); copy.PS = ps_dxil.as_deref().map(bytecode).unwrap_or_default(); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + let ps_hash = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); + if debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash) { + copy.DepthStencilState.StencilEnable = false.into(); + } + if debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash) { + copy.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + } let hr = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); if hr < 0 { note_translation_error(format!("the driver rejected the PSO with the translated shaders ({hr:#x})")); @@ -2289,8 +2375,19 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo if super::present::trace_frame() { let ps = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(vs), ps)); + // the input layout (semantic index, format, slot, offset) – what the vertices are read as + let il = &d.InputLayout; + let elems: Vec = if il.NumElements > 0 && !il.pInputElementDescs.is_null() { + std::slice::from_raw_parts(il.pInputElementDescs, il.NumElements as usize) + .iter() + .map(|e| format!("{}{} fmt {} slot {} @{}", e.SemanticName.to_string().unwrap_or_default(), e.SemanticIndex, e.Format.0, e.InputSlot, e.AlignedByteOffset as i32)) + .collect() + } else { + Vec::new() + }; + PSO_LAYOUTS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, elems.join(", ")); static N: AtomicU64 = AtomicU64::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 24 { + if N.fetch_add(1, Ordering::Relaxed) < 400 { let b = &d.BlendState.RenderTarget[0]; let z = &d.DepthStencilState; crate::xlog_info!( diff --git a/crates/xcl/src/hle/gameinput.rs b/crates/xcl/src/hle/gameinput.rs index b86e7d7..7e6df50 100644 --- a/crates/xcl/src/hle/gameinput.rs +++ b/crates/xcl/src/hle/gameinput.rs @@ -150,12 +150,48 @@ fn start() -> Instant { *T.get_or_init(Instant::now) } -/// `XCL_PRESS_A_AT`: seconds after start at which A is held for 200 ms -fn scripted_a() -> bool { - static AT: OnceLock> = OnceLock::new(); - let at = AT.get_or_init(|| std::env::var("XCL_PRESS_A_AT").ok().map(|v| v.split(',').filter_map(|s| s.trim().parse().ok()).collect()).unwrap_or_default()); - let t = start().elapsed().as_secs_f64(); - at.iter().any(|&s| t >= s && t < s + 0.2) +/// A button by its name in `XCL_PRESS_AT`. +fn button_named(name: &str) -> Option { + Some(match name.to_ascii_uppercase().as_str() { + "A" => A, + "B" => B, + "X" => X, + "Y" => Y, + "UP" => DPAD_UP, + "DOWN" => DPAD_DOWN, + "LEFT" => DPAD_LEFT, + "RIGHT" => DPAD_RIGHT, + "MENU" => MENU, + "VIEW" => VIEW, + "LB" => LEFT_SHOULDER, + "RB" => RIGHT_SHOULDER, + _ => return None, + }) +} + +/// `XCL_PRESS_AT=s:BUTTON,…` ("14:A,18.5:DOWN,20:A"; buttons A B X Y UP DOWN LEFT RIGHT MENU +/// VIEW LB RB) and `XCL_PRESS_A_AT=s,…`: buttons held for 200 ms at those seconds after the +/// host started (the log's times) – a title's menus walked without a person at the controls. +fn parse_presses(script: &str, a_only: &str) -> Vec<(f64, u32)> { + let mut v: Vec<(f64, u32)> = a_only.split(',').filter_map(|s| s.trim().parse().ok()).map(|s| (s, A)).collect(); + for item in script.split(',').map(str::trim).filter(|s| !s.is_empty()) { + match item.split_once(':').and_then(|(s, b)| Some((s.trim().parse::().ok()?, button_named(b.trim())?))) { + Some(p) => v.push(p), + None => crate::xlog_warn!("GameInput: XCL_PRESS_AT entry {item:?} not understood (seconds:BUTTON)"), + } + } + v +} + +fn scripted() -> u32 { + static AT: OnceLock> = OnceLock::new(); + let at = AT.get_or_init(|| { + let var = |n: &str| std::env::var(n).unwrap_or_default(); + parse_presses(&var("XCL_PRESS_AT"), &var("XCL_PRESS_A_AT")) + }); + // seconds since the host started, as the log's times (not since the title first polled) + let t = crate::log::uptime(); + at.iter().filter(|&&(s, _)| t >= s && t < s + 0.2).fold(0, |b, &(_, g)| b | g) } #[link(name = "user32")] @@ -203,9 +239,7 @@ pub fn poll() -> GamepadState { } } s.buttons |= unsafe { keyboard() }; - if scripted_a() { - s.buttons |= A; - } + s.buttons |= scripted(); { // the first presses of each button: worth a line (is input arriving at all?) static SEEN: AtomicU32 = AtomicU32::new(0); @@ -371,17 +405,31 @@ fn reading_vtable() -> *const usize { (4, reading_sequence as usize), (5, reading_timestamp as usize), (6, reading_device as usize), - (7, no_state as usize), + (7, no_state::<7> as usize), (22, reading_gamepad as usize), (24, reading_ui_navigation as usize), ]; - // counts and array states: none - for i in [8, 9, 10, 11, 12, 13, 14, 15, 17, 18] { - set.push((i, zero_count as usize)); + // counts and array states: none (each logged on its first call – which views of + // the device a title reads) + let counts: [usize; 10] = [ + zero_count::<8> as usize, + zero_count::<9> as usize, + zero_count::<10> as usize, + zero_count::<11> as usize, + zero_count::<12> as usize, + zero_count::<13> as usize, + zero_count::<14> as usize, + zero_count::<15> as usize, + zero_count::<17> as usize, + zero_count::<18> as usize, + ]; + for (i, f) in [8, 9, 10, 11, 12, 13, 14, 15, 17, 18].into_iter().zip(counts) { + set.push((i, f)); } // mouse, motion, arcade / flight stick, racing wheel: not this device - for i in [16, 19, 20, 21, 23] { - set.push((i, no_state as usize)); + let states: [usize; 5] = [no_state::<16> as usize, no_state::<19> as usize, no_state::<20> as usize, no_state::<21> as usize, no_state::<23> as usize]; + for (i, f) in [16, 19, 20, 21, 23].into_iter().zip(states) { + set.push((i, f)); } vtable("IGameInputReading", 32, &set) as usize }) as *const usize @@ -447,7 +495,23 @@ fn ours(device: *mut c_void) -> bool { device.is_null() || device == self::device() as *mut c_void } +/// A GameInput query of a kind not seen before: worth a line (which input a title reads how). +fn note_query(what: &str, kind: u32) { + static SEEN: Mutex> = Mutex::new(Vec::new()); + let what: &'static str = match what { + "GetCurrentReading" => "GetCurrentReading", + "GetNext/PreviousReading" => "GetNext/PreviousReading", + _ => "RegisterReadingCallback", + }; + let mut g = SEEN.lock().unwrap(); + if g.len() < 32 && !g.contains(&(what, kind)) { + g.push((what, kind)); + crate::xlog_info!("GameInput: {what} for kinds {kind:#x} first asked"); + } +} + unsafe extern "system" fn get_current_reading(_this: *mut Object, kind: u32, dev: *mut c_void, out: *mut *mut Reading) -> HRESULT { + note_query("GetCurrentReading", kind); if out.is_null() { return E_POINTER; } @@ -460,7 +524,8 @@ unsafe extern "system" fn get_current_reading(_this: *mut Object, kind: u32, dev } /// the readings before and after one are not kept -unsafe extern "system" fn other_reading(_this: *mut Object, _reference: *mut c_void, _kind: u32, _dev: *mut c_void, out: *mut *mut Reading) -> HRESULT { +unsafe extern "system" fn other_reading(_this: *mut Object, _reference: *mut c_void, kind: u32, _dev: *mut c_void, out: *mut *mut Reading) -> HRESULT { + note_query("GetNext/PreviousReading", kind); if !out.is_null() { *out = std::ptr::null_mut(); } @@ -481,6 +546,7 @@ static READING_CALLBACKS: Mutex> = Mutex::new(Vec::new( /// RegisterReadingCallback(device, kind, analog threshold, context, callback, &token) unsafe extern "system" fn register_reading_callback(_this: *mut Object, dev: *mut c_void, kind: u32, _threshold: f32, context: *mut c_void, cb: Option, token: *mut u64) -> HRESULT { + note_query("RegisterReadingCallback", kind); let t = TOKENS.fetch_add(1, Ordering::Relaxed) + 1; if !token.is_null() { *token = t; @@ -619,10 +685,42 @@ unsafe extern "system" fn reading_device(_this: *mut Reading, out: *mut *mut Obj *out = device(); } } -unsafe extern "system" fn zero_count(_this: *mut Reading, _a: u32, _b: *mut c_void) -> u32 { +/// IGameInputReading method names by slot (the logged ones) +fn reading_method(slot: usize) -> &'static str { + match slot { + 7 => "GetRawReport", + 8 => "GetControllerAxisCount", + 9 => "GetControllerAxisState", + 10 => "GetControllerButtonCount", + 11 => "GetControllerButtonState", + 12 => "GetControllerSwitchCount", + 13 => "GetControllerSwitchState", + 14 => "GetKeyCount", + 15 => "GetKeyState", + 16 => "GetMouseState", + 17 => "GetTouchCount", + 18 => "GetTouchState", + 19 => "GetMotionState", + 20 => "GetArcadeStickState", + 21 => "GetFlightStickState", + 23 => "GetRacingWheelState", + _ => "?", + } +} + +fn note_reading_call(slot: usize) { + static SEEN: AtomicU32 = AtomicU32::new(0); + if SEEN.fetch_or(1 << slot, Ordering::Relaxed) & (1 << slot) == 0 { + crate::xlog_info!("GameInput: IGameInputReading::{} first called (answered: none)", reading_method(slot)); + } +} + +unsafe extern "system" fn zero_count(_this: *mut Reading, _a: u32, _b: *mut c_void) -> u32 { + note_reading_call(SLOT); 0 } -unsafe extern "system" fn no_state(_this: *mut Reading, _out: *mut c_void) -> bool { +unsafe extern "system" fn no_state(_this: *mut Reading, _out: *mut c_void) -> bool { + note_reading_call(SLOT); false } unsafe extern "system" fn reading_gamepad(this: *mut Reading, out: *mut GamepadState) -> bool { @@ -684,4 +782,11 @@ mod tests { assert_eq!(get_current_reading(g, 0x10, std::ptr::null_mut(), &mut r), GAMEINPUT_E_READING_NOT_FOUND, "keyboard kind"); } } + + #[test] + fn press_script_parses_buttons_and_times() { + let v = parse_presses("14:A, 18.5:down,20:Rb,junk,3:NOPE", "1,2.5"); + assert_eq!(v, vec![(1.0, A), (2.5, A), (14.0, A), (18.5, DPAD_DOWN), (20.0, RIGHT_SHOULDER)]); + assert!(parse_presses("", "").is_empty()); + } } diff --git a/crates/xcl/src/hle/xgameruntime/gamesave.rs b/crates/xcl/src/hle/xgameruntime/gamesave.rs index f12a27b..7e35537 100644 --- a/crates/xcl/src/hle/xgameruntime/gamesave.rs +++ b/crates/xcl/src/hle/xgameruntime/gamesave.rs @@ -153,6 +153,13 @@ pub unsafe extern "system" fn XGameSaveGetRemainingQuota(p: *mut Provider, quota } let used: u64 = std::fs::read_dir(&pr.root).into_iter().flatten().flatten().flat_map(|e| blobs_of(&e.path())).map(|b| b.2).sum(); *quota = (QUOTA - used as i64).max(0); + static LAST: std::sync::Mutex> = std::sync::Mutex::new(None); + if let Ok(mut last) = LAST.lock() { + if *last != Some(*quota) { + *last = Some(*quota); + crate::xlog_info!("XGameSaveGetRemainingQuota: {} KiB left of {} MiB", *quota >> 10, QUOTA >> 20); + } + } S_OK } diff --git a/crates/xcl/src/hle/xgameruntime/mod.rs b/crates/xcl/src/hle/xgameruntime/mod.rs index b612392..b26f8a9 100644 --- a/crates/xcl/src/hle/xgameruntime/mod.rs +++ b/crates/xcl/src/hle/xgameruntime/mod.rs @@ -352,8 +352,17 @@ fn data_subdir(name: &str) -> PathBuf { p } +/// Host folder behind the title's persistent local storage. +fn pls_dir() -> PathBuf { + data_subdir("pls") +} + +/// The PLS path the title is given. On the console PLS is a folder mounted at the root of a +/// drive, and titles rely on it: Minecraft keeps only the drive name and builds +/// ":/Users//games/com.mojang" from it. So the title gets the VFS drive that +/// mounts `{data}\pls` ("S:\"); without such a mount, the host folder itself. fn pls_path() -> String { - data_subdir("pls").to_string_lossy().into_owned() + crate::state::config().pls_drive().unwrap_or_else(|| pls_dir().to_string_lossy().into_owned()) } pub unsafe extern "system" fn XPersistentLocalStorageGetPathSize(size: *mut usize) -> HRESULT { @@ -420,7 +429,7 @@ pub unsafe extern "system" fn XPersistentLocalStorageGetSpaceInfo(info: *mut XPe if info.is_null() { return E_INVALIDARG; } - let pls = pls_path(); + let pls = pls_dir().to_string_lossy().into_owned(); let (mut avail, mut total, mut free) = (0u64, 0u64, 0u64); let ok = GetDiskFreeSpaceExW(crate::util::wide(&pls).as_ptr(), &mut avail, &mut total, &mut free); // the title's quota (MicrosoftGame.Config , else 4 GiB) @@ -435,7 +444,24 @@ pub unsafe extern "system" fn XPersistentLocalStorageGetSpaceInfo(info: *mut XPe avail = quota; free = quota; } - *info = pls_space_info(quota, used, avail, free); + let out = pls_space_info(quota, used, avail, free); + // titles judge "storage low/full" from these figures: log each new answer + static LAST: std::sync::Mutex> = std::sync::Mutex::new(None); + let now = (out.available_free_bytes, out.total_free_bytes, out.used_bytes, out.total_bytes); + if let Ok(mut last) = LAST.lock() { + if *last != Some(now) { + *last = Some(now); + crate::xlog_info!( + "XPersistentLocalStorageGetSpaceInfo: {} MiB available, {} MiB free, {} MiB used of {} MiB (host {})", + now.0 >> 20, + now.1 >> 20, + now.2 >> 20, + now.3 >> 20, + if ok == 0 { "unavailable" } else { "ok" } + ); + } + } + *info = out; S_OK } diff --git a/crates/xcl/src/launcher.rs b/crates/xcl/src/launcher.rs index d7bfb70..9b24957 100644 --- a/crates/xcl/src/launcher.rs +++ b/crates/xcl/src/launcher.rs @@ -266,6 +266,11 @@ pub fn run(target: &Path, args: &[String]) -> i32 { eprintln!("xcl: writing {}: {e}", boot_path.display()); return 2; } + // the previous run's log and report stay as *.prev.*: a failure that a retry does not + // repeat is still there to read + let logs = boot.logs_dir(); + let _ = std::fs::rename(logs.join("xcl.log"), logs.join("xcl.prev.log")); + let _ = std::fs::rename(boot.report_path(), logs.join("report.prev.json")); let _ = std::fs::remove_file(boot.report_path()); println!("XCL {} – starting '{title}'", env!("CARGO_PKG_VERSION")); diff --git a/crates/xcl/src/log.rs b/crates/xcl/src/log.rs index db3e0c4..76b51b7 100644 --- a/crates/xcl/src/log.rs +++ b/crates/xcl/src/log.rs @@ -44,6 +44,11 @@ static LEVEL: AtomicU8 = AtomicU8::new(Level::Info as u8); static ECHO: AtomicBool = AtomicBool::new(true); static START: OnceLock = OnceLock::new(); +/// Seconds since the log started (the host's start) – the times log lines carry. +pub fn uptime() -> f64 { + START.get_or_init(Instant::now).elapsed().as_secs_f64() +} + pub fn init(path: Option<&Path>, level: Level, echo_stderr: bool) { START.get_or_init(Instant::now); LEVEL.store(level as u8, Ordering::Relaxed); diff --git a/crates/xcl/src/vfs_hooks.rs b/crates/xcl/src/vfs_hooks.rs index 5170357..bb99c24 100644 --- a/crates/xcl/src/vfs_hooks.rs +++ b/crates/xcl/src/vfs_hooks.rs @@ -210,6 +210,125 @@ unsafe extern "system" fn hk_set_attr_w(n: *const u16, attrs: u32) -> i32 { } } +// --------------------------------------------------------------------------------------- +// Free space: a console drive (T:\, G:\, …) reports the host volume its mount lives on. +// Untranslated, a console drive letter does not exist on the PC, the query fails and +// titles read it as a full disk (Minecraft then refuses to create a world). +// --------------------------------------------------------------------------------------- + +type FnDiskFreeExW = unsafe extern "system" fn(*const u16, *mut u64, *mut u64, *mut u64) -> i32; +type FnDiskFreeExA = unsafe extern "system" fn(*const u8, *mut u64, *mut u64, *mut u64) -> i32; +type FnDiskFreeW = unsafe extern "system" fn(*const u16, *mut u32, *mut u32, *mut u32, *mut u32) -> i32; +type FnDiskFreeA = unsafe extern "system" fn(*const u8, *mut u32, *mut u32, *mut u32, *mut u32) -> i32; +static O_DISK_FREE_EX_W: AtomicUsize = AtomicUsize::new(0); +static O_DISK_FREE_EX_A: AtomicUsize = AtomicUsize::new(0); +static O_DISK_FREE_W: AtomicUsize = AtomicUsize::new(0); +static O_DISK_FREE_A: AtomicUsize = AtomicUsize::new(0); + +// A NULL directory (the current directory's volume) has no path to translate and passes through. + +static SPACE_LOGGED: Mutex>> = Mutex::new(None); + +/// What a title learned about free space, once per queried directory: titles act on these +/// figures (a failed or tiny answer reads as a full disk), so the log shows what they saw. +/// Call right after the API: the title's last-error value survives the logging. +fn log_space(api: &str, path: &str, real: Option<&str>, answer: Option<(u64, u64)>) { + let err = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + if let Ok(mut g) = SPACE_LOGGED.lock() { + let seen = g.get_or_insert_with(HashSet::new); + if seen.len() < 64 && seen.insert(format!("{api}|{}", path.to_lowercase())) { + let host = match real { + Some(r) if r != path => format!(" (host {r})"), + _ => String::new(), + }; + match answer { + Some((avail, total)) => crate::xlog_info!("{api}({path}){host}: {} MiB available of {} MiB", avail >> 20, total >> 20), + None => crate::xlog_warn!("{api}({path}){host} failed (error {err})"), + } + } + } + unsafe { SetLastError(err) }; +} + +/// `GetDiskFreeSpaceW` figures in bytes: (free clusters, total clusters) × bytes per cluster. +unsafe fn clusters_to_bytes(spc: *const u32, bps: *const u32, nfree: *const u32, ntotal: *const u32) -> Option<(u64, u64)> { + if spc.is_null() || bps.is_null() || nfree.is_null() || ntotal.is_null() { + return None; + } + let cluster = *spc as u64 * *bps as u64; + Some((*nfree as u64 * cluster, *ntotal as u64 * cluster)) +} + +unsafe fn ex_answer(ok: i32, avail: *const u64, total: *const u64) -> Option<(u64, u64)> { + (ok != 0).then(|| (avail.as_ref().copied().unwrap_or(0), total.as_ref().copied().unwrap_or(0))) +} + +unsafe extern "system" fn hk_disk_free_ex_w(n: *const u16, avail: *mut u64, total: *mut u64, free: *mut u64) -> i32 { + let orig = orig!(O_DISK_FREE_EX_W as FnDiskFreeExW); + let Some(_g) = Guard::enter() else { return orig(n, avail, total, free) }; + let Some(path) = from_wide_ptr(n) else { return orig(n, avail, total, free) }; + let (r, real) = match read_target(&path) { + None => (orig(n, avail, total, free), None), + Some(Ok(p)) => (orig(wide(&p).as_ptr(), avail, total, free), Some(p)), + Some(Err(e)) => { + SetLastError(e); + (0, None) + } + }; + log_space("GetDiskFreeSpaceExW", &path, real.as_deref(), ex_answer(r, avail, total)); + r +} + +unsafe extern "system" fn hk_disk_free_ex_a(n: *const u8, avail: *mut u64, total: *mut u64, free: *mut u64) -> i32 { + let orig = orig!(O_DISK_FREE_EX_A as FnDiskFreeExA); + let Some(_g) = Guard::enter() else { return orig(n, avail, total, free) }; + let Some(path) = from_ansi_ptr(n) else { return orig(n, avail, total, free) }; + let (r, real) = match read_target(&path) { + None => (orig(n, avail, total, free), None), + Some(Ok(p)) => (orig!(O_DISK_FREE_EX_W as FnDiskFreeExW)(wide(&p).as_ptr(), avail, total, free), Some(p)), + Some(Err(e)) => { + SetLastError(e); + (0, None) + } + }; + log_space("GetDiskFreeSpaceExA", &path, real.as_deref(), ex_answer(r, avail, total)); + r +} + +unsafe extern "system" fn hk_disk_free_w(n: *const u16, spc: *mut u32, bps: *mut u32, nfree: *mut u32, ntotal: *mut u32) -> i32 { + let orig = orig!(O_DISK_FREE_W as FnDiskFreeW); + let Some(_g) = Guard::enter() else { return orig(n, spc, bps, nfree, ntotal) }; + let Some(path) = from_wide_ptr(n) else { return orig(n, spc, bps, nfree, ntotal) }; + let (r, real) = match read_target(&path) { + None => (orig(n, spc, bps, nfree, ntotal), None), + Some(Ok(p)) => (orig(wide(&p).as_ptr(), spc, bps, nfree, ntotal), Some(p)), + Some(Err(e)) => { + SetLastError(e); + (0, None) + } + }; + let answer = if r != 0 { clusters_to_bytes(spc, bps, nfree, ntotal) } else { None }; + log_space("GetDiskFreeSpaceW", &path, real.as_deref(), answer); + r +} + +unsafe extern "system" fn hk_disk_free_a(n: *const u8, spc: *mut u32, bps: *mut u32, nfree: *mut u32, ntotal: *mut u32) -> i32 { + let orig = orig!(O_DISK_FREE_A as FnDiskFreeA); + let Some(_g) = Guard::enter() else { return orig(n, spc, bps, nfree, ntotal) }; + let Some(path) = from_ansi_ptr(n) else { return orig(n, spc, bps, nfree, ntotal) }; + let (r, real) = match read_target(&path) { + None => (orig(n, spc, bps, nfree, ntotal), None), + Some(Ok(p)) => (orig!(O_DISK_FREE_W as FnDiskFreeW)(wide(&p).as_ptr(), spc, bps, nfree, ntotal), Some(p)), + Some(Err(e)) => { + SetLastError(e); + (0, None) + } + }; + let answer = if r != 0 { clusters_to_bytes(spc, bps, nfree, ntotal) } else { None }; + log_space("GetDiskFreeSpaceA", &path, real.as_deref(), answer); + r +} + // --------------------------------------------------------------------------------------- // Directory / delete / move / copy // --------------------------------------------------------------------------------------- @@ -605,6 +724,10 @@ pub fn install() -> Result<(), String> { ("GetFileAttributesExW", hk_get_attr_ex_w as usize, &O_GET_ATTR_EX_W), ("GetFileAttributesExA", hk_get_attr_ex_a as usize, &O_GET_ATTR_EX_A), ("SetFileAttributesW", hk_set_attr_w as usize, &O_SET_ATTR_W), + ("GetDiskFreeSpaceExW", hk_disk_free_ex_w as usize, &O_DISK_FREE_EX_W), + ("GetDiskFreeSpaceExA", hk_disk_free_ex_a as usize, &O_DISK_FREE_EX_A), + ("GetDiskFreeSpaceW", hk_disk_free_w as usize, &O_DISK_FREE_W), + ("GetDiskFreeSpaceA", hk_disk_free_a as usize, &O_DISK_FREE_A), ("CreateDirectoryW", hk_create_dir_w as usize, &O_CREATE_DIR_W), ("RemoveDirectoryW", hk_remove_dir_w as usize, &O_REMOVE_DIR_W), ("DeleteFileW", hk_delete_file_w as usize, &O_DELETE_FILE_W), diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index dcab736..fa17758 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -147,6 +147,8 @@ fn test_title_runs_and_game_folder_is_untouched() { assert!(wo.lines().any(|l| l == "data\\delete_me.txt"), "whiteouts: {wo}"); assert!(tdata.join("temp").join("scratch.tmp").is_file()); assert!(tdata.join("saves").join("test-scid").join("slot0.sav").is_file()); + // the PLS drive (S:\) is the data folder's pls + assert_eq!(std::fs::read(tdata.join("pls").join("Users").join("xcl").join("games").join("world.dat")).unwrap(), b"blocks"); // (4) report let report: serde_json::Value = diff --git a/tests/testtitle/src/main.rs b/tests/testtitle/src/main.rs index f71b875..45b1c06 100644 --- a/tests/testtitle/src/main.rs +++ b/tests/testtitle/src/main.rs @@ -60,6 +60,13 @@ extern "system" { fn LoadLibraryW(name: *const u16) -> usize; } +// The API set console titles import these from (Minecraft does), not kernel32. +#[link(name = "api-ms-win-core-file-l1-1-0", kind = "raw-dylib")] +extern "system" { + fn GetDiskFreeSpaceExW(dir: *const u16, avail: *mut u64, total: *mut u64, free: *mut u64) -> i32; + fn GetDiskFreeSpaceW(root: *const u16, spc: *mut u32, bps: *mut u32, free: *mut u32, total: *mut u32) -> i32; +} + #[link(name = "gameinput", kind = "raw-dylib")] extern "system" { fn GameInputCreate(out: *mut *mut c_void) -> HRESULT; @@ -451,6 +458,17 @@ fn main() { Ok(()) }); + check("files: T:\\ free space (the host volume behind the mount)", || unsafe { + let t = wide("T:\\"); + let (mut avail, mut total, mut free) = (0u64, 0u64, 0u64); + ensure!(GetDiskFreeSpaceExW(t.as_ptr(), &mut avail, &mut total, &mut free) != 0, "GetDiskFreeSpaceExW(T:\\) failed"); + ensure!(total > 0 && avail > 0 && avail <= total && free <= total, "avail {avail} free {free} total {total}"); + let (mut spc, mut bps, mut nfc, mut tnc) = (0u32, 0u32, 0u32, 0u32); + ensure!(GetDiskFreeSpaceW(t.as_ptr(), &mut spc, &mut bps, &mut nfc, &mut tnc) != 0, "GetDiskFreeSpaceW(T:\\) failed"); + ensure!(spc > 0 && bps > 0 && tnc > 0, "spc {spc} bps {bps} total clusters {tnc}"); + Ok(()) + }); + check("XGameRuntime: initialize + package identity", || unsafe { ensure!(XGameRuntimeInitialize() == 0, "init"); let mut buf = [0u8; 256]; @@ -569,6 +587,22 @@ fn main() { Ok(()) }); + check("XPersistentLocalStorage: a drive root, as on the console", || unsafe { + let mut pls = [0u8; 512]; + let mut used = 0usize; + ensure!(XPersistentLocalStorageGetPath(512, pls.as_mut_ptr(), &mut used) == 0, "pls"); + let root = cstr(&pls); + ensure!(root.len() == 3 && root.ends_with(":\\"), "PLS path {root:?} is not a drive root"); + // Minecraft keeps only the drive name and builds ":/Users//games/com.mojang" + let dir = format!("{}:/Users/xcl/games", &root[..1]); + std::fs::create_dir_all(&dir).map_err(|e| format!("create {dir}: {e}"))?; + std::fs::write(format!("{dir}/world.dat"), b"blocks").map_err(|e| format!("write {dir}/world.dat: {e}"))?; + let (mut avail, mut total, mut free) = (0u64, 0u64, 0u64); + ensure!(GetDiskFreeSpaceExW(wide(&dir).as_ptr(), &mut avail, &mut total, &mut free) != 0, "GetDiskFreeSpaceExW({dir}) failed"); + ensure!(avail > 0 && avail <= total, "avail {avail} total {total}"); + Ok(()) + }); + check("D3D12.X: queue + fence signal on the GPU", gpu::queue_fence); check("D3D12.X: shaders captured; console shader gets a fallback PSO", gpu::pso_capture_and_fallback); check("D3D12.X: retail-format console shader (XDAT/XBCH/FSSM) captured + fallback PSO", gpu::xbox_native_pso);