From 511d4d01dab55bd73589849b427bfdc99150e264 Mon Sep 17 00:00:00 2001 From: KDenKC <125705260+KDenKC@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:20:00 -0700 Subject: [PATCH 1/3] Recompiler: emit a bounded native mesh entry for one wave Checked: #3011 C4, #3040, #3042, #1936, #1937 and #3243. This entry refuses wave64, including split lowering. Add GPU pixel parity and two-pass fallback coverage. Assisted-by: Codex (GPT-6.2-Sol) --- crates/xcl/build.rs | 1 + crates/xcl/src/gpu/recomp/emit.rs | 60 +++++++++++---- crates/xcl/src/gpu/recomp/mod.rs | 14 +++- crates/xcl/src/gpu/recomp/native_mesh.rs | 96 ++++++++++++++++++++++++ crates/xcl/src/gpu/recomp/pso.rs | 16 ++++ crates/xcl/src/gpu/recomp/runner.rs | 58 +++++++++----- crates/xcl/src/gpu/recomp/tests.rs | 54 +++++++++++++ 7 files changed, 265 insertions(+), 34 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/native_mesh.rs diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index 4b38528494..f46e20fde0 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -15,6 +15,7 @@ const TRANSLATOR_SOURCES: &[&str] = &[ "src/gpu/recomp/emit.rs", "src/gpu/recomp/mesh_wave.rs", "src/gpu/recomp/mod.rs", + "src/gpu/recomp/native_mesh.rs", "src/gpu/recomp/upper_lanes.rs", "src/gpu/recomp/x64_masks.rs", "src/gpu/shader.rs", diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index a223135a50..a5b2f238ba 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -17,6 +17,7 @@ pub(super) enum Flow { } pub(super) struct Em { + pub(super) native_mesh: bool, /// whole-wave reductions (`graphics_reductions`) pub reductions: super::Reductions, opt: Options, @@ -602,6 +603,7 @@ impl Em { pub fn new(opt: Options) -> Self { Em { opt, + native_mesh: false, reductions: Default::default(), out: String::new(), indent: 1, @@ -1374,9 +1376,13 @@ impl Em { // GS_ALLOC_REQ: M0 = primitives << 12 | vertices (scalar: whatever EXEC is) if rdna2::field_value(d.enc, &d.words, "SIMM16").unwrap_or(0) & 0xF == 9 { let m0 = self.sreg(124); - self.line(&format!( - "if (lane_id == 0u) {{ res.Store(xcl_rec * 4u, {m0} & 0x3FFu); res.Store(xcl_rec * 4u + 4u, ({m0} >> 12) & 0x7FFu); }}" - )); + if self.native_mesh { + self.line(&format!("if (lane_id == 0u) xcl_counts = {m0};")); + } else { + self.line(&format!( + "if (lane_id == 0u) {{ res.Store(xcl_rec * 4u, {m0} & 0x3FFu); res.Store(xcl_rec * 4u + 4u, ({m0} >> 12) & 0x7FFu); }}" + )); + } } Flow::Next } @@ -2433,7 +2439,7 @@ impl Em { (Mode::Mesh(_), 12) => { for c in 0..4 { if enabled(c) { - st.push(format!("if (xcl_vok) res.Store((xcl_vtx + {c}u) * 4u, {});", Self::exp_comp(srcs, compr, c))); + st.push(self.mesh_vertex_store(c, &Self::exp_comp(srcs, compr, c))); } } } @@ -2450,12 +2456,16 @@ impl Em { for j in at { for c in 0..4 { if enabled(c) { - st.push(format!("if (xcl_vok) res.Store((xcl_vtx + {}u) * 4u, {});", 4 * (j + 1) + c, Self::exp_comp(srcs, compr, c))); + st.push(self.mesh_vertex_store(4 * (j + 1) + c, &Self::exp_comp(srcs, compr, c))); } } } } - (Mode::Mesh(_), 20) => st.push(format!("if (xcl_pok) res.Store(xcl_prm * 4u, {});", srcs[0])), + (Mode::Mesh(_), 20) => st.push(if self.native_mesh { + format!("xcl_primitive = {};", srcs[0]) + } else { + format!("if (xcl_pok) res.Store(xcl_prm * 4u, {});", srcs[0]) + }), (Mode::Mesh(_), 9) => {} _ => return Err("export target"), } @@ -2476,6 +2486,14 @@ impl Em { Ok(()) } + fn mesh_vertex_store(&self, component: usize, value: &str) -> String { + if self.native_mesh { + format!("xcl_vertex[{component}] = {value};") + } else { + format!("if (xcl_vok) res.Store((xcl_vtx + {component}u) * 4u, {value});") + } + } + /// (vdst, I/J VGPR or interp_mov parameter, attribute, channel) fn interp_fields(d: &Decoded) -> (u64, u64, u64, u64) { let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0); @@ -5066,7 +5084,12 @@ impl Em { // lane reads within a quad see helper lanes (`rla`) h.push_str("#define XCL_PIXEL 1\n"); } - h.push_str("RWByteAddressBuffer io : register(u0);\nRWByteAddressBuffer res : register(u1);\n"); + if self.native_mesh { + // The PS reads its own title arguments from u0. Native mesh uses the old record slot. + h.push_str("RWByteAddressBuffer io : register(u1);\n"); + } else { + h.push_str("RWByteAddressBuffer io : register(u0);\nRWByteAddressBuffer res : register(u1);\n"); + } // compute work across workgroups (bottom-up BVH builds: atomics, then reading what // other groups wrote) relies on GLC / cache invalidation on the console: keep the flat // memory coherent across the GPU only when the program actually uses those; otherwise @@ -5378,7 +5401,11 @@ static uint xcl_cap = 1u << 16; } self.safe_barrier_prelude(&mut h); let t = ms.threads; - let _ = writeln!(h, "[WaveSize({native_lanes})]\n[numthreads({t}, 1, 1)]\nvoid main(uint gi : SV_GroupIndex, uint3 gid : SV_GroupID)\n{{"); + if self.native_mesh { + super::native_mesh::entry(&mut h, ms); + } else { + let _ = writeln!(h, "[WaveSize({native_lanes})]\n[numthreads({t}, 1, 1)]\nvoid main(uint gi : SV_GroupIndex, uint3 gid : SV_GroupID)\n{{"); + } if self.safe_barrier { h.push_str(" xcl_s_barrier_init(gi);\n"); } @@ -5391,17 +5418,21 @@ static uint xcl_cap = 1u << 16; } // thread index in the group as the console numbers it: wave · lanes + lane let _ = writeln!(h, " uint xcl_wave = gi / {lanes}u;\n uint xcl_slot = xcl_wave * {lanes}u + lane_id;"); - let _ = writeln!(h, " uint xcl_rec = gid.x * {}u;", ms.record_dwords()); - let _ = writeln!(h, " uint xcl_vtx = xcl_rec + {MESH_HEADER}u + xcl_slot * {}u;", ms.vert_dwords()); - let _ = writeln!(h, " uint xcl_prm = xcl_rec + {}u + xcl_slot;", MESH_HEADER + ms.max_vertices as usize * ms.vert_dwords()); + if !self.native_mesh { + let _ = writeln!(h, " uint xcl_rec = gid.x * {}u;", ms.record_dwords()); + let _ = writeln!(h, " uint xcl_vtx = xcl_rec + {MESH_HEADER}u + xcl_slot * {}u;", ms.vert_dwords()); + let _ = writeln!(h, " uint xcl_prm = xcl_rec + {}u + xcl_slot;", MESH_HEADER + ms.max_vertices as usize * ms.vert_dwords()); + } // A record has room for `max_vertices` vertices and `max_primitives` primitives; a // thread past either exports nothing (the console's hardware drops an export past // what the program asked room for). `res` is a root UAV: nothing bounds a store // there, and one past the last record of the buffer is a store to an unmapped // address (a retail title's first frames with mesh programs lost the device to a // shader's access to unmapped memory on five shader units at once). - let _ = writeln!(h, " bool xcl_vok = xcl_slot < {}u;", ms.max_vertices); - let _ = writeln!(h, " bool xcl_pok = xcl_slot < {}u;", ms.max_primitives); + if !self.native_mesh { + let _ = writeln!(h, " bool xcl_vok = xcl_slot < {}u;", ms.max_vertices); + let _ = writeln!(h, " bool xcl_pok = xcl_slot < {}u;", ms.max_primitives); + } load_sgprs(&mut h); if sg.contains(&3) { h.push_str(" s3 = (s3 & 0xF0FFFFFFu) | (xcl_wave << 24);\n"); @@ -5422,6 +5453,9 @@ static uint xcl_cap = 1u << 16; if self.safe_barrier { h.push_str(" xcl_s_barrier_exit();\n"); } + if self.native_mesh { + super::native_mesh::finish(&mut h, ms); + } h.push_str("}\n"); } Mode::Geometry(g) => { diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 40e5550799..90d4c37346 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -64,6 +64,7 @@ pub mod partition; pub mod ps_masks; pub mod x64_masks; pub mod pso; +mod native_mesh; pub use emit::mesh_passthrough; pub mod runner; pub mod ssa; @@ -1941,10 +1942,16 @@ pub(crate) fn needs_coherent_mem(insts: &[Decoded]) -> bool { #[inline] pub fn translate(code: &[u8], opt: &Options) -> Result { let _stall = crate::stall::span(crate::stall::StallKind::ShaderTranslation); - translate_inner(code, opt) + translate_inner(code, opt, false) } -fn translate_inner(code: &[u8], opt: &Options) -> Result { +pub(super) fn translate_native_mesh(code: &[u8], opt: &Options) -> Result { + let Mode::Mesh(ms) = &opt.mode else { return Err("not a mesh entry".into()) }; + native_mesh::preflight(code, ms, opt.wave64)?; + translate_inner(code, opt, true) +} + +fn translate_inner(code: &[u8], opt: &Options, native_mesh: bool) -> Result { let program = code; let normalized; let opt = if opt.mem_windows & HEAP_WINDOWS != 0 { @@ -1997,6 +2004,7 @@ fn translate_inner(code: &[u8], opt: &Options) -> Result { } } let mut em = emit::Em::new(opt.clone()); + em.native_mesh = native_mesh; em.coherent_mem = matches!(opt.mode, Mode::Compute(_)) && needs_coherent_mem(&insts); em.configure_round_modes(&insts, branches == 0); em.writes_lds = emit::lds_order_wanted() && emit::writes_lds(&insts); @@ -2069,7 +2077,7 @@ fn translate_inner(code: &[u8], opt: &Options) -> Result { // smaller for DXC and the driver on big programs) emit_structured(&sctx, &mut em, &mut code, 0, u64::MAX, None, 0, &Conts::default(), &BTreeSet::new(), 1, &mut blocks, &mut flags); if code.len() > STRUCTURED_BYTES_PER_CODE_BYTE * program.len() { - return translate_inner(program, &Options { structured: false, ..opt.clone() }); + return translate_inner(program, &Options { structured: false, ..opt.clone() }, native_mesh); } } else { if gs_jump.is_some() && opt.split_wave64 && opt.wave64 { diff --git a/crates/xcl/src/gpu/recomp/native_mesh.rs b/crates/xcl/src/gpu/recomp/native_mesh.rs new file mode 100644 index 0000000000..13e31e67dd --- /dev/null +++ b/crates/xcl/src/gpu/recomp/native_mesh.rs @@ -0,0 +1,96 @@ +//! Eligibility and output layout for the single-wave native mesh entry. + +use std::fmt::Write; + +use super::{ranked, MsInterface}; +use crate::gpu::rdna2::{decode, field_value}; + +pub(super) fn preflight(code: &[u8], ms: &MsInterface, wave64: bool) -> Result<(), &'static str> { + if wave64 || ms.threads != 32 || !(1..=32).contains(&ms.max_vertices) || !(1..=32).contains(&ms.max_primitives) { + return Err("requires one wave32 and at most one vertex and primitive per lane"); + } + let params = ranked(&ms.outputs, true); + if !ms.outputs.iter().any(|e| e.system_value == 1 && e.mask == 15) + || params.iter().any(|e| e.component_type != 3 || e.system_value != 0) + || !fits_output(ms.max_vertices, params.len()) + { + return Err("unsupported mesh output signature"); + } + let mut offset = 0; + let mut counts = 0; + let mut position = false; + let mut primitive = false; + while offset < code.len() { + let d = decode(&code[offset..], offset as u64).map_err(|_| "cannot decode mesh program")?; + offset += d.len; + if d.inst.name.contains("_STORE") + || d.inst.name.contains("_ATOMIC") + || crate::gpu::dxil::kernel::real_lds_access(&d) + { + return Err("mesh program may write shared memory"); + } + if crate::gpu::rdna2::vgpr_uses(&d).0.contains(&5) { + return Err("uses the two-pass linear group index"); + } + let field = |name| field_value(d.enc, &d.words, name).unwrap_or_default(); + if d.inst.name == "S_SENDMSG" && field("SIMM16") & 0xf == 9 { + counts += 1; + } + if d.enc.name == "ENC_EXP" { + match (field("TGT"), field("EN"), field("COMPR")) { + (9, _, 0) | (32..=63, _, 0) => {} + (12, 15, 0) => position = true, + (20, 1, 0) => primitive = true, + _ => return Err("unsupported mesh export"), + } + } + } + if counts != 1 || !position || !primitive { + return Err("requires one allocation request, position and primitive exports"); + } + Ok(()) +} + +fn fits_output(max_vertices: u32, params: usize) -> bool { + // D3D12 rounds the vertex count to a multiple of 32 for the 32 KiB output budget. + // This entry declares float4 attributes and no per-primitive attributes. + const ROWS: usize = 32; + params < ROWS && (params + 1) * 16 * max_vertices.next_multiple_of(32) as usize <= 32 * 1024 +} + +pub(super) fn entry(h: &mut String, ms: &MsInterface) { + h.push_str("struct XclVert { float4 pos : SV_Position;\n"); + for (k, e) in ranked(&ms.outputs, true).into_iter().enumerate() { + let _ = writeln!(h, " float4 p{k} : {};", e.semantic()); + } + let _ = writeln!( + h, + "}};\n[outputtopology(\"triangle\")]\n[numthreads(32, 1, 1)]\nvoid main(uint gi : SV_GroupIndex, uint3 gid : SV_GroupID, out vertices XclVert verts[{}], out indices uint3 tris[{}])\n{{", + ms.max_vertices, ms.max_primitives, + ); + let words = ms.vert_dwords(); + let _ = writeln!(h, " uint xcl_vertex[{words}];\n [unroll] for (uint i = 0u; i < {words}u; ++i) xcl_vertex[i] = 0u;"); + h.push_str(" uint xcl_primitive = 0x80000000u;\n uint xcl_counts = 0u;\n"); +} + +pub(super) fn finish(h: &mut String, ms: &MsInterface) { + h.push_str(" uint counts = WaveReadLaneAt(xcl_counts, 0u);\n"); + let _ = writeln!(h, " uint nv = min(counts & 0x3ffu, {}u);", ms.max_vertices); + let _ = writeln!(h, " uint np = nv == 0u ? 0u : min((counts >> 12) & 0x7ffu, {}u);", ms.max_primitives); + h.push_str(" SetMeshOutputCounts(nv, np);\n if (xcl_slot < nv) {\n XclVert v;\n"); + for (k, field) in std::iter::once("pos".to_string()).chain((0..ranked(&ms.outputs, true).len()).map(|k| format!("p{k}"))).enumerate() { + let i = 4 * k; + let _ = writeln!(h, " v.{field} = asfloat(uint4(xcl_vertex[{i}], xcl_vertex[{}], xcl_vertex[{}], xcl_vertex[{}]));", i + 1, i + 2, i + 3); + } + h.push_str( + " verts[xcl_slot] = v;\n }\n if (xcl_slot < np) {\n uint p = xcl_primitive;\n uint3 x = uint3(p & 0x1ffu, (p >> 10) & 0x1ffu, (p >> 20) & 0x1ffu);\n tris[xcl_slot] = select((p >> 31) != 0u || any(x >= nv), uint3(0u, 0u, 0u), x);\n }\n", + ); +} + +#[cfg(test)] +#[test] +fn native_mesh_output_budget_includes_alignment_and_row_limit() { + assert!(fits_output(33, 31)); + assert!(!fits_output(65, 31)); + assert!(!fits_output(1, 32)); +} diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 0abc5314e4..e8328b146a 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1547,6 +1547,22 @@ pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Resul }) } +pub(crate) fn console_native_mesh(blob: &[u8]) -> Result, String> { + let sh = xbox::parse(blob).ok_or("not a console shader container")?; + let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 7)).ok_or("no NGG hardware variant")?; + let mode = interface(blob, &sh, f).ok_or("unknown mesh interface")?; + let p = f.programs.first().ok_or("FSSM without a program")?; + let code = &f.data[p.offset..p.offset + p.len]; + let t = super::translate_native_mesh(code, &Options { + mode, wave64: super::fssm_wave64(f, code), rodata: f.rodata(p), + mem_windows: windows_for_stage(mem_windows(), Stage::Mesh), ..Default::default() + })?; + if !t.complete() || !t.static_samplers.is_empty() { + return Err("native mesh translation or sampler layout unsupported".into()); + } + Ok(dxc::compile_cached(&t.hlsl, "main", "ms_6_6")?.0) +} + /// Whether the adapter runs only 32-lane waves (its wave range lacks 64): wave64 compute, /// mesh and geometry programs then need the split form. pub fn wave32_only(wave_min: u32, wave_max: u32) -> bool { diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index e71ac1975a..63aa4d06b6 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1329,18 +1329,39 @@ pub fn mesh_draw_split( mem: &[u32], size: u32, clear: [f32; 4], +) -> Result<(Vec<[f32; 4]>, Vec), String> { + mesh_draw_with(Some(cs), ms, ps, groups, split, record_dwords, sgprs, mem, size, clear) +} + +#[cfg(test)] +pub fn mesh_draw_native(ms: &[u8], ps: &[u8], groups: u32, sgprs: &[u32], mem: &[u32], size: u32) -> Result, String> { + mesh_draw_with(None, ms, ps, groups, 1, 0, sgprs, mem, size, [0.0; 4]).map(|(pixels, _)| pixels) +} + +#[allow(clippy::too_many_arguments)] +fn mesh_draw_with( + cs: Option<&[u8]>, + ms: &[u8], + ps: &[u8], + groups: u32, + split: u32, + record_dwords: usize, + sgprs: &[u32], + mem: &[u32], + size: u32, + clear: [f32; 4], ) -> Result<(Vec<[f32; 4]>, Vec), String> { let mut g = GPU.lock().unwrap(); let gpu = g.get_or_insert_with(init).as_mut().map_err(|x| x.clone())?; unsafe { let dev = &gpu.dev; - let cpso: ID3D12PipelineState = dev + let cpso: Option = cs.map(|cs| dev .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&gpu.rs), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as _, BytecodeLength: cs.len() }, ..Default::default() }) - .map_err(|x| format!("CreateComputePipelineState: {x}"))?; + .map_err(|x| format!("CreateComputePipelineState: {x}"))).transpose()?; let mut blend = D3D12_BLEND_DESC::default(); blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; let rast = D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() }; @@ -1411,34 +1432,35 @@ pub fn mesh_draw_split( upload.Unmap(0, None); let io_buf = buffer(dev, io_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; let mem_buf = buffer(dev, mem_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; - let res_buf = buffer(dev, res_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; + let res_buf = cpso.as_ref().map(|_| buffer(dev, res_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)).transpose()?; let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); let mut total = 0u64; dev.GetCopyableFootprints(&tex, 0, 1, 0, Some(&mut fp), None, None, Some(&mut total)); let readback = buffer(dev, total + res_bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?; let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &cpso).map_err(e)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, cpso.as_ref()).map_err(e)?; list.CopyBufferRegion(&io_buf, 0, &upload, 0, io_bytes); list.CopyBufferRegion(&mem_buf, 0, &upload, io_bytes, mem_bytes); list.ResourceBarrier(&[ transition(&io_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), transition(&mem_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - transition(&res_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), ]); // pass 1: the console program as a compute shader let _bound = bind_resources(dev, &list, &[], &[])?; - list.SetComputeRootSignature(&gpu.rs); - list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); - list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); - list.SetComputeRootUnorderedAccessView(2, mem_buf.GetGPUVirtualAddress()); - list.Dispatch(groups, 1, 1); - list.ResourceBarrier(&[uav_barrier(&res_buf)]); - // pass 2: rasterise the records + if let Some(res_buf) = &res_buf { + list.ResourceBarrier(&[transition(res_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + list.SetComputeRootSignature(&gpu.rs); + list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, mem_buf.GetGPUVirtualAddress()); + list.Dispatch(groups, 1, 1); + list.ResourceBarrier(&[uav_barrier(res_buf)]); + } list.SetPipelineState(&mpso); list.SetGraphicsRootSignature(&gpu.rs); list.SetGraphicsRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); - list.SetGraphicsRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); + list.SetGraphicsRootUnorderedAccessView(1, res_buf.as_ref().unwrap_or(&io_buf).GetGPUVirtualAddress()); list.SetGraphicsRootUnorderedAccessView(2, mem_buf.GetGPUVirtualAddress()); list.OMSetRenderTargets(1, Some(&rtv), false, None); list.ClearRenderTargetView(rtv, &clear, None); @@ -1446,14 +1468,14 @@ pub fn mesh_draw_split( list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { left: 0, top: 0, right: size as i32, bottom: size as i32 }]); let list6: ID3D12GraphicsCommandList6 = list.cast().map_err(e)?; list6.DispatchMesh(groups * split, 1, 1); - list.ResourceBarrier(&[ - transition(&rt, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE), - transition(&res_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), - ]); + list.ResourceBarrier(&[transition(&rt, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]); let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; let src = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&rt), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); - list.CopyBufferRegion(&readback, total, &res_buf, 0, res_bytes); + if let Some(res_buf) = &res_buf { + list.ResourceBarrier(&[transition(res_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&readback, total, res_buf, 0, res_bytes); + } list.Close().map_err(e)?; gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]); gpu.value += 1; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 57fd25bfb5..cbbc1a3f8f 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -7,6 +7,60 @@ use super::runner::{self, KernelState}; use super::{translate, Mode, Options}; use crate::gpu::rdna2::encode; +#[test] +fn gpu_native_mesh_matches_two_pass() { + if !gpu_ready() || !mesh_ready() { + return; + } + if runner::wave64_supported() == Ok(true) || runner::wave32_supported() != Ok(true) { + runner::skip_test("native mesh fixture requires a wave32-only adapter"); + return; + } + let code = prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 124), ("SSRC0", 255)], Some(1 << 12 | 3)), + ("S_SENDMSG", "ENC_SOPP", &[("SIMM16", 9)], None), + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 0), ("SRC0", 193), ("SRC1", 128)], None), + ("BUFFER_LOAD_DWORDX4", "ENC_MUBUF", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("EXP", "ENC_EXP", &[("TGT", 12), ("EN", 15), ("VSRC0", 10), ("VSRC1", 11), ("VSRC2", 12), ("VSRC3", 13)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 21), ("SRC0", 255)], Some(1 << 10 | 2 << 20)), + ("EXP", "ENC_EXP", &[("TGT", 20), ("EN", 1), ("VSRC0", 21), ("DONE", 1)], None), + ]); + let ms = super::MsInterface { + outputs: vec![crate::gpu::dxbc::SigElement { + name: "SV_Position".into(), index: 0, system_value: 1, component_type: 3, + register: 0, mask: 15, rw_mask: 15, stream: 0, + }], + threads: 32, max_vertices: 3, max_primitives: 1, + }; + let opt = Options { mode: Mode::Mesh(ms.clone()), wave64: false, ..Default::default() }; + let oversized = super::MsInterface { max_vertices: 33, ..ms.clone() }; + let rejected = Options { mode: Mode::Mesh(oversized.clone()), ..opt.clone() }; + assert!(super::translate_native_mesh(&code, &rejected).is_err()); + let fallback = translate(&code, &rejected).unwrap(); + assert!(fallback.complete()); + let native = super::translate_native_mesh(&code, &opt).unwrap(); + assert!(native.complete(), "{:?}", native.unsupported_why); + let two_pass = translate(&code, &opt).unwrap(); + let compile = |source: &str, profile| super::dxc::compile(source, "main", profile, &[]).unwrap_or_else(|e| panic!("{e}\n{source}")); + let native = compile(&native.hlsl, "ms_6_6"); + let cs = compile(&two_pass.hlsl, "cs_6_6"); + let passthrough = compile(&super::mesh_passthrough(&ms), "ms_6_6"); + let ps = compile("float4 main() : SV_Target0 { return float4(1, 0.5, 0.25, 1); }", "ps_6_6"); + let mut sgprs = vec![0; 128]; + sgprs[16..20].copy_from_slice(&[0x100, 16 << 16, 3, 0]); + let mut mem = vec![0; 256]; + for (i, (x, y)) in [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0)].into_iter().enumerate() { + mem[64 + i * 4..68 + i * 4].copy_from_slice(&[f(x), f(y), f(0.0), f(1.0)]); + } + let (expected, _) = runner::mesh_draw(&cs, &passthrough, &ps, 1, ms.record_dwords(), &sgprs, &mem, 16, [0.0; 4]).unwrap(); + assert!(expected.contains(&[1.0, 0.5, 0.25, 1.0])); + assert_eq!(runner::mesh_draw_native(&native, &ps, 1, &sgprs, &mem, 16).unwrap(), expected); + let fallback = compile(&fallback.hlsl, "cs_6_6"); + let oversized_pass = compile(&super::mesh_passthrough(&oversized), "ms_6_6"); + let (fallback, _) = runner::mesh_draw(&fallback, &oversized_pass, &ps, 1, oversized.record_dwords(), &sgprs, &mem, 16, [0.0; 4]).unwrap(); + assert_eq!(fallback, expected); +} + /// A GPU and DXC for the instruction tests. Wave64 programs run natively where the adapter /// has 64-lane waves and in the split form (`runner::options`) where it has only 32 (an /// adapter with neither, such as WARP, skips). From 39a39796deed348e9379a5aa80d7a04332704c00 Mon Sep 17 00:00:00 2001 From: KDenKC <125705260+KDenKC@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:20:01 -0700 Subject: [PATCH 2/3] D3D12.X: use native mesh for eligible draws when enabled Checked: #3011 C4, #3040, #3042, #2092, #1936 and #1937. Keep the existing two-pass PSO as fallback. Retain GPU bounds checks for indirect launches and forward the title count. Assisted-by: Codex (GPT-6.2-Sol) --- crates/xcl/src/hle/d3d12x/bind.rs | 77 +++++++++++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 58 ++++++++++++++++++++++- 2 files changed, 129 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 62d5549b14..4f2e01ca90 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -3109,6 +3109,27 @@ unsafe fn prepare_two_pass_stage( Ok(StageBind { rs, pso, views: [va(io_at), res_va, w(0), w(1), w(2), w(3)] }) } +unsafe fn native_mesh_stage(this: *mut c_void, pso: usize, tp: &super::real::TwoPassPso) -> Option { + let native = tp.native.get()?; + if super::list_x::tracked_list_type(this) != Some(D3D12_COMMAND_LIST_TYPE_DIRECT) { + return None; + } + super::list_x::ensure_view_heap(this); + let ms = prepare_two_pass_stage(this, pso, tp, 0, true, 0).ok()?; + let mut gfx = prepare_two_pass_stage(this, pso, tp, ms.views[0], false, 0).ok()?; + gfx.pso = native.as_raw() as usize; + Some(gfx) +} + +unsafe fn emit_native_mesh_stage(this: *mut c_void, list: &ID3D12GraphicsCommandList, stage: &StageBind, original: usize) { + let rs = stage.rs as *mut c_void; + list.SetGraphicsRootSignature(ID3D12RootSignature::from_raw_borrowed(&rs)); + for (slot, va) in stage.views.into_iter().enumerate() { + list.SetGraphicsRootUnorderedAccessView(slot as u32, va); + } + super::real::bind_pipeline_exact(this, original, stage.pso); +} + /// The pass that rewrites a two-pass ExecuteIndirect's arguments, on XCL's ABI: u0 = `count`, /// `stride`, `offset` (of the DispatchMesh argument), `split`, `cap` (groups with a record), and /// where the commands are (u2) and go (u3), in bytes. Each command goes out twice, for the compute @@ -3243,6 +3264,7 @@ unsafe fn make_scaled_args_buffer( batch: bool, fb_va: Option, fb_slot: u32, + native_mesh: bool, ) -> Result<(ID3D12Resource, u64), String> { let (rewrite, dst, dst_off) = prepare_scaled_args(this, src, count, max, stride, mesh_offset, split, cap, fb_va, fb_slot)?; // the title's writes of the arguments before this (`fresh_indirect_arguments`) @@ -3255,7 +3277,11 @@ unsafe fn make_scaled_args_buffer( } let (rs_raw, pso_raw) = (rewrite.rs as *mut c_void, rewrite.pso as *mut c_void); list.SetComputeRootSignature(ID3D12RootSignature::from_raw_borrowed(&rs_raw)); - list.SetPipelineState(ID3D12PipelineState::from_raw_borrowed(&pso_raw)); + if native_mesh { + super::real::bind_pipeline_exact(this, rewrite.pso, rewrite.pso); + } else { + list.SetPipelineState(ID3D12PipelineState::from_raw_borrowed(&pso_raw)); + } for (slot, va) in rewrite.views { list.SetComputeRootUnorderedAccessView(slot, va); } @@ -3399,6 +3425,22 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: } DrawPipeline::Other => None, }; + if let Some(tp) = &tp { + let groups = u64::from(x).saturating_mul(u64::from(y)).saturating_mul(u64::from(z)); + if groups > 0 && groups <= 1 << 22 && [x, y, z].into_iter().all(|dim| dim <= 65535) { + if let Some(stage) = native_mesh_stage(this, pso, tp) { + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + flush_two_pass(this, RunEnd::Draw); + emit_native_mesh_stage(this, list, &stage, raw_pso); + let t = super::gpu_profile::begin(this, pso, super::gpu_profile::Kind::Draw, [x, y, z]); + pc_dm(this, x, y, z); + super::gpu_profile::end(this, t); + mesh_work(this, super::targets::RAN); + count(DRAWS); + return; + } + } + } // (XCL_TWO_PASS_BATCH=2: deferred, or the deferred ones recorded before this one) if let Some(tp) = &tp { if two_pass_defer() && defer_dispatch_mesh(this, tp, pso, raw_pso, [x, y, z]) { @@ -3648,6 +3690,31 @@ unsafe fn execute_indirect_snapshot( } return; }; + // Keep the existing GPU bounds pass until a native launch can check its arguments. + // The final call still uses the title's count, so it executes only the live records. + if tp.native.get().is_some() && max > 0 { + let src = commands_at.filter(|&(_, n)| max as u64 * u64::from(msig.byte_stride) <= n as u64); + let count_source = if count_buf == 0 { Some(None) } else { count_at.map(Some) }; + if let (Some((src, _)), Some(count_source), Some(list), Some(stage)) = + (src, count_source, ID3D12GraphicsCommandList::from_raw_borrowed(&this), native_mesh_stage(this, pso, &tp)) + { + flush_two_pass(this, RunEnd::Draw); + let batch = two_pass_batch(); + if let Ok((scaled, at)) = make_scaled_args_buffer(this, list, src, count_source, max, msig.byte_stride, msig.mesh_offset, 1, 65535, batch, None, 0, true) { + emit_native_mesh_stage(this, list, &stage, raw_pso); + let t = super::gpu_profile::begin(this, pso, super::gpu_profile::Kind::IndirectDraw, [max, 0, 0]); + fresh_indirect_arguments(this, || pc(this, sig, max, scaled.as_raw() as usize, at, count_buf, count_off)); + super::gpu_profile::end(this, t); + if !batch { + emit_transition(list, &scaled, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + } + mesh_work(this, super::targets::RAN); + super::watch::note(raw_pso, super::watch::INDIRECT_MESH, [max, 0, 0]); + count(DRAWS); + return; + } + } + } // (XCL_TWO_PASS_BATCH=2: one command whose arguments and count are in unified memory // deferred; anything else as without, after the deferred draws before it) if two_pass_defer() && max == 1 && args != 0 { @@ -3695,7 +3762,7 @@ unsafe fn execute_indirect_snapshot( }; // the groups past the record buffer, and the commands past the count, are dropped // on the GPU (`SCALE_ARGS_HLSL`) - let (scaled, at) = make_scaled_args_buffer(this, list, src, count, max, msig.byte_stride, msig.mesh_offset, tp.mesh_groups_per_record, cap, batch, fb_va, fb_slot)?; + let (scaled, at) = make_scaled_args_buffer(this, list, src, count, max, msig.byte_stride, msig.mesh_offset, tp.mesh_groups_per_record, cap, batch, fb_va, fb_slot, false)?; if let Some(d) = &fb_dev { if fb_slot != 0 { let dk = d.as_raw() as usize; @@ -8567,7 +8634,7 @@ void main(uint t : SV_GroupIndex) { fn dummy_draw() -> DeferredDraw { DeferredDraw { snap: snap(0, None), - _tp: Arc::new(super::super::real::TwoPassPso { compute: 0, compute_rs: 0, mesh_rs: 0, record: Default::default(), mesh_groups_per_record: 1, kind: "MS" }), + _tp: Arc::new(super::super::real::TwoPassPso { native: Default::default(), compute: 0, compute_rs: 0, mesh_rs: 0, record: Default::default(), mesh_groups_per_record: 1, kind: "MS" }), _mesh_pso: None, _block: None, raw_pso: 0, @@ -8738,7 +8805,7 @@ void main(uint t : SV_GroupIndex) { let list = 0x7500_0031usize as *mut c_void; let draw = || DeferredDraw { snap: snap(0, None), - _tp: Arc::new(super::super::real::TwoPassPso { compute: 0, compute_rs: 0, mesh_rs: 0, record: Default::default(), mesh_groups_per_record: 1, kind: "MS" }), + _tp: Arc::new(super::super::real::TwoPassPso { native: Default::default(), compute: 0, compute_rs: 0, mesh_rs: 0, record: Default::default(), mesh_groups_per_record: 1, kind: "MS" }), _mesh_pso: None, _block: None, raw_pso: 0, @@ -8989,7 +9056,7 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) let this = &*fake as *const FakeList as *mut c_void; let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this).unwrap(); // no root signatures: the bind stops before it records anything else - let tp = super::super::real::TwoPassPso { compute: 0, compute_rs: 0, mesh_rs: 0, record: Default::default(), mesh_groups_per_record: 1, kind: "MS" }; + let tp = super::super::real::TwoPassPso { native: Default::default(), compute: 0, compute_rs: 0, mesh_rs: 0, record: Default::default(), mesh_groups_per_record: 1, kind: "MS" }; for compute_pass in [true, false] { super::super::list_x::set_descriptor_heaps_x(this, 0, std::ptr::null()); assert!(super::super::list_x::bound_heaps(this, false).is_empty()); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a9dad2dd11..1e686fb22a 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -8948,6 +8948,7 @@ unsafe fn compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, /// mesh pipeline state (pass-through MS + PS); the draw first runs `compute` (the console /// program, one record per thread group into `res`), then the mesh pipeline over the records. pub struct TwoPassPso { + pub native: std::sync::OnceLock, /// compute pipeline state, owned here, and its root signature (static samplers) pub compute: usize, pub compute_rs: usize, @@ -8965,6 +8966,9 @@ impl Drop for TwoPassPso { // the compute pipeline state is XCL's (the root signatures are cached or the title's); // lists in flight may bind it: `late_release` lets it go once the queues are past them super::late_release::hold_pipeline(self.compute); + if let Some(native) = self.native.take() { + super::late_release::hold_pipeline(native.into_raw() as usize); + } } } @@ -9004,6 +9008,7 @@ pub(super) fn register_two_pass_for_test(pso: usize, kind: &'static str) { TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert( pso, std::sync::Arc::new(TwoPassPso { + native: Default::default(), compute: 0, compute_rs: 0, mesh_rs: 0, @@ -9654,7 +9659,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let mesh_pso = mesh_pso.into_raw(); *ppv = mesh_pso; note_pso_rs(mesh_pso, mesh_rs); - TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert(mesh_pso as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); + TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert(mesh_pso as usize, std::sync::Arc::new(TwoPassPso { native: Default::default(), compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); if n < 5 || n % 1000 == 0 || pso_trace() { crate::xlog_info!("D3D12.X: pipeline from the console {kind} in two passes (compute {} B + mesh {} B DXIL; blobs reused: compute {creused}, mesh {greused})", tp.cs.len(), tp.ms.len()); @@ -9840,6 +9845,36 @@ unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: * with_switch_fallback(|| translated_mesh_stream_once(this, desc, riid, ppv)) } +unsafe fn try_native_mesh( + this: *mut c_void, ms: &[u8], ps: Option<&[u8]>, rs: *mut c_void, state: &[u8], +) -> Result { + let dev = ID3D12Device::from_raw_borrowed(&this).ok_or("no device")?; + let mut wave = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&mut wave as *mut D3D12_FEATURE_DATA_D3D12_OPTIONS1).cast(), std::mem::size_of_val(&wave) as u32) + .map_err(|_| "could not query wave size")?; + if !wave.WaveOps.as_bool() || wave.WaveLaneCountMin != 32 || wave.WaveLaneCountMax != 32 { + return Err("requires hardware wave32".into()); + } + let shader = crate::gpu::recomp::pso::console_native_mesh(ms)?; + let mut stream = two_pass_mesh_stream(rs, &shader, ps); + stream.0.extend_from_slice(state); + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: stream.0.len(), + pPipelineStateSubobjectStream: stream.0.as_mut_ptr().cast(), + }; + let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); + let mut raw = std::ptr::null_mut(); + // An optional PSO refusal must not recreate the already successful two-pass fallback. + let oom = HEAP_WINDOW_OOM.with(|flag| flag.get()); + let iid = pc_iid(Kind::PipelineState); + let hr = finish_pso(this, f, (&desc as *const D3D12_PIPELINE_STATE_STREAM_DESC).cast(), &iid, &mut raw); + HEAP_WINDOW_OOM.with(|flag| flag.set(oom)); + if hr < 0 || raw.is_null() { + return Err(format!("native mesh pipeline rejected ({hr:#x})")); + } + Ok(ID3D12PipelineState::from_raw(raw)) +} + unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { use crate::gpu::recomp::pso::{console_mesh, is_console}; if !crate::gpu::shader::readable(desc as usize, 16) { @@ -9901,6 +9936,7 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri let Some(rs) = abi_rs_for(this, &ps_samplers) else { return Some(E_INVALIDARG) }; // the title's state (blend, rasteriser, depth, formats …) with XCL's RS and shaders let mut out = two_pass_mesh_stream(rs, &tp.ms, ps.as_deref()); + let state_start = out.0.len(); for (ty, payload) in &subs { let skip = [0, 2, 14, 19, 24, 25].contains(ty); // RS, PS, topology, cached PSO, AS, MS if !skip { @@ -9932,6 +9968,26 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri let node_mask = stream_node_mask(&subs); let hr = finish_two_pass(this, &out, tp, rs, &ps_samplers, node_mask, "MS", riid, ppv); if hr >= 0 { + static NATIVE: std::sync::OnceLock = std::sync::OnceLock::new(); + if *NATIVE.get_or_init(|| std::env::var("XCL_NATIVE_MESH").is_ok_and(|s| s == "1")) + && !crate::gpu::recomp::dxc::defer() + && !crate::shaders::pipeline_library::building() + { + if let Some(pipeline) = two_pass_of_exact(*ppv as usize) { + let result = try_native_mesh(this, ms, ps.as_deref(), rs, &out.0[state_start..]); + let hash = crate::gpu::shader::fnv64(ms); + static SEEN: Mutex>> = Mutex::new(None); + if SEEN.lock().unwrap().get_or_insert_with(HashSet::new).insert((hash, result.is_ok())) { + match &result { + Ok(_) => crate::xlog_info!("D3D12.X: native mesh {hash:016x}: eligible"), + Err(e) => crate::xlog_info!("D3D12.X: native mesh {hash:016x}: using two passes ({e})"), + } + } + if let Ok(native) = result { + let _ = pipeline.native.set(native); + } + } + } super::dred::label(*ppv as usize, &[("ms", Some(ms)), ("ps", console_ps)]); if super::gpu_times::enabled() { PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(ms), console_ps.map_or(0, crate::gpu::shader::fnv64))); From 1e65e6a2f18df5894956644f39a76bfb4ae9e6b3 Mon Sep 17 00:00:00 2001 From: KDenKC <125705260+KDenKC@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:32:14 -0700 Subject: [PATCH 3/3] D3D12.X: keep legal native mesh arguments and report native draws Checked: #3327, #3011 C4 and #2092. Budget primitive indices too. Keep legal indirect dimensions, reject over-limit arguments with the existing feedback, and distinguish native meshes in the GPU timestamps and watch ring. Assisted-by: Codex (GPT-6.2-Sol) --- crates/xcl/src/gpu/recomp/native_mesh.rs | 16 ++++++------ crates/xcl/src/hle/d3d12x/bind.rs | 32 ++++++++++++++++++------ crates/xcl/src/hle/d3d12x/gpu_profile.rs | 17 ++++++++++--- crates/xcl/src/hle/d3d12x/gpu_times.rs | 5 ++++ crates/xcl/src/hle/d3d12x/watch.rs | 6 ++++- 5 files changed, 57 insertions(+), 19 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/native_mesh.rs b/crates/xcl/src/gpu/recomp/native_mesh.rs index 13e31e67dd..3002e21186 100644 --- a/crates/xcl/src/gpu/recomp/native_mesh.rs +++ b/crates/xcl/src/gpu/recomp/native_mesh.rs @@ -12,7 +12,7 @@ pub(super) fn preflight(code: &[u8], ms: &MsInterface, wave64: bool) -> Result<( let params = ranked(&ms.outputs, true); if !ms.outputs.iter().any(|e| e.system_value == 1 && e.mask == 15) || params.iter().any(|e| e.component_type != 3 || e.system_value != 0) - || !fits_output(ms.max_vertices, params.len()) + || !fits_output(ms.max_vertices, ms.max_primitives, params.len()) { return Err("unsupported mesh output signature"); } @@ -51,11 +51,12 @@ pub(super) fn preflight(code: &[u8], ms: &MsInterface, wave64: bool) -> Result<( Ok(()) } -fn fits_output(max_vertices: u32, params: usize) -> bool { +fn fits_output(max_vertices: u32, max_primitives: u32, params: usize) -> bool { // D3D12 rounds the vertex count to a multiple of 32 for the 32 KiB output budget. - // This entry declares float4 attributes and no per-primitive attributes. + // Budget float4 attributes and, conservatively, the uint3 triangle index for each primitive. const ROWS: usize = 32; - params < ROWS && (params + 1) * 16 * max_vertices.next_multiple_of(32) as usize <= 32 * 1024 + params < ROWS + && (params + 1) * 16 * max_vertices.next_multiple_of(32) as usize + 12 * max_primitives as usize <= 32 * 1024 } pub(super) fn entry(h: &mut String, ms: &MsInterface) { @@ -90,7 +91,8 @@ pub(super) fn finish(h: &mut String, ms: &MsInterface) { #[cfg(test)] #[test] fn native_mesh_output_budget_includes_alignment_and_row_limit() { - assert!(fits_output(33, 31)); - assert!(!fits_output(65, 31)); - assert!(!fits_output(1, 32)); + assert!(fits_output(32, 32, 31)); + assert!(fits_output(33, 1, 30)); + assert!(!fits_output(33, 1, 31)); + assert!(!fits_output(1, 1, 32)); } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 4f2e01ca90..67c88f352f 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -3137,6 +3137,7 @@ unsafe fn emit_native_mesh_stage(this: *mut c_void, list: &ID3D12GraphicsCommand /// both passes find a group's record by `gid.x` alone. With a count buffer (u0 dword 7 set: the /// count at dword 8's byte offset in u4), the commands past its count get no groups: they are run /// one by one (`two_pass_steps`), so without one. +/// Native mesh uses `split = 0`: keep valid dimensions and zero unsafe or inactive arguments. pub(super) const SCALE_ARGS_HLSL: &str = r#"RWByteAddressBuffer io : register(u0); RWByteAddressBuffer fb : register(u1); RWByteAddressBuffer src : register(u2); @@ -3161,18 +3162,18 @@ void main(uint tid : SV_DispatchThreadID) { raw_n = min(g.x, lim); raw_n = g.y > lim / raw_n ? lim : raw_n * g.y; raw_n = g.z > lim / raw_n ? lim : raw_n * g.z; - n = min(raw_n, cap); + n = split == 0u && (any(g > 65535u) || raw_n > cap) ? 0u : min(raw_n, cap); } uint fb_slot = io.Load(36); if (fb_slot != 0u) { uint prev; - if (raw_n > cap) { + if (raw_n > n) { fb.InterlockedAdd(0u, 1u); - fb.InterlockedAdd(4u, raw_n - cap); + fb.InterlockedAdd(4u, raw_n - n); } fb.InterlockedMax((fb_slot + 1u) * 4u, raw_n + 1u, prev); } - dst.Store3(d + offset, uint3(n, 1u, 1u)); + dst.Store3(d + offset, split == 0u && n != 0u ? g : uint3(n, 1u, 1u)); dst.Store3(m + offset, uint3(n * split, 1u, 1u)); } "#; @@ -3432,7 +3433,7 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; flush_two_pass(this, RunEnd::Draw); emit_native_mesh_stage(this, list, &stage, raw_pso); - let t = super::gpu_profile::begin(this, pso, super::gpu_profile::Kind::Draw, [x, y, z]); + let t = super::gpu_profile::begin(this, pso, super::gpu_profile::Kind::NativeMesh, [x, y, z]); pc_dm(this, x, y, z); super::gpu_profile::end(this, t); mesh_work(this, super::targets::RAN); @@ -3698,18 +3699,26 @@ unsafe fn execute_indirect_snapshot( if let (Some((src, _)), Some(count_source), Some(list), Some(stage)) = (src, count_source, ID3D12GraphicsCommandList::from_raw_borrowed(&this), native_mesh_stage(this, pso, &tp)) { + let (fb_dev, fb_va, fb_slot) = super::real::list_device(this).and_then(|dev| { + prepare_indirect_feedback(&dev, stage.pso) + .map(|(va, slot, _)| (dev.as_raw() as usize, Some(va), slot)) + }).unwrap_or_default(); flush_two_pass(this, RunEnd::Draw); let batch = two_pass_batch(); - if let Ok((scaled, at)) = make_scaled_args_buffer(this, list, src, count_source, max, msig.byte_stride, msig.mesh_offset, 1, 65535, batch, None, 0, true) { + let cap = 1 << 22; + if let Ok((scaled, at)) = make_scaled_args_buffer(this, list, src, count_source, max, msig.byte_stride, msig.mesh_offset, 0, cap, batch, fb_va, fb_slot, true) { + if fb_slot != 0 { + with(this, |s| s.fb_uses.push((fb_dev, fb_slot, cap))); + track_two_pass_list(this as usize); + } emit_native_mesh_stage(this, list, &stage, raw_pso); - let t = super::gpu_profile::begin(this, pso, super::gpu_profile::Kind::IndirectDraw, [max, 0, 0]); + let t = super::gpu_profile::begin(this, pso, super::gpu_profile::Kind::IndirectNativeMesh, [max, 0, 0]); fresh_indirect_arguments(this, || pc(this, sig, max, scaled.as_raw() as usize, at, count_buf, count_off)); super::gpu_profile::end(this, t); if !batch { emit_transition(list, &scaled, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); } mesh_work(this, super::targets::RAN); - super::watch::note(raw_pso, super::watch::INDIRECT_MESH, [max, 0, 0]); count(DRAWS); return; } @@ -8149,6 +8158,13 @@ void main(uint t : SV_GroupIndex) { assert_eq!(mesh, [[1, 6, 1, 1], [2, 72, 1, 1], [3, 3000, 1, 1], [4, 0, 1, 1], [5, 3000, 1, 1], [6, 3000, 1, 1], [7, 3000, 1, 1], [8, 0, 1, 1]]); } + #[test] + fn gpu_native_mesh_indirect_preserves_legal_dimensions() { + let commands = [[1, 300, 300, 1], [2, 65_536, 1, 1], [3, 4096, 4096, 1], [4, 2, 3, 4]]; + let Some((mesh, _)) = scale_args_counted(&commands, 0, 1 << 22, Some(3)) else { return }; + assert_eq!(mesh, [[1, 300, 300, 1], [2, 0, 1, 1], [3, 0, 1, 1], [4, 0, 1, 1]]); + } + /// Freed two-pass buffers are kept, many of one size too (a frame of recordings hands back /// tens of 32 MiB ones, and the next takes them again), up to the cap in bytes, oldest let go /// first; one no recording took for `FREE_RES_IDLE` goes. diff --git a/crates/xcl/src/hle/d3d12x/gpu_profile.rs b/crates/xcl/src/hle/d3d12x/gpu_profile.rs index 0317192fa0..216795221e 100644 --- a/crates/xcl/src/hle/d3d12x/gpu_profile.rs +++ b/crates/xcl/src/hle/d3d12x/gpu_profile.rs @@ -53,6 +53,8 @@ pub(super) enum Kind { IndirectDraw, /// an ExecuteIndirect with a PC pipeline PcIndirect, + NativeMesh, + IndirectNativeMesh, } impl Kind { @@ -63,6 +65,8 @@ impl Kind { Kind::Draw => "draw", Kind::IndirectDraw => "ExecuteIndirect (draws)", Kind::PcIndirect => "ExecuteIndirect with a PC pipeline", + Kind::NativeMesh => "native DispatchMesh", + Kind::IndirectNativeMesh => "native ExecuteIndirect (DispatchMesh)", } } } @@ -343,7 +347,12 @@ pub(super) struct Pair { /// Before the PC call of an op of console code on `list` (`pso`: its pipeline as bound). pub(super) unsafe fn begin(list: *mut c_void, pso: usize, kind: Kind, size: [u32; 3]) -> Option { // (every draw and dispatch with a translated pipeline comes by here: the ring of the last ones) - super::watch::note(pso, kind as u8 + 1, size); + let watch_kind = match kind { + Kind::NativeMesh => super::watch::NATIVE_MESH, + Kind::IndirectNativeMesh => super::watch::INDIRECT_NATIVE_MESH, + _ => kind as u8 + 1, + }; + super::watch::note(pso, watch_kind, size); super::gpu_times::before_op(list, pso, kind, size); if !on() || list.is_null() { return None; @@ -460,17 +469,19 @@ fn program(key: Key, shapes: &HashMap) -> String { } Kind::Draw | Kind::IndirectDraw if a != 0 => format!("VS {a:016x} PS {b:016x} {}", kind.name()), Kind::Draw | Kind::IndirectDraw => format!("{} with no console shader known", kind.name()), + Kind::NativeMesh | Kind::IndirectNativeMesh if a != 0 => format!("MS {a:016x} PS {b:016x} {}", kind.name()), + Kind::NativeMesh | Kind::IndirectNativeMesh => format!("{} with no console shader known", kind.name()), Kind::PcIndirect => kind.name().to_owned(), } } fn size_text(kind: Kind, size: [u32; 3]) -> String { match kind { - Kind::Dispatch => format!("{}x{}x{} groups", size[0], size[1], size[2]), + Kind::Dispatch | Kind::NativeMesh => format!("{}x{}x{} groups", size[0], size[1], size[2]), Kind::Draw => format!("{} vertices or indices x {} instances", size[0], size[1]), Kind::IndirectDispatch if size[1..] != [0, 0] => format!("{}x{}x{} groups, the GPU's", size[0], size[1], size[2]), Kind::IndirectDraw if size[1..] != [0, 0] => format!("{} vertices or indices x {} instances, the GPU's", size[0], size[1]), - Kind::IndirectDispatch | Kind::IndirectDraw | Kind::PcIndirect => format!("max count {} (its counts are the GPU's)", size[0]), + Kind::IndirectDispatch | Kind::IndirectDraw | Kind::IndirectNativeMesh | Kind::PcIndirect => format!("max count {} (its counts are the GPU's)", size[0]), } } diff --git a/crates/xcl/src/hle/d3d12x/gpu_times.rs b/crates/xcl/src/hle/d3d12x/gpu_times.rs index 9835891881..2fdd647ecd 100644 --- a/crates/xcl/src/hle/d3d12x/gpu_times.rs +++ b/crates/xcl/src/hle/d3d12x/gpu_times.rs @@ -111,6 +111,7 @@ pub(super) enum Kind { Graphics, /// a pipeline XCL built from a console MS or GS ("MS" / "GS"): a compute pass and a mesh pass Mesh(&'static str), + NativeMesh, /// an ExecuteIndirect with a PC pipeline Pc, /// the argument rewrites and compute passes of a run of deferred two-pass draws @@ -335,6 +336,8 @@ pub(super) unsafe fn before_op(list: *mut c_void, pso: usize, kind: super::gpu_p P::IndirectDispatch => (Kind::Compute, true), P::Draw => (Kind::Graphics, false), P::IndirectDraw => (Kind::Graphics, true), + P::NativeMesh => (Kind::NativeMesh, false), + P::IndirectNativeMesh => (Kind::NativeMesh, true), P::PcIndirect => (Kind::Pc, true), }; before(list, pso, kind, size, indirect); @@ -632,9 +635,11 @@ fn program_text(p: &Program, wave: &dyn Fn(u64) -> Option<&'static str>) -> Stri Kind::Compute if p.a != 0 => format!("compute {}{}", shader_text("cs", p.a), wave(p.a).map_or(String::new(), |w| format!(", {w}"))), Kind::Graphics if p.a != 0 => format!("graphics {}, {}", shader_text("vs", p.a), ps(p.b)), Kind::Mesh(k) if p.a != 0 => format!("mesh two-pass {}, {}", shader_text(&k.to_lowercase(), p.a), ps(p.b)), + Kind::NativeMesh if p.a != 0 => format!("mesh native {}, {}", shader_text("ms", p.a), ps(p.b)), Kind::Compute => format!("compute pipeline {:#x} (its CS not known)", p.pso), Kind::Graphics => format!("graphics pipeline {:#x} (its shaders not known)", p.pso), Kind::Mesh(k) => format!("mesh two-pass {k} pipeline {:#x} (its shaders not known)", p.pso), + Kind::NativeMesh => format!("mesh native pipeline {:#x} (its shaders not known)", p.pso), Kind::Pc => format!("PC pipeline {:#x}", p.pso), Kind::MeshBatch => "mesh two-pass compute passes of deferred draws (all programs)".into(), } diff --git a/crates/xcl/src/hle/d3d12x/watch.rs b/crates/xcl/src/hle/d3d12x/watch.rs index cd5badb731..de514d022c 100644 --- a/crates/xcl/src/hle/d3d12x/watch.rs +++ b/crates/xcl/src/hle/d3d12x/watch.rs @@ -43,11 +43,13 @@ static RING_PSO: [AtomicUsize; RING] = [const { AtomicUsize::new(0) }; RING]; /// frame (28 bits) << 36 | work (32 bits) << 4 | kind static RING_INFO: [AtomicU64; RING] = [const { AtomicU64::new(0) }; RING]; -/// kinds of work in the ring (`gpu_profile::Kind` + 1, then the mesh draws; 4 bits) +/// Mesh draw kinds in the ring, after the legacy `gpu_profile::Kind` values (4 bits). pub(super) const MESH: u8 = 6; pub(super) const INDIRECT_MESH: u8 = 7; /// a DispatchMesh with a PC pipeline (a translated pass-through one) pub(super) const PC_MESH: u8 = 8; +pub(super) const NATIVE_MESH: u8 = 9; +pub(super) const INDIRECT_NATIVE_MESH: u8 = 10; fn kind_name(kind: u8) -> &'static str { match kind { @@ -59,6 +61,8 @@ fn kind_name(kind: u8) -> &'static str { MESH => "DispatchMesh in two passes", INDIRECT_MESH => "ExecuteIndirect (DispatchMesh) in two passes", PC_MESH => "DispatchMesh", + NATIVE_MESH => "native DispatchMesh", + INDIRECT_NATIVE_MESH => "native ExecuteIndirect (DispatchMesh)", _ => "?", } }