From 1d031e3297be23e64af6e57e187b7a411b67cb20 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 05:53:55 +0000 Subject: [PATCH 1/2] Shader: add mesh emulation translation and cache metadata Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- apps/victory/src/translate.rs | 62 +- crates/victory-gpu/src/draw.rs | 1 + crates/victory-gpu/src/shader_cache.rs | 263 +++- crates/victory-shader/src/emit/bvh_tests.rs | 2 + crates/victory-shader/src/emit/host.rs | 435 +++++- .../src/emit/image_atomic_tests.rs | 2 + .../src/emit/intersect_tests.rs | 3 + crates/victory-shader/src/emit/lower.rs | 98 +- .../victory-shader/src/emit/lower/mesh_emu.rs | 415 +++++ crates/victory-shader/src/emit/lower/tests.rs | 6 + crates/victory-shader/src/emit/mesh_emu.rs | 1365 +++++++++++++++++ crates/victory-shader/src/emit/mod.rs | 74 +- crates/victory-shader/src/emit/rect.rs | 1 + .../src/emit/root_view_tests.rs | 2 + crates/victory-shader/src/emit/shader.rs | 119 +- crates/victory-shader/src/emit/valu_tests.rs | 4 + .../src/emit/waterfall_tests.rs | 2 + .../victory-shader/src/emit/wave64_tests.rs | 2 + 18 files changed, 2769 insertions(+), 87 deletions(-) create mode 100644 crates/victory-shader/src/emit/lower/mesh_emu.rs create mode 100644 crates/victory-shader/src/emit/mesh_emu.rs diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index 379f49e..b959138 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -155,6 +155,20 @@ struct Checks { keep: Option, validator: Option, host: Option<(Host, emit::HostShader)>, + mesh: emit::MeshMode, +} + +fn mesh_mode(host: Option<&Host>) -> emit::MeshMode { + match std::env::var("VICTORY_MESH_EMULATION") + .ok() + .as_deref() + .map(str::trim) + { + Some(v) if v == "1" || v.eq_ignore_ascii_case("true") => emit::MeshMode::Emulate, + Some(v) if v == "0" || v.eq_ignore_ascii_case("false") => emit::MeshMode::Native, + _ if host.is_some_and(|h| !h.mesh_shaders()) => emit::MeshMode::Emulate, + _ => emit::MeshMode::Native, + } } pub fn run( @@ -182,9 +196,7 @@ pub fn run( } else if validate_requested { println!("validator skipped (Windows only)"); } - if pipelines { - Host::new(false).map_err(anyhow::Error::msg)?; - } else if pipelines_requested { + if pipelines_requested && !pipelines { println!("host pipelines skipped (Windows only)"); } let pairs: Vec<(String, String)> = std::env::var("VICTORY_PAIRS") @@ -193,6 +205,13 @@ pub fn run( .filter_map(|p| p.split_once('+')) .map(|(v, p)| (v.trim().to_owned(), p.trim().to_owned())) .collect(); + let probe_host = if pipelines || !pairs.is_empty() { + Some(Host::new(false).map_err(anyhow::Error::msg)?) + } else { + None + }; + let mesh = mesh_mode(probe_host.as_ref()); + drop(probe_host); let kept = std::sync::Arc::new(Mutex::new(Vec::new())); let threads = jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get())); @@ -230,6 +249,7 @@ pub fn run( host: pipelines .then(|| Host::new(false).ok().map(|h| (h, host::stub_ps()))) .flatten(), + mesh, }); while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { translate(job, entry.path(), &seen, &mut t, checks); @@ -303,11 +323,15 @@ pub fn run( for (v, p) in &pairs { let made = match (find(v), find(p)) { (Some((_, vs)), Some((_, ps))) => if vs.stage == HwStage::Ms { - host.mesh_pipeline(vs, ps) + if vs.mesh_emu.is_some() { + host.emulated_mesh_pipelines(vs, ps).map(drop) + } else { + host.mesh_pipeline(vs, ps).map(drop) + } } else { - host.pipeline(vs, ps) + host.pipeline(vs, ps).map(drop) } - .map(|_| "pipeline created".to_owned()) + .map(|()| "pipeline created".to_owned()) .unwrap_or_else(|e| e), _ => "not emitted".to_owned(), }; @@ -419,7 +443,7 @@ fn translate( if let (Some(r), Some(i), Some(s)) = (res, raised, structured) { let label = || format!("{} {:?}", example(), p.stage); *counter(t, p.stage, 0) += 1; - match emit::emit(&container, &p, &program, &s, &i, &r) { + match emit::emit_with(&container, &p, &program, &s, &i, &r, checks.mesh) { Ok(shader) => { *counter(t, p.stage, 1) += 1; check(shader, t, checks, label); @@ -470,6 +494,9 @@ fn check( let made = match shader.stage { HwStage::Vs => h.pipeline(&shader, stub_ps).map(drop), HwStage::Cs => h.compute_pipeline(&shader).map(drop), + HwStage::Ms if shader.mesh_emu.is_some() => { + h.emulated_mesh_pipelines(&shader, stub_ps).map(drop) + } HwStage::Ms => h.mesh_pipeline(&shader, stub_ps).map(drop), _ => host::stub_vs(&shader).and_then(|vs| h.pipeline(&vs, &shader).map(drop)), }; @@ -486,7 +513,14 @@ fn check( let Some(v) = checks.validator.as_mut() else { return; }; - match v.validate(&mut shader.dxil) { + let result = v.validate(&mut shader.dxil).and_then(|()| { + if let Some(emu) = &shader.mesh_emu { + let mut unpack = emit::unpack_vertex_shader(emu, None).map_err(|e| e.to_string())?; + v.validate(&mut unpack)?; + } + Ok(()) + }); + match result { Ok(()) => { *counter(t, shader.stage, 2) += 1; if t.list { @@ -732,6 +766,10 @@ mod unsupported { Err(WHY.into()) } + pub fn mesh_shaders(&self) -> bool { + false + } + pub fn pipeline(&self, _: &HostShader, _: &HostShader) -> Result<(), String> { Err(WHY.into()) } @@ -740,6 +778,14 @@ mod unsupported { Err(WHY.into()) } + pub fn emulated_mesh_pipelines( + &self, + _: &HostShader, + _: &HostShader, + ) -> Result<(), String> { + Err(WHY.into()) + } + pub fn compute_pipeline(&self, _: &HostShader) -> Result<(), String> { Err(WHY.into()) } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index cb00917..a63d49d 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1600,6 +1600,7 @@ mod tests { descriptor_words: false, root_uavs: Vec::new(), root_indexed_views: Vec::new(), + mesh_emu: None, }, used, }); diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 7da073c..2664953 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -15,7 +15,7 @@ use std::sync::OnceLock; use std::sync::atomic::{AtomicU64, Ordering}; use victory_pipeline::{Cache, Converter}; -use victory_shader::emit::{HostShader, StaticSampler, UserData}; +use victory_shader::emit::{HostShader, MeshEmu, MeshMode, MeshOutput, StaticSampler, UserData}; use victory_shader::resource::RootIndexedView; use victory_shader::{HwStage, RootType}; @@ -100,11 +100,24 @@ fn build() -> &'static [u8; BUILD_LEN] { } /// The translation of a console shader container, from the cache when -/// there is one. +/// there is one, with native mesh output. pub(crate) fn host_shader(container: &[u8]) -> Result { - let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string()); + host_shader_with(container, MeshMode::Native) +} + +/// The translation of a console shader container in `mesh` mode. Native and +/// emulated mesh translations use separate converter ids: the same console +/// container has two independent cache entries. +#[allow(dead_code)] +pub(crate) fn host_shader_with(container: &[u8], mesh: MeshMode) -> Result { + let id = match mesh { + MeshMode::Native => "shader.dxil", + MeshMode::Emulate => "shader.dxil.mesh-emu", + }; + let translate = + |c: &[u8]| victory_shader::emit::translate_with(c, mesh).map_err(|e| e.to_string()); match CACHE.get() { - Some(cache) => cached(cache, build(), container, translate), + Some(cache) => cached(cache, build(), id, container, translate), None => translate(container), } } @@ -113,13 +126,14 @@ pub(crate) fn host_shader(container: &[u8]) -> Result { /// encoded translation out. `translated` keeps what it produced, so a /// store that cannot publish the entry costs no second translation. struct Translate { + id: &'static str, translate: F, translated: OnceLock, } impl Result + Send + Sync> Converter for Translate { fn id(&self) -> &'static str { - "shader.dxil" + self.id } fn version(&self) -> u32 { // The build fingerprint in the input does the versioning. @@ -138,11 +152,13 @@ impl Result + Send + Sync> Converter for Tra fn cached( cache: &Cache, build: &[u8; BUILD_LEN], + id: &'static str, container: &[u8], translate: impl Fn(&[u8]) -> Result + Send + Sync, ) -> Result { let input = [&build[..], container].concat(); let converter = Translate { + id, translate, translated: OnceLock::new(), }; @@ -186,7 +202,7 @@ fn cached( (converter.translate)(container) } -const MAGIC: &[u8; 4] = b"VSH2"; +const MAGIC: &[u8; 4] = b"VSH3"; const STAGES: [HwStage; 8] = [ HwStage::Ls, HwStage::Hs, @@ -276,6 +292,44 @@ fn encode(s: &HostShader) -> Vec { word(&mut out, value); } } + let encode_outputs = |out: &mut Vec, items: &[MeshOutput]| { + word(out, items.len() as u32); + for o in items { + let name = o.name.as_bytes(); + word(out, name.len() as u32); + out.extend(name); + for v in [ + o.index, + u32::from(o.kind), + u32::from(o.comp), + u32::from(o.interp), + o.row.unwrap_or(u32::MAX), + u32::from(o.col), + u32::from(o.cols), + o.dword_offset, + ] { + word(out, v); + } + } + }; + match &s.mesh_emu { + None => word(&mut out, 0), + Some(m) => { + word(&mut out, 1); + for v in [ + m.threads, + m.max_vertices, + m.max_primitives, + m.vertex_dwords, + m.prim_dwords, + u32::from(m.reads_group_id), + ] { + word(&mut out, v); + } + encode_outputs(&mut out, &m.vertex_outputs); + encode_outputs(&mut out, &m.prim_outputs); + } + } out } @@ -294,6 +348,36 @@ fn decode(bytes: &[u8]) -> Option { let n = self.word()? as usize; Some(self.take(n)?.to_vec()) } + fn outputs(&mut self) -> Option> { + let n = self.word()? as usize; + let mut out = Vec::with_capacity(n.min(256)); + for _ in 0..n { + let name = String::from_utf8(self.list()?).ok()?; + let index = self.word()?; + let kind = u8::try_from(self.word()?).ok()?; + let comp = u8::try_from(self.word()?).ok()?; + let interp = u8::try_from(self.word()?).ok()?; + let row = match self.word()? { + u32::MAX => None, + r => Some(r), + }; + let col = u8::try_from(self.word()?).ok()?; + let cols = u8::try_from(self.word()?).ok()?; + let dword_offset = self.word()?; + out.push(MeshOutput { + name, + index, + kind, + comp, + interp, + row, + col, + cols, + dword_offset, + }); + } + Some(out) + } } let mut r = Reader(bytes); if r.take(4)? != MAGIC { @@ -363,6 +447,20 @@ fn decode(bytes: &[u8]) -> Option { shift: u8::try_from(r.word()?).ok().filter(|&s| s < 32)?, }); } + let mesh_emu = match r.word()? { + 0 => None, + 1 => Some(MeshEmu { + threads: r.word()?, + max_vertices: r.word()?, + max_primitives: r.word()?, + vertex_dwords: r.word()?, + prim_dwords: r.word()?, + reads_group_id: flag(r.word()?)?, + vertex_outputs: r.outputs()?, + prim_outputs: r.outputs()?, + }), + _ => return None, + }; r.0.is_empty().then_some(HostShader { stage, dxil, @@ -375,6 +473,7 @@ fn decode(bytes: &[u8]) -> Option { descriptor_words, root_uavs, root_indexed_views, + mesh_emu, }) } @@ -412,9 +511,59 @@ mod tests { byte_offset: 32, shift: 5, }], + mesh_emu: None, } } + fn mesh_emu_shader() -> HostShader { + let mut s = shader(); + s.stage = HwStage::Ms; + s.mesh_emu = Some(MeshEmu { + threads: 64, + max_vertices: 32, + max_primitives: 16, + vertex_dwords: 8, + prim_dwords: 4, + reads_group_id: true, + vertex_outputs: vec![ + MeshOutput { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 4, + row: None, + col: 0, + cols: 4, + dword_offset: 0, + }, + MeshOutput { + name: "COLOR".into(), + index: 0, + kind: 0, + comp: 9, + interp: 2, + row: Some(0), + col: 0, + cols: 4, + dword_offset: 4, + }, + ], + prim_outputs: vec![MeshOutput { + name: "PRIMID".into(), + index: 0, + kind: 0, + comp: 5, + interp: 1, + row: Some(1), + col: 0, + cols: 1, + dword_offset: 0, + }], + }); + s + } + #[test] fn translations_come_back_from_the_cache() { let dir = tempfile::tempdir().unwrap(); @@ -426,26 +575,59 @@ mod tests { runs.fetch_add(1, Ordering::Relaxed); Ok(shader()) }; - assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); - assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!( + cached(&cache, &build, "shader.dxil", container, translate), + Ok(shader()) + ); + assert_eq!( + cached(&cache, &build, "shader.dxil", container, translate), + Ok(shader()) + ); assert_eq!(runs.load(Ordering::Relaxed), 1, "the second came from disk"); + // Another converter id caches separately. + let emu_runs = AtomicU64::new(0); + let emu_translate = |_: &[u8]| { + emu_runs.fetch_add(1, Ordering::Relaxed); + Ok(mesh_emu_shader()) + }; + assert_eq!( + cached( + &cache, + &build, + "shader.dxil.mesh-emu", + container, + emu_translate, + ), + Ok(mesh_emu_shader()) + ); + assert_eq!(emu_runs.load(Ordering::Relaxed), 1); + // Another build translates again. - assert_eq!(cached(&cache, &[8; 32], container, translate), Ok(shader())); + assert_eq!( + cached(&cache, &[8; 32], "shader.dxil", container, translate), + Ok(shader()) + ); assert_eq!(runs.load(Ordering::Relaxed), 2); // A damaged entry is a miss, translated and stored again. for e in walk(dir.path()) { - std::fs::write(e, b"VSH1 broken").unwrap(); + std::fs::write(e, b"VSH3 broken").unwrap(); } - assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!( + cached(&cache, &build, "shader.dxil", container, translate), + Ok(shader()) + ); assert_eq!(runs.load(Ordering::Relaxed), 3); - assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!( + cached(&cache, &build, "shader.dxil", container, translate), + Ok(shader()) + ); assert_eq!(runs.load(Ordering::Relaxed), 3); // Failures are not stored. let fail = |_: &[u8]| Err::("unsupported".to_owned()); - assert!(cached(&cache, &build, b"other", fail).is_err()); + assert!(cached(&cache, &build, "shader.dxil", b"other", fail).is_err()); } fn walk(dir: &std::path::Path) -> Vec { @@ -496,16 +678,19 @@ mod tests { descriptor_words: true, root_uavs: Vec::new(), root_indexed_views: Vec::new(), + mesh_emu: None, } } #[test] fn entries_round_trip_and_reject_damage() { - let bytes = encode(&shader()); - assert_eq!(decode(&bytes), Some(shader())); - assert_eq!(decode(&bytes[..bytes.len() - 1]), None); - assert_eq!(decode(&[bytes.as_slice(), &[0]].concat()), None); - assert_eq!(decode(b"VSH0"), None); + for shader in [shader(), mesh_emu_shader()] { + let bytes = encode(&shader); + assert_eq!(decode(&bytes), Some(shader)); + assert_eq!(decode(&bytes[..bytes.len() - 1]), None); + assert_eq!(decode(&[bytes.as_slice(), &[0]].concat()), None); + } + assert_eq!(decode(b"VSH2"), None); } #[test] @@ -578,8 +763,14 @@ mod tests { b[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); assert_eq!(decode(&b), None, "too many user-data entries"); - // The last list's length: the bytes it promises are not there. - let at = bytes.len() - s.root_srvs.len() - 4; + // The root-SRV list's length: the bytes it promises are not there. + let mut at = 12 + s.dxil.len() + 4; + for u in &s.user_data { + at += 16 + usize::from(matches!(u.root, RootType::Other(_))) * 4; + } + at += 4 + s.samplers.len() * 16; + at += 4 + s.static_samplers.len() * 40; + at += 4 + s.root_cbvs.len(); let mut b = bytes.clone(); b[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); assert_eq!(decode(&b), None, "a root SRV list that is not there"); @@ -639,17 +830,32 @@ mod tests { s }; let (a, b) = (b"first container".as_slice(), b"second container"); - assert_eq!(cached(&cache, &[7; 32], a, translate), Ok(of(a))); - assert_eq!(cached(&cache, &[7; 32], b, translate), Ok(of(b))); + assert_eq!( + cached(&cache, &[7; 32], "shader.dxil", a, translate), + Ok(of(a)) + ); + assert_eq!( + cached(&cache, &[7; 32], "shader.dxil", b, translate), + Ok(of(b)) + ); assert_eq!(runs.load(Ordering::Relaxed), 2); assert_eq!(walk(dir.path()).len(), 2, "one entry per container"); - assert_eq!(cached(&cache, &[7; 32], a, translate), Ok(of(a))); - assert_eq!(cached(&cache, &[7; 32], b, translate), Ok(of(b))); + assert_eq!( + cached(&cache, &[7; 32], "shader.dxil", a, translate), + Ok(of(a)) + ); + assert_eq!( + cached(&cache, &[7; 32], "shader.dxil", b, translate), + Ok(of(b)) + ); assert_eq!(runs.load(Ordering::Relaxed), 2, "both came from the cache"); // Another build's translation is a separate entry too. - assert_eq!(cached(&cache, &[8; 32], b, translate), Ok(of(b))); + assert_eq!( + cached(&cache, &[8; 32], "shader.dxil", b, translate), + Ok(of(b)) + ); assert_eq!(runs.load(Ordering::Relaxed), 3); assert_eq!(walk(dir.path()).len(), 3); } @@ -663,6 +869,7 @@ mod tests { let container = b"a console container".as_slice(); let translate = |_: &[u8]| -> Result { Ok(shader()) }; let converter = Translate { + id: "shader.dxil", translate, translated: OnceLock::new(), }; @@ -675,7 +882,10 @@ mod tests { runs.fetch_add(1, Ordering::Relaxed); Ok(shader()) }; - assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!( + cached(&cache, &build, "shader.dxil", container, translate), + Ok(shader()) + ); assert_eq!(runs.load(Ordering::Relaxed), 1, "no second translation"); assert!(path.is_dir(), "the entry path is still unusable"); } @@ -683,6 +893,7 @@ mod tests { #[test] fn the_converter_needs_the_build_fingerprint() { let converter = Translate { + id: "shader.dxil", translate: |c: &[u8]| -> Result { let mut s = shader(); s.dxil = c.to_vec(); diff --git a/crates/victory-shader/src/emit/bvh_tests.rs b/crates/victory-shader/src/emit/bvh_tests.rs index ff37bbb..2a7305f 100644 --- a/crates/victory-shader/src/emit/bvh_tests.rs +++ b/crates/victory-shader/src/emit/bvh_tests.rs @@ -364,6 +364,7 @@ mod gpu { outputs: Vec::new(), prims: Vec::new(), crumbs: None, + emulate_mesh: false, mesh_stride: 0, }) .expect("lower"); @@ -379,6 +380,7 @@ mod gpu { descriptor_words: lowered.descriptor_words, root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), + mesh_emu: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 3e8d590..7dd8295 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -157,6 +157,14 @@ impl Host { &self, stages: &[(&HostShader, D3D12_SHADER_VISIBILITY)], ) -> Result { + self.root_signature_with_extra(stages, &[]).map(|(r, _)| r) + } + + fn root_signature_with_extra( + &self, + stages: &[(&HostShader, D3D12_SHADER_VISIBILITY)], + extra: &[D3D12_ROOT_PARAMETER1], + ) -> Result<(ID3D12RootSignature, u32), String> { let mut params: Vec = stages .iter() .map(|&(s, vis)| D3D12_ROOT_PARAMETER1 { @@ -224,6 +232,8 @@ impl Host { }); } } + let extra_base = params.len() as u32; + params.extend_from_slice(extra); let mut samplers = Vec::new(); for &(s, vis) in stages { for (n, d) in s.static_samplers.iter().enumerate() { @@ -260,7 +270,7 @@ impl Host { }, }; // SAFETY: the description points at live arrays. - unsafe { + let root = unsafe { let mut blob = None; let mut error = None; D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut error)) @@ -270,8 +280,9 @@ impl Host { blob.GetBufferPointer().cast::(), blob.GetBufferSize(), ); - self.device.CreateRootSignature(0, bytes).map_err(err) - } + self.device.CreateRootSignature(0, bytes).map_err(err)? + }; + Ok((root, extra_base)) } /// A compute pipeline; user data is root parameter 0. @@ -551,6 +562,113 @@ impl Host { // SAFETY: the stream points at live data and outlives the call. unsafe { device.CreatePipelineState(&desc) }.map_err(err) } + + /// Whether the host supports hardware mesh shaders at shader model 6.6. + pub fn mesh_shaders(&self) -> bool { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + // SAFETY: writes into `options` of its exact size. + unsafe { + self.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS7, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .is_ok() + && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED + } + } + + /// Dual compute + unpack vertex/pixel pipelines for an emulated mesh shader. + pub fn emulated_mesh_pipelines( + &self, + ms: &HostShader, + ps: &HostShader, + ) -> Result { + let emu = ms + .mesh_emu + .as_ref() + .ok_or("mesh shader was not translated in emulation mode")?; + let mut cs_extra = vec![D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, + RegisterSpace: super::MESH_EMU_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }]; + if emu.reads_group_id { + cs_extra.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: super::MESH_EMU_SPACE, + Num32BitValues: 4, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + cs_extra.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, + RegisterSpace: super::MESH_EMU_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + } + let (cs_root, cs_base) = + self.root_signature_with_extra(&[(ms, D3D12_SHADER_VISIBILITY_ALL)], &cs_extra)?; + let cs_pso = self.compute_pipeline_with(&cs_root, &ms.dxil)?; + + let unpack_vs = + super::unpack_vertex_shader(emu, Some(&ps.dxil)).map_err(|e| e.to_string())?; + let (gfx_root, gfx_srv_param) = self.root_signature_with_extra( + &[(ps, D3D12_SHADER_VISIBILITY_PIXEL)], + &[D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, + RegisterSpace: super::MESH_EMU_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_VERTEX, + }], + )?; + let gfx_pso = self.pipeline_with(&gfx_root, &unpack_vs, &ps.dxil)?; + + Ok(EmulatedMeshPipelines { + cs_root, + cs_pso, + gfx_root, + gfx_pso, + cs_uav_param: cs_base, + cs_cbv_param: emu.reads_group_id.then_some(cs_base + 1), + cs_srv_param: emu.reads_group_id.then_some(cs_base + 2), + gfx_srv_param, + }) + } +} + +/// Compute + unpack graphics pipelines built for an emulated mesh shader. +pub struct EmulatedMeshPipelines { + pub cs_root: ID3D12RootSignature, + pub cs_pso: ID3D12PipelineState, + pub gfx_root: ID3D12RootSignature, + pub gfx_pso: ID3D12PipelineState, + pub cs_uav_param: u32, + pub cs_cbv_param: Option, + pub cs_srv_param: Option, + pub gfx_srv_param: u32, } /// A vertex shader that feeds `ps`'s inputs (zeros) and a position. @@ -646,6 +764,7 @@ fn stub(pixel: bool, outputs: Vec) -> HostShader { descriptor_words: false, root_uavs: Vec::new(), root_indexed_views: Vec::new(), + mesh_emu: None, } } @@ -1514,3 +1633,313 @@ impl Host { } } } + +/// Bindings for [`Host::draw_emulated_mesh`]. +#[cfg(test)] +pub struct EmulatedMeshDraw<'a> { + pub cs_roots: Vec<(u32, Root)>, + pub ps_roots: Vec<(u32, Root)>, + pub size: (u32, u32), + pub groups: u32, + pub max_primitives: u32, + pub group_bytes: u32, + pub base_group: u32, + pub slot_map: Option<&'a [u32]>, +} + +#[cfg(test)] +impl Host { + /// Runs an emulated mesh shader (`cs_6_6`) followed by its unpack `vs_6_6` + /// + `ps_6_6` draw into a cleared RGBA32F render target and returns texels. + pub fn draw_emulated_mesh( + &self, + pipes: &EmulatedMeshPipelines, + d: &EmulatedMeshDraw, + ) -> Result, String> { + let dev = &self.device; + let (w, h) = d.size; + // SAFETY: D3D12 calls with descriptions that outlive them; resources + // remain alive until the fence reports GPU completion. + unsafe { + let queue: ID3D12CommandQueue = dev + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .map_err(err)?; + let alloc: ID3D12CommandAllocator = dev + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .map_err(err)?; + let list: ID3D12GraphicsCommandList = dev + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pipes.cs_pso) + .map_err(err)?; + let tex_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(w), + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let buf_desc = |size: u64, flags| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(4), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let make = |heap: D3D12_HEAP_TYPE, + desc: &D3D12_RESOURCE_DESC, + state, + clear: Option<&D3D12_CLEAR_VALUE>| { + let mut r: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: heap, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + desc, + state, + clear.map(|c| c as *const _), + &mut r, + ) + .map_err(err)?; + r.ok_or_else(|| "no resource".to_string()) + }; + let target = make( + D3D12_HEAP_TYPE_DEFAULT, + &tex_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + Some(&D3D12_CLEAR_VALUE { + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0; 4] }, + }), + )?; + let rtv_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: 1, + ..Default::default() + }) + .map_err(err)?; + let rtv = rtv_heap.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(&target, None, rtv); + let views: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .map_err(err)?; + let sampler_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + NumDescriptors: 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .map_err(err)?; + + let out_bytes = (u64::from(d.groups.max(1)) * u64::from(d.group_bytes.max(4))).max(256); + let output = make( + D3D12_HEAP_TYPE_DEFAULT, + &buf_desc(out_bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + None, + )?; + let map_words = d.slot_map.map_or(1, |m| m.len().max(1)); + let map_bytes = ((map_words * 4).next_multiple_of(256)) as u64; + let slot_map_buf = make( + D3D12_HEAP_TYPE_UPLOAD, + &buf_desc(map_bytes, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + )?; + let mut mp = std::ptr::null_mut(); + slot_map_buf.Map(0, None, Some(&mut mp)).map_err(err)?; + std::ptr::write_bytes(mp, 0, map_bytes as usize); + if let Some(map) = d.slot_map { + std::ptr::copy_nonoverlapping(map.as_ptr(), mp.cast::(), map.len()); + } + slot_map_buf.Unmap(0, None); + + let mut keep = Vec::new(); + let upload_dwords = |data: &[u32]| -> Result { + let bytes = (data.len() * 4).next_multiple_of(256) as u64; + let b = make( + D3D12_HEAP_TYPE_UPLOAD, + &buf_desc(bytes, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + )?; + let mut p = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).map_err(err)?; + std::ptr::copy_nonoverlapping(data.as_ptr(), p.cast::(), data.len()); + b.Unmap(0, None); + Ok(b) + }; + + list.SetDescriptorHeaps(&[Some(views.clone()), Some(sampler_heap.clone())]); + list.SetComputeRootSignature(&pipes.cs_root); + for (param, arg) in &d.cs_roots { + match arg { + Root::Constants(data) => list.SetComputeRoot32BitConstants( + *param, + data.len() as u32, + data.as_ptr().cast(), + 0, + ), + Root::View { srv, data } => { + let b = upload_dwords(data)?; + let va = b.GetGPUVirtualAddress(); + if *srv { + list.SetComputeRootShaderResourceView(*param, va); + } else { + list.SetComputeRootConstantBufferView(*param, va); + } + keep.push(b); + } + Root::Table { .. } => return Err("descriptor tables not supported here".into()), + } + } + list.SetComputeRootUnorderedAccessView( + pipes.cs_uav_param, + output.GetGPUVirtualAddress(), + ); + if let Some(p) = pipes.cs_cbv_param { + let c = [d.base_group, 0, 0, 0]; + list.SetComputeRoot32BitConstants(p, 4, c.as_ptr().cast(), 0); + } + if let Some(p) = pipes.cs_srv_param { + list.SetComputeRootShaderResourceView(p, slot_map_buf.GetGPUVirtualAddress()); + } + list.Dispatch(d.groups, 1, 1); + + list.ResourceBarrier(&[transition( + &output, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + list.SetPipelineState(&pipes.gfx_pso); + list.SetGraphicsRootSignature(&pipes.gfx_root); + for (param, arg) in &d.ps_roots { + match arg { + Root::Constants(data) => list.SetGraphicsRoot32BitConstants( + *param, + data.len() as u32, + data.as_ptr().cast(), + 0, + ), + Root::View { srv, data } => { + let b = upload_dwords(data)?; + let va = b.GetGPUVirtualAddress(); + if *srv { + list.SetGraphicsRootShaderResourceView(*param, va); + } else { + list.SetGraphicsRootConstantBufferView(*param, va); + } + keep.push(b); + } + Root::Table { .. } => return Err("descriptor tables not supported here".into()), + } + } + list.SetGraphicsRootShaderResourceView( + pipes.gfx_srv_param, + output.GetGPUVirtualAddress(), + ); + list.ClearRenderTargetView(rtv, &[0.0; 4], None); + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.RSSetViewports(&[D3D12_VIEWPORT { + Width: w as f32, + Height: h as f32, + MaxDepth: 1.0, + ..Default::default() + }]); + list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { + right: w as i32, + bottom: h as i32, + ..Default::default() + }]); + list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list.DrawInstanced(d.groups * d.max_primitives * 3, 1, 0, 0); + + list.ResourceBarrier(&[transition( + &target, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let pitch = (w as usize * 16).next_multiple_of(256); + let readback = make( + D3D12_HEAP_TYPE_READBACK, + &buf_desc((pitch * h as usize) as u64, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + None, + )?; + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&readback), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + Width: w, + Height: h, + Depth: 1, + RowPitch: pitch as u32, + }, + }, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&target), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().map_err(err)?; + queue.ExecuteCommandLists(&[Some(list.cast().map_err(err)?)]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(err)?; + queue.Signal(&fence, 1).map_err(err)?; + while fence.GetCompletedValue() < 1 { + if let Err(e) = dev.GetDeviceRemovedReason() { + return Err(format!("device removed: {}", err(e))); + } + std::thread::yield_now(); + } + if let Err(e) = dev.GetDeviceRemovedReason() { + return Err(format!("device removed: {}", err(e))); + } + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).map_err(err)?; + let mut out = Vec::with_capacity((w * h) as usize); + for y in 0..h as usize { + let row = std::slice::from_raw_parts( + p.cast::().add(y * pitch).cast::<[f32; 4]>(), + w as usize, + ); + out.extend_from_slice(row); + } + readback.Unmap(0, None); + drop(keep); + Ok(out) + } + } +} diff --git a/crates/victory-shader/src/emit/image_atomic_tests.rs b/crates/victory-shader/src/emit/image_atomic_tests.rs index f686195..6f463e3 100644 --- a/crates/victory-shader/src/emit/image_atomic_tests.rs +++ b/crates/victory-shader/src/emit/image_atomic_tests.rs @@ -126,6 +126,7 @@ fn build(op: u8, pair: bool) -> HostShader { prims: Vec::new(), mesh_stride: 0, crumbs: None, + emulate_mesh: false, }) .expect("lower"); let shader = HostShader { @@ -140,6 +141,7 @@ fn build(op: u8, pair: bool) -> HostShader { descriptor_words: lowered.descriptor_words, root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), + mesh_emu: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) diff --git a/crates/victory-shader/src/emit/intersect_tests.rs b/crates/victory-shader/src/emit/intersect_tests.rs index 23463a7..333bc0c 100644 --- a/crates/victory-shader/src/emit/intersect_tests.rs +++ b/crates/victory-shader/src/emit/intersect_tests.rs @@ -178,6 +178,7 @@ fn build( prims: Vec::new(), mesh_stride: 0, crumbs: None, + emulate_mesh: false, })?; let shader = HostShader { stage: HwStage::Cs, @@ -189,6 +190,7 @@ fn build( root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views.clone(), + mesh_emu: None, address_map: lowered.address_map, descriptor_words: lowered.descriptor_words, }; @@ -684,6 +686,7 @@ fn a_structure_that_returns_triangle_ids_is_refused_by_name() { prims: Vec::new(), mesh_stride: 0, crumbs: None, + emulate_mesh: false, }); match r { Err(ShaderError::Unsupported { what, .. }) => { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index b2b010c..da097a9 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -68,6 +68,7 @@ pub(crate) struct Lowered { pub samplers: Vec<[u32; 4]>, /// The wave size the shader requires of the host, if any. pub wave_size: Option, + pub mesh_emu: Option, /// Heap handles made with a non-uniform index. #[cfg(test)] pub nonuniform_handles: u32, @@ -93,6 +94,7 @@ pub(crate) struct Parts<'a> { /// With breadcrumbs (see [`super::breadcrumbs`]): the shader's slot. #[allow(dead_code)] pub crumbs: Option, + pub emulate_mesh: bool, } enum Stop { @@ -370,6 +372,8 @@ struct Lower<'a> { /// order met (the word each owns in the shader's slot). #[allow(dead_code)] crumb_loops: HashMap, + /// Mesh shader lowered to compute + buffer output when emulating. + mesh_emu: Option, } /// Iterations after which a loop is left (per entry into it), unless @@ -1672,15 +1676,23 @@ impl<'a> Lower<'a> { HashSet::new() }; let mut no_barrier = HashSet::new(); + let mut mesh_emu = None; if let StageIo::Ms(ms) = &x.native.io { - s.prims = x.prims.clone(); s.threads = Some([ms.threads, 1, 1]); s.lds_dwords = ms.lds_bytes.div_ceil(4); - s.mesh = Some(super::shader::Mesh { - max_vertices: ms.max_vertices, - max_primitives: ms.max_primitives, - topology: ms.topology, - }); + if x.emulate_mesh { + s.inputs.clear(); + s.outputs.clear(); + s.prims.clear(); + mesh_emu = Some(mesh_emu_state(ms, x)); + } else { + s.prims = x.prims.clone(); + s.mesh = Some(super::shader::Mesh { + max_vertices: ms.max_vertices, + max_primitives: ms.max_primitives, + topology: ms.topology, + }); + } // Barriers order the lanes' LDS accesses; the console's // allocation request needs them too, but the host does not. One // lane sends that request, and what it dominates (the path for @@ -1818,6 +1830,7 @@ impl<'a> Lower<'a> { counters: HashMap::new(), abort: None, ret: None, + mesh_emu, } } @@ -2352,6 +2365,20 @@ impl<'a> Lower<'a> { self.s.m.new_block() }); } + self.cur = self.s.entry; + self.find_sections(); + if self.mesh_emu.is_some() { + self.mesh_emu_init().map_err(|w| unsupported(0, w))?; + } + self.inputs()?; + if let Some(mesh) = self.s.mesh { + self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?; + } else if self.mesh_emu.is_some() { + self.mesh_emu_prologue(); + } + if self.cur != self.s.entry { + self.block[order[0]] = Some(self.cur); + } // Loop headers count iterations (`LOOP_LIMIT`). for &b in &order { let header = p.blocks[b] @@ -2364,13 +2391,6 @@ impl<'a> Lower<'a> { self.counters.insert(b, (phi, Vec::new())); } } - self.cur = self.s.entry; - self.find_sections(); - self.inputs()?; - if let Some(mesh) = self.s.mesh { - self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?; - self.block[order[0]] = Some(self.cur); - } for &b in &order { self.cur = self.block[b].expect("reachable"); self.cur_ir = b; @@ -2435,6 +2455,7 @@ impl<'a> Lower<'a> { let wave_size = self.s.wave_size; let address_map = self.s.address_map.is_some(); let descriptor_words = self.s.descriptor_words.is_some(); + let mesh_emu = self.mesh_emu.take().map(MeshEmuState::finish); Ok(Lowered { wave_size, cmp_samplers, @@ -2443,6 +2464,7 @@ impl<'a> Lower<'a> { root_uavs, address_map, descriptor_words, + mesh_emu, #[cfg(test)] nonuniform_handles: self.s.nonuniform_handles, #[cfg(test)] @@ -2524,6 +2546,9 @@ impl<'a> Lower<'a> { Input::GroupId(c) => return self.compute_id("groupId.i32", 94, c), Input::GroupInfo => return Val::Missing("the thread-group info SGPR"), Input::MeshGroup => { + if self.mesh_emu.is_some() { + return self.mesh_group_emu(); + } let Val::I32(g) = self.compute_id("groupId.i32", 94, 0) else { unreachable!() }; @@ -4676,11 +4701,14 @@ impl<'a> Lower<'a> { prev } + fn is_mesh(&self) -> bool { + self.s.mesh.is_some() || self.mesh_emu.is_some() + } /// Code that depends on the lane layout: wave operations, and in compute /// the console's wave size (lanes are thread ids in group order there). /// Pixel lanes match only within a quad. fn cross_lane(&mut self, quad: bool) -> Result<(), Why> { - if self.s.mesh.is_some() { + if self.is_mesh() { // shortcut: no wave size for mesh shaders in SM 6.6, so host // lanes cannot follow the console's; emulate through group-shared // memory if mesh programs turn out to need these. @@ -4853,7 +4881,7 @@ impl<'a> Lower<'a> { } fn lane_index(&mut self) -> V { - if self.s.mesh.is_some() { + if self.is_mesh() { // The console's lane: mesh code reads no other lanes, so host // waves need not match the console's. let f = self.mesh_thread(); @@ -5026,7 +5054,7 @@ impl<'a> Lower<'a> { || offset & 0x1C == 0x1C && offset & 0x380 == 0 && offset >> 10 & 0x1F < 4; // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the // console's, so quad-local swizzles read through quad operations. - let mesh_quad = self.s.mesh.is_some() && quad; + let mesh_quad = self.is_mesh() && quad; if !mesh_quad { self.cross_lane(quad)?; } @@ -7593,7 +7621,7 @@ impl<'a> Lower<'a> { let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("a DPP operand")?)?; // Quad permutations and DPP8 stay in groups the pixel layout shares. let quad = matches!(dpp, Dpp::Row { ctrl: 0..=0xFF, .. }); - let mesh_quad = self.s.mesh.is_some() && quad; + let mesh_quad = self.is_mesh() && quad; if !mesh_quad { self.cross_lane(quad)?; } @@ -10037,7 +10065,7 @@ impl<'a> Lower<'a> { return Err("v_mbcnt of a mask that is no ballot (console lane layout)"); } self.s.flags |= flags::WAVE_OPS; - } else if self.s.mesh.is_none() { + } else if !self.is_mesh() { self.cross_lane(false)?; } let lane = self.console_lane(); @@ -11877,7 +11905,7 @@ impl<'a> Lower<'a> { return Err("a compressed export"); } let guard = self.guard(b, i)?; - let mesh = self.s.mesh.is_some(); + let mesh = self.is_mesh(); let c = self.cur; if let Some(g) = guard && !mesh @@ -11891,6 +11919,9 @@ impl<'a> Lower<'a> { .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]); } if mesh && e.target == Target::Primitive { + if self.mesh_emu.is_some() { + return self.emit_indices_emu(e, guard); + } return self.emit_indices(e, guard); } let param_row = |usage: Usage, row: u8| match usage { @@ -11903,10 +11934,11 @@ impl<'a> Lower<'a> { // outputs are elements of `prims`. let mut stores = Vec::new(); let primitive = matches!(e.target, Target::PrimitiveParam { .. }); - let outputs = if primitive { - &self.s.prims - } else { - &self.s.outputs + let outputs = match (&self.mesh_emu, primitive) { + (Some(m), true) => &m.prim_sigs, + (Some(m), false) => &m.vertex_sigs, + (None, true) => &self.s.prims, + (None, false) => &self.s.outputs, }; let by_kind = |kind: u8| outputs.iter().position(|o| o.kind == kind); // 16-bit vertex outputs: the halves each dword carries, as (output @@ -12009,7 +12041,13 @@ impl<'a> Lower<'a> { } } fn elements<'l>(l: &'l mut Lower, primitive: bool) -> &'l mut Vec { - if primitive { + if let Some(m) = l.mesh_emu.as_mut() { + if primitive { + &mut m.prim_sigs + } else { + &mut m.vertex_sigs + } + } else if primitive { &mut l.s.prims } else { &mut l.s.outputs @@ -12021,6 +12059,9 @@ impl<'a> Lower<'a> { { return Err("a 16-bit output the stage data does not mark"); } + if self.mesh_emu.is_some() { + return self.store_mesh_emu_outputs(guard, primitive, &stores); + } // A mesh lane writes its own vertex or primitive, where it exports. let at = if mesh { let flat = self.mesh_thread(); @@ -12170,9 +12211,11 @@ impl<'a> Lower<'a> { .iter() .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r) }; - let free: std::collections::BTreeSet = self - .s - .outputs + let vertex_sigs = match &self.mesh_emu { + Some(m) => &m.vertex_sigs, + None => &self.s.outputs, + }; + let free: std::collections::BTreeSet = vertex_sigs .iter() .filter(|o| o.kind == 0) .filter_map(|o| o.row) @@ -12200,5 +12243,6 @@ fn interp_mode(kind: Barycentric) -> Option { } include!("lower/methods.rs"); +include!("lower/mesh_emu.rs"); #[cfg(test)] mod tests; diff --git a/crates/victory-shader/src/emit/lower/mesh_emu.rs b/crates/victory-shader/src/emit/lower/mesh_emu.rs new file mode 100644 index 0000000..86f5eb0 --- /dev/null +++ b/crates/victory-shader/src/emit/lower/mesh_emu.rs @@ -0,0 +1,415 @@ +fn mesh_emu_state(ms: &crate::native::MeshIo, x: &Parts) -> MeshEmuState { + let (vertex_offsets, vertex_dwords) = pack_offsets(&x.outputs); + let (prim_offsets, prim_dwords) = pack_offsets(&x.prims); + MeshEmuState { + threads: ms.threads, + max_vertices: ms.max_vertices, + max_primitives: ms.max_primitives, + topology: ms.topology, + vertex_sigs: x.outputs.clone(), + vertex_offsets, + vertex_dwords, + prim_sigs: x.prims.clone(), + prim_offsets, + prim_dwords, + reads_group_id: false, + vals: None, + } +} + +struct MeshEmuVals { + uav: V, + local_group: V, + group_base: V, + flat_lt_verts: Option, + flat_lt_prims: Option, + index_bytes: u32, + vertex_stride_bytes: u32, + prim_offset_bytes: u32, + prim_stride_bytes: u32, +} + +struct MeshEmuState { + threads: u32, + max_vertices: u32, + max_primitives: u32, + topology: u8, + vertex_sigs: Vec, + vertex_offsets: Vec, + vertex_dwords: u32, + prim_sigs: Vec, + prim_offsets: Vec, + prim_dwords: u32, + reads_group_id: bool, + vals: Option, +} + +fn pack_offsets(sigs: &[SigElement]) -> (Vec, u32) { + let mut offsets = Vec::with_capacity(sigs.len()); + let mut next = 0u32; + for e in sigs { + offsets.push(next); + next += u32::from(e.cols); + } + (offsets, next) +} + + +impl MeshEmuState { + fn finish(self) -> super::MeshEmu { + let to_outputs = |sigs: Vec, offsets: Vec| { + sigs.into_iter() + .zip(offsets) + .map(|(s, dword_offset)| super::MeshOutput { + name: s.name, + index: s.index, + kind: s.kind, + comp: s.comp, + interp: s.interp, + row: s.row, + col: s.col, + cols: s.cols, + dword_offset, + }) + .collect() + }; + super::MeshEmu { + threads: self.threads, + max_vertices: self.max_vertices, + max_primitives: self.max_primitives, + vertex_dwords: self.vertex_dwords, + prim_dwords: self.prim_dwords, + reads_group_id: self.reads_group_id, + vertex_outputs: to_outputs(self.vertex_sigs, self.vertex_offsets), + prim_outputs: to_outputs(self.prim_sigs, self.prim_offsets), + } + } +} + +impl<'a> Lower<'a> { + fn mesh_emu_init(&mut self) -> Result<(), Why> { + let (threads, raw_verts, raw_prims, topology, vertex_dwords, prim_dwords) = { + let m = self.mesh_emu.as_ref().expect("mesh emu"); + ( + m.threads, + m.max_vertices, + m.max_primitives, + m.topology, + m.vertex_dwords, + m.prim_dwords, + ) + }; + if topology != 2 { + return Err("a mesh shader not drawing triangles"); + } + if threads == 0 || threads > 1024 || raw_verts > 256 || raw_prims > 256 { + return Err("a mesh shader beyond the host's limits"); + } + let max_vertices = raw_verts.min(threads); + let max_primitives = raw_prims.min(threads); + if max_vertices == 0 || max_primitives == 0 { + return Err("an empty mesh shader output"); + } + let index_bytes = max_primitives * 4; + let vertex_stride_bytes = vertex_dwords * 4; + let prim_offset_bytes = index_bytes + max_vertices * vertex_stride_bytes; + let prim_stride_bytes = prim_dwords * 4; + let group_bytes = prim_offset_bytes + max_primitives * prim_stride_bytes; + + let e = self.s.entry; + let i32t = self.s.t.i32; + let uav = self.s.emu_uav_handle(); + let k0 = self.s.m.i32(0); + let local_group = self.s.op(e, "groupId.i32", Attr::ReadNone, i32t, 94, &[k0]); + let flat = self.mesh_thread(); + let group_stride = self.s.m.i32(group_bytes); + let group_base = self.s.m.bin(e, Bin::Mul, local_group, group_stride); + let flat_lt_verts = (threads > max_vertices).then(|| { + let mv = self.s.m.i32(max_vertices); + self.s.m.cmp(e, pred::IULT, flat, mv) + }); + let flat_lt_prims = (threads > max_primitives).then(|| { + let mp = self.s.m.i32(max_primitives); + self.s.m.cmp(e, pred::IULT, flat, mp) + }); + let m = self.mesh_emu.as_mut().expect("mesh emu"); + m.max_vertices = max_vertices; + m.max_primitives = max_primitives; + m.vals = Some(MeshEmuVals { + uav, + local_group, + group_base, + flat_lt_verts, + flat_lt_prims, + index_bytes, + vertex_stride_bytes, + prim_offset_bytes, + prim_stride_bytes, + }); + Ok(()) + } + + /// Initializes every primitive index word in the group slice as culled + /// (`bit 31 = 1`) so unexported slots never draw stale data. + fn mesh_emu_prologue(&mut self) { + let (uav, group_base, flat_lt_prims) = { + let v = self + .mesh_emu + .as_ref() + .expect("mesh emu") + .vals + .as_ref() + .expect("mesh emu init"); + (v.uav, v.group_base, v.flat_lt_prims) + }; + let flat = self.mesh_thread(); + let at = self.begin_guarded(flat_lt_prims); + let c = self.cur; + let k2 = self.s.m.i32(2); + let byte_off = self.s.m.bin(c, Bin::Shl, flat, k2); + let addr = self.s.m.bin(c, Bin::Add, group_base, byte_off); + let undef = self.s.m.undef(self.s.t.i32); + let culled = self.s.m.i32(0x8000_0000); + let mask1 = self.s.m.i8(1); + let align4 = self.s.m.i32(4); + let void = self.s.t.void; + self.s.op( + c, + "rawBufferStore.i32", + Attr::NoUnwind, + void, + 140, + &[uav, addr, undef, culled, undef, undef, undef, mask1, align4], + ); + self.end_guarded(at, &[]); + } + + fn combine_guards(&mut self, a: Option, b: Option) -> Option { + match (a, b) { + (Some(x), Some(y)) => Some(self.s.m.bin(self.cur, Bin::And, x, y)), + (Some(x), None) | (None, Some(x)) => Some(x), + (None, None) => None, + } + } + + /// Emulated mesh: `exp prim` writes the packed primitive index word + /// (preserving bit 31 as the cull flag) to `u0, space 2`. + fn emit_indices_emu(&mut self, e: &Export, guard: Option) -> Result<(), Why> { + let v = e.values[0].ok_or("a primitive export without its indices")?; + let x = self.i32_of(v)?; + let (uav, group_base, flat_lt_prims) = { + let v = self + .mesh_emu + .as_ref() + .expect("mesh emu") + .vals + .as_ref() + .expect("mesh emu init"); + (v.uav, v.group_base, v.flat_lt_prims) + }; + let guard = self.combine_guards(guard, flat_lt_prims); + let flat = self.mesh_thread(); + let at = self.begin_guarded(guard); + let c = self.cur; + let k2 = self.s.m.i32(2); + let byte_off = self.s.m.bin(c, Bin::Shl, flat, k2); + let addr = self.s.m.bin(c, Bin::Add, group_base, byte_off); + let undef = self.s.m.undef(self.s.t.i32); + let mask1 = self.s.m.i8(1); + let align4 = self.s.m.i32(4); + let void = self.s.t.void; + self.s.op( + c, + "rawBufferStore.i32", + Attr::NoUnwind, + void, + 140, + &[uav, addr, undef, x, undef, undef, undef, mask1, align4], + ); + self.end_guarded(at, &[]); + Ok(()) + } + + /// Emulated mesh: stores vertex (`primitive == false`) or per-primitive + /// (`primitive == true`) exported scalars into `u0, space 2`, coalescing + /// contiguous dword slots up to 4 dwords per store. + fn store_mesh_emu_outputs( + &mut self, + guard: Option, + primitive: bool, + stores: &[(usize, u8, Value, Option)], + ) -> Result<(), Why> { + if stores.is_empty() { + return Ok(()); + } + let mut items: Vec<(u32, V, Option)> = Vec::with_capacity(stores.len()); + for &(id, col, value, half) in stores { + let x = self.i32_of(value)?; + let slot = { + let m = self.mesh_emu.as_mut().expect("mesh emu"); + let (sigs, offsets) = if primitive { + (&mut m.prim_sigs, &m.prim_offsets) + } else { + (&mut m.vertex_sigs, &m.vertex_offsets) + }; + sigs[id].usage |= 1 << col; + offsets[id] + u32::from(col) + }; + items.push((slot, x, half)); + } + items.sort_by_key(|&(slot, _, _)| slot); + let mut deduped: Vec<(u32, V, Option)> = Vec::with_capacity(items.len()); + for item in items { + if let Some(last) = deduped.last_mut() + && last.0 == item.0 + { + *last = item; + } else { + deduped.push(item); + } + } + let (uav, group_base, bound_guard, base_offset, stride_bytes) = { + let v = self + .mesh_emu + .as_ref() + .expect("mesh emu") + .vals + .as_ref() + .expect("mesh emu init"); + if primitive { + ( + v.uav, + v.group_base, + v.flat_lt_prims, + v.prim_offset_bytes, + v.prim_stride_bytes, + ) + } else { + ( + v.uav, + v.group_base, + v.flat_lt_verts, + v.index_bytes, + v.vertex_stride_bytes, + ) + } + }; + let guard = self.combine_guards(guard, bound_guard); + let flat = self.mesh_thread(); + let at = self.begin_guarded(guard); + let c = self.cur; + let mut converted = Vec::with_capacity(deduped.len()); + for (slot, mut x, half) in deduped { + if let Some(high) = half { + if high { + let k16 = self.s.m.i32(16); + x = self.s.m.bin(c, Bin::LShr, x, k16); + } + let f32t = self.s.t.f32; + let f = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]); + x = self.as_int(f); + } + converted.push((slot, x)); + } + let stride = self.s.m.i32(stride_bytes); + let rel = self.s.m.bin(c, Bin::Mul, flat, stride); + let off = if base_offset == 0 { + rel + } else { + let base_k = self.s.m.i32(base_offset); + self.s.m.bin(c, Bin::Add, base_k, rel) + }; + let rec_base = self.s.m.bin(c, Bin::Add, group_base, off); + let undef = self.s.m.undef(self.s.t.i32); + let align4 = self.s.m.i32(4); + let void = self.s.t.void; + let mut idx = 0; + while idx < converted.len() { + let start_slot = converted[idx].0; + let mut len = 1usize; + while len < 4 + && idx + len < converted.len() + && converted[idx + len].0 == start_slot + len as u32 + { + len += 1; + } + let addr = if start_slot == 0 { + rec_base + } else { + let disp = self.s.m.i32(start_slot * 4); + self.s.m.bin(c, Bin::Add, rec_base, disp) + }; + let v0 = converted[idx].1; + let v1 = if len > 1 { converted[idx + 1].1 } else { undef }; + let v2 = if len > 2 { converted[idx + 2].1 } else { undef }; + let v3 = if len > 3 { converted[idx + 3].1 } else { undef }; + let mask = self.s.m.i8((1u8 << len) - 1); + self.s.op( + c, + "rawBufferStore.i32", + Attr::NoUnwind, + void, + 140, + &[uav, addr, undef, v0, v1, v2, v3, mask, align4], + ); + idx += len; + } + self.end_guarded(at, &[]); + Ok(()) + } + fn mesh_group_emu(&mut self) -> Val { + let m = self.mesh_emu.as_mut().expect("mesh emu"); + m.reads_group_id = true; + let local_group = m.vals.as_ref().expect("mesh emu init").local_group; + let cbv = self.s.emu_cbv_handle(); + let srv = self.s.emu_srv_handle(); + let c = self.cur; + let i32t = self.s.t.i32; + let k0 = self.s.m.i32(0); + let base_ret = self.s.op( + c, + "cbufferLoadLegacy.i32", + Attr::ReadOnly, + self.s.t.cbuf_ret, + 59, + &[cbv, k0], + ); + let base = self.s.m.extract(c, base_ret, 0); + let flag = self.s.m.i32(super::INDIRECT_SLOT_MAP_FLAG); + let is_map = self.s.m.cmp(c, pred::EQ, base, flag); + let map_bb = self.s.m.new_block(); + let add_bb = self.s.m.new_block(); + let join_bb = self.s.m.new_block(); + self.s.m.terminate(c, Term::CondBr(is_map, map_bb, add_bb)); + + let k2 = self.s.m.i32(2); + let off = self.s.m.bin(map_bb, Bin::Shl, local_group, k2); + let undef = self.s.m.undef(i32t); + let mask1 = self.s.m.i8(1); + let align4 = self.s.m.i32(4); + let r = self.s.op( + map_bb, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[srv, off, undef, mask1, align4], + ); + let f = self.s.m.extract(map_bb, r, 0); + let g_map = self.s.m.cast(map_bb, Cast::Bitcast, f, i32t); + self.s.m.terminate(map_bb, Term::Br(join_bb)); + + let g_add = self.s.m.bin(add_bb, Bin::Add, local_group, base); + self.s.m.terminate(add_bb, Term::Br(join_bb)); + + let g = self.s.m.phi(join_bb, i32t); + self.s.m.set_phi(g, vec![(g_map, map_bb), (g_add, add_bb)]); + let n = self.s.m.i32(self.x.mesh_stride); + let res = self.s.m.bin(join_bb, Bin::Mul, g, n); + self.cur = join_bb; + Val::I32(res) + } + +} diff --git a/crates/victory-shader/src/emit/lower/tests.rs b/crates/victory-shader/src/emit/lower/tests.rs index d010b86..643869c 100644 --- a/crates/victory-shader/src/emit/lower/tests.rs +++ b/crates/victory-shader/src/emit/lower/tests.rs @@ -159,6 +159,7 @@ fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { prims: vec![], mesh_stride: 0, crumbs: None, + emulate_mesh: false, }) .map(|_| ()) } @@ -210,6 +211,7 @@ fn lower_wave( prims: vec![], mesh_stride: 0, crumbs: None, + emulate_mesh: false, }) } @@ -250,6 +252,7 @@ fn counted_loop(crumbs: Option) -> Lowered { outputs: vec![], prims: vec![], mesh_stride: 0, + emulate_mesh: false, crumbs, }) .unwrap() @@ -419,6 +422,7 @@ fn perm_features(selector: u32) -> u64 { prims: vec![], mesh_stride: 0, crumbs: None, + emulate_mesh: false, }) .unwrap(); @@ -1045,6 +1049,7 @@ fn first_half_of_interpolation_stays_missing_when_live_and_lowers_when_overwritt prims: vec![], mesh_stride: 0, crumbs: None, + emulate_mesh: false, }) }; // Overwritten on the s0 != 0 branch: p1 never reaches exp. @@ -1743,6 +1748,7 @@ fn constant_64_bit_compares_lower_without_int64() { prims: vec![], mesh_stride: 0, crumbs: None, + emulate_mesh: false, }) .unwrap(); let sfi0 = crate::dxbc::Container::parse(&emitted.dxil) diff --git a/crates/victory-shader/src/emit/mesh_emu.rs b/crates/victory-shader/src/emit/mesh_emu.rs new file mode 100644 index 0000000..a2f1b53 --- /dev/null +++ b/crates/victory-shader/src/emit/mesh_emu.rs @@ -0,0 +1,1365 @@ +//! Mesh shader emulation (`cs_6_6` + generated unpack `vs_6_6`) for SM 6.6 +//! GPUs that lack hardware mesh shaders (`D3D12_MESH_SHADER_TIER_NOT_SUPPORTED`). +//! +//! An emulated mesh program (`MeshMode::Emulate`) compiles as a compute shader +//! (`cs_6_6`) with the console's `[numthreads(threads, 1, 1)]` and LDS, writing +//! packed primitive indices, per-vertex attributes (`OSG1`), and per-primitive +//! attributes (`PSG1`) into a fixed-stride per-group slice of a raw UAV buffer +//! at `u0` in [`MESH_EMU_SPACE`]: +//! +//! ```text +//! group g (byte offset = g * group_bytes): +//! [0 .. index_bytes) max_primitives x u32 (v0 | v1<<10 | v2<<20 | cull<<31) +//! [index_bytes .. prim_offset_bytes) max_vertices x vertex_dwords x u32 +//! [prim_offset_bytes .. group_bytes) max_primitives x prim_dwords x u32 +//! ``` +//! +//! [`unpack_vertex_shader`] builds the matching `vs_6_6` that reads that raw +//! buffer at `t0` in [`MESH_EMU_SPACE`] by `SV_VertexID`, culls bit-31 primitives via quiet +//! `NaN` on `SV_Position`, and emits every vertex and per-primitive attribute in +//! the exact signature layout the title's pixel shader (`ps_6_6`) expects. + +use std::collections::BTreeMap; + +use super::bitcode::{Attr, Bin, Cast, Term, pred}; +use super::container::SigElement; +use super::shader::Shader; +use crate::ShaderError; +use crate::dxbc::{Container, FourCC, u32_at}; + +/// Sentinel `base_group` value in `b0` in [`MESH_EMU_SPACE`] telling an emulated mesh +/// compute shader that reads `SV_GroupID` to look up its per-record group ID +/// in the `slot_map` raw SRV (`t0` in the same space). +pub const INDIRECT_SLOT_MAP_FLAG: u32 = u32::MAX; + +/// Whether a console mesh shader (`HwStage::Ms`) translates to native `ms_6_6` +/// or to a compute + vertex emulation pair. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum MeshMode { + #[default] + Native, + Emulate, +} + +/// One vertex or per-primitive attribute stored in the emulated mesh buffer. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MeshOutput { + pub name: String, + pub index: u32, + pub kind: u8, + pub comp: u8, + pub interp: u8, + pub row: Option, + pub col: u8, + pub cols: u8, + /// Dword offset of channel 0 from the start of a vertex or primitive record. + pub dword_offset: u32, +} + +/// Memory layout and metadata emitted by an emulated mesh compute shader. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MeshEmu { + pub threads: u32, + pub max_vertices: u32, + pub max_primitives: u32, + pub vertex_dwords: u32, + pub prim_dwords: u32, + pub reads_group_id: bool, + pub vertex_outputs: Vec, + pub prim_outputs: Vec, +} + +impl MeshEmu { + /// Bytes reserved per group for packed primitive index words. + pub fn index_bytes(&self) -> u32 { + self.max_primitives * 4 + } + + /// Byte offset of vertex attribute records within one group slice. + pub fn vertex_offset_bytes(&self) -> u32 { + self.index_bytes() + } + + /// Stride in bytes of one vertex record. + pub fn vertex_stride_bytes(&self) -> u32 { + self.vertex_dwords * 4 + } + + /// Byte offset of per-primitive attribute records within one group slice. + pub fn prim_offset_bytes(&self) -> u32 { + self.index_bytes() + self.max_vertices * self.vertex_stride_bytes() + } + + /// Stride in bytes of one per-primitive record. + pub fn prim_stride_bytes(&self) -> u32 { + self.prim_dwords * 4 + } + + /// Total bytes occupied by one threadgroup in the intermediate buffer. + pub fn group_bytes(&self) -> u32 { + self.prim_offset_bytes() + self.max_primitives * self.prim_stride_bytes() + } +} + +#[derive(Clone, Copy)] +enum OutputSource { + Vertex { dword_offset: u32, avail_cols: u8 }, + Prim { dword_offset: u32, avail_cols: u8 }, + Zero, +} + +struct UnpackOutput { + sig: SigElement, + src: OutputSource, +} + +/// Generates a `vs_6_6` DXIL container that unpacks `emu`'s raw buffer (`t0, +/// space 2`) by `SV_VertexID` into the input signature expected by `ps_dxil` +/// (or rasterizer system values only for depth-only pipelines). +pub fn unpack_vertex_shader(emu: &MeshEmu, ps_dxil: Option<&[u8]>) -> Result, ShaderError> { + if emu.max_vertices == 0 || emu.max_primitives == 0 { + return Err(ShaderError::Unsupported { + offset: 0, + what: "an empty mesh shader output", + }); + } + + let plan = build_output_plan(emu, ps_dxil)?; + + let mut s = Shader::new(false); + s.inputs = vec![SigElement { + name: "SV_VertexID".into(), + index: 0, + kind: 1, + comp: 5, + interp: 0, + row: Some(0), + col: 0, + cols: 1, + usage: 1, + half: false, + }]; + s.outputs = plan.iter().map(|o| o.sig.clone()).collect(); + + let buf = s.emu_srv_handle(); + let e = s.entry; + let i32t = s.t.i32; + let undef_i32 = s.m.undef(i32t); + let vid = { + let zero = s.m.i32(0); + let z8 = s.m.i8(0); + s.op( + e, + "loadInput.i32", + Attr::ReadNone, + i32t, + 4, + &[zero, zero, z8, undef_i32], + ) + }; + + let k3 = s.m.i32(3); + let tri = s.m.bin(e, Bin::UDiv, vid, k3); + let corner = s.m.bin(e, Bin::URem, vid, k3); + let (group_idx, prim_idx) = if emu.max_primitives == 1 { + (tri, s.m.i32(0)) + } else { + let mp = s.m.i32(emu.max_primitives); + ( + s.m.bin(e, Bin::UDiv, tri, mp), + s.m.bin(e, Bin::URem, tri, mp), + ) + }; + + let group_stride = s.m.i32(emu.group_bytes()); + let group_base = s.m.bin(e, Bin::Mul, group_idx, group_stride); + let k2 = s.m.i32(2); + let prim_byte = s.m.bin(e, Bin::Shl, prim_idx, k2); + let idx_off = s.m.bin(e, Bin::Add, group_base, prim_byte); + + let idx_load = { + let mask1 = s.m.i8(1); + let align4 = s.m.i32(4); + s.op( + e, + "rawBufferLoad.f32", + Attr::ReadOnly, + s.t.res_ret, + 139, + &[buf, idx_off, undef_i32, mask1, align4], + ) + }; + let idx_f = s.m.extract(e, idx_load, 0); + let packed = s.m.cast(e, Cast::Bitcast, idx_f, i32t); + let zero_i = s.m.i32(0); + let culled = s.m.cmp(e, pred::SLT, packed, zero_i); + + let cull_bb = s.m.new_block(); + let draw_bb = s.m.new_block(); + s.m.terminate(e, Term::CondBr(culled, cull_bb, draw_bb)); + + // Culled primitive: write quiet NaN to SV_Position so the rasterizer drops + // the triangle regardless of depth-clip settings, and zero other outputs. + for (id, out) in plan.iter().enumerate() { + for c in 0..out.sig.cols { + let (suffix, val) = if out.sig.kind == 3 { + (".f32", s.m.f32(0x7FC0_0000)) + } else if out.sig.comp == 9 { + (".f32", s.m.f32(0)) + } else { + (".i32", zero_i) + }; + let id_k = s.m.i32(id as u32); + let col_k = s.m.i8(c); + s.op( + cull_bb, + &format!("storeOutput{suffix}"), + Attr::NoUnwind, + s.t.void, + 5, + &[id_k, zero_i, col_k, val], + ); + } + } + s.m.terminate(cull_bb, Term::Ret); + + // Active primitive: load vertex and/or per-primitive attributes and store them. + let needs_vert = plan + .iter() + .any(|o| matches!(o.src, OutputSource::Vertex { .. })); + let needs_prim = plan + .iter() + .any(|o| matches!(o.src, OutputSource::Prim { .. })); + + let v_base = if needs_vert { + let k10 = s.m.i32(10); + let shift = s.m.bin(draw_bb, Bin::Mul, corner, k10); + let shifted = s.m.bin(draw_bb, Bin::LShr, packed, shift); + let mask = s.m.i32(0x3FF); + let v_raw = s.m.bin(draw_bb, Bin::And, shifted, mask); + let mv = s.m.i32(emu.max_vertices); + let in_bounds = s.m.cmp(draw_bb, pred::IULT, v_raw, mv); + let last_v = s.m.i32(emu.max_vertices - 1); + let v_idx = s.m.select(draw_bb, in_bounds, v_raw, last_v); + let v_stride = s.m.i32(emu.vertex_stride_bytes()); + let v_rel = s.m.bin(draw_bb, Bin::Mul, v_idx, v_stride); + let v_off_base = s.m.i32(emu.vertex_offset_bytes()); + let v_off = s.m.bin(draw_bb, Bin::Add, v_off_base, v_rel); + Some(s.m.bin(draw_bb, Bin::Add, group_base, v_off)) + } else { + None + }; + + let p_base = if needs_prim { + let p_stride = s.m.i32(emu.prim_stride_bytes()); + let p_rel = s.m.bin(draw_bb, Bin::Mul, prim_idx, p_stride); + let p_off_base = s.m.i32(emu.prim_offset_bytes()); + let p_off = s.m.bin(draw_bb, Bin::Add, p_off_base, p_rel); + Some(s.m.bin(draw_bb, Bin::Add, group_base, p_off)) + } else { + None + }; + + let zero_f = s.m.f32(0); + let align4 = s.m.i32(4); + for (id, out) in plan.iter().enumerate() { + let (base, dword_offset, avail_cols) = match out.src { + OutputSource::Vertex { + dword_offset, + avail_cols, + } => (v_base.expect("vertex base"), dword_offset, avail_cols), + OutputSource::Prim { + dword_offset, + avail_cols, + } => (p_base.expect("prim base"), dword_offset, avail_cols), + OutputSource::Zero => { + for c in 0..out.sig.cols { + let (suffix, val) = if out.sig.comp == 9 { + (".f32", zero_f) + } else { + (".i32", zero_i) + }; + let id_k = s.m.i32(id as u32); + let col_k = s.m.i8(c); + s.op( + draw_bb, + &format!("storeOutput{suffix}"), + Attr::NoUnwind, + s.t.void, + 5, + &[id_k, zero_i, col_k, val], + ); + } + continue; + } + }; + + let load_cols = out.sig.cols.min(avail_cols).min(4); + let loaded = if load_cols > 0 { + let addr = if dword_offset == 0 { + base + } else { + let disp = s.m.i32(dword_offset * 4); + s.m.bin(draw_bb, Bin::Add, base, disp) + }; + let mask = s.m.i8((1u8 << load_cols) - 1); + Some(s.op( + draw_bb, + "rawBufferLoad.f32", + Attr::ReadOnly, + s.t.res_ret, + 139, + &[buf, addr, undef_i32, mask, align4], + )) + } else { + None + }; + + for c in 0..out.sig.cols { + let (suffix, val) = match loaded { + Some(agg) if c < load_cols => { + let f = s.m.extract(draw_bb, agg, u32::from(c)); + if out.sig.comp == 9 { + (".f32", f) + } else { + (".i32", s.m.cast(draw_bb, Cast::Bitcast, f, i32t)) + } + } + _ if out.sig.comp == 9 => (".f32", zero_f), + _ => (".i32", zero_i), + }; + let id_k = s.m.i32(id as u32); + let col_k = s.m.i8(c); + s.op( + draw_bb, + &format!("storeOutput{suffix}"), + Attr::NoUnwind, + s.t.void, + 5, + &[id_k, zero_i, col_k, val], + ); + } + } + s.m.terminate(draw_bb, Term::Ret); + Ok(s.finish()) +} + +fn build_output_plan( + emu: &MeshEmu, + ps_dxil: Option<&[u8]>, +) -> Result, ShaderError> { + let mut plan = Vec::new(); + let mut occupied: BTreeMap = BTreeMap::new(); + let mut next_row: u32 = 0; + + fn occupy(occupied: &mut BTreeMap, next_row: &mut u32, row: u32, col: u8, cols: u8) { + let mask = ((1u8 << cols.min(4)) - 1) << col.min(3); + *occupied.entry(row).or_default() |= mask; + *next_row = (*next_row).max(row + 1); + } + + let mut emitted_sys: Vec<(u8, u32)> = Vec::new(); + + if let Some(ps_bytes) = ps_dxil { + let c = Container::parse(ps_bytes)?; + let ps_inputs = match c.part(FourCC::ISG1) { + Some(part) => super::signature(part.data)?, + None => Vec::new(), + }; + let ps_interps = c + .part(FourCC::PSV0) + .map(|p| psv_input_interps(p.data)) + .unwrap_or_default(); + + for pi in &ps_inputs { + if !matches!(pi.kind, 0 | 3 | 4 | 5 | 6 | 7) { + continue; + } + let (found, from_prim) = match find_mesh_output(&emu.vertex_outputs, pi) { + Some(o) => (Some(o), false), + None => match find_mesh_output(&emu.prim_outputs, pi) { + Some(o) => (Some(o), true), + None => (None, false), + }, + }; + let row = pi.row.unwrap_or(next_row); + let (col, cols) = if pi.kind == 3 { + (0, 4) + } else { + (pi.col, pi.cols) + }; + let src = match found { + Some(o) if pi.kind == 3 => OutputSource::Vertex { + dword_offset: o.dword_offset, + avail_cols: o.cols, + }, + Some(o) if col >= o.col && (col - o.col) < o.cols => { + let skip = u32::from(col - o.col); + let avail_cols = o.cols - skip as u8; + let dword_offset = o.dword_offset + skip; + if from_prim { + OutputSource::Prim { + dword_offset, + avail_cols, + } + } else { + OutputSource::Vertex { + dword_offset, + avail_cols, + } + } + } + _ => OutputSource::Zero, + }; + + let ps_interp = ps_interps + .iter() + .find(|&&(r, c, k, _)| r == row && c == pi.col && k == pi.kind) + .map(|&(_, _, _, m)| m) + .unwrap_or(0); + let interp = match pi.kind { + 3 => 4, + 4 | 5 => 1, + 6 | 7 => 2, + _ => match ps_interp { + 1 => 1, + 2 | 3 | 6 => 2, + 4 | 5 | 7 => 4, + _ if from_prim => 1, + _ if pi.comp == 9 => 2, + _ => 1, + }, + }; + + if pi.kind != 0 { + emitted_sys.push((pi.kind, pi.index)); + } + occupy(&mut occupied, &mut next_row, row, col, cols); + plan.push(UnpackOutput { + sig: SigElement { + name: pi.name.clone(), + index: pi.index, + kind: pi.kind, + comp: pi.comp, + interp, + row: Some(row), + col, + cols, + usage: (1u8 << cols) - 1, + half: false, + }, + src, + }); + } + } + + for (outputs, from_prim) in [(&emu.vertex_outputs, false), (&emu.prim_outputs, true)] { + for o in outputs { + if !matches!(o.kind, 3..=7) { + continue; + } + if emitted_sys.contains(&(o.kind, o.index)) { + continue; + } + emitted_sys.push((o.kind, o.index)); + let mask = ((1u8 << o.cols.min(4)) - 1) << o.col.min(3); + let (row, col) = match o.row { + Some(r) if (occupied.get(&r).copied().unwrap_or(0) & mask) == 0 => (r, o.col), + _ => (next_row, 0), + }; + occupy(&mut occupied, &mut next_row, row, col, o.cols); + let interp = match o.kind { + 3 => 4, + 4 | 5 => 1, + _ if from_prim => 1, + _ => 2, + }; + let src = if from_prim { + OutputSource::Prim { + dword_offset: o.dword_offset, + avail_cols: o.cols, + } + } else { + OutputSource::Vertex { + dword_offset: o.dword_offset, + avail_cols: o.cols, + } + }; + plan.push(UnpackOutput { + sig: SigElement { + name: o.name.clone(), + index: o.index, + kind: o.kind, + comp: o.comp, + interp, + row: Some(row), + col, + cols: o.cols, + usage: (1u8 << o.cols) - 1, + half: false, + }, + src, + }); + } + } + + if !plan.iter().any(|o| o.sig.kind == 3) { + let row = next_row; + plan.push(UnpackOutput { + sig: SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 4, + row: Some(row), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }, + src: OutputSource::Zero, + }); + } + + Ok(plan) +} + +fn find_mesh_output<'a>(outputs: &'a [MeshOutput], pi: &SigElement) -> Option<&'a MeshOutput> { + let matches = |o: &&MeshOutput| { + if pi.kind != 0 { + o.kind == pi.kind && o.index == pi.index + } else { + o.kind == 0 && o.index == pi.index && o.name.eq_ignore_ascii_case(&pi.name) + } + }; + outputs + .iter() + .find(|o| matches(o) && o.col == pi.col) + .or_else(|| outputs.iter().find(matches)) +} + +/// Reads `(row, col, kind, interp)` tuples for `PSV0` input signature elements. +fn psv_input_interps(psv: &[u8]) -> Vec<(u32, u8, u8, u8)> { + let Ok(info_size) = u32_at(psv, 0).map(|n| n as usize) else { + return Vec::new(); + }; + if info_size < 32 || psv.len() < 4 + info_size { + return Vec::new(); + } + let input_count = usize::from(psv[4 + 28]); + let mut at = 4 + info_size; + let Ok(binding_count) = u32_at(psv, at).map(|n| n as usize) else { + return Vec::new(); + }; + at += 4; + if binding_count > 0 { + let Ok(entry_size) = u32_at(psv, at).map(|n| n as usize) else { + return Vec::new(); + }; + at += 4; + at = match binding_count + .checked_mul(entry_size) + .and_then(|n| at.checked_add(n)) + { + Some(next) if next <= psv.len() => next, + _ => return Vec::new(), + }; + } + let Ok(string_bytes) = u32_at(psv, at).map(|n| n as usize) else { + return Vec::new(); + }; + at += 4; + if at + string_bytes > psv.len() { + return Vec::new(); + } + at += string_bytes; + let Ok(indices_count) = u32_at(psv, at).map(|n| n as usize) else { + return Vec::new(); + }; + at += 4; + if at + indices_count * 4 > psv.len() { + return Vec::new(); + } + at += indices_count * 4; + if at + 4 > psv.len() { + return Vec::new(); + } + let Ok(elem_size) = u32_at(psv, at).map(|n| n as usize) else { + return Vec::new(); + }; + at += 4; + if elem_size < 14 { + return Vec::new(); + } + let mut out = Vec::new(); + for k in 0..input_count { + let Some(e) = psv.get(at + k * elem_size..at + (k + 1) * elem_size) else { + break; + }; + let alloc = e[10]; + if alloc & 0x40 == 0 { + continue; + } + let row = u32::from(e[9]); + let col = (alloc >> 4) & 3; + let kind = e[11]; + let interp = e[13]; + out.push((row, col, kind, interp)); + } + out +} + +#[cfg(test)] +mod unpack_tests { + use super::*; + + #[test] + fn depth_only_unpack_shader_is_a_container() { + let emu = MeshEmu { + threads: 32, + max_vertices: 3, + max_primitives: 1, + vertex_dwords: 4, + prim_dwords: 0, + reads_group_id: false, + vertex_outputs: vec![MeshOutput { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 4, + row: Some(0), + col: 0, + cols: 4, + dword_offset: 0, + }], + prim_outputs: Vec::new(), + }; + let vs = unpack_vertex_shader(&emu, None).unwrap(); + let c = Container::parse(&vs).unwrap(); + let osg = super::super::signature(c.part(FourCC::OSG1).unwrap().data).unwrap(); + assert_eq!(osg.len(), 1); + assert_eq!(osg[0].name, "SV_Position"); + assert_eq!(osg[0].kind, 3); + } +} + +#[cfg(all(test, windows))] +mod tests { + use super::super::validator::Validator; + use super::*; + + fn fake_ps_container(inputs: &[SigElement]) -> Vec { + let mut s = Shader::new(true); + s.inputs = inputs.to_vec(); + s.outputs = vec![SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }]; + let b = s.entry; + let zero = s.m.f32(0); + for c in 0..4u8 { + let zero_i = s.m.i32(0); + let col_k = s.m.i8(c); + s.op( + b, + "storeOutput.f32", + Attr::NoUnwind, + s.t.void, + 5, + &[zero_i, zero_i, col_k, zero], + ); + } + s.m.terminate(b, Term::Ret); + s.finish() + } + + #[test] + fn unpack_vs_signature_matches_ps_with_per_primitive_outputs() { + let emu = MeshEmu { + threads: 32, + max_vertices: 16, + max_primitives: 8, + vertex_dwords: 8, + prim_dwords: 4, + reads_group_id: false, + vertex_outputs: vec![ + MeshOutput { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 4, + row: Some(0), + col: 0, + cols: 4, + dword_offset: 0, + }, + MeshOutput { + name: "COLOR".into(), + index: 0, + kind: 0, + comp: 9, + interp: 2, + row: Some(1), + col: 0, + cols: 4, + dword_offset: 4, + }, + ], + prim_outputs: vec![MeshOutput { + name: "PRIMDATA".into(), + index: 0, + kind: 0, + comp: 9, + interp: 1, + row: Some(0), + col: 0, + cols: 4, + dword_offset: 0, + }], + }; + + // PS places COLOR0 at row 0 (colliding with MS SV_Position row 0!) + // and PRIMDATA at row 1, without reading SV_Position. + let ps = fake_ps_container(&[ + SigElement { + name: "COLOR".into(), + index: 0, + kind: 0, + comp: 9, + interp: 2, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }, + SigElement { + name: "PRIMDATA".into(), + index: 0, + kind: 0, + comp: 9, + interp: 1, + row: Some(1), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }, + ]); + + let mut vs = unpack_vertex_shader(&emu, Some(&ps)).unwrap(); + let c = Container::parse(&vs).unwrap(); + let osg1 = super::super::signature(c.part(FourCC::OSG1).unwrap().data).unwrap(); + assert_eq!(osg1.len(), 3); + assert_eq!(osg1[0].name, "COLOR"); + assert_eq!(osg1[0].row, Some(0)); + assert_eq!(osg1[1].name, "PRIMDATA"); + assert_eq!(osg1[1].row, Some(1)); + assert_eq!(osg1[2].name, "SV_Position"); + assert_eq!(osg1[2].row, Some(2)); + assert_eq!( + psv_input_interps(c.part(FourCC::PSV0).unwrap().data), + vec![(0, 0, 1, 0)] + ); + let ps_c = Container::parse(&ps).unwrap(); + assert_eq!( + psv_input_interps(ps_c.part(FourCC::PSV0).unwrap().data), + vec![(0, 0, 0, 2), (1, 0, 0, 1)] + ); + + // Depth-only pipeline (ps == None) still emits SV_Position. + let mut depth_vs = unpack_vertex_shader(&emu, None).unwrap(); + let dc = Container::parse(&depth_vs).unwrap(); + let dosg = super::super::signature(dc.part(FourCC::OSG1).unwrap().data).unwrap(); + assert_eq!(dosg.len(), 1); + assert_eq!(dosg[0].kind, 3); + + if let Ok(mut v) = Validator::load(Validator::default_path().as_deref()) { + v.validate(&mut vs).unwrap(); + v.validate(&mut depth_vs).unwrap(); + } + } + + use super::super::host::{EmulatedMeshDraw, Host}; + use super::super::{HostShader, emit_with}; + use crate::native::{HwStage, MeshIo, NativeProgram, PsInput, StageIo, Usage, VsOutput}; + use crate::{io, ir, resource, structure}; + + const S_ENDPGM: u32 = 0xBF81_0000; + const S_BARRIER: u32 = 0xBF8A_0000; + + const fn sgpr(n: u8) -> u16 { + n as u16 + } + + const fn vgpr(n: u8) -> u16 { + 256 + n as u16 + } + + const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 { + 0x7E00_0000 | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF) + } + + const fn vop1_lit(op: u16, vdst: u8, lit: u32) -> [u32; 2] { + [vop1(op, vdst, 0xFF), lit] + } + + const fn vop2(op: u16, vdst: u8, src0: u16, vsrc1: u8) -> u32 { + (op as u32 & 0x3F) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) + } + + const fn vopc(op: u16, src0: u16, vsrc1: u8) -> u32 { + 0x7C00_0000 | (op as u32 & 0xFF) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) + } + + const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] { + [ + 0x35 << 26 | (op as u32 & 0x3FF) << 16 | vdst as u32, + (src0 as u32 & 0x1FF) | (src1 as u32 & 0x1FF) << 9 | (src2 as u32 & 0x1FF) << 18, + ] + } + + const fn ds(op: u8, vdst: u8, vaddr: u8, vdata0: u8, vdata1: u8, offset: u16) -> [u32; 2] { + [ + 0xD800_0000 | (op as u32) << 18 | offset as u32, + (vdst as u32) << 24 | (vdata1 as u32) << 16 | (vdata0 as u32) << 8 | vaddr as u32, + ] + } + + const fn exp(target: u8, en: u8, v: [u8; 4], done: bool, vm: bool) -> [u32; 2] { + [ + 0x3E << 26 + | (vm as u32) << 12 + | (done as u32) << 11 + | (target as u32 & 0x3F) << 4 + | (en as u32 & 0xF), + (v[0] as u32) | (v[1] as u32) << 8 | (v[2] as u32) << 16 | (v[3] as u32) << 24, + ] + } + + const fn v_interp_mov_f32(vdst: u8, attr: u8, chan: u8) -> u32 { + 0xC800_0000 | (vdst as u32) << 18 | 2 << 16 | (attr as u32) << 10 | (chan as u32) << 8 | 2 + } + + fn sig_el(name: &str, kind: u8, comp: u8, row: Option, usage: u8) -> SigElement { + SigElement { + name: name.into(), + index: 0, + kind, + comp, + interp: 0, + row, + col: 0, + cols: 4, + usage, + half: false, + } + } + + fn compile_ms( + words: &[u32], + io_outputs: Vec, + osg1: &[SigElement], + psg1: &[SigElement], + (threads, max_vertices, max_primitives, lds_bytes): (u32, u32, u32, u32), + ) -> HostShader { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Ms, + wave64: false, + vgprs: 32, + layout: Vec::new(), + used: Vec::new(), + io: StageIo::Ms(MeshIo { + outputs: io_outputs, + clip_cntl: 0, + threads, + max_vertices, + max_primitives, + topology: 2, + lds_bytes, + }), + code, + }; + let osg_bytes = super::super::container::signature(osg1, false); + let psg_bytes = super::super::container::signature(psg1, false); + let container_bytes = + crate::dxbc::build(&[(FourCC::OSG1, &osg_bytes), (FourCC::PSG1, &psg_bytes)]); + let c = Container::parse(&container_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 raised = io::raise(&p, &native).unwrap(); + let shader = emit_with(&c, &native, &p, &st, &raised, &res, MeshMode::Emulate).unwrap(); + if let Ok(mut v) = Validator::load(Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("emulated mesh CS validation failed"); + } + shader + } + + fn compile_flat_ps(semantic_name: &str) -> HostShader { + let words = [ + v_interp_mov_f32(0, 0, 0), + v_interp_mov_f32(1, 0, 1), + v_interp_mov_f32(2, 0, 2), + v_interp_mov_f32(3, 0, 3), + exp(0, 0xF, [0, 1, 2, 3], true, true)[0], + exp(0, 0xF, [0, 1, 2, 3], true, true)[1], + S_ENDPGM, + ]; + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 8, + layout: Vec::new(), + used: Vec::new(), + io: StageIo::Ps { + inputs: vec![PsInput { + usage: Usage::Generic, + row: 0, + mask: 0xF, + attr: 0, + flat: true, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr: 0, + rsrc2: 0, + db_shader_control: 0, + patches: Vec::new(), + }, + code, + }; + let isg1 = + super::super::container::signature(&[sig_el(semantic_name, 0, 9, Some(0), 0xF)], true); + let osg1 = + super::super::container::signature(&[sig_el("SV_Target", 16, 9, Some(0), 0xF)], false); + let container_bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]); + let c = Container::parse(&container_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 raised = io::raise(&p, &native).unwrap(); + let shader = emit_with(&c, &native, &p, &st, &raised, &res, MeshMode::Emulate).unwrap(); + if let Ok(mut v) = Validator::load(Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("PS validation failed"); + } + shader + } + + fn run_on_hosts(mut f: impl FnMut(&str, &Host)) { + let _one = super::super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + ran += 1; + f(label, &host); + } + assert!( + ran > 0 || std::env::var("CI").is_err(), + "no SM 6.6 host available" + ); + } + + #[test] + fn emulated_mesh_draws_triangle_and_culls_bit31_and_unexported() { + let build_variant = |cull_prim0: bool| { + let mut words = Vec::new(); + // v0 = tid (0..7) + words.extend(vop3(0x365, 0, 193, 128, 0)); + // Default position: (-1, -1, 0.5, 1.0) + words.extend(vop1_lit(0x001, 1, (-1.0f32).to_bits())); + words.extend(vop1_lit(0x001, 2, (-1.0f32).to_bits())); + words.extend(vop1_lit(0x001, 3, 0.5f32.to_bits())); + words.extend(vop1_lit(0x001, 4, 1.0f32.to_bits())); + // Default color: RED (1, 0, 0, 1); scratch constants v10=3.0, v11=1.0, v12=0.0 + words.extend(vop1_lit(0x001, 5, 1.0f32.to_bits())); + words.extend(vop1_lit(0x001, 6, 0.0f32.to_bits())); + words.extend(vop1_lit(0x001, 7, 0.0f32.to_bits())); + words.extend(vop1_lit(0x001, 8, 1.0f32.to_bits())); + words.extend(vop1_lit(0x001, 10, 3.0f32.to_bits())); + words.extend(vop1_lit(0x001, 11, 1.0f32.to_bits())); + words.extend(vop1_lit(0x001, 12, 0.0f32.to_bits())); + // tid == 1 or tid == 4 -> pos.x = 3.0 + words.push(vopc(0x0C2, 129, 0)); + words.push(vop2(0x001, 1, vgpr(1), 10)); + words.push(vopc(0x0C2, 132, 0)); + words.push(vop2(0x001, 1, vgpr(1), 10)); + // tid == 2 or tid == 5 -> pos.y = 3.0 + words.push(vopc(0x0C2, 130, 0)); + words.push(vop2(0x001, 2, vgpr(2), 10)); + words.push(vopc(0x0C2, 133, 0)); + words.push(vop2(0x001, 2, vgpr(2), 10)); + // tid >= 3 (3 <= tid, i.e., 3 < tid + 1 or 2 < tid) -> green (0, 1, 0, 1) + words.push(vopc(0x0C1, 130, 0)); // 2 < v0 + words.push(vop2(0x001, 5, vgpr(5), 12)); + words.push(vop2(0x001, 6, vgpr(6), 11)); + words.extend(exp(12, 0xF, [1, 2, 3, 4], false, false)); + words.extend(exp(32, 0xF, [5, 6, 7, 8], false, false)); + // v9 = (3 | 4<<10 | 5<<20) | 0x8000_0000 (bit-31 culled green tri) + words.extend(vop1_lit(0x001, 9, 0x8050_1003)); + if !cull_prim0 { + words.extend(vop1_lit(0x001, 13, 0x0020_0400)); + words.push(vopc(0x0C2, 128, 0)); // v0 == 0 + words.push(vop2(0x001, 9, vgpr(9), 13)); + } + // Only tid < 2 (2 > v0) exports `exp prim`; slot 2 relies on prologue cull. + words.push(vopc(0x0C4, 130, 0)); // 2 > v0 + words.push(0xBE80_3C6A); // s_and_saveexec_b32 s0, vcc_lo + words.push(0xBF88_0002); // s_cbranch_execz +2 + words.extend(exp(20, 0x1, [9, 0, 0, 0], true, false)); + words.push(0x887E_007E); // s_or_b32 exec_lo, exec_lo, s0 + words.push(S_ENDPGM); + + compile_ms( + &words, + vec![VsOutput { + usage: Usage::Generic, + row: 0, + param: 0, + fp16: false, + pack2: false, + }], + &[ + sig_el("SV_Position", 3, 9, None, 0xF), + sig_el("COLOR", 0, 9, Some(0), 0xF), + ], + &[], + (8, 6, 3, 0), + ) + }; + + let ms_active = build_variant(false); + let ms_culled = build_variant(true); + let ps = compile_flat_ps("COLOR"); + let emu_active = ms_active.mesh_emu.as_ref().unwrap().clone(); + let emu_culled = ms_culled.mesh_emu.as_ref().unwrap().clone(); + + run_on_hosts(|label, host| { + let pipes_active = host.emulated_mesh_pipelines(&ms_active, &ps).unwrap(); + let pixels = host + .draw_emulated_mesh( + &pipes_active, + &EmulatedMeshDraw { + cs_roots: Vec::new(), + ps_roots: Vec::new(), + size: (8, 8), + groups: 1, + max_primitives: emu_active.max_primitives, + group_bytes: emu_active.group_bytes(), + base_group: 0, + slot_map: None, + }, + ) + .unwrap_or_else(|e| panic!("{label}: active draw failed: {e}")); + assert!( + pixels.iter().all(|&p| p == [1.0, 0.0, 0.0, 1.0]), + "{label}: expected full red, got {:?}", + pixels[0] + ); + + let pipes_culled = host.emulated_mesh_pipelines(&ms_culled, &ps).unwrap(); + let pixels = host + .draw_emulated_mesh( + &pipes_culled, + &EmulatedMeshDraw { + cs_roots: Vec::new(), + ps_roots: Vec::new(), + size: (8, 8), + groups: 1, + max_primitives: emu_culled.max_primitives, + group_bytes: emu_culled.group_bytes(), + base_group: 0, + slot_map: None, + }, + ) + .unwrap_or_else(|e| panic!("{label}: culled draw failed: {e}")); + assert!( + pixels.iter().all(|&p| p == [0.0, 0.0, 0.0, 0.0]), + "{label}: expected all culled, got {:?}", + pixels[0] + ); + }); + } + + #[test] + fn emulated_mesh_group_id_supports_base_group_and_slot_map() { + let mut words = Vec::new(); + // s2 = group_id (from v5 via v_readfirstlane_b32) + words.push(vop1(0x002, 2, vgpr(5))); + // v0 = tid (0..3) + words.extend(vop3(0x365, 0, 193, 128, 0)); + // v5 = float(s2), v6 = 0, v7 = 0, v8 = 1.0 -> COLOR0.r = group_id + words.push(vop1(0x006, 5, sgpr(2))); + words.extend(vop1_lit(0x001, 6, 0.0f32.to_bits())); + words.extend(vop1_lit(0x001, 7, 0.0f32.to_bits())); + words.extend(vop1_lit(0x001, 8, 1.0f32.to_bits())); + // If s2 == 36 (group 9 * mesh_stride 4): draw right triangle (0, 1), (2, 1), (0, -3) + // covering top-right; otherwise draw left triangle (-1, 1), (0, 1), (-1, -3) covering top-left. + // v10 = 36, v11 = s2; compare vcc = (v11 == 36) + words.push(vop1(0x001, 11, sgpr(2))); + words.extend(vop1_lit(0x001, 10, 36)); + // Base left x (-1.0), vs right x (0.0) in v12 + words.extend(vop1_lit(0x001, 1, (-1.0f32).to_bits())); + words.extend(vop1_lit(0x001, 12, 0.0f32.to_bits())); + words.push(vopc(0x0C2, vgpr(10), 11)); + words.push(vop2(0x001, 1, vgpr(1), 12)); // base x: -1 or 0 + // If tid == 1: x += 1.0 (left: -1->0) or +2.0 (right: 0->2) + words.extend(vop1_lit(0x001, 13, 1.0f32.to_bits())); + words.extend(vop1_lit(0x001, 14, 2.0f32.to_bits())); + words.push(vopc(0x0C2, vgpr(10), 11)); + words.push(vop2(0x001, 13, vgpr(13), 14)); // width: 1.0 or 2.0 + words.extend(vop2_add_f32_helper(14, 1, 13)); + words.push(vopc(0x0C2, 129, 0)); // tid == 1 + words.push(vop2(0x001, 1, vgpr(1), 14)); + // y: default 1.0, tid == 2 -> -3.0; z = 0.5, w = 1.0 + words.extend(vop1_lit(0x001, 2, 1.0f32.to_bits())); + words.extend(vop1_lit(0x001, 15, (-3.0f32).to_bits())); + words.push(vopc(0x0C2, 130, 0)); // tid == 2 + words.push(vop2(0x001, 2, vgpr(2), 15)); + words.extend(vop1_lit(0x001, 3, 0.5f32.to_bits())); + words.extend(vop1_lit(0x001, 4, 1.0f32.to_bits())); + + words.extend(exp(12, 0xF, [1, 2, 3, 4], false, false)); + words.extend(exp(32, 0xF, [5, 6, 7, 8], false, false)); + words.extend(vop1_lit(0x001, 9, 0x0020_0400)); + words.extend(exp(20, 0x1, [9, 0, 0, 0], true, false)); + words.push(S_ENDPGM); + + let ms = compile_ms( + &words, + vec![VsOutput { + usage: Usage::Generic, + row: 0, + param: 0, + fp16: false, + pack2: false, + }], + &[ + sig_el("SV_Position", 3, 9, None, 0xF), + sig_el("COLOR", 0, 9, Some(0), 0xF), + ], + &[], + (4, 3, 1, 0), + ); + let emu = ms.mesh_emu.as_ref().unwrap(); + assert!(emu.reads_group_id); + let ps = compile_flat_ps("COLOR"); + + run_on_hosts(|label, host| { + let pipes = host.emulated_mesh_pipelines(&ms, &ps).unwrap(); + // Chunked direct dispatch: 1 group starting at base_group = 5 -> top-left = 5.0 + let direct = host + .draw_emulated_mesh( + &pipes, + &EmulatedMeshDraw { + cs_roots: Vec::new(), + ps_roots: Vec::new(), + size: (8, 8), + groups: 1, + max_primitives: emu.max_primitives, + group_bytes: emu.group_bytes(), + base_group: 5, + slot_map: None, + }, + ) + .unwrap_or_else(|e| panic!("{label}: base_group draw failed: {e}")); + assert_eq!(direct[0], [20.0, 0.0, 0.0, 1.0], "{label}: direct[0]"); + + // Multi-record indirect dispatch: 2 local groups reading slot_map [2, 9] + let indirect = host + .draw_emulated_mesh( + &pipes, + &EmulatedMeshDraw { + cs_roots: Vec::new(), + ps_roots: Vec::new(), + size: (8, 8), + groups: 2, + max_primitives: emu.max_primitives, + group_bytes: emu.group_bytes(), + base_group: INDIRECT_SLOT_MAP_FLAG, + slot_map: Some(&[2, 9]), + }, + ) + .unwrap_or_else(|e| panic!("{label}: slot_map draw failed: {e}")); + assert_eq!(indirect[0], [8.0, 0.0, 0.0, 1.0], "{label}: top-left"); + assert_eq!(indirect[7], [36.0, 0.0, 0.0, 1.0], "{label}: top-right"); + }); + } + + const fn vop2_add_f32_helper(vdst: u8, src0_v: u8, vsrc1: u8) -> [u32; 1] { + [vop2(0x003, vdst, vgpr(src0_v), vsrc1)] + } + + #[test] + fn emulated_mesh_passes_per_primitive_psg1_to_ps() { + let mut words = Vec::new(); + words.extend(vop3(0x365, 0, 193, 128, 0)); + words.extend(vop1_lit(0x001, 1, (-1.0f32).to_bits())); + words.extend(vop1_lit(0x001, 2, (-1.0f32).to_bits())); + words.extend(vop1_lit(0x001, 3, 0.5f32.to_bits())); + words.extend(vop1_lit(0x001, 4, 1.0f32.to_bits())); + words.extend(vop1_lit(0x001, 10, 3.0f32.to_bits())); + words.push(vopc(0x0C2, 129, 0)); + words.push(vop2(0x001, 1, vgpr(1), 10)); + words.push(vopc(0x0C2, 130, 0)); + words.push(vop2(0x001, 2, vgpr(2), 10)); + words.extend(exp(12, 0xF, [1, 2, 3, 4], false, false)); + + words.extend(vop1_lit(0x001, 5, 0.25f32.to_bits())); + words.extend(vop1_lit(0x001, 6, 0.5f32.to_bits())); + words.extend(vop1_lit(0x001, 7, 0.75f32.to_bits())); + words.extend(vop1_lit(0x001, 8, 1.0f32.to_bits())); + // Per-primitive parameter 0 (`param = 0x80` -> PSG1 PRIMCOLOR at row 0) + words.extend(exp(32, 0xF, [5, 6, 7, 8], false, false)); + + words.extend(vop1_lit(0x001, 9, 0x0020_0400)); + words.extend(exp(20, 0x1, [9, 0, 0, 0], true, false)); + words.push(S_ENDPGM); + + let ms = compile_ms( + &words, + vec![VsOutput { + usage: Usage::Generic, + row: 0, + param: 0x80, + fp16: false, + pack2: false, + }], + &[sig_el("SV_Position", 3, 9, None, 0xF)], + &[sig_el("PRIMCOLOR", 0, 9, Some(0), 0xF)], + (4, 3, 1, 0), + ); + let ps = compile_flat_ps("PRIMCOLOR"); + let emu = ms.mesh_emu.as_ref().unwrap().clone(); + + run_on_hosts(|label, host| { + let pipes = host.emulated_mesh_pipelines(&ms, &ps).unwrap(); + let pixels = host + .draw_emulated_mesh( + &pipes, + &EmulatedMeshDraw { + cs_roots: Vec::new(), + ps_roots: Vec::new(), + size: (8, 8), + groups: 1, + max_primitives: emu.max_primitives, + group_bytes: emu.group_bytes(), + base_group: 0, + slot_map: None, + }, + ) + .unwrap_or_else(|e| panic!("{label}: draw failed: {e}")); + assert!( + pixels.iter().all(|&p| p == [0.25, 0.5, 0.75, 1.0]), + "{label}: expected [0.25, 0.5, 0.75, 1.0], got {:?}", + pixels[0] + ); + }); + } + + #[test] + fn emulated_mesh_supports_lds_barrier_and_quad_swizzle() { + let mut words = Vec::new(); + // v0 = tid (0..3) + words.extend(vop3(0x365, 0, 193, 128, 0)); + // v14 = tid * 4 (LDS byte offset) + words.push(vop2(0x01A, 14, 130, 0)); // v_lshlrev_b32 v14, 2, v0 + // v15 = float(tid + 1) * 0.25 -> thread 2 writes 0.75 into lds[8] + words.push(vop2(0x025, 15, 129, 0)); // v_add_nc_u32 v15, 1, v0 + words.push(vop1(0x006, 15, vgpr(15))); // v_cvt_f32_u32 v15, v15 + words.extend(vop1_lit(0x001, 16, 0.25f32.to_bits())); + words.push(vop2(0x008, 15, vgpr(15), 16)); // v_mul_f32 v15, v15, v16 + words.extend(ds(0x0D, 0, 14, 15, 0, 0)); // ds_write_b32 v14, v15 + words.push(S_BARRIER); + // Each lane reads ((tid + 3) & 3) * 4 -> lane 3 reads lds[8] (0.75) + words.push(vop2(0x025, 14, 131, 0)); // v_add_nc_u32 v14, 3, v0 + words.push(vop2(0x01B, 14, 131, 14)); // v_and_b32 v14, 3, v14 + words.push(vop2(0x01A, 14, 130, 14)); // v_lshlrev_b32 v14, 2, v14 + words.extend(ds(0x36, 5, 14, 0, 0, 0)); // ds_read_b32 v5, v14 + // Broadcast quad lane 3's value (0.75) to all 4 lanes in the quad + words.extend(ds(0x35, 5, 5, 0, 0, 0x80FF)); // ds_swizzle_b32 v5, v5 offset:0x80FF + + // Position + COLOR(v5, 0, 0, 1) + words.extend(vop1_lit(0x001, 1, (-1.0f32).to_bits())); + words.extend(vop1_lit(0x001, 2, (-1.0f32).to_bits())); + words.extend(vop1_lit(0x001, 3, 0.5f32.to_bits())); + words.extend(vop1_lit(0x001, 4, 1.0f32.to_bits())); + words.extend(vop1_lit(0x001, 10, 3.0f32.to_bits())); + words.push(vopc(0x0C2, 129, 0)); + words.push(vop2(0x001, 1, vgpr(1), 10)); + words.push(vopc(0x0C2, 130, 0)); + words.push(vop2(0x001, 2, vgpr(2), 10)); + words.extend(vop1_lit(0x001, 6, 0.0f32.to_bits())); + words.extend(vop1_lit(0x001, 7, 0.0f32.to_bits())); + words.extend(vop1_lit(0x001, 8, 1.0f32.to_bits())); + words.extend(exp(12, 0xF, [1, 2, 3, 4], false, false)); + words.extend(exp(32, 0xF, [5, 6, 7, 8], false, false)); + words.extend(vop1_lit(0x001, 9, 0x0020_0400)); + words.extend(exp(20, 0x1, [9, 0, 0, 0], true, false)); + words.push(S_ENDPGM); + + let ms = compile_ms( + &words, + vec![VsOutput { + usage: Usage::Generic, + row: 0, + param: 0, + fp16: false, + pack2: false, + }], + &[ + sig_el("SV_Position", 3, 9, None, 0xF), + sig_el("COLOR", 0, 9, Some(0), 0xF), + ], + &[], + (4, 3, 1, 16), + ); + let ps = compile_flat_ps("COLOR"); + let emu = ms.mesh_emu.as_ref().unwrap().clone(); + + run_on_hosts(|label, host| { + let pipes = host.emulated_mesh_pipelines(&ms, &ps).unwrap(); + let pixels = host + .draw_emulated_mesh( + &pipes, + &EmulatedMeshDraw { + cs_roots: Vec::new(), + ps_roots: Vec::new(), + size: (8, 8), + groups: 1, + max_primitives: emu.max_primitives, + group_bytes: emu.group_bytes(), + base_group: 0, + slot_map: None, + }, + ) + .unwrap_or_else(|e| panic!("{label}: draw failed: {e}")); + assert!( + pixels.iter().all(|&p| p == [0.75, 0.0, 0.0, 1.0]), + "{label}: expected [0.75, 0.0, 0.0, 1.0], got {:?}", + pixels[0] + ); + }); + } +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index f55a5c1..0a13cdb 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -94,6 +94,7 @@ mod image_atomic_tests; #[cfg(all(test, windows))] mod intersect_tests; mod lower; +mod mesh_emu; #[cfg(test)] mod mtbuf_tests; mod own_bits; @@ -118,12 +119,14 @@ use crate::native::{HwStage, NativeProgram, RootType}; use crate::{ShaderError, io, ir, resource, structure}; pub use lower::set_host_max_wave; +pub use mesh_emu::{INDIRECT_SLOT_MAP_FLAG, MeshEmu, MeshMode, MeshOutput, unpack_vertex_shader}; pub use rect::rect_list_gs; pub use sampler::StaticSampler; pub use shader::{ - ADDRESS_MAP_SPACE, DESCRIPTOR_WORDS_SPACE, MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, - SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, SLOT_STRIDES_COUNT, USER_DATA_SPACE, - USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, set_view_heap_limit, view_heap_limit, + ADDRESS_MAP_SPACE, DESCRIPTOR_WORDS_SPACE, MEMORY_FAULTS, MEMORY_PAGES, MESH_EMU_SPACE, + ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, SLOT_STRIDES_COUNT, + USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, set_view_heap_limit, + view_heap_limit, }; /// The loop limit without an override: 2^14. @@ -266,6 +269,9 @@ pub struct HostShader { pub root_uavs: Vec, /// Heap descriptors that can be selected from root state at bind time. pub root_indexed_views: Vec, + /// Populated when a mesh program (`HwStage::Ms`) was translated in + /// [`MeshMode::Emulate`] mode as a `cs_6_6` compute shader. + pub mesh_emu: Option, } impl HostShader { @@ -296,8 +302,14 @@ pub struct UserData { } /// Translates the vertex, pixel, compute or mesh program of a console -/// shader container. +/// shader container with native mesh output. pub fn translate(container: &[u8]) -> Result { + translate_with(container, MeshMode::Native) +} + +/// Translates the vertex, pixel, compute or mesh program of a console +/// shader container using `mesh` mode for mesh programs (`HwStage::Ms`). +pub fn translate_with(container: &[u8], mesh: MeshMode) -> Result { let c = Container::parse(container)?; let dxil = c .part(FourCC::DXIL) @@ -321,10 +333,10 @@ pub fn translate(container: &[u8]) -> Result { let res = resource::track(&p, &native.layout, native.stage, st.as_ref().ok())?; let io = io::raise(&p, &native)?; let st = st?; - emit(&c, &native, &p, &st, &io, &res) + emit_with(&c, &native, &p, &st, &io, &res, mesh) } -/// Emits a program whose earlier stages already ran. +/// Emits a program whose earlier stages already ran, with native mesh output. pub fn emit( c: &Container, native: &NativeProgram, @@ -332,10 +344,24 @@ pub fn emit( st: &structure::Structured, io: &io::Io, res: &resource::Resources, +) -> Result { + emit_with(c, native, p, st, io, res, MeshMode::Native) +} + +/// Emits a program whose earlier stages already ran, using `mesh` mode for +/// mesh programs (`HwStage::Ms`). +pub fn emit_with( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + st: &structure::Structured, + io: &io::Io, + res: &resource::Resources, + mesh: MeshMode, ) -> Result { // (what an earlier program's lowering on this thread left behind) lower::take_needs(); - let original = emit_program(c, native, p, st, io, res); + let original = emit_program(c, native, p, st, io, res, mesh); // A console wave64 compute program on a host of 32-lane waves that // still needs 64 lanes, or whose cross-lane code sits where not every // lane runs: once more with its early-outs left out @@ -396,7 +422,7 @@ pub fn emit( ]; for (name, f) in &forms { if let Some((p, st, io, res)) = f { - let again = emit_program(c, native, p, st, io, res); + let again = emit_program(c, native, p, st, io, res, mesh); report(name, &again); if done(&again) { return again.map(|(shader, _)| shader); @@ -425,7 +451,7 @@ pub fn emit( None }; if let Some((p, st, io, res)) = &deep { - let again = emit_program(c, native, p, st, io, res); + let again = emit_program(c, native, p, st, io, res, mesh); report("without skips, scalars followed", &again); if done(&again) { return again.map(|(shader, _)| shader); @@ -460,7 +486,8 @@ pub fn emit( if let Some((p, st, io, res)) = f && idiom(p, st) == exact { - let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); + let local = + lower::with_local_waves(|| emit_program(c, native, p, st, io, res, mesh)); report( &format!( "local waves ({}), {name}", @@ -474,7 +501,8 @@ pub fn emit( } } if idiom(p, st) == exact { - let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); + let local = + lower::with_local_waves(|| emit_program(c, native, p, st, io, res, mesh)); report( if exact { "local waves (idiom)" @@ -493,8 +521,9 @@ pub fn emit( if !strict { for (name, f) in &forms { if let Some((p, st, io, res)) = f { - let local = - lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); + let local = lower::with_local_waves_any(|| { + emit_program(c, native, p, st, io, res, mesh) + }); report( &format!("local waves (APPROXIMATE, any mask), {name}"), &local, @@ -504,7 +533,8 @@ pub fn emit( } } } - let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); + let local = + lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res, mesh)); report("local waves (APPROXIMATE, any mask)", &local); if done(&local) { return local.map(|(shader, _)| shader); @@ -524,7 +554,7 @@ pub fn emit( let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some()); match again { Ok(_) => again, - Err(_) => emit_program(c, native, p, st, io, res), + Err(_) => emit_program(c, native, p, st, io, res, mesh), } } other => other, @@ -543,7 +573,7 @@ pub fn emit( let st = structure::structure(&p)?; let io = io::raise(&p, native)?; let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader) + emit_program(c, native, &p, &st, &io, &res, mesh).map(|(shader, _)| shader) } /// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane @@ -581,7 +611,7 @@ fn widen( let io = io::raise(p, native)?; let res = resource::track(p, &native.layout, native.stage, Some(&st))?; lower::take_needs(); - let r = emit_program(c, native, p, &st, &io, &res); + let r = emit_program(c, native, p, &st, &io, &res, MeshMode::Native); let needs = lower::take_needs(); // (or translated for 64-lane waves still: shared memory read and written where not // every lane runs, whose blocks the lowering names too) @@ -620,6 +650,7 @@ fn emit_program( st: &structure::Structured, io: &io::Io, res: &resource::Resources, + mesh: MeshMode, ) -> Result<(HostShader, Option), ShaderError> { let sig = |fourcc| -> Result, ShaderError> { match c.part(fourcc) { @@ -702,6 +733,7 @@ fn emit_program( prims, mesh_stride, crumbs: breadcrumbs().then(|| breadcrumb_slot(&c.digest)), + emulate_mesh: native.stage == HwStage::Ms && mesh == MeshMode::Emulate, })?; let wave_size = l.wave_size; let shader = HostShader { @@ -716,6 +748,7 @@ fn emit_program( descriptor_words: l.descriptor_words, root_uavs: l.root_uavs, root_indexed_views: res.root_indexed_views.clone(), + mesh_emu: l.mesh_emu, }; Ok((shader, wave_size)) } @@ -965,6 +998,7 @@ pub fn debug_ps(targets: u32) -> HostShader { descriptor_words: false, root_uavs: Vec::new(), root_indexed_views: Vec::new(), + mesh_emu: None, } } @@ -1252,6 +1286,7 @@ mod tests { descriptor_words: false, root_uavs: Vec::new(), root_indexed_views: Vec::new(), + mesh_emu: None, }; let file = |var: &str, stage| { std::env::var(var).ok().map(|p| super::HostShader { @@ -1266,6 +1301,7 @@ mod tests { descriptor_words: false, root_uavs: Vec::new(), root_indexed_views: Vec::new(), + mesh_emu: None, }) }; let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps); @@ -1542,6 +1578,7 @@ mod tests { prims: Vec::new(), mesh_stride: 0, crumbs: None, + emulate_mesh: false, }) .expect("lower"); let shader = super::HostShader { @@ -1556,6 +1593,7 @@ mod tests { descriptor_words: l.descriptor_words, root_uavs: l.root_uavs, root_indexed_views: Vec::new(), + mesh_emu: None, }; #[cfg(windows)] if let Ok(mut v) = super::validator::Validator::load( @@ -2005,6 +2043,7 @@ mod tests { prims: Vec::new(), mesh_stride: 0, crumbs: None, + emulate_mesh: false, }) .unwrap(); #[cfg(windows)] @@ -2029,6 +2068,7 @@ mod tests { descriptor_words: false, root_uavs: _l.root_uavs, root_indexed_views: Vec::new(), + mesh_emu: None, }; let (root, pso) = host.compute_pipeline(&cs).unwrap(); let inputs: Vec = [ diff --git a/crates/victory-shader/src/emit/rect.rs b/crates/victory-shader/src/emit/rect.rs index 7b78e64..d2a236f 100644 --- a/crates/victory-shader/src/emit/rect.rs +++ b/crates/victory-shader/src/emit/rect.rs @@ -412,6 +412,7 @@ mod tests { root_srvs: Vec::new(), root_uavs: Vec::new(), root_indexed_views: Vec::new(), + mesh_emu: None, address_map: false, descriptor_words: false, }; diff --git a/crates/victory-shader/src/emit/root_view_tests.rs b/crates/victory-shader/src/emit/root_view_tests.rs index 6433141..ceb4c30 100644 --- a/crates/victory-shader/src/emit/root_view_tests.rs +++ b/crates/victory-shader/src/emit/root_view_tests.rs @@ -106,6 +106,7 @@ fn build(kind: ResourceType) -> HostShader { prims: Vec::new(), mesh_stride: 0, crumbs: None, + emulate_mesh: false, }) .expect("lower"); let shader = HostShader { @@ -120,6 +121,7 @@ fn build(kind: ResourceType) -> HostShader { descriptor_words: lowered.descriptor_words, root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), + mesh_emu: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 724d88e..00875ed 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -21,6 +21,11 @@ pub const ADDRESS_MAP_SPACE: u32 = 2; /// when the shader reads descriptors as numbers beyond what host views /// tell (see [`super::HostShader::descriptor_words`]). pub const DESCRIPTOR_WORDS_SPACE: u32 = 3; +/// Where mesh shader emulation binds its scratch UAV (`u0`), indirect slot +/// map / unpack vertex input SRV (`t0`), and group-base CBV (`b0`). Space 2 +/// and 3 are the fork's address map and descriptor words, so emulation uses +/// the next space rather than upstream's `MESH_EMU_SPACE = 2`. +pub const MESH_EMU_SPACE: u32 = 4; /// The root SRV `t` in [`ROOT_CBV_SPACE`] of a shader that /// reads buffers through descriptors it picks from the view heap at an @@ -165,6 +170,9 @@ pub(crate) struct Shader { pub descriptor_words: Option, /// Root UAVs (raw buffers) read or written, likewise. pub root_uavs: Vec<(u8, V)>, + emu_cbv: Option, + emu_srv: Option, + emu_uav: Option, pub flags: u64, /// Heap handles made with a non-uniform index. pub nonuniform_handles: u32, @@ -227,6 +235,9 @@ impl Shader { address_map: None, descriptor_words: None, root_uavs: Vec::new(), + emu_cbv: None, + emu_srv: None, + emu_uav: None, flags: 0, nonuniform_handles: 0, cbuffer_handles: 0, @@ -358,6 +369,64 @@ impl Shader { h } + /// The handle of the mesh emulation group-base CBV (`b0` in + /// [`MESH_EMU_SPACE`]). + pub fn emu_cbv_handle(&mut self) -> V { + if let Some(h) = self.emu_cbv { + return h; + } + let z = self.m.i32(0); + let bind = [z, z, self.m.i32(MESH_EMU_SPACE), self.m.i8(2)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, z, f], + ); + let h = self.annotate(block, h, 13, 16); + self.emu_cbv = Some(h); + h + } + + /// The handle of the mesh emulation raw SRV (`t0` in [`MESH_EMU_SPACE`]). + pub fn emu_srv_handle(&mut self) -> V { + if let Some(h) = self.emu_srv { + return h; + } + let h = self.space_handle(MESH_EMU_SPACE); + self.emu_srv = Some(h); + h + } + + /// The handle of the mesh emulation raw UAV (`u0` in [`MESH_EMU_SPACE`]). + pub fn emu_uav_handle(&mut self) -> V { + if let Some(h) = self.emu_uav { + return h; + } + let z = self.m.i32(0); + let bind = [z, z, self.m.i32(MESH_EMU_SPACE), self.m.i8(1)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, z, f], + ); + let h = self.annotate(block, h, 11 | 0x1000, 0); + self.flags |= flags::RAW_BUFFERS; + self.emu_uav = Some(h); + h + } + /// The handle of the address map (`t0` in [`ADDRESS_MAP_SPACE`], a raw /// buffer), made in the entry block. pub fn address_map_handle(&mut self) -> V { @@ -540,6 +609,9 @@ impl Shader { || self.address_map.is_some() || self.descriptor_words.is_some() || !self.root_uavs.is_empty() + || self.emu_cbv.is_some() + || self.emu_srv.is_some() + || self.emu_uav.is_some() { let empty = self.m.md_str(""); let mut cbvs = None; @@ -590,6 +662,29 @@ impl Shader { dxil_kind: 13, }); } + if self.emu_cbv.is_some() { + let arr = self.m.array(4, self.t.i32); + let ty = self.m.named_struct("EmuConst", vec![arr]); + let p = self.m.ptr(ty); + let u = self.m.undef(p); + let ops = vec![ + Some(i32c(&mut self, cbv_list.len() as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, MESH_EMU_SPACE)), + Some(i32c(&mut self, 0)), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 16)), + None, + ]; + cbv_list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 2, + space: MESH_EMU_SPACE, + register: 0, + dxil_kind: 13, + }); + } if !cbv_list.is_empty() { cbvs = Some(self.m.md_node(cbv_list)); } @@ -606,6 +701,9 @@ impl Shader { if self.descriptor_words.is_some() { raw.push((DESCRIPTOR_WORDS_SPACE, 0)); } + if self.emu_srv.is_some() { + raw.push((MESH_EMU_SPACE, 0)); + } if !raw.is_empty() { let ty = self .m @@ -636,7 +734,15 @@ impl Shader { srvs = Some(self.m.md_node(list)); } let mut uavs = None; - if !self.root_uavs.is_empty() { + let mut raw_uavs: Vec<(u32, u32)> = self + .root_uavs + .iter() + .map(|&(slot, _)| (ROOT_CBV_SPACE, u32::from(slot))) + .collect(); + if self.emu_uav.is_some() { + raw_uavs.push((MESH_EMU_SPACE, 0)); + } + if !raw_uavs.is_empty() { let ty = self .m .named_struct("struct.RWByteAddressBuffer", vec![self.t.i32]); @@ -645,7 +751,7 @@ impl Shader { let no = self.m.bool(false); let no = self.m.md_value(no); let mut list = Vec::new(); - for (n, (slot, _)) in self.root_uavs.clone().into_iter().enumerate() { + for (n, (space, register)) in raw_uavs.into_iter().enumerate() { // Id, variable, name, space, lower bound, range size, // shape (11: raw buffer), globally coherent, counter, // rasterizer ordered, no extra properties. @@ -653,8 +759,8 @@ impl Shader { Some(i32c(&mut self, n as u32)), Some(self.m.md_value(u)), Some(empty), - Some(i32c(&mut self, ROOT_CBV_SPACE)), - Some(i32c(&mut self, u32::from(slot))), + Some(i32c(&mut self, space)), + Some(i32c(&mut self, register)), Some(i32c(&mut self, 1)), Some(i32c(&mut self, 11)), Some(no), @@ -665,8 +771,8 @@ impl Shader { list.push(Some(self.m.md_node(ops))); bindings.push(Binding { kind: 7, - space: ROOT_CBV_SPACE, - register: u32::from(slot), + space, + register, dxil_kind: 11, }); } @@ -990,6 +1096,7 @@ mod tests { descriptor_words: false, root_uavs: Vec::new(), root_indexed_views: Vec::new(), + mesh_emu: None, }; if let Ok(host) = Host::new(false) { host.compute_pipeline(&hs).unwrap(); diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index a047f99..08c3503 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -143,6 +143,7 @@ fn build_valu_cs_threads(body: &[u32], threads: u32) -> HostShader { prims: Vec::new(), mesh_stride: 0, crumbs: None, + emulate_mesh: false, }) .expect("lower"); @@ -158,6 +159,7 @@ fn build_valu_cs_threads(body: &[u32], threads: u32) -> HostShader { descriptor_words: lowered.descriptor_words, root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), + mesh_emu: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { @@ -2174,6 +2176,7 @@ fn build_test_cs(body: &[u32], compute: ComputeIo, result_store: &[u32]) -> Host prims: Vec::new(), mesh_stride: 0, crumbs: None, + emulate_mesh: false, }) .expect("lower"); @@ -2189,6 +2192,7 @@ fn build_test_cs(body: &[u32], compute: ComputeIo, result_store: &[u32]) -> Host descriptor_words: lowered.descriptor_words, root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), + mesh_emu: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index 8951b5e..44b1b2b 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -70,6 +70,7 @@ fn build(words: &[u32], buffers: bool) -> HostShader { prims: Vec::new(), mesh_stride: 0, crumbs: None, + emulate_mesh: false, }) .expect("lower"); // One access with each lane's own heap index, no wave operation. @@ -87,6 +88,7 @@ fn build(words: &[u32], buffers: bool) -> HostShader { descriptor_words: lowered.descriptor_words, root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), + mesh_emu: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index d4f7c50..9162d38 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -114,6 +114,7 @@ fn lowered( prims: Vec::new(), mesh_stride: 0, crumbs: None, + emulate_mesh: false, }); lower::TEST_HOST_WAVE.set(was); let lowered = lowered?; @@ -127,6 +128,7 @@ fn lowered( root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, + mesh_emu: None, address_map: lowered.address_map, descriptor_words: lowered.descriptor_words, }) From 3356382ddb285f002eec6f05883cbbe23663d6f1 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 05:55:35 +0000 Subject: [PATCH 2/2] Shader: fix mesh emulation doc links Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-shader/src/emit/mesh_emu.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/victory-shader/src/emit/mesh_emu.rs b/crates/victory-shader/src/emit/mesh_emu.rs index a2f1b53..fda59a2 100644 --- a/crates/victory-shader/src/emit/mesh_emu.rs +++ b/crates/victory-shader/src/emit/mesh_emu.rs @@ -5,7 +5,7 @@ //! (`cs_6_6`) with the console's `[numthreads(threads, 1, 1)]` and LDS, writing //! packed primitive indices, per-vertex attributes (`OSG1`), and per-primitive //! attributes (`PSG1`) into a fixed-stride per-group slice of a raw UAV buffer -//! at `u0` in [`MESH_EMU_SPACE`]: +//! at `u0` in [`MESH_EMU_SPACE`](super::shader::MESH_EMU_SPACE): //! //! ```text //! group g (byte offset = g * group_bytes): @@ -15,7 +15,7 @@ //! ``` //! //! [`unpack_vertex_shader`] builds the matching `vs_6_6` that reads that raw -//! buffer at `t0` in [`MESH_EMU_SPACE`] by `SV_VertexID`, culls bit-31 primitives via quiet +//! buffer at `t0` in [`MESH_EMU_SPACE`](super::shader::MESH_EMU_SPACE) by `SV_VertexID`, culls bit-31 primitives via quiet //! `NaN` on `SV_Position`, and emits every vertex and per-primitive attribute in //! the exact signature layout the title's pixel shader (`ps_6_6`) expects. @@ -27,7 +27,7 @@ use super::shader::Shader; use crate::ShaderError; use crate::dxbc::{Container, FourCC, u32_at}; -/// Sentinel `base_group` value in `b0` in [`MESH_EMU_SPACE`] telling an emulated mesh +/// Sentinel `base_group` value in `b0` in [`MESH_EMU_SPACE`](super::shader::MESH_EMU_SPACE) telling an emulated mesh /// compute shader that reads `SV_GroupID` to look up its per-record group ID /// in the `slot_map` raw SRV (`t0` in the same space). pub const INDIRECT_SLOT_MAP_FLAG: u32 = u32::MAX;