From 7e3a621d600495f47f06e143690b54c5378e0c39 Mon Sep 17 00:00:00 2001 From: gdemontalivet Date: Wed, 25 Nov 2026 21:21:48 +0000 Subject: [PATCH] Backport paired mesh/pixel output pruning for over-budget character pipelines Port Texbirds' Marvisak/VIctory#2398 to the macOS runtime. Preserve the runtime compiler options and limit container retention to the experimental path. Co-authored-by: Tex --- crates/victory-gpu/src/pipeline.rs | 133 ++++- crates/victory-gpu/src/pipeline/host.rs | 20 + crates/victory-gpu/src/shader_cache.rs | 14 +- crates/victory-shader/src/emit/container.rs | 53 ++ crates/victory-shader/src/emit/lower.rs | 99 ++-- crates/victory-shader/src/emit/lower/mesh.rs | 94 ++++ crates/victory-shader/src/emit/mod.rs | 536 ++++++++++++++++++- 7 files changed, 862 insertions(+), 87 deletions(-) create mode 100644 crates/victory-shader/src/emit/lower/mesh.rs diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 97d5f227..a37e11bb 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -60,12 +60,11 @@ pub(crate) struct Shader { pub(crate) stage: &'static str, /// The first 8 bytes of its BLAKE3, as logged. pub(crate) hash: String, + #[cfg(windows)] + full_hash: [u8; 32], /// The container's length, as logged once its bytes are gone. size: usize, - /// The container, until `translated` has made its translation (or its - /// refusal) and let it go: a run holds one per distinct shader its title - /// passes, and nothing reads it after. Off Windows nothing translates, - /// so only tests keep it. + /// Released after translation unless an experimental mesh/pixel pair may need it. #[cfg(any(windows, test))] container: Mutex>, #[cfg(windows)] @@ -88,15 +87,21 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc { shaders .get_or_insert_with(HashMap::new) .entry(*full.as_bytes()) - .or_insert_with(|| Arc::new(Shader::new(stage, bytes))) + .or_insert_with(|| Arc::new(Shader::with_hash(stage, bytes, full))) .clone() } impl Shader { fn new(stage: &'static str, bytes: &[u8]) -> Shader { + Self::with_hash(stage, bytes, blake3::hash(bytes)) + } + + fn with_hash(stage: &'static str, bytes: &[u8], digest: blake3::Hash) -> Shader { Shader { stage, - hash: blake3::hash(bytes).to_hex()[..16].to_owned(), + hash: digest.to_hex()[..16].to_owned(), + #[cfg(windows)] + full_hash: *digest.as_bytes(), size: bytes.len(), #[cfg(any(windows, test))] container: Mutex::new(bytes.to_vec()), @@ -126,7 +131,15 @@ impl Shader { let done = translate(&container); // After the translation, not before: if it panics, the // bytes are still there for the next try. - *container = Vec::new(); + let keep = link_mesh_outputs() && done.0.as_ref().is_ok_and(|t| { + self.stage == "pixel" + || (self.stage == "mesh" + && victory_shader::emit::mesh_output_bytes(&t.host.dxil) + .is_some_and(|n| n > victory_shader::emit::MESH_OUTPUT_LIMIT)) + }); + if !keep { + *container = Vec::new(); + } done }; let ms = started.elapsed().as_millis() as u64; @@ -213,6 +226,112 @@ fn with_resources( Ok(Translated { host, used }) } +#[cfg(windows)] +fn link_mesh_outputs() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| crate::switch::on("VICTORY_LINK_MESH_OUTPUTS")) +} + +#[cfg(windows)] +struct LinkedPair { + mesh: Arc, + pixel: Option>, +} + +#[cfg(windows)] +type LinkedKey = ([u8; 32], Option<[u8; 32]>); + +#[cfg(windows)] +impl Shader { + fn with_translation(&self, translated: Translated) -> Arc { + let cell = OnceLock::new(); + let _ = cell.set(Some(translated)); + Arc::new(Shader { + stage: self.stage, + hash: self.hash.clone(), + full_hash: self.full_hash, + size: self.size, + container: Mutex::new(Vec::new()), + translated: cell, + }) + } +} + +/// Re-translates a mesh shader together with its paired pixel shader (if any) +/// so arbitrary mesh outputs unread by the pixel shader are pruned under +/// D3D12's 32 KiB mesh output limit (`victory_shader::emit::MESH_OUTPUT_LIMIT`). +#[cfg(windows)] +pub(crate) fn translate_linked( + ms: &Shader, + ps: Option<&Shader>, +) -> Option<(Arc, Option>)> { + static LINKED: Mutex>>> = Mutex::new(None); + let key = (ms.full_hash, ps.map(|p| p.full_hash)); + if let Some(hit) = LINKED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .and_then(|m| m.get(&key)) + { + return hit + .as_ref() + .map(|pair| (pair.mesh.clone(), pair.pixel.clone())); + } + let mesh_bytes = ms.container.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let pixel_bytes = ps.map(|p| p.container.lock().unwrap_or_else(|e| e.into_inner()).clone()); + let options = crate::shader_cache::runtime_options(); + let result = match victory_shader::emit::translate_linked( + &mesh_bytes, + pixel_bytes.as_deref(), + options, + ) { + Ok((ms_host, ps_host)) => { + let ms_bytes = victory_shader::emit::mesh_output_bytes(&ms_host.dxil); + let ms_used = ms.translated()?.used.clone(); + let mesh = ms.with_translation( + Translated { + host: ms_host, + used: ms_used, + }, + ); + let pixel = match (ps, ps_host) { + (Some(p), Some(host)) => Some(p.with_translation( + Translated { + host, + used: p.translated()?.used.clone(), + }, + )), + _ => None, + }; + tracing::info!( + mesh = %ms.hash, + pixel = ps.map_or("none", |p| p.hash.as_str()), + bytes = ms_bytes, + "mesh and pixel linked under 32 KiB output budget" + ); + Some(LinkedPair { mesh, pixel }) + } + Err(e) => { + tracing::warn!( + mesh = %ms.hash, + pixel = ps.map_or("none", |p| p.hash.as_str()), + error = %e, + "linked mesh/pixel translation failed; using standalone translation" + ); + None + } + }; + let out = result + .as_ref() + .map(|pair| (pair.mesh.clone(), pair.pixel.clone())); + LINKED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get_or_insert_with(HashMap::new) + .insert(key, result); + out +} + #[repr(C)] struct Pipeline { object: Object, diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index bbb2d9ab..68548b22 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -355,6 +355,26 @@ impl HostPipeline { for (s, _) in &stages { s.translated()?; } + // Mesh shaders whose standalone output footprint exceeds D3D12's 32 KiB + // limit are re-translated together with their paired pixel shader, + // pruning outputs the pixel shader never reads. + let linked = mesh.filter(|_| super::link_mesh_outputs()).and_then(|ms| { + let bytes = victory_shader::emit::mesh_output_bytes(&ms.translated()?.host.dxil)?; + if bytes <= victory_shader::emit::MESH_OUTPUT_LIMIT { + return None; + } + super::translate_linked(ms, find("pixel").map(Arc::as_ref)) + }); + let stages: Vec<(&Arc, D3D12_SHADER_VISIBILITY)> = match &linked { + Some((ms, ps)) => { + let mut v = vec![(ms, D3D12_SHADER_VISIBILITY_MESH)]; + if let Some(ps) = ps { + v.push((ps, D3D12_SHADER_VISIBILITY_PIXEL)); + } + v + } + None => stages, + }; let host = host()?; // `SFI0`: 64-bit atomics on typed resources and on heap resources. let atomics64 = stages.iter().any(|(s, _)| { diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 1db6ce6a..c82c3caf 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -139,18 +139,22 @@ fn options_build(locks: bool, bias: bool) -> &'static [u8; 32] { }) } -/// The translation of a console shader container, from the cache when -/// there is one, and whether it came from there. -pub fn host_shader(container: &[u8]) -> (Result, bool) { +pub(crate) fn runtime_options() -> victory_shader::emit::Options { // Writes through views mark their pages: copy-backs compare only those // (`crate::shadow::copy_back_marks`). // Under Wine (D3DMetal), 64-bit image atomics run under locks: its own // leave the texels untouched (`emit`, "Atomic locks"). - let options = victory_shader::emit::Options { + victory_shader::emit::Options { view_marks: true, atomic_locks: atomic_locks(), bias_as_gradients: bias_as_gradients(), - }; + } +} + +/// The translation of a console shader container, from the cache when +/// there is one, and whether it came from there. +pub fn host_shader(container: &[u8]) -> (Result, bool) { + let options = runtime_options(); let translate = |c: &[u8]| victory_shader::emit::translate_with(c, options).map_err(|e| e.to_string()); let build = if options.atomic_locks || options.bias_as_gradients { diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index 3f0de1ac..d884fac6 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -3,6 +3,30 @@ //! program (`DXIL`), laid out as validator version 1.6 lays them out, plus //! the container hash that D3D12 checks. +/// D3D12 / DXIL maximum combined byte size of a mesh shader's vertex and +/// primitive outputs per thread group (`kMaxMSOutputTotalBytes`). +pub const MESH_OUTPUT_LIMIT: u32 = 32 * 1024; + +/// Combined byte size of a mesh shader's vertex and primitive outputs as DXIL +/// validates it: 4 bytes per declared component of every allocated element, +/// times the vertex and primitive maxima each rounded up to a multiple of 32. +pub(crate) fn mesh_output_bytes( + outputs: &[SigElement], + prims: &[SigElement], + max_vertices: u32, + max_primitives: u32, +) -> u32 { + let stride = |els: &[SigElement]| -> u32 { + els.iter() + .filter(|e| e.row.is_some()) + .map(|e| u32::from(e.cols) * 4) + .sum() + }; + stride(outputs) + .saturating_mul(max_vertices.next_multiple_of(32)) + .saturating_add(stride(prims).saturating_mul(max_primitives.next_multiple_of(32))) +} + /// One signature element: one row (D3D12 links stages by semantic). #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct SigElement { @@ -512,4 +536,33 @@ mod tests { assert_ne!(a, b); assert_eq!(a, shader_hash(b"program a")); } + + #[test] + fn mesh_output_bytes_matches_dxil_budget() { + let el = |row: u32, cols: u8| SigElement { + name: "TEXCOORD".into(), + index: row, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col: 0, + cols, + usage: 0, + half: false, + }; + // 16 float4 rows = 64 components; at 128 vertices that is exactly 32 KiB. + let v16: Vec = (0..16).map(|r| el(r, 4)).collect(); + assert_eq!(mesh_output_bytes(&v16, &[], 128, 128), MESH_OUTPUT_LIMIT); + // One more scalar pushes past 32 KiB. + let mut v17 = v16.clone(); + v17.push(el(16, 1)); + assert_eq!(mesh_output_bytes(&v17, &[], 128, 128), 33_280); + // Maxima round up to multiples of 32, and primitive outputs add on top. + let prim = [el(0, 2)]; + assert_eq!( + mesh_output_bytes(&v16[..1], &prim, 33, 1), + 4 * 4 * 64 + 2 * 4 * 32 + ); + } } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 4c9b4967..9066e998 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -21,6 +21,9 @@ use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source, USER use crate::structure::{Atom, Bool, LaneExit, Map, Set, Structured}; mod bvh; +mod mesh; +pub(crate) use mesh::KeptOutputs; +use mesh::prune_signature; type Why = &'static str; @@ -96,9 +99,16 @@ enum Stop { } pub(crate) fn lower(parts: &Parts) -> Result { + lower_pruned(parts, None) +} + +pub(crate) fn lower_pruned( + parts: &Parts, + keep: Option<&KeptOutputs>, +) -> Result { let mut bad = HashMap::new(); loop { - match Lower::new(parts, &bad).run() { + match Lower::new(parts, &bad, keep).run() { Ok(l) => return Ok(l), Err(Stop::Retry(v, why)) => { if bad.insert(v, why).is_some() { @@ -533,7 +543,7 @@ fn smem_dwords(name: &str) -> Option { } impl<'a> Lower<'a> { - fn new(x: &'a Parts<'a>, bad: &'a HashMap) -> Self { + fn new(x: &'a Parts<'a>, bad: &'a HashMap, keep: Option<&KeptOutputs>) -> Self { let p = x.p; let mut phi_at = Map::default(); for (b, block) in p.blocks.iter().enumerate() { @@ -544,6 +554,13 @@ impl<'a> Lower<'a> { let mut s = Shader::new(x.native.stage == HwStage::Ps); s.inputs = x.inputs.clone(); s.outputs = x.outputs.clone(); + if let Some(keep) = keep { + if x.native.stage == HwStage::Ps { + prune_signature(&mut s.inputs, keep); + } else if x.native.stage == HwStage::Ms { + prune_signature(&mut s.outputs, keep); + } + } let insts = || p.blocks.iter().flat_map(|b| &b.insts); let writes_uavs = insts().any(|i| { matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. }) @@ -599,11 +616,20 @@ impl<'a> Lower<'a> { let mut no_barrier = Set::default(); if let StageIo::Ms(ms) = &x.native.io { s.prims = x.prims.clone(); + if let Some(keep) = keep { prune_signature(&mut s.prims, keep); } s.threads = Some([ms.threads, 1, 1]); s.lds_dwords = ms.lds_bytes.div_ceil(4); + let mut max_vertices = ms.max_vertices; + let mut max_primitives = ms.max_primitives; + if super::container::mesh_output_bytes(&s.outputs, &s.prims, max_vertices, max_primitives) + > super::container::MESH_OUTPUT_LIMIT + { + max_vertices = max_vertices.min(ms.threads); + max_primitives = max_primitives.min(ms.threads); + } s.mesh = Some(super::shader::Mesh { - max_vertices: ms.max_vertices, - max_primitives: ms.max_primitives, + max_vertices, + max_primitives, topology: ms.topology, }); // Barriers order the lanes' LDS accesses; the console's @@ -2871,65 +2897,6 @@ impl<'a> Lower<'a> { }) } - /// Mesh: the counts and the primitives no lane exports. The console's - /// counts come from one lane's allocation request, which DXIL cannot - /// express (one call, dominating every output write). - // shortcut: the counts are the declared maxima and each lane first culls - // its primitive (all indices 0, zero area), so primitives past the - // program's count are culled and vertices past it unused; this costs - // the host the unused vertex and primitive slots. Pass the program's own - // counts if that shows in frame time. - fn mesh_prologue(&mut self, mesh: super::shader::Mesh) -> Result<(), Why> { - let threads = self.s.threads.expect("mesh")[0]; - if mesh.topology != 2 { - return Err("a mesh shader not drawing triangles"); - } - if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 { - return Err("a mesh shader beyond the host's limits"); - } - let e = self.s.entry; - let void = self.s.t.void; - let (v, p) = ( - self.s.m.i32(mesh.max_vertices), - self.s.m.i32(mesh.max_primitives), - ); - self.s - .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]); - let flat = self.mesh_thread(); - let guard = (threads > mesh.max_primitives).then(|| self.s.m.cmp(e, pred::IULT, flat, p)); - let at = self.begin_guarded(guard); - let z = self.s.m.i32(0); - self.s.op( - self.cur, - "emitIndices", - Attr::NoUnwind, - void, - 169, - &[flat, z, z, z], - ); - self.end_guarded(at, &[]); - Ok(()) - } - - /// Mesh: the thread's index in the group, which is its vertex and - /// primitive index. - fn mesh_thread(&mut self) -> V { - if let Some(f) = self.flat { - return f; - } - let e = self.s.entry; - let f = self.s.op( - e, - "flattenedThreadIdInGroup.i32", - Attr::ReadNone, - self.s.t.i32, - 96, - &[], - ); - self.flat = Some(f); - f - } - /// The console wave size. fn wave(&self) -> u32 { if self.x.native.wave64 { 64 } else { 32 } @@ -8016,7 +7983,7 @@ impl<'a> Lower<'a> { // per dword (`packed_half`); the host's are 32-bit floats. let half = |l: &mut Self, h: u8| -> Result, Why> { let src = if pack2 { - packed_half(&l.s.inputs, attribute.row, h) + packed_half(&l.x.inputs, attribute.row, h) } else { h.is_multiple_of(2).then_some((attribute.row, h / 2)) }; @@ -9866,7 +9833,7 @@ impl<'a> Lower<'a> { for high in [false, true] { let h = 2 * ch + u8::from(high); let src = if pack2 { - packed_half(outputs, row, h) + packed_half(&self.x.outputs, row, h) } else { (!high).then_some((row, ch)) }; @@ -10056,7 +10023,7 @@ impl<'a> Lower<'a> { .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r) }; let free: std::collections::BTreeSet = self - .s + .x .outputs .iter() .filter(|o| o.kind == 0) diff --git a/crates/victory-shader/src/emit/lower/mesh.rs b/crates/victory-shader/src/emit/lower/mesh.rs new file mode 100644 index 00000000..b758f37f --- /dev/null +++ b/crates/victory-shader/src/emit/lower/mesh.rs @@ -0,0 +1,94 @@ +//! Mesh shader output signatures, counts and lane indices. + +use super::{Attr, HashMap, Lower, SigElement, V, Why, pred}; +use crate::emit::shader::Mesh; + +/// Semantic key `(UPPERCASE_NAME, index)` -> 4-bit absolute channel mask of +/// arbitrary (`kind == 0`) inputs read by the paired pixel shader. +pub(crate) type KeptOutputs = HashMap<(String, u32), u8>; + +/// Keeps only arbitrary (`kind == 0`) signature elements whose semantic has at +/// least one channel read in `keep`, trimming unread leading and trailing +/// channels. System values (`kind != 0`) stay untouched. +pub(super) fn prune_signature(elements: &mut Vec, keep: &KeptOutputs) { + elements.retain_mut(|e| { + if e.kind != 0 { + return true; + } + if e.row.is_none() { + return false; + } + let key = (e.name.to_ascii_uppercase(), e.index); + let used = keep.get(&key).copied().unwrap_or(0); + let rel = (used >> e.col) & ((1u8 << e.cols) - 1); + if rel == 0 { + return false; + } + let first = rel.trailing_zeros() as u8; + let last = 7 - rel.leading_zeros() as u8; + e.col += first; + e.cols = last - first + 1; + true + }); +} + +impl Lower<'_> { + /// Mesh: the counts and the primitives no lane exports. The console's + /// counts come from one lane's allocation request, which DXIL cannot + /// express (one call, dominating every output write). + // shortcut: the counts are the declared maxima and each lane first culls + // its primitive (all indices 0, zero area), so primitives past the + // program's count are culled and vertices past it unused; this costs + // the host the unused vertex and primitive slots. Pass the program's own + // counts if that shows in frame time. + pub(super) fn mesh_prologue(&mut self, mesh: Mesh) -> Result<(), Why> { + let threads = self.s.threads.expect("mesh")[0]; + if mesh.topology != 2 { + return Err("a mesh shader not drawing triangles"); + } + if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 { + return Err("a mesh shader beyond the host's limits"); + } + let e = self.s.entry; + let void = self.s.t.void; + let (v, p) = ( + self.s.m.i32(mesh.max_vertices), + self.s.m.i32(mesh.max_primitives), + ); + self.s + .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]); + let flat = self.mesh_thread(); + let guard = (threads > mesh.max_primitives).then(|| self.s.m.cmp(e, pred::IULT, flat, p)); + let at = self.begin_guarded(guard); + let z = self.s.m.i32(0); + self.s.op( + self.cur, + "emitIndices", + Attr::NoUnwind, + void, + 169, + &[flat, z, z, z], + ); + self.end_guarded(at, &[]); + Ok(()) + } + + /// Mesh: the thread's index in the group, which is its vertex and + /// primitive index. + pub(super) fn mesh_thread(&mut self) -> V { + if let Some(f) = self.flat { + return f; + } + let e = self.s.entry; + let f = self.s.op( + e, + "flattenedThreadIdInGroup.i32", + Attr::ReadNone, + self.s.t.i32, + 96, + &[], + ); + self.flat = Some(f); + f + } +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index a4b6dfb0..6761abe1 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -240,6 +240,7 @@ use crate::dxbc::{Container, FourCC}; use crate::native::{HwStage, NativeProgram, RootType}; use crate::{ShaderError, io, ir, resource, structure}; +pub use container::MESH_OUTPUT_LIMIT; pub use sampler::StaticSampler; pub use shader::{ HEAP_SAMPLERS, HEAP_VIEWS, MEMORY_SPACE, NULL_BUFFER_VIEW, ROOT_CBV_SPACE, SAMPLER_SPACE, @@ -392,14 +393,49 @@ pub struct Options { pub bias_as_gradients: bool, } -/// Translates the vertex, pixel, compute or mesh program of a console -/// shader container, without write marks. -pub fn translate(container: &[u8]) -> Result { - translate_with(container, Options::default()) +/// Combined vertex + primitive output byte size of an emitted mesh shader +/// container (`None` for non-mesh containers or malformed headers). +pub fn mesh_output_bytes(dxil: &[u8]) -> Option { + let c = Container::parse(dxil).ok()?; + let psv = c.part(FourCC::PSV0)?.data; + // RuntimeInfo v2 header: 4-byte size prefix (>= 48), then 48-byte info + // block with stage at +24 (13 = mesh), max_vertices at +12, + // max_primitives at +14. + if crate::dxbc::u32_at(psv, 0).ok()? < 48 || *psv.get(4 + 24)? != 13 { + return None; + } + let u16_at = |off: usize| -> Option { + let b: [u8; 2] = psv.get(off..off + 2)?.try_into().ok()?; + Some(u32::from(u16::from_le_bytes(b))) + }; + let max_vertices = u16_at(4 + 12)?; + let max_primitives = u16_at(4 + 14)?; + let outputs = c + .part(FourCC::OSG1) + .and_then(|p| signature(p.data).ok()) + .unwrap_or_default(); + let prims = c + .part(FourCC::PSG1) + .and_then(|p| signature(p.data).ok()) + .unwrap_or_default(); + Some(container::mesh_output_bytes( + &outputs, + &prims, + max_vertices, + max_primitives, + )) } -/// [`translate`] made as `options` say. -pub fn translate_with(container: &[u8], options: Options) -> Result { +struct Prepared<'a> { + c: Container<'a>, + native: NativeProgram, + p: ir::Program, + st: structure::Structured, + io: io::Io, + res: resource::Resources, +} + +fn prepare(container: &[u8]) -> Result, ShaderError> { let c = Container::parse(container)?; let dxil = c .part(FourCC::DXIL) @@ -423,7 +459,133 @@ pub fn translate_with(container: &[u8], options: Options) -> Result 4-bit absolute channel mask. +fn pixel_input_reads(dxil: &[u8]) -> Result { + let c = Container::parse(dxil)?; + let Some(part) = c.part(FourCC::ISG1) else { + return Ok(lower::KeptOutputs::new()); + }; + let mut reads = lower::KeptOutputs::new(); + let count = crate::dxbc::u32_at(part.data, 0)? as usize; + let base = crate::dxbc::u32_at(part.data, 4)? as usize; + for i in 0..count { + let at = base + 32 * i; + // System value at +12: 0 is arbitrary (non-SV). + if crate::dxbc::u32_at(part.data, at + 12)? != 0 { + continue; + } + let name_at = crate::dxbc::u32_at(part.data, at + 4)? as usize; + let name = part + .data + .get(name_at..) + .and_then(|s| s.split(|&b| b == 0).next()) + .ok_or(ShaderError::Malformed("signature name out of bounds"))?; + let index = crate::dxbc::u32_at(part.data, at + 8)?; + let rw = *part + .data + .get(at + 25) + .ok_or(ShaderError::Malformed("truncated"))?; + if rw != 0 { + let key = (String::from_utf8_lossy(name).to_ascii_uppercase(), index); + *reads.entry(key).or_insert(0) |= rw; + } + } + Ok(reads) +} + +/// Translates the vertex, pixel, compute or mesh program of a console +/// shader container, without write marks. +pub fn translate(container: &[u8]) -> Result { + translate_with(container, Options::default()) +} + +/// [`translate`] made as `options` say. +pub fn translate_with(container: &[u8], options: Options) -> Result { + let prep = prepare(container)?; + emit_pruned( + &EmitInput { + c: &prep.c, + native: &prep.native, + p: &prep.p, + st: &prep.st, + io: &prep.io, + res: &prep.res, + }, + options, + None, + ) +} + +/// Re-translates a mesh shader together with its paired pixel shader (or +/// `None` for depth-only draws), pruning arbitrary mesh outputs the pixel +/// shader never reads so the mesh shader fits within [`MESH_OUTPUT_LIMIT`] +/// (32 KiB) while keeping both stages' signatures linked for D3D12. +pub fn translate_linked( + mesh: &[u8], + pixel: Option<&[u8]>, + options: Options, +) -> Result<(HostShader, Option), ShaderError> { + let mp = prepare(mesh)?; + let ms_in = EmitInput { + c: &mp.c, + native: &mp.native, + p: &mp.p, + st: &mp.st, + io: &mp.io, + res: &mp.res, + }; + let emit_mesh = |reads: &lower::KeptOutputs| { + let linked = emit_pruned(&ms_in, options, Some(reads))?; + let bytes = mesh_output_bytes(&linked.dxil) + .ok_or(ShaderError::Malformed("linked shader has no mesh output declaration"))?; + if bytes > MESH_OUTPUT_LIMIT { + return Err(ShaderError::Unsupported { + offset: 0, + what: "mesh outputs required by the next stage exceed 32 KiB", + }); + } + Ok(linked) + }; + let Some(ps_bytes) = pixel else { + return Ok((emit_mesh(&lower::KeptOutputs::new())?, None)); + }; + let pp = prepare(ps_bytes)?; + if pp.native.stage != HwStage::Ps { + return Err(ShaderError::Malformed("mesh output consumer is not a pixel shader")); + } + let ps_in = EmitInput { + c: &pp.c, + native: &pp.native, + p: &pp.p, + st: &pp.st, + io: &pp.io, + res: &pp.res, + }; + let full_ps = emit_pruned(&ps_in, options, None)?; + let reads = pixel_input_reads(&full_ps.dxil)?; + let linked_ms = emit_mesh(&reads)?; + let linked_ps = emit_pruned(&ps_in, options, Some(&reads))?; + Ok((linked_ms, Some(linked_ps))) +} + +struct EmitInput<'a> { + c: &'a Container<'a>, + native: &'a NativeProgram, + p: &'a ir::Program, + st: &'a structure::Structured, + io: &'a io::Io, + res: &'a resource::Resources, } /// Emits a program whose earlier stages already ran, without write marks. @@ -448,6 +610,33 @@ pub fn emit_with( res: &resource::Resources, options: Options, ) -> Result { + emit_pruned( + &EmitInput { + c, + native, + p, + st, + io, + res, + }, + options, + None, + ) +} + +fn emit_pruned( + input: &EmitInput<'_>, + options: Options, + keep: Option<&lower::KeptOutputs>, +) -> Result { + let EmitInput { + c, + native, + p, + st, + io, + res, + } = *input; let sig = |fourcc| -> Result, ShaderError> { match c.part(fourcc) { Some(part) => signature(part.data), @@ -517,14 +706,14 @@ pub fn emit_with( atomic_locks: options.atomic_locks, bias_as_gradients: options.bias_as_gradients, }; - let l = match lower::lower(&parts(st, res)) { + let l = match lower::lower_pruned(&parts(st, res), keep) { // Discarded lanes kept on as helpers can read what no surviving // lane does (a register only killed lanes skipped writing); such a // program kills them as the console does (`structure::killing`). Err(_) if !st.discards.is_empty() => { let st = structure::killing(p)?; let res = resource::track(p, &native.layout, native.stage, Some(&st))?; - lower::lower(&parts(&st, &res))? + lower::lower_pruned(&parts(&st, &res), keep)? } l => l?, }; @@ -1820,4 +2009,333 @@ mod tests { // Translated or refused with a reason; it must not panic. let _ = super::emit(&c, &native, &p, &st, &io, &res); } + + /// Builds a synthetic mesh shader declaring `SV_Position` plus 16 `float4` + /// `TEXCOORD` outputs (68 components total). At 128 vertices that is + /// 34,816 bytes (> 32 KiB DXIL budget). + fn wide_mesh_parts( + threads: u32, + max_vertices: u32, + max_primitives: u32, + ) -> (Vec, NativeProgram) { + let mut words = vec![ + 0xD765_0001u32, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0x0001_00C1, + 0x3604_0281, // v_and_b32 v2, 1, v1 + 0x3606_0282, // v_and_b32 v3, 2, v1 + 0x7E04_0D02, // v_cvt_f32_u32 v2, v2 + 0x7E06_0D03, // v_cvt_f32_u32 v3, v3 + 0x1008_04F6, // v_mul_f32 v4, 4.0, v2 + 0x0608_08F3, // v_add_f32 v4, -1.0, v4 + 0x100A_06F4, // v_mul_f32 v5, 2.0, v3 + 0x060A_0AF3, // v_add_f32 v5, -1.0, v5 + 0x7E0C_02F0, // v_mov_b32 v6, 0.5 + 0x7E0E_02F2, // v_mov_b32 v7, 1.0 + 0x7E10_02FF, // v_mov_b32 v8, 0.25 + 0.25f32.to_bits(), + 0x7E12_02FF, // v_mov_b32 v9, TRIANGLE + TRIANGLE, + 0x7E14_0280, // v_mov_b32 v10, 0.0 + ]; + // param0 = (1.0, 0.5, 0.0, 0.0) + words.extend([0xF800_000F | (32 << 4), 0x0A0A_0607]); + // param1..14 = (0.0, 0.0, 0.0, 0.0) + for k in 1..15u32 { + words.extend([0xF800_000F | ((32 + k) << 4), 0x0A0A_0A0A]); + } + // param15 = (0.0, 0.0, 0.25, 1.0) + words.extend([0xF800_000F | ((32 + 15) << 4), 0x0708_0A0A]); + words.extend([ + 0xF800_0941, // exp prim v9, off, off, off done + 0x0000_0009, + 0xF800_08CF, // exp pos0 v4, v5, v6, v7 done + 0x0706_0504, + 0xBF81_0000, // s_endpgm + ]); + let outputs: Vec = (0..16u8) + .map(|k| crate::native::VsOutput { + usage: crate::native::Usage::Generic, + row: k + 1, + param: k, + fp16: false, + pack2: false, + }) + .collect(); + let native = NativeProgram { + stage: HwStage::Ms, + wave64: false, + vgprs: 12, + layout: vec![], + used: vec![], + io: StageIo::Ms(crate::native::MeshIo { + outputs, + clip_cntl: 0, + threads, + max_vertices, + max_primitives, + topology: 2, + lds_bytes: 0, + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let mut sig = vec![SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }]; + for k in 0..16u32 { + sig.push(SigElement { + name: "TEXCOORD".into(), + index: k, + kind: 0, + comp: 9, + interp: 0, + row: Some(k + 1), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }); + } + let osg1 = container::signature(&sig, false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + (bytes, native) + } + + /// A 64-lane mesh shader whose declared `max_vertices`/`max_primitives` + /// (128) would push its 68 output components past 32 KiB tightens those + /// maxima down to its thread count (64), fitting in 17,408 bytes and + /// passing DXIL validation standalone. + #[test] + fn mesh_exceeding_32k_tightens_counts_to_group_threads() { + let (bytes, native) = wide_mesh_parts(64, 128, 128); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let ms = emit(&c, &native, &p, &st, &io, &res).unwrap(); + assert_eq!(mesh_output_bytes(&ms.dxil), Some(68 * 4 * 64)); + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut ms.dxil.clone()).unwrap(); + } + } + + /// A 128-lane mesh shader with 68 output components (34,816 B > 32 KiB + /// even at one vertex per lane) linked with its pixel shader: pruning + /// unread attributes (`TEXCOORD1..14`) and unread leading/trailing channels + /// (`TEXCOORD0.zw`, `TEXCOORD15.xy`) brings both stages into matching + /// signatures under 32 KiB, passes DXIL validation, and draws the exact + /// pixel output on hardware and WARP. + #[test] + fn linked_mesh_and_pixel_prune_unused_outputs_under_32k_and_draw() { + let (ms_bytes, ms_native) = wide_mesh_parts(128, 128, 128); + let mc = Container::parse(&ms_bytes).unwrap(); + let mp = ir::build(&ms_native.patched_code(), ms_native.wave64, ms_native.vgprs).unwrap(); + let mst = structure::structure(&mp).unwrap(); + let mres = resource::track(&mp, &ms_native.layout, ms_native.stage, Some(&mst)).unwrap(); + let mio = io::raise(&mp, &ms_native).unwrap(); + let ms_in = EmitInput { + c: &mc, + native: &ms_native, + p: &mp, + st: &mst, + io: &mio, + res: &mres, + }; + // Standalone emission stays over 32 KiB (68 * 4 * 128 = 34,816 B). + let standalone = emit_pruned(&ms_in, Options::default(), None).unwrap(); + assert_eq!(mesh_output_bytes(&standalone.dxil), Some(34_816)); + assert!(mesh_output_bytes(&standalone.dxil).unwrap() > MESH_OUTPUT_LIMIT); + + // Depth-only linking (no pixel shader) drops all arbitrary outputs. + let empty = lower::KeptOutputs::new(); + let depth_ms = emit_pruned(&ms_in, Options::default(), Some(&empty)).unwrap(); + assert_eq!(mesh_output_bytes(&depth_ms.dxil), Some(4 * 4 * 128)); + + // Paired pixel shader declaring the same 17 rows, reading only + // TEXCOORD0.xy and TEXCOORD15.zw. + let p1 = |vdst: u32, attr: u32, ch: u32| { + 0xC800_0000u32 | (vdst << 18) | (attr << 10) | (ch << 8) + }; + let p2 = |vdst: u32, attr: u32, ch: u32| { + 0xC801_0001u32 | (vdst << 18) | (attr << 10) | (ch << 8) + }; + let ps_words = [ + p1(2, 0, 0), + p2(2, 0, 0), // v2 = TEXCOORD0.x (1.0) + p1(3, 0, 1), + p2(3, 0, 1), // v3 = TEXCOORD0.y (0.5) + p1(4, 15, 2), + p2(4, 15, 2), // v4 = TEXCOORD15.z (0.25) + p1(5, 15, 3), + p2(5, 15, 3), // v5 = TEXCOORD15.w (1.0) + 0xF800_180F, + 0x0504_0302, // exp mrt0, v2, v3, v4, v5 done vm + 0xBF81_0000, // s_endpgm + ]; + let ps_inputs: Vec = (0..16u8) + .map(|k| crate::native::PsInput { + usage: crate::native::Usage::Generic, + row: k + 1, + mask: 0xF, + attr: k, + flat: false, + fp16: false, + pack2: false, + row2: 0, + }) + .collect(); + let ps_native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 8, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: ps_inputs, + input_addr: 1 << 1, + db_shader_control: 0, + patches: vec![], + }, + code: ps_words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let mut ps_sig = vec![SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0, + half: false, + }]; + for k in 0..16u32 { + ps_sig.push(SigElement { + name: "TEXCOORD".into(), + index: k, + kind: 0, + comp: 9, + interp: 0, + row: Some(k + 1), + col: 0, + cols: 4, + usage: 0, + half: false, + }); + } + let isg1 = container::signature(&ps_sig, true); + let osg1 = rows(&[("SV_Target", 16, false)], false); + let ps_bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]); + let pc = Container::parse(&ps_bytes).unwrap(); + let pp = ir::build(&ps_native.patched_code(), ps_native.wave64, ps_native.vgprs).unwrap(); + let pst = structure::structure(&pp).unwrap(); + let pres = resource::track(&pp, &ps_native.layout, ps_native.stage, Some(&pst)).unwrap(); + let pio = io::raise(&pp, &ps_native).unwrap(); + let ps_in = EmitInput { + c: &pc, + native: &ps_native, + p: &pp, + st: &pst, + io: &pio, + res: &pres, + }; + let full_ps = emit_pruned(&ps_in, Options::default(), None).unwrap(); + let reads = pixel_input_reads(&full_ps.dxil).unwrap(); + assert_eq!(reads.len(), 2); + assert_eq!(reads.get(&("TEXCOORD".into(), 0)), Some(&0b0011)); + assert_eq!(reads.get(&("TEXCOORD".into(), 15)), Some(&0b1100)); + + let linked_ms = emit_pruned(&ms_in, Options::default(), Some(&reads)).unwrap(); + let linked_ps = emit_pruned(&ps_in, Options::default(), Some(&reads)).unwrap(); + // SV_Position (4) + TEXCOORD0.xy (2) + TEXCOORD15.zw (2) = 8 components. + assert_eq!(mesh_output_bytes(&linked_ms.dxil), Some(8 * 4 * 128)); + assert!(!linked_ps.dxil.is_empty()); + + #[cfg(windows)] + { + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut depth_ms.dxil.clone()).unwrap(); + v.validate(&mut linked_ms.dxil.clone()).unwrap(); + v.validate(&mut linked_ps.dxil.clone()).unwrap(); + } + use super::host::{Draw, Host, Root}; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_FEATURE_D3D12_OPTIONS7, D3D12_FEATURE_DATA_D3D12_OPTIONS7, + D3D12_MESH_SHADER_TIER_NOT_SUPPORTED, D3D12_SHADER_VISIBILITY_MESH, + D3D12_SHADER_VISIBILITY_PIXEL, + }; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + // SAFETY: the query writes the structure of the given size. + let queried = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS7, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + }; + if queried.is_err() + || options.MeshShaderTier == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED + { + eprintln!("no mesh shaders on the {label} device; skipped"); + continue; + } + let root = host + .root_signature_for(&[ + (&linked_ms, D3D12_SHADER_VISIBILITY_MESH), + (&linked_ps, D3D12_SHADER_VISIBILITY_PIXEL), + ]) + .unwrap(); + let pso = host + .mesh_pipeline_with(&root, &linked_ms.dxil, &linked_ps.dxil) + .unwrap_or_else(|e| panic!("{label}: mesh pipeline: {e}")); + let texels = host + .draw( + &root, + &pso, + &Draw { + roots: vec![ + (0, Root::Constants(vec![0])), + (1, Root::Constants(vec![0])), + ], + textures: &[], + samplers: &[], + vertices: &[], + stride: 0, + size: (16, 16), + mesh_groups: 1, + }, + ) + .unwrap_or_else(|e| panic!("{label}: draw: {e}")); + assert!( + texels.iter().all(|t| *t == [1.0, 0.5, 0.25, 1.0]), + "{label}: unexpected pixel {:?}", + texels.first() + ); + } + } + } + }