From 9f9069061ff03494c89b8800884ee889cbd28847 Mon Sep 17 00:00:00 2001 From: Personed Date: Wed, 25 Nov 2026 04:23:54 -0300 Subject: [PATCH 1/2] GPU: emulate indirect mesh dispatches --- crates/victory-gpu/src/draw.rs | 188 +++++++++++++++++++++++- crates/victory-gpu/src/mesh_emu.rs | 226 +++++++++++++++++++++++++++-- docs/architecture.md | 7 +- 3 files changed, 405 insertions(+), 16 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 7ef88ff..5d7707b 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2078,6 +2078,7 @@ impl State { p: &HostPipeline, buffers: &crate::mesh_emu::Buffers, base_group: u32, + slot_map_gpu: u64, ) -> bool { let Some(emu) = &p.mesh_emu else { return false; @@ -2104,10 +2105,11 @@ impl State { l.SetComputeRoot32BitConstants(param, 4, constants.as_ptr().cast(), 0); } if let Some(param) = emu.cs_srv_param { - l.SetComputeRootShaderResourceView(param, buffers.dummy_srv_gpu); + l.SetComputeRootShaderResourceView(param, slot_map_gpu); } } list.keep(&buffers.output); + list.keep(&buffers.slot_map); list.keep(&buffers.dummy_srv); true } @@ -2622,7 +2624,7 @@ impl State { let mut base = 0u32; while base < x { let chunk = (x - base).min(group_cap); - if !self.bind_emulated_cs(list, p, buffers, base) { + if !self.bind_emulated_cs(list, p, buffers, base, buffers.dummy_srv_gpu) { self.restore_mesh_emu_state(list); return false; } @@ -3187,6 +3189,20 @@ impl State { }, None => None, }; + if kind == MESH && (mesh_test() == 1 || !mesh_kept(self.pipeline)) { + why("mesh draws are switched off (VICTORY_MESH_TEST=skip)"); + return false; + } + if kind == MESH && p.mesh_emu.is_some() { + return self.execute_indirect_mesh_emulated( + list, + p, + (stride, max), + (&args, arguments, len), + counter.as_ref().map(|(s, at)| (s, *at)), + &why, + ); + } let Some(signature) = matches!(kind, DRAW | INDEXED | DISPATCH | MESH) .then(|| host_signature(kind, stride)) .flatten() @@ -3194,10 +3210,6 @@ impl State { why("no host signature"); return false; }; - if kind == MESH && (mesh_test() == 1 || !mesh_kept(self.pipeline)) { - why("mesh draws are switched off (VICTORY_MESH_TEST=skip)"); - return false; - } // A window of records clamped in one pass (`windows`): for single // records without a count buffer, drawn by shaders that store to no // buffer. Anything else ends the window: it uses the scratch buffer @@ -3344,6 +3356,170 @@ impl State { } true } + fn execute_indirect_mesh_emulated( + &mut self, + list: &HostList, + p: &HostPipeline, + (stride, max): (u32, u32), + (args, arguments, len): (&std::sync::Arc, u64, u64), + counter: Option<(&std::sync::Arc, u64)>, + why: &dyn Fn(&str), + ) -> bool { + if stride < 12 { + why("indirect mesh stride smaller than 12 bytes"); + return false; + } + if max > crate::mesh_emu::MAX_INDIRECT_RECORDS { + why("indirect mesh record count exceeds the emulation safety limit"); + return false; + } + let Some(emu_pipe) = &p.mesh_emu else { + return false; + }; + let Some(buffers) = crate::mesh_emu::buffers() else { + why("no mesh emulation buffers"); + return false; + }; + let group_cap = buffers.group_cap(emu_pipe.emu.group_bytes()); + if group_cap == 0 { + why("mesh emulation buffer smaller than one group"); + return false; + } + let (Some(dispatch_sig), Some(draw_sig)) = (host_signature(2, 12), host_signature(0, 16)) + else { + why("no host indirect command signature"); + return false; + }; + let count_gpu = counter.map(|(s, at)| s.gpu(at)); + if count_gpu.is_some_and(|g| !g.is_multiple_of(4)) { + why("count not 4-byte aligned"); + return false; + } + args.refresh(list, arguments, len); + let count_arg = counter.as_ref().map(|(s, at)| { + s.refresh(list, *at, 4); + (&s.buffer, s.offset(*at)) + }); + // Clamp the title's records before the preparation pass reads them; + // this also applies the shared indirect work budget. + let Some(bounded) = crate::indirect::bound( + list, + (&args.buffer, args.offset(arguments)), + count_arg, + (10, stride, max), + ) else { + why("not bounded (no clamp, or arguments not 4-byte aligned)"); + return false; + }; + list.flush_barriers(); + // SAFETY: `bounded` is the live scratch resource returned by `bound`. + let bounded_gpu = unsafe { bounded.GetGPUVirtualAddress() }; + if !buffers.prepare_indirect( + list, + &bounded, + bounded_gpu, + count_gpu, + stride, + max, + emu_pipe.emu.max_primitives, + group_cap, + ) { + crate::indirect::done(list, &bounded); + why("indirect mesh preparation inputs exceed safe limits"); + return false; + } + list.keep(&buffers.indirect_args); + self.host_pipeline = 0; + self.host_roots = [0; 2]; + + let finish_indirect = |list: &HostList| { + let args_back = transition( + &buffers.indirect_args, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ); + // SAFETY: an open list; emulation buffers return to UAV for the + // next preparation pass. + unsafe { + if max > 1 { + let map_back = transition( + &buffers.slot_map, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ); + list.list.ResourceBarrier(&[args_back, map_back]); + } else { + list.list.ResourceBarrier(&[args_back]); + } + } + }; + + let (base_group, slot_map_gpu) = if max > 1 { + ( + victory_shader::emit::INDIRECT_SLOT_MAP_FLAG, + buffers.slot_map_gpu, + ) + } else { + (0, buffers.dummy_srv_gpu) + }; + if !self.bind_emulated_cs(list, p, buffers, base_group, slot_map_gpu) { + finish_indirect(list); + self.restore_mesh_emu_state(list); + why("prepare emulated mesh CS failed"); + return false; + } + #[cfg(feature = "diagnostics")] + list.note_op(|| { + self.op_text( + format!("indirect mesh-emu max {max} at {arguments:#x}"), + false, + ) + }); + list.flush_barriers(); + // SAFETY: open list with the emulated compute pipeline bound, + // generated indirect arguments, and `output` in UAV state. + unsafe { + list.list + .ExecuteIndirect(&dispatch_sig, 1, &buffers.indirect_args, 0, None, 0); + list.list.ResourceBarrier(&[transition( + &buffers.output, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + } + if !self.bind_emulated_gfx(list, p, buffers) { + // SAFETY: restore `output` for the next dispatch. + unsafe { + list.list.ResourceBarrier(&[transition( + &buffers.output, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + } + finish_indirect(list); + self.restore_mesh_emu_state(list); + why("prepare emulated mesh graphics failed"); + return false; + } + list.flush_barriers(); + self.mesh_scissor(list, true); + // SAFETY: open list with the unpack graphics pipeline bound and + // generated draw arguments at offset 16. + unsafe { + list.list + .ExecuteIndirect(&draw_sig, 1, &buffers.indirect_args, 16, None, 0); + list.list.ResourceBarrier(&[transition( + &buffers.output, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + } + self.mesh_scissor(list, false); + finish_indirect(list); + self.restore_mesh_emu_state(list); + DRAWN.fetch_add(1, Ordering::Relaxed); + true + } } /// The host command signature for one argument of `kind` with records diff --git a/crates/victory-gpu/src/mesh_emu.rs b/crates/victory-gpu/src/mesh_emu.rs index e4cb9a5..fd84286 100644 --- a/crates/victory-gpu/src/mesh_emu.rs +++ b/crates/victory-gpu/src/mesh_emu.rs @@ -1,27 +1,81 @@ -//! Shared GPU memory for compute + vertex mesh emulation. +//! Shared GPU memory and preparation shaders for mesh emulation. //! //! An emulated mesh pipeline first runs the translated mesh shader as //! compute, writing packed primitive indices and attributes into `output`. //! Its generated vertex shader then reads that memory by `SV_VertexID` and -//! feeds the title's pixel shader. The buffer is shared by every emulated -//! mesh dispatch, with direct dispatches split into chunks that fit. +//! feeds the title's pixel shader. Indirect mesh dispatches first run a +//! tiny preparation pass that sums the clamped group counts, builds a slot +//! map across indirect records, and writes host dispatch/draw arguments. use std::sync::OnceLock; -use crate::host::{Host, host, name}; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; +use windows::core::s; +use crate::host::{Host, HostList, host, name, transition}; + +const SLOT_MAP_BYTES: u64 = 65_536 * 4; +const INDIRECT_ARGS_BYTES: u64 = 256; +pub(crate) const MAX_INDIRECT_RECORDS: u32 = 65_535; const OUTPUT_FALLBACK_SIZES: &[u64] = &[128 << 20, 64 << 20, 32 << 20, 16 << 20]; +const PREP_SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" +cbuffer Info : register(b0) { + uint stride; + uint max_records; + uint max_primitives; + uint group_cap; + uint has_count; + uint build_map; +}; +ByteAddressBuffer args : register(t0); +ByteAddressBuffer count_buf : register(t1); +RWByteAddressBuffer out_args : register(u0); +RWByteAddressBuffer slot_map : register(u1); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint n = has_count != 0 ? min(count_buf.Load(0), max_records) : max_records; + uint cap = min(group_cap, 65535u); + uint total = 0; + for (uint r = 0; r < n; ++r) { + if (total >= cap) { + break; + } + uint3 g = args.Load3(r * stride); + uint gx = (g.y != 0 && g.z != 0) ? g.x : 0; + uint left = cap - total; + uint take = min(gx, left); + if (build_map != 0) { + for (uint k = 0; k < take; ++k) { + slot_map.Store((total + k) * 4, k); + } + } + total += take; + } + out_args.Store4(0, uint4(total, 1, 1, 0)); + out_args.Store4(16, uint4(total * max_primitives * 3, 1, 0, 0)); +} +"#; + pub(crate) struct Buffers { pub(crate) output: ID3D12Resource, pub(crate) output_gpu: u64, pub(crate) output_bytes: u64, + pub(crate) slot_map: ID3D12Resource, + pub(crate) slot_map_gpu: u64, + pub(crate) indirect_args: ID3D12Resource, + pub(crate) indirect_args_gpu: u64, pub(crate) dummy_srv: ID3D12Resource, pub(crate) dummy_srv_gpu: u64, + prep_root: ID3D12RootSignature, + prep_pso: ID3D12PipelineState, } -// SAFETY: D3D12 resources are free-threaded. +// SAFETY: D3D12 resources, root signatures, and pipeline states are free-threaded. unsafe impl Send for Buffers {} // SAFETY: as above. unsafe impl Sync for Buffers {} @@ -32,7 +86,7 @@ pub(crate) fn buffers() -> Option<&'static Buffers> { .get_or_init(|| match make() { Some(b) => Some(b), None => { - tracing::warn!("no mesh emulation output buffer; emulated mesh dispatches dropped"); + tracing::warn!("no mesh emulation buffers; emulated mesh dispatches dropped"); None } }) @@ -67,31 +121,109 @@ fn allocate_output(host: &Host) -> Option<(ID3D12Resource, u64)> { None } +fn compile_prep( + device: &ID3D12Device, +) -> windows::core::Result<(ID3D12RootSignature, ID3D12PipelineState)> { + let mut code: Option = None; + let mut errors: Option = None; + // SAFETY: static HLSL source and entry strings live through the call; + // output pointers are ours. + let compiled = unsafe { + D3DCompile( + PREP_SOURCE.as_ptr().cast(), + PREP_SOURCE.len(), + s!("mesh_indirect_prep"), + None, + None, + s!("main"), + s!("cs_5_1"), + 0, + 0, + &mut code, + Some(&mut errors), + ) + }; + if let Err(error) = compiled { + if let Some(errors) = errors { + // SAFETY: the blob owns its bytes. + let text = unsafe { + std::slice::from_raw_parts( + errors.GetBufferPointer().cast::(), + errors.GetBufferSize(), + ) + }; + tracing::info!( + "mesh_indirect_prep: system compiler refused it ({}); trying DXC", + String::from_utf8_lossy(text).trim() + ); + } + return Err(error); + } + let code = code.as_ref().ok_or_else(windows::core::Error::empty)?; + // SAFETY: the blob owns its bytes. + let bytes = unsafe { + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) + }; + // SAFETY: `bytes` is valid compiled shader bytecode with an embedded + // root signature, alive through pipeline creation. + unsafe { + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; + let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + Ok((root, pso)) + } +} + fn make() -> Option { let host = host()?; let (output, output_bytes) = allocate_output(host)?; + let slot_map = + host.default_buffer(SLOT_MAP_BYTES, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)?; + let indirect_args = host.default_buffer( + INDIRECT_ARGS_BYTES, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + )?; let (dummy_srv, dummy_ptr) = host.upload_buffer(256)?; // SAFETY: `dummy_ptr` points to 256 writable bytes of the live upload buffer. unsafe { std::ptr::write_bytes(dummy_ptr, 0, 256) }; + let (prep_root, prep_pso) = compile_prep(&host.device) + .inspect_err(|e| tracing::warn!(error = %e, "mesh_indirect_prep pipeline failed")) + .ok()?; name(&output, || format!("mesh emu output {output_bytes:#x}")); + name(&slot_map, || "mesh emu slot_map".into()); + name(&indirect_args, || "mesh emu indirect_args".into()); name(&dummy_srv, || "mesh emu dummy_srv".into()); - // SAFETY: both are live buffer resources. - let (output_gpu, dummy_srv_gpu) = unsafe { + // SAFETY: all are live buffer resources. + let (output_gpu, slot_map_gpu, indirect_args_gpu, dummy_srv_gpu) = unsafe { ( output.GetGPUVirtualAddress(), + slot_map.GetGPUVirtualAddress(), + indirect_args.GetGPUVirtualAddress(), dummy_srv.GetGPUVirtualAddress(), ) }; tracing::info!( output_mb = output_bytes >> 20, - "mesh shader emulation output buffer ready" + "mesh shader emulation buffers ready" ); Some(Buffers { output, output_gpu, output_bytes, + slot_map, + slot_map_gpu, + indirect_args, + indirect_args_gpu, dummy_srv, dummy_srv_gpu, + prep_root, + prep_pso, }) } @@ -100,4 +232,80 @@ impl Buffers { pub(crate) fn group_cap(&self, group_bytes: u32) -> u32 { (self.output_bytes / u64::from(group_bytes.max(4))).min(65_535) as u32 } + + /// Sums indirect mesh group counts into host dispatch/draw arguments, + /// clamped to one output-buffer chunk. When several records can run, + /// `slot_map` maps each compacted group to its group inside its record. + /// Leaves `indirect_args` in `INDIRECT_ARGUMENT` and `slot_map` readable. + #[allow(clippy::too_many_arguments)] + pub(crate) fn prepare_indirect( + &self, + list: &HostList, + args: &ID3D12Resource, + args_gpu: u64, + count_gpu: Option, + stride: u32, + max_records: u32, + max_primitives: u32, + group_cap: u32, + ) -> bool { + if max_records > MAX_INDIRECT_RECORDS + || group_cap == 0 + || !args_gpu.is_multiple_of(4) + || count_gpu.is_some_and(|gpu| !gpu.is_multiple_of(4)) + { + return false; + } + let l = &list.list; + let build_map = max_records > 1; + let has_count = count_gpu.is_some(); + let count_gpu = count_gpu.unwrap_or(args_gpu); + let args_to_srv = transition( + args, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + ); + let constants = [ + stride, + max_records, + max_primitives, + group_cap, + u32::from(has_count), + u32::from(build_map), + ]; + // SAFETY: an open list; all GPU addresses name live buffers kept for + // the submission. + unsafe { + l.ResourceBarrier(&[args_to_srv]); + l.SetComputeRootSignature(&self.prep_root); + l.SetPipelineState(&self.prep_pso); + l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + l.SetComputeRootShaderResourceView(1, args_gpu); + l.SetComputeRootShaderResourceView(2, count_gpu); + l.SetComputeRootUnorderedAccessView(3, self.indirect_args_gpu); + l.SetComputeRootUnorderedAccessView(4, self.slot_map_gpu); + l.Dispatch(1, 1, 1); + let args_barrier = transition( + &self.indirect_args, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + ); + let source_barrier = transition( + args, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_COMMON, + ); + if build_map { + let map_barrier = transition( + &self.slot_map, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + ); + l.ResourceBarrier(&[args_barrier, map_barrier, source_barrier]); + } else { + l.ResourceBarrier(&[args_barrier, source_barrier]); + } + } + true + } } diff --git a/docs/architecture.md b/docs/architecture.md index 14f29bc..fa2c820 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -97,7 +97,12 @@ the lanes take, from structurisation), and accessed with a non-uniform heap index in one pass. On GPUs with SM 6.6 that lack hardware mesh shaders (or with `VICTORY_MESH_EMULATION=1`), console mesh programs (`HwStage::Ms`) lower to a compute pass (`cs_6_6`) writing packed primitive indices and attributes into a -VRAM buffer read back by a generated unpack vertex shader (`vs_6_6`). +VRAM buffer read back by a generated unpack vertex shader (`vs_6_6`). Indirect +mesh work first runs a preparation pass over the clamped records: it compacts +the requested groups into host dispatch/draw arguments and, for multi-record +calls, a slot map that preserves each record-local mesh group id. +Emulated indirect calls currently accept at most 65,535 records so preparation +work and slot-map writes remain bounded. `victory translate` runs every shader it finds (containers, SGD5 files) through these and lists what they cannot handle yet. From 5a81f26ff6ced41e265cb72c698d4acf5810f284 Mon Sep 17 00:00:00 2001 From: Personed Date: Wed, 25 Nov 2026 04:26:57 -0300 Subject: [PATCH 2/2] GPU: remove unavailable barrier flush calls --- crates/victory-gpu/src/draw.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 5d7707b..e4e84db 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3411,7 +3411,6 @@ impl State { why("not bounded (no clamp, or arguments not 4-byte aligned)"); return false; }; - list.flush_barriers(); // SAFETY: `bounded` is the live scratch resource returned by `bound`. let bounded_gpu = unsafe { bounded.GetGPUVirtualAddress() }; if !buffers.prepare_indirect( @@ -3475,7 +3474,6 @@ impl State { false, ) }); - list.flush_barriers(); // SAFETY: open list with the emulated compute pipeline bound, // generated indirect arguments, and `output` in UAV state. unsafe { @@ -3501,7 +3499,6 @@ impl State { why("prepare emulated mesh graphics failed"); return false; } - list.flush_barriers(); self.mesh_scissor(list, true); // SAFETY: open list with the unpack graphics pipeline bound and // generated draw arguments at offset 16.