From f462cf64b4f949a85a01d5651910caaa51eddc57 Mon Sep 17 00:00:00 2001 From: Simon Date: Tue, 24 Nov 2026 02:04:46 +0100 Subject: [PATCH 1/3] D3D12.X: shrink the game image to the window with an area filter Text and thin lines of a retail title looked jagged in the XCL window. Root cause: the title presents 3840x2160, present.rs copied it into a swap chain of the same size (DXGI_SCALING_STRETCH) and DWM shrank it to the window (1280x720 by default) with a single bilinear tap per pixel: at 3x or 1.5x it skips texels, so strokes get uneven and edges stair-step. A full-size frame dump of the same frame is clean. When the window's client area is smaller than the image on either side, the swap chain now takes the client size (ResizeBuffers on resize) and a full-screen triangle draws the image into it: its pixel shader averages the whole footprint of each window pixel (area filter, exact partial texel weights), in linear light - 8/10-bit UNORM decoded and encoded with the sRGB curve (the swap chain's default colour space), an _SRGB source through its view, FP16 (scRGB) as is. A window as large as the image keeps the copy; a minimized one (0x0) shows nothing and keeps its swap chain. Without DXC (or a pipeline the device refuses) the copy stays, with one log line. Frame dumps still read the title's own image. One "present:" line names the route and the sizes. Resizes: the presenter draws on the title's adopted device, whose CreateRenderTargetView hook (note_rtv) keeps a reference to every view's resource; the filter's view of a back buffer would hold one swap chain buffer and make every ResizeBuffers fail (DXGI_ERROR_INVALID_CALL), so Scaler::record forgets its own view at once. A refused ResizeBuffers is logged once per size and asked for again twice a second; the frame is still shown, drawn at the swap chain's current size. present_now's per-frame work is present_frame, so a test can drive it. Tests: the route decision; a GPU test drawing 1-pixel lines and a checker from 3840x2160 and 1920x1080 into 1280x720 against a CPU area filter (within 1.5 of 255); a GPU test on an adopted device with a hidden window: frames at 1280x720, 1920x1080, 800x450 (each new back buffer matches the CPU filter), minimized, 1280x720 again, and a refused resize that still shows the frame. Assisted-by: Claude Code (Claude Opus 5.5) --- crates/xcl/src/hle/d3d12x/present.rs | 169 +++++- .../xcl/src/hle/d3d12x/present/downscale.rs | 531 ++++++++++++++++++ 2 files changed, 669 insertions(+), 31 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/present/downscale.rs diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 83a909468..2fc5adcd6 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -34,6 +34,9 @@ use windows::Win32::UI::WindowsAndMessaging::*; use crate::gpu::fence::{self, FenceError}; use crate::stubs::StubInfo; +mod downscale; +use downscale::Route; + static RTVS: Mutex>> = Mutex::new(None); static LISTS: Mutex>> = Mutex::new(None); static CANDIDATE: Mutex> = Mutex::new(None); // (queue, resource) – resource AddRef'd @@ -530,6 +533,14 @@ struct Presenter { fence: ID3D12Fence, copy_source: Option, dumps: Vec, + /// the area filter for a window smaller than the image (`downscale`); failed: copy only + scaler: Option, + scaler_failed: bool, + /// the route last logged, with the image size + route: Option<(Route, (u32, u32))>, + /// the swap chain size (and format) ResizeBuffers last refused, and when: logged once, + /// asked for again twice a second + resize_failed: Option<((u32, u32, DXGI_FORMAT), Instant)>, disabled: bool, value: u64, event: HANDLE, @@ -566,6 +577,11 @@ unsafe fn transition(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: unsafe fn new_presenter(queue: usize) -> Option { let dev_raw = super::real::device_raw(); let dev = ID3D12Device::from_raw_borrowed(&dev_raw)?; + presenter_for(dev, queue) +} + +/// A presenter on `dev` for the title's `queue` (its swap chain is made at the first frame). +unsafe fn presenter_for(dev: &ID3D12Device, queue: usize) -> Option { let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?; let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).ok()?; list.Close().ok()?; @@ -573,24 +589,41 @@ 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(), scaler: None, scaler_failed: false, route: None, resize_failed: None, disabled: false, value: 0, event, last: Instant::now() - Duration::from_secs(1), }) } unsafe fn ensure_swapchain(p: &mut Presenter, hwnd: HWND, w: u32, h: u32, fmt: DXGI_FORMAT) -> bool { - if let Some(sc) = &p.sc { + if let Some(sc) = p.sc.clone() { if p.w == w && p.h == h && p.fmt == fmt { return true; } - if sc.ResizeBuffers(2, w, h, fmt, DXGI_SWAP_CHAIN_FLAG(0)).is_ok() { - p.w = w; - p.h = h; - p.fmt = fmt; - crate::xlog_info!("present: swap chain {w}x{h} {:?}", fmt); - return true; + let want = (w, h, fmt); + // a size refused just now is not asked for again every frame + if p.resize_failed.is_some_and(|(f, t)| f == want && t.elapsed() < Duration::from_millis(500)) { + return false; + } + // the GPU is done with the back buffers: every draw into them came before the previous + // copy's signal on this queue, waited for in `present_frame` + match sc.ResizeBuffers(2, w, h, fmt, DXGI_SWAP_CHAIN_FLAG(0)) { + Ok(()) => { + p.w = w; + p.h = h; + p.fmt = fmt; + p.resize_failed = None; + crate::xlog_info!("present: swap chain {w}x{h} {:?}", fmt); + return true; + } + Err(e) => { + if p.resize_failed.map(|(f, _)| f) != Some(want) { + let why = e.message(); + crate::xlog_warn!("present: ResizeBuffers to {w}x{h} {fmt:?}: {:#010x} {} – the swap chain stays {}x{}", e.code().0 as u32, why.lines().next().unwrap_or_default(), p.w, p.h); + } + p.resize_failed = Some((want, Instant::now())); + return false; + } } - return false; } let Ok(factory) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) else { return false }; let qraw = p.queue as *mut c_void; @@ -668,36 +701,84 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { return; } let Some(desc) = backbuffer_like(src.as_raw() as usize) else { return }; - let Some(fmt) = swap_format(desc.Format) else { return }; let Some(hwnd) = ensure_window() else { return }; if p.queue != queue { return; // swap chain is bound to the first queue we presented from } + if !present_frame(p, hwnd, src, &desc) { + return; + } + let n = PRESENTS.fetch_add(1, Ordering::Relaxed); + if n == 0 { + crate::xlog_info!("present: first game frame shown ({}x{})", desc.Width, desc.Height); + } +} + +/// Show `src` (described by `desc`) in `hwnd` through `p`'s swap chain, on `p.queue`: false when +/// no frame was shown (minimized, the previous copy not done in time, an error). +unsafe fn present_frame(p: &mut Presenter, hwnd: HWND, src: ID3D12Resource, desc: &D3D12_RESOURCE_DESC) -> bool { + let Some(fmt) = swap_format(desc.Format) else { return false }; // wait for the previous copy so the allocator can be reused if let Err(e) = fence::wait(&p.fence, p.value, &p.dev, Some(p.event), 100) { p.disabled = matches!(&e, FenceError::Removed(_)); if !matches!(&e, FenceError::Timeout(_)) { crate::xlog_error!("present: previous copy: {e}"); } - return; + return false; } p.copy_source = None; p.dumps.clear(); - if !ensure_swapchain(p, hwnd, desc.Width as u32, desc.Height, fmt) { - return; + let image = (desc.Width as u32, desc.Height); + let client = client_size(hwnd); + let mut route = downscale::route(image, client); + if route == Route::Filter && !scaler_ready(p, fmt) { + route = Route::Copy; + } + if p.route != Some((route, image)) { + let how = match route { + Route::Filter => "area filter into a swap chain of the client size", + Route::Copy => "copy, the window stretches it", + Route::Skip => "nothing shown, the swap chain keeps its size", + }; + crate::xlog_info!("present: {}x{} image in a {}x{} client area – {how}", image.0, image.1, client.0, client.1); + p.route = Some((route, image)); + } + if route == Route::Skip { + return false; } - let Some(sc) = p.sc.clone() else { return }; - let Ok(bb) = sc.GetBuffer::(sc.GetCurrentBackBufferIndex()) else { return }; + let (mut sw, mut sh) = if route == Route::Filter { client } else { image }; + if !ensure_swapchain(p, hwnd, sw, sh, fmt) { + // the swap chain keeps its size this frame and the filter draws the image into it (the + // window stretches it): a resize never costs a frame + if p.sc.is_none() || !scaler_ready(p, p.fmt) { + return false; + } + (route, sw, sh) = (Route::Filter, p.w, p.h); + } + let Some(sc) = p.sc.clone() else { return false }; + let Ok(bb) = sc.GetBuffer::(sc.GetCurrentBackBufferIndex()) else { return false }; if p.alloc.Reset().is_err() || p.list.Reset(&p.alloc, None).is_err() { - return; + return false; } - let b1 = [transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST)]; - p.list.ResourceBarrier(&b1); - p.list.CopyResource(&bb, &src); + // the back buffer's state while it is written + let written = match (route, &p.scaler) { + (Route::Filter, Some(scaler)) => { + p.list.ResourceBarrier(&[transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)]); + // the title's image is promoted from COMMON to a shader resource, as for the copy + scaler.record(&p.dev, &p.list, &src, &bb, sw, sh); + D3D12_RESOURCE_STATE_RENDER_TARGET + } + _ => { + let b1 = [transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST)]; + p.list.ResourceBarrier(&b1); + p.list.CopyResource(&bb, &src); + D3D12_RESOURCE_STATE_COPY_DEST + } + }; let due = frame_dump_due(); let mut dumps = Vec::new(); if due { - if let Some((buffer, footprint)) = readback_copy(&p.list, &src, &desc) { + if let Some((buffer, footprint)) = readback_copy(&p.list, &src, desc) { dumps.push(FrameDump { _source: src.clone(), buffer, footprint, format: desc.Format, tag: "frame".into() }); } } @@ -724,14 +805,14 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { dumps.push(FrameDump { _source: res, buffer, footprint, format, tag }); } } - let b2 = [transition(&bb, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT)]; + let b2 = [transition(&bb, written, D3D12_RESOURCE_STATE_PRESENT)]; p.list.ResourceBarrier(&b2); if p.list.Close().is_err() { - return; + return false; } - let qraw = queue as *mut c_void; - let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&qraw) else { return }; - let Ok(cl) = p.list.cast::() else { return }; + let qraw = p.queue as *mut c_void; + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&qraw) else { return false }; + let Ok(cl) = p.list.cast::() else { return false }; q.ExecuteCommandLists(&[Some(cl)]); p.copy_source = Some(src); p.dumps = dumps; @@ -741,13 +822,13 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { p.disabled = true; let e = fence::api_error(&p.dev, "Signal", e); crate::xlog_error!("present: submit copy: {e}"); - return; + return false; } if let Err(e) = sc.Present(0, DXGI_PRESENT(0)).ok() { let e = fence::api_error(&p.dev, "Present", e); p.disabled = matches!(&e, FenceError::Removed(_)); crate::xlog_error!("present: {e}"); - return; + return false; } p.last = Instant::now(); if !p.dumps.is_empty() { @@ -761,15 +842,41 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { p.disabled = matches!(&e, FenceError::Removed(_)); crate::xlog_error!("present: frame dump copy: {e}"); if p.disabled { - return; + return false; } } } } - let n = PRESENTS.fetch_add(1, Ordering::Relaxed); - if n == 0 { - crate::xlog_info!("present: first game frame shown ({}x{})", desc.Width, desc.Height); + true +} + +/// The XCL window's client area (0x0 when minimized or unknown). +unsafe fn client_size(hwnd: HWND) -> (u32, u32) { + let mut rc = RECT::default(); + if GetClientRect(hwnd, &mut rc).is_err() { + return (0, 0); + } + ((rc.right - rc.left).max(0) as u32, (rc.bottom - rc.top).max(0) as u32) +} + +/// The area filter for back buffers of `fmt` is made (once per format; a failure – no DXC – +/// leaves the copy for good, with one log line). +unsafe fn scaler_ready(p: &mut Presenter, fmt: DXGI_FORMAT) -> bool { + if p.scaler.as_ref().is_some_and(|s| s.fmt == fmt) { + return true; + } + // inside a non-blocking pipeline creation nothing may compile: the copy this time + if p.scaler_failed || crate::gpu::recomp::dxc::in_cached_only() { + return false; + } + match downscale::Scaler::new(&p.dev, fmt) { + Ok(s) => p.scaler = Some(s), + Err(e) => { + p.scaler_failed = true; + crate::xlog_warn!("present: no area filter for a window smaller than the image ({e}) – the window stretches the copy"); + } } + p.scaler.is_some() } /// `XCL_FRAME_DUMP=1`: every 120th shown frame is written to the logs folder (`XCL_FRAME_DUMP=n`, diff --git a/crates/xcl/src/hle/d3d12x/present/downscale.rs b/crates/xcl/src/hle/d3d12x/present/downscale.rs new file mode 100644 index 000000000..dad8c59d4 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/present/downscale.rs @@ -0,0 +1,531 @@ +//! The title's image shrunk to the XCL window's client area by XCL itself. +//! +//! A 3840x2160 frame copied into a swap chain of its own size is shrunk by DWM with a single +//! bilinear tap per window pixel: at 3x (1280x720) or 1.5x it skips texels, and thin strokes and +//! text stair-step. Here the swap chain is the client size instead, and a full-screen triangle's +//! pixel shader averages the whole footprint of each window pixel in the game image (an area / +//! box filter, exact partial-texel weights), in linear light. +//! +//! Linear light: 8- and 10-bit UNORM images are decoded with the sRGB curve before averaging +//! and encoded again after – the swap chain has the default (sRGB) colour space, so that is how +//! the window shows those values; an _SRGB source is decoded by its view. FP16 is scRGB, linear +//! already. + +use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// How the title's image reaches the window. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Route { + /// copied into a swap chain of the image's size, DWM stretches it (the window is as large) + Copy, + /// drawn into a swap chain of the client size through the area filter + Filter, + /// not shown: the client area is empty (minimized), the swap chain keeps its size + Skip, +} + +/// `Skip` when the client area is empty (minimized); `Filter` when it is smaller than the image +/// on either side; `Copy` when it is as large or larger. +pub fn route(image: (u32, u32), client: (u32, u32)) -> Route { + if client.0 == 0 || client.1 == 0 { + Route::Skip + } else if client.0 >= image.0 && client.1 >= image.1 { + Route::Copy + } else { + Route::Filter + } +} + +const SHADER: &str = r#" +#define RS "RootConstants(num32BitConstants=4, b0), DescriptorTable(SRV(t0), visibility=SHADER_VISIBILITY_PIXEL)" +Texture2D src : register(t0); +cbuffer C : register(b0) { uint2 dst; uint flags; uint pad; }; + +[RootSignature(RS)] +float4 vs(uint id : SV_VertexID) : SV_Position { + float2 t = float2((id << 1) & 2, id & 2); + return float4(t * float2(2, -2) + float2(-1, 1), 0, 1); +} + +float3 decode(float3 c) { return select(c <= 0.04045, c / 12.92, pow((c + 0.055) / 1.055, 2.4)); } +float3 encode(float3 c) { return select(c <= 0.0031308, c * 12.92, 1.055 * pow(c, 1.0 / 2.4) - 0.055); } + +// the mean of the texels under this window pixel, each weighted by the area it covers +[RootSignature(RS)] +float4 ps(float4 pos : SV_Position) : SV_Target { + uint sw, sh; + src.GetDimensions(sw, sh); + float2 s = float2(sw, sh) / float2(dst); + float2 lo = floor(pos.xy) * s; + float2 hi = min(lo + s, float2(sw, sh)); + int2 a = (int2)floor(lo); + int2 b = (int2)ceil(hi); + float4 sum = 0; + float total = 0; + for (int y = a.y; y < b.y; y++) { + float wy = min(hi.y, y + 1) - max(lo.y, y); + for (int x = a.x; x < b.x; x++) { + float w = wy * (min(hi.x, x + 1) - max(lo.x, x)); + float4 c = src.Load(int3(x, y, 0)); + if (flags & 1) c.rgb = decode(saturate(c.rgb)); + sum += c * w; + total += w; + } + } + float4 r = sum / max(total, 1e-6); + if (flags & 2) r.rgb = encode(saturate(r.rgb)); + return r; +} +"#; + +/// The area-filter pipeline for one back buffer format, with its two descriptors. +pub struct Scaler { + pub fmt: DXGI_FORMAT, + rs: ID3D12RootSignature, + pso: ID3D12PipelineState, + srv: ID3D12DescriptorHeap, + rtv: ID3D12DescriptorHeap, +} + +/// The SRV format for a source of `f` (a typeless one is read as UNORM / FLOAT, like the copy). +fn view_format(f: DXGI_FORMAT) -> DXGI_FORMAT { + match f { + DXGI_FORMAT_R8G8B8A8_TYPELESS => DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_FORMAT_B8G8R8A8_TYPELESS => DXGI_FORMAT_B8G8R8A8_UNORM, + DXGI_FORMAT_R10G10B10A2_TYPELESS => DXGI_FORMAT_R10G10B10A2_UNORM, + DXGI_FORMAT_R16G16B16A16_TYPELESS => DXGI_FORMAT_R16G16B16A16_FLOAT, + f => f, + } +} + +impl Scaler { + /// The pipeline drawing into a `fmt` render target on `dev` (Err: no DXC, or the device + /// refused it). + pub unsafe fn new(dev: &ID3D12Device, fmt: DXGI_FORMAT) -> Result { + use crate::gpu::recomp::dxc::compile_cached; + let (vs, _) = compile_cached(SHADER, "vs", "vs_6_0")?; + let (ps, _) = compile_cached(SHADER, "ps", "ps_6_0")?; + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &ps).map_err(|e| format!("CreateRootSignature: {e}"))?; + let mut pd = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&rs), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as _, BytecodeLength: vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as _, BytecodeLength: ps.len() }, + SampleMask: u32::MAX, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pd.RTVFormats[0] = fmt; + let pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&pd).map_err(|e| format!("CreateGraphicsPipelineState: {e}"))?; + let heap = |ty, flags| { + dev.CreateDescriptorHeap::(&D3D12_DESCRIPTOR_HEAP_DESC { Type: ty, NumDescriptors: 1, Flags: flags, NodeMask: 0 }) + .map_err(|e| format!("CreateDescriptorHeap: {e}")) + }; + let srv = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)?; + let rtv = heap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE)?; + Ok(Scaler { fmt, rs, pso, srv, rtv }) + } + + /// Record on `list` the draw of `src` (subresource 0, readable as a pixel shader resource) + /// over all of `dst` (`w`x`h`, `self.fmt`, in RENDER_TARGET state). The descriptors are + /// rewritten: the previous recording must have finished on the GPU. + pub unsafe fn record(&self, dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, src: &ID3D12Resource, dst: &ID3D12Resource, w: u32, h: u32) { + let view = view_format(src.GetDesc().Format); + let srv_desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: view, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, ..Default::default() } }, + }; + dev.CreateShaderResourceView(src, Some(&srv_desc), self.srv.GetCPUDescriptorHandleForHeapStart()); + let rtv = self.rtv.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(dst, None, rtv); + // `dev` is the title's (adopted) device: its CreateRenderTargetView hook keeps a reference + // to the view's resource for guessing the title's frame (`note_rtv`). Held on a swap chain + // buffer, that reference makes every ResizeBuffers fail (DXGI_ERROR_INVALID_CALL): the + // presenter's own view is forgotten at once. + super::note_rtv(rtv.ptr, std::ptr::null_mut()); + let decode = matches!(view, DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM | DXGI_FORMAT_R10G10B10A2_UNORM); + let encode = self.fmt != DXGI_FORMAT_R16G16B16A16_FLOAT; + let constants = [w, h, decode as u32 | (encode as u32) << 1, 0]; + list.SetGraphicsRootSignature(&self.rs); + list.SetDescriptorHeaps(&[Some(self.srv.clone())]); + list.SetGraphicsRoot32BitConstants(0, 4, constants.as_ptr() as _, 0); + list.SetGraphicsRootDescriptorTable(1, self.srv.GetGPUDescriptorHandleForHeapStart()); + list.SetPipelineState(&self.pso); + list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list.RSSetViewports(&[D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: w as f32, Height: h as f32, MinDepth: 0.0, MaxDepth: 1.0 }]); + list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { left: 0, top: 0, right: w as i32, bottom: h as i32 }]); + list.OMSetRenderTargets(1, Some(&rtv as *const _), false, None); + list.DrawInstanced(3, 1, 0, 0); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use windows::core::{w, Interface, PCWSTR}; + use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + use windows::Win32::System::LibraryLoader::GetModuleHandleW; + use windows::Win32::UI::WindowsAndMessaging::*; + + #[test] + fn route_filters_only_when_the_window_is_smaller() { + let uhd = (3840, 2160); + for client in [(1280, 720), (1920, 1080), (2560, 1440), (3840, 2000), (3000, 2160)] { + assert_eq!(route(uhd, client), Route::Filter, "{client:?}"); + } + for client in [(3840, 2160), (5120, 2880)] { + assert_eq!(route(uhd, client), Route::Copy, "{client:?}"); + } + // minimized: nothing shown – not a copy into a swap chain resized to the image + for client in [(0, 0), (1280, 0), (0, 720)] { + assert_eq!(route(uhd, client), Route::Skip, "{client:?}"); + } + } + + fn srgb_to_linear(c: f64) -> f64 { + if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } + } + + fn linear_to_srgb(c: f64) -> f64 { + if c <= 0.0031308 { c * 12.92 } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 } + } + + /// 1-pixel lines and a 1-pixel checker, the hard case for a single bilinear tap. + fn pattern(w: usize, h: usize) -> Vec { + let mut v = vec![0u8; w * h * 4]; + for y in 0..h { + for x in 0..w { + let t = &mut v[(y * w + x) * 4..][..4]; + t[0] = if (x + y) % 2 == 0 { 255 } else { 0 }; + t[1] = if x % 7 == 0 || y % 5 == 0 { 255 } else { 16 }; + t[2] = ((x * 3 + y * 5) % 256) as u8; + t[3] = 255; + } + } + v + } + + /// The area filter on the CPU, in linear light (sRGB curve), as 8-bit sRGB. + fn reference(src: &[u8], sw: usize, sh: usize, dw: usize, dh: usize) -> Vec<[f64; 3]> { + let lut: Vec = (0..256).map(|v| srgb_to_linear(v as f64 / 255.0)).collect(); + let (sx, sy) = (sw as f64 / dw as f64, sh as f64 / dh as f64); + let mut out = Vec::with_capacity(dw * dh); + for oy in 0..dh { + let (ly, hy) = (oy as f64 * sy, (oy as f64 + 1.0) * sy); + for ox in 0..dw { + let (lx, hx) = (ox as f64 * sx, (ox as f64 + 1.0) * sx); + let (mut sum, mut total) = ([0.0; 3], 0.0); + for y in ly.floor() as usize..(hy.ceil() as usize).min(sh) { + let wy = hy.min(y as f64 + 1.0) - ly.max(y as f64); + for x in lx.floor() as usize..(hx.ceil() as usize).min(sw) { + let wt = wy * (hx.min(x as f64 + 1.0) - lx.max(x as f64)); + for c in 0..3 { + sum[c] += wt * lut[src[(y * sw + x) * 4 + c] as usize]; + } + total += wt; + } + } + out.push(sum.map(|s| 255.0 * linear_to_srgb(s / total))); + } + } + out + } + + fn buffer(dev: &ID3D12Device, size: u64, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES) -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut r: Option = None; + unsafe { dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap() }; + r.unwrap() + } + + fn texture(dev: &ID3D12Device, w: u32, h: u32, flags: D3D12_RESOURCE_FLAGS, state: D3D12_RESOURCE_STATES) -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w as u64, + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: flags, + ..Default::default() + }; + let mut r: Option = None; + unsafe { dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap() }; + r.unwrap() + } + + fn copy_location(r: &ID3D12Resource, fp: Option) -> D3D12_TEXTURE_COPY_LOCATION { + unsafe { + match fp { + Some(fp) => D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }, + None => D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }, + } + } + } + + /// A `w`x`h` RGBA8 texture holding `src`, left in `after`: the upload is recorded on `list` + /// (the upload buffer returned with it must live until the list ran). + unsafe fn upload(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, src: &[u8], w: u32, h: u32, after: D3D12_RESOURCE_STATES) -> (ID3D12Resource, ID3D12Resource) { + let tex = texture(dev, w, h, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + let (mut fp, mut size) = (D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(), 0u64); + dev.GetCopyableFootprints(&tex.GetDesc(), 0, 1, 0, Some(&mut fp), None, None, Some(&mut size)); + let up = buffer(dev, size, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).unwrap(); + for y in 0..h as usize { + let row = &src[y * w as usize * 4..][..w as usize * 4]; + std::ptr::copy_nonoverlapping(row.as_ptr(), (p as *mut u8).add(fp.Offset as usize + y * fp.Footprint.RowPitch as usize), row.len()); + } + up.Unmap(0, None); + list.CopyTextureRegion(©_location(&tex, None), 0, 0, 0, ©_location(&up, Some(fp)), None); + list.ResourceBarrier(&[super::super::transition(&tex, D3D12_RESOURCE_STATE_COPY_DEST, after)]); + (tex, up) + } + + /// `list` closed, run on `queue` and waited for. + unsafe fn run(dev: &ID3D12Device, queue: &ID3D12CommandQueue, list: &ID3D12GraphicsCommandList) { + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, dev, None, 30_000).unwrap(); + } + + /// The `w`x`h` RGBA8 texels of a readback (`readback_copy`) that ran. + unsafe fn texels(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, w: u32, h: u32) -> Vec { + let mut out = vec![0u8; (w * h * 4) as usize]; + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + for y in 0..h as usize { + let row = &mut out[y * w as usize * 4..][..w as usize * 4]; + std::ptr::copy_nonoverlapping((p as *const u8).add(fp.Offset as usize + y * fp.Footprint.RowPitch as usize), row.as_mut_ptr(), row.len()); + } + rb.Unmap(0, None); + out + } + + /// `src` (sw x sh RGBA8) through the scaler into a dw x dh target, read back as RGBA8. + unsafe fn downscale(dev: &ID3D12Device, scaler: &Scaler, src: &[u8], sw: u32, sh: u32, dw: u32, dh: u32) -> Vec { + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let (tex, _up) = upload(dev, &list, src, sw, sh, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + let rt = texture(dev, dw, dh, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_RENDER_TARGET); + scaler.record(dev, &list, &tex, &rt, dw, dh); + list.ResourceBarrier(&[super::super::transition(&rt, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let (rb, fp) = super::super::readback_copy(&list, &rt, &rt.GetDesc()).unwrap(); + run(dev, &queue, &list); + texels(&rb, &fp, dw, dh) + } + + /// `got` (dw pixels a row, RGBA8) is the CPU area filter's `want` within 1.5 of 255. + fn check(got: &[u8], want: &[[f64; 3]], dw: usize, what: &str) { + let mut worst = (0.0f64, 0usize); + for (i, w) in want.iter().enumerate() { + for c in 0..3 { + let d = (got[i * 4 + c] as f64 - w[c]).abs(); + if d > worst.0 { + worst = (d, i); + } + } + } + let i = worst.1; + assert!(worst.0 <= 1.5, "{what}: pixel ({}, {}) is {:?}, the area filter gives {:?}", i % dw, i / dw, &got[i * 4..i * 4 + 3], want[i]); + } + + /// A device on the GPU, else on WARP. + fn device() -> Option { + let mut dev: Option = None; + unsafe { + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp = CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()).ok()?; + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).ok()?; + } + } + dev + } + + /// 3840x2160 → 1280x720 (3x) and 1920x1080 → 1280x720 (1.5x) match the CPU area filter. + #[test] + fn downscale_matches_a_cpu_area_filter() { + unsafe { + let Some(dev) = device() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + if crate::gpu::recomp::dxc::location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + let scaler = Scaler::new(&dev, DXGI_FORMAT_R8G8B8A8_UNORM).unwrap(); + for (sw, sh) in [(3840u32, 2160u32), (1920, 1080)] { + let (dw, dh) = (1280u32, 720u32); + let src = pattern(sw as usize, sh as usize); + let got = downscale(&dev, &scaler, &src, sw, sh, dw, dh); + let want = reference(&src, sw as usize, sh as usize, dw as usize, dh as usize); + check(&got, &want, dw as usize, &format!("{sw}x{sh} → {dw}x{dh}")); + } + } + } + + /// A hidden popup window (no frame: the client area is the whole window) on a thread of its + /// own that pumps its messages, as the XCL window is. + struct TestWindow { + hwnd: HWND, + thread: Option>, + } + + unsafe extern "system" fn test_wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { + if msg == WM_DESTROY { + PostQuitMessage(0); + return LRESULT(0); + } + DefWindowProcW(hwnd, msg, wp, lp) + } + + impl TestWindow { + fn new() -> TestWindow { + let (tx, rx) = std::sync::mpsc::channel(); + let thread = std::thread::spawn(move || unsafe { + let inst = GetModuleHandleW(PCWSTR::null()).unwrap(); + let class = w!("XCLPresentTestWindow"); + let wc = WNDCLASSW { + lpfnWndProc: Some(test_wndproc), + hInstance: inst.into(), + lpszClassName: class, + ..Default::default() + }; + RegisterClassW(&wc); + let hwnd = CreateWindowExW(WINDOW_EX_STYLE(0), class, w!("XCL present test"), WS_POPUP, 0, 0, 1280, 720, None, None, Some(inst.into()), None).unwrap(); + tx.send(hwnd.0 as isize).unwrap(); + let mut msg = MSG::default(); + while GetMessageW(&mut msg, None, 0, 0).as_bool() { + DispatchMessageW(&msg); + } + }); + TestWindow { + hwnd: HWND(rx.recv().unwrap() as *mut std::ffi::c_void), + thread: Some(thread), + } + } + + /// The client area made `w`x`h` (0x0: as when minimized). + unsafe fn resize(&self, w: u32, h: u32) { + SetWindowPos(self.hwnd, None, 0, 0, w as i32, h as i32, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE).unwrap(); + assert_eq!(super::super::client_size(self.hwnd), (w, h)); + } + } + + impl Drop for TestWindow { + fn drop(&mut self) { + unsafe { + let _ = PostMessageW(Some(self.hwnd), WM_CLOSE, WPARAM(0), LPARAM(0)); + } + if let Some(t) = self.thread.take() { + let _ = t.join(); + } + } + } + + /// The swap chain follows the window while a title presents: 1280x720, larger (1920x1080), + /// smaller (800x450) – each frame shown at the client size, the filter drawing into the new + /// size as the CPU filter does; minimized (0x0): nothing shown and no resize; restored: shown + /// again. On an adopted device, as the title's is (its CreateRenderTargetView hook is in the + /// path). + #[test] + fn swap_chain_follows_the_window() { + use crate::hle::d3d12x::real; + unsafe { + let Some(dev) = device() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + if crate::gpu::recomp::dxc::location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + real::adopt(dev.as_raw(), real::Kind::Device); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + // inside a present, as `present_now` runs it: these submissions are not the title's frames + super::super::IN_PRESENT.with(|c| c.set(true)); + // the title's 3840x2160 image, in COMMON as PresentX hands it over + let (iw, ih) = (3840u32, 2160u32); + let pixels = pattern(iw as usize, ih as usize); + let (image, _up) = upload(&dev, &list, &pixels, iw, ih, D3D12_RESOURCE_STATE_COMMON); + run(&dev, &queue, &list); + let desc = image.GetDesc(); + let window = TestWindow::new(); + let mut p = super::super::presenter_for(&dev, queue.as_raw() as usize).expect("presenter"); + for (k, (w, h)) in [(1280u32, 720u32), (1920, 1080), (800, 450), (0, 0), (1280, 720)].into_iter().enumerate() { + window.resize(w, h); + let before = (p.w, p.h); + let shown = super::super::present_frame(&mut p, window.hwnd, image.clone(), &desc); + if w == 0 { + assert!(!shown, "minimized: nothing is shown"); + assert_eq!((p.w, p.h), before, "minimized: the swap chain keeps its size"); + continue; + } + assert!(shown, "{w}x{h}: the frame is shown"); + let sc = p.sc.clone().unwrap(); + let d = sc.GetDesc1().unwrap(); + assert_eq!((p.w, p.h, d.Width, d.Height), (w, h, w, h), "the swap chain follows the {w}x{h} client area"); + assert_eq!(p.route, Some((Route::Filter, (iw, ih)))); + if k > 2 { + continue; // a size checked already + } + // the filter into the new back buffer, read back + crate::gpu::fence::wait(&p.fence, p.value, &dev, None, 30_000).unwrap(); + let bb: ID3D12Resource = sc.GetBuffer(sc.GetCurrentBackBufferIndex()).unwrap(); + alloc.Reset().unwrap(); + list.Reset(&alloc, None).unwrap(); + list.ResourceBarrier(&[super::super::transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)]); + p.scaler.as_ref().unwrap().record(&dev, &list, &image, &bb, w, h); + list.ResourceBarrier(&[super::super::transition(&bb, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let (rb, fp) = super::super::readback_copy(&list, &bb, &bb.GetDesc()).unwrap(); + list.ResourceBarrier(&[super::super::transition(&bb, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_PRESENT)]); + run(&dev, &queue, &list); + drop(bb); + let want = reference(&pixels, iw as usize, ih as usize, w as usize, h as usize); + check(&texels(&rb, &fp, w, h), &want, w as usize, &format!("{iw}x{ih} → {w}x{h} window")); + } + // a resize DXGI refuses (a back buffer still referenced): the frame is shown anyway, + // drawn at the swap chain's size; another size is asked for at once + let held: ID3D12Resource = p.sc.as_ref().unwrap().GetBuffer(0).unwrap(); + window.resize(1920, 1080); + assert!(super::super::present_frame(&mut p, window.hwnd, image.clone(), &desc), "a refused resize still shows the frame"); + assert_eq!((p.w, p.h), (1280, 720), "refused: the swap chain keeps its size"); + drop(held); + window.resize(800, 450); + assert!(super::super::present_frame(&mut p, window.hwnd, image.clone(), &desc)); + assert_eq!((p.w, p.h), (800, 450), "the next size is asked for at once"); + // the last frame done before the presenter goes (the runtime waits too, `present_now`): + // its allocator, the filter's pipeline and descriptor heaps and the swap chain released + // under the GPU hung the device – the one every GPU test of the process shares + crate::gpu::fence::wait(&p.fence, p.value, &dev, None, 30_000).unwrap(); + drop(p); + super::super::IN_PRESENT.with(|c| c.set(false)); + } + } +} From b7900d0010b2b808ec3c77243f25c8fe40dbe6eb Mon Sep 17 00:00:00 2001 From: MrCheese5 <332716892+MrCheese5@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:20:50 +0000 Subject: [PATCH 2/3] D3D12.X: a presenter waits for its last present before it is released Dropping a Presenter released the swap chain, the scaler's descriptor heaps and the title's image while its last present's command list could still be running on the GPU. swap_chain_follows_the_window drops its presenter right after the last present_frame; when the list was still running, the device was suspended (0x887A0005) and the GPU tests that ran after it failed. That happens intermittently and depends on timing. The drop now waits for the presenter's fence (2 s at most; not after a failed Signal, when the presenter is disabled). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/present.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 2fc5adcd6..653624827 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -1100,6 +1100,11 @@ unsafe fn write_frame(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRI impl Drop for Presenter { fn drop(&mut self) { unsafe { + // the last present's list may still run: it uses the swap chain's buffers, the + // scaler's descriptors and the title's image, all released with the presenter + if !self.disabled { + let _ = fence::wait(&self.fence, self.value, &self.dev, Some(self.event), 2000); + } let _ = CloseHandle(self.event); } } From 8244a72a195d85dff35a5308c0e47535eff8c5ba Mon Sep 17 00:00:00 2001 From: MrCheese5 <332716892+MrCheese5@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:22:31 +0000 Subject: [PATCH 3/3] D3D12.X: the game's image keeps its aspect ratio in the window A 16:9 image in a window of another shape (a 21:9 or 16:10 screen) was stretched to it. The swap chain is now the client area's size and the image is placed in it by `scaling` (xcl.toml, XCL_SCALING): - "fit" (default): the aspect ratio is kept, with black bars - "integer": whole multiples only (falls back to fit in a smaller window) - "stretch": the old behaviour An image that lands 1:1 (3840x2160 in a 5120x2160 client area) is copied texel for texel at its place (Route::Place, after clearing the bars). Other sizes go through the area filter, which now draws into a rectangle (viewport + an origin root constant) with the bars cleared to black. Without DXC the old stretched copy stays. Tests: place() for each scaling, the routes, and on the GPU a 1280x720 image placed 1:1 in 1680x720 (exact texels, black bars) and filtered into 1032x432 (against a CPU area filter). Co-Authored-By: Claude Opus 5.5 --- README.md | 3 + crates/xcl/src/config.rs | 5 + crates/xcl/src/hle/d3d12x/present.rs | 84 +++++-- .../xcl/src/hle/d3d12x/present/downscale.rs | 220 +++++++++++++++--- 4 files changed, 261 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index 2a957e95e..76a75f526 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,9 @@ A **gamepad is recommended**: console games are made for one, and their menus an E / Q Y / X, Shift / Ctrl the stick clicks, Tab View, P Menu. `keyboard_mouse` and `mouse_sensitivity` in the game's `xcl.toml` turn it off or change the mouse speed. A gamepad and the keyboard / mouse can be used together. +- **Window:** the game's image keeps its aspect ratio in a window of another shape (black bars; an + image that fits 1:1 is copied texel for texel). `scaling` in the game's `xcl.toml`: `"fit"`, + `"integer"` (whole multiples only), `"stretch"` (the old behaviour); `XCL_SCALING` overrides it. ## Building and usage diff --git a/crates/xcl/src/config.rs b/crates/xcl/src/config.rs index 1503e550a..1ef899ebc 100644 --- a/crates/xcl/src/config.rs +++ b/crates/xcl/src/config.rs @@ -60,6 +60,10 @@ pub struct Config { /// "center" (the primary monitor's work area), or "x,y" (top-left of the window, screen /// coordinates; clamped into the nearest monitor's work area). `XCL_WINDOW_POS` overrides. pub window_pos: String, + /// How the game's image fills the window: "fit" (aspect ratio kept, black bars – a 16:9 + /// image in a 21:9 window), "integer" (whole multiples only, 1:1 pixels) or "stretch". + /// `XCL_SCALING` overrides. + pub scaling: String, /// Answer `XUserGetTokenAndSignature*` with XCL's local placeholder token (for a backend of /// your own that accepts it). Off: the request fails as on a console that cannot reach Xbox /// Live (0x80072EFD), and titles go their offline way – Xbox Live's and the titles' own @@ -184,6 +188,7 @@ impl Default for Config { window_width: 1280, window_height: 720, window_pos: "auto".into(), + scaling: "fit".into(), xbox_live_tokens: false, keyboard_mouse: true, mouse_sensitivity: 1.0, diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 653624827..e052a36b4 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -537,7 +537,7 @@ struct Presenter { scaler: Option, scaler_failed: bool, /// the route last logged, with the image size - route: Option<(Route, (u32, u32))>, + route: Option<(Route, (u32, u32), (u32, u32))>, /// the swap chain size (and format) ResizeBuffers last refused, and when: logged once, /// asked for again twice a second resize_failed: Option<((u32, u32, DXGI_FORMAT), Instant)>, @@ -730,51 +730,49 @@ unsafe fn present_frame(p: &mut Presenter, hwnd: HWND, src: ID3D12Resource, desc p.dumps.clear(); let image = (desc.Width as u32, desc.Height); let client = client_size(hwnd); - let mut route = downscale::route(image, client); - if route == Route::Filter && !scaler_ready(p, fmt) { + let scaling = scaling(); + let mut route = downscale::route(image, client, scaling); + if matches!(route, Route::Filter | Route::Place) && !scaler_ready(p, fmt) { route = Route::Copy; } - if p.route != Some((route, image)) { + let mut rect = downscale::place(image, client, scaling); + if p.route != Some((route, image, client)) { let how = match route { Route::Filter => "area filter into a swap chain of the client size", + Route::Place => "copied 1:1 into a swap chain of the client size", + Route::Copy if client == image => "copy", Route::Copy => "copy, the window stretches it", Route::Skip => "nothing shown, the swap chain keeps its size", }; - crate::xlog_info!("present: {}x{} image in a {}x{} client area – {how}", image.0, image.1, client.0, client.1); - p.route = Some((route, image)); + let at = if matches!(route, Route::Filter | Route::Place) && (rect.2, rect.3) != client { + format!(" at {}x{}+{}+{} ({scaling:?}, black bars around it)", rect.2, rect.3, rect.0, rect.1) + } else { + String::new() + }; + crate::xlog_info!("present: {}x{} image in a {}x{} client area – {how}{at}", image.0, image.1, client.0, client.1); + p.route = Some((route, image, client)); } if route == Route::Skip { return false; } - let (mut sw, mut sh) = if route == Route::Filter { client } else { image }; + let (sw, sh) = if route == Route::Copy { image } else { client }; if !ensure_swapchain(p, hwnd, sw, sh, fmt) { // the swap chain keeps its size this frame and the filter draws the image into it (the // window stretches it): a resize never costs a frame if p.sc.is_none() || !scaler_ready(p, p.fmt) { return false; } - (route, sw, sh) = (Route::Filter, p.w, p.h); + route = Route::Filter; + rect = downscale::place(image, (p.w, p.h), scaling); } + let full = (rect.0, rect.1, rect.2, rect.3) == (0, 0, p.w, p.h); let Some(sc) = p.sc.clone() else { return false }; let Ok(bb) = sc.GetBuffer::(sc.GetCurrentBackBufferIndex()) else { return false }; if p.alloc.Reset().is_err() || p.list.Reset(&p.alloc, None).is_err() { return false; } // the back buffer's state while it is written - let written = match (route, &p.scaler) { - (Route::Filter, Some(scaler)) => { - p.list.ResourceBarrier(&[transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)]); - // the title's image is promoted from COMMON to a shader resource, as for the copy - scaler.record(&p.dev, &p.list, &src, &bb, sw, sh); - D3D12_RESOURCE_STATE_RENDER_TARGET - } - _ => { - let b1 = [transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST)]; - p.list.ResourceBarrier(&b1); - p.list.CopyResource(&bb, &src); - D3D12_RESOURCE_STATE_COPY_DEST - } - }; + let written = draw(&p.dev, &p.list, p.scaler.as_ref(), route, &src, &bb, D3D12_RESOURCE_STATE_PRESENT, rect, full); let due = frame_dump_due(); let mut dumps = Vec::new(); if due { @@ -850,6 +848,48 @@ unsafe fn present_frame(p: &mut Presenter, hwnd: HWND, src: ID3D12Resource, desc true } +/// `scaling` (`XCL_SCALING` overrides): how the image fills the window; "fit" when unknown. +fn scaling() -> downscale::Scaling { + static S: std::sync::OnceLock = std::sync::OnceLock::new(); + *S.get_or_init(|| { + let env = std::env::var("XCL_SCALING").ok(); + let v = env.as_deref().unwrap_or(&crate::state::config().scaling); + downscale::Scaling::parse(v).unwrap_or_else(|| { + crate::xlog_warn!("scaling: expected \"fit\", \"integer\" or \"stretch\", got {v:?} – using fit"); + downscale::Scaling::Fit + }) + }) +} + +/// Record on `list` how `src` (the title's image) goes into `bb` (a back buffer in state +/// `from`) for `route` at `rect` (`full`: `rect` covers all of `bb`). Returns `bb`'s state after. +#[allow(clippy::too_many_arguments)] +unsafe fn draw(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, scaler: Option<&downscale::Scaler>, route: Route, src: &ID3D12Resource, bb: &ID3D12Resource, from: D3D12_RESOURCE_STATES, rect: (u32, u32, u32, u32), full: bool) -> D3D12_RESOURCE_STATES { + match (route, scaler) { + (Route::Filter, Some(scaler)) => { + list.ResourceBarrier(&[transition(bb, from, D3D12_RESOURCE_STATE_RENDER_TARGET)]); + // the title's image is promoted from COMMON to a shader resource, as for the copy + scaler.record_into(dev, list, src, bb, rect, !full); + D3D12_RESOURCE_STATE_RENDER_TARGET + } + (Route::Place, Some(scaler)) => { + // black bars, then the image copied texel for texel between them + list.ResourceBarrier(&[transition(bb, from, D3D12_RESOURCE_STATE_RENDER_TARGET)]); + scaler.clear(dev, list, bb); + list.ResourceBarrier(&[transition(bb, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_DEST)]); + 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 image = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(src), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, rect.0, rect.1, 0, &image, None); + D3D12_RESOURCE_STATE_COPY_DEST + } + _ => { + list.ResourceBarrier(&[transition(bb, from, D3D12_RESOURCE_STATE_COPY_DEST)]); + list.CopyResource(bb, src); + D3D12_RESOURCE_STATE_COPY_DEST + } + } +} + /// The XCL window's client area (0x0 when minimized or unknown). unsafe fn client_size(hwnd: HWND) -> (u32, u32) { let mut rc = RECT::default(); diff --git a/crates/xcl/src/hle/d3d12x/present/downscale.rs b/crates/xcl/src/hle/d3d12x/present/downscale.rs index dad8c59d4..e795bd9c4 100644 --- a/crates/xcl/src/hle/d3d12x/present/downscale.rs +++ b/crates/xcl/src/hle/d3d12x/present/downscale.rs @@ -18,30 +18,85 @@ use windows::Win32::Graphics::Dxgi::Common::*; /// How the title's image reaches the window. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Route { - /// copied into a swap chain of the image's size, DWM stretches it (the window is as large) + /// copied into a swap chain of the image's size (the client area is exactly as large; and + /// without the filter, where DWM stretches it) Copy, - /// drawn into a swap chain of the client size through the area filter + /// copied 1:1 into a swap chain of the client size at its place, black around it (a 16:9 + /// image on a 21:9 screen of the same height) + Place, + /// drawn into a swap chain of the client size through the area filter, at its place Filter, /// not shown: the client area is empty (minimized), the swap chain keeps its size Skip, } -/// `Skip` when the client area is empty (minimized); `Filter` when it is smaller than the image -/// on either side; `Copy` when it is as large or larger. -pub fn route(image: (u32, u32), client: (u32, u32)) -> Route { +/// How the image fills the client area (`scaling` in xcl.toml, `XCL_SCALING` overrides). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Scaling { + /// as large as fits with its aspect ratio kept, centred, black bars around it + Fit, + /// the largest whole multiple of the image that fits (1:1 pixels at 1x), else as `Fit` + Integer, + /// the whole client area, aspect ratio not kept + Stretch, +} + +impl Scaling { + pub fn parse(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "fit" | "aspect" | "auto" | "" => Some(Scaling::Fit), + "integer" | "pixel" => Some(Scaling::Integer), + "stretch" | "fill" => Some(Scaling::Stretch), + _ => None, + } + } +} + +/// Where the image goes in the client area: (x, y, width, height). +pub fn place(image: (u32, u32), client: (u32, u32), scaling: Scaling) -> (u32, u32, u32, u32) { + let ((iw, ih), (cw, ch)) = (image, client); + if iw == 0 || ih == 0 || cw == 0 || ch == 0 { + return (0, 0, cw, ch); + } + let (w, h) = match scaling { + Scaling::Stretch => (cw, ch), + Scaling::Integer if (cw / iw).min(ch / ih) >= 1 => { + let k = (cw / iw).min(ch / ih); + (iw * k, ih * k) + } + _ => { + let (iw, ih, cw, ch) = (iw as u64, ih as u64, cw as u64, ch as u64); + if cw * ih > ch * iw { + // wider than the image: bars left and right + (((ch * iw + ih / 2) / ih).clamp(1, cw) as u32, ch as u32) + } else { + (cw as u32, ((cw * ih + iw / 2) / iw).clamp(1, ch) as u32) + } + } + }; + ((cw - w) / 2, (ch - h) / 2, w, h) +} + +/// `Skip` when the client area is empty (minimized); `Copy` when the image fills it 1:1; +/// `Place` when it goes there 1:1 with bars around it; else `Filter`. +pub fn route(image: (u32, u32), client: (u32, u32), scaling: Scaling) -> Route { if client.0 == 0 || client.1 == 0 { - Route::Skip - } else if client.0 >= image.0 && client.1 >= image.1 { + return Route::Skip; + } + let (_, _, w, h) = place(image, client, scaling); + if (w, h) != image { + Route::Filter + } else if client == image { Route::Copy } else { - Route::Filter + Route::Place } } const SHADER: &str = r#" -#define RS "RootConstants(num32BitConstants=4, b0), DescriptorTable(SRV(t0), visibility=SHADER_VISIBILITY_PIXEL)" +#define RS "RootConstants(num32BitConstants=6, b0), DescriptorTable(SRV(t0), visibility=SHADER_VISIBILITY_PIXEL)" Texture2D src : register(t0); -cbuffer C : register(b0) { uint2 dst; uint flags; uint pad; }; +cbuffer C : register(b0) { uint2 dst; uint flags; uint pad; uint2 origin; }; [RootSignature(RS)] float4 vs(uint id : SV_VertexID) : SV_Position { @@ -58,7 +113,7 @@ float4 ps(float4 pos : SV_Position) : SV_Target { uint sw, sh; src.GetDimensions(sw, sh); float2 s = float2(sw, sh) / float2(dst); - float2 lo = floor(pos.xy) * s; + float2 lo = (floor(pos.xy) - float2(origin)) * s; float2 hi = min(lo + s, float2(sw, sh)); int2 a = (int2)floor(lo); int2 b = (int2)ceil(hi); @@ -135,7 +190,34 @@ impl Scaler { /// Record on `list` the draw of `src` (subresource 0, readable as a pixel shader resource) /// over all of `dst` (`w`x`h`, `self.fmt`, in RENDER_TARGET state). The descriptors are /// rewritten: the previous recording must have finished on the GPU. + #[cfg(test)] pub unsafe fn record(&self, dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, src: &ID3D12Resource, dst: &ID3D12Resource, w: u32, h: u32) { + self.record_into(dev, list, src, dst, (0, 0, w, h), false); + } + + /// The view of `dst` in the scaler's RTV heap (forgotten by `note_rtv` at once). + unsafe fn target(&self, dev: &ID3D12Device, dst: &ID3D12Resource) -> D3D12_CPU_DESCRIPTOR_HANDLE { + let rtv = self.rtv.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(dst, None, rtv); + // `dev` is the title's (adopted) device: its CreateRenderTargetView hook keeps a reference + // to the view's resource for guessing the title's frame (`note_rtv`). Held on a swap chain + // buffer, that reference makes every ResizeBuffers fail (DXGI_ERROR_INVALID_CALL): the + // presenter's own view is forgotten at once. + super::note_rtv(rtv.ptr, std::ptr::null_mut()); + rtv + } + + /// Record on `list` a clear of all of `dst` (RENDER_TARGET state) to black: the bars around + /// a placed image. + pub unsafe fn clear(&self, dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, dst: &ID3D12Resource) { + let rtv = self.target(dev, dst); + list.ClearRenderTargetView(rtv, &[0.0, 0.0, 0.0, 1.0], None); + } + + /// As `record`, into the `rect` (x, y, width, height) of `dst` only; `clear`: the rest of + /// `dst` is cleared to black first. + pub unsafe fn record_into(&self, dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, src: &ID3D12Resource, dst: &ID3D12Resource, rect: (u32, u32, u32, u32), clear: bool) { + let (x, y, w, h) = rect; let view = view_format(src.GetDesc().Format); let srv_desc = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: view, @@ -144,24 +226,21 @@ impl Scaler { Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, ..Default::default() } }, }; dev.CreateShaderResourceView(src, Some(&srv_desc), self.srv.GetCPUDescriptorHandleForHeapStart()); - let rtv = self.rtv.GetCPUDescriptorHandleForHeapStart(); - dev.CreateRenderTargetView(dst, None, rtv); - // `dev` is the title's (adopted) device: its CreateRenderTargetView hook keeps a reference - // to the view's resource for guessing the title's frame (`note_rtv`). Held on a swap chain - // buffer, that reference makes every ResizeBuffers fail (DXGI_ERROR_INVALID_CALL): the - // presenter's own view is forgotten at once. - super::note_rtv(rtv.ptr, std::ptr::null_mut()); + let rtv = self.target(dev, dst); + if clear { + list.ClearRenderTargetView(rtv, &[0.0, 0.0, 0.0, 1.0], None); + } let decode = matches!(view, DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM | DXGI_FORMAT_R10G10B10A2_UNORM); let encode = self.fmt != DXGI_FORMAT_R16G16B16A16_FLOAT; - let constants = [w, h, decode as u32 | (encode as u32) << 1, 0]; + let constants = [w, h, decode as u32 | (encode as u32) << 1, 0, x, y]; list.SetGraphicsRootSignature(&self.rs); list.SetDescriptorHeaps(&[Some(self.srv.clone())]); - list.SetGraphicsRoot32BitConstants(0, 4, constants.as_ptr() as _, 0); + list.SetGraphicsRoot32BitConstants(0, constants.len() as u32, constants.as_ptr() as _, 0); list.SetGraphicsRootDescriptorTable(1, self.srv.GetGPUDescriptorHandleForHeapStart()); list.SetPipelineState(&self.pso); list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - list.RSSetViewports(&[D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: w as f32, Height: h as f32, MinDepth: 0.0, MaxDepth: 1.0 }]); - list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { left: 0, top: 0, right: w as i32, bottom: h as i32 }]); + list.RSSetViewports(&[D3D12_VIEWPORT { TopLeftX: x as f32, TopLeftY: y as f32, Width: w as f32, Height: h as f32, MinDepth: 0.0, MaxDepth: 1.0 }]); + list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { left: x as i32, top: y as i32, right: (x + w) as i32, bottom: (y + h) as i32 }]); list.OMSetRenderTargets(1, Some(&rtv as *const _), false, None); list.DrawInstanced(3, 1, 0, 0); } @@ -180,16 +259,39 @@ mod tests { #[test] fn route_filters_only_when_the_window_is_smaller() { let uhd = (3840, 2160); - for client in [(1280, 720), (1920, 1080), (2560, 1440), (3840, 2000), (3000, 2160)] { - assert_eq!(route(uhd, client), Route::Filter, "{client:?}"); - } - for client in [(3840, 2160), (5120, 2880)] { - assert_eq!(route(uhd, client), Route::Copy, "{client:?}"); + for client in [(1280, 720), (1920, 1080), (2560, 1440), (3840, 2000), (3000, 2160), (5120, 2880)] { + assert_eq!(route(uhd, client, Scaling::Fit), Route::Filter, "{client:?}"); } + assert_eq!(route(uhd, (3840, 2160), Scaling::Fit), Route::Copy); + // a 21:9 screen of the image's height: the image 1:1 between bars + assert_eq!(route(uhd, (5120, 2160), Scaling::Fit), Route::Place); + assert_eq!(route(uhd, (5120, 2160), Scaling::Stretch), Route::Filter); + assert_eq!(route(uhd, (7680, 4320), Scaling::Integer), Route::Filter); + assert_eq!(route(uhd, (4000, 2400), Scaling::Integer), Route::Place); // minimized: nothing shown – not a copy into a swap chain resized to the image for client in [(0, 0), (1280, 0), (0, 720)] { - assert_eq!(route(uhd, client), Route::Skip, "{client:?}"); + assert_eq!(route(uhd, client, Scaling::Fit), Route::Skip, "{client:?}"); + } + } + + #[test] + fn place_keeps_the_aspect_ratio() { + let uhd = (3840, 2160); + // 21:9 at 5120x2160: 640-pixel bars left and right + assert_eq!(place(uhd, (5120, 2160), Scaling::Fit), (640, 0, 3840, 2160)); + assert_eq!(place(uhd, (3440, 1440), Scaling::Fit), (440, 0, 2560, 1440)); + // taller than 16:9 (16:10): bars above and below + assert_eq!(place(uhd, (1920, 1200), Scaling::Fit), (0, 60, 1920, 1080)); + assert_eq!(place(uhd, (1280, 720), Scaling::Fit), (0, 0, 1280, 720)); + assert_eq!(place(uhd, (5120, 2160), Scaling::Stretch), (0, 0, 5120, 2160)); + // integer: 1080p twice on a 4K screen; a window smaller than the image falls back to fit + assert_eq!(place((1920, 1080), (5120, 2160), Scaling::Integer), (640, 0, 3840, 2160)); + assert_eq!(place((1920, 1080), (3440, 1440), Scaling::Integer), (760, 180, 1920, 1080)); + assert_eq!(place(uhd, (3440, 1440), Scaling::Integer), (440, 0, 2560, 1440)); + for s in ["fit", "Integer", " stretch "] { + assert!(Scaling::parse(s).is_some(), "{s}"); } + assert_eq!(Scaling::parse("zoom"), None); } fn srgb_to_linear(c: f64) -> f64 { @@ -388,6 +490,66 @@ mod tests { } } + /// A 16:9 image on wider screens: 1:1 between black bars (`Place`, 1280x720 in 1680x720) + /// and through the filter between bars (1280x720 in 1032x432: 768x432 at x 132) – the bars + /// black, the image as the copy or the CPU filter gives it. + #[test] + fn placed_image_between_black_bars() { + unsafe { + let Some(dev) = device() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + if crate::gpu::recomp::dxc::location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + let scaler = Scaler::new(&dev, DXGI_FORMAT_R8G8B8A8_UNORM).unwrap(); + let (iw, ih) = (1280u32, 720u32); + let src = pattern(iw as usize, ih as usize); + for (client, want_route, want_rect) in [((1680u32, 720u32), Route::Place, (200, 0, 1280, 720)), ((1032, 432), Route::Filter, (132, 0, 768, 432))] { + let route = route((iw, ih), client, Scaling::Fit); + let rect = place((iw, ih), client, Scaling::Fit); + assert_eq!((route, rect), (want_route, want_rect), "{client:?}"); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let (tex, _up) = upload(&dev, &list, &src, iw, ih, D3D12_RESOURCE_STATE_COMMON); + // the back buffer, with something in it the bars must cover + let fill = vec![200u8; (client.0 * client.1 * 4) as usize]; + let (bb, _up2) = upload(&dev, &list, &fill, client.0, client.1, D3D12_RESOURCE_STATE_COMMON); + let bb_rt = texture(&dev, client.0, client.1, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_DEST); + list.ResourceBarrier(&[super::super::transition(&bb, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyResource(&bb_rt, &bb); + list.ResourceBarrier(&[super::super::transition(&bb_rt, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT)]); + let after = super::super::draw(&dev, &list, Some(&scaler), route, &tex, &bb_rt, D3D12_RESOURCE_STATE_PRESENT, rect, false); + list.ResourceBarrier(&[super::super::transition(&bb_rt, after, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let (rb, fp) = super::super::readback_copy(&list, &bb_rt, &bb_rt.GetDesc()).unwrap(); + run(&dev, &queue, &list); + let got = texels(&rb, &fp, client.0, client.1); + let (x0, y0, w, h) = rect; + let reference = (route == Route::Filter).then(|| reference(&src, iw as usize, ih as usize, w as usize, h as usize)); + for y in 0..client.1 { + for x in 0..client.0 { + let t = &got[((y * client.0 + x) * 4) as usize..][..3]; + let inside = x >= x0 && x < x0 + w && y >= y0 && y < y0 + h; + if !inside { + assert_eq!(t, [0, 0, 0], "{client:?}: bar pixel ({x}, {y})"); + } else if let Some(r) = &reference { + let want = r[((y - y0) * w + (x - x0)) as usize]; + for c in 0..3 { + assert!((t[c] as f64 - want[c]).abs() <= 1.5, "{client:?}: ({x}, {y}) is {t:?}, the area filter gives {want:?}"); + } + } else { + let s = &src[(((y - y0) * iw + (x - x0)) * 4) as usize..][..3]; + assert_eq!(t, s, "{client:?}: ({x}, {y}) is not the image's texel"); + } + } + } + } + } + } + /// A hidden popup window (no frame: the client area is the whole window) on a thread of its /// own that pumps its messages, as the XCL window is. struct TestWindow { @@ -491,7 +653,7 @@ mod tests { let sc = p.sc.clone().unwrap(); let d = sc.GetDesc1().unwrap(); assert_eq!((p.w, p.h, d.Width, d.Height), (w, h, w, h), "the swap chain follows the {w}x{h} client area"); - assert_eq!(p.route, Some((Route::Filter, (iw, ih)))); + assert_eq!(p.route, Some((Route::Filter, (iw, ih), (w, h)))); if k > 2 { continue; // a size checked already }