diff --git a/runtime/d3d12/src/device/compute_table.rs b/runtime/d3d12/src/device/compute_table.rs index a3e99b24..ddeb5b4f 100644 --- a/runtime/d3d12/src/device/compute_table.rs +++ b/runtime/d3d12/src/device/compute_table.rs @@ -73,7 +73,7 @@ fn missing_literal_samplers(shader: &[u8], stage: u32, existing: &[[u32; 13]]) - if private.iter().all(covered) { Vec::new() } else { private } } -fn static_sampler(s: [u32; 13]) -> D3D12_STATIC_SAMPLER_DESC { +pub(super) fn static_sampler(s: [u32; 13]) -> D3D12_STATIC_SAMPLER_DESC { D3D12_STATIC_SAMPLER_DESC { Filter: D3D12_FILTER(s[0] as i32), AddressU: D3D12_TEXTURE_ADDRESS_MODE(s[1] as i32), diff --git a/runtime/d3d12/src/device/mesh_table.rs b/runtime/d3d12/src/device/mesh_table.rs index 52d06652..14b1612b 100644 --- a/runtime/d3d12/src/device/mesh_table.rs +++ b/runtime/d3d12/src/device/mesh_table.rs @@ -17,6 +17,31 @@ pub(super) fn reflected( mesh: &[u8], pixel: Option<&[u8]>, node: u32, +) -> Result>> { + build(device, original, mesh, pixel, node, &[]) +} + +/// The mesh table with `samplers` appended as static samplers of both the host +/// root and the root the pixel stage is translated against. Used when the +/// pixel program builds a literal sampler the title's root leaves out. +pub(super) fn reflected_with_samplers( + device: &ID3D12Device, + original: &RootSource, + mesh: &[u8], + pixel: Option<&[u8]>, + node: u32, + samplers: &[[u32; 13]], +) -> Result>> { + build(device, original, mesh, pixel, node, samplers) +} + +fn build( + device: &ID3D12Device, + original: &RootSource, + mesh: &[u8], + pixel: Option<&[u8]>, + node: u32, + extra: &[[u32; 13]], ) -> Result>> { let Ok(root) = parse_rts0(original.payload()) else { return Ok(None); @@ -37,7 +62,7 @@ pub(super) fn reflected( _ => None, }) .collect(); - if layout.replacements.is_empty() && pixel_tables.is_empty() { + if layout.replacements.is_empty() && pixel_tables.is_empty() && extra.is_empty() { return Ok(None); } let mesh_rewritten: Vec = layout.replacements.keys().copied().collect(); @@ -118,11 +143,39 @@ pub(super) fn reflected( let reader = reader.ok_or(E_POINTER)?; let mut desc = *reader.GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1)?; let source = desc.Anonymous.Desc_1_1; - if source.NumParameters as usize != root.params.len() || source.pParameters.is_null() { + if source.NumParameters as usize != root.params.len() { return Err(E_INVALIDARG.into()); } - let mut params = std::slice::from_raw_parts(source.pParameters, root.params.len()).to_vec(); + let mut params = if root.params.is_empty() { + Vec::new() + } else { + if source.pParameters.is_null() { + return Err(E_INVALIDARG.into()); + } + std::slice::from_raw_parts(source.pParameters, root.params.len()).to_vec() + }; let originals = params.clone(); + // Appended static samplers join the title's own in both roots built + // below. The storage outlives both serializations. + let sampler_storage: Vec = if extra.is_empty() { + Vec::new() + } else { + let mut samplers = if source.NumStaticSamplers == 0 { + Vec::new() + } else { + if source.pStaticSamplers.is_null() { + return Err(E_INVALIDARG.into()); + } + std::slice::from_raw_parts(source.pStaticSamplers, source.NumStaticSamplers as usize) + .to_vec() + }; + samplers.extend(extra.iter().copied().map(super::compute_table::static_sampler)); + samplers + }; + if !sampler_storage.is_empty() { + desc.Anonymous.Desc_1_1.pStaticSamplers = sampler_storage.as_ptr(); + desc.Anonymous.Desc_1_1.NumStaticSamplers = sampler_storage.len() as u32; + } let mut range_storage = vec![Vec::new(); params.len()]; for (index, change) in layout.replacements { let parameter = &mut params[index]; @@ -216,8 +269,9 @@ pub(super) fn reflected( }) }; // The root the pixel program is translated against: the title's, with - // those tables as the program reads them. - let pixel_root = if pixel_storage.is_empty() { + // those tables as the program reads them. Appended samplers alone also + // need a pixel root: the guest root itself has none of them. + let pixel_root = if pixel_storage.is_empty() && sampler_storage.is_empty() { None } else { let mut for_pixel = originals.clone(); diff --git a/runtime/d3d12/src/device/stream.rs b/runtime/d3d12/src/device/stream.rs index 2b2fccf5..4f39cd9d 100644 --- a/runtime/d3d12/src/device/stream.rs +++ b/runtime/d3d12/src/device/stream.rs @@ -259,6 +259,7 @@ unsafe fn create( super::compute_table::capture_stage_root(pixel, root); } let mut rooted = [None, None]; + let mut mesh_pixel_prepared = false; // A mesh pipeline's pixel stage runs under the guest root too (its // parameters are unchanged by the mesh table). Translate it against that // root, as a vertex/pixel pair is, so its constant buffers and views use the @@ -267,12 +268,43 @@ unsafe fn create( // table carries a root that follows the program instead. if let (Some(root), Some((pixel, _)), Some(_)) = (guest_root, original[1], original[7]) && original[0].is_none() - && let Some(variant) = shader_cache::raster_with_root( + { + let variant = shader_cache::raster_with_root( pixel, pipeline.raster_table.as_ref().and_then(|table| table.pixel_root.as_ref()).unwrap_or(root).payload(), + ); + // The shader can already embed the effective root; in that case there + // is no new variant to prepare. + mesh_pixel_prepared = shader_cache::prepared(variant.as_deref().unwrap_or(pixel)).is_some(); + if mesh_pixel_prepared { + rooted[1] = variant; + } + } + // A mesh pipeline's pixel program can build a literal sampler the title's + // root does not hold: the console compiles the state into the program, so + // the root can pair with a program whose words match none of its static + // samplers. The root-less fallback then reads space 32765, which no mesh + // root carries, and the driver rejects the pipeline. Rebuild the mesh + // table with the unmatched states as private static samplers, in the host + // root and in the root the pixel stage is translated against, and keep it + // only when the pixel stage then translates against that root. + if !mesh_pixel_prepared + && let (Some((mesh, _)), Some(root), Some(field)) = (original[7], guest_root, root_record) + && original[2..7].iter().all(Option::is_none) + && original[0].is_none() + && let Some((pixel, _)) = original[1] + && let Ok(signature) = tuxbox_dxbc::rootsig::parse_rts0(root.payload()) + && let Some(unmatched) = tuxbox_dxbc::inline_sampler::unmatched(pixel, 0, &signature) + // A failed speculative root build leaves the original fallback usable. + && let Ok(Some(table)) = super::mesh_table::reflected_with_samplers( + &device.native, root, mesh, Some(pixel), node_mask, &unmatched, ) + && let Some(pixel_root) = &table.pixel_root + && let Some(variant) = shader_cache::raster_with_root(pixel, pixel_root.payload()) && shader_cache::prepared(&variant).is_some() { + unsafe { field.write(table.native.as_raw()) }; + pipeline.raster_table = Some(table); rooted[1] = Some(variant); } if let Some(root) = guest_root && original[0].is_some() && original[1].is_some() diff --git a/runtime/dxbc/src/inline_sampler.rs b/runtime/dxbc/src/inline_sampler.rs index cf7f4426..7af36486 100644 --- a/runtime/dxbc/src/inline_sampler.rs +++ b/runtime/dxbc/src/inline_sampler.rs @@ -498,6 +498,94 @@ fn omitted_states( ) } +/// Each literal sampler state of the program that no static sampler visible to +/// the stage in `root` carries, as private static samplers of space 32765. +/// +/// The console compiles a sampler from constant words into the program, so a +/// title can pair it with a root whose static samplers hold none of its states. +/// The translator keys a sampler by register alone, so the private registers +/// sit above every sampler register the root or the program names: one another +/// space also uses would refuse the translation ("overlaps another space"). +pub fn unmatched(shader: &[u8], stage: u32, root: &crate::rootsig::RootSig) -> Option> { + let d = Dxbc::parse(shader).ok()?; + let chunk = |tag| { + let c = d.chunk(tag)?; + shader.get(c.offset..c.offset + c.size) + }; + let dxil = chunk(b"DXIL")?; + // Samplers indexed from the sampler heap need the guest's actual heap. + if !matches!(stage, 0 | 5) + || word(dxil, 0)? >> 16 != stage + || u64::from_le_bytes(chunk(b"SFI0")?.try_into().ok()?) & (3 << 25) != 0 + { + return None; + } + let programs = xdat::programs(dxil.get(24..)?).ok()?; + let [program] = programs.as_slice() else { return None }; + let resources = crate::mesh_table::shader_resources(shader)?; + let recorded: Vec = + compute_table::records(program)?.filter(|r| r[0] == 0x401).map(|r| r[2]).collect(); + let visibility = if stage == 0 { 5 } else { 0 }; + unmatched_states(&fssm::decode(program).ok()?.isa, root, &resources, &recorded, visibility) +} + +/// The literal states of `isa` that `root` does not carry for `visibility`, +/// placed at the private registers above every sampler register the root, the +/// PSV resource list (`resources`), or the FSSM static-sampler records +/// (`recorded`) names. +fn unmatched_states( + isa: &[u8], + root: &crate::rootsig::RootSig, + resources: &[[u32; 4]], + recorded: &[u32], + visibility: u32, +) -> Option> { + use crate::rootsig::RootParamKind; + // A root that reads the sampler heap directly has no use for static ones. + if root.flags & 0x800 != 0 { + return None; + } + let mut top = root.static_samplers.iter().map(|s| s[10]).fold(0u32, u32::max); + for param in &root.params { + let RootParamKind::Table(ranges) = ¶m.kind else { continue }; + for range in ranges { + if range.range_type == 3 { + // An unbounded sampler table addresses every register above its base. + if range.num == u32::MAX { + return None; + } + let last = range.base_register.checked_add(range.num.checked_sub(1)?)?; + top = top.max(last); + } + } + } + for &[ty, _, low, high] in resources { + if ty == 1 { + top = top.max(low).max(high); + } + } + for ®ister in recorded { + top = top.max(register); + } + let states = literal_sites(isa, visibility)?.descriptors; + let visible = |s: &&[u32; 13]| s[12] == 0 || s[12] == visibility; + let missing: Vec<[u32; 13]> = states + .into_iter() + .filter(|state| !root.static_samplers.iter().filter(visible).any(|s| s[..10] == state[..10])) + .collect(); + if missing.is_empty() { + return None; + } + let mut placed = Vec::with_capacity(missing.len()); + for (index, mut state) in missing.into_iter().enumerate() { + state[10] = top.checked_add(1)?.checked_add(index as u32)?; + state[11] = 32765; + state[12] = visibility; + placed.push(state); + } + Some(placed) +} + #[cfg(test)] #[path = "tests/inline_sampler.rs"] mod tests; diff --git a/runtime/dxbc/src/tests/inline_sampler.rs b/runtime/dxbc/src/tests/inline_sampler.rs index 7d5c3779..5b95ba8d 100644 --- a/runtime/dxbc/src/tests/inline_sampler.rs +++ b/runtime/dxbc/src/tests/inline_sampler.rs @@ -1,3 +1,5 @@ +use crate::rootsig::RootRange; + #[test] fn comparison_sampler_recovers_opaque_white_border_and_less_equal() { // State seen in ProjectScarlett issue #39. No game shader bytes needed. @@ -211,3 +213,162 @@ fn a_static_sampler_the_root_leaves_out_takes_its_declared_register() { elsewhere[10] = 1; assert_eq!(omitted(&[(17, 1), (1, 1)], &[17, 1], &[elsewhere]), None); } + +/// RootSig helper: one optional sampler table plus the given static samplers. +fn unmatched_root( + statics: Vec<[u32; 13]>, + sampler_table: Option, + flags: u32, +) -> crate::rootsig::RootSig { + crate::rootsig::RootSig { + version: 2, + flags, + params: vec![crate::rootsig::RootParam { + visibility: 0, + kind: crate::rootsig::RootParamKind::Table( + sampler_table.into_iter().collect(), + ), + }], + num_static_samplers: statics.len() as u32, + static_samplers: statics, + } +} + +fn isa_of(words: &[u32]) -> Vec { + words.iter().flat_map(|x| x.to_le_bytes()).collect() +} + +// image_sample_c with the comparison state, then image_sample with a linear +// clamped state (the same two sites the omitted test uses). +const TWO_STATES: [u32; 14] = [ + 0xb008_30b6u32, // s_movk_i32 s8 + 0xbe89_03ff, 0x00c0_0000, + 0xbe8a_03ff, 0x1850_0000, + 0xbe8b_03ff, 0x8000_0000, + 0xf0a0_0f08, 0x0040_0a0a, // image_sample_c + 0xb008_0092, // s_movk_i32 s8, clamp + 0xbe8b_0380, // s_mov_b32 s11, 0 + 0xf080_0f08, 0x0040_0a0a, // image_sample + 0xbf81_0000, +]; + +#[test] +fn unmatched_literal_states_take_private_registers_above_every_named_sampler() { + let isa = isa_of(&TWO_STATES); + // The root carries the linear state at s1 space1, has a sampler table + // s4..s5 space0, and the program declares samplers s0..s2 plus s1 in FSSM. + let carried = super::descriptor([0x92, 0xc00000, 0x18500000, 0], 1, 1, 0, false).unwrap(); + let table = RootRange { range_type: 3, num: 2, base_register: 4, space: 0, offset_in_table: 0 }; + let root = unmatched_root(vec![carried], Some(table.clone()), 0); + let found = super::unmatched_states(&isa, &root, &[[1, 0, 0, 2]], &[1], 5).unwrap(); + // Only the comparison state is missing, above all of 1, 4..=5, 0..=2. + assert_eq!(found.len(), 1); + assert_eq!( + found[0], + [0x95, 4, 4, 3, 0, 1, 4, 2, 0, 12.0_f32.to_bits(), 6, 32765, 5] + ); + // The translator binds the placed descriptor to the same literal words. + assert!(super::matches_static( + [0x30b6, 0xc00000, 0x18500000, 0x80000000], + &found[0], + true + )); + // A root that already carries the comparison state has nothing missing. + let mut covered = found[0]; + covered[10] = 1; + covered[11] = 1; + let root = unmatched_root(vec![carried, covered], Some(table), 0); + assert_eq!(super::unmatched_states(&isa, &root, &[[1, 0, 0, 2]], &[1], 5), None); +} + +#[test] +fn unmatched_registers_stay_above_the_programs_own_declared_samplers() { + // One anisotropic wrap site. With plain numbering from 0 the private + // register would collide with a sampler register another space uses. + let isa = isa_of(&[ + 0xb008_0400u32, // s_movk_i32 s8, 0x400 + 0xbe89_03ff, 0x00c0_0000, + 0xbe8a_03ff, 0x18f0_0000, + 0xbe8b_0380, + 0xf080_0f08, 0x0040_0a0a, // image_sample + 0xbf81_0000, + ]); + let other = super::descriptor([0x30b6, 0xc00000, 0x18500000, 0x80000000], 2, 0, 0, true).unwrap(); + let root = unmatched_root(vec![other], None, 0); + // The program declares samplers s0..s20 and names s3 in FSSM. + let found = super::unmatched_states(&isa, &root, &[[1, 0, 0, 20]], &[3], 5).unwrap(); + assert_eq!( + found, + vec![[0x55, 1, 1, 1, 0, 4, 1, 0, 0, 12.0_f32.to_bits(), 21, 32765, 5]] + ); + assert!(super::matches_static([0x400, 0xc00000, 0x18f00000, 0], &found[0], false)); +} + +#[test] +fn unmatched_ignores_samplers_visible_only_to_another_stage() { + let isa = isa_of(&TWO_STATES); + let linear = super::descriptor([0x92, 0xc00000, 0x18500000, 0], 3, 0, 1, false).unwrap(); + let root = unmatched_root(vec![linear], None, 0); + // A vertex-visible sampler does not cover the pixel stage's state. + let found = super::unmatched_states(&isa, &root, &[[1, 0, 3, 3]], &[3], 5).unwrap(); + assert_eq!(found.len(), 2); + assert!(found.iter().all(|s| (s[11], s[12]) == (32765, 5))); + assert!(found.iter().all(|s| s[10] > 3)); + // All-visible or pixel-visible does. + for visibility in [0, 5] { + let mut covered = linear; + covered[12] = visibility; + let root = unmatched_root(vec![covered], None, 0); + let found = super::unmatched_states(&isa, &root, &[[1, 0, 3, 3]], &[3], 5).unwrap(); + assert_eq!(found.len(), 1); + assert_eq!(found[0][0], 0x95); + } +} + +#[test] +fn unmatched_fails_closed_on_heap_indexed_roots_and_unbounded_sampler_tables() { + let isa = isa_of(&TWO_STATES); + let carried = super::descriptor([0x92, 0xc00000, 0x18500000, 0], 1, 1, 0, false).unwrap(); + // A root that reads the sampler heap directly. + let root = unmatched_root(vec![carried], None, 0x800); + assert_eq!(super::unmatched_states(&isa, &root, &[], &[], 5), None); + // An unbounded sampler table addresses every register above its base. + let open = RootRange { range_type: 3, num: u32::MAX, base_register: 4, space: 0, offset_in_table: 0 }; + let root = unmatched_root(vec![carried], Some(open), 0); + assert_eq!(super::unmatched_states(&isa, &root, &[], &[], 5), None); + // A program without literal sites has nothing missing. + let empty = isa_of(&[0xbf81_0000]); + let root = unmatched_root(vec![carried], None, 0); + assert_eq!(super::unmatched_states(&empty, &root, &[], &[], 5), None); +} + +#[test] +fn unmatched_rejects_invalid_or_exhausted_sampler_register_ranges() { + let isa = isa_of(&TWO_STATES); + for (base_register, num) in [(4, 0), (u32::MAX, 1), (u32::MAX, 2), (u32::MAX - 1, 1)] { + let range = RootRange { range_type: 3, num, base_register, space: 0, offset_in_table: 0 }; + let root = unmatched_root(Vec::new(), Some(range), 0); + assert_eq!(super::unmatched_states(&isa, &root, &[], &[], 5), None); + } +} + +#[test] +fn unmatched_places_each_missing_state_on_its_own_private_register() { + let isa = isa_of(&TWO_STATES); + // No static samplers at all: both literal states are missing, placed above + // the declared s0..s2 and the FSSM-named s1, s17, in unique-state order. + let root = unmatched_root(Vec::new(), None, 0); + let found = super::unmatched_states(&isa, &root, &[[1, 0, 0, 2]], &[1, 17], 5).unwrap(); + assert_eq!(found.len(), 2); + let mut by_register: Vec<_> = found.iter().map(|s| (s[10], s[0])).collect(); + by_register.sort_unstable(); + assert_eq!(by_register, [(18, 0x15), (19, 0x95)]); + // A compute stage sees all-visible samplers only and places visibility 0. + let root = unmatched_root(Vec::new(), None, 0); + let found = super::unmatched_states(&isa, &root, &[[1, 0, 0, 2]], &[1, 17], 0).unwrap(); + assert!(found.iter().all(|s| (s[11], s[12]) == (32765, 0))); + let pixel_only = super::descriptor([0x92, 0xc00000, 0x18500000, 0], 1, 0, 5, false).unwrap(); + let root = unmatched_root(vec![pixel_only], None, 0); + let found = super::unmatched_states(&isa, &root, &[[1, 0, 0, 2]], &[1, 17], 0).unwrap(); + assert_eq!(found.len(), 2); +}