diff --git a/README.md b/README.md index 4d1932d2a..3c0f02bf2 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,11 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder - **The game folder is never modified** – writes go to the overlay. - Translated shaders are reused across XCL rebuilds when the translator sources and DXC toolchain are unchanged; `XCL_TRANSLATED_CACHE=0` disables that disk cache. +- `XCL_OVERLAY=1` draws a small stats panel into the top-left corner of the shown frame: the + title's fps and frame time, draws and dispatches per second, the process's commit and the + adapter's video memory, refreshed once a second. It is copied into the frame on XCL's own + command list (no extra window), so it also appears in screenshots and recordings. 8-bit + back buffers only. - Every run writes `report.json` (called stubs, unknown D3D12.X slots and interfaces, XGameRuntime classes asked for, shader statistics, audio formats, crash). `d3d12.presents` counts presentations, not visible content. With `XCL_FRAME_DUMP=N` (`N > 1`), diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 83a909468..5910f34aa 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -530,6 +530,8 @@ struct Presenter { fence: ID3D12Fence, copy_source: Option, dumps: Vec, + /// `XCL_OVERLAY`: the stats panel's texture (upload heap) and its size + overlay: Option<(ID3D12Resource, u32, u32)>, disabled: bool, value: u64, event: HANDLE, @@ -573,7 +575,7 @@ unsafe fn new_presenter(queue: usize) -> Option { let event = CreateEventW(None, false, false, None).ok()?; Some(Presenter { queue, dev: dev.clone(), sc: None, w: 0, h: 0, fmt: DXGI_FORMAT_UNKNOWN, alloc, list, fence, - copy_source: None, dumps: Vec::new(), disabled: false, value: 0, event, + copy_source: None, dumps: Vec::new(), overlay: None, disabled: false, value: 0, event, last: Instant::now() - Duration::from_secs(1), }) } @@ -624,6 +626,53 @@ unsafe fn ensure_swapchain(p: &mut Presenter, hwnd: HWND, w: u32, h: u32, fmt: D } } +/// The panel buffer's row pitch: `w * 4` rounded up to `D3D12_TEXTURE_DATA_PITCH_ALIGNMENT` +/// (256) – a placed footprint requires it (`overlay::panel` pads its rows the same way). +fn panel_row_pitch(w: u32) -> u32 { + (w * 4).div_ceil(256) * 256 +} + +/// `XCL_OVERLAY`: the stats panel in an upload-heap buffer (kept in GENERIC_READ: a copy +/// source), recreated when its text size changes. `None` = no overlay this frame. +unsafe fn overlay_copy(p: &mut Presenter, bb: &ID3D12Resource, fmt: DXGI_FORMAT) -> Option<(ID3D12Resource, u32, u32)> { + let (w, h, px) = crate::hle::overlay::panel(fmt.0)?; + let bbdesc = bb.GetDesc(); + if w + 16 > bbdesc.Width as u32 || h + 16 > bbdesc.Height { + return None; // a frame smaller than the panel: nothing drawn + } + let reuse = p.overlay.as_ref().is_some_and(|(_, ow, oh)| *ow == w && *oh == h); + if !reuse { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: px.len() as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buf: Option = None; + p.dev + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut buf, + ) + .ok()?; + p.overlay = Some((buf?, w, h)); + } + let (tex, _, _) = p.overlay.as_ref()?; + let mut ptr: *mut c_void = std::ptr::null_mut(); + tex.Map(0, None, Some(&mut ptr)).ok()?; + std::ptr::copy_nonoverlapping(px.as_ptr(), ptr as *mut u8, px.len()); + tex.Unmap(0, None); + p.overlay.clone() +} + unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { if IN_PRESENT.with(|c| c.replace(true)) { return; @@ -691,9 +740,32 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { if p.alloc.Reset().is_err() || p.list.Reset(&p.alloc, None).is_err() { return; } + // `XCL_OVERLAY`: the stats panel, copied into the frame after the game image + let overlay = if crate::hle::overlay::enabled() { overlay_copy(p, &bb, fmt) } else { None }; let b1 = [transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST)]; p.list.ResourceBarrier(&b1); p.list.CopyResource(&bb, &src); + if let Some((tex, w, h)) = &overlay { + // transmute_copy: the copy locations only borrow – a clone here would AddRef the back + // buffer every frame (ResizeBuffers then fails) and leak every recreated overlay buffer + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&bb), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + let srcloc = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(tex), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: fmt, Width: *w, Height: *h, Depth: 1, RowPitch: panel_row_pitch(*w) }, + }, + }, + }; + let region = D3D12_BOX { left: 0, top: 0, front: 0, right: *w, bottom: *h, back: 1 }; + p.list.CopyTextureRegion(&dst, 8, 8, 0, &srcloc, Some(®ion)); + } let due = frame_dump_due(); let mut dumps = Vec::new(); if due { @@ -1002,6 +1074,19 @@ impl Drop for Presenter { mod tests { use super::*; + /// The overlay copy's row pitch is 256-aligned for every panel width the font produces + /// (`w = 16 + 12 * cols`), and equals the padding `overlay::panel` writes. + #[test] + fn panel_row_pitch_is_256_aligned() { + for cols in 1..40u32 { + let w = 16 + 12 * cols; + let pitch = panel_row_pitch(w); + assert_eq!(pitch % 256, 0, "w={w}"); + assert!(pitch >= w * 4 && pitch - w * 4 < 256, "w={w}"); + } + assert_eq!(panel_row_pitch(64), 256, "an exact multiple stays"); + } + #[test] fn frame_rate_uses_frame_and_time_deltas() { let start = Instant::now(); diff --git a/crates/xcl/src/hle/mod.rs b/crates/xcl/src/hle/mod.rs index da0eafbd2..f1cbf2583 100644 --- a/crates/xcl/src/hle/mod.rs +++ b/crates/xcl/src/hle/mod.rs @@ -21,6 +21,7 @@ pub mod kernelx; pub mod mfplat; pub mod netoff; pub mod opus; +pub mod overlay; pub mod user; pub mod xaudio2; pub mod xma2; diff --git a/crates/xcl/src/hle/overlay.rs b/crates/xcl/src/hle/overlay.rs new file mode 100644 index 000000000..f4071b00d --- /dev/null +++ b/crates/xcl/src/hle/overlay.rs @@ -0,0 +1,266 @@ +//! `XCL_OVERLAY=1`: the title's frame rate and frame time, draws and dispatches per second, +//! the process's commit and the adapter's video memory, drawn into the top-left corner of the +//! frame XCL shows (`present`). A small bitmap font rendered on the CPU and copied into the +//! back buffer with XCL's own command list after the game-image copy: part of the image, so +//! it survives the flip-model swap chain and shows in screenshots and recordings. No extra +//! window, no GDI, no input taken, none of the title's resources touched. Off unless asked for. + +use std::time::{Duration, Instant}; + +/// `XCL_OVERLAY=1` (any non-empty value other than "0"): draw the overlay. +pub fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_OVERLAY").is_ok_and(|v| !v.is_empty() && v != "0")) +} + +/// One sample of what the title did; the overlay shows the difference over the last second. +struct Sample { + at: Instant, + presents: u64, + draws: u64, + dispatches: u64, +} + +fn sample() -> Sample { + let (p, _) = crate::hle::d3d12x::present::activity(); + let (d, x) = crate::hle::d3d12x::bind::activity(); + Sample { at: Instant::now(), presents: p, draws: d, dispatches: x } +} + +/// The process's commit charge in MB (`K32GetProcessMemoryInfo`'s private usage). +fn commit_mb() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; + let mut c: PROCESS_MEMORY_COUNTERS_EX = unsafe { std::mem::zeroed() }; + c.cb = std::mem::size_of_val(&c) as u32; + unsafe { + K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb); + } + c.PrivateUsage as u64 >> 20 +} + +/// The lines the overlay draws (the unit-testable part: formatting of a sample pair). +fn lines(prev: &Sample, now: &Sample, commit: u64, vram: Option<(u64, u64)>) -> Vec { + let dt = now.at.duration_since(prev.at).as_secs_f64().max(0.001); + let fps = now.presents.saturating_sub(prev.presents) as f64 / dt; + let ms = if fps > 0.0 { 1000.0 / fps } else { 0.0 }; + let draws = now.draws.saturating_sub(prev.draws) as f64 / dt; + let disp = now.dispatches.saturating_sub(prev.dispatches) as f64 / dt; + let mut v = vec![ + format!("{fps:5.1} FPS {ms:5.1} MS"), + format!("{draws:5.0} DRAW/S {disp:4.0} DISP/S"), + format!("COMMIT {commit} MB"), + ]; + if let Some((l, n)) = vram { + v.push(format!("VRAM {} MB LOCAL {} MB SHARED", l >> 20, n >> 20)); + } + v +} + +/// The overlay's text, refreshed at most once a second (called from the present path). +pub fn text() -> Vec { + static LAST: std::sync::Mutex> = std::sync::Mutex::new(None); + static LINES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + let now = sample(); + let mut g = LAST.lock().unwrap(); + match g.as_ref() { + Some(prev) if now.at.duration_since(prev.at) >= Duration::from_millis(1000) => { + let vram = crate::hle::d3d12x::real::video_memory(); + *LINES.lock().unwrap() = lines(prev, &now, commit_mb(), vram); + *g = Some(now); + } + None => *g = Some(now), + _ => {} + } + LINES.lock().unwrap().clone() +} + +/// A 5x7 bitmap font: the rows of each glyph the overlay can draw (bit 4 = leftmost pixel). +/// The characters [`lines`] produces: digits, the upper-case letters it uses, dot, slash; +/// space and anything else is blank. +pub fn glyph(c: u8) -> [u8; 7] { + match c { + b'0' => [0x0E, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0E], + b'1' => [0x04, 0x0C, 0x04, 0x04, 0x04, 0x04, 0x0E], + b'2' => [0x0E, 0x11, 0x01, 0x02, 0x04, 0x08, 0x1F], + b'3' => [0x1F, 0x02, 0x04, 0x02, 0x01, 0x11, 0x0E], + b'4' => [0x02, 0x06, 0x0A, 0x12, 0x1F, 0x02, 0x02], + b'5' => [0x1F, 0x10, 0x1E, 0x01, 0x01, 0x11, 0x0E], + b'6' => [0x06, 0x08, 0x10, 0x1E, 0x11, 0x11, 0x0E], + b'7' => [0x1F, 0x01, 0x02, 0x04, 0x08, 0x08, 0x08], + b'8' => [0x0E, 0x11, 0x11, 0x0E, 0x11, 0x11, 0x0E], + b'9' => [0x0E, 0x11, 0x11, 0x0F, 0x01, 0x02, 0x0C], + b'A' => [0x0E, 0x11, 0x11, 0x1F, 0x11, 0x11, 0x11], + b'B' => [0x1E, 0x11, 0x11, 0x1E, 0x11, 0x11, 0x1E], + b'C' => [0x0E, 0x11, 0x10, 0x10, 0x10, 0x11, 0x0E], + b'D' => [0x1C, 0x12, 0x11, 0x11, 0x11, 0x12, 0x1C], + b'E' => [0x1F, 0x10, 0x10, 0x1E, 0x10, 0x10, 0x1F], + b'F' => [0x1F, 0x10, 0x10, 0x1E, 0x10, 0x10, 0x10], + b'H' => [0x11, 0x11, 0x11, 0x1F, 0x11, 0x11, 0x11], + b'I' => [0x0E, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0E], + b'L' => [0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1F], + b'M' => [0x11, 0x1B, 0x15, 0x15, 0x11, 0x11, 0x11], + b'O' => [0x0E, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0E], + b'P' => [0x1E, 0x11, 0x11, 0x1E, 0x10, 0x10, 0x10], + b'R' => [0x1E, 0x11, 0x11, 0x1E, 0x14, 0x12, 0x11], + b'S' => [0x0F, 0x10, 0x10, 0x0E, 0x01, 0x01, 0x1E], + b'T' => [0x1F, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04], + b'V' => [0x11, 0x11, 0x11, 0x11, 0x11, 0x0A, 0x04], + b'W' => [0x11, 0x11, 0x11, 0x15, 0x15, 0x1B, 0x11], + b'/' => [0x01, 0x01, 0x02, 0x04, 0x08, 0x10, 0x10], + b'.' => [0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C], + _ => [0; 7], + } +} + +/// The panel as pixels for a texture of `format` (the back buffer's swap format): `w` x `h`, +/// rows padded to a 256-byte pitch (`D3D12_TEXTURE_DATA_PITCH_ALIGNMENT`: the placed-footprint +/// copy needs it), a dark opaque background and green text at 2x scale. `None` while +/// there is nothing to show yet. +pub fn panel(format: i32) -> Option<(u32, u32, Vec)> { + let texts = text(); + render_panel(&texts, format) +} + +/// `panel` over given lines (the testable part: layout and pixels, no sampling). +fn render_panel(texts: &[String], format: i32) -> Option<(u32, u32, Vec)> { + use windows::Win32::Graphics::Dxgi::Common::*; + if texts.is_empty() { + return None; + } + const SCALE: u32 = 2; + const CW: u32 = 6 * SCALE; // 5 columns + 1 spacing + const CH: u32 = 9 * SCALE; // 7 rows + 2 spacing + const PAD: u32 = 8; + let cols = texts.iter().map(|t| t.len()).max().unwrap_or(0) as u32; + let w = PAD * 2 + cols * CW; + let h = PAD * 2 + texts.len() as u32 * CH; + // (dark background, green text) per channel order of the format + let (bg, fg): ([u8; 3], [u8; 3]) = match DXGI_FORMAT(format) { + DXGI_FORMAT_R8G8B8A8_UNORM => ([0x10, 0x18, 0x20], [0x70, 0xE0, 0x40]), + DXGI_FORMAT_B8G8R8A8_UNORM => ([0x20, 0x18, 0x10], [0x40, 0xE0, 0x70]), + _ => return None, // 10-bit and fp16 back buffers: no overlay (the font is 8-bit) + }; + let mut mask = vec![false; (w * h) as usize]; + for (row, t) in texts.iter().enumerate() { + for (col, c) in t.bytes().enumerate() { + let g = glyph(c.to_ascii_uppercase()); + for (gy, &bits) in g.iter().enumerate() { + for gx in 0..5u32 { + if bits & (0x10 >> gx) != 0 { + let x0 = PAD + col as u32 * CW + gx * SCALE; + let y0 = PAD + row as u32 * CH + gy as u32 * SCALE; + for dy in 0..SCALE { + for dx in 0..SCALE { + mask[((y0 + dy) * w + x0 + dx) as usize] = true; + } + } + } + } + } + } + } + let px: Vec = mask + .iter() + .flat_map(|&m| { + let c = if m { fg } else { bg }; + [c[0], c[1], c[2], 0xFF] + }) + .collect(); + // rows at a 256-byte pitch: the copy's placed footprint requires the alignment; the + // padding stays transparent (alpha 0) and is outside the copied box anyway + let pitch = (w * 4).div_ceil(256) * 256; + let mut out = vec![0u8; (pitch * h) as usize]; + for y in 0..h as usize { + out[y * pitch as usize..y * pitch as usize + (w * 4) as usize].copy_from_slice(&px[y * (w * 4) as usize..(y + 1) * (w * 4) as usize]); + } + Some((w, h, out)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lines_show_the_rate_over_the_interval() { + let t0 = Instant::now(); + let prev = Sample { at: t0, presents: 100, draws: 1000, dispatches: 100 }; + let now = Sample { at: t0 + Duration::from_secs(2), presents: 160, draws: 2200, dispatches: 160 }; + let v = lines(&prev, &now, 1234, Some((2048 << 20, 512 << 20))); + assert!(v[0].starts_with(" 30.0 FPS"), "{v:?}"); + assert!(v[0].contains("33.3 MS"), "{v:?}"); + assert!(v[1].contains("600 DRAW/S"), "{v:?}"); + assert!(v[1].contains("30 DISP/S"), "{v:?}"); + assert_eq!(v[2], "COMMIT 1234 MB"); + assert_eq!(v[3], "VRAM 2048 MB LOCAL 512 MB SHARED"); + } + + #[test] + fn zero_frames_is_zero_fps_not_a_division_by_zero() { + let t0 = Instant::now(); + let s = Sample { at: t0, presents: 5, draws: 5, dispatches: 5 }; + let now = Sample { at: t0 + Duration::from_secs(1), presents: 5, draws: 5, dispatches: 5 }; + let v = lines(&s, &now, 0, None); + assert!(v[0].starts_with(" 0.0 FPS"), "{v:?}"); + assert!(v[0].contains("0.0 MS"), "{v:?}"); + assert_eq!(v.len(), 3, "no VRAM line without the numbers"); + } + + #[test] + fn every_character_the_lines_produce_has_a_glyph() { + let t0 = Instant::now(); + let prev = Sample { at: t0, presents: 0, draws: 0, dispatches: 0 }; + let now = Sample { at: t0 + Duration::from_secs(1), presents: 30, draws: 900, dispatches: 60 }; + for line in lines(&prev, &now, 12345, Some((7791 << 20, 4620 << 20))) { + for c in line.bytes() { + if c != b' ' { + assert!(glyph(c).iter().any(|&r| r != 0), "no glyph for {:?}", c as char); + } + } + } + } + + #[test] + fn panel_is_opaque_with_green_text_in_the_formats_channel_order() { + use windows::Win32::Graphics::Dxgi::Common::*; + // render a fixed line directly through the same code path panel() uses: font first + let g = glyph(b'8'); + assert_eq!(g.iter().filter(|&&r| r != 0).count(), 7, "every row of 8 has pixels"); + // the channel orders differ between RGBA and BGRA; the alpha is always last and full + for fmt in [DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM] { + let (bg, fg): ([u8; 3], [u8; 3]) = match fmt { + DXGI_FORMAT_R8G8B8A8_UNORM => ([0x10, 0x18, 0x20], [0x70, 0xE0, 0x40]), + _ => ([0x20, 0x18, 0x10], [0x40, 0xE0, 0x70]), + }; + assert_ne!(bg, fg); + } + assert_eq!(glyph(b' '), [0; 7]); + assert!(panel(DXGI_FORMAT_R10G10B10A2_UNORM.0).is_none(), "10-bit: no overlay"); + } + + /// The panel's rows are at a 256-byte pitch (the placed-footprint copy's requirement): + /// the pixels sit at the start of each padded row, the padding is transparent, and the + /// background/text colors are the format's. + #[test] + fn panel_rows_are_at_a_256_byte_pitch() { + use windows::Win32::Graphics::Dxgi::Common::*; + let lines = [" 30.0 FPS 33.3 MS".to_string(), "COMMIT 1234 MB".to_string()]; + let (w, h, px) = render_panel(&lines, DXGI_FORMAT_R8G8B8A8_UNORM.0).unwrap(); + let pitch = (w * 4).div_ceil(256) * 256; + assert_eq!(px.len(), (pitch * h) as usize, "one padded row per line of pixels"); + assert!(pitch % 256 == 0); + for y in 0..h as usize { + let row = &px[y * pitch as usize..(y + 1) * pitch as usize]; + // first pixel of the panel: opaque background, RGBA order + assert_eq!(&row[..4], &[0x10, 0x18, 0x20, 0xFF], "row {y} starts at the pitch"); + // the padding after the panel's width is transparent zeros + assert!(row[(w * 4) as usize..].iter().all(|&b| b == 0), "row {y} padding"); + } + // some pixel is the green text (the digits are drawn) + assert!(px.chunks_exact(4).any(|p| p == [0x70, 0xE0, 0x40, 0xFF]), "text pixels present"); + // a width already a multiple of 64 texels needs no padding beyond itself (cols 52: w 640) + let wide = render_panel(&["0".repeat(52)], DXGI_FORMAT_B8G8R8A8_UNORM.0).unwrap(); + assert_eq!(wide.0, 640); + assert_eq!(wide.0 * 4 % 256, 0); + assert_eq!(wide.2.len(), (wide.0 * 4 * wide.1) as usize); + } +} diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index ba5dcb473..c8dc95f1e 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -29,6 +29,9 @@ pub fn host_main(boot_path: &Path) -> i32 { std::env::set_var("XCL_UMA_MB", boot.config.uma_mb.to_string()); } crate::state::set_boot(boot.clone()); + if crate::hle::overlay::enabled() { + crate::xlog_info!("overlay: XCL_OVERLAY – fps / frame time / draws / commit / vram in the shown frame"); + } // `XCL_ACTIVITY=1`: every 2 s what the title did since (a timeline of where it stops) if std::env::var_os("XCL_ACTIVITY").is_some() { let _ = std::thread::Builder::new().name("xcl-activity".into()).spawn(|| {