From 656cfa15e3de63590a4e5a303c792cd122ccb54a Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sat, 28 Nov 2026 19:35:42 +0200 Subject: [PATCH 01/15] d3d12: mesh programs translate as compute on a host without mesh shaders (D3D12-MESH-COMPUTE-FALLBACK) set_host_mesh_shaders(false) lowers a mesh program as cs_6_6. setMeshOutputCounts goes. emitIndices, storeVertexOutput and storePrimitiveOutput become raw stores into the root UAV SLOT_MESH_OUT (251), in the group's MeshOut slot: max_vertices vertices, then max_primitives primitives (three indices, then the per-primitive outputs). - The buffer is MESH_OUT_BYTES (64 MiB). A 256-byte header holds a draw's arguments: lane 0 of each group raises its instance count to the group id + 1, so an indirect dispatch's draw needs no CPU read. - Groups past MeshOut::groups_cap write to one sink slot after the last. - mesh_vs() builds the pass-through vertex shader that draws it. SV_VertexID gives primitive and corner, SV_InstanceID the group. It reads the root SRV SLOT_MESH_IN (250) and outputs the program's vertex outputs register for register, plus the per-primitive outputs where the pixel shader reads them, constant. A group past the cap draws a triangle of no area. - HostShader carries the layout and the signatures, and the shader cache encodes them. host_settings() has a word for it, so a translation for one kind of host never serves the other. Tests: the triangle mesh fixture translates as compute (layout, root UAV, empty output signature; dxil.dll takes it for plain, edge-flagged and culled primitives) and stays a mesh shader with mesh shaders. Its vertex shader validates. On a device, the program run as compute and drawn lights the texels the mesh pipeline lights, compared texel for texel where the device has mesh shaders. The test harness gets a root UAV for dispatches, root SRVs in draws and a vertex count. Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/shader_cache.rs | 58 ++++- .../leonida-shader/src/emit/diff_tests.rs | 2 + d3d12/crates/leonida-shader/src/emit/host.rs | 52 +++- .../src/emit/intersect_tests.rs | 3 + d3d12/crates/leonida-shader/src/emit/lower.rs | 225 +++++++++++++++-- .../crates/leonida-shader/src/emit/mesh_vs.rs | 206 +++++++++++++++ d3d12/crates/leonida-shader/src/emit/mod.rs | 234 +++++++++++++++++- .../leonida-shader/src/emit/pack_tests.rs | 2 + .../leonida-shader/src/emit/permlane_tests.rs | 2 + .../leonida-shader/src/emit/probe_tests.rs | 1 + d3d12/crates/leonida-shader/src/emit/rect.rs | 2 + .../crates/leonida-shader/src/emit/shader.rs | 89 +++++++ .../leonida-shader/src/emit/size_tests.rs | 2 + .../leonida-shader/src/emit/valu_tests.rs | 6 + .../src/emit/waterfall_tests.rs | 4 + .../leonida-shader/src/emit/wave64_tests.rs | 7 + 16 files changed, 871 insertions(+), 24 deletions(-) create mode 100644 d3d12/crates/leonida-shader/src/emit/mesh_vs.rs diff --git a/d3d12/crates/leonida-gpu/src/shader_cache.rs b/d3d12/crates/leonida-gpu/src/shader_cache.rs index 82481d0034..bf136a117c 100644 --- a/d3d12/crates/leonida-gpu/src/shader_cache.rs +++ b/d3d12/crates/leonida-gpu/src/shader_cache.rs @@ -218,7 +218,7 @@ fn paired_override(container: &[u8], mut shader: HostShader) -> HostShader { let Some(dir) = DIR.get_or_init(|| std::env::var_os("LEONIDA_PAIRED_SHADER_DIR").map(PathBuf::from)) else { return shader; }; - if shader.stage != HwStage::Cs || leonida_shader::emit::host_settings() != [32, 999_999, 0, 0] { + if shader.stage != HwStage::Cs || leonida_shader::emit::host_settings() != [32, 999_999, 0, 0, 0] { return shader; } let digest = blake3::hash(container).to_hex(); @@ -397,6 +397,26 @@ fn encode(s: &HostShader) -> Vec { word(&mut out, u32::from(slot)); word(&mut out, dword); } + // A mesh program lowered as compute: its output layout (0: none). + match &s.mesh_out { + None => word(&mut out, 0), + Some(m) => { + word(&mut out, 1); + for value in [m.max_vertices, m.max_primitives, m.vertex_stride, m.primitive_stride] { + word(&mut out, value); + } + for at in [&m.vertex_at, &m.primitive_at] { + word(&mut out, at.len() as u32); + for &offset in at { + word(&mut out, offset); + } + } + for part in [&m.osg1, &m.psg1] { + word(&mut out, part.len() as u32); + out.extend_from_slice(part); + } + } + } out } @@ -470,6 +490,30 @@ fn decode(bytes: &[u8]) -> Option { for _ in 0..n { half_views.push((u8::try_from(r.word()?).ok()?, r.word()?)); } + let mesh_out = match r.word()? { + 0 => None, + 1 => { + let [max_vertices, max_primitives, vertex_stride, primitive_stride] = + [r.word()?, r.word()?, r.word()?, r.word()?]; + let mut offsets = || -> Option> { + let n = r.word()? as usize; + (0..n.min(1024)).map(|_| r.word()).collect() + }; + let (vertex_at, primitive_at) = (offsets()?, offsets()?); + let (osg1, psg1) = (r.list()?, r.list()?); + Some(leonida_shader::emit::MeshOut { + max_vertices, + max_primitives, + vertex_stride, + primitive_stride, + vertex_at, + primitive_at, + osg1, + psg1, + }) + } + _ => return None, + }; r.0.is_empty().then_some(HostShader { stage, dxil, @@ -481,6 +525,7 @@ fn decode(bytes: &[u8]) -> Option { root_uavs, root_indexed_views, half_views, + mesh_out, }) } @@ -543,6 +588,17 @@ mod tests { shift: 5, }], half_views: vec![(0, 8), (4, 0)], + // A mesh program's output layout survives the round trip. + mesh_out: Some(leonida_shader::emit::MeshOut { + max_vertices: 64, + max_primitives: 126, + vertex_stride: 32, + primitive_stride: 16, + vertex_at: vec![0, 16], + primitive_at: vec![12], + osg1: b"OSG1 part".to_vec(), + psg1: Vec::new(), + }), } } diff --git a/d3d12/crates/leonida-shader/src/emit/diff_tests.rs b/d3d12/crates/leonida-shader/src/emit/diff_tests.rs index b870750dc7..f0094ad7b2 100644 --- a/d3d12/crates/leonida-shader/src/emit/diff_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/diff_tests.rs @@ -773,6 +773,7 @@ fn translated_shaders_draw_as_pc_ones() { stride: 24, size: (16, 16), mesh_groups: 0, + vertex_count: 0, }; let mut failures = Vec::new(); let only = std::env::var("LEONIDA_DIFF_ONLY").ok(); @@ -895,6 +896,7 @@ fn translated_mesh_shaders_draw_as_pc_ones() { stride: 0, size: (16, 16), mesh_groups, + vertex_count: 0, }; let mut failures = Vec::new(); let only = std::env::var("LEONIDA_DIFF_ONLY").ok(); diff --git a/d3d12/crates/leonida-shader/src/emit/host.rs b/d3d12/crates/leonida-shader/src/emit/host.rs index 1ee50a3aeb..103d46cc9c 100644 --- a/d3d12/crates/leonida-shader/src/emit/host.rs +++ b/d3d12/crates/leonida-shader/src/emit/host.rs @@ -613,6 +613,7 @@ fn stub(pixel: bool, outputs: Vec) -> HostShader { root_uavs: Vec::new(), root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, } } @@ -631,6 +632,9 @@ pub enum Root { srv: bool, data: Vec, }, + /// A root UAV over a raw buffer of this many dwords, zeroed + /// ([`Host::dispatch`] only; its contents come after the heap's UAVs). + Uav(u32), } /// Bindings for [`Host::draw`]: root arguments and the heap contents. @@ -647,6 +651,8 @@ pub struct Draw<'a> { pub size: (u32, u32), /// Mesh thread groups to dispatch instead of drawing (0: draw). pub mesh_groups: u32, + /// Vertices drawn (0: three, one triangle). + pub vertex_count: u32, } #[cfg(test)] @@ -868,7 +874,33 @@ impl Host { at.ptr += (index * size) as u64; list.SetGraphicsRootDescriptorTable(*param, at); } - Root::View { .. } => return Err("root views in a draw".into()), + Root::View { srv: true, data } => { + let bytes = (data.len() * 4).next_multiple_of(256) as u64; + let b = make( + D3D12_HEAP_TYPE_UPLOAD, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + 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); + list.SetGraphicsRootShaderResourceView(*param, b.GetGPUVirtualAddress()); + keep.push(b); + } + Root::View { .. } | Root::Uav(_) => { + return Err("a root CBV or UAV in a draw".into()); + } } } list.OMSetRenderTargets(1, Some(&rtv), false, None); @@ -898,7 +930,8 @@ impl Host { let list6: ID3D12GraphicsCommandList6 = list.cast().map_err(err)?; list6.DispatchMesh(d.mesh_groups, 1, 1); } else { - list.DrawInstanced(3, 1, 0, 0); + let count = if d.vertex_count == 0 { 3 } else { d.vertex_count }; + list.DrawInstanced(count, 1, 0, 0); } list.ResourceBarrier(&[transition( &target, @@ -1476,6 +1509,21 @@ impl Host { } keep.push(b); } + Root::Uav(n) => { + let bytes = u64::from(*n) * 4; + let b = make( + D3D12_HEAP_TYPE_DEFAULT, + &buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_COMMON, + )?; + list.SetComputeRootUnorderedAccessView(*param, b.GetGPUVirtualAddress()); + let rb = make( + D3D12_HEAP_TYPE_READBACK, + &buffer(bytes, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + uavs.push((b, None, *n, rb)); + } } } let [x, y, z] = d.groups; diff --git a/d3d12/crates/leonida-shader/src/emit/intersect_tests.rs b/d3d12/crates/leonida-shader/src/emit/intersect_tests.rs index 91143f6457..c296573b4a 100644 --- a/d3d12/crates/leonida-shader/src/emit/intersect_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/intersect_tests.rs @@ -183,6 +183,7 @@ pub(super) fn build_compute_shader( outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, })?; let shader = HostShader { stage: HwStage::Cs, @@ -195,6 +196,7 @@ pub(super) fn build_compute_shader( root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views.clone(), half_views: lowered.half_views, + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); @@ -693,6 +695,7 @@ fn a_structure_that_returns_triangle_ids_is_refused_by_name() { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }); match r { Err(ShaderError::Unsupported { what, .. }) => { diff --git a/d3d12/crates/leonida-shader/src/emit/lower.rs b/d3d12/crates/leonida-shader/src/emit/lower.rs index 895edceca4..a897d21c34 100644 --- a/d3d12/crates/leonida-shader/src/emit/lower.rs +++ b/d3d12/crates/leonida-shader/src/emit/lower.rs @@ -61,6 +61,8 @@ enum Val { pub(crate) struct Lowered { pub dxil: Vec, + /// A mesh program lowered as compute: where its outputs went. + pub mesh_out: Option, /// Bit n: immediate sampler n is a comparison sampler. pub cmp_samplers: u64, pub root_cbvs: Vec, @@ -94,6 +96,10 @@ pub(crate) struct Parts<'a> { pub prims: Vec, /// Mesh: what the group id arrives multiplied by. pub mesh_stride: u32, + /// Mesh: lower the program as compute, its outputs going to + /// [`super::SLOT_MESH_OUT`] ([`super::shader::MeshOut`]): for a host + /// without mesh shaders. + pub mesh_compute: bool, } enum Stop { @@ -427,6 +433,9 @@ struct Lower<'a> { console_lanes: bool, /// Mesh: the thread index in the group (made in the entry block). flat: Option, + /// Mesh as compute: the byte offset of this group's + /// [`super::SLOT_MESH_OUT`] slot (made in the entry block). + mesh_base: Option, /// Mesh: IR blocks whose `s_barrier` is left out. no_barrier: HashSet, /// IR blocks whose `s_barrier` not every lane is sure to reach (a lane @@ -1586,8 +1595,46 @@ fn own_bits_on() -> bool { /// What the translator was told of the host, for a cache's key: the widest /// wave, the view heap's limit, where the raw twins of its views start, and /// what it writes for the console's own hardware. -pub fn host_settings() -> [u32; 4] { - [host_max_wave(), super::shader::view_heap_limit(), super::shader::raw_views(), host_rdna()] +pub fn host_settings() -> [u32; 5] { + [ + host_max_wave(), + super::shader::view_heap_limit(), + super::shader::raw_views(), + host_rdna(), + u32::from(host_mesh_compute()), + ] +} + +static HOST_MESH_COMPUTE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Tells the translator whether the host runs mesh shaders. Without them a +/// mesh program is lowered as compute, its outputs going to +/// [`super::SLOT_MESH_OUT`] for the pass-through vertex shader +/// ([`super::mesh_vs`]) to draw. +pub fn set_host_mesh_shaders(on: bool) { + HOST_MESH_COMPUTE.store(!on, std::sync::atomic::Ordering::Relaxed); +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`host_mesh_compute`], for its thread only. + pub(super) static TEST_MESH_COMPUTE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Whether mesh programs are translated as compute (the host has no mesh +/// shaders, or `LEONIDA_MESH_COMPUTE=1` asked for it): the pipeline side +/// draws them through `mesh_vs`. +pub fn mesh_as_compute() -> bool { + host_mesh_compute() +} + +/// Whether mesh programs are lowered as compute ([`set_host_mesh_shaders`]). +pub(super) fn host_mesh_compute() -> bool { + #[cfg(test)] + if let Some(on) = TEST_MESH_COMPUTE.get() { + return on; + } + HOST_MESH_COMPUTE.load(std::sync::atomic::Ordering::Relaxed) } static HOST_RDNA: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); @@ -2372,6 +2419,14 @@ impl<'a> Lower<'a> { max_primitives: ms.max_primitives, topology: ms.topology, }); + if x.mesh_compute { + s.mesh_compute = Some(super::shader::MeshOut::new( + ms.max_vertices, + ms.max_primitives, + &s.outputs, + &s.prims, + )); + } // 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 @@ -2497,6 +2552,7 @@ impl<'a> Lower<'a> { wave_base: None, wave_rank: None, flat: None, + mesh_base: None, no_barrier, fence_only, half_outputs: half_outputs(&x.native.io, &x.outputs), @@ -3295,7 +3351,16 @@ impl<'a> Lower<'a> { let half_views = std::mem::take(&mut self.half_views).into_iter().collect(); let cmp_samplers = self.s.cmp_samplers; let wave_size = self.s.wave_size; + // Mesh as compute: the container is a compute shader's, with no + // output signatures (what they held is in the layout). + let mesh_out = self.s.mesh_compute.take(); + if mesh_out.is_some() { + self.s.mesh = None; + self.s.outputs.clear(); + self.s.prims.clear(); + } Ok(Lowered { + mesh_out, wave_size, cmp_samplers, root_cbvs, @@ -5878,7 +5943,10 @@ impl<'a> Lower<'a> { let fits = |m: super::shader::Mesh| { mesh_output_bytes(outputs, prims, m.max_vertices, m.max_primitives) <= MESH_OUTPUT_LIMIT }; - if !fits(mesh) { + let compute = self.s.mesh_compute.is_some(); + // As compute there is no output limit: the maxima stay the + // program's, as the layout has them. + if !compute && !fits(mesh) { mesh.max_vertices = mesh.max_vertices.min(threads); mesh.max_primitives = mesh.max_primitives.min(threads); // shortcut: outputs past the cap even at the lane count are @@ -5896,9 +5964,29 @@ impl<'a> Lower<'a> { self.s.m.i32(mesh.max_vertices), self.s.m.i32(mesh.max_primitives), ); - self.s - .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]); + if !compute { + self.s + .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]); + } let flat = self.mesh_thread(); + if compute { + // Made here, in the entry block, before any guarded block ends + // it: every store below uses them. + self.mesh_base(); + let out = self.s.root_uav_handle(super::SLOT_MESH_OUT); + // Lane 0 raises the header's instance count to the group's id + 1: + // after the dispatch it holds the groups to draw. + let i32t = self.s.t.i32; + let zero = self.s.m.i32(0); + let group = self.s.op(e, "groupId.i32", Attr::ReadNone, i32t, 94, &[zero]); + let one = self.s.m.i32(1); + let count = self.s.m.bin(e, Bin::Add, group, one); + let first = self.s.m.cmp(e, pred::EQ, flat, zero); + let at = self.begin_guarded(Some(first)); + let (code, byte, iu) = (self.s.m.i32(7), self.s.m.i32(4), self.s.m.undef(i32t)); + self.s.op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &[out, code, byte, iu, iu, count]); + self.end_guarded(at, &[]); + } let z = self.s.m.i32(0); // Every primitive of the declared count starts culled, also those // past the lanes (a count of 256 with 128 lanes): lane n culls @@ -5916,14 +6004,18 @@ impl<'a> Lower<'a> { let guard = ((pass + 1) * threads > mesh.max_primitives) .then(|| self.s.m.cmp(self.cur, pred::IULT, index, p)); let at = self.begin_guarded(guard); - self.s.op( - self.cur, - "emitIndices", - Attr::NoUnwind, - void, - 169, - &[index, z, z, z], - ); + if compute { + self.mesh_out_indices(index, [z, z, z]); + } else { + self.s.op( + self.cur, + "emitIndices", + Attr::NoUnwind, + void, + 169, + &[index, z, z, z], + ); + } self.end_guarded(at, &[]); } Ok(()) @@ -5948,6 +6040,71 @@ impl<'a> Lower<'a> { f } + /// Mesh as compute: the byte offset of this group's slot in + /// [`super::SLOT_MESH_OUT`] (the host group's x id times the slot size). + fn mesh_base(&mut self) -> V { + if let Some(b) = self.mesh_base { + return b; + } + let m = self.s.mesh_compute.as_ref().expect("mesh as compute"); + let (bytes, cap) = (m.group_bytes(), m.groups_cap()); + let e = self.s.entry; + let zero = self.s.m.i32(0); + let i32t = self.s.t.i32; + let group = self.s.op(e, "groupId.i32", Attr::ReadNone, i32t, 94, &[zero]); + // A group past the cap writes to the slot after the last one. + let cap = self.s.m.i32(cap); + let slot = self.s.op(e, "binary.i32", Attr::ReadNone, i32t, 40, &[group, cap]); + self.s.m.tag(slot, super::bitcode::Tag::Clamp); + let k = self.s.m.i32(bytes); + let b = self.s.m.bin(e, Bin::Mul, slot, k); + let header = self.s.m.i32(super::shader::MESH_OUT_HEADER); + let b = self.s.m.bin(e, Bin::Add, b, header); + self.mesh_base = Some(b); + b + } + + /// Mesh as compute: one dword, `value`, at byte `at` of this group's + /// slot in the current block. + fn mesh_out_store(&mut self, at: V, value: V) { + let base = self.mesh_base(); + let out = self.s.root_uav_handle(super::SLOT_MESH_OUT); + let c = self.cur; + let place = self.s.m.bin(c, Bin::Add, base, at); + let iu = self.s.m.undef(self.s.t.i32); + let (mask, align) = (self.s.m.i8(1), self.s.m.i32(4)); + let void = self.s.t.void; + self.s.op( + c, + "rawBufferStore.i32", + Attr::NoUnwind, + void, + 140, + &[out, place, iu, value, iu, iu, iu, mask, align], + ); + } + + /// Mesh as compute: the byte offset of primitive `index` in the slot. + fn mesh_primitive_at(&mut self, index: V) -> V { + let m = self.s.mesh_compute.as_ref().expect("mesh as compute"); + let (first, stride) = (m.primitives_at(), m.primitive_stride); + let c = self.cur; + let (first, stride) = (self.s.m.i32(first), self.s.m.i32(stride)); + let at = self.s.m.bin(c, Bin::Mul, index, stride); + self.s.m.bin(c, Bin::Add, at, first) + } + + /// Mesh as compute: the three indices of primitive `index`. + fn mesh_out_indices(&mut self, index: V, corners: [V; 3]) { + let at = self.mesh_primitive_at(index); + for (k, v) in corners.into_iter().enumerate() { + let c = self.cur; + let off = self.s.m.i32(4 * k as u32); + let place = self.s.m.bin(c, Bin::Add, at, off); + self.mesh_out_store(place, v); + } + } + /// The console wave size. fn wave(&self) -> u32 { if self.x.native.wave64 { 64 } else { 32 } @@ -13965,6 +14122,30 @@ impl<'a> Lower<'a> { } _ => (".i32", x), }; + let placed = self.s.mesh_compute.as_ref().filter(|_| mesh).map(|layout| { + let element = if primitive { layout.primitive_at[id] } else { layout.vertex_at[id] }; + (element + 4 * u32::from(col), layout.vertex_stride) + }); + if let Some((column, vertex_stride)) = placed { + // As compute: the value's bits at the element's column of + // this lane's vertex or primitive (`x` is the float the + // output takes for `.f32`). + let bits = if suffix == ".f32" { self.as_int(x) } else { x }; + let flat = self.mesh_thread(); + let c = self.cur; + let at = if primitive { + let at = self.mesh_primitive_at(flat); + let off = self.s.m.i32(column); + self.s.m.bin(c, Bin::Add, at, off) + } else { + let stride = self.s.m.i32(vertex_stride); + let at = self.s.m.bin(c, Bin::Mul, flat, stride); + let off = self.s.m.i32(column); + self.s.m.bin(c, Bin::Add, at, off) + }; + self.mesh_out_store(at, bits); + continue; + } let mut args = vec![ self.s.m.i32(id as u32), self.s.m.i32(0), @@ -14035,13 +14216,16 @@ impl<'a> Lower<'a> { } *slot = i; } - let mut args = vec![flat]; - for i in indices { - args.push(self.s.m.select(c, culled, z, i)); + let corners = indices.map(|i| self.s.m.select(c, culled, z, i)); + if self.s.mesh_compute.is_some() { + self.mesh_out_indices(flat, corners); + } else { + let mut args = vec![flat]; + args.extend(corners); + let void = self.s.t.void; + self.s + .op(c, "emitIndices", Attr::NoUnwind, void, 169, &args); } - let void = self.s.t.void; - self.s - .op(c, "emitIndices", Attr::NoUnwind, void, 169, &args); self.end_guarded(at, &[]); Ok(()) } @@ -14606,6 +14790,7 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, + mesh_compute: false, }) .map(|_| ()) } @@ -14656,6 +14841,7 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, + mesh_compute: false, }) } @@ -14826,6 +15012,7 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, + mesh_compute: false, }).unwrap(); let container = diff --git a/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs b/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs new file mode 100644 index 0000000000..f570562a30 --- /dev/null +++ b/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs @@ -0,0 +1,206 @@ +//! The vertex shader that draws a mesh program run as compute on a host +//! without mesh shaders (`D3D12-MESH-COMPUTE-FALLBACK`). The compute +//! variant ([`super::set_host_mesh_shaders`]) writes each group's vertices, +//! primitive indices and per-primitive outputs to [`super::SLOT_MESH_OUT`] +//! in its [`MeshOut`] layout; the draw that follows is a triangle list of +//! `3 * max_primitives` vertices and one instance a group, with this shader +//! in front of the title's pixel shader, reading the same buffer as the root +//! SRV [`super::SLOT_MESH_IN`]. (An indirect dispatch draws with the +//! header's arguments, which the groups wrote.) +//! +//! Vertex `id` of instance `g` is corner `id % 3` of primitive `id / 3` of +//! group `g`. A group past [`MeshOut::groups_cap`] had no slot of its own: +//! it draws nothing. A primitive the program culled, or +//! never wrote, has indices 0, 0, 0: a triangle of no area, as on the mesh +//! path. Every corner is its own vertex here, so a per-primitive output is +//! a vertex output with constant interpolation, the same at all three. +//! +//! The outputs are the mesh program's vertex outputs, register for +//! register, and its per-primitive outputs in the registers the pixel +//! shader reads them from (by semantic and index): a mesh pipeline's +//! per-primitive outputs have their own signature, which a vertex shader +//! has not. + +use super::bitcode::{Attr, Bin, Term, V}; +use super::container::SigElement; +use super::shader::{MeshOut, Shader}; +use crate::ShaderError; +use crate::dxbc::{Container, FourCC}; + +/// The pass-through vertex shader (a DXIL container) for a mesh program +/// translated as compute with `layout`, drawn with the translated pixel +/// shader `ps` (its [`super::HostShader::dxil`]) if the pipeline has one. +pub fn mesh_vs(layout: &MeshOut, ps: Option<&[u8]>) -> Result, ShaderError> { + let vertex = super::signature(&layout.osg1)?; + let primitive = super::signature(&layout.psg1)?; + let wanted = match ps { + Some(ps) => { + let c = Container::parse(ps)?; + match c.part(FourCC::ISG1) { + Some(part) => super::signature(part.data)?, + None => Vec::new(), + } + } + None => Vec::new(), + }; + build(layout, vertex, &primitive, &wanted) +} + +/// Where an output's value comes from: byte `at` of its vertex (`false`) +/// or of its primitive past the indices (`true`). +struct Source { + primitive: bool, + at: u32, +} + +fn build( + layout: &MeshOut, + vertex: Vec, + primitive: &[SigElement], + ps_inputs: &[SigElement], +) -> Result, ShaderError> { + let unsupported = |what| ShaderError::Unsupported { offset: 0, what }; + if vertex.len() != layout.vertex_at.len() || primitive.len() != layout.primitive_at.len() { + return Err(unsupported("a mesh layout that does not match its signatures")); + } + if vertex.iter().any(|e| e.row.is_none()) { + return Err(unsupported("a mesh vertex output without a register")); + } + if layout.max_primitives == 0 { + return Err(unsupported("a mesh program without primitives")); + } + let mut outputs = Vec::new(); + let mut sources = Vec::new(); + for (e, &at) in vertex.iter().zip(&layout.vertex_at) { + outputs.push(SigElement { + usage: (1 << e.cols) - 1, + ..e.clone() + }); + sources.push(Source { primitive: false, at }); + } + // A per-primitive output goes where the pixel shader reads it; one the + // pixel shader does not read is not drawn with. + for (p, &at) in primitive.iter().zip(&layout.primitive_at) { + let Some(e) = ps_inputs + .iter() + .find(|e| e.name.eq_ignore_ascii_case(&p.name) && e.index == p.index && e.row.is_some()) + else { + continue; + }; + let clash = outputs.iter().any(|o| { + o.row == e.row && o.col < e.col + p.cols && e.col < o.col + o.cols + }); + if clash || e.cols < p.cols { + return Err(unsupported( + "a per-primitive output whose pixel shader register a vertex output takes", + )); + } + outputs.push(SigElement { + row: e.row, + col: e.col, + interp: 1, + usage: (1 << p.cols) - 1, + ..p.clone() + }); + sources.push(Source { primitive: true, at }); + } + + let mut s = Shader::new(false); + let system = |name: &str, kind, row| SigElement { + name: name.into(), + index: 0, + kind, + comp: 5, + interp: 0, + row: Some(row), + col: 0, + cols: 1, + usage: 1, + half: false, + }; + s.inputs = vec![system("SV_VertexID", 1, 0), system("SV_InstanceID", 2, 1)]; + s.outputs = outputs; + let b = s.entry; + let i32t = s.t.i32; + let k = |s: &mut Shader, v: u32| s.m.i32(v); + + // (vertex id, instance id) -> primitive, corner, group. + let input = |s: &mut Shader, n: u32| { + let args = [s.m.i32(n), s.m.i32(0), s.m.i8(0), s.m.undef(i32t)]; + s.op(b, "loadInput.i32", Attr::ReadNone, i32t, 4, &args) + }; + let (id, group) = (input(&mut s, 0), input(&mut s, 1)); + let three = k(&mut s, 3); + let prim = s.m.bin(b, Bin::UDiv, id, three); + let corner = s.m.bin(b, Bin::URem, id, three); + // A group past the cap wrote to the sink slot: it draws nothing. + let cap = k(&mut s, layout.groups_cap()); + let past = s.m.cmp(b, super::bitcode::pred::IUGT, group, cap); + let group = s.op(b, "binary.i32", Attr::ReadNone, i32t, 40, &[group, cap]); + s.m.tag(group, super::bitcode::Tag::Clamp); + + // Byte offsets in the buffer. + let slot = k(&mut s, layout.group_bytes()); + let base = s.m.bin(b, Bin::Mul, group, slot); + let header = k(&mut s, super::shader::MESH_OUT_HEADER); + let base = s.m.bin(b, Bin::Add, base, header); + let (first, pstride) = (k(&mut s, layout.primitives_at()), k(&mut s, layout.primitive_stride)); + let prim_at = s.m.bin(b, Bin::Mul, prim, pstride); + let prim_at = s.m.bin(b, Bin::Add, prim_at, first); + let prim_at = s.m.bin(b, Bin::Add, prim_at, base); + let four = k(&mut s, 4); + let corner_at = s.m.bin(b, Bin::Mul, corner, four); + let index_at = s.m.bin(b, Bin::Add, prim_at, corner_at); + let index = load(&mut s, index_at); + let zero = k(&mut s, 0); + let index = s.m.select(b, past, zero, index); + // An index past the vertices (none is written so) reads vertex 0. + let index = { + let last = k(&mut s, layout.max_vertices.saturating_sub(1)); + let v = s.op(b, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]); + s.m.tag(v, super::bitcode::Tag::Clamp); + v + }; + let vstride = k(&mut s, layout.vertex_stride); + let vertex_at = s.m.bin(b, Bin::Mul, index, vstride); + let vertex_at = s.m.bin(b, Bin::Add, vertex_at, base); + + for (id, source) in sources.iter().enumerate() { + let (from, cols, float) = { + let e = &s.outputs[id]; + (if source.primitive { prim_at } else { vertex_at }, e.cols, e.comp == 9) + }; + for col in 0..cols { + let off = k(&mut s, source.at + 4 * u32::from(col)); + let at = s.m.bin(b, Bin::Add, from, off); + let bits = load(&mut s, at); + let (name, value) = if float { + let f32t = s.t.f32; + ("storeOutput.f32", s.m.cast(b, super::bitcode::Cast::Bitcast, bits, f32t)) + } else { + ("storeOutput.i32", bits) + }; + let args = [k(&mut s, id as u32), k(&mut s, 0), s.m.i8(col), value]; + s.op(b, name, Attr::NoUnwind, s.t.void, 5, &args); + } + } + s.m.terminate(b, Term::Ret); + Ok(s.finish()) +} + +/// The dword at byte `at` of [`super::SLOT_MESH_IN`], as an i32. +fn load(s: &mut Shader, at: V) -> V { + let b = s.entry; + let handle = s.root_srv_handle(super::SLOT_MESH_IN); + let (undef, mask, align) = (s.m.undef(s.t.i32), s.m.i8(1), s.m.i32(4)); + let r = s.op( + b, + "rawBufferLoad.f32", + Attr::ReadOnly, + s.t.res_ret, + 139, + &[handle, at, undef, mask, align], + ); + let f = s.m.extract(b, r, 0); + s.m.cast(b, super::bitcode::Cast::Bitcast, f, s.t.i32) +} diff --git a/d3d12/crates/leonida-shader/src/emit/mod.rs b/d3d12/crates/leonida-shader/src/emit/mod.rs index 707095287c..28586eff66 100644 --- a/d3d12/crates/leonida-shader/src/emit/mod.rs +++ b/d3d12/crates/leonida-shader/src/emit/mod.rs @@ -94,6 +94,7 @@ mod lds_exact; mod lds_flags; mod lds_init; mod lower; +pub mod mesh_vs; mod own_bits; #[cfg(all(test, windows))] mod permlane_tests; @@ -127,10 +128,12 @@ use crate::{ShaderError, io, ir, resource, structure}; pub use bitcode::census; pub use sampler::StaticSampler; -pub use lower::{host_settings, set_host_max_wave, set_host_rdna, take_pack_why}; +pub use lower::{host_settings, mesh_as_compute, set_host_max_wave, set_host_mesh_shaders, set_host_rdna, take_pack_why}; +pub use mesh_vs::mesh_vs; pub use rect::rect_list_gs; pub use shader::{ - MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, + MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, MeshOut, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, + MESH_OUT_BYTES, MESH_OUT_HEADER, SLOT_MESH_IN, SLOT_MESH_OUT, SLOT_STRIDES, SLOT_STRIDE_CONSTANT, SLOT_STRIDES_COUNT, SLOT_TABLE_STRIDES, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_PACK_GROUPS, USER_PACK_X, USER_PACK_Y, PACK_FOLD, pack_grid, pack_group, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS, constant_marks, constants_raw, raw_views, set_raw_views, set_view_heap_limit, view_heap_limit, }; @@ -595,6 +598,10 @@ pub struct HostShader { /// descriptor picked at run time keeps the float path (its slot, and so /// its format, is known only then). pub half_views: Vec<(u8, u32)>, + /// A mesh program lowered as compute ([`set_host_mesh_shaders`]): the + /// shader is `cs_6_6` and writes what its outputs would to the root UAV + /// [`SLOT_MESH_OUT`] in this layout; [`mesh_vs::mesh_vs`] reads it back. + pub mesh_out: Option, } impl HostShader { @@ -1464,6 +1471,7 @@ fn emit_program_plain( outputs, prims, mesh_stride, + mesh_compute: matches!(native.io, crate::native::StageIo::Ms(_)) && lower::host_mesh_compute(), })?; let counted = match early { EarlyDepth::NotAsked => None, @@ -1497,6 +1505,7 @@ fn emit_program_plain( root_uavs: l.root_uavs, root_indexed_views: res.root_indexed_views.clone(), half_views: l.half_views, + mesh_out: l.mesh_out, }; Ok((shader, wave_size)) } @@ -1971,6 +1980,7 @@ mod tests { outputs, prims: vec![], mesh_stride: 0, + mesh_compute: false, }) .unwrap(); let out = emit(&c, &native, &p, &st, &io, &res).unwrap(); @@ -2406,6 +2416,7 @@ mod tests { root_uavs: Vec::new(), root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }; let file = |var: &str, stage| { std::env::var(var).ok().map(|p| super::HostShader { @@ -2419,6 +2430,7 @@ mod tests { root_uavs: Vec::new(), root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }) }; let ps = file("LEONIDA_REF_PS", crate::HwStage::Ps).unwrap_or(ps); @@ -2578,6 +2590,7 @@ mod tests { stride: 0, size: (16, 16), mesh_groups: 1, + vertex_count: 0, }, ) .unwrap_or_else(|e| panic!("{label}: draw: {e}")); @@ -2703,6 +2716,75 @@ mod tests { } } + /// On a host without mesh shaders a mesh program translates as compute + /// (`D3D12-MESH-COMPUTE-FALLBACK`): no output signatures, the root UAV + /// [`SLOT_MESH_OUT`], and the layout of its outputs: one position (16 + /// bytes a vertex) and three indices (12 bytes a primitive) for each of + /// its 32 vertices and primitives. dxil.dll, where there is one, takes + /// the module for every primitive export the native path takes. + #[test] + fn a_mesh_program_translates_as_compute_without_mesh_shaders() { + #[cfg(windows)] + let mut validator = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) + .ok(); + super::lower::TEST_MESH_COMPUTE.set(Some(true)); + for prim in [ + TRIANGLE, + TRIANGLE | EDGE_FLAGS, + TRIANGLE | EDGE_FLAGS | CULL, + ] { + let cs = triangle_mesh(prim).unwrap_or_else(|e| panic!("{prim:#x}: {e}")); + let layout = cs.mesh_out.as_ref().unwrap_or_else(|| panic!("{prim:#x}: no layout")); + assert_eq!( + ( + layout.max_vertices, + layout.max_primitives, + layout.vertex_stride, + layout.primitive_stride + ), + (32, 32, 16, 12), + "{prim:#x}" + ); + assert_eq!((&layout.vertex_at[..], &layout.primitive_at[..]), (&[0][..], &[][..]), "{prim:#x}"); + // The mesh program's position, for the pass-through vertex shader. + let position = signature(&layout.osg1).unwrap(); + assert_eq!(position.len(), 1, "{prim:#x}"); + assert_eq!((position[0].kind, position[0].cols), (3, 4), "{prim:#x}"); + assert!(cs.root_uavs.contains(&SLOT_MESH_OUT), "{prim:#x}: {:?}", cs.root_uavs); + let c = Container::parse(&cs.dxil).unwrap(); + // A compute shader's output signature is there and empty. + let outputs = c.part(FourCC::OSG1).map(|p| signature(p.data).unwrap()); + assert_eq!(outputs, Some(vec![]), "{prim:#x}"); + assert!(c.part(FourCC::PSG1).is_none(), "{prim:#x}"); + #[cfg(windows)] + if let Some(v) = validator.as_mut() { + v.validate(&mut cs.dxil.clone()) + .unwrap_or_else(|e| panic!("{prim:#x}: {e}")); + } + } + // Its pass-through vertex shader: SV_VertexID in, the program's + // position out (register for register), and dxil.dll takes it. + let cs = triangle_mesh(TRIANGLE).unwrap(); + let vs = mesh_vs(cs.mesh_out.as_ref().unwrap(), None).unwrap(); + let c = Container::parse(&vs).unwrap(); + let inputs = signature(c.part(FourCC::ISG1).unwrap().data).unwrap(); + assert_eq!(inputs.iter().map(|e| (e.kind, e.comp)).collect::>(), [(1, 5), (2, 5)]); + let outputs = signature(c.part(FourCC::OSG1).unwrap().data).unwrap(); + assert_eq!(outputs.iter().map(|e| (e.kind, e.row, e.cols)).collect::>(), [(3, Some(0), 4)]); + #[cfg(windows)] + if let Some(v) = validator.as_mut() { + v.validate(&mut vs.clone()).unwrap_or_else(|e| panic!("mesh_vs: {e}")); + } + // The same program on a host with mesh shaders stays one. + super::lower::TEST_MESH_COMPUTE.set(Some(false)); + let ms = triangle_mesh(TRIANGLE).unwrap(); + assert_eq!(ms.mesh_out, None); + assert!(!ms.root_uavs.contains(&SLOT_MESH_OUT)); + super::lower::TEST_MESH_COMPUTE.set(None); + } + /// A triangle mesh program on the host GPU and on WARP (where they have /// mesh shaders): triangle (0, 1, 2) covers the target with its corners' /// edge flags set as without them; with the culling bit, nothing is lit. @@ -2761,6 +2843,7 @@ mod tests { stride: 0, size: (16, 16), mesh_groups: 1, + vertex_count: 0, }, ) .unwrap_or_else(|e| panic!("{label}: draw: {e}")); @@ -2782,6 +2865,145 @@ mod tests { } } + /// `D3D12-MESH-COMPUTE-FALLBACK` on a device: the triangle mesh program + /// run as compute, then drawn as a triangle list with its pass-through + /// vertex shader, lights the texels the mesh pipeline lights (all of + /// them in the pixel shader's colour, none when the program culls its + /// triangle), with or without edge flags. Where the device has mesh + /// shaders the two draws are compared texel for texel; the fallback + /// itself needs none (WARP, or a shader model 6.6 card). + #[test] + #[cfg(windows)] + fn a_mesh_program_run_as_compute_draws_what_the_mesh_pipeline_draws() { + use super::host::{Dispatch, Draw, Host, Root}; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_FEATURE_D3D12_OPTIONS7, D3D12_FEATURE_DATA_D3D12_OPTIONS7, + D3D12_MESH_SHADER_TIER_NOT_SUPPORTED, D3D12_SHADER_VISIBILITY_ALL, + D3D12_SHADER_VISIBILITY_MESH, D3D12_SHADER_VISIBILITY_VERTEX, + }; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let ps = constant_color(); + 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; + }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + // SAFETY: the query writes the structure of the given size. + let queried = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS7, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + }; + let mesh_shaders = + queried.is_ok() && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED; + let draw = |roots, mesh_groups, vertex_count| Draw { + roots, + textures: &[], + samplers: &[], + vertices: &[], + stride: 0, + size: (16, 16), + mesh_groups, + vertex_count, + }; + for (prim, culled) in [ + (TRIANGLE, false), + (TRIANGLE | EDGE_FLAGS, false), + (TRIANGLE | EDGE_FLAGS | CULL, true), + ] { + // The program as compute: its outputs into the root UAV. + super::lower::TEST_MESH_COMPUTE.set(Some(true)); + let cs = triangle_mesh(prim); + super::lower::TEST_MESH_COMPUTE.set(None); + let cs = cs.unwrap(); + let layout = cs.mesh_out.clone().unwrap(); + let root = host + .root_signature_for(&[(&cs, D3D12_SHADER_VISIBILITY_ALL)]) + .unwrap(); + let pso = host + .compute_pipeline_with(&root, &cs.dxil) + .unwrap_or_else(|e| panic!("{label}: compute pipeline: {e}")); + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(vec![0])), + (1, Root::Uav((MESH_OUT_HEADER + layout.group_bytes()) / 4)), + ], + views: &[], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch: {e}")); + let written = out.last().unwrap().clone(); + // Drawn with the pass-through vertex shader. + let vs = mesh_vs(&layout, Some(&ps)).unwrap(); + let vs_shader = HostShader { + stage: HwStage::Vs, + dxil: vs.clone(), + user_data: vec![], + samplers: vec![], + static_samplers: vec![], + root_cbvs: vec![], + root_srvs: vec![SLOT_MESH_IN], + root_uavs: vec![], + root_indexed_views: vec![], + half_views: vec![], + mesh_out: None, + }; + let root = host + .root_signature_for(&[(&vs_shader, D3D12_SHADER_VISIBILITY_VERTEX)]) + .unwrap(); + let pso = host + .pipeline_with(&root, &vs, &ps) + .unwrap_or_else(|e| panic!("{label}: pass-through pipeline: {e}")); + let roots = vec![ + (0, Root::Constants(vec![0])), + (1, Root::View { srv: true, data: written }), + ]; + let texels = host + .draw(&root, &pso, &draw(roots, 0, 3 * layout.max_primitives)) + .unwrap_or_else(|e| panic!("{label}: draw: {e}")); + let lit = texels.iter().filter(|t| t[3] != 0.0).count(); + if culled { + assert_eq!(lit, 0, "{label}, {prim:#x}: a culled triangle lit texels"); + } else { + assert!( + texels.iter().all(|t| *t == [1.0, 0.5, 0.25, 1.0]), + "{label}, {prim:#x}: {lit} of 256 texels lit" + ); + } + if mesh_shaders { + let ms = triangle_mesh(prim).unwrap(); + let root = host + .root_signature_for(&[(&ms, D3D12_SHADER_VISIBILITY_MESH)]) + .unwrap(); + let pso = host + .mesh_pipeline_with(&root, &ms.dxil, &ps) + .unwrap_or_else(|e| panic!("{label}: mesh pipeline: {e}")); + let native = host + .draw(&root, &pso, &draw(vec![(0, Root::Constants(vec![0]))], 1, 0)) + .unwrap_or_else(|e| panic!("{label}: mesh draw: {e}")); + assert_eq!(texels, native, "{label}, {prim:#x}: the fallback and the mesh pipeline differ"); + } + } + eprintln!("{label}: the mesh program drew as compute (mesh shaders there: {mesh_shaders})"); + ran += 1; + } + if ran == 0 { + eprintln!("no SM 6.6 device; skipped"); + } + } + /// A pixel shader interpolating at sample positions (PERSP_SAMPLE /// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency: /// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1) @@ -3003,6 +3225,7 @@ mod tests { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }) .unwrap(); // The calls that read the SRV: 28 a dword, 7 with four a call. @@ -3029,6 +3252,7 @@ mod tests { root_uavs: l.root_uavs, root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }; let (root, pso) = host.compute_pipeline(&cs).unwrap(); // Twelve dwords: the loads below run across the view's end. @@ -3132,6 +3356,7 @@ mod tests { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }) .unwrap(); super::shader::CONSTANTS_RAW_HERE.set(None); @@ -3165,6 +3390,7 @@ mod tests { root_uavs: l.root_uavs, root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }; let (root, pso) = host.compute_pipeline(&cs).unwrap(); let views: Vec = if raw { @@ -3291,6 +3517,7 @@ mod tests { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }) .unwrap(); let mut dxil = l.dxil; @@ -3313,6 +3540,7 @@ mod tests { root_uavs: l.root_uavs, root_indexed_views: Vec::new(), half_views: l.half_views, + mesh_out: None, }; let (root, pso) = host.compute_pipeline(&cs).unwrap(); let inputs: Vec = [ @@ -3751,6 +3979,7 @@ mod barycentric_tests { root_uavs: Vec::new(), root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }; validate(&vs); // One triangle covers an 8x8 target, with attribute values 2, 6, 10. @@ -3793,6 +4022,7 @@ mod barycentric_tests { stride: 32, size: (8, 8), mesh_groups: 0, + vertex_count: 0, }, ) .expect("draw partial interpolation"); diff --git a/d3d12/crates/leonida-shader/src/emit/pack_tests.rs b/d3d12/crates/leonida-shader/src/emit/pack_tests.rs index 2fa7f2275d..7ae9836689 100644 --- a/d3d12/crates/leonida-shader/src/emit/pack_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/pack_tests.rs @@ -152,6 +152,7 @@ fn translate(native: &NativeProgram, k: u32) -> Result outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }); lower::TEST_GROUP_PACK.set(packing); lower::TEST_HOST_WAVE.set(was); @@ -167,6 +168,7 @@ fn translate(native: &NativeProgram, k: u32) -> Result root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views.clone(), half_views: lowered.half_views, + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) diff --git a/d3d12/crates/leonida-shader/src/emit/permlane_tests.rs b/d3d12/crates/leonida-shader/src/emit/permlane_tests.rs index a72b559d9f..86edb1d087 100644 --- a/d3d12/crates/leonida-shader/src/emit/permlane_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/permlane_tests.rs @@ -93,6 +93,7 @@ fn lowered(native: &NativeProgram, host_wave: u32) -> Result Result { diff --git a/d3d12/crates/leonida-shader/src/emit/probe_tests.rs b/d3d12/crates/leonida-shader/src/emit/probe_tests.rs index b8fc775334..28413aa1d3 100644 --- a/d3d12/crates/leonida-shader/src/emit/probe_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/probe_tests.rs @@ -35,6 +35,7 @@ fn probe() { root_uavs: Vec::new(), root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }; let (root, pso) = match host.compute_pipeline(&shader) { Ok(made) => made, diff --git a/d3d12/crates/leonida-shader/src/emit/rect.rs b/d3d12/crates/leonida-shader/src/emit/rect.rs index ba2f4b9a05..983bc4c07b 100644 --- a/d3d12/crates/leonida-shader/src/emit/rect.rs +++ b/d3d12/crates/leonida-shader/src/emit/rect.rs @@ -416,6 +416,7 @@ mod tests { root_uavs: Vec::new(), root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }; ( host(crate::native::HwStage::Vs, vs), @@ -465,6 +466,7 @@ mod tests { stride: 32, size: (8, 8), mesh_groups: 0, + vertex_count: 0, }; host.draw(&root, &pso, &d).unwrap() }; diff --git a/d3d12/crates/leonida-shader/src/emit/shader.rs b/d3d12/crates/leonida-shader/src/emit/shader.rs index 2255f9ecdc..4ca71e678b 100644 --- a/d3d12/crates/leonida-shader/src/emit/shader.rs +++ b/d3d12/crates/leonida-shader/src/emit/shader.rs @@ -80,6 +80,22 @@ pub fn constant_marks() -> bool { pub const SLOT_MEMORY: u8 = 254; /// See [`SLOT_MEMORY`]. pub const SLOT_FAULTS: u8 = 253; +/// A mesh program translated as compute (the host has no mesh shaders): the +/// root UAV `u` takes what the mesh outputs would, one +/// [`MeshOut`] slot per group, for the pass-through vertex shader +/// (`mesh_vs.rs`) to read back as the root SRV `t`. +pub const SLOT_MESH_OUT: u8 = 251; +/// See [`SLOT_MESH_OUT`]. +pub const SLOT_MESH_IN: u8 = 250; +/// Bytes of the [`SLOT_MESH_OUT`] buffer: the header, then the groups' +/// slots ([`MeshOut::groups_cap`] of them and one more, where groups past +/// the cap write). +pub const MESH_OUT_BYTES: u32 = 64 << 20; +/// Bytes before the first group's slot: the draw arguments of the groups +/// written (`D3D12_DRAW_ARGUMENTS`: the host writes `3 * max_primitives` +/// to dword 0 and zero to dword 1 before a dispatch; each group raises +/// dword 1 to its id + 1, so it holds the group count for an indirect draw). +pub const MESH_OUT_HEADER: u32 = 256; /// Entries of the [`SLOT_MEMORY`] directory: title addresses below 128 GiB. pub const MEMORY_PAGES: u32 = 1 << 21; /// In a directory entry's first dword: shaders do not store there by address @@ -214,6 +230,74 @@ pub(crate) struct Mesh { pub topology: u8, } +/// Where a mesh program lowered as compute ([`SLOT_MESH_OUT`]) puts what +/// its outputs would hold, in bytes from the start of its group's slot: +/// `max_vertices` vertices of `vertex_stride` bytes, then `max_primitives` +/// primitives of `primitive_stride` bytes (three indices, then the +/// per-primitive outputs). Each output element takes one dword per +/// column, in signature order (`vertex_at`, `primitive_at`). The +/// pass-through vertex shader (`mesh_vs.rs`) reads the same layout. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MeshOut { + pub max_vertices: u32, + pub max_primitives: u32, + pub vertex_stride: u32, + pub primitive_stride: u32, + /// Byte offset of each vertex output element (OSG1 order). + pub vertex_at: Vec, + /// Byte offset of each per-primitive output element (PSG1 order), + /// past the three indices. + pub primitive_at: Vec, + /// The mesh program's vertex outputs as an `OSG1` part, and its + /// per-primitive outputs as a `PSG1` part: what the pass-through vertex + /// shader outputs. + pub osg1: Vec, + pub psg1: Vec, +} + +impl MeshOut { + /// The layout for these maxima and signatures. + pub fn new(max_vertices: u32, max_primitives: u32, outputs: &[SigElement], prims: &[SigElement]) -> Self { + let place = |first: u32, elements: &[SigElement]| { + let mut at = Vec::with_capacity(elements.len()); + let mut next = first; + for e in elements { + at.push(next); + next += 4 * u32::from(e.cols); + } + (at, next) + }; + let (vertex_at, vertex_stride) = place(0, outputs); + let (primitive_at, primitive_stride) = place(12, prims); + MeshOut { + max_vertices, + max_primitives, + vertex_stride, + primitive_stride, + vertex_at, + primitive_at, + osg1: super::container::signature(outputs, false), + psg1: super::container::signature(prims, false), + } + } + + /// Bytes of one group's slot. + pub fn group_bytes(&self) -> u32 { + self.max_vertices * self.vertex_stride + self.max_primitives * self.primitive_stride + } + + /// Groups with a slot of their own in [`MESH_OUT_BYTES`]; one more slot + /// takes the writes of every group past them (which draw nothing). + pub fn groups_cap(&self) -> u32 { + ((MESH_OUT_BYTES - MESH_OUT_HEADER) / self.group_bytes().max(4)).saturating_sub(1).max(1) + } + + /// Byte offset of primitive 0 in a group's slot. + pub fn primitives_at(&self) -> u32 { + self.max_vertices * self.vertex_stride + } +} + /// What a geometry shader declares: triangles in, triangle strips out on /// stream 0, one instance. #[derive(Debug, Clone, Copy)] @@ -304,6 +388,10 @@ pub(crate) struct Shader { pub prims: Vec, /// A mesh shader (`threads` is its thread-group size). pub mesh: Option, + /// The mesh program is lowered as compute: the outputs go to + /// [`SLOT_MESH_OUT`] in this layout (`mesh` stays set while lowering and + /// is cleared before [`Shader::finish`]). + pub mesh_compute: Option, /// A geometry shader (the rectangle stage, `rect.rs`); `pixel` is false. pub geometry: Option, /// Dwords of user data the shader reads (0: no user-data buffer). @@ -368,6 +456,7 @@ impl Shader { outputs: Vec::new(), prims: Vec::new(), mesh: None, + mesh_compute: None, geometry: None, user_data: 0, samplers: 0, diff --git a/d3d12/crates/leonida-shader/src/emit/size_tests.rs b/d3d12/crates/leonida-shader/src/emit/size_tests.rs index 9cba89a92f..300fffe28c 100644 --- a/d3d12/crates/leonida-shader/src/emit/size_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/size_tests.rs @@ -62,6 +62,7 @@ fn build(words: &[u32], srv: (u8, u32)) -> Result { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, })?; let shader = HostShader { stage: HwStage::Cs, @@ -74,6 +75,7 @@ fn build(words: &[u32], srv: (u8, u32)) -> Result { root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) diff --git a/d3d12/crates/leonida-shader/src/emit/valu_tests.rs b/d3d12/crates/leonida-shader/src/emit/valu_tests.rs index 4f10e95e9b..3a21bdec14 100644 --- a/d3d12/crates/leonida-shader/src/emit/valu_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/valu_tests.rs @@ -168,6 +168,7 @@ fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }) .expect("lower"); @@ -182,6 +183,7 @@ fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader { root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, half_views: lowered.half_views, + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { @@ -1954,6 +1956,7 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }) .expect("lower"); @@ -1968,6 +1971,7 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() { root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), half_views: lowered.half_views, + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); @@ -2166,6 +2170,7 @@ fn build_table_typed_cs(body: &[u32], used: Vec) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }) .expect("lower"); let shader = HostShader { @@ -2179,6 +2184,7 @@ fn build_table_typed_cs(body: &[u32], used: Vec) -> HostShader { root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, half_views: lowered.half_views, + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); diff --git a/d3d12/crates/leonida-shader/src/emit/waterfall_tests.rs b/d3d12/crates/leonida-shader/src/emit/waterfall_tests.rs index b25f684e94..a0d76ba95a 100644 --- a/d3d12/crates/leonida-shader/src/emit/waterfall_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/waterfall_tests.rs @@ -69,6 +69,7 @@ fn build(words: &[u32], buffers: bool) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }) .expect("lower"); // One access with each lane's own heap index, no wave operation. @@ -85,6 +86,7 @@ fn build(words: &[u32], buffers: bool) -> HostShader { root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), half_views: lowered.half_views, + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) @@ -369,6 +371,7 @@ fn immediate_sampler_chosen_by_control_flow() { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }) .unwrap_or_else(|e| panic!("{case_name}: lower failed: {e}")); @@ -388,6 +391,7 @@ fn immediate_sampler_chosen_by_control_flow() { root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) diff --git a/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs b/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs index 309dc48eb2..5f5247409e 100644 --- a/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs @@ -129,6 +129,7 @@ fn lowered_counted( outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }, counted); lower::TEST_HOST_WAVE.set(was); let lowered = lowered?; @@ -143,6 +144,7 @@ fn lowered_counted( root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, half_views: lowered.half_views, + mesh_out: None, }) } @@ -268,6 +270,7 @@ fn on_64_lanes(native: &NativeProgram, p: &ir::Program) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }); lower::TEST_HOST_WAVE.set(was); let lowered = lowered.expect("lower"); @@ -283,6 +286,7 @@ fn on_64_lanes(native: &NativeProgram, p: &ir::Program) -> HostShader { root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, half_views: Vec::new(), + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); @@ -1010,6 +1014,7 @@ fn flag_wave(native: &NativeProgram) -> Option { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }); lower::TEST_HOST_WAVE.set(was); lowered.expect("lower").wave_size @@ -1353,6 +1358,7 @@ fn partial_dispatch_with_a_cross_half_wave_op_runs_in_32_lane_waves() { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }); lower::TEST_HOST_WAVE.set(was); let lowered = lowered.unwrap_or_else(|e| panic!("lower: {e}")); @@ -1374,6 +1380,7 @@ fn partial_dispatch_with_a_cross_half_wave_op_runs_in_32_lane_waves() { root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views.clone(), half_views: lowered.half_views, + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()).unwrap_or_else(|e| panic!("DXIL validation: {e}")); From dc5818bb8424d96b642ba07cd03a3251d529a147 Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sat, 28 Nov 2026 19:35:42 +0200 Subject: [PATCH 02/15] d3d12: mesh pipelines draw through compute and a triangle list without mesh shaders At device creation the translator is told whether the host has mesh shaders at shader model 6.6 (LEONIDA_MESH_COMPUTE=1 takes the fallback on any card). Without them, a mesh pipeline is made as two: - the mesh program as a compute pipeline; - the pass-through vertex shader with the title's pixel shader and state, drawing triangle lists with no vertex input. The draw path: - A mesh dispatch binds the compute pipeline with the title's graphics root arguments (roots_ref reads them while title_side_graphics is set). - It dispatches and draws 3 * max_primitives vertices, one instance a group. - An indirect one writes the header's draw arguments (WriteBufferImmediate), runs the title's record with a dispatch signature, and draws from the header with ExecuteIndirect. - The buffer goes common -> UAV -> shader resource and indirect argument -> common. shortcut: an indirect call of several records is left out (each would fill the same slots). MEASURED on a GTX 1050 Ti (Pascal: mesh shader tier 0), Windows 10 with #2557: the title gets past its start screen through the opening cutscenes into the first playable scene. Without this, every mesh pipeline was refused and the world drew nothing. Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/draw.rs | 211 +++++++++++++++++- d3d12/crates/leonida-gpu/src/host.rs | 18 ++ d3d12/crates/leonida-gpu/src/pipeline.rs | 63 ++++++ d3d12/crates/leonida-gpu/src/pipeline/host.rs | 76 ++++++- 4 files changed, 366 insertions(+), 2 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index d729e65cad..8381f99392 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs @@ -67,6 +67,22 @@ fn is_depth_companion(stencil: &View, depth: &View) -> bool { && s[7] == d[7] } +/// The device-local buffer mesh programs run as compute write to +/// ([`leonida_shader::emit::MESH_OUT_BYTES`], made once; it starts and ends +/// each use in the common state). +fn mesh_buffer() -> Option { + static BUFFER: std::sync::Mutex> = std::sync::Mutex::new(None); + let mut held = BUFFER.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(b) = held.as_ref() { + return Some(b.clone()); + } + let size = u64::from(leonida_shader::emit::MESH_OUT_BYTES); + let b = crate::host::host()?.uav_buffer(size)?; + tracing::info!(mib = size >> 20, "mesh buffer (mesh programs run as compute)"); + *held = Some(b.clone()); + Some(b) +} + /// Shader interface metadata shared by every pipeline variant and draw. pub(crate) struct TablePlan { groups: Vec, @@ -980,6 +996,10 @@ pub(crate) struct State { heaps: [usize; 2], graphics: Vec, compute: Vec, + /// While a mesh program runs as compute (`D3D12-MESH-COMPUTE-FALLBACK`): + /// its root arguments are the title's graphics ones, bound on the + /// compute side. + title_side_graphics: bool, vertex: [VertexView; 32], index: IndexView, /// Bound render target and depth resources, for their host states. @@ -2694,6 +2714,10 @@ impl State { } for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] { for (at, &(slot, param)) in views.iter().enumerate() { + if srv && slot == leonida_shader::emit::SLOT_MESH_IN { + // Ours: the mesh buffer, bound by `mesh_as_compute`. + continue; + } if srv && slot == leonida_shader::emit::SLOT_MEMORY { // Ours: the directory of title memory by address. if let Some(m) = &memory { @@ -2763,6 +2787,10 @@ impl State { } } for &(slot, param) in &stage.root_uavs { + if slot == leonida_shader::emit::SLOT_MESH_OUT { + // Ours: the mesh buffer, bound by `mesh_as_compute`. + continue; + } if slot == leonida_shader::emit::SLOT_FAULTS { // Ours: where shaders note the pages they found empty. if let Some(m) = &memory { @@ -4619,6 +4647,148 @@ impl State { ) } + /// `D3D12-MESH-COMPUTE-FALLBACK`: `x` groups of a mesh pipeline on a host + /// without mesh shaders. The mesh program runs as compute with the + /// title's graphics root arguments, writing each group's outputs to the + /// mesh buffer; the pipeline then draws them as a triangle list of + /// `x * max_primitives * 3` vertices through its pass-through vertex + /// shader. The buffer starts and ends each use in the common state, so + /// every list finds it there. + fn mesh_as_compute(&mut self, list: &HostList, x: u32, p: &crate::pipeline::host::HostPipeline) -> bool { + let Some(mc) = p.mesh_compute.as_deref() else { + return false; + }; + // Groups past the buffer's slots (`MeshOut::groups_cap`) draw nothing. + if x > mc.layout.groups_cap() { + once!(x, cap = mc.layout.groups_cap(), "a mesh dispatch of more groups than the mesh buffer holds: the rest draw nothing"); + } + let n = x.min(65_535); + if n == 0 { + return true; + } + let Some(buffer) = mesh_buffer() else { + once!("no mesh buffer: the mesh draw is dropped"); + return false; + }; + let l = &list.list; + self.title_side_graphics = true; + let bound = self.bind(list, &mc.cs, true); + self.title_side_graphics = false; + if !bound { + return false; + } + use windows::Win32::Graphics::Direct3D12::{ + D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + }; + // SAFETY: an open list, a live buffer and the compute pipeline bound. + unsafe { + l.ResourceBarrier(&[crate::host::transition( + &buffer, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + l.SetComputeRootUnorderedAccessView(mc.out_param, buffer.GetGPUVirtualAddress()); + l.Dispatch(n, 1, 1); + l.ResourceBarrier(&[crate::host::transition( + &buffer, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + } + // The compute pipeline took the list's pipeline slot. + self.host_pipeline = 0; + let drawn = self.prepare_for(list, false, true); + // SAFETY: as above, the graphics pipeline bound when `drawn`. + unsafe { + if drawn { + self.mesh_scissor(list, true); + l.SetGraphicsRootShaderResourceView(mc.in_param, buffer.GetGPUVirtualAddress()); + l.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + l.DrawInstanced(mc.layout.max_primitives * 3, n, 0, 0); + self.mesh_scissor(list, false); + } + l.ResourceBarrier(&[crate::host::transition( + &buffer, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_COMMON, + )]); + } + list.keep(&buffer); + drawn + } + + /// [`Self::mesh_as_compute`] for one indirect record: the record's + /// `(x, y, z)` is a dispatch's arguments as it stands (`stride` apart), + /// so the compute pipeline runs it as recorded; its groups raise the + /// buffer header's instance count, and the draw reads the header's + /// arguments (`3 * max_primitives` vertices, one instance a group). + fn mesh_indirect_as_compute( + &mut self, + list: &HostList, + p: &crate::pipeline::host::HostPipeline, + (arguments, at, stride): (&ID3D12Resource, u64, u32), + count: Option<(&ID3D12Resource, u64)>, + ) -> bool { + let Some(mc) = p.mesh_compute.as_deref() else { + return false; + }; + let (Some(dispatch), Some(draw)) = (host_signature(2, stride), host_signature(0, 16)) else { + return false; + }; + let Some(buffer) = mesh_buffer() else { + once!("no mesh buffer: the mesh draw is dropped"); + return false; + }; + let Ok(l2) = list.list.cast::() else { + return false; + }; + self.title_side_graphics = true; + let bound = self.bind(list, &mc.cs, true); + self.title_side_graphics = false; + if !bound { + return false; + } + use windows::Win32::Graphics::Direct3D12::{ + D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, + }; + let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + let l = &list.list; + // SAFETY: an open list, live buffers and the compute pipeline bound. + unsafe { + let va = buffer.GetGPUVirtualAddress(); + l.ResourceBarrier(&[crate::host::transition(&buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); + let header = [mc.layout.max_primitives * 3, 0, 0, 0].map(|v| v); + let params: Vec = header + .iter() + .enumerate() + .map(|(k, &value)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: va + 4 * k as u64, Value: value }) + .collect(); + l2.WriteBufferImmediate(params.len() as u32, params.as_ptr(), None); + l.ResourceBarrier(&[crate::host::transition(&buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + l.SetComputeRootUnorderedAccessView(mc.out_param, va); + l.ExecuteIndirect(&dispatch, 1, arguments, at, count.map(|c| c.0), count.map_or(0, |c| c.1)); + l.ResourceBarrier(&[crate::host::transition(&buffer, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, read)]); + } + self.host_pipeline = 0; + let drawn = self.prepare_for(list, false, true); + // SAFETY: as above, the graphics pipeline bound when `drawn`. + unsafe { + if drawn { + self.mesh_scissor(list, true); + l.SetGraphicsRootShaderResourceView(mc.in_param, buffer.GetGPUVirtualAddress()); + l.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + l.ExecuteIndirect(&draw, 1, &buffer, 0, None, 0); + self.mesh_scissor(list, false); + } + l.ResourceBarrier(&[crate::host::transition(&buffer, read, D3D12_RESOURCE_STATE_COMMON)]); + } + list.keep(&buffer); + drawn + } + /// A mesh draw under `LEONIDA_MESH_TEST=scissor` rasterises one pixel: /// the scissors before it (`on`), the title's after it. fn mesh_scissor(&self, list: &HostList, on: bool) { @@ -4645,6 +4815,20 @@ impl State { crate::drops::begin(); crate::drops::note(Why::SkipList); } + // Without mesh shaders: the program as compute, its output drawn. + let fallback = crate::pipeline::host_pipeline_for(self.pipeline as This, &self.target_formats) + .filter(|p| p.mesh_compute.is_some()); + if let Some(p) = fallback { + let ran = !held && self.mesh_as_compute(list, x, p); + if ran { + self.drew(Some(p)); + DRAWN.fetch_add(1, Ordering::Relaxed); + } else { + DROPPED.fetch_add(1, Ordering::Relaxed); + crate::drops::count_noted(Kind::Draw, Why::Other); + } + return; + } let ran = !held && self.prepare_for(list, false, true) && match list.list.cast::() { @@ -4747,7 +4931,7 @@ impl State { } fn roots_ref(&self, compute: bool) -> &Vec { - if compute { + if compute && !self.title_side_graphics { &self.compute } else { &self.graphics @@ -5681,6 +5865,19 @@ impl State { )); return false; } + // `D3D12-MESH-COMPUTE-FALLBACK`: the pipeline is a compute and a + // graphics one, not a mesh pipeline, so the title's indirect mesh + // dispatch cannot run as recorded (the host loses the device when it + // is: 2026-11-28, GTX 1050 Ti). + // So it runs as compute and a draw (`mesh_indirect_as_compute`), one + // record at a time. + // shortcut: several records a call (each would fill the same slots) + // are left out. + if kind == MESH && p.mesh_compute.is_some() && max != 1 { + once!(max, "an indirect mesh dispatch of several records without mesh shaders is left out"); + why("an indirect mesh dispatch of several records without mesh shaders"); + return false; + } // A program run several console groups to a host group takes the console's grid from // root constants the records carry (`crate::indirect::bound_packed`). if kind == DISPATCH && pack_broken(p) { @@ -5820,6 +6017,18 @@ impl State { (bounded, 0) } }; + if kind == MESH && p.mesh_compute.is_some() { + let counted = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); + let ran = self.mesh_indirect_as_compute(list, p, (&bounded, at, stride), counted); + if ran { + self.drew(Some(p)); + DRAWN.fetch_add(1, Ordering::Relaxed); + } else { + crate::drops::note(Why::BindFailed); + why("the mesh program as compute did not run"); + } + return ran; + } let ran = match kind { DRAW | INDEXED => self.prepare(list, kind == INDEXED), MESH => self.prepare_for(list, false, true), diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index 41a90d743f..c5d47593d6 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -1191,6 +1191,24 @@ fn create() -> windows::core::Result { let amd = crate::indirect::amd(&device); leonida_shader::emit::set_host_rdna(amd && o1.WaveLaneCountMin == 32 && o1.WaveLaneCountMax == 64); } + // `D3D12-MESH-COMPUTE-FALLBACK`: without mesh shaders at shader model 6.6 (Pascal and older) the + // translator writes mesh programs as compute, drawn through a vertex shader of ours + // (`pipeline::host::MeshCompute`). `LEONIDA_MESH_COMPUTE=1` takes that path on any card. + let mut o7 = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + let mut model = D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: D3D_SHADER_MODEL_6_6, + }; + let mesh = device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, (&raw mut o7).cast(), size_of_val(&o7) as u32) + .is_ok() + && device + .CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, (&raw mut model).cast(), size_of_val(&model) as u32) + .is_ok() + && o7.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED + && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0; + let forced = std::env::var_os("LEONIDA_MESH_COMPUTE").is_some_and(|v| v == "1"); + leonida_shader::emit::set_host_mesh_shaders(mesh && !forced); + tracing::info!(mesh, forced, "mesh programs run as compute: {}", !mesh || forced); let messages = debug .then(|| device.cast::().ok()) .flatten(); diff --git a/d3d12/crates/leonida-gpu/src/pipeline.rs b/d3d12/crates/leonida-gpu/src/pipeline.rs index b6122e33d4..fbf2a5c58d 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline.rs @@ -176,6 +176,69 @@ pub(crate) struct Translated { #[cfg(windows)] impl Shader { + /// `D3D12-MESH-COMPUTE-FALLBACK`, on a host without mesh shaders: this + /// mesh program seen as a compute stage (its translation there is the + /// compute variant, which writes its outputs to + /// [`leonida_shader::emit::SLOT_MESH_OUT`]), and the pass-through vertex + /// shader that draws what it wrote in front of the pixel shader `ps`, + /// with the layout both use. None when the program did not translate + /// as compute or the vertex shader cannot be made (logged). + pub(crate) fn mesh_fallback( + &self, + ps: Option<&Shader>, + ) -> Option<(Arc, Arc, leonida_shader::emit::MeshOut)> { + let layout = self.translated()?.host.mesh_out.clone()?; + let cs = Arc::new(Shader { + stage: "compute", + hash: self.hash.clone(), + container: self.container.clone(), + ambient: None, + translated: OnceLock::new(), + }); + let ps_dxil = ps.and_then(Shader::translated).map(|t| t.host.dxil.as_slice()); + let dxil = match leonida_shader::emit::mesh_vs(&layout, ps_dxil) { + Ok(dxil) => dxil, + Err(e) => { + tracing::warn!(error = %e, shader = %self.hash, "no pass-through vertex shader for a mesh program"); + return None; + } + }; + let host = leonida_shader::emit::HostShader { + stage: leonida_shader::HwStage::Vs, + dxil, + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: vec![leonida_shader::emit::SLOT_MESH_IN], + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + half_views: Vec::new(), + mesh_out: None, + }; + let vs = Arc::new(Shader { + stage: "vertex", + hash: format!("{}.vs", self.hash), + container: Vec::new(), + ambient: None, + translated: OnceLock::from(Some(Translated { + host, + threads: None, + used: Vec::new(), + tables: crate::draw::TablePlan::new(&[], &[]), + stores: false, + stores_by_address: false, + stores_past_views: false, + writes: false, + pack: None, + pack_logged: Default::default(), + picks: Default::default(), + bound: Default::default(), + })), + }); + Some((cs, vs, layout)) + } + /// The translation, made on first use; a shader that does not /// translate is logged once. pub(crate) fn translated(&self) -> Option<&Translated> { diff --git a/d3d12/crates/leonida-gpu/src/pipeline/host.rs b/d3d12/crates/leonida-gpu/src/pipeline/host.rs index 6776eab8e1..e07f3ebca7 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/host.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/host.rs @@ -582,6 +582,19 @@ fn biased_root_srvs(root_srvs: &[(u8, u32)], user_data: &[leonida_shader::emit:: .fold(0, |mask, (at, _)| mask | 1 << at) } +/// `D3D12-MESH-COMPUTE-FALLBACK`: how a mesh pipeline runs on a host +/// without mesh shaders. The mesh program runs as compute (`cs`), writing +/// its groups' outputs to a buffer bound as its root UAV `out_param`; the +/// pipeline it belongs to then draws them as a triangle list with the +/// pass-through vertex shader, reading the buffer as its root SRV +/// `in_param`. `layout` is where each group's outputs lie. +pub(crate) struct MeshCompute { + pub(crate) cs: HostPipeline, + pub(crate) out_param: u32, + pub(crate) in_param: u32, + pub(crate) layout: leonida_shader::emit::MeshOut, +} + pub(crate) struct HostPipeline { /// A compute pipeline (else graphics). pub(crate) compute: bool, @@ -604,6 +617,8 @@ pub(crate) struct HostPipeline { /// listing (empty for compute). #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] pub(crate) state: String, + /// A mesh pipeline drawn without mesh shaders ([`MeshCompute`]). + pub(crate) mesh_compute: Option>, } /// Logs a pipeline that gets no host pipeline, once per reason. @@ -640,6 +655,9 @@ impl HostPipeline { ); } let mesh = find("mesh"); + if mesh.is_some() && leonida_shader::emit::mesh_as_compute() { + return Self::mesh_compute(shaders, g); + } let stages = if let Some(cs) = compute { vec![(cs, D3D12_SHADER_VISIBILITY_ALL)] } else { @@ -717,11 +735,12 @@ impl HostPipeline { // table of strides, the directory of title memory by // address and its fault notes. let ours = if uav { - slot == leonida_shader::emit::SLOT_FAULTS + slot == leonida_shader::emit::SLOT_FAULTS || slot == leonida_shader::emit::SLOT_MESH_OUT } else { slot == leonida_shader::emit::SLOT_STRIDES || slot == leonida_shader::emit::SLOT_TABLE_STRIDES || slot == leonida_shader::emit::SLOT_MEMORY + || slot == leonida_shader::emit::SLOT_MESH_IN }; if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() { // A one-view table: the view's size bounds the @@ -849,6 +868,7 @@ impl HostPipeline { inputs: Vec::new(), rects: false, state: String::new(), + mesh_compute: None, }); } let Some(g) = g else { @@ -905,6 +925,7 @@ impl HostPipeline { inputs: Vec::new(), rects: false, state: String::new(), + mesh_compute: None, }); } @@ -1026,6 +1047,7 @@ impl HostPipeline { slots: g.slots(), inputs: g.elements(), rects: rect_gs.is_some(), + mesh_compute: None, state: { let (d, r, b) = (&g.depth, &g.rasterizer, &g.blend.RenderTarget[0]); let face = |f: &D3D12_DEPTH_STENCILOP_DESC| { @@ -1082,6 +1104,58 @@ pub(super) fn stream_pipeline( ) } +impl HostPipeline { + /// A mesh pipeline on a host without mesh shaders + /// (`D3D12-MESH-COMPUTE-FALLBACK`): the mesh program as a compute + /// pipeline, and a graphics pipeline of the pass-through vertex shader + /// and the title's pixel shader with the title's state, drawing + /// triangle lists with no vertex input. The graphics one is returned, + /// as a mesh pipeline (the draw path takes it for mesh dispatches), + /// carrying the compute one. + fn mesh_compute(shaders: &[Arc], g: Option<&GraphicsState>) -> Option { + let ms = shaders.iter().find(|s| s.stage == "mesh")?; + let ps = shaders.iter().find(|s| s.stage == "pixel"); + let Some(g) = g else { + return refuse("graphics state not kept (plain description)", shaders); + }; + let Some((cs, vs, layout)) = ms.mesh_fallback(ps.map(|p| &**p)) else { + return refuse("a mesh program that does not run as compute", shaders); + }; + let compute = HostPipeline::new(&[cs], None)?; + let out_param = compute + .stages + .first()? + .root_uavs + .iter() + .find(|r| r.0 == leonida_shader::emit::SLOT_MESH_OUT)? + .1; + // The title's state, drawing triangles from no vertex input. + let mut state = g.with_formats(&g.formats()); + state.topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + state.inputs.clear(); + state.names.clear(); + let mut stages = vec![vs]; + stages.extend(ps.cloned()); + let mut graphics = HostPipeline::new(&stages, Some(&state))?; + let in_param = graphics + .stages + .first()? + .root_srvs + .iter() + .find(|r| r.0 == leonida_shader::emit::SLOT_MESH_IN)? + .1; + tracing::info!(?shaders, "host mesh pipeline as compute and a triangle list (no mesh shaders)"); + graphics.mesh = true; + graphics.mesh_compute = Some(Box::new(MeshCompute { + cs: compute, + out_param, + in_param, + layout, + })); + Some(graphics) + } +} + /// A graphics pipeline enabling the depth bounds test: `D3D12_GRAPHICS_PIPELINE_STATE_DESC` /// has no field for `DepthBoundsTestEnable`, so it is created and loaded as a /// pipeline-state stream with `DEPTH_STENCIL1`. From bc0c72f500a486fd88a761b5b65221a73fa14740 Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sun, 29 Nov 2026 12:20:05 +0200 Subject: [PATCH 03/15] d3d12: mesh fallback review fixes: no mesh signature for it, the sink slot drawn by no instance, the title's topology back, offsets beside their elements From timbot103's audit of dc5818bb8 (#2580): - An indirect mesh dispatch run as compute makes no host mesh command signature first: a host without mesh shaders may refuse one, and the fallback needs none (draw.rs). - Slot `groups_cap` is the sink every group from the cap on writes to at once: mesh_vs draws nothing for an instance from the cap on (it took only those past it), and the direct path draws at most `cap` instances. - The fallback's triangle list no longer stays the list's topology: the title's comes back after it (`restore_topology`). - MeshOut's OSG1/PSG1 parts keep their elements in the order of the byte offsets made for them: sorted by register, an element stood beside another's offset where the outputs were not in register order. - A per-primitive render-target or viewport index is refused by mesh_vs rather than left out (the translator does not export them yet). - The host device is made before a pipeline chooses between the mesh path and the fallback, so a pipeline made first cannot keep the mesh path. - The mesh program's own stores (to title buffers) count after a fallback draw, as the draw's do (`drew_mesh_as_compute`). Tests: mesh_out_parts_keep_their_elements_beside_their_offsets (fails without the fix), the_mesh_sink_slot_draws_nothing (GPU; the test harness's Draw takes an instance count). Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/draw.rs | 53 ++++++-- d3d12/crates/leonida-gpu/src/pipeline/host.rs | 7 + .../leonida-shader/src/emit/container.rs | 16 ++- .../leonida-shader/src/emit/diff_tests.rs | 2 + d3d12/crates/leonida-shader/src/emit/host.rs | 4 +- .../crates/leonida-shader/src/emit/mesh_vs.rs | 12 +- d3d12/crates/leonida-shader/src/emit/mod.rs | 121 ++++++++++++++++++ d3d12/crates/leonida-shader/src/emit/rect.rs | 1 + .../crates/leonida-shader/src/emit/shader.rs | 6 +- 9 files changed, 208 insertions(+), 14 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index 8381f99392..7b1cbc432d 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs @@ -1995,6 +1995,14 @@ impl State { }; } + /// The title's topology on the list again, after a pass of ours set + /// another (the mesh fallback's triangle list). + fn restore_topology(&mut self, list: &HostList) { + if self.topology_set { + self.set_topology(list, self.topology); + } + } + pub(crate) fn set_pipeline(&mut self, pipeline: This) { self.pipeline = pipeline as usize; } @@ -4705,7 +4713,8 @@ impl State { self.mesh_scissor(list, true); l.SetGraphicsRootShaderResourceView(mc.in_param, buffer.GetGPUVirtualAddress()); l.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - l.DrawInstanced(mc.layout.max_primitives * 3, n, 0, 0); + // Instances from the cap on would read the sink slot. + l.DrawInstanced(mc.layout.max_primitives * 3, n.min(mc.layout.groups_cap()), 0, 0); self.mesh_scissor(list, false); } l.ResourceBarrier(&[crate::host::transition( @@ -4714,6 +4723,11 @@ impl State { D3D12_RESOURCE_STATE_COMMON, )]); } + // The fallback drew a triangle list: the title's next draw has its + // own topology again. + if drawn { + self.restore_topology(list); + } list.keep(&buffer); drawn } @@ -4785,6 +4799,11 @@ impl State { } l.ResourceBarrier(&[crate::host::transition(&buffer, read, D3D12_RESOURCE_STATE_COMMON)]); } + // The fallback drew a triangle list: the title's next draw has its + // own topology again. + if drawn { + self.restore_topology(list); + } list.keep(&buffer); drawn } @@ -4821,7 +4840,7 @@ impl State { if let Some(p) = fallback { let ran = !held && self.mesh_as_compute(list, x, p); if ran { - self.drew(Some(p)); + self.drew_mesh_as_compute(p); DRAWN.fetch_add(1, Ordering::Relaxed); } else { DROPPED.fetch_add(1, Ordering::Relaxed); @@ -5651,6 +5670,16 @@ impl State { /// A draw with the pipeline `p` was recorded (as [`State::buffers_written`] /// if its shaders can store to buffers). + /// [`Self::drew`] for a mesh pipeline run as compute and a draw: the + /// mesh program's own stores (to title buffers; its outputs to the mesh + /// buffer are not counted) as well as the draw's. + fn drew_mesh_as_compute(&mut self, p: &HostPipeline) { + self.drew(Some(p)); + if let Some(mc) = p.mesh_compute.as_deref() { + self.drew(Some(&mc.cs)); + } + } + fn drew(&mut self, p: Option<&HostPipeline>) { if p.is_none_or(|p| p.stages.iter().any(|stage| stage.translated().stores)) { // (With 4 a known pipeline's stores are told apart by address, if they are all @@ -5901,16 +5930,20 @@ impl State { }, None => None, }; - let Some(signature) = matches!(kind, DRAW | INDEXED | DISPATCH | MESH) + // A mesh program run as compute needs no host signature of its own + // (`mesh_indirect_as_compute` makes its own of a dispatch and a + // draw), and a host without mesh shaders may refuse a mesh one. + let as_compute = kind == MESH && p.mesh_compute.is_some(); + let signature = (matches!(kind, DRAW | INDEXED | DISPATCH | MESH) && !as_compute) .then(|| match pack { Some(pack) => pack_signature(&p.root, pack), None => host_signature(kind, stride), }) - .flatten() - else { + .flatten(); + if signature.is_none() && !as_compute { why("no host signature"); return false; - }; + } if kind == MESH && (mesh_test() == 1 || !mesh_kept(self.pipeline)) { crate::drops::note(Why::SkipList); why("mesh draws are switched off (LEONIDA_MESH_TEST=skip)"); @@ -6017,11 +6050,11 @@ impl State { (bounded, 0) } }; - if kind == MESH && p.mesh_compute.is_some() { + if as_compute { let counted = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); let ran = self.mesh_indirect_as_compute(list, p, (&bounded, at, stride), counted); if ran { - self.drew(Some(p)); + self.drew_mesh_as_compute(p); DRAWN.fetch_add(1, Ordering::Relaxed); } else { crate::drops::note(Why::BindFailed); @@ -6029,6 +6062,10 @@ impl State { } return ran; } + // (Made above for every kind but a mesh program run as compute.) + let Some(signature) = signature else { + return false; + }; let ran = match kind { DRAW | INDEXED => self.prepare(list, kind == INDEXED), MESH => self.prepare_for(list, false, true), diff --git a/d3d12/crates/leonida-gpu/src/pipeline/host.rs b/d3d12/crates/leonida-gpu/src/pipeline/host.rs index e07f3ebca7..5e141f0c1a 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/host.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/host.rs @@ -655,6 +655,13 @@ impl HostPipeline { ); } let mesh = find("mesh"); + // Whether mesh programs run as compute is known once the host device + // is made (`crate::host::create`): made first, so a pipeline made + // before it does not take (and keep) the mesh path on a host + // without mesh shaders. + if mesh.is_some() { + host()?; + } if mesh.is_some() && leonida_shader::emit::mesh_as_compute() { return Self::mesh_compute(shaders, g); } diff --git a/d3d12/crates/leonida-shader/src/emit/container.rs b/d3d12/crates/leonida-shader/src/emit/container.rs index 9ed2b78bd0..c41618ec92 100644 --- a/d3d12/crates/leonida-shader/src/emit/container.rs +++ b/d3d12/crates/leonida-shader/src/emit/container.rs @@ -66,6 +66,18 @@ impl SigElement { /// `ISG1`/`OSG1`: 32-byte rows, then the names. pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec { + signature_sorted(elements, input, true) +} + +/// [`signature`] with the elements in the order given, not sorted by +/// register: for a part only we read back (a mesh program's outputs, +/// `super::shader::MeshOut`), whose elements must stay beside the byte +/// offsets made in that order. +pub(crate) fn signature_in_order(elements: &[SigElement], input: bool) -> Vec { + signature_sorted(elements, input, false) +} + +fn signature_sorted(elements: &[SigElement], input: bool, sorted: bool) -> Vec { let mut out = Vec::new(); out.extend((elements.len() as u32).to_le_bytes()); out.extend(8u32.to_le_bytes()); @@ -90,7 +102,9 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec { } } let mut order: Vec = (0..elements.len()).collect(); - order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), offsets[i])); + if sorted { + order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), offsets[i])); + } for i in order { let (e, offset) = (&elements[i], offsets[i]); let used = e.usage << e.col; diff --git a/d3d12/crates/leonida-shader/src/emit/diff_tests.rs b/d3d12/crates/leonida-shader/src/emit/diff_tests.rs index f0094ad7b2..91879879e9 100644 --- a/d3d12/crates/leonida-shader/src/emit/diff_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/diff_tests.rs @@ -774,6 +774,7 @@ fn translated_shaders_draw_as_pc_ones() { size: (16, 16), mesh_groups: 0, vertex_count: 0, + instances: 0, }; let mut failures = Vec::new(); let only = std::env::var("LEONIDA_DIFF_ONLY").ok(); @@ -897,6 +898,7 @@ fn translated_mesh_shaders_draw_as_pc_ones() { size: (16, 16), mesh_groups, vertex_count: 0, + instances: 0, }; let mut failures = Vec::new(); let only = std::env::var("LEONIDA_DIFF_ONLY").ok(); diff --git a/d3d12/crates/leonida-shader/src/emit/host.rs b/d3d12/crates/leonida-shader/src/emit/host.rs index 103d46cc9c..26c3316676 100644 --- a/d3d12/crates/leonida-shader/src/emit/host.rs +++ b/d3d12/crates/leonida-shader/src/emit/host.rs @@ -653,6 +653,8 @@ pub struct Draw<'a> { pub mesh_groups: u32, /// Vertices drawn (0: three, one triangle). pub vertex_count: u32, + /// Instances drawn (0: one). + pub instances: u32, } #[cfg(test)] @@ -931,7 +933,7 @@ impl Host { list6.DispatchMesh(d.mesh_groups, 1, 1); } else { let count = if d.vertex_count == 0 { 3 } else { d.vertex_count }; - list.DrawInstanced(count, 1, 0, 0); + list.DrawInstanced(count, d.instances.max(1), 0, 0); } list.ResourceBarrier(&[transition( &target, diff --git a/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs b/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs index f570562a30..a12e8b8b63 100644 --- a/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs +++ b/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs @@ -81,6 +81,12 @@ fn build( // A per-primitive output goes where the pixel shader reads it; one the // pixel shader does not read is not drawn with. for (p, &at) in primitive.iter().zip(&layout.primitive_at) { + // A render-target or viewport index is the rasteriser's, read or not + // (the translator refuses to export them as yet: `lower.rs`, "render- + // target or viewport index exports"). + if matches!(p.kind, 4 | 5) { + return Err(unsupported("a per-primitive render-target or viewport index")); + } let Some(e) = ps_inputs .iter() .find(|e| e.name.eq_ignore_ascii_case(&p.name) && e.index == p.index && e.row.is_some()) @@ -133,9 +139,11 @@ fn build( let three = k(&mut s, 3); let prim = s.m.bin(b, Bin::UDiv, id, three); let corner = s.m.bin(b, Bin::URem, id, three); - // A group past the cap wrote to the sink slot: it draws nothing. + // Slots 0 to cap - 1 are groups' own; slot cap is the sink every group + // from cap on wrote to at once: an instance from cap on draws nothing + // (and nothing reads the sink). let cap = k(&mut s, layout.groups_cap()); - let past = s.m.cmp(b, super::bitcode::pred::IUGT, group, cap); + let past = s.m.cmp(b, super::bitcode::pred::IUGE, group, cap); let group = s.op(b, "binary.i32", Attr::ReadNone, i32t, 40, &[group, cap]); s.m.tag(group, super::bitcode::Tag::Clamp); diff --git a/d3d12/crates/leonida-shader/src/emit/mod.rs b/d3d12/crates/leonida-shader/src/emit/mod.rs index 28586eff66..d46884dffd 100644 --- a/d3d12/crates/leonida-shader/src/emit/mod.rs +++ b/d3d12/crates/leonida-shader/src/emit/mod.rs @@ -2591,6 +2591,7 @@ mod tests { size: (16, 16), mesh_groups: 1, vertex_count: 0, + instances: 0, }, ) .unwrap_or_else(|e| panic!("{label}: draw: {e}")); @@ -2844,6 +2845,7 @@ mod tests { size: (16, 16), mesh_groups: 1, vertex_count: 0, + instances: 0, }, ) .unwrap_or_else(|e| panic!("{label}: draw: {e}")); @@ -2911,6 +2913,7 @@ mod tests { size: (16, 16), mesh_groups, vertex_count, + instances: 0, }; for (prim, culled) in [ (TRIANGLE, false), @@ -3004,6 +3007,123 @@ mod tests { } } + /// The sink slot (`MeshOut::groups_cap`) takes the writes of every + /// group past the cap at once, so the pass-through vertex shader draws + /// nothing of it: a triangle there, in a buffer drawn with one instance + /// more than the cap, lights no texel, where the same triangle in slot 0 + /// lights them all. + #[test] + #[cfg(windows)] + fn the_mesh_sink_slot_draws_nothing() { + use super::host::{Dispatch, Draw, Host, Root}; + use windows::Win32::Graphics::Direct3D12::{D3D12_SHADER_VISIBILITY_ALL, D3D12_SHADER_VISIBILITY_VERTEX}; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; skipped"); + return; + }; + let ps = constant_color(); + super::lower::TEST_MESH_COMPUTE.set(Some(true)); + let cs = triangle_mesh(TRIANGLE); + super::lower::TEST_MESH_COMPUTE.set(None); + let cs = cs.unwrap(); + let layout = cs.mesh_out.clone().unwrap(); + let root = host.root_signature_for(&[(&cs, D3D12_SHADER_VISIBILITY_ALL)]).unwrap(); + let pso = host.compute_pipeline_with(&root, &cs.dxil).unwrap(); + let slot_words = (layout.group_bytes() / 4) as usize; + let header_words = (MESH_OUT_HEADER / 4) as usize; + let one = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(vec![0])), + (1, Root::Uav((MESH_OUT_HEADER + layout.group_bytes()) / 4)), + ], + views: &[], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap(); + let group0 = one.last().unwrap()[header_words..header_words + slot_words].to_vec(); + let vs = mesh_vs(&layout, Some(&ps)).unwrap(); + let vs_shader = HostShader { + stage: HwStage::Vs, + dxil: vs.clone(), + user_data: vec![], + samplers: vec![], + static_samplers: vec![], + root_cbvs: vec![], + root_srvs: vec![SLOT_MESH_IN], + root_uavs: vec![], + root_indexed_views: vec![], + half_views: vec![], + mesh_out: None, + }; + let root = host.root_signature_for(&[(&vs_shader, D3D12_SHADER_VISIBILITY_VERTEX)]).unwrap(); + let pso = host.pipeline_with(&root, &vs, &ps).unwrap(); + let cap = layout.groups_cap(); + // The triangle in slot `at` of a whole buffer, drawn with `instances`. + let lit = |at: u32, instances: u32| { + let mut data = vec![0u32; (MESH_OUT_BYTES / 4) as usize]; + let first = header_words + at as usize * slot_words; + data[first..first + slot_words].copy_from_slice(&group0); + let texels = host + .draw( + &root, + &pso, + &Draw { + roots: vec![(0, Root::Constants(vec![0])), (1, Root::View { srv: true, data })], + textures: &[], + samplers: &[], + vertices: &[], + stride: 0, + size: (16, 16), + mesh_groups: 0, + vertex_count: 3 * layout.max_primitives, + instances, + }, + ) + .unwrap(); + texels.iter().filter(|t| t[3] != 0.0).count() + }; + assert_eq!(lit(0, 1), 256, "the triangle in slot 0"); + assert_eq!(lit(cap, cap + 1), 0, "the sink slot (cap {cap}) drew"); + } + + /// A mesh program's outputs out of register order (the position in a + /// row of its own after a parameter, as the 2020 compiler's first entry + /// can be) keep each element beside its byte offset: the layout's parts + /// list them in the order the offsets were made, which is the order the + /// pass-through vertex shader pairs them in. + #[test] + fn mesh_out_parts_keep_their_elements_beside_their_offsets() { + let el = |name: &str, kind: u8, row: u32, cols: u8| container::SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp: if kind == 0 { 2 } else { 0 }, + row: Some(row), + col: 0, + cols, + usage: (1 << cols) - 1, + half: false, + }; + let outputs = [el("TEXCOORD", 0, 2, 2), el("SV_Position", 3, 0, 4), el("COLOR", 0, 1, 3)]; + let prims = [el("PRIMDATA", 0, 4, 1), el("PRIMFLAGS", 0, 3, 2)]; + let layout = MeshOut::new(3, 1, &outputs, &prims); + assert_eq!(layout.vertex_at, [0, 8, 24]); + assert_eq!(layout.primitive_at, [12, 16]); + let names = |part: &[u8]| signature(part).unwrap().into_iter().map(|e| e.name).collect::>(); + assert_eq!(names(&layout.osg1), ["TEXCOORD", "SV_Position", "COLOR"]); + assert_eq!(names(&layout.psg1), ["PRIMDATA", "PRIMFLAGS"]); + } + /// A pixel shader interpolating at sample positions (PERSP_SAMPLE /// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency: /// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1) @@ -4023,6 +4143,7 @@ mod barycentric_tests { size: (8, 8), mesh_groups: 0, vertex_count: 0, + instances: 0, }, ) .expect("draw partial interpolation"); diff --git a/d3d12/crates/leonida-shader/src/emit/rect.rs b/d3d12/crates/leonida-shader/src/emit/rect.rs index 983bc4c07b..4fab257544 100644 --- a/d3d12/crates/leonida-shader/src/emit/rect.rs +++ b/d3d12/crates/leonida-shader/src/emit/rect.rs @@ -467,6 +467,7 @@ mod tests { size: (8, 8), mesh_groups: 0, vertex_count: 0, + instances: 0, }; host.draw(&root, &pso, &d).unwrap() }; diff --git a/d3d12/crates/leonida-shader/src/emit/shader.rs b/d3d12/crates/leonida-shader/src/emit/shader.rs index 4ca71e678b..9e36a38de5 100644 --- a/d3d12/crates/leonida-shader/src/emit/shader.rs +++ b/d3d12/crates/leonida-shader/src/emit/shader.rs @@ -276,8 +276,10 @@ impl MeshOut { primitive_stride, vertex_at, primitive_at, - osg1: super::container::signature(outputs, false), - psg1: super::container::signature(prims, false), + // In element order, as the offsets above: sorted by register the + // elements would no longer stand beside their offsets. + osg1: super::container::signature_in_order(outputs, false), + psg1: super::container::signature_in_order(prims, false), } } From 1b33fa2bb1b9e6377aa39db1641000278c8f928d Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sun, 29 Nov 2026 16:19:56 +0200 Subject: [PATCH 04/15] d3d12: drew()'s doc comment back on drew(), not on drew_mesh_as_compute Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/draw.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index 7b1cbc432d..c899535bc8 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs @@ -5668,8 +5668,6 @@ impl State { } } - /// A draw with the pipeline `p` was recorded (as [`State::buffers_written`] - /// if its shaders can store to buffers). /// [`Self::drew`] for a mesh pipeline run as compute and a draw: the /// mesh program's own stores (to title buffers; its outputs to the mesh /// buffer are not counted) as well as the draw's. @@ -5680,6 +5678,8 @@ impl State { } } + /// A draw with the pipeline `p` was recorded (as [`State::buffers_written`] + /// if its shaders can store to buffers). fn drew(&mut self, p: Option<&HostPipeline>) { if p.is_none_or(|p| p.stages.iter().any(|stage| stage.translated().stores)) { // (With 4 a known pipeline's stores are told apart by address, if they are all From 1b6b223d37f97210fce7df70b23a205a8fa92b40 Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sun, 29 Nov 2026 19:20:44 +0200 Subject: [PATCH 05/15] d3d12: MeshOut::new is crate-private, as SigElement it takes Both callers are in leonida-shader; a public constructor taking a crate-private type set off private_interfaces. Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-shader/src/emit/shader.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/d3d12/crates/leonida-shader/src/emit/shader.rs b/d3d12/crates/leonida-shader/src/emit/shader.rs index 9e36a38de5..9c0d1a30ee 100644 --- a/d3d12/crates/leonida-shader/src/emit/shader.rs +++ b/d3d12/crates/leonida-shader/src/emit/shader.rs @@ -257,7 +257,7 @@ pub struct MeshOut { impl MeshOut { /// The layout for these maxima and signatures. - pub fn new(max_vertices: u32, max_primitives: u32, outputs: &[SigElement], prims: &[SigElement]) -> Self { + pub(crate) fn new(max_vertices: u32, max_primitives: u32, outputs: &[SigElement], prims: &[SigElement]) -> Self { let place = |first: u32, elements: &[SigElement]| { let mut at = Vec::with_capacity(elements.len()); let mut next = first; From 924b29417548d7798febe17bca99bf91790238c3 Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sun, 29 Nov 2026 20:28:04 +0200 Subject: [PATCH 06/15] d3d12: the mesh fallback's recording in one place, tested in one list on a device The commands the mesh fallback records between and after the pipelines the draw path binds (barriers, the dispatch or counted indirect dispatch, the header of the indirect draw, the triangle list drawn from the buffer, the title's topology again) move from draw.rs into mesh_fallback::MeshRun, which draw.rs calls. A test records the same commands on a device of its own, as a title does in one list: a counted indirect run (count 1), a direct run of three groups, a run whose triangle is culled, a counted indirect run with a count of 0, then the title's triangle strip; every texel comes out as the runs and the strip draw it. Without the topology restored the strip draws one triangle (64 texels differ); without the header's instance count reset the count-0 run draws the first run's groups again (100 differ). leonida-shader's host checks (emit::host) take the test programs this needs: triangle_mesh_program (the triangle mesh program its own tests used), color_ps and position_vs; dxbc::build is there for them too. draw.rs names its topology mapping (host_topology). Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/Cargo.toml | 2 + d3d12/crates/leonida-gpu/src/draw.rs | 162 ++++----- d3d12/crates/leonida-gpu/src/lib.rs | 2 + d3d12/crates/leonida-gpu/src/mesh_fallback.rs | 149 ++++++++ .../leonida-gpu/src/mesh_fallback/tests.rs | 335 ++++++++++++++++++ d3d12/crates/leonida-shader/src/dxbc.rs | 4 +- d3d12/crates/leonida-shader/src/emit/host.rs | 149 ++++++++ d3d12/crates/leonida-shader/src/emit/mod.rs | 102 +----- 8 files changed, 708 insertions(+), 197 deletions(-) create mode 100644 d3d12/crates/leonida-gpu/src/mesh_fallback.rs create mode 100644 d3d12/crates/leonida-gpu/src/mesh_fallback/tests.rs diff --git a/d3d12/crates/leonida-gpu/Cargo.toml b/d3d12/crates/leonida-gpu/Cargo.toml index b7806fe009..03e00b25cd 100644 --- a/d3d12/crates/leonida-gpu/Cargo.toml +++ b/d3d12/crates/leonida-gpu/Cargo.toml @@ -24,6 +24,8 @@ blake3.workspace = true [dev-dependencies] tempfile.workspace = true +# The host checks' device and shaders (`emit::host`) for the mesh fallback's test. +leonida-shader = { workspace = true, features = ["host"] } [features] # Debugging switches (frame capture, the host debug layer, per-draw data). diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index c899535bc8..e28559a155 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs @@ -67,6 +67,15 @@ fn is_depth_companion(stencil: &View, depth: &View) -> bool { && s[7] == d[7] } +/// The host topology a title's draws with `topology` go out with: the +/// console's rectangles, fans, loops and quads as triangle lists. +fn host_topology(topology: u32) -> u32 { + match topology { + RECTANGLES | TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => 4, + t => t, + } +} + /// The device-local buffer mesh programs run as compute write to /// ([`leonida_shader::emit::MESH_OUT_BYTES`], made once; it starts and ends /// each use in the common state). @@ -1980,14 +1989,10 @@ impl State { pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) { self.topology = topology; self.topology_set = true; - let host = match topology { - RECTANGLES => 4, - TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => { - once!(topology, "console topology drawn as a triangle list"); - 4 - } - t => t, - }; + if matches!(topology, TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP) { + once!(topology, "console topology drawn as a triangle list"); + } + let host = host_topology(topology); // SAFETY: an open list. unsafe { list.list @@ -1995,14 +2000,6 @@ impl State { }; } - /// The title's topology on the list again, after a pass of ours set - /// another (the mesh fallback's triangle list). - fn restore_topology(&mut self, list: &HostList) { - if self.topology_set { - self.set_topology(list, self.topology); - } - } - pub(crate) fn set_pipeline(&mut self, pipeline: This) { self.pipeline = pipeline as usize; } @@ -4678,60 +4675,54 @@ impl State { once!("no mesh buffer: the mesh draw is dropped"); return false; }; - let l = &list.list; self.title_side_graphics = true; let bound = self.bind(list, &mc.cs, true); self.title_side_graphics = false; if !bound { return false; } - use windows::Win32::Graphics::Direct3D12::{ - D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - }; + let run = self.mesh_run(list, &buffer, mc); // SAFETY: an open list, a live buffer and the compute pipeline bound. - unsafe { - l.ResourceBarrier(&[crate::host::transition( - &buffer, - D3D12_RESOURCE_STATE_COMMON, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - )]); - l.SetComputeRootUnorderedAccessView(mc.out_param, buffer.GetGPUVirtualAddress()); - l.Dispatch(n, 1, 1); - l.ResourceBarrier(&[crate::host::transition( - &buffer, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, - )]); - } - // The compute pipeline took the list's pipeline slot. - self.host_pipeline = 0; - let drawn = self.prepare_for(list, false, true); - // SAFETY: as above, the graphics pipeline bound when `drawn`. - unsafe { - if drawn { - self.mesh_scissor(list, true); - l.SetGraphicsRootShaderResourceView(mc.in_param, buffer.GetGPUVirtualAddress()); - l.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - // Instances from the cap on would read the sink slot. - l.DrawInstanced(mc.layout.max_primitives * 3, n.min(mc.layout.groups_cap()), 0, 0); - self.mesh_scissor(list, false); - } - l.ResourceBarrier(&[crate::host::transition( - &buffer, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, - D3D12_RESOURCE_STATE_COMMON, - )]); - } - // The fallback drew a triangle list: the title's next draw has its - // own topology again. + let drawn = unsafe { + run.direct(n, || { + // The compute pipeline took the list's pipeline slot. + self.host_pipeline = 0; + let drawn = self.prepare_for(list, false, true); + if drawn { + self.mesh_scissor(list, true); + } + drawn + }) + }; if drawn { - self.restore_topology(list); + self.mesh_scissor(list, false); } list.keep(&buffer); drawn } + /// The recorder of a mesh run on `list` ([`crate::mesh_fallback`]): it + /// sets the title's topology again after its triangle list, for the + /// title's next draw. + fn mesh_run<'a>( + &self, + list: &'a HostList, + buffer: &'a ID3D12Resource, + mc: &crate::pipeline::host::MeshCompute, + ) -> crate::mesh_fallback::MeshRun<'a> { + crate::mesh_fallback::MeshRun { + list: &list.list, + buffer, + out_param: mc.out_param, + in_param: mc.in_param, + max_primitives: mc.layout.max_primitives, + groups_cap: mc.layout.groups_cap(), + restore: self + .topology_set + .then(|| windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(host_topology(self.topology) as i32)), + } + } + /// [`Self::mesh_as_compute`] for one indirect record: the record's /// `(x, y, z)` is a dispatch's arguments as it stands (`stride` apart), /// so the compute pipeline runs it as recorded; its groups raise the @@ -4754,55 +4745,30 @@ impl State { once!("no mesh buffer: the mesh draw is dropped"); return false; }; - let Ok(l2) = list.list.cast::() else { - return false; - }; self.title_side_graphics = true; let bound = self.bind(list, &mc.cs, true); self.title_side_graphics = false; if !bound { return false; } - use windows::Win32::Graphics::Direct3D12::{ - D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, - }; - let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; - let l = &list.list; + let run = self.mesh_run(list, &buffer, mc); // SAFETY: an open list, live buffers and the compute pipeline bound. - unsafe { - let va = buffer.GetGPUVirtualAddress(); - l.ResourceBarrier(&[crate::host::transition(&buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); - let header = [mc.layout.max_primitives * 3, 0, 0, 0].map(|v| v); - let params: Vec = header - .iter() - .enumerate() - .map(|(k, &value)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: va + 4 * k as u64, Value: value }) - .collect(); - l2.WriteBufferImmediate(params.len() as u32, params.as_ptr(), None); - l.ResourceBarrier(&[crate::host::transition(&buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); - l.SetComputeRootUnorderedAccessView(mc.out_param, va); - l.ExecuteIndirect(&dispatch, 1, arguments, at, count.map(|c| c.0), count.map_or(0, |c| c.1)); - l.ResourceBarrier(&[crate::host::transition(&buffer, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, read)]); - } - self.host_pipeline = 0; - let drawn = self.prepare_for(list, false, true); - // SAFETY: as above, the graphics pipeline bound when `drawn`. - unsafe { - if drawn { - self.mesh_scissor(list, true); - l.SetGraphicsRootShaderResourceView(mc.in_param, buffer.GetGPUVirtualAddress()); - l.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - l.ExecuteIndirect(&draw, 1, &buffer, 0, None, 0); - self.mesh_scissor(list, false); - } - l.ResourceBarrier(&[crate::host::transition(&buffer, read, D3D12_RESOURCE_STATE_COMMON)]); - } - // The fallback drew a triangle list: the title's next draw has its - // own topology again. + let drawn = unsafe { + run.indirect(&dispatch, &draw, (arguments, at), count, || { + self.host_pipeline = 0; + let drawn = self.prepare_for(list, false, true); + if drawn { + self.mesh_scissor(list, true); + } + drawn + }) + }; + let Some(drawn) = drawn else { + once!("a list without WriteBufferImmediate: the mesh draw is dropped"); + return false; + }; if drawn { - self.restore_topology(list); + self.mesh_scissor(list, false); } list.keep(&buffer); drawn diff --git a/d3d12/crates/leonida-gpu/src/lib.rs b/d3d12/crates/leonida-gpu/src/lib.rs index 3aa021b01d..8c070a046d 100644 --- a/d3d12/crates/leonida-gpu/src/lib.rs +++ b/d3d12/crates/leonida-gpu/src/lib.rs @@ -40,6 +40,8 @@ pub mod descriptor; pub mod device; #[cfg(windows)] mod draw; +#[cfg(windows)] +mod mesh_fallback; #[cfg(any(windows, test))] mod drops; #[cfg(windows)] diff --git a/d3d12/crates/leonida-gpu/src/mesh_fallback.rs b/d3d12/crates/leonida-gpu/src/mesh_fallback.rs new file mode 100644 index 0000000000..ed19cc651d --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/mesh_fallback.rs @@ -0,0 +1,149 @@ +//! `D3D12-MESH-COMPUTE-FALLBACK` as it is recorded on a command list: the +//! mesh program as compute writing each group's outputs to the mesh buffer +//! (`leonida_shader::emit::MESH_OUT_BYTES`), then a triangle list drawn +//! from them through the pass-through vertex shader +//! (`leonida_shader::emit::mesh_vs`). The draw path binds the pipelines and +//! the title's root arguments (`crate::draw`); what is recorded between and +//! after them is here, so a test records the same commands on a device of +//! its own. +//! +//! The buffer starts and ends each run in the common state, so every list, +//! and every run in one list, finds it there. + +use windows::Win32::Graphics::Direct3D::{D3D_PRIMITIVE_TOPOLOGY, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST}; +use windows::Win32::Graphics::Direct3D12::{ + D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, ID3D12CommandSignature, ID3D12GraphicsCommandList, + ID3D12GraphicsCommandList2, ID3D12Resource, +}; +use windows::core::Interface; + +use crate::host::transition; + +/// One run of a mesh pipeline as compute and a triangle list. +pub(crate) struct MeshRun<'a> { + pub(crate) list: &'a ID3D12GraphicsCommandList, + /// The mesh buffer, in the common state. + pub(crate) buffer: &'a ID3D12Resource, + /// The compute pipeline's root UAV the groups write to. + pub(crate) out_param: u32, + /// The graphics pipeline's root SRV the vertex shader reads. + pub(crate) in_param: u32, + pub(crate) max_primitives: u32, + /// Instances from this one on would read the sink slot + /// (`MeshOut::groups_cap`). + pub(crate) groups_cap: u32, + /// The topology the list has again after the draw (the title's, for its + /// next draw); `None` leaves the triangle list. + pub(crate) restore: Option, +} + +impl MeshRun<'_> { + /// `x` groups, the compute pipeline and its root arguments bound: + /// dispatches them, then `graphics` binds the graphics pipeline and its + /// root arguments (false: nothing is drawn) and the groups are drawn, + /// one instance a group up to the cap. Whether it drew. + /// + /// # Safety + /// An open list with the compute pipeline bound; live resources. + pub(crate) unsafe fn direct(&self, x: u32, graphics: impl FnOnce() -> bool) -> bool { + let n = x.min(65_535); + if n == 0 { + return true; + } + let (l, buffer) = (self.list, self.buffer); + // SAFETY: as the caller promises. + unsafe { + l.ResourceBarrier(&[transition(buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + l.SetComputeRootUnorderedAccessView(self.out_param, buffer.GetGPUVirtualAddress()); + l.Dispatch(n, 1, 1); + l.ResourceBarrier(&[transition( + buffer, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + } + let drawn = graphics(); + // SAFETY: as above, the graphics pipeline bound when `drawn`. + unsafe { + if drawn { + self.draw_from_buffer(|l| l.DrawInstanced(self.max_primitives * 3, n.min(self.groups_cap), 0, 0)); + } + l.ResourceBarrier(&[transition( + buffer, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_COMMON, + )]); + } + drawn + } + + /// One indirect record, the compute pipeline and its root arguments + /// bound: the record at `arguments` (a dispatch's `(x, y, z)` with the + /// title's stride, in `dispatch`) runs as recorded, or not at all when + /// the count at `count` is 0. Each group raises the instance count in + /// the buffer's header, which is written first ([3 * max_primitives, 0, + /// 0, 0]), and the draw (`draw`, of 16-byte records) reads the header. + /// `graphics` as for [`Self::direct`]. Whether it drew; `None` on a + /// list without `WriteBufferImmediate`. + /// + /// # Safety + /// As [`Self::direct`]; the argument and count buffers in the indirect + /// argument state. + pub(crate) unsafe fn indirect( + &self, + dispatch: &ID3D12CommandSignature, + draw: &ID3D12CommandSignature, + (arguments, at): (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, + graphics: impl FnOnce() -> bool, + ) -> Option { + let (l, buffer) = (self.list, self.buffer); + let l2 = l.cast::().ok()?; + let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + // SAFETY: as the caller promises. + unsafe { + let va = buffer.GetGPUVirtualAddress(); + l.ResourceBarrier(&[transition(buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); + let header = [self.max_primitives * 3, 0, 0, 0]; + let params: Vec = header + .iter() + .enumerate() + .map(|(k, &value)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: va + 4 * k as u64, Value: value }) + .collect(); + l2.WriteBufferImmediate(params.len() as u32, params.as_ptr(), None); + l.ResourceBarrier(&[transition(buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + l.SetComputeRootUnorderedAccessView(self.out_param, va); + l.ExecuteIndirect(dispatch, 1, arguments, at, count.map(|c| c.0), count.map_or(0, |c| c.1)); + l.ResourceBarrier(&[transition(buffer, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, read)]); + } + let drawn = graphics(); + // SAFETY: as above, the graphics pipeline bound when `drawn`. + unsafe { + if drawn { + self.draw_from_buffer(|l| l.ExecuteIndirect(draw, 1, buffer, 0, None, 0)); + } + l.ResourceBarrier(&[transition(buffer, read, D3D12_RESOURCE_STATE_COMMON)]); + } + Some(drawn) + } + + /// The draw itself: the buffer as the vertex shader's root SRV, a + /// triangle list, then the topology to restore. + unsafe fn draw_from_buffer(&self, draw: impl FnOnce(&ID3D12GraphicsCommandList)) { + let l = self.list; + // SAFETY: an open list with the graphics pipeline bound. + unsafe { + l.SetGraphicsRootShaderResourceView(self.in_param, self.buffer.GetGPUVirtualAddress()); + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + draw(l); + if let Some(t) = self.restore { + l.IASetPrimitiveTopology(t); + } + } + } +} + +#[cfg(test)] +mod tests; diff --git a/d3d12/crates/leonida-gpu/src/mesh_fallback/tests.rs b/d3d12/crates/leonida-gpu/src/mesh_fallback/tests.rs new file mode 100644 index 0000000000..3750657cf6 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/mesh_fallback/tests.rs @@ -0,0 +1,335 @@ +//! The mesh fallback's recording ([`MeshRun`]) on a device, several runs in +//! one command list as a title records them, then a draw of the title's +//! own: each run draws what its own dispatch wrote, a counted indirect run +//! with a count of 0 draws nothing (the header's instance count starts at 0 +//! each run), and the strip after them draws as a strip. + +use leonida_shader::HwStage; +use leonida_shader::emit::host::{Host, MESH_CULL, MESH_TRIANGLE, color_ps, position_vs, triangle_mesh_program}; +use leonida_shader::emit::{HostShader, MESH_OUT_BYTES, SLOT_MESH_IN, mesh_vs, set_host_mesh_shaders}; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D::*; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::MeshRun; + +const SIZE: u32 = 16; +const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; +const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; +const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; +const YELLOW: [f32; 4] = [1.0, 1.0, 0.0, 1.0]; +const MAGENTA: [f32; 4] = [1.0, 0.0, 1.0, 1.0]; + +fn buffer(device: &ID3D12Device, heap: D3D12_HEAP_TYPE, bytes: u64, uav: bool, state: D3D12_RESOURCE_STATES) -> ID3D12Resource { + let mut made: Option = None; + // SAFETY: plain descriptions that outlive the call. + unsafe { + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: if uav { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE }, + ..Default::default() + }, + state, + None, + &mut made, + ) + .unwrap(); + } + made.unwrap() +} + +/// An upload buffer holding `data`. +fn upload(device: &ID3D12Device, data: &[T]) -> ID3D12Resource { + let bytes = size_of_val(data); + let b = buffer(device, D3D12_HEAP_TYPE_UPLOAD, bytes.max(256) as u64, false, D3D12_RESOURCE_STATE_GENERIC_READ); + // SAFETY: a mapped upload buffer of at least `bytes`. + unsafe { + let mut p = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::copy_nonoverlapping(data.as_ptr().cast::(), p.cast::(), bytes); + b.Unmap(0, None); + } + b +} + +fn signature(device: &ID3D12Device, kind: D3D12_INDIRECT_ARGUMENT_TYPE, stride: u32) -> ID3D12CommandSignature { + let argument = D3D12_INDIRECT_ARGUMENT_DESC { Type: kind, ..Default::default() }; + let mut made: Option = None; + // SAFETY: a description of one argument; no root arguments. + unsafe { + device + .CreateCommandSignature( + &D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: stride, + NumArgumentDescs: 1, + pArgumentDescs: &argument, + NodeMask: 0, + }, + None, + &mut made, + ) + .unwrap(); + } + made.unwrap() +} + +/// The colour a texel ends with: the strip's right half over the second +/// run's lower-left triangle over the first run's whole target. +fn expected(column: u32, row: u32) -> [f32; 4] { + let x = -1.0 + (2 * column + 1) as f32 / SIZE as f32; + let y = 1.0 - (2 * row + 1) as f32 / SIZE as f32; + if x > 0.0 { + MAGENTA + } else if x + y < 0.0625 { + GREEN + } else { + RED + } +} + +#[test] +fn mesh_runs_in_one_list_draw_their_own_groups_and_the_strip_after_them_its_strip() { + // The programs as compute, as on a host without mesh shaders. + set_host_mesh_shaders(false); + let programs = [ + triangle_mesh_program(MESH_TRIANGLE, 4.0), + // Far corners at 1.0625: the target's lower-left triangle, its edge + // past every texel centre (x + y < 0.0625). + triangle_mesh_program(MESH_TRIANGLE, 2.0625), + triangle_mesh_program(MESH_TRIANGLE | MESH_CULL, 4.0), + ]; + set_host_mesh_shaders(true); + let [full, half, culled] = programs.map(|p| p.unwrap()); + let layout = full.mesh_out.clone().expect("translated as compute"); + let vs = HostShader { + stage: HwStage::Vs, + dxil: mesh_vs(&layout, None).unwrap(), + user_data: vec![], + samplers: vec![], + static_samplers: vec![], + root_cbvs: vec![], + root_srvs: vec![SLOT_MESH_IN], + root_uavs: vec![], + root_indexed_views: vec![], + half_views: vec![], + mesh_out: None, + }; + let strip_vs = position_vs(); + 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; + }; + let device = &host.device; + let compute = |cs: &HostShader| { + let root = host.root_signature_for(&[(cs, D3D12_SHADER_VISIBILITY_ALL)]).unwrap(); + let pso = host.compute_pipeline_with(&root, &cs.dxil).unwrap(); + (root, pso) + }; + let [full_cs, half_cs, culled_cs] = [&full, &half, &culled].map(compute); + let mesh_root = host.root_signature_for(&[(&vs, D3D12_SHADER_VISIBILITY_VERTEX)]).unwrap(); + let mesh_pso = |rgba| host.pipeline_with(&mesh_root, &vs.dxil, &color_ps(rgba).dxil).unwrap(); + let [red, green, blue, yellow] = [RED, GREEN, BLUE, YELLOW].map(mesh_pso); + let strip_root = host.root_signature_for(&[(&strip_vs, D3D12_SHADER_VISIBILITY_VERTEX)]).unwrap(); + let strip_pso = host.pipeline_with(&strip_root, &strip_vs.dxil, &color_ps(MAGENTA).dxil).unwrap(); + + // SAFETY: D3D12 calls with descriptions that outlive them; every + // resource is alive until the fence below says the GPU is done. + unsafe { + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .unwrap(); + let alloc: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = + device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + // The target. + let mut target: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(SIZE), + Height: SIZE, + 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() + }, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut target, + ) + .unwrap(); + let target = target.unwrap(); + let rtv_heap: ID3D12DescriptorHeap = device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: 1, + ..Default::default() + }) + .unwrap(); + let rtv = rtv_heap.GetCPUDescriptorHandleForHeapStart(); + device.CreateRenderTargetView(&target, None, rtv); + list.ClearRenderTargetView(rtv, &[0.0; 4], None); + + let mesh_buffer = + buffer(device, D3D12_HEAP_TYPE_DEFAULT, u64::from(MESH_OUT_BYTES), true, D3D12_RESOURCE_STATE_COMMON); + // Two dispatch records (12 bytes apart) and the counts 1 and 0. + let arguments = upload(device, &[1u32, 1, 1, 1, 1, 1]); + let counts = upload(device, &[1u32, 0]); + let dispatch = signature(device, D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, 12); + let draw = signature(device, D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, 16); + // The strip: the target's right half, x from 0 to 1. + let corners: [[f32; 4]; 4] = [[0.0, -1.0, 0.5, 1.0], [1.0, -1.0, 0.5, 1.0], [0.0, 1.0, 0.5, 1.0], [1.0, 1.0, 0.5, 1.0]]; + let vertices = upload(device, &corners); + + // The title draws strips: its topology, set before the runs. + list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); + let run = MeshRun { + list: &list, + buffer: &mesh_buffer, + out_param: 1, + in_param: 1, + max_primitives: layout.max_primitives, + groups_cap: layout.groups_cap(), + restore: Some(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP), + }; + let bind_compute = |(root, pso): &(ID3D12RootSignature, ID3D12PipelineState)| { + list.SetComputeRootSignature(root); + list.SetPipelineState(pso); + list.SetComputeRoot32BitConstant(0, 0, 0); + }; + let graphics = |pso: &ID3D12PipelineState| { + list.SetGraphicsRootSignature(&mesh_root); + list.SetPipelineState(pso); + list.SetGraphicsRoot32BitConstant(0, 0, 0); + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.RSSetViewports(&[D3D12_VIEWPORT { + Width: SIZE as f32, + Height: SIZE as f32, + MaxDepth: 1.0, + ..Default::default() + }]); + list.RSSetScissorRects(&[RECT { right: SIZE as i32, bottom: SIZE as i32, ..Default::default() }]); + true + }; + + // 1. Counted indirect, count 1: the whole target red. + bind_compute(&full_cs); + assert_eq!(run.indirect(&dispatch, &draw, (&arguments, 0), Some((&counts, 0)), || graphics(&red)), Some(true)); + // 2. Direct, three groups: the lower-left triangle green. + bind_compute(&half_cs); + assert!(run.direct(3, || graphics(&green))); + // 3. Direct, the triangle culled: nothing blue, where the + // buffer still holds the green run's triangles. + bind_compute(&culled_cs); + assert!(run.direct(2, || graphics(&blue))); + // 4. Counted indirect, count 0: no group runs, and the instance + // count the first indirect run left in the header is not + // drawn again: nothing yellow. + bind_compute(&full_cs); + assert_eq!( + run.indirect(&dispatch, &draw, (&arguments, 12), Some((&counts, 4)), || graphics(&yellow)), + Some(true) + ); + // 5. The title's strip, its topology left as the runs restored it. + list.SetGraphicsRootSignature(&strip_root); + list.SetPipelineState(&strip_pso); + list.SetGraphicsRoot32BitConstant(0, 0, 0); + list.IASetVertexBuffers( + 0, + Some(&[D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: vertices.GetGPUVirtualAddress(), + SizeInBytes: size_of_val(&corners) as u32, + StrideInBytes: 16, + }]), + ); + list.DrawInstanced(4, 1, 0, 0); + + // Read the target back. + list.ResourceBarrier(&[crate::host::transition( + &target, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let pitch = SIZE * 16; + let readback = buffer( + device, + D3D12_HEAP_TYPE_READBACK, + u64::from(pitch * SIZE), + false, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + 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: SIZE, + Height: SIZE, + Depth: 1, + RowPitch: pitch, + }, + }, + }, + }; + 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().unwrap(); + queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).unwrap())]); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + while fence.GetCompletedValue() < 1 { + if let Err(e) = device.GetDeviceRemovedReason() { + panic!("{label}: device removed: {e}"); + } + std::thread::yield_now(); + } + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).unwrap(); + let texels = std::slice::from_raw_parts(p.cast::<[f32; 4]>(), (SIZE * SIZE) as usize).to_vec(); + readback.Unmap(0, None); + + let wrong: Vec<(u32, u32, [f32; 4], [f32; 4])> = (0..SIZE * SIZE) + .map(|i| (i % SIZE, i / SIZE)) + .map(|(c, r)| (c, r, texels[(r * SIZE + c) as usize], expected(c, r))) + .filter(|&(_, _, got, want)| got != want) + .collect(); + assert!( + wrong.is_empty(), + "{label}: {} of {} texels differ, first (column, row, got, wanted): {:?}", + wrong.len(), + SIZE * SIZE, + wrong[0] + ); + } + eprintln!("{label}: four mesh runs and a strip in one list drew as recorded"); + ran += 1; + } + if ran == 0 { + eprintln!("no SM 6.6 device; skipped"); + } +} diff --git a/d3d12/crates/leonida-shader/src/dxbc.rs b/d3d12/crates/leonida-shader/src/dxbc.rs index 8d5bd73ee2..adc075c226 100644 --- a/d3d12/crates/leonida-shader/src/dxbc.rs +++ b/d3d12/crates/leonida-shader/src/dxbc.rs @@ -131,8 +131,8 @@ pub(crate) fn u64_at(data: &[u8], at: usize) -> Result { .ok_or(ShaderError::Malformed("truncated")) } -/// Builds a container from parts (test helper). -#[cfg(test)] +/// Builds a container from parts (tests and the host checks, `emit::host`). +#[cfg(any(test, feature = "host"))] pub fn build(parts: &[(FourCC, &[u8])]) -> Vec { let table = HEADER_SIZE + 4 * parts.len(); let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::(); diff --git a/d3d12/crates/leonida-shader/src/emit/host.rs b/d3d12/crates/leonida-shader/src/emit/host.rs index 26c3316676..47517e71d5 100644 --- a/d3d12/crates/leonida-shader/src/emit/host.rs +++ b/d3d12/crates/leonida-shader/src/emit/host.rs @@ -617,6 +617,155 @@ fn stub(pixel: bool, outputs: Vec) -> HostShader { } } +/// A pixel shader writing the constant colour `rgba` to target 0. +pub fn color_ps(rgba: [f32; 4]) -> HostShader { + use super::bitcode::{Attr, Term}; + let mut s = super::shader::Shader::new(true); + s.outputs.push(SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }); + let b = s.entry; + for (c, v) in rgba.into_iter().enumerate() { + let args = [s.m.i32(0), s.m.i32(0), s.m.i8(c as u8), s.m.f32(v.to_bits())]; + s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + s.m.terminate(b, Term::Ret); + plain(crate::native::HwStage::Ps, s.finish()) +} + +/// A vertex shader passing its float4 `POSITION` through as `SV_Position`. +pub fn position_vs() -> HostShader { + use super::bitcode::{Attr, Term}; + let mut s = super::shader::Shader::new(false); + let element = |name: &str, kind: u8, interp: u8| SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }; + s.inputs = vec![element("POSITION", 0, 0)]; + s.outputs = vec![element("SV_Position", 3, 4)]; + for col in 0..4 { + let args = [s.m.i32(0), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)]; + let v = s.op(s.entry, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args); + let args = [s.m.i32(0), s.m.i32(0), s.m.i8(col), v]; + s.op(s.entry, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + s.m.terminate(s.entry, Term::Ret); + plain(crate::native::HwStage::Vs, s.finish()) +} + +fn plain(stage: crate::native::HwStage, dxil: Vec) -> HostShader { + HostShader { + stage, + dxil, + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + half_views: Vec::new(), + mesh_out: None, + } +} + +/// Triangle (0, 1, 2) as a primitive export: each corner's 9-bit index in +/// its 10-bit field ([`triangle_mesh_program`]). +pub const MESH_TRIANGLE: u32 = 1 << 10 | 2 << 20; +/// The edge flags of the three corners (bits 9, 19 and 29). +pub const MESH_EDGE_FLAGS: u32 = 1 << 9 | 1 << 19 | 1 << 29; +/// The culling bit of a primitive export. +pub const MESH_CULL: u32 = 1 << 31; + +/// A one-wave (32-lane) console mesh program, translated: its lanes all +/// export primitive `prim` and, as vertex `lane`, the position +/// (lane & 1 ? reach - 1 : -1, lane & 2 ? reach - 1 : -1, 0.5, 1), so +/// triangle (0, 1, 2) has its far corners at `reach` - 1 (with `reach` 4 +/// it covers the whole target). Translated as a mesh program or as compute +/// as the translator is set ([`super::set_host_mesh_shaders`]). +pub fn triangle_mesh_program(prim: u32, reach: f32) -> Result { + use crate::native::{HwStage, MeshIo, NativeProgram, StageIo}; + // (the second corner's y comes out as 2 x its lane bit: half of it) + let [x, y] = [reach.to_bits(), (reach / 2.0).to_bits()]; + let words = [ + 0xD765_0001u32, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0x0001_00C1, + 0x3604_0281, // v_and_b32 v2, 1, v1 + 0x3606_0282, // v_and_b32 v3, 2, v1 + 0x7E04_0D02, // v_cvt_f32_u32 v2, v2 + 0x7E06_0D03, // v_cvt_f32_u32 v3, v3 + 0x1008_04FF, // v_mul_f32 v4, reach, v2 + x, + 0x0608_08F3, // v_add_f32 v4, -1.0, v4 + 0x100A_06FF, // v_mul_f32 v5, reach / 2, v3 + y, + 0x060A_0AF3, // v_add_f32 v5, -1.0, v5 + 0x7E0C_02F0, // v_mov_b32 v6, 0.5 + 0x7E0E_02F2, // v_mov_b32 v7, 1.0 + 0x7E12_02FF, // v_mov_b32 v9, prim + prim, + 0xF800_0941, // exp prim v9, off, off, off done + 0x0000_0009, + 0xF800_08CF, // exp pos0 v4, v5, v6, v7 done + 0x0706_0504, + 0xBF81_0000, // s_endpgm + ]; + let native = NativeProgram { + stage: HwStage::Ms, + wave64: false, + vgprs: 10, + layout: vec![], + used: vec![], + io: StageIo::Ms(MeshIo { + outputs: vec![], + clip_cntl: 0, + threads: 32, + max_vertices: 32, + max_primitives: 32, + topology: 2, + lds_bytes: 0, + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let position = SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }; + let osg1 = super::container::signature(&[position], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes)?; + let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let st = crate::structure::structure(&p)?; + let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = crate::io::raise(&p, &native)?; + super::emit(&c, &native, &p, &st, &io, &res) +} + /// A root argument for [`Host::draw`]. #[cfg(test)] pub enum Root { diff --git a/d3d12/crates/leonida-shader/src/emit/mod.rs b/d3d12/crates/leonida-shader/src/emit/mod.rs index d46884dffd..01fe25fe85 100644 --- a/d3d12/crates/leonida-shader/src/emit/mod.rs +++ b/d3d12/crates/leonida-shader/src/emit/mod.rs @@ -2368,31 +2368,7 @@ mod tests { /// A pixel shader writing a constant colour. #[cfg(windows)] fn constant_color() -> Vec { - let mut s = Shader::new(true); - s.outputs.push(SigElement { - name: "SV_Target".into(), - index: 0, - kind: 16, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 15, - half: false, - }); - let b = s.entry; - for (c, v) in [1.0f32, 0.5, 0.25, 1.0].into_iter().enumerate() { - let args = [ - s.m.i32(0), - s.m.i32(0), - s.m.i8(c as u8), - s.m.f32(v.to_bits()), - ]; - s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); - } - s.m.terminate(b, super::bitcode::Term::Ret); - s.finish() + super::host::color_ps([1.0, 0.5, 0.25, 1.0]).dxil } #[test] @@ -2609,85 +2585,17 @@ mod tests { } } - /// Triangle (0, 1, 2), each corner's 9-bit index in its 10-bit field. - const TRIANGLE: u32 = 1 << 10 | 2 << 20; - /// The edge flags of the three corners (bits 9, 19 and 29). - const EDGE_FLAGS: u32 = 1 << 9 | 1 << 19 | 1 << 29; - /// The culling bit. - const CULL: u32 = 1 << 31; + use super::host::{MESH_CULL as CULL, MESH_EDGE_FLAGS as EDGE_FLAGS, MESH_TRIANGLE as TRIANGLE}; - /// A one-wave (32-lane) triangle mesh program whose lanes all export - /// primitive `prim` and, as vertex `lane`, the position - /// (lane & 1 ? 3 : -1, lane & 2 ? 3 : -1, 0.5, 1): triangle (0, 1, 2) - /// covers the whole target. + /// The triangle mesh program covering the whole target + /// ([`super::host::triangle_mesh_program`]). fn triangle_mesh(prim: u32) -> Result { triangle_mesh_to(prim, 4.0) } /// The triangle with its far corners at `reach` - 1. fn triangle_mesh_to(prim: u32, reach: f32) -> Result { - // (the second corner's y comes out as 2 x its lane bit: half of it) - let [x, y] = [reach.to_bits(), (reach / 2.0).to_bits()]; - let words = [ - 0xD765_0001u32, // v_mbcnt_lo_u32_b32 v1, -1, 0 - 0x0001_00C1, - 0x3604_0281, // v_and_b32 v2, 1, v1 - 0x3606_0282, // v_and_b32 v3, 2, v1 - 0x7E04_0D02, // v_cvt_f32_u32 v2, v2 - 0x7E06_0D03, // v_cvt_f32_u32 v3, v3 - 0x1008_04FF, // v_mul_f32 v4, reach, v2 - x, - 0x0608_08F3, // v_add_f32 v4, -1.0, v4 - 0x100A_06FF, // v_mul_f32 v5, reach / 2, v3 - y, - 0x060A_0AF3, // v_add_f32 v5, -1.0, v5 - 0x7E0C_02F0, // v_mov_b32 v6, 0.5 - 0x7E0E_02F2, // v_mov_b32 v7, 1.0 - 0x7E12_02FF, // v_mov_b32 v9, prim - prim, - 0xF800_0941, // exp prim v9, off, off, off done - 0x0000_0009, - 0xF800_08CF, // exp pos0 v4, v5, v6, v7 done - 0x0706_0504, - 0xBF81_0000, // s_endpgm - ]; - let native = NativeProgram { - stage: HwStage::Ms, - wave64: false, - vgprs: 10, - layout: vec![], - used: vec![], - io: StageIo::Ms(crate::native::MeshIo { - outputs: vec![], - clip_cntl: 0, - threads: 32, - max_vertices: 32, - max_primitives: 32, - topology: 2, - lds_bytes: 0, - }), - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let position = SigElement { - name: "SV_Position".into(), - index: 0, - kind: 3, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 0xF, - half: false, - }; - let osg1 = container::signature(&[position], false); - let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); - let c = Container::parse(&bytes)?; - let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; - let st = structure::structure(&p)?; - let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - let io = io::raise(&p, &native)?; - emit(&c, &native, &p, &st, &io, &res) + super::host::triangle_mesh_program(prim, reach) } /// A primitive export's corners are 9-bit indices: the edge flag above From d5e9ecfcea1cbb1e5437bdee74cbf645fcc326a9 Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sat, 28 Nov 2026 19:35:58 +0200 Subject: [PATCH 07/15] d3d12: pixel shaders read barycentrics stand-ins on a host without barycentrics (D3D12-BARYCENTRICS-FALLBACK) Without D3D12 barycentrics (before Turing) every pixel shader that reads SV_Barycentrics or attributeAtVertex is refused at pipeline creation (the debug layer: "Shader uses Barycentrics, but the device does not support this"). set_host_barycentrics(false) translates them with ordinary inputs instead: - LEONIDA_BARY, a float3 per interpolation mode, for SV_Barycentrics; - LEONIDA_VTX, constant one-channel inputs whose semantic index names the element, column and vertex, for attributeAtVertex at vertices 1 and 2 (vertex 0 is the element itself). - They take rows past the title's own, packed four to a row; a shader that would need more than 32 rows is refused. bary_gs() builds the geometry stage that writes them. It passes the vertex shader's outputs through, register for register, and adds: - one-hot weights (1,0,0) / (0,1,0) / (0,0,1) at the corners; - each corner's value of the elements read at a vertex; - the primitive id if the pixel shader wants it. A stand-in that lands on a vertex shader register moves a system value to a free row and drops a user output the pixel shader does not read. host_settings() gets a sixth word. MEASURED before coding (the title's translated pixel shaders): 4058 read barycentrics, 4040 of them through attributeAtVertex; packed, 54 need more than 32 rows. Tests: seven hand-worked barycentric programs read the stand-ins; the pixel shaders and the geometry stage validate in dxil.dll. A device test draws them through the stage and checks the hand-worked values (compared with native barycentrics where the device has them). A weight rotation mutant fails it. Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/shader_cache.rs | 2 +- .../crates/leonida-shader/src/emit/bary_gs.rs | 250 ++++++++++++++++ d3d12/crates/leonida-shader/src/emit/lower.rs | 217 +++++++++++++- d3d12/crates/leonida-shader/src/emit/mod.rs | 275 +++++++++++++++++- 4 files changed, 740 insertions(+), 4 deletions(-) create mode 100644 d3d12/crates/leonida-shader/src/emit/bary_gs.rs diff --git a/d3d12/crates/leonida-gpu/src/shader_cache.rs b/d3d12/crates/leonida-gpu/src/shader_cache.rs index bf136a117c..47a85045b5 100644 --- a/d3d12/crates/leonida-gpu/src/shader_cache.rs +++ b/d3d12/crates/leonida-gpu/src/shader_cache.rs @@ -218,7 +218,7 @@ fn paired_override(container: &[u8], mut shader: HostShader) -> HostShader { let Some(dir) = DIR.get_or_init(|| std::env::var_os("LEONIDA_PAIRED_SHADER_DIR").map(PathBuf::from)) else { return shader; }; - if shader.stage != HwStage::Cs || leonida_shader::emit::host_settings() != [32, 999_999, 0, 0, 0] { + if shader.stage != HwStage::Cs || leonida_shader::emit::host_settings() != [32, 999_999, 0, 0, 0, 0] { return shader; } let digest = blake3::hash(container).to_hex(); diff --git a/d3d12/crates/leonida-shader/src/emit/bary_gs.rs b/d3d12/crates/leonida-shader/src/emit/bary_gs.rs new file mode 100644 index 0000000000..4064c85f08 --- /dev/null +++ b/d3d12/crates/leonida-shader/src/emit/bary_gs.rs @@ -0,0 +1,250 @@ +//! The geometry shader that stands in for D3D12 barycentrics on a host +//! without them (`D3D12-BARYCENTRICS-FALLBACK`; Pascal and older). Such a +//! host refuses a pixel shader that reads `SV_Barycentrics` or calls +//! `attributeAtVertex`, so the translator +//! ([`super::set_host_barycentrics`]) has the pixel shader read ordinary +//! inputs instead, and this stage, behind the translated vertex shader, +//! writes them: +//! +//! - [`super::BARY_INPUT`] (three floats, interpolated as the pixel shader +//! declares): (1, 0, 0), (0, 1, 0) and (0, 0, 1) at vertices 0, 1 and 2, +//! which interpolate to the weights `SV_Barycentrics` holds. +//! - [`super::VERTEX_INPUT`] (one constant channel each): vertex 1's or +//! 2's value of the vertex shader output in the register and column its +//! semantic index names ([`super::vertex_source`]). Vertex 0's is the +//! constant input itself: the triangle goes out in the order it came, so +//! the first vertex, whose value a constant input takes, is vertex 0. +//! +//! Every other output is the vertex shader's, register for register, except +//! one in a register the stand-ins take (the pixel shader does not read +//! it: its own inputs come first). A pixel shader that declares a +//! primitive id gets the triangle's, which the host leaves to the geometry +//! stage when there is one. + +use super::bitcode::{Attr, Cast, Term, V}; +use super::container::SigElement; +use super::shader::{Geometry, Shader}; +use crate::ShaderError; +use crate::dxbc::{Container, FourCC}; + +/// The scalars a geometry shader may emit per invocation (vertices times +/// output components). +const MAX_SCALARS: u32 = 1024; + +fn signature(dxil: &[u8], fourcc: FourCC) -> Result, ShaderError> { + let c = Container::parse(dxil)?; + match c.part(fourcc) { + Some(part) => super::signature(part.data), + None => Ok(Vec::new()), + } +} + +fn stand_in(e: &SigElement) -> bool { + e.name == super::BARY_INPUT || e.name == super::VERTEX_INPUT +} + +/// Whether the translated pixel shader `ps` ([`super::HostShader::dxil`]) +/// reads inputs that only [`bary_gs`] writes. +pub fn needs_bary_gs(ps: &[u8]) -> bool { + signature(ps, FourCC::ISG1).is_ok_and(|inputs| inputs.iter().any(stand_in)) +} + +/// The geometry shader (a DXIL container) for triangles drawn with the +/// translated vertex shader `vs` and pixel shader `ps`. +pub fn bary_gs(vs: &[u8], ps: &[u8]) -> Result, ShaderError> { + build(signature(vs, FourCC::OSG1)?, &signature(ps, FourCC::ISG1)?) +} + +/// What an output of the stage carries. +enum Source { + /// The vertex shader's output `id`, as it is. + Output(usize), + /// One of the weights: 1 at vertex `k`'s column, 0 elsewhere. + Weights, + /// Vertex `k`'s value of input `id`'s column `col`, or 0 when the vertex + /// shader writes nothing there. + Vertex(Option<(usize, u8)>, u32), + /// The primitive id. + Primitive, +} + +fn build(mut vs_outputs: Vec, ps_inputs: &[SigElement]) -> Result, ShaderError> { + let unsupported = |what| ShaderError::Unsupported { offset: 0, what }; + if vs_outputs.iter().any(|e| e.row.is_none()) { + return Err(unsupported("a barycentrics stage behind an output without a register")); + } + for e in &mut vs_outputs { + // Interpolation as `emit_program` declares a vertex shader's + // outputs; a geometry shader's inputs carry the same modes. + e.interp = match (e.kind, e.comp) { + (3, _) => 4, + (0 | 6 | 7, 9) => 2, + (0, _) => 1, + _ => 0, + }; + e.usage = (1 << e.cols) - 1; + } + let ours: Vec<&SigElement> = ps_inputs.iter().filter(|e| stand_in(e)).collect(); + if ours.iter().any(|e| e.row.is_none()) { + return Err(unsupported("a barycentrics stand-in without a register")); + } + let taken = |row: Option| ours.iter().any(|e| e.row == row); + + // The pixel shader placed its stand-ins after its own inputs, not + // knowing the vertex shader's registers: an output there the pixel + // shader does not read. A system value (the position, clip distances) + // moves to a free register past them, where the pixel shader does not + // look for it; anything else is left out. + let mut outputs = Vec::new(); + let mut sources = Vec::new(); + let mut moved = Vec::new(); + for (id, e) in vs_outputs.iter().enumerate() { + if taken(e.row) { + if e.kind != 0 { + moved.push(id); + } + continue; + } + outputs.push(e.clone()); + sources.push(Source::Output(id)); + } + let used = outputs.iter().chain(ours.iter().copied()).filter_map(|e| e.row).max(); + let mut free = used.map_or(0, |r| r + 1); + // (elements that shared a row stay together: old row, new row) + let mut rows: Vec<(Option, u32)> = Vec::new(); + for id in moved { + let mut e = vs_outputs[id].clone(); + let row = match rows.iter().find(|(old, _)| *old == e.row) { + Some(&(_, new)) => new, + None => { + rows.push((e.row, free)); + free += 1; + free - 1 + } + }; + e.row = Some(row); + outputs.push(e); + sources.push(Source::Output(id)); + } + if free > 32 { + return Err(unsupported("a barycentrics stage with more than 32 output registers")); + } + for e in &ours { + let source = if e.name == super::BARY_INPUT { + Source::Weights + } else { + let (k, row, col) = super::vertex_source(e.index); + if !(1..=2).contains(&k) { + return Err(unsupported("a vertex stand-in of a vertex other than 1 or 2")); + } + let input = vs_outputs.iter().enumerate().find_map(|(id, o)| { + (o.row == Some(row) && col >= o.col && col < o.col + o.cols).then(|| (id, col - o.col)) + }); + Source::Vertex(input, u32::from(k)) + }; + // (a signature has no interpolation mode: as `emit_program` + // declares the vertex shader's float and integer outputs) + let interp = if e.name == super::VERTEX_INPUT { 1 } else { 2 }; + outputs.push(SigElement { + usage: (1 << e.cols) - 1, + interp, + ..(*e).clone() + }); + sources.push(source); + } + // The primitive id the pixel shader declares, as one more output. + let wanted = ps_inputs + .iter() + .find(|e| e.kind == 10 && e.row.is_some()) + .filter(|_| !vs_outputs.iter().any(|o| o.kind == 10)); + if let Some(e) = wanted { + // Alone in its columns, and in a row of constant elements. + let clash = outputs.iter().any(|o| { + let overlap = o.col < e.col + e.cols && e.col < o.col + o.cols; + o.row == e.row && (o.interp != 1 || overlap) + }); + if clash { + return Err(unsupported( + "a barycentrics stage whose primitive id shares a register with another output", + )); + } + outputs.push(SigElement { + interp: 1, + usage: (1 << e.cols) - 1, + ..e.clone() + }); + sources.push(Source::Primitive); + } + let scalars: u32 = outputs.iter().map(|e| u32::from(e.cols)).sum(); + if scalars * 3 > MAX_SCALARS { + return Err(unsupported( + "a barycentrics stage with more output components than a geometry shader emits", + )); + } + + let mut s = Shader::new(false); + s.geometry = Some(Geometry { max_vertices: 3 }); + s.inputs = vs_outputs; + s.outputs = outputs; + let b = s.entry; + let primitive = sources + .iter() + .any(|x| matches!(x, Source::Primitive)) + .then(|| s.op(b, "primitiveID.i32", Attr::ReadNone, s.t.i32, 108, &[])); + let stream = s.m.i8(0); + for vertex in 0..3u32 { + for (out, source) in sources.iter().enumerate() { + let float = s.outputs[out].comp == 9; + let cols = s.outputs[out].cols; + let values: Vec = match *source { + Source::Output(id) => (0..cols).map(|col| load(&mut s, id, col, vertex)).collect(), + Source::Weights => (0..u32::from(cols)) + .map(|col| s.m.f32((if col == vertex { 1f32 } else { 0f32 }).to_bits())) + .collect(), + Source::Vertex(input, k) => { + let v = match input { + Some((id, col)) => { + let v = load(&mut s, id, col, k); + let from_float = s.inputs[id].comp == 9; + match (from_float, float) { + (true, false) => s.m.cast(b, Cast::Bitcast, v, s.t.i32), + (false, true) => s.m.cast(b, Cast::Bitcast, v, s.t.f32), + _ => v, + } + } + None if float => s.m.f32(0), + None => s.m.i32(0), + }; + vec![v] + } + Source::Primitive => vec![primitive.expect("the primitive id is read")], + }; + let name = if float { "storeOutput.f32" } else { "storeOutput.i32" }; + for (col, value) in values.into_iter().enumerate() { + let args = [s.m.i32(out as u32), s.m.i32(0), s.m.i8(col as u8), value]; + s.op(b, name, Attr::NoUnwind, s.t.void, 5, &args); + } + } + s.op(b, "emitStream", Attr::NoUnwind, s.t.void, 97, &[stream]); + } + s.op(b, "cutStream", Attr::NoUnwind, s.t.void, 98, &[stream]); + s.m.terminate(b, Term::Ret); + Ok(s.finish()) +} + +/// Column `col` of input `id` at vertex `vertex` of the triangle. +fn load(s: &mut Shader, id: usize, col: u8, vertex: u32) -> V { + let (name, ty) = if s.inputs[id].comp == 9 { + ("loadInput.f32", s.t.f32) + } else { + ("loadInput.i32", s.t.i32) + }; + let args = [ + s.m.i32(id as u32), + s.m.i32(0), + s.m.i8(col), + s.m.i32(vertex), + ]; + let entry = s.entry; + s.op(entry, name, Attr::ReadNone, ty, 4, &args) +} diff --git a/d3d12/crates/leonida-shader/src/emit/lower.rs b/d3d12/crates/leonida-shader/src/emit/lower.rs index a897d21c34..e40d65c361 100644 --- a/d3d12/crates/leonida-shader/src/emit/lower.rs +++ b/d3d12/crates/leonida-shader/src/emit/lower.rs @@ -1594,17 +1594,44 @@ fn own_bits_on() -> bool { /// What the translator was told of the host, for a cache's key: the widest /// wave, the view heap's limit, where the raw twins of its views start, and -/// what it writes for the console's own hardware. -pub fn host_settings() -> [u32; 5] { +/// what it writes for the console's own hardware, whether mesh programs +/// run as compute and whether pixel shaders go without barycentrics. +pub fn host_settings() -> [u32; 6] { [ host_max_wave(), super::shader::view_heap_limit(), super::shader::raw_views(), host_rdna(), u32::from(host_mesh_compute()), + u32::from(!host_barycentrics()), ] } +static HOST_NO_BARYCENTRICS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Tells the translator whether the host has D3D12 barycentrics +/// (`SV_Barycentrics`, `attributeAtVertex`; Turing and newer). Without them +/// a pixel shader reads the weights and the other vertices' values from +/// ordinary inputs a geometry shader of ours writes ([`super::bary_gs`]). +pub fn set_host_barycentrics(on: bool) { + HOST_NO_BARYCENTRICS.store(!on, std::sync::atomic::Ordering::Relaxed); +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`host_barycentrics`], for its thread only. + pub(super) static TEST_BARYCENTRICS: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Whether pixel shaders may use D3D12 barycentrics ([`set_host_barycentrics`]). +pub fn host_barycentrics() -> bool { + #[cfg(test)] + if let Some(on) = TEST_BARYCENTRICS.get() { + return on; + } + !HOST_NO_BARYCENTRICS.load(std::sync::atomic::Ordering::Relaxed) +} + static HOST_MESH_COMPUTE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// Tells the translator whether the host runs mesh shaders. Without them a @@ -3343,6 +3370,9 @@ impl<'a> Lower<'a> { } self.fill_phis()?; } + if self.s.pixel && !host_barycentrics() { + place_fallback_inputs(&mut self.s.inputs).map_err(|why| unsupported(0, why))?; + } let user_data = self.user_reads.values().copied().collect(); self.s.samplers = self.samplers.len() as u32; let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect(); @@ -3816,6 +3846,9 @@ impl<'a> Lower<'a> { if index > 1 { return Val::Missing("pull-model barycentrics"); } + if !host_barycentrics() { + return self.fallback_barycentric(mode, index); + } // One element per interpolation mode (the console's own, if its // signature declares one): DXIL allows two. let bary = |e: &SigElement| e.kind == 28; @@ -3858,6 +3891,60 @@ impl<'a> Lower<'a> { self.load_any_input(id, index + 1) } + /// [`Self::barycentric`] on a host without barycentrics: channel + /// `index + 1` of an ordinary three-float input [`super::BARY_INPUT`] + /// interpolated with `mode`, which [`super::bary_gs`] writes as (1, 0, + /// 0), (0, 1, 0) and (0, 0, 1) at the triangle's vertices 0, 1 and 2: + /// interpolated, the weights `SV_Barycentrics` would hold. Its register + /// is placed after the title's inputs when the shader is finished. + fn fallback_barycentric(&mut self, mode: u8, index: u8) -> Val { + // A barycentrics element the console's signature declared is not + // read any more: the weights come from ours. + let ours = |e: &SigElement| e.kind == 0 && e.name == super::BARY_INPUT; + let console = self + .s + .inputs + .iter() + .position(|e| e.kind == 28 && (e.interp == mode || e.usage == 0)); + let id = match self.s.inputs.iter().position(|e| ours(e) && e.interp == mode) { + Some(id) => id, + None => { + let index = self.s.inputs.iter().filter(|e| ours(e)).count() as u32; + if index >= 2 { + return Val::Missing("barycentrics of a third interpolation mode"); + } + if let Some(id) = console + && (self.s.inputs[id].col != 0 || self.s.inputs[id].cols < 3) + { + return Val::Missing("a console barycentrics element without i and j"); + } + let e = SigElement { + name: super::BARY_INPUT.into(), + index, + kind: 0, + comp: 9, + interp: mode, + row: None, + col: 0, + cols: 3, + usage: 0, + half: false, + }; + match console { + Some(id) => { + self.s.inputs[id] = e; + id + } + None => { + self.s.inputs.push(e); + self.s.inputs.len() - 1 + } + } + } + }; + self.load_any_input(id, index + 1) + } + fn i32_of(&mut self, v: Value) -> Result { match self.get(v)? { Val::I32(x) => Ok(x), @@ -12284,6 +12371,9 @@ impl<'a> Lower<'a> { /// Vertex `k` (0 the provoking vertex, as `barycentric` orders them) /// of a constant input element's channel, as a float. fn vertex_input(&mut self, id: usize, col: u8, k: u8) -> V { + if !host_barycentrics() { + return self.fallback_vertex_input(id, col, k); + } let e = &mut self.s.inputs[id]; e.usage |= 1 << col; let int = e.comp != 9; @@ -12315,6 +12405,69 @@ impl<'a> Lower<'a> { } } + /// [`Self::vertex_input`] on a host without barycentrics. Vertex 0 is + /// the element itself: it is constant, and a constant input is the + /// first vertex's, which [`super::bary_gs`] emits first. Vertices 1 and + /// 2 are one-channel constant inputs [`super::VERTEX_INPUT`] of their + /// own whose semantic index names the source ([`super::vertex_index`]): + /// the geometry shader copies that vertex's value of the vertex + /// shader's output in the element's register and column into them. + fn fallback_vertex_input(&mut self, id: usize, col: u8, k: u8) -> V { + let e = &self.s.inputs[id]; + // The other vertices' values as 32-bit floats or as raw bits. + let int = e.comp != 9; + let comp = if int { 5 } else { 9 }; + let source = e.row.map(|row| (row, e.col + col)); + let id = match (k, source) { + (0, _) | (_, None) => id, + (k, Some((row, col))) => { + let index = super::vertex_index(k, row, col); + let ours = |e: &SigElement| e.name == super::VERTEX_INPUT && e.index == index; + match self.s.inputs.iter().position(ours) { + Some(id) => id, + None => { + self.s.inputs.push(SigElement { + name: super::VERTEX_INPUT.into(), + index, + kind: 0, + comp, + interp: 1, + row: None, + col: 0, + cols: 1, + usage: 0, + half: false, + }); + self.s.inputs.len() - 1 + } + } + } + }; + // A source without a register (a system value) has no vertex + // shader output to copy: its vertex 0 value stands for all three. + let col = if k == 0 || source.is_none() { col } else { 0 }; + let e = &mut self.s.inputs[id]; + e.usage |= 1 << col; + let (ty, suffix) = if int { + (self.s.t.i32, ".i32") + } else { + (self.s.t.f32, ".f32") + }; + let entry = self.s.entry; + let args = [ + self.s.m.i32(id as u32), + self.s.m.i32(0), + self.s.m.i8(col), + self.s.m.undef(self.s.t.i32), + ]; + let v = self.s.op(entry, &format!("loadInput{suffix}"), Attr::ReadNone, ty, 4, &args); + if int { + self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.f32) + } else { + v + } + } + /// `x` (an f16 in the low bits) as the low half of VGPR `reg`: 16-bit /// results keep the register's high half (GFX10). fn low_half(&mut self, inst: &Inst, reg: u8, x: V) -> V { @@ -14580,6 +14733,66 @@ impl<'a> Lower<'a> { /// The DXIL interpolation mode of a kind of barycentrics (none for the /// pull model). +/// The pixel inputs a host without barycentrics reads in their place +/// ([`super::BARY_INPUT`], [`super::VERTEX_INPUT`]) get registers after the +/// title's: each weights element a row of its own (its interpolation mode +/// is the row's), the one-channel vertex values packed four to a row, the +/// floats and the integers apart. A console barycentrics element no +/// barycentric read took over is not declared on the host: it turns into +/// an unread weights element. More rows than a pixel shader has (32) are +/// refused. +fn place_fallback_inputs(inputs: &mut [SigElement]) -> Result<(), Why> { + const ROWS: u32 = 32; + let ours = |e: &SigElement| e.name == super::BARY_INPUT || e.name == super::VERTEX_INPUT; + // (indices after the two a barycentric read may take) + for (n, e) in inputs.iter_mut().filter(|e| e.kind == 28).enumerate() { + *e = SigElement { + name: super::BARY_INPUT.into(), + index: 2 + n as u32, + kind: 0, + comp: 9, + interp: if e.interp == 0 { 2 } else { e.interp }, + row: None, + col: 0, + cols: 3, + usage: 0, + half: false, + }; + } + let mut next = inputs + .iter() + .filter(|e| !ours(e)) + .filter_map(|e| e.row) + .max() + .map_or(0, |r| r + 1); + for e in inputs.iter_mut().filter(|e| e.name == super::BARY_INPUT) { + e.row = Some(next); + next += 1; + } + for comp in [9, 5] { + let mut col = 0; + for e in inputs + .iter_mut() + .filter(|e| e.name == super::VERTEX_INPUT && e.row.is_none() && e.comp == comp) + { + e.row = Some(next); + e.col = col; + col += 1; + if col == 4 { + col = 0; + next += 1; + } + } + if col != 0 { + next += 1; + } + } + if next > ROWS { + return Err("more pixel inputs than 32 registers with the barycentrics stand-ins"); + } + Ok(()) +} + fn interp_mode(kind: Barycentric) -> Option { Some(match kind { Barycentric::PerspectiveCenter => 2, diff --git a/d3d12/crates/leonida-shader/src/emit/mod.rs b/d3d12/crates/leonida-shader/src/emit/mod.rs index 01fe25fe85..daf83c400f 100644 --- a/d3d12/crates/leonida-shader/src/emit/mod.rs +++ b/d3d12/crates/leonida-shader/src/emit/mod.rs @@ -80,6 +80,7 @@ //! shaders and draws triangle lists with the title's own vertex counts. //! It binds nothing. +mod bary_gs; mod bitcode; mod container; #[cfg(all(test, windows))] @@ -128,7 +129,32 @@ use crate::{ShaderError, io, ir, resource, structure}; pub use bitcode::census; pub use sampler::StaticSampler; -pub use lower::{host_settings, mesh_as_compute, set_host_max_wave, set_host_mesh_shaders, set_host_rdna, take_pack_why}; +pub use bary_gs::{bary_gs, needs_bary_gs}; +pub use lower::{ + host_barycentrics, host_settings, mesh_as_compute, set_host_barycentrics, set_host_max_wave, set_host_mesh_shaders, + set_host_rdna, take_pack_why, +}; + +/// A host without barycentrics: the pixel input that stands for +/// `SV_Barycentrics` (three floats, one element per interpolation mode, semantic +/// index 0 or 1), written by [`bary_gs`]. +pub const BARY_INPUT: &str = "LEONIDA_BARY"; + +/// A host without barycentrics: a one-channel constant pixel input holding one +/// channel of another vertex's value (what `attributeAtVertex` read); its +/// semantic index says which ([`vertex_index`]). +pub const VERTEX_INPUT: &str = "LEONIDA_VTX"; + +/// The semantic index of the [`VERTEX_INPUT`] that holds vertex `k` (1 or 2) of +/// the value in register `row`, column `col`. +pub fn vertex_index(k: u8, row: u32, col: u8) -> u32 { + u32::from(k) << 16 | row << 2 | u32::from(col) +} + +/// [`vertex_index`] read back: (vertex, register, column). +pub fn vertex_source(index: u32) -> (u8, u32, u8) { + ((index >> 16) as u8, (index >> 2) & 0x3fff, (index & 3) as u8) +} pub use mesh_vs::mesh_vs; pub use rect::rect_list_gs; pub use shader::{ @@ -4175,6 +4201,253 @@ mod barycentric_tests { validate(&shader); } + /// What a program of [`barycentric_programs`] writes at weights i and j + /// of a triangle whose TEXCOORD0 is (2, 3) at vertex 0, (6, 5) at 1 and + /// (10, 7) at 2. + type Expected = fn(f32, f32) -> f32; + + /// The pixel programs of the barycentrics tests above: (name, words, + /// barycentrics the program loads, what it writes). + fn barycentric_programs() -> Vec<(&'static str, Vec, u32, Expected)> { + let [e0, e1] = exp_mrt0(2); + let [f0, f1] = exp_mrt0(4); + let [g0, g1] = exp_mrt0(3); + vec![ + ("values", vec![v_add_f32(2, 0, 1), e0, e1, S_ENDPGM], PERSP_CENTER, |i, j| i + j), + ("two modes", vec![v_add_f32(4, 0, 3), f0, f1, S_ENDPGM], PERSP_CENTER | LINEAR_CENTER, |i, j| i + j), + ( + "interpolation and a value", + vec![0xC808_0000, 0xC809_0001, v_add_f32(3, 2, 1), g0, g1, S_ENDPGM], + PERSP_CENTER, + |i, j| 2.0 + 4.0 * i + 8.0 * j + j, + ), + ( + "computed i", + vec![0x1006_00F0, 0xC808_0003, 0xC809_0001, e0, e1, S_ENDPGM], + PERSP_CENTER, + |i, j| 2.0 + 2.0 * i + 8.0 * j, + ), + ( + "constant weights", + vec![0x7E06_02F0, 0xC808_0003, 0xC809_0003, e0, e1, S_ENDPGM], + PERSP_CENTER, + |_, _| 8.0, + ), + ( + "computed and loaded", + vec![ + 0xC810_0100, + 0xC811_0101, + 0x1006_02F0, + 0xC808_0000, + 0xC809_0003, + v_add_f32(2, 2, 4), + e0, + e1, + S_ENDPGM, + ], + PERSP_CENTER, + |i, j| 5.0 + 6.0 * i + 8.0 * j, + ), + ( + "p10", + vec![0xC808_0000, 0xC809_0001, 0xC812_0000, v_add_f32(2, 2, 4), e0, e1, S_ENDPGM], + PERSP_CENTER, + |i, j| 6.0 + 4.0 * i + 8.0 * j, + ), + ] + } + + /// `pixel` as a host without barycentrics translates it. + fn pixel_without_barycentrics(words: &[u32], ena: u32) -> Result { + let was = lower::TEST_BARYCENTRICS.replace(Some(false)); + let shader = pixel(words, ena); + lower::TEST_BARYCENTRICS.set(was); + shader + } + + /// `D3D12-BARYCENTRICS-FALLBACK`: without host barycentrics every one of + /// those programs declares neither the feature nor `SV_Barycentrics`; + /// it reads `LEONIDA_BARY` and `LEONIDA_VTX` inputs in registers after + /// its own, and the validator accepts it. + #[test] + fn without_host_barycentrics_pixel_programs_read_stand_ins() { + for (name, words, ena, _) in barycentric_programs() { + let shader = pixel_without_barycentrics(&words, ena).unwrap_or_else(|e| panic!("{name}: {e}")); + let (features, inputs) = parts(&shader); + assert_eq!(features & 0x2_0000, 0, "{name}: the Barycentrics feature"); + assert!(inputs.iter().all(|e| e.kind != 28), "{name}: {inputs:?}"); + let ours: Vec<_> = inputs.iter().filter(|e| e.name == BARY_INPUT || e.name == VERTEX_INPUT).collect(); + assert!(!ours.is_empty(), "{name}: no stand-ins: {inputs:?}"); + let own = inputs + .iter() + .filter(|e| e.name != BARY_INPUT && e.name != VERTEX_INPUT) + .filter_map(|e| e.row) + .max(); + for e in &ours { + assert!(e.row.is_some() && e.row > own, "{name}: {e:?} not after the title's inputs"); + if e.name == VERTEX_INPUT { + assert_eq!(e.cols, 1, "{name}: {e:?}"); + assert!((1..=2).contains(&vertex_source(e.index).0), "{name}: {e:?}"); + } + } + assert!(needs_bary_gs(&shader.dxil), "{name}"); + validate(&shader); + // With host barycentrics the same program needs no stage. + assert!(!needs_bary_gs(&pixel(&words, ena).unwrap().dxil), "{name}"); + } + assert_eq!(vertex_source(vertex_index(2, 31, 3)), (2, 31, 3)); + } + + /// The vertex shader of the device tests: POSITION and TEXCOORD0 through, + /// TEXCOORD in output row 0 as the translated pixel shaders read it. + #[cfg(windows)] + fn texcoord_vs() -> HostShader { + use super::bitcode::{Attr, Term}; + use super::shader::Shader; + let mut s = Shader::new(false); + s.inputs = vec![element("POSITION", 0, 0), element("TEXCOORD", 0, 1)]; + for e in &mut s.inputs { + e.usage = 15; + } + s.outputs = vec![element("TEXCOORD", 0, 0), element("SV_Position", 3, 1)]; + for (i, e) in s.outputs.iter_mut().enumerate() { + e.usage = 15; + e.interp = if i == 1 { 4 } else { 2 }; + } + for row in 0..2 { + for col in 0..4 { + let args = [s.m.i32(row), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)]; + let v = s.op(s.entry, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args); + let args = [s.m.i32(1 - row), s.m.i32(0), s.m.i8(col), v]; + s.op(s.entry, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + } + s.m.terminate(s.entry, Term::Ret); + HostShader { + stage: HwStage::Vs, + dxil: s.finish(), + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + half_views: Vec::new(), + mesh_out: None, + } + } + + /// The stage links the vertex shader with each stand-in pixel shader, + /// and the validator accepts it. + #[test] + #[cfg(windows)] + fn the_barycentrics_stage_is_a_valid_geometry_shader() { + let vs = texcoord_vs(); + for (name, words, ena, _) in barycentric_programs() { + let ps = pixel_without_barycentrics(&words, ena).unwrap(); + let gs = bary_gs(&vs.dxil, &ps.dxil).unwrap_or_else(|e| panic!("{name}: {e}")); + let c = Container::parse(&gs).unwrap(); + // Program version: geometry (2), shader model 6.6. + assert_eq!(c.part(FourCC::DXIL).unwrap().data[..4], [0x66, 0, 2, 0], "{name}"); + let outs = signature(c.part(FourCC::OSG1).unwrap().data).unwrap(); + let (_, ins) = parts(&ps); + for e in ins.iter().filter(|e| e.row.is_some() && e.kind == 0) { + assert!( + outs.iter().any(|o| (&o.name, o.index, o.row, o.col) == (&e.name, e.index, e.row, e.col)), + "{name}: {e:?} is not written" + ); + } + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut gs.clone()).unwrap_or_else(|e| panic!("{name}: {e}")); + } + } + } + + /// One triangle over an 8x8 target: each program drawn through the stage + /// with the stand-ins writes what the console's interpolation gives + /// (worked out by hand), and, where the host has barycentrics to compare + /// with, what the host draws with them. + #[test] + #[cfg(windows)] + fn the_barycentrics_stage_draws_what_host_barycentrics_draw() { + use super::host::{Draw, Host}; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let vs = texcoord_vs(); + // (the triangle of `first_half_values_render_on_hardware_and_warp`: + // at a pixel's centre i is (row + 0.5) / 16 and j (column + 0.5) / 16) + let vertices = [ + -1.0, 1.0, 0.5, 1.0, 2.0, 3.0, 0.0, 0.0, -1.0, -3.0, 0.5, 1.0, 6.0, 5.0, 0.0, 0.0, 3.0, + 1.0, 0.5, 1.0, 10.0, 7.0, 0.0, 0.0, + ]; + let mut ran = 0; + for (backend, warp) in [("hardware", false), ("WARP", true)] { + let Ok(host) = Host::new(warp) else { continue }; + let mut options = + windows::Win32::Graphics::Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS3::default(); + // SAFETY: a correctly sized output for the feature query. + unsafe { + host.device + .CheckFeatureSupport( + windows::Win32::Graphics::Direct3D12::D3D12_FEATURE_D3D12_OPTIONS3, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .unwrap(); + } + let native = options.BarycentricsSupported.as_bool(); + for (name, words, ena, expected) in barycentric_programs() { + let draw = |ps: &HostShader, gs: Option<&[u8]>| { + let root = host.root_signature(&vs, ps).unwrap(); + let pso = host + .pipeline_with_gs(&root, &vs.dxil, gs, &ps.dxil) + .unwrap_or_else(|e| panic!("{backend} {name}: {e}")); + let d = Draw { + roots: Vec::new(), + textures: &[], + samplers: &[], + vertices: &vertices, + stride: 32, + size: (8, 8), + mesh_groups: 0, + vertex_count: 0, + instances: 0, + }; + host.draw(&root, &pso, &d).unwrap() + }; + let ps = pixel_without_barycentrics(&words, ena).unwrap(); + let gs = bary_gs(&vs.dxil, &ps.dxil).unwrap(); + let ours = draw(&ps, Some(&gs[..])); + for (n, texel) in ours.iter().enumerate() { + let i = (n / 8) as f32 / 16.0 + 0.5 / 16.0; + let j = (n % 8) as f32 / 16.0 + 0.5 / 16.0; + let want = expected(i, j); + assert!( + texel.iter().all(|got| (got - want).abs() < 1e-4), + "{backend} {name} pixel {n}: {texel:?}, not {want}" + ); + } + if native { + let theirs = draw(&pixel(&words, ena).unwrap(), None); + for (n, (a, b)) in ours.iter().zip(&theirs).enumerate() { + assert!( + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4), + "{backend} {name} pixel {n}: stand-ins {a:?}, barycentrics {b:?}" + ); + } + } + } + ran += 1; + eprintln!("the barycentrics stage draws on {backend} (compared: {native})"); + } + if ran == 0 { + eprintln!("no SM 6.6 host; GPU checks skipped"); + } + } + /// P10 of an attribute the program interpolates is P1 - P0. #[test] fn p10_of_an_interpolated_attribute() { From 38ccdccef086692ad69f1eda2069e738414ba1ed Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sat, 28 Nov 2026 19:35:58 +0200 Subject: [PATCH 08/15] d3d12: pipelines put the barycentrics stage in on a host without barycentrics At device creation, OPTIONS3.BarycentricsSupported tells the translator whether to use stand-ins (LEONIDA_BARY_FALLBACK=1 takes the fallback on any card). A graphics pipeline whose pixel shader reads them gets bary_gs between its vertex and pixel shaders, named apart in the pipeline library. shortcut: a rectangle list drops its own geometry stage for it (logged); mesh-as-compute pipelines do not get it yet. MEASURED on a GTX 1050 Ti, Windows 10 with #2557 and the D3D12 debug layer, 10 minutes of play: - "host pipeline refused": 0 (369 before); - "Shader uses Barycentrics": 0 (435 before); - no geometry/pixel stage linkage messages; - 2 pixel shaders refused for 32 rows. Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/host.rs | 12 ++++++++ d3d12/crates/leonida-gpu/src/pipeline/host.rs | 29 +++++++++++++++++-- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index c5d47593d6..412c8931ff 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -1209,6 +1209,18 @@ fn create() -> windows::core::Result { let forced = std::env::var_os("LEONIDA_MESH_COMPUTE").is_some_and(|v| v == "1"); leonida_shader::emit::set_host_mesh_shaders(mesh && !forced); tracing::info!(mesh, forced, "mesh programs run as compute: {}", !mesh || forced); + // `D3D12-BARYCENTRICS-FALLBACK`: without D3D12 barycentrics (Pascal and older refuse every pixel + // shader that reads them: "Shader uses Barycentrics, but the device does not support this") the + // translator reads the weights and the other vertices' values from inputs a geometry stage of ours + // writes (`leonida_shader::emit::bary_gs`). `LEONIDA_BARY_FALLBACK=1` takes that path on any card. + let mut o3 = D3D12_FEATURE_DATA_D3D12_OPTIONS3::default(); + let barycentrics = device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS3, (&raw mut o3).cast(), size_of_val(&o3) as u32) + .is_ok() + && o3.BarycentricsSupported.as_bool(); + let forced = crate::switch::on("LEONIDA_BARY_FALLBACK"); + leonida_shader::emit::set_host_barycentrics(barycentrics && !forced); + tracing::info!(barycentrics, forced, "pixel shaders read barycentrics through a geometry stage: {}", !barycentrics || forced); let messages = debug .then(|| device.cast::().ok()) .flatten(); diff --git a/d3d12/crates/leonida-gpu/src/pipeline/host.rs b/d3d12/crates/leonida-gpu/src/pipeline/host.rs index 5e141f0c1a..44b0d5acd2 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/host.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/host.rs @@ -949,12 +949,31 @@ impl HostPipeline { Err(e) => tracing::warn!(error = %e, ?shaders, "no rectangle geometry stage"), } } + // `D3D12-BARYCENTRICS-FALLBACK`: a pixel shader translated for a host + // without barycentrics (`leonida_shader::emit::set_host_barycentrics`) + // reads inputs that only the barycentrics geometry stage writes. + // shortcut: a rectangle list then goes without its own stage (the + // two do not combine yet): `draw` completes its rectangles as it does + // when the host refuses that stage. + let mut bary_gs = None; + if let Some(ps) = stages.get(1).and_then(|(s, _)| s.translated()) + && leonida_shader::emit::needs_bary_gs(&ps.host.dxil) + { + let vs = &stages[0].0.translated()?.host.dxil; + if rect_gs.take().is_some() { + tracing::warn!(?shaders, "a rectangle list without its geometry stage: its pixel shader needs the barycentrics stage"); + } + match leonida_shader::emit::bary_gs(vs, &ps.host.dxil) { + Ok(gs) => bary_gs = Some(gs), + Err(e) => tracing::warn!(error = %e, ?shaders, "no barycentrics geometry stage"), + } + } let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { // SAFETY: a borrowed pointer the description never releases. pRootSignature: unsafe { std::mem::transmute_copy(&root) }, VS: code(0), PS: code(1), - GS: rect_gs.as_ref().map_or(D3D12_SHADER_BYTECODE::default(), |gs| { + GS: rect_gs.as_ref().or(bary_gs.as_ref()).map_or(D3D12_SHADER_BYTECODE::default(), |gs| { D3D12_SHADER_BYTECODE { pShaderBytecode: gs.as_ptr().cast(), BytecodeLength: gs.len(), @@ -984,6 +1003,12 @@ impl HostPipeline { // A pipeline with the geometry stage has a name of its own in the // library; the others keep theirs. let name = |gs: Option<&Vec>| match gs { + Some(gs) if bary_gs.is_some() => super::library::name( + "graphics barycentrics", + &root_blob, + &[&code_bytes(&code(0)), &code_bytes(&code(1)), &gs[..]], + &state, + ), Some(gs) => super::library::name( "graphics rectangles", &root_blob, @@ -1011,7 +1036,7 @@ impl HostPipeline { || unsafe { host.device.CreateGraphicsPipelineState(desc) }, ) }; - let mut made = make(&desc, &name(rect_gs.as_ref())); + let mut made = make(&desc, &name(rect_gs.as_ref().or(bary_gs.as_ref()))); if made.is_err() && rect_gs.is_some() { // The host refused the geometry stage: once more without it. tracing::warn!(?shaders, "host pipeline refused with the rectangle geometry stage"); From 5674b8a97aaee6cd4b5ea3627e359a00abca589f Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sat, 28 Nov 2026 20:15:29 +0200 Subject: [PATCH 09/15] d3d12: mesh_vs writes the barycentrics stand-ins for a mesh program run as compute A pixel shader drawn behind a mesh program on a host without barycentrics reads LEONIDA_BARY and LEONIDA_VTX, which no geometry stage writes on that path: they read zero, and what the title draws with mesh shaders came out black. mesh_vs writes them itself, since every corner is its own vertex there: - the weights are 1 at the corner's column; - vertex k's value is read through the primitive's corner-k index, the same at all three corners. A vertex output on a stand-in's register is left out, or moves past them if it is a system value (as bary_gs). Pipelines that draw through mesh_vs do not get bary_gs. Test: for the seven barycentric programs, every stand-in their pixel shader reads is a mesh_vs output in the same register, and dxil.dll takes the vertex shader (mesh 8, barycentric 19 tests pass on a GTX 1050 Ti). Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/pipeline/host.rs | 7 + .../crates/leonida-shader/src/emit/mesh_vs.rs | 131 ++++++++++++++++-- d3d12/crates/leonida-shader/src/emit/mod.rs | 39 ++++++ 3 files changed, 162 insertions(+), 15 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/pipeline/host.rs b/d3d12/crates/leonida-gpu/src/pipeline/host.rs index 44b0d5acd2..77a649f00f 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/host.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/host.rs @@ -956,7 +956,14 @@ impl HostPipeline { // two do not combine yet): `draw` completes its rectangles as it does // when the host refuses that stage. let mut bary_gs = None; + // (A mesh program run as compute draws through `mesh_vs`, which writes + // the stand-ins itself: every corner is its own vertex there.) + let mesh_vs = stages + .first() + .and_then(|(s, _)| s.translated()) + .is_some_and(|t| t.host.root_srvs.contains(&leonida_shader::emit::SLOT_MESH_IN)); if let Some(ps) = stages.get(1).and_then(|(s, _)| s.translated()) + && !mesh_vs && leonida_shader::emit::needs_bary_gs(&ps.host.dxil) { let vs = &stages[0].0.translated()?.host.dxil; diff --git a/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs b/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs index a12e8b8b63..48917884df 100644 --- a/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs +++ b/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs @@ -46,11 +46,18 @@ pub fn mesh_vs(layout: &MeshOut, ps: Option<&[u8]>) -> Result, ShaderErr build(layout, vertex, &primitive, &wanted) } -/// Where an output's value comes from: byte `at` of its vertex (`false`) -/// or of its primitive past the indices (`true`). -struct Source { - primitive: bool, - at: u32, +/// Where an output's value comes from. +enum Source { + /// Byte `at` of its vertex (`false`) or of its primitive past the + /// indices (`true`). + Out { primitive: bool, at: u32 }, + /// [`super::BARY_INPUT`] on a host without barycentrics: 1 at the + /// corner's column, 0 elsewhere (each corner is its own vertex here, so + /// interpolated they are the weights). + Weights, + /// [`super::VERTEX_INPUT`]: corner `k`'s value of the vertex output at + /// byte `at` (none there: 0), the same at all three corners. + Corner { k: u32, at: Option }, } fn build( @@ -69,14 +76,33 @@ fn build( if layout.max_primitives == 0 { return Err(unsupported("a mesh program without primitives")); } + // The pixel shader's barycentrics stand-ins (a host without + // barycentrics) are placed past its own inputs, not knowing the mesh + // program's registers: a vertex output there that the pixel shader does + // not read is left out, a system value moves past them (as `bary_gs`). + let ours: Vec<&SigElement> = ps_inputs + .iter() + .filter(|e| e.name == super::BARY_INPUT || e.name == super::VERTEX_INPUT) + .collect(); + if ours.iter().any(|e| e.row.is_none()) { + return Err(unsupported("a barycentrics stand-in without a register")); + } + let taken = |row: Option| ours.iter().any(|e| e.row == row); let mut outputs = Vec::new(); let mut sources = Vec::new(); - for (e, &at) in vertex.iter().zip(&layout.vertex_at) { + let mut moved = Vec::new(); + for (id, (e, &at)) in vertex.iter().zip(&layout.vertex_at).enumerate() { + if taken(e.row) { + if e.kind != 0 { + moved.push(id); + } + continue; + } outputs.push(SigElement { usage: (1 << e.cols) - 1, ..e.clone() }); - sources.push(Source { primitive: false, at }); + sources.push(Source::Out { primitive: false, at }); } // A per-primitive output goes where the pixel shader reads it; one the // pixel shader does not read is not drawn with. @@ -108,7 +134,50 @@ fn build( usage: (1 << p.cols) - 1, ..p.clone() }); - sources.push(Source { primitive: true, at }); + sources.push(Source::Out { primitive: true, at }); + } + let used = outputs.iter().chain(ours.iter().copied()).filter_map(|e| e.row).max(); + let mut free = used.map_or(0, |r| r + 1); + let mut rows: Vec<(Option, u32)> = Vec::new(); + for id in moved { + let mut e = vertex[id].clone(); + let row = match rows.iter().find(|(old, _)| *old == e.row) { + Some(&(_, new)) => new, + None => { + rows.push((e.row, free)); + free += 1; + free - 1 + } + }; + e.row = Some(row); + e.usage = (1 << e.cols) - 1; + outputs.push(e); + sources.push(Source::Out { primitive: false, at: layout.vertex_at[id] }); + } + if free > 32 { + return Err(unsupported("a mesh vertex shader with more than 32 output registers")); + } + for e in &ours { + let source = if e.name == super::BARY_INPUT { + Source::Weights + } else { + let (k, row, col) = super::vertex_source(e.index); + if !(1..=2).contains(&k) { + return Err(unsupported("a vertex stand-in of a vertex other than 1 or 2")); + } + let at = vertex.iter().zip(&layout.vertex_at).find_map(|(o, &at)| { + (o.row == Some(row) && col >= o.col && col < o.col + o.cols).then(|| at + 4 * u32::from(col - o.col)) + }); + Source::Corner { k: u32::from(k), at } + }; + // (as `bary_gs`: a signature has no interpolation mode) + let interp = if e.name == super::VERTEX_INPUT { 1 } else { 2 }; + outputs.push(SigElement { + usage: (1 << e.cols) - 1, + interp, + ..(*e).clone() + }); + sources.push(source); } let mut s = Shader::new(false); @@ -173,17 +242,49 @@ fn build( let vertex_at = s.m.bin(b, Bin::Mul, index, vstride); let vertex_at = s.m.bin(b, Bin::Add, vertex_at, base); + let f32t = s.t.f32; for (id, source) in sources.iter().enumerate() { - let (from, cols, float) = { - let e = &s.outputs[id]; - (if source.primitive { prim_at } else { vertex_at }, e.cols, e.comp == 9) + let (cols, float) = (s.outputs[id].cols, s.outputs[id].comp == 9); + // Corner `k`'s vertex, for a vertex stand-in. + let corner_vertex = match *source { + Source::Corner { k: c, .. } => { + let off = k(&mut s, 4 * c); + let at = s.m.bin(b, Bin::Add, prim_at, off); + let i = load(&mut s, at); + let i = s.m.select(b, past, zero, i); + let last = k(&mut s, layout.max_vertices.saturating_sub(1)); + let i = s.op(b, "binary.i32", Attr::ReadNone, i32t, 40, &[i, last]); + s.m.tag(i, super::bitcode::Tag::Clamp); + let v = s.m.bin(b, Bin::Mul, i, vstride); + Some(s.m.bin(b, Bin::Add, v, base)) + } + _ => None, }; for col in 0..cols { - let off = k(&mut s, source.at + 4 * u32::from(col)); - let at = s.m.bin(b, Bin::Add, from, off); - let bits = load(&mut s, at); + let bits = match *source { + Source::Out { primitive, at } => { + let from = if primitive { prim_at } else { vertex_at }; + let off = k(&mut s, at + 4 * u32::from(col)); + let at = s.m.bin(b, Bin::Add, from, off); + load(&mut s, at) + } + Source::Weights => { + let c = k(&mut s, u32::from(col)); + let here = s.m.cmp(b, super::bitcode::pred::EQ, corner, c); + let (one, nought) = (s.m.f32(1.0f32.to_bits()), s.m.f32(0)); + let w = s.m.select(b, here, one, nought); + s.m.cast(b, super::bitcode::Cast::Bitcast, w, i32t) + } + Source::Corner { at, .. } => match (at, corner_vertex) { + (Some(at), Some(v)) => { + let off = k(&mut s, at); + let at = s.m.bin(b, Bin::Add, v, off); + load(&mut s, at) + } + _ => zero, + }, + }; let (name, value) = if float { - let f32t = s.t.f32; ("storeOutput.f32", s.m.cast(b, super::bitcode::Cast::Bitcast, bits, f32t)) } else { ("storeOutput.i32", bits) diff --git a/d3d12/crates/leonida-shader/src/emit/mod.rs b/d3d12/crates/leonida-shader/src/emit/mod.rs index daf83c400f..e9832cf3e4 100644 --- a/d3d12/crates/leonida-shader/src/emit/mod.rs +++ b/d3d12/crates/leonida-shader/src/emit/mod.rs @@ -4299,6 +4299,45 @@ mod barycentric_tests { assert_eq!(vertex_source(vertex_index(2, 31, 3)), (2, 31, 3)); } + /// A mesh program run as compute draws through `mesh_vs`, which writes the + /// pixel shader's stand-ins itself (each corner is its own vertex there): + /// every stand-in the pixel shader reads is a `mesh_vs` output in the same + /// register, and dxil.dll takes the vertex shader. + #[test] + fn mesh_vs_writes_the_barycentrics_stand_ins() { + let element = |name: &str, kind, row| SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp: 2, + row: Some(row), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }; + let outputs = [element("SV_Position", 3, 0), element("TEXCOORD", 0, 1)]; + let layout = MeshOut::new(32, 32, &outputs, &[]); + for (name, words, ena, _) in barycentric_programs() { + let ps = pixel_without_barycentrics(&words, ena).unwrap_or_else(|e| panic!("{name}: {e}")); + let (_, inputs) = parts(&ps); + let vs = mesh_vs(&layout, Some(&ps.dxil)).unwrap_or_else(|e| panic!("{name}: mesh_vs: {e}")); + let c = Container::parse(&vs).unwrap(); + let written = signature(c.part(FourCC::OSG1).unwrap().data).unwrap(); + for e in inputs.iter().filter(|e| e.name == BARY_INPUT || e.name == VERTEX_INPUT) { + assert!( + written.iter().any(|o| o.name == e.name && o.index == e.index && o.row == e.row && o.col == e.col), + "{name}: {e:?} not written: {written:?}" + ); + } + #[cfg(windows)] + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut vs.clone()).unwrap_or_else(|e| panic!("{name}: {e}")); + } + } + } + /// The vertex shader of the device tests: POSITION and TEXCOORD0 through, /// TEXCOORD in output row 0 as the translated pixel shaders read it. #[cfg(windows)] From 7e691b652ca9fd71de973aafd7141d3ef077313e Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sun, 29 Nov 2026 12:24:01 +0200 Subject: [PATCH 10/15] d3d12: barycentrics stage review fixes: the vertex shader's interpolation, no mesh pipeline with the stand-ins, triangles only, moved outputs into free registers From timbot103's audit of c2f4cd35a (#2581): - bary_gs takes the vertex shader's interpolation from its PSV0, as the translator declared it from the title's (a float packed beside an integer can be constant there), instead of a default by type: the stage's rows carry the vertex shader's modes. - With the barycentrics stand-ins (no barycentrics, or LEONIDA_BARY_FALLBACK=1) mesh programs run as compute: a mesh pipeline has no stage after the mesh program to write the stand-ins, and mesh_vs writes them. - A pipeline with the barycentrics stage (`HostPipeline::bary`) draws triangle lists and strips only; a draw with points, lines or adjacency is left out and logged once (shortcut: no stage for those inputs yet). - A system value moved out of the stand-ins' rows takes the lowest free register (`lowest_free_row`), below the highest in use where one is free, in bary_gs and mesh_vs alike. Not in this commit: a rectangle list whose pixel shader needs the stand-ins still goes without the rectangle stage (the marked shortcut in pipeline/host.rs); the sink slot and the IA topology are fixed in the mesh commit below. Tests: the_vertex_shaders_interpolation_comes_from_its_psv0, moved_outputs_take_the_lowest_free_register. Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/draw.rs | 9 ++ d3d12/crates/leonida-gpu/src/host.rs | 37 ++++--- d3d12/crates/leonida-gpu/src/pipeline/host.rs | 6 ++ .../crates/leonida-shader/src/emit/bary_gs.rs | 98 +++++++++++++++---- .../crates/leonida-shader/src/emit/mesh_vs.rs | 13 +-- d3d12/crates/leonida-shader/src/emit/mod.rs | 21 ++++ 6 files changed, 145 insertions(+), 39 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index e28559a155..b24da23eeb 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs @@ -2451,6 +2451,15 @@ impl State { // Its geometry stage would turn each triangle into a rectangle. once!("a rectangle pipeline drawn with another topology"); } + // The barycentrics stage takes triangles: points, lines and the + // topologies with adjacency do not draw through it. + // shortcut: such a draw is left out (a stage of each input kind would + // draw it; none of them has been seen). + if p.bary && self.topology_set && !matches!(host_topology(self.topology), 4 | 5) { + once!(topology = self.topology, "a draw with the barycentrics stage and no triangles is left out"); + crate::drops::note(Why::BindFailed); + return false; + } if !self.bind(list, p, false) { crate::drops::note(Why::BindFailed); return false; diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index 412c8931ff..28bc746644 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -1191,6 +1191,23 @@ fn create() -> windows::core::Result { let amd = crate::indirect::amd(&device); leonida_shader::emit::set_host_rdna(amd && o1.WaveLaneCountMin == 32 && o1.WaveLaneCountMax == 64); } + // `D3D12-BARYCENTRICS-FALLBACK`: without D3D12 barycentrics (Pascal and older refuse every pixel + // shader that reads them: "Shader uses Barycentrics, but the device does not support this") the + // translator reads the weights and the other vertices' values from inputs a geometry stage of ours + // writes (`leonida_shader::emit::bary_gs`). `LEONIDA_BARY_FALLBACK=1` takes that path on any card. + let mut o3 = D3D12_FEATURE_DATA_D3D12_OPTIONS3::default(); + let barycentrics = device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS3, (&raw mut o3).cast(), size_of_val(&o3) as u32) + .is_ok() + && o3.BarycentricsSupported.as_bool(); + let bary_forced = crate::switch::on("LEONIDA_BARY_FALLBACK"); + leonida_shader::emit::set_host_barycentrics(barycentrics && !bary_forced); + tracing::info!( + barycentrics, + forced = bary_forced, + "pixel shaders read barycentrics through a geometry stage: {}", + !barycentrics || bary_forced + ); // `D3D12-MESH-COMPUTE-FALLBACK`: without mesh shaders at shader model 6.6 (Pascal and older) the // translator writes mesh programs as compute, drawn through a vertex shader of ours // (`pipeline::host::MeshCompute`). `LEONIDA_MESH_COMPUTE=1` takes that path on any card. @@ -1207,20 +1224,12 @@ fn create() -> windows::core::Result { && o7.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0; let forced = std::env::var_os("LEONIDA_MESH_COMPUTE").is_some_and(|v| v == "1"); - leonida_shader::emit::set_host_mesh_shaders(mesh && !forced); - tracing::info!(mesh, forced, "mesh programs run as compute: {}", !mesh || forced); - // `D3D12-BARYCENTRICS-FALLBACK`: without D3D12 barycentrics (Pascal and older refuse every pixel - // shader that reads them: "Shader uses Barycentrics, but the device does not support this") the - // translator reads the weights and the other vertices' values from inputs a geometry stage of ours - // writes (`leonida_shader::emit::bary_gs`). `LEONIDA_BARY_FALLBACK=1` takes that path on any card. - let mut o3 = D3D12_FEATURE_DATA_D3D12_OPTIONS3::default(); - let barycentrics = device - .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS3, (&raw mut o3).cast(), size_of_val(&o3) as u32) - .is_ok() - && o3.BarycentricsSupported.as_bool(); - let forced = crate::switch::on("LEONIDA_BARY_FALLBACK"); - leonida_shader::emit::set_host_barycentrics(barycentrics && !forced); - tracing::info!(barycentrics, forced, "pixel shaders read barycentrics through a geometry stage: {}", !barycentrics || forced); + // With the barycentrics stand-ins (above) a pixel shader behind a mesh program reads inputs that + // only `mesh_vs` writes: a mesh pipeline has no stage after the mesh program to write them, so mesh + // programs run as compute then too. + let stand_ins = !barycentrics || bary_forced; + leonida_shader::emit::set_host_mesh_shaders(mesh && !forced && !stand_ins); + tracing::info!(mesh, forced, stand_ins, "mesh programs run as compute: {}", !mesh || forced || stand_ins); let messages = debug .then(|| device.cast::().ok()) .flatten(); diff --git a/d3d12/crates/leonida-gpu/src/pipeline/host.rs b/d3d12/crates/leonida-gpu/src/pipeline/host.rs index 77a649f00f..80bd764f57 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/host.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/host.rs @@ -611,6 +611,9 @@ pub(crate) struct HostPipeline { /// (`leonida_shader::emit::rect_list_gs`): its rectangle draws go out /// as the title gives them, three vertices a rectangle. pub(crate) rects: bool, + /// Has the barycentrics geometry stage (`leonida_shader::emit::bary_gs`), + /// which takes triangles: lists and strips only. + pub(crate) bary: bool, /// Its shaders, for reports of slow submissions. pub(crate) name: String, /// Its depth, stencil, cull and blend state in short, for the frame @@ -874,6 +877,7 @@ impl HostPipeline { slots: 0, inputs: Vec::new(), rects: false, + bary: false, state: String::new(), mesh_compute: None, }); @@ -931,6 +935,7 @@ impl HostPipeline { slots: 0, inputs: Vec::new(), rects: false, + bary: false, state: String::new(), mesh_compute: None, }); @@ -1086,6 +1091,7 @@ impl HostPipeline { slots: g.slots(), inputs: g.elements(), rects: rect_gs.is_some(), + bary: bary_gs.is_some(), mesh_compute: None, state: { let (d, r, b) = (&g.depth, &g.rasterizer, &g.blend.RenderTarget[0]); diff --git a/d3d12/crates/leonida-shader/src/emit/bary_gs.rs b/d3d12/crates/leonida-shader/src/emit/bary_gs.rs index 4064c85f08..ac4c80a2b1 100644 --- a/d3d12/crates/leonida-shader/src/emit/bary_gs.rs +++ b/d3d12/crates/leonida-shader/src/emit/bary_gs.rs @@ -52,7 +52,28 @@ pub fn needs_bary_gs(ps: &[u8]) -> bool { /// The geometry shader (a DXIL container) for triangles drawn with the /// translated vertex shader `vs` and pixel shader `ps`. pub fn bary_gs(vs: &[u8], ps: &[u8]) -> Result, ShaderError> { - build(signature(vs, FourCC::OSG1)?, &signature(ps, FourCC::ISG1)?) + build(vertex_outputs(vs)?, &signature(ps, FourCC::ISG1)?) +} + +/// The vertex shader's outputs with the interpolation it declares: the +/// default by kind and type, then what its PSV0 lists (the translator takes +/// those from the title's, and a float packed beside an integer can be +/// constant there), so the stage's inputs and outputs carry the vertex +/// shader's modes row for row. +fn vertex_outputs(vs: &[u8]) -> Result, ShaderError> { + let mut outputs = signature(vs, FourCC::OSG1)?; + for e in &mut outputs { + e.interp = match (e.kind, e.comp) { + (3, _) => 4, + (0 | 6 | 7, 9) => 2, + (0, _) => 1, + _ => 0, + }; + } + if let Some(psv) = Container::parse(vs)?.part(FourCC::PSV0) { + super::vertex_output_interpolation(psv.data, &mut outputs)?; + } + Ok(outputs) } /// What an output of the stage carries. @@ -73,15 +94,8 @@ fn build(mut vs_outputs: Vec, ps_inputs: &[SigElement]) -> Result 4, - (0 | 6 | 7, 9) => 2, - (0, _) => 1, - _ => 0, - }; e.usage = (1 << e.cols) - 1; } let ours: Vec<&SigElement> = ps_inputs.iter().filter(|e| stand_in(e)).collect(); @@ -108,8 +122,7 @@ fn build(mut vs_outputs: Vec, ps_inputs: &[SigElement]) -> Result = outputs.iter().chain(ours.iter().copied()).filter_map(|e| e.row).collect(); // (elements that shared a row stay together: old row, new row) let mut rows: Vec<(Option, u32)> = Vec::new(); for id in moved { @@ -117,18 +130,16 @@ fn build(mut vs_outputs: Vec, ps_inputs: &[SigElement]) -> Result new, None => { - rows.push((e.row, free)); - free += 1; - free - 1 + let new = super::lowest_free_row(&mut busy) + .ok_or(unsupported("a barycentrics stage with more than 32 output registers"))?; + rows.push((e.row, new)); + new } }; e.row = Some(row); outputs.push(e); sources.push(Source::Output(id)); } - if free > 32 { - return Err(unsupported("a barycentrics stage with more than 32 output registers")); - } for e in &ours { let source = if e.name == super::BARY_INPUT { Source::Weights @@ -248,3 +259,56 @@ fn load(s: &mut Shader, id: usize, col: u8, vertex: u32) -> V { let entry = s.entry; s.op(entry, name, Attr::ReadNone, ty, 4, &args) } + +#[cfg(test)] +mod tests { + use super::super::container::{Psv, SigElement, psv, signature}; + use crate::dxbc::FourCC; + + fn el(name: &str, kind: u8, comp: u8, row: u32, col: u8, cols: u8, interp: u8) -> SigElement { + SigElement { + name: name.into(), + index: 0, + kind, + comp, + interp, + row: Some(row), + col, + cols, + usage: (1 << cols) - 1, + half: false, + } + } + + /// The stage takes the vertex shader's interpolation from its PSV0: a + /// float the vertex shader declares constant (beside an integer in its + /// row) stays constant, where the default by type would make it linear + /// and the row would mix two modes. + #[test] + fn the_vertex_shaders_interpolation_comes_from_its_psv0() { + let outputs = [ + el("SV_Position", 3, 9, 0, 0, 4, 4), + el("TEXCOORD", 0, 9, 1, 0, 1, 1), + el("TEXCOORD", 0, 5, 1, 1, 1, 1), + el("COLOR", 0, 9, 2, 0, 4, 2), + ]; + let psv0 = psv(&Psv { + stage: 1, + flag: true, + inputs: &[], + outputs: &outputs, + prims: &[], + mesh: None, + geometry: None, + bindings: &[], + threads: [0; 3], + wave_size: None, + }); + let osg1 = signature(&outputs, false); + let vs = crate::dxbc::build(&[(FourCC::OSG1, &osg1), (FourCC::PSV0, &psv0)]); + let modes: Vec<(String, u8, u8)> = + super::vertex_outputs(&vs).unwrap().into_iter().map(|e| (e.name, e.comp, e.interp)).collect(); + let want = [("SV_Position", 9, 4), ("TEXCOORD", 9, 1), ("TEXCOORD", 5, 1), ("COLOR", 9, 2)]; + assert_eq!(modes, want.map(|(n, c, i)| (n.to_owned(), c, i))); + } +} diff --git a/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs b/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs index 48917884df..fd8c802afb 100644 --- a/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs +++ b/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs @@ -136,17 +136,17 @@ fn build( }); sources.push(Source::Out { primitive: true, at }); } - let used = outputs.iter().chain(ours.iter().copied()).filter_map(|e| e.row).max(); - let mut free = used.map_or(0, |r| r + 1); + let mut busy: Vec = outputs.iter().chain(ours.iter().copied()).filter_map(|e| e.row).collect(); let mut rows: Vec<(Option, u32)> = Vec::new(); for id in moved { let mut e = vertex[id].clone(); let row = match rows.iter().find(|(old, _)| *old == e.row) { Some(&(_, new)) => new, None => { - rows.push((e.row, free)); - free += 1; - free - 1 + let new = super::lowest_free_row(&mut busy) + .ok_or(unsupported("a mesh vertex shader with more than 32 output registers"))?; + rows.push((e.row, new)); + new } }; e.row = Some(row); @@ -154,9 +154,6 @@ fn build( outputs.push(e); sources.push(Source::Out { primitive: false, at: layout.vertex_at[id] }); } - if free > 32 { - return Err(unsupported("a mesh vertex shader with more than 32 output registers")); - } for e in &ours { let source = if e.name == super::BARY_INPUT { Source::Weights diff --git a/d3d12/crates/leonida-shader/src/emit/mod.rs b/d3d12/crates/leonida-shader/src/emit/mod.rs index e9832cf3e4..6db1d9da1d 100644 --- a/d3d12/crates/leonida-shader/src/emit/mod.rs +++ b/d3d12/crates/leonida-shader/src/emit/mod.rs @@ -1536,6 +1536,16 @@ fn emit_program_plain( Ok((shader, wave_size)) } +/// The lowest of the 32 output registers not in `busy`, taken (added to +/// it); `None` when all are. A system value our stages move out of the way +/// of the barycentrics stand-ins goes there: below the highest register in +/// use too, where one is free. +fn lowest_free_row(busy: &mut Vec) -> Option { + let row = (0..32).find(|r| !busy.contains(r))?; + busy.push(row); + Some(row) +} + /// The title's vertex output interpolation lives in PSV0. A float packed /// beside an integer can be explicitly constant, as can a float on its own. /// OSG1 supplies the physical rows and columns used to match both tables. @@ -3029,6 +3039,17 @@ mod tests { assert_eq!(lit(cap, cap + 1), 0, "the sink slot (cap {cap}) drew"); } + /// A system value moved out of the stand-ins' way takes the lowest free + /// register, below the highest one in use where one is free. + #[test] + fn moved_outputs_take_the_lowest_free_register() { + let mut busy = vec![0, 1, 3, 31]; + assert_eq!(lowest_free_row(&mut busy), Some(2)); + assert_eq!(lowest_free_row(&mut busy), Some(4)); + let mut full: Vec = (0..32).collect(); + assert_eq!(lowest_free_row(&mut full), None); + } + /// A mesh program's outputs out of register order (the position in a /// row of its own after a parameter, as the 2020 compiler's first entry /// can be) keep each element beside its byte offset: the layout's parts From 8bd30f5b8142dedf58ef10108d1c24d3ff29588c Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sun, 29 Nov 2026 16:28:00 +0200 Subject: [PATCH 11/15] d3d12: rectangles with the barycentrics stand-ins get one geometry stage A rectangle list draw whose pixel shader needs the barycentrics fallback had to pick one geometry shader: the rectangle stage (fourth corner) or the barycentrics stage (weights and per-vertex values). It now gets rect_bary_gs, which completes the rectangle and writes the stand-ins for each of its two triangles, six vertices in one stage. bary_gs is split into layout/values/store so both stages share the signature walk and the stand-in sources. Tests: a portable one (six vertices, every pixel shader input written, no position refused) and, on Windows, the validator and a draw compared with host barycentrics where the device has them. Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/pipeline/host.rs | 44 +++- .../crates/leonida-shader/src/emit/bary_gs.rs | 116 +++++++--- d3d12/crates/leonida-shader/src/emit/mod.rs | 113 +++++++++- d3d12/crates/leonida-shader/src/emit/rect.rs | 212 ++++++++++++++---- 4 files changed, 399 insertions(+), 86 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/pipeline/host.rs b/d3d12/crates/leonida-gpu/src/pipeline/host.rs index 80bd764f57..e8552a533a 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/host.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/host.rs @@ -956,11 +956,12 @@ impl HostPipeline { } // `D3D12-BARYCENTRICS-FALLBACK`: a pixel shader translated for a host // without barycentrics (`leonida_shader::emit::set_host_barycentrics`) - // reads inputs that only the barycentrics geometry stage writes. - // shortcut: a rectangle list then goes without its own stage (the - // two do not combine yet): `draw` completes its rectangles as it does - // when the host refuses that stage. + // reads inputs that only the barycentrics geometry stage writes. A + // rectangle list gets one stage that does both + // (`leonida_shader::emit::rect_bary_gs`), so its indexed and indirect + // rectangles still draw. let mut bary_gs = None; + let mut rect_bary = false; // (A mesh program run as compute draws through `mesh_vs`, which writes // the stand-ins itself: every corner is its own vertex there.) let mesh_vs = stages @@ -972,12 +973,25 @@ impl HostPipeline { && leonida_shader::emit::needs_bary_gs(&ps.host.dxil) { let vs = &stages[0].0.translated()?.host.dxil; - if rect_gs.take().is_some() { - tracing::warn!(?shaders, "a rectangle list without its geometry stage: its pixel shader needs the barycentrics stage"); + if rect_gs.is_some() { + match leonida_shader::emit::rect_bary_gs(vs, &ps.host.dxil) { + Ok(gs) => { + rect_gs = Some(gs); + rect_bary = true; + } + Err(e) => { + // `draw` then completes the rectangles it can (not indexed or + // indirect ones), as when the host refuses the rectangle stage. + tracing::warn!(error = %e, ?shaders, "no rectangle and barycentrics geometry stage"); + rect_gs = None; + } + } } - match leonida_shader::emit::bary_gs(vs, &ps.host.dxil) { - Ok(gs) => bary_gs = Some(gs), - Err(e) => tracing::warn!(error = %e, ?shaders, "no barycentrics geometry stage"), + if !rect_bary { + match leonida_shader::emit::bary_gs(vs, &ps.host.dxil) { + Ok(gs) => bary_gs = Some(gs), + Err(e) => tracing::warn!(error = %e, ?shaders, "no barycentrics geometry stage"), + } } } let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { @@ -1015,6 +1029,12 @@ impl HostPipeline { // A pipeline with the geometry stage has a name of its own in the // library; the others keep theirs. let name = |gs: Option<&Vec>| match gs { + Some(gs) if rect_bary => super::library::name( + "graphics rectangles barycentrics", + &root_blob, + &[&code_bytes(&code(0)), &code_bytes(&code(1)), &gs[..]], + &state, + ), Some(gs) if bary_gs.is_some() => super::library::name( "graphics barycentrics", &root_blob, @@ -1049,7 +1069,9 @@ impl HostPipeline { ) }; let mut made = make(&desc, &name(rect_gs.as_ref().or(bary_gs.as_ref()))); - if made.is_err() && rect_gs.is_some() { + // (Not with the barycentrics in it: without the stage the pixel shader + // reads inputs nothing writes.) + if made.is_err() && rect_gs.is_some() && !rect_bary { // The host refused the geometry stage: once more without it. tracing::warn!(?shaders, "host pipeline refused with the rectangle geometry stage"); host.log_messages(); @@ -1091,7 +1113,7 @@ impl HostPipeline { slots: g.slots(), inputs: g.elements(), rects: rect_gs.is_some(), - bary: bary_gs.is_some(), + bary: bary_gs.is_some() || rect_bary, mesh_compute: None, state: { let (d, r, b) = (&g.depth, &g.rasterizer, &g.blend.RenderTarget[0]); diff --git a/d3d12/crates/leonida-shader/src/emit/bary_gs.rs b/d3d12/crates/leonida-shader/src/emit/bary_gs.rs index ac4c80a2b1..86185165b8 100644 --- a/d3d12/crates/leonida-shader/src/emit/bary_gs.rs +++ b/d3d12/crates/leonida-shader/src/emit/bary_gs.rs @@ -60,7 +60,7 @@ pub fn bary_gs(vs: &[u8], ps: &[u8]) -> Result, ShaderError> { /// those from the title's, and a float packed beside an integer can be /// constant there), so the stage's inputs and outputs carry the vertex /// shader's modes row for row. -fn vertex_outputs(vs: &[u8]) -> Result, ShaderError> { +pub(super) fn vertex_outputs(vs: &[u8]) -> Result, ShaderError> { let mut outputs = signature(vs, FourCC::OSG1)?; for e in &mut outputs { e.interp = match (e.kind, e.comp) { @@ -77,7 +77,7 @@ fn vertex_outputs(vs: &[u8]) -> Result, ShaderError> { } /// What an output of the stage carries. -enum Source { +pub(super) enum Source { /// The vertex shader's output `id`, as it is. Output(usize), /// One of the weights: 1 at vertex `k`'s column, 0 elsewhere. @@ -89,7 +89,21 @@ enum Source { Primitive, } -fn build(mut vs_outputs: Vec, ps_inputs: &[SigElement]) -> Result, ShaderError> { +/// A barycentrics stage's outputs and what each carries, for the vertex +/// shader outputs `vs_outputs` (its inputs) and the pixel shader inputs +/// `ps_inputs`, emitting `vertices` vertices: [`bary_gs`] (one triangle) +/// and [`super::rect::rect_bary_gs`] (a rectangle's two). +pub(super) struct Layout { + pub(super) inputs: Vec, + pub(super) outputs: Vec, + pub(super) sources: Vec, +} + +pub(super) fn layout( + mut vs_outputs: Vec, + ps_inputs: &[SigElement], + vertices: u32, +) -> Result { let unsupported = |what| ShaderError::Unsupported { offset: 0, what }; if vs_outputs.iter().any(|e| e.row.is_none()) { return Err(unsupported("a barycentrics stage behind an output without a register")); @@ -187,15 +201,23 @@ fn build(mut vs_outputs: Vec, ps_inputs: &[SigElement]) -> Result MAX_SCALARS { + if scalars * vertices > MAX_SCALARS { return Err(unsupported( "a barycentrics stage with more output components than a geometry shader emits", )); } + Ok(Layout { + inputs: vs_outputs, + outputs, + sources, + }) +} +fn build(vs_outputs: Vec, ps_inputs: &[SigElement]) -> Result, ShaderError> { + let Layout { inputs, outputs, sources } = layout(vs_outputs, ps_inputs, 3)?; let mut s = Shader::new(false); s.geometry = Some(Geometry { max_vertices: 3 }); - s.inputs = vs_outputs; + s.inputs = inputs; s.outputs = outputs; let b = s.entry; let primitive = sources @@ -205,36 +227,9 @@ fn build(mut vs_outputs: Vec, ps_inputs: &[SigElement]) -> Result = match *source { - Source::Output(id) => (0..cols).map(|col| load(&mut s, id, col, vertex)).collect(), - Source::Weights => (0..u32::from(cols)) - .map(|col| s.m.f32((if col == vertex { 1f32 } else { 0f32 }).to_bits())) - .collect(), - Source::Vertex(input, k) => { - let v = match input { - Some((id, col)) => { - let v = load(&mut s, id, col, k); - let from_float = s.inputs[id].comp == 9; - match (from_float, float) { - (true, false) => s.m.cast(b, Cast::Bitcast, v, s.t.i32), - (false, true) => s.m.cast(b, Cast::Bitcast, v, s.t.f32), - _ => v, - } - } - None if float => s.m.f32(0), - None => s.m.i32(0), - }; - vec![v] - } - Source::Primitive => vec![primitive.expect("the primitive id is read")], - }; - let name = if float { "storeOutput.f32" } else { "storeOutput.i32" }; - for (col, value) in values.into_iter().enumerate() { - let args = [s.m.i32(out as u32), s.m.i32(0), s.m.i8(col as u8), value]; - s.op(b, name, Attr::NoUnwind, s.t.void, 5, &args); - } + let at = |s: &mut Shader, id: usize, col: u8, k: u32| load(s, id, col, k); + let values = values(&mut s, out, source, vertex, primitive, at); + store(&mut s, out, values); } s.op(b, "emitStream", Attr::NoUnwind, s.t.void, 97, &[stream]); } @@ -243,6 +238,57 @@ fn build(mut vs_outputs: Vec, ps_inputs: &[SigElement]) -> Result, + mut at: impl FnMut(&mut Shader, usize, u8, u32) -> V, +) -> Vec { + let b = s.entry; + let float = s.outputs[out].comp == 9; + let cols = s.outputs[out].cols; + match *source { + Source::Output(id) => (0..cols).map(|col| at(s, id, col, local)).collect(), + Source::Weights => (0..u32::from(cols)) + .map(|col| s.m.f32((if col == local { 1f32 } else { 0f32 }).to_bits())) + .collect(), + Source::Vertex(input, k) => { + let v = match input { + Some((id, col)) => { + let v = at(s, id, col, k); + let from_float = s.inputs[id].comp == 9; + match (from_float, float) { + (true, false) => s.m.cast(b, Cast::Bitcast, v, s.t.i32), + (false, true) => s.m.cast(b, Cast::Bitcast, v, s.t.f32), + _ => v, + } + } + None if float => s.m.f32(0), + None => s.m.i32(0), + }; + vec![v] + } + Source::Primitive => vec![primitive.expect("the primitive id is read")], + } +} + +/// Stores `values` (one a column) to output `out` of the vertex being +/// emitted. +pub(super) fn store(s: &mut Shader, out: usize, values: Vec) { + let b = s.entry; + let name = if s.outputs[out].comp == 9 { "storeOutput.f32" } else { "storeOutput.i32" }; + for (col, value) in values.into_iter().enumerate() { + let args = [s.m.i32(out as u32), s.m.i32(0), s.m.i8(col as u8), value]; + s.op(b, name, Attr::NoUnwind, s.t.void, 5, &args); + } +} + /// Column `col` of input `id` at vertex `vertex` of the triangle. fn load(s: &mut Shader, id: usize, col: u8, vertex: u32) -> V { let (name, ty) = if s.inputs[id].comp == 9 { diff --git a/d3d12/crates/leonida-shader/src/emit/mod.rs b/d3d12/crates/leonida-shader/src/emit/mod.rs index 6db1d9da1d..7add87e326 100644 --- a/d3d12/crates/leonida-shader/src/emit/mod.rs +++ b/d3d12/crates/leonida-shader/src/emit/mod.rs @@ -156,7 +156,7 @@ pub fn vertex_source(index: u32) -> (u8, u32, u8) { ((index >> 16) as u8, (index >> 2) & 0x3fff, (index & 3) as u8) } pub use mesh_vs::mesh_vs; -pub use rect::rect_list_gs; +pub use rect::{rect_bary_gs, rect_list_gs}; pub use shader::{ MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, MeshOut, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, MESH_OUT_BYTES, MESH_OUT_HEADER, SLOT_MESH_IN, SLOT_MESH_OUT, SLOT_STRIDES, @@ -4508,6 +4508,117 @@ mod barycentric_tests { } } + /// The stage for a rectangle list whose pixel shader reads the stand-ins + /// is a geometry shader of six vertices that writes every stand-in the + /// pixel shader reads, and the validator, where there is one, takes it. + #[test] + #[cfg(windows)] + fn the_rectangle_barycentrics_stage_is_a_valid_geometry_shader() { + let vs = texcoord_vs(); + for (name, words, ena, _) in barycentric_programs() { + let ps = pixel_without_barycentrics(&words, ena).unwrap(); + let gs = rect_bary_gs(&vs.dxil, &ps.dxil).unwrap_or_else(|e| panic!("{name}: {e}")); + let c = Container::parse(&gs).unwrap(); + // Program version: geometry (2), shader model 6.6. + assert_eq!(c.part(FourCC::DXIL).unwrap().data[..4], [0x66, 0, 2, 0], "{name}"); + let psv = c.part(FourCC::PSV0).unwrap().data; + // Six vertices: the rectangle's two triangles. + assert_eq!(psv[30..32], [6, 0], "{name}"); + let outs = signature(c.part(FourCC::OSG1).unwrap().data).unwrap(); + let (_, ins) = parts(&ps); + for e in ins.iter().filter(|e| e.row.is_some() && e.kind == 0) { + assert!( + outs.iter().any(|o| (&o.name, o.index, o.row, o.col) == (&e.name, e.index, e.row, e.col)), + "{name}: {e:?} is not written" + ); + } + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut gs.clone()).unwrap_or_else(|e| panic!("{name}: {e}")); + } + } + } + + /// A rectangle (three corners of the whole 8x8 target) drawn through the + /// rectangle and barycentrics stage with the stand-ins gives, pixel for + /// pixel, what the host draws through the rectangle stage with its own + /// barycentrics (where it has them to compare with): each of the + /// rectangle's two triangles carries its own weights and its own + /// vertices' values, the fourth vertex's included. + #[test] + #[cfg(windows)] + fn the_rectangle_barycentrics_stage_draws_what_host_barycentrics_draw() { + use super::host::{Draw, Host}; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let vs = texcoord_vs(); + // Top left, bottom left, bottom right: the corner is the second. + let vertices = [ + -1.0, 1.0, 0.5, 1.0, 2.0, 3.0, 0.0, 0.0, -1.0, -1.0, 0.5, 1.0, 6.0, 5.0, 0.0, 0.0, 1.0, + -1.0, 0.5, 1.0, 10.0, 7.0, 0.0, 0.0, + ]; + let mut ran = 0; + for (backend, warp) in [("hardware", false), ("WARP", true)] { + let Ok(host) = Host::new(warp) else { continue }; + let mut options = + windows::Win32::Graphics::Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS3::default(); + // SAFETY: a correctly sized output for the feature query. + unsafe { + host.device + .CheckFeatureSupport( + windows::Win32::Graphics::Direct3D12::D3D12_FEATURE_D3D12_OPTIONS3, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .unwrap(); + } + let native = options.BarycentricsSupported.as_bool(); + for (name, words, ena, _) in barycentric_programs() { + let draw = |ps: &HostShader, gs: &[u8]| { + let root = host.root_signature(&vs, ps).unwrap(); + let pso = host + .pipeline_with_gs(&root, &vs.dxil, Some(gs), &ps.dxil) + .unwrap_or_else(|e| panic!("{backend} {name}: {e}")); + let d = Draw { + roots: Vec::new(), + textures: &[], + samplers: &[], + vertices: &vertices, + stride: 32, + size: (8, 8), + mesh_groups: 0, + vertex_count: 0, + instances: 0, + }; + host.draw(&root, &pso, &d).unwrap() + }; + let ps = pixel_without_barycentrics(&words, ena).unwrap(); + let gs = rect_bary_gs(&vs.dxil, &ps.dxil).unwrap(); + let ours = draw(&ps, &gs); + assert!( + ours.iter().flatten().all(|v| v.is_finite()), + "{backend} {name}: {ours:?}" + ); + if native { + let theirs_ps = pixel(&words, ena).unwrap(); + let theirs_gs = rect_list_gs(&vs.dxil, Some(&theirs_ps.dxil[..])).unwrap(); + let theirs = draw(&theirs_ps, &theirs_gs); + for (n, (a, b)) in ours.iter().zip(&theirs).enumerate() { + assert!( + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4), + "{backend} {name} pixel {n}: stand-ins {a:?}, barycentrics {b:?}" + ); + } + } + } + ran += 1; + eprintln!("the rectangle barycentrics stage draws on {backend} (compared: {native})"); + } + if ran == 0 { + eprintln!("no SM 6.6 host; GPU checks skipped"); + } + } + /// P10 of an attribute the program interpolates is P1 - P0. #[test] fn p10_of_an_interpolated_attribute() { diff --git a/d3d12/crates/leonida-shader/src/emit/rect.rs b/d3d12/crates/leonida-shader/src/emit/rect.rs index 4fab257544..08b691cd31 100644 --- a/d3d12/crates/leonida-shader/src/emit/rect.rs +++ b/d3d12/crates/leonida-shader/src/emit/rect.rs @@ -127,12 +127,58 @@ fn build(mut outputs: Vec, ps_inputs: &[SigElement]) -> Result Vec> { + let b = s.entry; // Every input of the three vertices: [element][column][vertex]. let mut corners: Vec> = Vec::new(); for id in 0..s.inputs.len() { let mut columns = Vec::new(); for col in 0..s.inputs[id].cols { - columns.push([0, 1, 2].map(|vertex| load(&mut s, id, col, vertex))); + columns.push([0, 1, 2].map(|vertex| load(s, id, col, vertex))); } corners.push(columns); } @@ -146,28 +192,28 @@ fn build(mut outputs: Vec, ps_inputs: &[SigElement]) -> Result = Vec::new(); for i in 0..3 { let (a, c) = ((i + 1) % 3, (i + 2) % 3); - let (xa, yc) = (same(&mut s, x[i], x[a]), same(&mut s, y[i], y[c])); - let (xc, ya) = (same(&mut s, x[i], x[c]), same(&mut s, y[i], y[a])); - let (one, other) = (both(&mut s, xa, yc), both(&mut s, xc, ya)); - let shares = either(&mut s, one, other); - let mut here = both(&mut s, shares, plain); + let (xa, yc) = (same(s, x[i], x[a]), same(s, y[i], y[c])); + let (xc, ya) = (same(s, x[i], x[c]), same(s, y[i], y[a])); + let (one, other) = (both(s, xa, yc), both(s, xc, ya)); + let shares = either(s, one, other); + let mut here = both(s, shares, plain); for &found in &corner { - let earlier = not(&mut s, found); - here = both(&mut s, here, earlier); + let earlier = not(s, found); + here = both(s, here, earlier); } corner.push(here); } @@ -203,33 +249,55 @@ fn build(mut outputs: Vec, ps_inputs: &[SigElement]) -> Result Result, ShaderError> { + let unsupported = |what| ShaderError::Unsupported { offset: 0, what }; + let ps_inputs = { + let c = Container::parse(ps)?; + match c.part(FourCC::ISG1) { + Some(part) => super::signature(part.data)?, + None => Vec::new(), + } + }; + let inputs = super::bary_gs::vertex_outputs(vs)?; + let super::bary_gs::Layout { inputs, outputs, sources } = super::bary_gs::layout(inputs, &ps_inputs, VERTICES)?; + let Some(position) = inputs + .iter() + .position(|e| e.kind == 3 && e.comp == 9 && e.cols == 4) + else { + return Err(unsupported("a rectangle list without a four-component position")); + }; + let mut s = Shader::new(false); + s.geometry = Some(Geometry { + max_vertices: VERTICES, + }); + s.inputs = inputs; + s.outputs = outputs; + let b = s.entry; + let emitted = rect_vertices(&mut s, position); // The rectangle's number: the triangle's, three vertices a rectangle. - let mut number = None; - if let Some(id) = primitive { - let n = s.op(b, "primitiveID.i32", Attr::ReadNone, s.t.i32, 108, &[]); - number = Some((id, n)); - } + let primitive = sources + .iter() + .any(|x| matches!(x, super::bary_gs::Source::Primitive)) + .then(|| s.op(b, "primitiveID.i32", Attr::ReadNone, s.t.i32, 108, &[])); let stream = s.m.i8(0); - for vertex in 0..VERTICES as usize { - for (id, columns) in emitted.iter().enumerate() { - let name = if s.outputs[id].comp == 9 { - "storeOutput.f32" - } else { - "storeOutput.i32" - }; - for (col, values) in columns.iter().enumerate() { - let args = [ - s.m.i32(id as u32), - s.m.i32(0), - s.m.i8(col as u8), - values[vertex], - ]; - s.op(b, name, Attr::NoUnwind, s.t.void, 5, &args); - } - } - if let Some((id, n)) = number { - let args = [s.m.i32(id as u32), s.m.i32(0), s.m.i8(0), n]; - s.op(b, "storeOutput.i32", Attr::NoUnwind, s.t.void, 5, &args); + for vertex in 0..VERTICES { + // Vertex `local` of the emitted triangle that starts at `first`. + let (first, local) = (vertex / 3 * 3, vertex % 3); + for (out, source) in sources.iter().enumerate() { + let at = |_: &mut Shader, id: usize, col: u8, k: u32| emitted[id][usize::from(col)][(first + k) as usize]; + let values = super::bary_gs::values(&mut s, out, source, local, primitive, at); + super::bary_gs::store(&mut s, out, values); } s.op(b, "emitStream", Attr::NoUnwind, s.t.void, 97, &[stream]); // The strip ends after the first triangle. @@ -342,6 +410,72 @@ mod tests { } } + /// The rectangle and barycentrics stage (no device needed): six + /// vertices, the vertex shader's outputs register for register, and + /// the stand-ins the pixel shader reads (the weights and vertex 1's and + /// 2's value of TEXCOORD0.x) written; the validator, where there is one, + /// takes it. + #[test] + fn the_rectangle_barycentrics_stage_writes_the_stand_ins() { + use super::super::container::{Psv, psv, signature}; + let mut outputs = outputs(); + for e in &mut outputs { + e.usage = (1 << e.cols) - 1; + e.interp = match (e.kind, e.comp) { + (3, _) => 4, + (0, 9) => 2, + _ => 1, + }; + } + let psv0 = psv(&Psv { + stage: 1, + flag: true, + inputs: &[], + outputs: &outputs, + prims: &[], + mesh: None, + geometry: None, + bindings: &[], + threads: [0; 3], + wave_size: None, + }); + let osg1 = signature(&outputs, false); + let vs = crate::dxbc::build(&[(FourCC::OSG1, &osg1), (FourCC::PSV0, &psv0)]); + // The pixel shader: TEXCOORD0 in row 1, its stand-ins past its inputs. + let mut weights = element(super::super::BARY_INPUT, 0, 0, 9, 3, 3); + weights.interp = 2; + let mut v1 = element(super::super::VERTEX_INPUT, super::super::vertex_index(1, 1, 0), 0, 9, 4, 1); + v1.interp = 1; + let mut v2 = element(super::super::VERTEX_INPUT, super::super::vertex_index(2, 1, 0), 0, 9, 4, 1); + v2.interp = 1; + v2.col = 1; + let ps_inputs = vec![element("TEXCOORD", 0, 0, 9, 1, 4), weights, v1, v2]; + let isg1 = signature(&ps_inputs, true); + let ps = crate::dxbc::build(&[(FourCC::ISG1, &isg1)]); + let gs = rect_bary_gs(&vs, &ps).unwrap(); + let c = Container::parse(&gs).unwrap(); + // Program version: geometry (2), shader model 6.6. + assert_eq!(c.part(FourCC::DXIL).unwrap().data[..4], [0x66, 0, 2, 0]); + // Six vertices: the rectangle's two triangles. + assert_eq!(c.part(FourCC::PSV0).unwrap().data[30..32], [6, 0]); + let outs = super::super::signature(c.part(FourCC::OSG1).unwrap().data).unwrap(); + for e in &ps_inputs { + assert!( + outs.iter().any(|o| (&o.name, o.index, o.row, o.col) == (&e.name, e.index, e.row, e.col)), + "{e:?} is not written" + ); + } + // A position is still needed to complete the rectangle. + let no_position = crate::dxbc::build(&[(FourCC::OSG1, &signature(&outputs[1..], false))]); + assert!(rect_bary_gs(&no_position, &ps).is_err()); + #[cfg(windows)] + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut gs.clone()).unwrap(); + } + } + /// Refused with a reason: no position, a primitive id in a register a /// vertex output has, more components than six vertices may carry. #[test] From 66afbce6290066157f16466e20256a811a20e52d Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sun, 29 Nov 2026 19:30:54 +0200 Subject: [PATCH 12/15] d3d12: triangles with adjacency draw through a barycentrics stage that takes six vertices A pipeline with the barycentrics stage left out every draw of triangle lists or strips with adjacency (the stage takes three vertices). Such a draw now goes out with a variant whose stage, bary_gs_adjacency, takes triangles with adjacency (DXIL input primitive 7) and draws the triangle at 0, 2, 4, as the rasterizer would without a geometry shader. The variant is made at the first such draw, on the same chain as the per-format variants (make::for_adjacency), so barycentrics pipelines are not all made twice. GraphicsState carries the flag into its description (a name of its own in the library) and into the pipeline book (bit 1 of the depth bounds byte; books written before read as without), so the next run makes it ahead of time. Geometry and PSV0 take the input primitive instead of a fixed 3. Points and lines with the stage are still left out. Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/draw.rs | 30 +++++++-- d3d12/crates/leonida-gpu/src/pipeline.rs | 12 ++++ d3d12/crates/leonida-gpu/src/pipeline/host.rs | 32 +++++++++- .../crates/leonida-gpu/src/pipeline/known.rs | 14 ++++- d3d12/crates/leonida-gpu/src/pipeline/make.rs | 61 +++++++++++++++---- .../crates/leonida-shader/src/emit/bary_gs.rs | 61 +++++++++++++++++-- .../leonida-shader/src/emit/container.rs | 14 ++--- d3d12/crates/leonida-shader/src/emit/mod.rs | 2 +- d3d12/crates/leonida-shader/src/emit/rect.rs | 2 + .../crates/leonida-shader/src/emit/shader.rs | 21 +++++-- 10 files changed, 207 insertions(+), 42 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index b24da23eeb..84cb7f4008 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs @@ -2439,10 +2439,21 @@ impl State { crate::drops::note(Why::SkipList); return false; } - let Some(p) = crate::pipeline::host_pipeline_for(self.pipeline as This, &self.target_formats) else { + let Some(mut p) = crate::pipeline::host_pipeline_for(self.pipeline as This, &self.target_formats) else { crate::drops::note(crate::pipeline::why_gone(self.pipeline as This)); return false; }; + // The barycentrics stage takes three vertices; a draw of triangles + // with adjacency goes out with the variant whose stage takes six. + if p.bary && self.topology_set && matches!(self.topology, TRIANGLE_LIST_ADJACENCY | TRIANGLE_STRIP_ADJACENCY) { + let Some(adjacency) = + crate::pipeline::host_pipeline_adjacency(self.pipeline as This, &self.target_formats) + else { + crate::drops::note(Why::NotMade); + return false; + }; + p = adjacency; + } if p.compute || p.mesh != mesh { once!(mesh, "a draw or mesh dispatch with another kind of pipeline"); return false; @@ -2451,11 +2462,16 @@ impl State { // Its geometry stage would turn each triangle into a rectangle. once!("a rectangle pipeline drawn with another topology"); } - // The barycentrics stage takes triangles: points, lines and the - // topologies with adjacency do not draw through it. - // shortcut: such a draw is left out (a stage of each input kind would - // draw it; none of them has been seen). - if p.bary && self.topology_set && !matches!(host_topology(self.topology), 4 | 5) { + // The barycentrics stage takes triangles (with adjacency in its + // variant above): points and lines do not draw through it. + // shortcut: such a draw is left out (a stage that turns them into + // triangles would draw it; none has been seen). + let triangles = if p.adjacency { + matches!(self.topology, TRIANGLE_LIST_ADJACENCY | TRIANGLE_STRIP_ADJACENCY) + } else { + matches!(host_topology(self.topology), 4 | 5) + }; + if p.bary && self.topology_set && !triangles { once!(topology = self.topology, "a draw with the barycentrics stage and no triangles is left out"); crate::drops::note(Why::BindFailed); return false; @@ -6960,6 +6976,8 @@ fn describe(view: Option<&View>) -> String { /// The console's own primitive topologies. const TRIANGLE_FAN: u32 = 6; +const TRIANGLE_LIST_ADJACENCY: u32 = 12; +const TRIANGLE_STRIP_ADJACENCY: u32 = 13; const RECTANGLES: u32 = 17; const LINE_LOOP: u32 = 18; const QUADS: u32 = 19; diff --git a/d3d12/crates/leonida-gpu/src/pipeline.rs b/d3d12/crates/leonida-gpu/src/pipeline.rs index fbf2a5c58d..4dc04f79eb 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline.rs @@ -778,6 +778,18 @@ pub(crate) fn host_pipeline_for<'a>(this: This, bound: &host::TargetFormats) -> make::ready(p) } +/// As [`host_pipeline_for`], for a draw of triangles with adjacency with a +/// pipeline whose barycentrics stage takes triangles: the variant whose +/// stage takes six vertices ([`make::for_adjacency`]); `None` while it is +/// being made or if it cannot be. +#[cfg(windows)] +pub(crate) fn host_pipeline_adjacency<'a>(this: This, bound: &host::TargetFormats) -> Option<&'a host::HostPipeline> { + if this.is_null() { + return None; + } + make::for_adjacency(&pipeline(this).host, bound) +} + /// Why the title pipeline `this` has no host pipeline now, for the drop /// counters (`crate::drops`): on a skip list, not made yet, or refused. #[cfg(windows)] diff --git a/d3d12/crates/leonida-gpu/src/pipeline/host.rs b/d3d12/crates/leonida-gpu/src/pipeline/host.rs index e8552a533a..7b4ad81b25 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/host.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/host.rs @@ -33,6 +33,10 @@ pub(crate) struct GraphicsState { pub(crate) targets: D3D12_RT_FORMAT_ARRAY, pub(super) depth_format: DXGI_FORMAT, pub(super) samples: DXGI_SAMPLE_DESC, + /// Made for draws of triangles with adjacency: a barycentrics stage + /// takes six vertices (`leonida_shader::emit::bary_gs_adjacency`). + /// Only set on a variant made at such a draw ([`Self::with_adjacency`]). + pub(crate) adjacency: bool, } impl Default for GraphicsState { @@ -87,6 +91,7 @@ impl Default for GraphicsState { Count: 1, Quality: 0, }, + adjacency: false, } } } @@ -319,6 +324,17 @@ impl GraphicsState { targets, depth_format: self.depth_format, samples: self.samples, + adjacency: self.adjacency, + } + } + + /// The same state for draws of triangles with adjacency (in the formats + /// it declares): its barycentrics stage takes six vertices. Its + /// description differs, so it has a name of its own in the library. + pub(crate) fn with_adjacency(&self, formats: &TargetFormats) -> GraphicsState { + GraphicsState { + adjacency: true, + ..self.with_formats(formats) } } } @@ -447,7 +463,7 @@ impl GraphicsState { self.targets, self.depth_format.0, self.samples - ) + ) + if self.adjacency { " adjacency" } else { "" } } fn depth1(&self) -> D3D12_DEPTH_STENCIL_DESC1 { @@ -614,6 +630,10 @@ pub(crate) struct HostPipeline { /// Has the barycentrics geometry stage (`leonida_shader::emit::bary_gs`), /// which takes triangles: lists and strips only. pub(crate) bary: bool, + /// Its barycentrics stage takes triangles with adjacency instead + /// (`leonida_shader::emit::bary_gs_adjacency`): list and strip + /// with adjacency only. + pub(crate) adjacency: bool, /// Its shaders, for reports of slow submissions. pub(crate) name: String, /// Its depth, stencil, cull and blend state in short, for the frame @@ -878,6 +898,7 @@ impl HostPipeline { inputs: Vec::new(), rects: false, bary: false, + adjacency: false, state: String::new(), mesh_compute: None, }); @@ -936,6 +957,7 @@ impl HostPipeline { inputs: Vec::new(), rects: false, bary: false, + adjacency: false, state: String::new(), mesh_compute: None, }); @@ -988,7 +1010,12 @@ impl HostPipeline { } } if !rect_bary { - match leonida_shader::emit::bary_gs(vs, &ps.host.dxil) { + let made = if g.adjacency { + leonida_shader::emit::bary_gs_adjacency(vs, &ps.host.dxil) + } else { + leonida_shader::emit::bary_gs(vs, &ps.host.dxil) + }; + match made { Ok(gs) => bary_gs = Some(gs), Err(e) => tracing::warn!(error = %e, ?shaders, "no barycentrics geometry stage"), } @@ -1114,6 +1141,7 @@ impl HostPipeline { inputs: g.elements(), rects: rect_gs.is_some(), bary: bary_gs.is_some() || rect_bary, + adjacency: bary_gs.is_some() && g.adjacency, mesh_compute: None, state: { let (d, r, b) = (&g.depth, &g.rasterizer, &g.blend.RenderTarget[0]); diff --git a/d3d12/crates/leonida-gpu/src/pipeline/known.rs b/d3d12/crates/leonida-gpu/src/pipeline/known.rs index e7c8558a34..7692bfa6ab 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/known.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/known.rs @@ -326,7 +326,9 @@ macro_rules! numbers { impl GraphicsState { /// The state as bytes. fn put(&self, out: &mut Vec) { - out.push(u8::from(self.depth_bounds)); + // Bit 0: depth bounds; bit 1: made for triangles with adjacency + // (books written before it read as without). + out.push(u8::from(self.depth_bounds) | u8::from(self.adjacency) << 1); for f in [self.rasterizer.DepthBiasClamp, self.rasterizer.SlopeScaledDepthBias] { out.extend(f.to_le_bytes()); } @@ -369,7 +371,8 @@ impl GraphicsState { fn get(bytes: &[u8]) -> Option { let mut g = GraphicsState::default(); let (&bounds, mut rest) = bytes.split_first()?; - g.depth_bounds = bounds != 0; + g.depth_bounds = bounds & 1 != 0; + g.adjacency = bounds & 2 != 0; let mut next = || { let (head, after) = rest.split_first_chunk::<4>()?; rest = after; @@ -421,7 +424,12 @@ mod tests { #[test] fn a_state_comes_back_as_it_was() { - let mut g = GraphicsState { sample_mask: 7, depth_bounds: true, ..Default::default() }; + let mut g = GraphicsState { + sample_mask: 7, + depth_bounds: true, + adjacency: true, + ..Default::default() + }; g.rasterizer.DepthBias = -3; g.rasterizer.SlopeScaledDepthBias = 1.25; g.blend.RenderTarget[3].RenderTargetWriteMask = 5; diff --git a/d3d12/crates/leonida-gpu/src/pipeline/make.rs b/d3d12/crates/leonida-gpu/src/pipeline/make.rs index b5626b09a7..2f50c884d1 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/make.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/make.rs @@ -55,6 +55,8 @@ pub(crate) struct Pending { /// without a graphics state), and the same shaders and state for other /// formats bound at a draw ([`for_formats`]): a chain, one link per set. pub(crate) formats: TargetFormats, + /// Made for draws of triangles with adjacency ([`for_adjacency`]). + adjacency: bool, variant: OnceLock>, } @@ -169,6 +171,7 @@ impl Pending { scene_input, left_out, formats: graphics.as_ref().map_or([0; 9], |g| g.formats()), + adjacency: graphics.as_ref().is_some_and(|g| g.adjacency), variant: OnceLock::new(), shaders, graphics, @@ -334,28 +337,60 @@ fn variants_on() -> bool { #[cold] pub(crate) fn for_formats<'a>(p: &'a Arc, bound: &TargetFormats) -> Option<&'a HostPipeline> { match p.graphics.as_deref() { - Some(g) if variants_on() => ready(variant(p, g, &super::host::formats_for(&p.formats, bound))), + Some(g) if variants_on() => ready(variant(p, g, &super::host::formats_for(&p.formats, bound), false)), _ => ready(p), } } -/// The pipeline of `p`'s shaders and state `g` for the formats `bound`: -/// found in the chain from `p`, or added to it (logged once per set). -fn variant<'a>(p: &'a Arc, g: &GraphicsState, bound: &TargetFormats) -> &'a Arc { +/// The host pipeline for a draw of triangles with adjacency with `p`, whose +/// barycentrics stage takes triangles ([`HostPipeline::bary`]): that of the +/// same shaders and state with a stage that takes six vertices, made at the +/// first such draw (a title draws few, so not every barycentrics pipeline +/// is made twice), in the formats a draw into `bound` takes. +#[cold] +pub(crate) fn for_adjacency<'a>(p: &'a Arc, bound: &TargetFormats) -> Option<&'a HostPipeline> { + let g = p.graphics.as_deref()?; + let formats = if variants_on() && super::host::formats_differ(&p.formats, bound) { + super::host::formats_for(&p.formats, bound) + } else { + p.formats + }; + let v = variant(p, g, &formats, true); + if !v.adjacency { + return None; + } + ready(v) +} + +/// The pipeline of `p`'s shaders and state `g` for the formats `bound`, for +/// draws of triangles with adjacency or not: found in the chain from `p`, +/// or added to it (logged once per set). +fn variant<'a>(p: &'a Arc, g: &GraphicsState, bound: &TargetFormats, adjacency: bool) -> &'a Arc { let mut at = p; for _ in 0..64 { let next = at.variant.get_or_init(|| { let so_far = VARIANTS.fetch_add(1, Ordering::Relaxed) + 1; - tracing::info!( - pipeline = %hashes(p), - declared = ?p.formats, - bound = ?bound, - so_far, - "a pipeline is made again for the render target formats bound at its draw (LEONIDA_TARGET_VARIANTS=0: the draw goes out with the title's pipeline)" - ); - Arc::new(Pending::new(p.shaders.clone(), Some(Box::new(g.with_formats(bound))))) + let state = if adjacency { + tracing::info!( + pipeline = %hashes(p), + bound = ?bound, + so_far, + "a pipeline is made again for triangles with adjacency (its barycentrics stage takes six vertices)" + ); + g.with_adjacency(bound) + } else { + tracing::info!( + pipeline = %hashes(p), + declared = ?p.formats, + bound = ?bound, + so_far, + "a pipeline is made again for the render target formats bound at its draw (LEONIDA_TARGET_VARIANTS=0: the draw goes out with the title's pipeline)" + ); + g.with_formats(bound) + }; + Arc::new(Pending::new(p.shaders.clone(), Some(Box::new(state)))) }); - if next.formats == *bound { + if next.formats == *bound && next.adjacency == adjacency { return next; } at = next; diff --git a/d3d12/crates/leonida-shader/src/emit/bary_gs.rs b/d3d12/crates/leonida-shader/src/emit/bary_gs.rs index 86185165b8..c45fb36690 100644 --- a/d3d12/crates/leonida-shader/src/emit/bary_gs.rs +++ b/d3d12/crates/leonida-shader/src/emit/bary_gs.rs @@ -52,7 +52,15 @@ pub fn needs_bary_gs(ps: &[u8]) -> bool { /// The geometry shader (a DXIL container) for triangles drawn with the /// translated vertex shader `vs` and pixel shader `ps`. pub fn bary_gs(vs: &[u8], ps: &[u8]) -> Result, ShaderError> { - build(vertex_outputs(vs)?, &signature(ps, FourCC::ISG1)?) + build(vertex_outputs(vs)?, &signature(ps, FourCC::ISG1)?, false) +} + +/// [`bary_gs`] for triangle lists and strips with adjacency: the stage takes +/// six vertices and draws the triangle at 0, 2 and 4 (the adjacent vertices +/// are only there for a geometry shader to read, and the rasterizer draws +/// the same triangle without one). +pub fn bary_gs_adjacency(vs: &[u8], ps: &[u8]) -> Result, ShaderError> { + build(vertex_outputs(vs)?, &signature(ps, FourCC::ISG1)?, true) } /// The vertex shader's outputs with the interpolation it declares: the @@ -213,10 +221,19 @@ pub(super) fn layout( }) } -fn build(vs_outputs: Vec, ps_inputs: &[SigElement]) -> Result, ShaderError> { +fn build( + vs_outputs: Vec, + ps_inputs: &[SigElement], + adjacency: bool, +) -> Result, ShaderError> { let Layout { inputs, outputs, sources } = layout(vs_outputs, ps_inputs, 3)?; let mut s = Shader::new(false); - s.geometry = Some(Geometry { max_vertices: 3 }); + let (input, step) = if adjacency { + (Geometry::TRIANGLES_ADJACENCY, 2) + } else { + (Geometry::TRIANGLES, 1) + }; + s.geometry = Some(Geometry { input, max_vertices: 3 }); s.inputs = inputs; s.outputs = outputs; let b = s.entry; @@ -227,7 +244,7 @@ fn build(vs_outputs: Vec, ps_inputs: &[SigElement]) -> Result { pub prims: &'a [SigElement], /// Mesh: its state and the group-shared bytes it declares. pub mesh: Option<(super::shader::Mesh, u32)>, - /// Geometry (triangles in, triangle strips out on stream 0): its - /// maximum vertex count. `flag`: writes `SV_Position`. - pub geometry: Option, + /// Geometry (triangle strips out on stream 0): its DXIL input primitive + /// and maximum vertex count. `flag`: writes `SV_Position`. + pub geometry: Option<(u32, u32)>, pub bindings: &'a [Binding], /// Compute: thread-group size and required wave size. pub threads: [u32; 3], @@ -224,10 +224,10 @@ pub(crate) fn psv(p: &Psv) -> Vec { info[27] = mesh.topology; info[30] = p.prims.len() as u8; } - if let Some(max_vertices) = p.geometry { - // Input primitive (3: triangles), output topology (5: triangle - // strips), stream mask, position written; the vertex maximum. - info[0..4].copy_from_slice(&3u32.to_le_bytes()); + if let Some((input, max_vertices)) = p.geometry { + // Input primitive, output topology (5: triangle strips), stream + // mask, position written; the vertex maximum. + info[0..4].copy_from_slice(&input.to_le_bytes()); info[4..8].copy_from_slice(&5u32.to_le_bytes()); info[8..12].copy_from_slice(&1u32.to_le_bytes()); info[12] = u8::from(p.flag); diff --git a/d3d12/crates/leonida-shader/src/emit/mod.rs b/d3d12/crates/leonida-shader/src/emit/mod.rs index 7add87e326..15f679d671 100644 --- a/d3d12/crates/leonida-shader/src/emit/mod.rs +++ b/d3d12/crates/leonida-shader/src/emit/mod.rs @@ -129,7 +129,7 @@ use crate::{ShaderError, io, ir, resource, structure}; pub use bitcode::census; pub use sampler::StaticSampler; -pub use bary_gs::{bary_gs, needs_bary_gs}; +pub use bary_gs::{bary_gs, bary_gs_adjacency, needs_bary_gs}; pub use lower::{ host_barycentrics, host_settings, mesh_as_compute, set_host_barycentrics, set_host_max_wave, set_host_mesh_shaders, set_host_rdna, take_pack_why, diff --git a/d3d12/crates/leonida-shader/src/emit/rect.rs b/d3d12/crates/leonida-shader/src/emit/rect.rs index 08b691cd31..c7f91e733d 100644 --- a/d3d12/crates/leonida-shader/src/emit/rect.rs +++ b/d3d12/crates/leonida-shader/src/emit/rect.rs @@ -89,6 +89,7 @@ fn build(mut outputs: Vec, ps_inputs: &[SigElement]) -> Result Result, ShaderError> { }; let mut s = Shader::new(false); s.geometry = Some(Geometry { + input: Geometry::TRIANGLES, max_vertices: VERTICES, }); s.inputs = inputs; diff --git a/d3d12/crates/leonida-shader/src/emit/shader.rs b/d3d12/crates/leonida-shader/src/emit/shader.rs index 9c0d1a30ee..7a500424e3 100644 --- a/d3d12/crates/leonida-shader/src/emit/shader.rs +++ b/d3d12/crates/leonida-shader/src/emit/shader.rs @@ -300,13 +300,22 @@ impl MeshOut { } } -/// What a geometry shader declares: triangles in, triangle strips out on -/// stream 0, one instance. +/// What a geometry shader declares: triangles (with or without adjacency) +/// in, triangle strips out on stream 0, one instance. #[derive(Debug, Clone, Copy)] pub(crate) struct Geometry { + /// DXIL input primitive: 3 triangles, 7 triangles with adjacency. + pub input: u32, pub max_vertices: u32, } +impl Geometry { + /// Triangles in. + pub const TRIANGLES: u32 = 3; + /// Triangles with adjacency in: six vertices, the triangle's at 0, 2, 4. + pub const TRIANGLES_ADJACENCY: u32 = 7; +} + /// The null slot every host view heap keeps at its end (0: no limit). Shaders translated while /// it is set read that slot for any view index at or past it. A read past a heap's end is /// undefined: a host that caps its heap (NVIDIA at 1 000 000 views; a retail game's heap is @@ -1005,10 +1014,10 @@ impl Shader { props.push(self.m.md_value(f)); } if let Some(g) = self.geometry { - // Input primitive (3: triangles), maximum vertices, stream - // mask, output topology (5: triangle strips), instances. + // Input primitive, maximum vertices, stream mask, output + // topology (5: triangle strips), instances. props.push(i32c(&mut self, 1)); - let state = [3, g.max_vertices, 1, 5, 1].map(|n| Some(i32c(&mut self, n))); + let state = [g.input, g.max_vertices, 1, 5, 1].map(|n| Some(i32c(&mut self, n))); props.push(self.m.md_node(state.to_vec())); } if let Some(threads) = self.threads { @@ -1133,7 +1142,7 @@ impl Shader { outputs: &self.outputs, prims: &self.prims, mesh: self.mesh.map(|m| (m, self.lds_dwords * 4)), - geometry: self.geometry.map(|g| g.max_vertices), + geometry: self.geometry.map(|g| (g.input, g.max_vertices)), bindings: &bindings, threads: self.threads.unwrap_or_default(), wave_size: self.wave_size, From eab9c1e0f4b60c1c0fabe3d42d6787a3001bed8b Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sun, 29 Nov 2026 21:10:02 +0200 Subject: [PATCH 13/15] d3d12: the test programs in emit::test_programs, built on every platform The mesh, colour and position programs 924b29417 put in emit::host are needed by portable tests too (primitive_export_indices_drop_the_edge_flags), and emit::host is Windows-only: the Linux test build did not resolve them. They need no device, so they live in emit::test_programs, built for tests and the host feature on every platform. Co-Authored-By: Claude Opus 5.5 --- .../leonida-gpu/src/mesh_fallback/tests.rs | 3 +- d3d12/crates/leonida-shader/src/emit/host.rs | 149 ----------------- d3d12/crates/leonida-shader/src/emit/mod.rs | 10 +- .../leonida-shader/src/emit/test_programs.rs | 157 ++++++++++++++++++ 4 files changed, 165 insertions(+), 154 deletions(-) create mode 100644 d3d12/crates/leonida-shader/src/emit/test_programs.rs diff --git a/d3d12/crates/leonida-gpu/src/mesh_fallback/tests.rs b/d3d12/crates/leonida-gpu/src/mesh_fallback/tests.rs index 3750657cf6..59f40e1c0c 100644 --- a/d3d12/crates/leonida-gpu/src/mesh_fallback/tests.rs +++ b/d3d12/crates/leonida-gpu/src/mesh_fallback/tests.rs @@ -5,7 +5,8 @@ //! each run), and the strip after them draws as a strip. use leonida_shader::HwStage; -use leonida_shader::emit::host::{Host, MESH_CULL, MESH_TRIANGLE, color_ps, position_vs, triangle_mesh_program}; +use leonida_shader::emit::host::Host; +use leonida_shader::emit::test_programs::{MESH_CULL, MESH_TRIANGLE, color_ps, position_vs, triangle_mesh_program}; use leonida_shader::emit::{HostShader, MESH_OUT_BYTES, SLOT_MESH_IN, mesh_vs, set_host_mesh_shaders}; use windows::Win32::Foundation::RECT; use windows::Win32::Graphics::Direct3D::*; diff --git a/d3d12/crates/leonida-shader/src/emit/host.rs b/d3d12/crates/leonida-shader/src/emit/host.rs index 47517e71d5..26c3316676 100644 --- a/d3d12/crates/leonida-shader/src/emit/host.rs +++ b/d3d12/crates/leonida-shader/src/emit/host.rs @@ -617,155 +617,6 @@ fn stub(pixel: bool, outputs: Vec) -> HostShader { } } -/// A pixel shader writing the constant colour `rgba` to target 0. -pub fn color_ps(rgba: [f32; 4]) -> HostShader { - use super::bitcode::{Attr, Term}; - let mut s = super::shader::Shader::new(true); - s.outputs.push(SigElement { - name: "SV_Target".into(), - index: 0, - kind: 16, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 15, - half: false, - }); - let b = s.entry; - for (c, v) in rgba.into_iter().enumerate() { - let args = [s.m.i32(0), s.m.i32(0), s.m.i8(c as u8), s.m.f32(v.to_bits())]; - s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); - } - s.m.terminate(b, Term::Ret); - plain(crate::native::HwStage::Ps, s.finish()) -} - -/// A vertex shader passing its float4 `POSITION` through as `SV_Position`. -pub fn position_vs() -> HostShader { - use super::bitcode::{Attr, Term}; - let mut s = super::shader::Shader::new(false); - let element = |name: &str, kind: u8, interp: u8| SigElement { - name: name.into(), - index: 0, - kind, - comp: 9, - interp, - row: Some(0), - col: 0, - cols: 4, - usage: 15, - half: false, - }; - s.inputs = vec![element("POSITION", 0, 0)]; - s.outputs = vec![element("SV_Position", 3, 4)]; - for col in 0..4 { - let args = [s.m.i32(0), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)]; - let v = s.op(s.entry, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args); - let args = [s.m.i32(0), s.m.i32(0), s.m.i8(col), v]; - s.op(s.entry, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); - } - s.m.terminate(s.entry, Term::Ret); - plain(crate::native::HwStage::Vs, s.finish()) -} - -fn plain(stage: crate::native::HwStage, dxil: Vec) -> HostShader { - HostShader { - stage, - dxil, - user_data: Vec::new(), - samplers: Vec::new(), - static_samplers: Vec::new(), - root_cbvs: Vec::new(), - root_srvs: Vec::new(), - root_uavs: Vec::new(), - root_indexed_views: Vec::new(), - half_views: Vec::new(), - mesh_out: None, - } -} - -/// Triangle (0, 1, 2) as a primitive export: each corner's 9-bit index in -/// its 10-bit field ([`triangle_mesh_program`]). -pub const MESH_TRIANGLE: u32 = 1 << 10 | 2 << 20; -/// The edge flags of the three corners (bits 9, 19 and 29). -pub const MESH_EDGE_FLAGS: u32 = 1 << 9 | 1 << 19 | 1 << 29; -/// The culling bit of a primitive export. -pub const MESH_CULL: u32 = 1 << 31; - -/// A one-wave (32-lane) console mesh program, translated: its lanes all -/// export primitive `prim` and, as vertex `lane`, the position -/// (lane & 1 ? reach - 1 : -1, lane & 2 ? reach - 1 : -1, 0.5, 1), so -/// triangle (0, 1, 2) has its far corners at `reach` - 1 (with `reach` 4 -/// it covers the whole target). Translated as a mesh program or as compute -/// as the translator is set ([`super::set_host_mesh_shaders`]). -pub fn triangle_mesh_program(prim: u32, reach: f32) -> Result { - use crate::native::{HwStage, MeshIo, NativeProgram, StageIo}; - // (the second corner's y comes out as 2 x its lane bit: half of it) - let [x, y] = [reach.to_bits(), (reach / 2.0).to_bits()]; - let words = [ - 0xD765_0001u32, // v_mbcnt_lo_u32_b32 v1, -1, 0 - 0x0001_00C1, - 0x3604_0281, // v_and_b32 v2, 1, v1 - 0x3606_0282, // v_and_b32 v3, 2, v1 - 0x7E04_0D02, // v_cvt_f32_u32 v2, v2 - 0x7E06_0D03, // v_cvt_f32_u32 v3, v3 - 0x1008_04FF, // v_mul_f32 v4, reach, v2 - x, - 0x0608_08F3, // v_add_f32 v4, -1.0, v4 - 0x100A_06FF, // v_mul_f32 v5, reach / 2, v3 - y, - 0x060A_0AF3, // v_add_f32 v5, -1.0, v5 - 0x7E0C_02F0, // v_mov_b32 v6, 0.5 - 0x7E0E_02F2, // v_mov_b32 v7, 1.0 - 0x7E12_02FF, // v_mov_b32 v9, prim - prim, - 0xF800_0941, // exp prim v9, off, off, off done - 0x0000_0009, - 0xF800_08CF, // exp pos0 v4, v5, v6, v7 done - 0x0706_0504, - 0xBF81_0000, // s_endpgm - ]; - let native = NativeProgram { - stage: HwStage::Ms, - wave64: false, - vgprs: 10, - layout: vec![], - used: vec![], - io: StageIo::Ms(MeshIo { - outputs: vec![], - clip_cntl: 0, - threads: 32, - max_vertices: 32, - max_primitives: 32, - topology: 2, - lds_bytes: 0, - }), - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let position = SigElement { - name: "SV_Position".into(), - index: 0, - kind: 3, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 0xF, - half: false, - }; - let osg1 = super::container::signature(&[position], false); - let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); - let c = Container::parse(&bytes)?; - let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs)?; - let st = crate::structure::structure(&p)?; - let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st))?; - let io = crate::io::raise(&p, &native)?; - super::emit(&c, &native, &p, &st, &io, &res) -} - /// A root argument for [`Host::draw`]. #[cfg(test)] pub enum Root { diff --git a/d3d12/crates/leonida-shader/src/emit/mod.rs b/d3d12/crates/leonida-shader/src/emit/mod.rs index 9a0f23a84b..1387a43912 100644 --- a/d3d12/crates/leonida-shader/src/emit/mod.rs +++ b/d3d12/crates/leonida-shader/src/emit/mod.rs @@ -90,6 +90,8 @@ mod diff_tests; mod intersect_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host; +#[cfg(any(test, feature = "host"))] +pub mod test_programs; mod lds_exact; mod lds_flags; mod lds_init; @@ -2466,7 +2468,7 @@ mod tests { /// A pixel shader writing a constant colour. #[cfg(windows)] fn constant_color() -> Vec { - super::host::color_ps([1.0, 0.5, 0.25, 1.0]).dxil + super::test_programs::color_ps([1.0, 0.5, 0.25, 1.0]).dxil } #[test] @@ -2807,17 +2809,17 @@ mod tests { } } - use super::host::{MESH_CULL as CULL, MESH_EDGE_FLAGS as EDGE_FLAGS, MESH_TRIANGLE as TRIANGLE}; + use super::test_programs::{MESH_CULL as CULL, MESH_EDGE_FLAGS as EDGE_FLAGS, MESH_TRIANGLE as TRIANGLE}; /// The triangle mesh program covering the whole target - /// ([`super::host::triangle_mesh_program`]). + /// ([`super::test_programs::triangle_mesh_program`]). fn triangle_mesh(prim: u32) -> Result { triangle_mesh_to(prim, 4.0) } /// The triangle with its far corners at `reach` - 1. fn triangle_mesh_to(prim: u32, reach: f32) -> Result { - super::host::triangle_mesh_program(prim, reach) + super::test_programs::triangle_mesh_program(prim, reach) } /// A primitive export's corners are 9-bit indices: the edge flag above diff --git a/d3d12/crates/leonida-shader/src/emit/test_programs.rs b/d3d12/crates/leonida-shader/src/emit/test_programs.rs new file mode 100644 index 0000000000..8b8e88445b --- /dev/null +++ b/d3d12/crates/leonida-shader/src/emit/test_programs.rs @@ -0,0 +1,157 @@ +//! Programs for checks of the host side without the title (tests here and +//! the `host` feature's users, the runtime's tests): a mesh program whose +//! triangle covers a part of the target as asked, a constant-colour pixel +//! shader and a position pass-through vertex shader. None needs a device. + +use super::HostShader; +use super::container::SigElement; +use crate::dxbc::{Container, FourCC}; + +/// A pixel shader writing the constant colour `rgba` to target 0. +pub fn color_ps(rgba: [f32; 4]) -> HostShader { + use super::bitcode::{Attr, Term}; + let mut s = super::shader::Shader::new(true); + s.outputs.push(SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }); + let b = s.entry; + for (c, v) in rgba.into_iter().enumerate() { + let args = [s.m.i32(0), s.m.i32(0), s.m.i8(c as u8), s.m.f32(v.to_bits())]; + s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + s.m.terminate(b, Term::Ret); + plain(crate::native::HwStage::Ps, s.finish()) +} + +/// A vertex shader passing its float4 `POSITION` through as `SV_Position`. +pub fn position_vs() -> HostShader { + use super::bitcode::{Attr, Term}; + let mut s = super::shader::Shader::new(false); + let element = |name: &str, kind: u8, interp: u8| SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }; + s.inputs = vec![element("POSITION", 0, 0)]; + s.outputs = vec![element("SV_Position", 3, 4)]; + for col in 0..4 { + let args = [s.m.i32(0), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)]; + let v = s.op(s.entry, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args); + let args = [s.m.i32(0), s.m.i32(0), s.m.i8(col), v]; + s.op(s.entry, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + s.m.terminate(s.entry, Term::Ret); + plain(crate::native::HwStage::Vs, s.finish()) +} + +fn plain(stage: crate::native::HwStage, dxil: Vec) -> HostShader { + HostShader { + stage, + dxil, + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + half_views: Vec::new(), + mesh_out: None, + } +} + +/// Triangle (0, 1, 2) as a primitive export: each corner's 9-bit index in +/// its 10-bit field ([`triangle_mesh_program`]). +pub const MESH_TRIANGLE: u32 = 1 << 10 | 2 << 20; +/// The edge flags of the three corners (bits 9, 19 and 29). +pub const MESH_EDGE_FLAGS: u32 = 1 << 9 | 1 << 19 | 1 << 29; +/// The culling bit of a primitive export. +pub const MESH_CULL: u32 = 1 << 31; + +/// A one-wave (32-lane) console mesh program, translated: its lanes all +/// export primitive `prim` and, as vertex `lane`, the position +/// (lane & 1 ? reach - 1 : -1, lane & 2 ? reach - 1 : -1, 0.5, 1), so +/// triangle (0, 1, 2) has its far corners at `reach` - 1 (with `reach` 4 +/// it covers the whole target). Translated as a mesh program or as compute +/// as the translator is set ([`super::set_host_mesh_shaders`]). +pub fn triangle_mesh_program(prim: u32, reach: f32) -> Result { + use crate::native::{HwStage, MeshIo, NativeProgram, StageIo}; + // (the second corner's y comes out as 2 x its lane bit: half of it) + let [x, y] = [reach.to_bits(), (reach / 2.0).to_bits()]; + let words = [ + 0xD765_0001u32, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0x0001_00C1, + 0x3604_0281, // v_and_b32 v2, 1, v1 + 0x3606_0282, // v_and_b32 v3, 2, v1 + 0x7E04_0D02, // v_cvt_f32_u32 v2, v2 + 0x7E06_0D03, // v_cvt_f32_u32 v3, v3 + 0x1008_04FF, // v_mul_f32 v4, reach, v2 + x, + 0x0608_08F3, // v_add_f32 v4, -1.0, v4 + 0x100A_06FF, // v_mul_f32 v5, reach / 2, v3 + y, + 0x060A_0AF3, // v_add_f32 v5, -1.0, v5 + 0x7E0C_02F0, // v_mov_b32 v6, 0.5 + 0x7E0E_02F2, // v_mov_b32 v7, 1.0 + 0x7E12_02FF, // v_mov_b32 v9, prim + prim, + 0xF800_0941, // exp prim v9, off, off, off done + 0x0000_0009, + 0xF800_08CF, // exp pos0 v4, v5, v6, v7 done + 0x0706_0504, + 0xBF81_0000, // s_endpgm + ]; + let native = NativeProgram { + stage: HwStage::Ms, + wave64: false, + vgprs: 10, + layout: vec![], + used: vec![], + io: StageIo::Ms(MeshIo { + outputs: vec![], + clip_cntl: 0, + threads: 32, + max_vertices: 32, + max_primitives: 32, + topology: 2, + lds_bytes: 0, + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let position = SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }; + let osg1 = super::container::signature(&[position], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes)?; + let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let st = crate::structure::structure(&p)?; + let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = crate::io::raise(&p, &native)?; + super::emit(&c, &native, &p, &st, &io, &res) +} From 74ac98c64b6b65ba94e8161738fe8fb76cec7c74 Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sun, 29 Nov 2026 21:42:30 +0200 Subject: [PATCH 14/15] d3d12: the mesh fallback's shaders take main's sample-mask fields Main's Shader gained mask and masked_twins (the sample mask's pixel shader twins); the mesh program seen as compute and its pass-through vertex shader are the title's own forms: no mask, no twins yet. Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/pipeline.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/d3d12/crates/leonida-gpu/src/pipeline.rs b/d3d12/crates/leonida-gpu/src/pipeline.rs index f26fb9986a..5601bc4a83 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline.rs @@ -211,6 +211,8 @@ impl Shader { container: self.container.clone(), ambient: None, translated: OnceLock::new(), + mask: None, + masked_twins: Mutex::new(Vec::new()), }); let ps_dxil = ps.and_then(Shader::translated).map(|t| t.host.dxil.as_slice()); let dxil = match leonida_shader::emit::mesh_vs(&layout, ps_dxil) { @@ -252,6 +254,8 @@ impl Shader { picks: Default::default(), bound: Default::default(), })), + mask: None, + masked_twins: Mutex::new(Vec::new()), }); Some((cs, vs, layout)) } From 1e13fef64cc6dee97a613a7b11d435fba1b05b3f Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sun, 29 Nov 2026 21:42:41 +0200 Subject: [PATCH 15/15] d3d12: main's sample-mask twins in other formats are no adjacency variants masked_for (main) picks a variant of the masked pipeline for the bound formats through variant(), which now also says whether the variant is for triangles with adjacency: these are not. Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/pipeline/make.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/d3d12/crates/leonida-gpu/src/pipeline/make.rs b/d3d12/crates/leonida-gpu/src/pipeline/make.rs index e7dbcdf765..f1cdc731b1 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/make.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/make.rs @@ -410,7 +410,7 @@ fn variant<'a>(p: &'a Arc, g: &GraphicsState, bound: &TargetFormats, ad pub(crate) fn masked_for<'a>(p: &'a Arc, bound: &TargetFormats) -> Option<&'a HostPipeline> { match p.graphics.as_deref() { Some(g) if variants_on() && p.formats != *bound && super::host::formats_differ(&p.formats, bound) => { - made_or_start(variant(p, g, &super::host::formats_for(&p.formats, bound))) + made_or_start(variant(p, g, &super::host::formats_for(&p.formats, bound), false)) } _ => made_or_start(p), }