From fa2d1d3716b69dc6703121fc251db18924039534 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:59:08 -0500 Subject: [PATCH 1/6] D3D12.X: rect lists drawn whole through a generated geometry shader The console's rect lists (IASetPrimitiveTopology 17, AMD's DI_PT_RECTLIST; pipeline topology type 19) were drawn as triangle lists: each rect as the triangle of its three vertices, half of it. A translated VS+PS pipeline of topology type 19 now gets a pass-through GS (emit::rect_list_gs, declared from the VS's own output struct) that adds the fourth corner. The three vertices are corners of a screen-aligned rectangle (AMD PAL palCmdBuffer.h: "Each rect is three 2D axis-aligned rectangle vertices"), and the corner between the other two is not always v0: Mesa radeonsi's blits send (x1,y1), (x1,y2), (x2,y1), xf86-video-ati's r600 EXA (x1,y1), (x1,y2), (x2,y2). The corner is the vertex sharing x with one of the others and y with the other; the fourth vertex is a + b - corner, its outputs likewise (both drivers' texture coordinates rely on that). Bounded to what is established: three vertices with one positive w (then clip and screen space agree and so do the interpolation modes); others stay one triangle. Refused, keeping the old triangle form: integer VS outputs, a PS that reads flat (an integer input or v_interp_mov_f32), a PC PS - which vertex gives a rect's flat values is not established. The stream path keeps type 19 for the translated pipeline; the graphics stand-in maps it. Tests: rect_list_gs_outputs, rect_list_ps_reads_flat (CPU); gpu_rect_list_corners: corners at v0, v1, v2 cover the rect with the attribute linear everywhere, part stays clear without the GS, and a non-rectangle or unequal-w triangle draws the same with and without it. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/emit.rs | 43 ++++++++++ crates/xcl/src/gpu/recomp/pso.rs | 40 ++++++++++ crates/xcl/src/gpu/recomp/runner.rs | 18 +++++ crates/xcl/src/gpu/recomp/tests.rs | 117 ++++++++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/list_x.rs | 8 +- crates/xcl/src/hle/d3d12x/real.rs | 37 ++++++++- 6 files changed, 258 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index b72eda37e..591c293e3 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -4506,6 +4506,49 @@ fn out_struct(h: &mut String, name: &str, outputs: &[SigElement]) { h.push_str("};\n"); } +/// Geometry shader for the console's rect lists (IASetPrimitiveTopology 17, AMD's +/// DI_PT_RECTLIST; PSO topology type 19) behind a translated VS with these outputs: the PC has +/// no such topology, the draw arrives as a triangle list and each rect's three vertices come +/// here. They are three corners of a screen-aligned rectangle (AMD PAL, `palCmdBuffer.h`: +/// "Each rect is three 2D axis-aligned rectangle vertices"), and the corner between the other +/// two is not always the same vertex: Mesa's radeonsi blits send (x1,y1), (x1,y2), (x2,y1) – v0 +/// – and xf86-video-ati's r600 EXA (x1,y1), (x1,y2), (x2,y2) – v1. The corner is the vertex +/// sharing x with one of the others and y with the other; the fourth vertex is the opposite +/// corner, a + b - corner, with every output taken the same way (both drivers' texture +/// coordinates rely on the implied corner continuing them linearly). Only for three vertices +/// with one positive w – then a + b - corner is the same in clip and screen space and every +/// interpolation mode agrees; three that are not such corners, or differ in w, stay the one +/// triangle they make. Refused (Err): integer outputs, which are flat – which vertex of a rect +/// gives a flat value is not established, so neither is how the two halves would carry it +/// (the PS side: `pso::ps_reads_flat`). +pub fn rect_list_gs(outputs: &[SigElement]) -> Result { + if let Some(e) = ranked(outputs, true).iter().find(|e| hlsl_type(e) != "float") { + return Err(format!("{} is an integer output (flat)", e.semantic())); + } + let mut h = String::new(); + h.push_str("// generated by XCL: a console rect list's rectangles (three corners, the fourth implied)\n"); + out_struct(&mut h, "XclOut", outputs); + h.push_str("[maxvertexcount(6)]\nvoid main(triangle XclOut v[3], inout TriangleStream s)\n{\n"); + h.push_str(" s.Append(v[0]);\n s.Append(v[1]);\n s.Append(v[2]);\n"); + h.push_str(" if (!(v[0].pos.w > 0.0 && v[1].pos.w == v[0].pos.w && v[2].pos.w == v[0].pos.w))\n return;\n"); + h.push_str(" float2 q[3] = { v[0].pos.xy / v[0].pos.w, v[1].pos.xy / v[1].pos.w, v[2].pos.xy / v[2].pos.w };\n"); + // the corner c: x shared with a and y with b, or the other way round (a = c + 1, b = c + 2) + h.push_str(" uint c = 3u;\n [unroll] for (uint i = 0u; i < 3u; i++) {\n"); + h.push_str(" float2 p = q[i], a = q[(i + 1u) % 3u], b = q[(i + 2u) % 3u];\n"); + h.push_str(" bool corner = (p.x == a.x && p.y == b.y) || (p.x == b.x && p.y == a.y);\n"); + h.push_str(" bool degenerate = all(p == a) || all(p == b) || all(a == b);\n"); + h.push_str(" if (c == 3u && corner && !degenerate)\n c = i;\n }\n"); + h.push_str(" if (c == 3u)\n return;\n"); + h.push_str(" XclOut k = v[c], a = v[(c + 1u) % 3u], b = v[(c + 2u) % 3u];\n XclOut d = a;\n"); + h.push_str(" d.pos = a.pos + b.pos - k.pos;\n"); + for k in 0..ranked(outputs, true).len() { + let _ = writeln!(h, " d.p{k} = a.p{k} + b.p{k} - k.p{k};"); + } + // (c, a, b) is the first triangle's winding; (a, d, b) – its point reflection – keeps it + h.push_str(" s.RestartStrip();\n s.Append(a);\n s.Append(d);\n s.Append(b);\n}\n"); + Ok(h) +} + /// Second pass of the mesh mode: a mesh shader that turns the records written by the /// translated program (one per group, see `MsInterface::record_dwords`) into vertices and /// triangles. Null primitives (bit 31) and out-of-range indices are culled. diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index d8b692fae..cc2b2c27a 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -585,6 +585,46 @@ pub fn console_geometry(vs: &[u8], gs: &[u8], ps: Option<&[u8]>, split_wave64: b finish_two_pass(translation, record, ps) } +/// The geometry shader (gs_6_6 DXIL) that draws a console rect list's rectangles behind the +/// console VS `vs` (its container): `emit::rect_list_gs` for the VS's output signature, which +/// is what the translated VS's output struct is declared from. +pub fn rect_list_gs(vs: &[u8]) -> Result, String> { + let outputs = crate::gpu::dxbc::signatures(vs).1; + if outputs.is_empty() { + return Err("the VS has no output signature".into()); + } + Ok(dxc::compile_cached(&super::emit::rect_list_gs(&outputs)?, "main", "gs_6_6")?.0) +} + +/// Whether the console PS `ps` (its container) reads an attribute flat: an integer input, or a +/// `v_interp_mov_f32` – what the translation declares `nointerpolation` (`emit`, `XclIn`). A rect +/// list's flat values are not carried by `rect_list_gs` (see there). +pub fn ps_reads_flat(ps: &[u8]) -> Result { + let sh = xbox::parse(ps).ok_or("not a console shader container")?; + let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 5)).ok_or("no PS hardware variant")?; + let Some(Mode::Pixel(psi)) = interface(ps, &sh, f) else { + return Err("unknown PS interface".into()); + }; + if super::ranked(&psi.inputs, false).iter().any(|e| e.component_type != 3) { + return Ok(true); + } + let p = f.programs.first().ok_or("FSSM without a program")?; + reads_flat(&f.data[p.offset..p.offset + p.len]) +} + +/// Whether PS code has a `v_interp_mov_f32`. +pub fn reads_flat(code: &[u8]) -> Result { + let mut off = 0usize; + while off + 4 <= code.len() { + let d = crate::gpu::rdna2::decode(&code[off..], off as u64).map_err(|e| format!("+{off:#x}: cannot decode ({e:?})"))?; + if d.inst.name.eq_ignore_ascii_case("v_interp_mov_f32") { + return Ok(true); + } + off += d.len; + } + Ok(false) +} + /// XCL shader ABI root signature (see the module docs); `graphics` allows an input layout. pub fn abi_root_signature(dev: &ID3D12Device, graphics: bool) -> Result { abi_root_signature_with(dev, graphics, &[]) diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 751699614..ce17c1cd9 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -630,6 +630,23 @@ pub fn draw( mem: &[u32], size: u32, clear: [f32; 4], +) -> Result, String> { + draw_gs(vs, None, ps, layout, vertices, stride, sgprs, mem, size, clear) +} + +/// `draw` with a geometry shader (DXIL) between the VS and the PS. +#[allow(clippy::too_many_arguments)] +pub fn draw_gs( + vs: &[u8], + gs: Option<&[u8]>, + ps: &[u8], + layout: &[VertexElement], + vertices: &[f32], + stride: u32, + sgprs: &[u32], + mem: &[u32], + size: u32, + clear: [f32; 4], ) -> Result, String> { let mut g = GPU.lock().unwrap(); let gpu = g.get_or_insert_with(init).as_mut().map_err(|x| x.clone())?; @@ -654,6 +671,7 @@ pub fn draw( pRootSignature: 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() }, + GS: gs.map_or_else(D3D12_SHADER_BYTECODE::default, |g| D3D12_SHADER_BYTECODE { pShaderBytecode: g.as_ptr() as _, BytecodeLength: g.len() }), SampleMask: u32::MAX, InputLayout: D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elems.as_ptr(), NumElements: elems.len() as u32 }, PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index e609a34cd..d648a58d7 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1641,6 +1641,123 @@ fn gpu_graphics_vs_ps_draw() { } } +/// `emit::rect_list_gs` refuses integer (flat) outputs and declares the VS's output struct. +#[test] +fn rect_list_gs_outputs() { + let float = [el("SV_Position", 0, 1, 3, 0, 0xF), el("TEXCOORD", 0, 0, 3, 1, 0xF), el("SV_ClipDistance", 0, 2, 3, 2, 1)]; + let h = super::emit::rect_list_gs(&float).unwrap(); + assert!(h.contains("triangle XclOut v[3]") && h.contains("d.p0 = a.p0 + b.p0 - k.p0;") && h.contains("d.p1 = a.p1 + b.p1 - k.p1;"), "{h}"); + let flat = [el("SV_Position", 0, 1, 3, 0, 0xF), el("TEXCOORD", 0, 0, 1, 1, 0xF)]; + assert!(super::emit::rect_list_gs(&flat).unwrap_err().contains("TEXCOORD0")); + if super::dxc::location().is_ok() { + super::dxc::compile(&h, "main", "gs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{h}")); + } +} + +/// A PS with `v_interp_mov_f32` reads flat (`pso::reads_flat`): its rect list keeps no GS. +#[test] +fn rect_list_ps_reads_flat() { + let mov = prog(&[ + ("V_INTERP_MOV_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 2), ("ATTR", 0), ("ATTRCHAN", 0)], None), + ]); + let p2 = prog(&[ + ("V_INTERP_P1_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 0), ("ATTR", 0), ("ATTRCHAN", 0)], None), + ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 0)], None), + ]); + assert!(super::pso::reads_flat(&mov).unwrap()); + assert!(!super::pso::reads_flat(&p2).unwrap()); +} + +/// Console rect lists (DI_PT_RECTLIST) drawn through `emit::rect_list_gs`: three corners of a +/// screen-aligned rectangle, the corner between the other two at v0 (Mesa radeonsi's blits), +/// v1 (xf86-video-ati's r600 EXA) or v2. Each covers the whole rectangle and its attribute – the +/// vertex's own position – is the pixel's position everywhere, the implied corner's quarter +/// included (both drivers' texture coordinates depend on it). Without the GS (as before) part +/// of the rectangle stays clear; three vertices that are not such corners, or differ in w, draw +/// the same with and without it. Synthetic: the expected images are the rectangle and the +/// triangle, not a measurement of the hardware. +#[test] +fn gpu_rect_list_corners() { + if !gpu_ready() { + return; + } + use super::{PsInterface, VsInterface}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32B32A32_FLOAT; + let vs_code = prog(&[ + ("EXP", "ENC_EXP", &[("TGT", 12), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1)], None), + ("EXP", "ENC_EXP", &[("TGT", 32), ("EN", 0xF), ("VSRC0", 8), ("VSRC1", 9), ("VSRC2", 10), ("VSRC3", 11)], None), + ]); + let vsi = VsInterface { + inputs: vec![el("POSITION", 0, 0, 3, 0, 0xF), el("COLOR", 0, 0, 3, 1, 0xF)], + outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF), el("COLOR", 0, 0, 3, 1, 0xF)], + attr_base: 4, + params: None, + }; + let mut ps_ops: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = Vec::new(); + for c in 0..2u64 { + ps_ops.push(("V_INTERP_P1_F32", "ENC_VINTRP", vec![("VDST", 4 + c), ("VSRC", 0), ("ATTR", 0), ("ATTRCHAN", c)], None)); + ps_ops.push(("V_INTERP_P2_F32", "ENC_VINTRP", vec![("VDST", 4 + c), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", c)], None)); + } + ps_ops.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 6), ("SRC0", 128)], None)); + ps_ops.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 7), ("SRC0", 242)], None)); + ps_ops.push(("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None)); + let ps_list: Vec<(&str, &str, &[(&str, u64)], Option)> = ps_ops.iter().map(|(n, e, f, l)| (*n, *e, f.as_slice(), *l)).collect(); + let ps_code = prog(&ps_list); + let psi = PsInterface { + inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF), el("COLOR", 0, 0, 3, 1, 0xF)], + outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], + input_ena: 0x302, + attrs: None, + }; + let outputs = vsi.outputs.clone(); + let vt = translate(&vs_code, &Options { mode: Mode::Vertex(vsi), wave64: true, ..Default::default() }).unwrap(); + let pt = translate(&ps_code, &Options { mode: Mode::Pixel(psi), wave64: true, ..Default::default() }).unwrap(); + assert!(vt.complete() && pt.complete(), "{:?} {:?}", vt.unsupported, pt.unsupported); + let vs = super::dxc::compile(&vt.hlsl, "main", "vs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", vt.hlsl)); + let ps = super::dxc::compile(&pt.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", pt.hlsl)); + let gs_hlsl = super::emit::rect_list_gs(&outputs).unwrap(); + let gs = super::dxc::compile(&gs_hlsl, "main", "gs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{gs_hlsl}")); + let layout = [ + runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 0 }, + runner::VertexElement { semantic: "COLOR", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 16 }, + ]; + // a vertex at NDC (x, y) with clip w: position (x·w, y·w, 0, w), COLOR (x, y, 0, 1) + let verts = |ps: &[[f32; 3]]| -> Vec { ps.iter().flat_map(|&[x, y, w]| [x * w, y * w, 0.0, w, x, y, 0.0, 1.0]).collect() }; + let (n, clear) = (16usize, [0.0f32, 0.0, 1.0, 0.5]); + let ndc = |x: usize, y: usize| ((x as f32 + 0.5) / 8.0 - 1.0, 1.0 - (y as f32 + 0.5) / 8.0); + let run = |v: &[f32], with_gs: bool| runner::draw_gs(&vs, with_gs.then_some(gs.as_slice()), &ps, &layout, v, 32, &[], &[], n as u32, clear).unwrap(); + let (x1, x2, y1, y2) = (-0.5f32, 0.5, -0.5, 0.5); + for (name, corners) in [ + ("corner v0 (radeonsi)", [[x1, y1], [x1, y2], [x2, y1]]), + ("corner v1 (r600 EXA)", [[x1, y1], [x1, y2], [x2, y2]]), + ("corner v2", [[x1, y2], [x2, y1], [x1, y1]]), + ] { + let v = verts(&corners.map(|[x, y]| [x, y, 1.0])); + let px = run(&v, true); + for y in 0..n { + for x in 0..n { + let (fx, fy) = ndc(x, y); + let want = if fx > x1 && fx < x2 && fy > y1 && fy < y2 { [fx, fy, 0.0, 1.0] } else { clear }; + let got = px[y * n + x]; + assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-5), "{name}: pixel ({x},{y}) = {got:?}, expected {want:?}"); + } + } + // the negative control: as a triangle list only part of the rectangle is drawn + let tri = run(&v, false); + let missing = (0..n * n).filter(|&i| px[i] != clear && tri[i] == clear).count(); + assert!(missing >= 16, "{name}: without the GS {missing} of the rectangle's pixels stay clear"); + } + // left as the triangle they make: not three rectangle corners, and corners with unequal w + for (name, v) in [ + ("not a rectangle", verts(&[[-0.5, -0.5, 1.0], [0.25, 0.5, 1.0], [0.5, -0.25, 1.0]])), + ("unequal w", verts(&[[x1, y1, 1.0], [x1, y2, 2.0], [x2, y1, 1.0]])), + ] { + let (with, without) = (run(&v, true), run(&v, false)); + assert!(without.iter().any(|p| *p != clear), "{name}: the triangle draws"); + assert!(with.iter().zip(&without).all(|(a, b)| a.iter().zip(b).all(|(p, q)| (p - q).abs() < 1e-5)), "{name}: the GS changed the image"); + } +} + /// One instruction (programs built in loops). fn ins(name: &str, enc: &str, fields: &[(&str, u64)], lit: Option) -> Vec { encode(name, enc, fields, lit).unwrap_or_else(|x| panic!("{name}: {x}")) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 9b2826ff0..e5ee5ad63 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -409,8 +409,10 @@ const PC_OM_SET_RENDER_TARGETS: usize = 46; /// console #20 IASetPrimitiveTopology (PC #20) /// The console's rect list (AMD's DI_PT_RECTLIST, 0x11): three vertices of a rectangle, the -/// fourth implied. The PC has no such topology; until a geometry shader expands them, each rect -/// is drawn as the triangle of its three vertices (a retail game's full-screen passes). +/// fourth implied. The PC has no such topology: the draw is a triangle list, and a translated +/// pipeline of topology type 19 completes each rect in a geometry shader (`pso::rect_list_gs`); +/// where it has none (refused, see `real::rect_list_gs`) each rect is drawn as the triangle of +/// its three vertices (a retail game's full-screen passes). pub(super) const RECT_LIST: u32 = 17; pub(super) unsafe extern "system" fn ia_set_topology_x(this: *mut c_void, t: u32) { @@ -426,7 +428,7 @@ pub(super) unsafe extern "system" fn ia_set_topology_x(this: *mut c_void, t: u32 n }; if new { - crate::xlog_warn!("D3D12.X: IASetPrimitiveTopology({t}) – a console topology the PC does not have{}", if t == RECT_LIST { ": rect lists are drawn as triangle lists (each rect's first half only)" } else { "" }); + crate::xlog_warn!("D3D12.X: IASetPrimitiveTopology({t}) – a console topology the PC does not have{}", if t == RECT_LIST { ": rect lists are drawn as triangle lists, completed by a GS in rect list pipelines" } else { "" }); } } let rect = t == RECT_LIST; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 74650d589..c1d7dac26 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3256,6 +3256,16 @@ 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(); + // a rect list pipeline: the fourth corner of each rect comes from a generated GS; without + // it each rect is drawn as the triangle of its three vertices + let rect_gs = if d.PrimitiveTopologyType.0 == RECT_LIST_TYPE && copy.GS.pShaderBytecode.is_null() { + rect_list_gs(vs, shader_bytes(&d.PS)).map_err(|e| note_translation_error(format!("rect list drawn as triangles: {e}"))).ok() + } else { + None + }; + if let Some(gs) = &rect_gs { + copy.GS = bytecode(gs); + } pc_topology_type(&mut copy); let ps_hash = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); if debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash) { @@ -3458,6 +3468,7 @@ unsafe fn standin_graphics(this: *mut c_void, f: PsoFn, desc: *const c_void, rii copy.StreamOutput = std::mem::zeroed(); copy.InputLayout = D3D12_INPUT_LAYOUT_DESC::default(); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + pc_topology_type(&mut copy); finish_pso(this, f, © as *const _ as *const c_void, riid, ppv) } @@ -3944,8 +3955,27 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { Some((buf, [size, 0])) } +/// The console's pipeline topology type of rect lists (draws of topology 17, `list_x::RECT_LIST`). +const RECT_LIST_TYPE: i32 = 19; + +/// The GS that completes a rect list's rects behind the console VS `vs` and the PS `ps`; refused +/// for a PS that reads flat or is not a console one (its inputs' modes are not known). +fn rect_list_gs(vs: &[u8], ps: Option<&[u8]>) -> Result, String> { + use crate::gpu::recomp::pso; + if let Some(p) = ps { + if !pso::is_console(p) { + return Err("a PC pixel shader".into()); + } + if pso::ps_reads_flat(p)? { + return Err("the PS reads a flat attribute".into()); + } + } + pso::rect_list_gs(vs) +} + /// A topology type the PC has: the console's for rect lists (19, with draws of topology 17 – -/// `list_x::RECT_LIST`) is TRIANGLE, as those draws become triangle lists; UNDEFINED (a stream +/// `list_x::RECT_LIST`) is TRIANGLE, as those draws become triangle lists (the rects' fourth +/// corners come from `pso::rect_list_gs`, added by `translated_graphics_pso`); UNDEFINED (a stream /// without one) is TRIANGLE, or PATCH with a hull shader – the PC refuses both with a VS. fn pc_topology_type(g: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC) { // (and the console's D16S8 depth format the PC's: `device_x::pc_view_format`) @@ -4084,7 +4114,10 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { _ => {} } } - pc_topology_type(&mut g); + // a rect list stays one for translated_graphics_pso, which gives it its GS + if g.PrimitiveTopologyType.0 != RECT_LIST_TYPE { + pc_topology_type(&mut g); + } StreamPipeline::Graphics(Box::new(g)) } From 4bf546684c9d27bb4e81c5cbdd0807951f847db6 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:16:11 -0500 Subject: [PATCH 2/6] Rect lists: test the full-screen pass order reported downstream gpu_rect_list_fullscreen_order draws the three corners a downstream build (theaustinayers/xcl build 5, linked in #189) reports from a retail title's full-screen passes: positions (-1,1) (-1,-1) (1,-1), texture coordinates (0,0) (0,1) (1,1), so the shared corner is v1 and the implied one is (1,1) with (1,0). Plain HLSL VS/PS around emit::rect_list_gs on a 16x16 target: every pixel must carry its texture coordinate, for w 1 and 2; without the GS (the negative control) only about half the pixels are drawn. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/xcl/src/gpu/recomp/tests.rs | 41 ++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index d648a58d7..b338e71ac 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1668,6 +1668,47 @@ fn rect_list_ps_reads_flat() { assert!(!super::pso::reads_flat(&p2).unwrap()); } +/// `emit::rect_list_gs` on the full-screen pass a downstream build (theaustinayers/xcl, build 5, +/// via #189) reports from a retail title: positions (−1,1) (−1,−1) (1,−1), texture coordinates +/// (0,0) (0,1) (1,1), the shared corner v1 and the implied one (1,1) with (1,0). Plain HLSL +/// VS/PS around the GS. Every pixel must be drawn with its texture coordinate, for w 1 and 2; +/// without the GS about half are. +#[test] +fn gpu_rect_list_fullscreen_order() { + if !gpu_ready() { + return; + } + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32B32A32_FLOAT; + let outputs = [el("SV_Position", 0, 1, 3, 0, 0xF), el("TEXCOORD", 0, 0, 3, 1, 0xF)]; + let vs_hlsl = "struct V { float4 pos : SV_Position; float4 uv : TEXCOORD0; };\nV main(float4 pos : POSITION, float4 uv : TEXCOORD0) { V o; o.pos = pos; o.uv = uv; return o; }\n"; + let ps_hlsl = "float4 main(float4 pos : SV_Position, float4 uv : TEXCOORD0) : SV_Target { return uv; }\n"; + let vs = super::dxc::compile(vs_hlsl, "main", "vs_6_6", &[]).unwrap(); + let ps = super::dxc::compile(ps_hlsl, "main", "ps_6_6", &[]).unwrap(); + let gs_hlsl = super::emit::rect_list_gs(&outputs).unwrap(); + let gs = super::dxc::compile(&gs_hlsl, "main", "gs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{gs_hlsl}")); + let layout = [ + runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 0 }, + runner::VertexElement { semantic: "TEXCOORD", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 16 }, + ]; + let (n, clear) = (16usize, [0.0f32, 0.0, 1.0, 0.5]); + let corners = [([-1.0f32, 1.0], [0.0f32, 0.0]), ([-1.0, -1.0], [0.0, 1.0]), ([1.0, -1.0], [1.0, 1.0])]; + for w in [1.0f32, 2.0] { + let v: Vec = corners.iter().flat_map(|&([x, y], [s, t])| [x * w, y * w, 0.0, w, s, t, 0.0, 1.0]).collect(); + let run = |with_gs: bool| runner::draw_gs(&vs, with_gs.then_some(gs.as_slice()), &ps, &layout, &v, 32, &[], &[], n as u32, clear).unwrap(); + let px = run(true); + for y in 0..n { + for x in 0..n { + let want = [(x as f32 + 0.5) / n as f32, (y as f32 + 0.5) / n as f32, 0.0, 1.0]; + let got = px[y * n + x]; + assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-5), "w {w}: pixel ({x},{y}) = {got:?}, expected {want:?}"); + } + } + // the negative control: the three vertices alone draw the lower-left half + let drawn = run(false).iter().filter(|p| **p != clear).count(); + assert!(drawn > n * n / 3 && drawn < n * n * 2 / 3, "w {w}: without the GS {drawn} of {} pixels drawn", n * n); + } +} + /// Console rect lists (DI_PT_RECTLIST) drawn through `emit::rect_list_gs`: three corners of a /// screen-aligned rectangle, the corner between the other two at v0 (Mesa radeonsi's blits), /// v1 (xf86-video-ati's r600 EXA) or v2. Each covers the whole rectangle and its attribute – the From c217b1fbecb0d43725615b2c6470dbbb221a057f Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:22:20 -0500 Subject: [PATCH 3/6] Rect lists: test that a CPU-expanded rect's second triangle is completed too gpu_rect_list_fullscreen_order also draws the other half of the full-screen rect as a triangle: v0, v2 and the implied corner, what a draw expanded to two triangles a rect on the CPU sends next (#195). Those are three corners of the same rect, so the GS completes it to the whole rect as well. A draw expanded on the CPU must therefore not also get this GS, or each rect is drawn twice (the same image when opaque, wrong with blending). Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/xcl/src/gpu/recomp/tests.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index b338e71ac..e61cd1ad4 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1672,7 +1672,10 @@ fn rect_list_ps_reads_flat() { /// via #189) reports from a retail title: positions (−1,1) (−1,−1) (1,−1), texture coordinates /// (0,0) (0,1) (1,1), the shared corner v1 and the implied one (1,1) with (1,0). Plain HLSL /// VS/PS around the GS. Every pixel must be drawn with its texture coordinate, for w 1 and 2; -/// without the GS about half are. +/// without the GS about half are. The other half of that rect as a triangle (v0, v2 and the +/// implied corner – what a draw expanded to two triangles a rect on the CPU sends next) is three +/// corners of the same rect, so the GS completes it to the whole rect as well: such a draw must +/// not also get this GS, or each rect is drawn twice. #[test] fn gpu_rect_list_fullscreen_order() { if !gpu_ready() { @@ -1691,8 +1694,9 @@ fn gpu_rect_list_fullscreen_order() { runner::VertexElement { semantic: "TEXCOORD", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 16 }, ]; let (n, clear) = (16usize, [0.0f32, 0.0, 1.0, 0.5]); - let corners = [([-1.0f32, 1.0], [0.0f32, 0.0]), ([-1.0, -1.0], [0.0, 1.0]), ([1.0, -1.0], [1.0, 1.0])]; - for w in [1.0f32, 2.0] { + let first = [([-1.0f32, 1.0], [0.0f32, 0.0]), ([-1.0, -1.0], [0.0, 1.0]), ([1.0, -1.0], [1.0, 1.0])]; + let second = [([-1.0f32, 1.0], [0.0f32, 0.0]), ([1.0, -1.0], [1.0, 1.0]), ([1.0, 1.0], [1.0, 0.0])]; + for (name, corners, w) in [("v0 v1 v2", first, 1.0f32), ("v0 v1 v2", first, 2.0), ("v0 v2 v3", second, 1.0)] { let v: Vec = corners.iter().flat_map(|&([x, y], [s, t])| [x * w, y * w, 0.0, w, s, t, 0.0, 1.0]).collect(); let run = |with_gs: bool| runner::draw_gs(&vs, with_gs.then_some(gs.as_slice()), &ps, &layout, &v, 32, &[], &[], n as u32, clear).unwrap(); let px = run(true); @@ -1700,12 +1704,12 @@ fn gpu_rect_list_fullscreen_order() { for x in 0..n { let want = [(x as f32 + 0.5) / n as f32, (y as f32 + 0.5) / n as f32, 0.0, 1.0]; let got = px[y * n + x]; - assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-5), "w {w}: pixel ({x},{y}) = {got:?}, expected {want:?}"); + assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-5), "{name}, w {w}: pixel ({x},{y}) = {got:?}, expected {want:?}"); } } - // the negative control: the three vertices alone draw the lower-left half + // the negative control: the three vertices alone draw half the rect let drawn = run(false).iter().filter(|p| **p != clear).count(); - assert!(drawn > n * n / 3 && drawn < n * n * 2 / 3, "w {w}: without the GS {drawn} of {} pixels drawn", n * n); + assert!(drawn > n * n / 3 && drawn < n * n * 2 / 3, "{name}, w {w}: without the GS {drawn} of {} pixels drawn", n * n); } } From 938fdd2e65d3e54e151af917dbdc8cb346de2a60 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:31:47 -0500 Subject: [PATCH 4/6] Rect lists: retry a refused GS pipeline without it, map untranslated stream rect lists From the review of #199: - translated_graphics_pso: when the driver refuses a pipeline with the generated rect list GS, it is made once more without it (retry_without_rect_gs) and a note is logged, so each rect is drawn as its first triangle, as before, rather than by the dummy shaders. - A stream pipeline of type 19 that is not translated (HS/DS, a translation error) gets the PC's topology type before the driver sees it (untranslated_stream_desc), as at 956a476, where the stream path mapped it. dev_create_graphics_pso's body is now graphics_pso, with a flag for descs from a stream; a direct CreateGraphicsPipelineState is unchanged. - rect_list_gs compares clip-space x and y directly: w is one already. Tests (CPU): a_refused_rect_list_gs_is_retried_without_it (injected refusal), untranslated_stream_rect_lists_get_the_pcs_topology_type. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/xcl/src/gpu/recomp/emit.rs | 3 +- crates/xcl/src/hle/d3d12x/real.rs | 106 ++++++++++++++++++++++++++++-- 2 files changed, 104 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 591c293e3..052573b67 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -4531,7 +4531,8 @@ pub fn rect_list_gs(outputs: &[SigElement]) -> Result { h.push_str("[maxvertexcount(6)]\nvoid main(triangle XclOut v[3], inout TriangleStream s)\n{\n"); h.push_str(" s.Append(v[0]);\n s.Append(v[1]);\n s.Append(v[2]);\n"); h.push_str(" if (!(v[0].pos.w > 0.0 && v[1].pos.w == v[0].pos.w && v[2].pos.w == v[0].pos.w))\n return;\n"); - h.push_str(" float2 q[3] = { v[0].pos.xy / v[0].pos.w, v[1].pos.xy / v[1].pos.w, v[2].pos.xy / v[2].pos.w };\n"); + // one w: clip-space x and y compare as the screen's do + h.push_str(" float2 q[3] = { v[0].pos.xy, v[1].pos.xy, v[2].pos.xy };\n"); // the corner c: x shared with a and y with b, or the other way round (a = c + 1, b = c + 2) h.push_str(" uint c = 3u;\n [unroll] for (uint i = 0u; i < 3u; i++) {\n"); h.push_str(" float2 p = q[i], a = q[(i + 1u) % 3u], b = q[(i + 2u) % 3u];\n"); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index c1d7dac26..772efdea2 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3274,7 +3274,7 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo 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); + let hr = retry_without_rect_gs(&mut copy, rect_gs.is_some(), |c| finish_pso(this, f, c 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}; topology type {}, {} render targets, DSV format {}, HS {}, GS {})", @@ -3538,6 +3538,11 @@ unsafe fn build_stream(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { } pub(super) unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + graphics_pso(this, desc, riid, ppv, false) +} + +/// `dev_create_graphics_pso`; `stream`: the desc is a pipeline stream's (`stream_pipeline`). +unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, stream: bool) -> HRESULT { super::null::capture_graphics_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateGraphicsPipelineState"))); let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_graphics_pso(this, f, desc, riid, ppv)) } else { (translated_graphics_pso(this, f, desc, riid, ppv), false) }; @@ -3551,7 +3556,8 @@ pub(super) unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void, } else if let Some(hr) = translated { return hr; } - let hr = finish_pso(this, f, desc, riid, ppv); + let pc = untranslated_stream_desc(desc, stream); + let hr = finish_pso(this, f, pc.as_ref().map_or(desc, |g| g as *const _ as *const c_void), riid, ppv); if hr >= 0 || !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return hr; } @@ -3958,6 +3964,34 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { /// The console's pipeline topology type of rect lists (draws of topology 17, `list_x::RECT_LIST`). const RECT_LIST_TYPE: i32 = 19; +/// `create(copy)`, and once more without the generated rect list GS (`rect_gs`) when the driver +/// refuses the pipeline with it: each rect is then drawn as the triangle of its three vertices, +/// as without the GS, rather than not at all (the untranslated fallback's dummy shaders). +fn retry_without_rect_gs(copy: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, rect_gs: bool, mut create: impl FnMut(&D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> HRESULT) -> HRESULT { + let hr = create(copy); + if hr >= 0 || !rect_gs { + return hr; + } + note_translation_error(format!("the driver rejected the PSO with the rect list GS ({hr:#x}): rect list drawn as triangles")); + copy.GS = D3D12_SHADER_BYTECODE::default(); + create(copy) +} + +/// What an untranslated pipeline from a stream is made from: a rect list's (type 19, which +/// `stream_pipeline` keeps for `translated_graphics_pso`) with the PC's topology type, as the +/// stream path made it before; None: `desc` as it is. +unsafe fn untranslated_stream_desc(desc: *const c_void, stream: bool) -> Option { + if !stream || !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return None; + } + let mut g = std::ptr::read(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); + if g.PrimitiveTopologyType.0 != RECT_LIST_TYPE { + return None; + } + pc_topology_type(&mut g); + Some(g) +} + /// The GS that completes a rect list's rects behind the console VS `vs` and the PS `ps`; refused /// for a PS that reads flat or is not a console one (its inputs' modes are not known). fn rect_list_gs(vs: &[u8], ps: Option<&[u8]>) -> Result, String> { @@ -4114,7 +4148,8 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { _ => {} } } - // a rect list stays one for translated_graphics_pso, which gives it its GS + // a rect list stays one for translated_graphics_pso, which gives it its GS (untranslated, it + // becomes the PC's in graphics_pso) if g.PrimitiveTopologyType.0 != RECT_LIST_TYPE { pc_topology_type(&mut g); } @@ -4142,7 +4177,7 @@ pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void return hr; } match stream_pipeline(desc) { - StreamPipeline::Graphics(d) => return dev_create_graphics_pso(this, &*d as *const _ as *const c_void, riid, ppv), + StreamPipeline::Graphics(d) => return graphics_pso(this, &*d as *const _ as *const c_void, riid, ppv, true), StreamPipeline::Compute(d) => return dev_create_compute_pso(this, &*d as *const _ as *const c_void, riid, ppv), StreamPipeline::Unknown => {} } @@ -4679,6 +4714,69 @@ pub fn stop_if_device_removed() { } } +#[cfg(test)] +mod rect_list_pso_tests { + use super::*; + + const REFUSED: HRESULT = 0x8007_0057u32 as i32; + + fn with_gs(gs: &[u8]) -> D3D12_GRAPHICS_PIPELINE_STATE_DESC { + D3D12_GRAPHICS_PIPELINE_STATE_DESC { GS: D3D12_SHADER_BYTECODE { pShaderBytecode: gs.as_ptr() as _, BytecodeLength: gs.len() }, ..Default::default() } + } + + /// A pipeline the driver refuses with the rect list GS is made again without it, once; one + /// it accepts keeps the GS, and a refused pipeline without a rect list GS is not retried. + #[test] + fn a_refused_rect_list_gs_is_retried_without_it() { + let gs = [0u8; 4]; + let mut copy = with_gs(&gs); + let mut calls = Vec::new(); + let hr = retry_without_rect_gs(&mut copy, true, |c| { + calls.push(c.GS.pShaderBytecode.is_null()); + if c.GS.pShaderBytecode.is_null() { + 0 + } else { + REFUSED + } + }); + assert_eq!((hr, calls), (0, vec![false, true])); + let mut copy = with_gs(&gs); + let mut n = 0; + assert_eq!( + retry_without_rect_gs(&mut copy, true, |_| { + n += 1; + 0 + }), + 0 + ); + assert!(n == 1 && !copy.GS.pShaderBytecode.is_null()); + let mut n = 0; + assert_eq!( + retry_without_rect_gs(&mut copy, false, |_| { + n += 1; + REFUSED + }), + REFUSED + ); + assert!(n == 1 && !copy.GS.pShaderBytecode.is_null()); + } + + /// An untranslated rect list pipeline from a stream gets the PC's topology type (TRIANGLE), + /// as at 956a476; other types, and a direct CreateGraphicsPipelineState, are left as they are. + #[test] + fn untranslated_stream_rect_lists_get_the_pcs_topology_type() { + let at = |t: i32| D3D12_GRAPHICS_PIPELINE_STATE_DESC { PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE(t), ..Default::default() }; + let desc = |g: &D3D12_GRAPHICS_PIPELINE_STATE_DESC| g as *const _ as *const c_void; + let (rect, tri) = (at(RECT_LIST_TYPE), at(3)); + unsafe { + let g = untranslated_stream_desc(desc(&rect), true).expect("a stream's rect list"); + assert_eq!(g.PrimitiveTopologyType, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE); + assert!(untranslated_stream_desc(desc(&tri), true).is_none()); + assert!(untranslated_stream_desc(desc(&rect), false).is_none()); + } + } +} + #[cfg(test)] mod cache_report_tests { use super::*; From 82cba126d550d3ece4d87e9ea80dae102535df0e Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:44:21 -0500 Subject: [PATCH 5/6] Rect lists: real::has_rect_list_gs, the pipelines given the generated GS For #195, which expands rect lists to two triangles a rect on the CPU: a draw on a pipeline that has the GS must not be expanded too, since each half is three corners of the rect and the GS would complete both. has_rect_list_gs(pso) answers that, for a pipeline as is_translated_graphics takes it. A pipeline made again without the GS (retry_without_rect_gs) is not noted, and forget_pso drops the entry with the pipeline's address. Test (CPU): pipelines_with_the_rect_list_gs_are_known_until_forgotten. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/xcl/src/hle/d3d12x/real.rs | 38 +++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 772efdea2..bb6bbbce5 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1497,6 +1497,24 @@ pub fn is_translated_graphics(pso: usize) -> bool { pso != 0 && TRANSLATED_GRAPHICS.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) } +/// graphics pipelines given the generated rect list GS (`rect_list_gs`) +static RECT_LIST_GS: Mutex>> = Mutex::new(None); + +/// Whether `pso` (as `is_translated_graphics` takes it: a stand-in resolved) draws rect lists +/// whole with the generated GS. Its draws must not be expanded to two triangles a rect as well: +/// each half is three corners of the rect and the GS would complete both. +pub fn has_rect_list_gs(pso: usize) -> bool { + pso != 0 && RECT_LIST_GS.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) +} + +/// Note `pso`, made from `copy`, if it kept the generated rect list GS (`rect_gs`; a pipeline +/// made again without it, `retry_without_rect_gs`, did not). +fn note_rect_list_gs(pso: usize, copy: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, rect_gs: bool) { + if pso != 0 && rect_gs && !copy.GS.pShaderBytecode.is_null() { + RECT_LIST_GS.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + } +} + /// Whether `pso` runs a translated console compute shader. pub fn is_translated_compute(pso: usize) -> bool { pso != 0 && TRANSLATED_COMPUTE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) @@ -1528,6 +1546,9 @@ fn forget_pso(pso: usize) { if let Some(s) = TRANSLATED_GRAPHICS.lock().unwrap().as_mut() { s.remove(&pso); } + if let Some(s) = RECT_LIST_GS.lock().unwrap().as_mut() { + s.remove(&pso); + } if let Some(m) = PSO_RS.lock().unwrap().as_mut() { m.remove(&pso); } @@ -3289,6 +3310,7 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); 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)); @@ -4761,6 +4783,22 @@ mod rect_list_pso_tests { assert!(n == 1 && !copy.GS.pShaderBytecode.is_null()); } + /// `has_rect_list_gs`: a pipeline made with the rect list GS, not one made again without it + /// (or never given it), and not once its address is forgotten. + #[test] + fn pipelines_with_the_rect_list_gs_are_known_until_forgotten() { + let gs = [0u8; 4]; + let (kept, dropped, none) = (0x7E57_1000usize, 0x7E57_2000usize, 0x7E57_3000usize); + let mut copy = with_gs(&gs); + note_rect_list_gs(kept, ©, true); + assert!(retry_without_rect_gs(&mut copy, true, |c| if c.GS.pShaderBytecode.is_null() { 0 } else { REFUSED }) == 0); + note_rect_list_gs(dropped, ©, true); + note_rect_list_gs(none, &with_gs(&gs), false); + assert!(has_rect_list_gs(kept) && !has_rect_list_gs(dropped) && !has_rect_list_gs(none) && !has_rect_list_gs(0)); + forget_pso(kept); + assert!(!has_rect_list_gs(kept)); + } + /// An untranslated rect list pipeline from a stream gets the PC's topology type (TRIANGLE), /// as at 956a476; other types, and a direct CreateGraphicsPipelineState, are left as they are. #[test] From 7ac404889fa5d37ac5383f4c4f94e65ff7f8411b Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:59:48 -0500 Subject: [PATCH 6/6] Rect lists: no CPU expansion for a pipeline with the rect list GS Main expands a DrawInstanced of a rect list on the CPU (bind::draw_rects, from #195): v0 v1 v2, then v0 v2 v3. On a pipeline with the rect list GS each of those halves is three corners of the rect, so the GS completed both and every rect was drawn twice (gpu_rect_list_fullscreen_order shows the second half completed). draw_rects now leaves a pipeline with the GS alone (cpu_rect_expansion: real::has_rect_list_gs of the resolved pipeline); it still expands rect lists on the pipelines the GS refuses. Test (CPU): rect_lists_with_the_rect_list_gs_are_not_expanded_on_the_cpu. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/xcl/src/hle/d3d12x/bind.rs | 21 +++++++++++++++++++++ crates/xcl/src/hle/d3d12x/real.rs | 7 +++++++ 2 files changed, 28 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 7344db087..d8df8e34a 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -254,6 +254,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us /// is kept (a packed colour), any other is taken as a float. Vertices a shader makes from the /// vertex index alone (no vertex buffer) are not expanded. unsafe fn draw_rects(this: *mut c_void, list: &ID3D12GraphicsCommandList, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) -> bool { + if !cpu_rect_expansion(with(this, |s| s.pso)) { + return false; + } let Some(vbs) = super::list_x::rect_list_state(this) else { return false }; let rects = (vertices / 3) as usize; if vbs.is_empty() || rects == 0 || rects > 4096 { @@ -302,6 +305,13 @@ unsafe fn draw_rects(this: *mut c_void, list: &ID3D12GraphicsCommandList, vertic true } +/// Whether a rect list drawn with the bound pipeline `pso` is expanded on the CPU (`draw_rects`): +/// not with the rect list GS (`real::has_rect_list_gs`), which completes each rect itself – both +/// would draw every rect twice (each CPU half is three corners of the rect). +fn cpu_rect_expansion(pso: usize) -> bool { + !super::real::has_rect_list_gs(super::pso_async::resolve(pso)) +} + /// #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))); @@ -877,6 +887,17 @@ mod tests { use super::*; use std::sync::atomic::AtomicUsize; + /// A pipeline with the rect list GS draws its rect lists whole: draw_rects leaves them alone. + #[test] + fn rect_lists_with_the_rect_list_gs_are_not_expanded_on_the_cpu() { + let (with_gs, without) = (0x7E57_4000usize, 0x7E57_5000usize); + real::register_rect_list_gs_for_test(with_gs); + assert!(!cpu_rect_expansion(with_gs)); + assert!(cpu_rect_expansion(without) && cpu_rect_expansion(0)); + real::forget_pso_for_test(with_gs); + assert!(cpu_rect_expansion(with_gs)); + } + /// Minimal RTS0 v2 root signature blob with one 4-constant parameter. fn test_rts0_blob() -> Vec { let words: [u32; 12] = [ diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index bb6bbbce5..8234852ed 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1527,6 +1527,13 @@ pub(super) fn register_translated_compute_for_test(pso: usize) { } } +#[cfg(test)] +pub(super) fn register_rect_list_gs_for_test(pso: usize) { + if pso != 0 { + RECT_LIST_GS.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + } +} + #[cfg(test)] pub(super) fn register_translated_graphics_for_test(pso: usize) { if pso != 0 {