diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index b72eda3..591c293 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 d8b692f..cc2b2c2 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 7516996..ce17c1c 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 e609a34..d648a58 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 9b2826f..e5ee5ad 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 74650d5..c1d7dac 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)) }