diff --git a/crates/xcl/src/config.rs b/crates/xcl/src/config.rs index 40fbf80..21e9083 100644 --- a/crates/xcl/src/config.rs +++ b/crates/xcl/src/config.rs @@ -49,6 +49,10 @@ pub struct Config { pub d3d12_debug: bool, /// "auto" (show the title's frames in an XCL window) or "off". pub present: String, + /// Raytracing tier reported by `CheckFeatureSupport(D3D12_OPTIONS5)`: + /// "auto" (host GPU tier), "tier1_1" (11), "tier1_0" (10), or "off" (0). + /// `XCL_RAYTRACING` overrides. + pub raytracing: String, pub window_width: u32, pub window_height: u32, } @@ -131,6 +135,7 @@ impl Default for Config { d3d12_adapter: "auto".into(), d3d12_debug: false, present: "auto".into(), + raytracing: "auto".into(), window_width: 1280, window_height: 720, } @@ -169,6 +174,27 @@ impl Config { pub fn is_series_s(&self) -> bool { self.device_type.eq_ignore_ascii_case("lockhart") || self.device_type.eq_ignore_ascii_case("series s") } + + /// Configured `D3D12_RAYTRACING_TIER` override for `CheckFeatureSupport(D3D12_OPTIONS5)`: + /// `None` keeps the host GPU tier ("auto"), `Some(0 / 10 / 11)` forces NOT_SUPPORTED / + /// TIER_1_0 / TIER_1_1. `XCL_RAYTRACING` overrides `xcl.toml`. + pub fn raytracing_tier_override(&self) -> Option { + let env = std::env::var("XCL_RAYTRACING").ok(); + let mode = env.as_deref().unwrap_or(self.raytracing.as_str()).trim(); + parse_raytracing_tier(mode) + } +} + +pub fn parse_raytracing_tier(mode: &str) -> Option { + if mode.eq_ignore_ascii_case("off") || mode.eq_ignore_ascii_case("none") || mode == "0" { + Some(0) + } else if mode.eq_ignore_ascii_case("tier1_0") || mode.eq_ignore_ascii_case("1.0") || mode == "10" { + Some(10) + } else if mode.eq_ignore_ascii_case("tier1_1") || mode.eq_ignore_ascii_case("1.1") || mode == "11" { + Some(11) + } else { + None + } } /// Everything the host process needs; written by the launcher as JSON. @@ -215,5 +241,21 @@ mod tests { let c: Config = toml::from_str("device_type = \"lockhart\"\n").unwrap(); assert!(c.is_series_s()); assert_eq!(c.gamertag, "Player1"); + assert_eq!(c.raytracing, "auto"); + } + + #[test] + fn raytracing_tier_parsing() { + assert_eq!(parse_raytracing_tier("auto"), None); + assert_eq!(parse_raytracing_tier(""), None); + assert_eq!(parse_raytracing_tier("off"), Some(0)); + assert_eq!(parse_raytracing_tier("none"), Some(0)); + assert_eq!(parse_raytracing_tier("0"), Some(0)); + assert_eq!(parse_raytracing_tier("tier1_0"), Some(10)); + assert_eq!(parse_raytracing_tier("1.0"), Some(10)); + assert_eq!(parse_raytracing_tier("10"), Some(10)); + assert_eq!(parse_raytracing_tier("tier1_1"), Some(11)); + assert_eq!(parse_raytracing_tier("1.1"), Some(11)); + assert_eq!(parse_raytracing_tier("11"), Some(11)); } } diff --git a/crates/xcl/src/gpu/bvh.rs b/crates/xcl/src/gpu/bvh.rs index 7fb02d8..6a7f8a4 100644 --- a/crates/xcl/src/gpu/bvh.rs +++ b/crates/xcl/src/gpu/bvh.rs @@ -65,6 +65,22 @@ pub struct Instance { pub blas_bounds: Aabb, } +/// Worst-case console acceleration structure size (bytes) matching `XboxBvhBuilder.dll`'s +/// `GetRaytracingAccelerationStructurePrebuildInfo`: 256-byte header, `leaf_count` leaves +/// (64 B triangles for BLAS, 128 B instances for TLAS), `max(leaf_count, 2) - 1` box32 nodes +/// (128 B), plus 4 bytes of parent pointers per 64 bytes of nodes, rounded up to 1 KiB. +pub fn prebuild_size(leaf_count: u64, top_level: bool) -> u64 { + let leaf = if top_level { INSTANCE_BYTES as u64 } else { TRI_BYTES as u64 }; + let nodes = leaf_count * leaf + (leaf_count.max(2) - 1) * BOX_BYTES as u64; + (HEADER_BYTES as u64 + nodes + nodes / 64 * 4).div_ceil(1024) * 1024 +} + +/// Whether a console BVH header has bit 24 ("compressed / dehydrated", as stored in +/// `*_bvh4.rpf` before `XboxBvhBuilder::Rehydrate*`) set in dword 0. +pub fn is_compressed_header(data: &[u8]) -> bool { + data.len() >= 4 && ((word(data, 0) >> 24) & 1) != 0 +} + /// Bottom level over `tris`; `geometry` goes to every triangle node. pub fn build(tris: &[Triangle], geometry: u32) -> Bvh { let bounds: Vec = tris.iter().map(|t| bounds(t.iter().copied())).collect(); @@ -277,11 +293,24 @@ pub fn intersect_node(data: &[u8], node: u32, tmax: f32, o: [f32; 3], d: [f32; 3 let w = [0, 1, 2].map(|j| word(data, at + 16 + 12 * k + 4 * j)); ([half(w[0]), half(w[0] >> 16), half(w[1])], [half(w[1] >> 16), half(w[2]), half(w[2] >> 16)]) }; - let t1 = [0, 1, 2].map(|a| (mn[a] - o[a]) * inv[a]); - let t2 = [0, 1, 2].map(|a| (mx[a] - o[a]) * inv[a]); - let a = t1[0].min(t2[0]).max(t1[1].min(t2[1])).max(t1[2].min(t2[2])); - let b = t1[0].max(t2[0]).min(t1[1].max(t2[1])).min(t1[2].max(t2[2])); - if child != INVALID && a <= b && b >= 0.0 && a <= tmax { + let valid = child != INVALID && (0..3).all(|a| mn[a] <= mx[a]); + let (mut a, mut b) = (f32::NEG_INFINITY, f32::INFINITY); + for axis in 0..3 { + let (lo, hi) = if inv[axis].is_infinite() { + if o[axis] >= mn[axis] && o[axis] <= mx[axis] { + (f32::NEG_INFINITY, f32::INFINITY) + } else { + (f32::INFINITY, f32::NEG_INFINITY) + } + } else { + let t1 = (mn[axis] - o[axis]) * inv[axis]; + let t2 = (mx[axis] - o[axis]) * inv[axis]; + (t1.min(t2), t1.max(t2)) + }; + a = a.max(lo); + b = b.min(hi); + } + if valid && a <= b && b >= 0.0 && a <= tmax { *h = (a, child); } } @@ -541,4 +570,39 @@ pub(crate) mod tests { } assert!(hits > 100, "{hits} hits"); } + + #[test] + fn prebuild_size_and_compressed_header() { + // matches XboxBvhBuilder.dll's GetRaytracingAccelerationStructurePrebuildInfo formula + assert_eq!(prebuild_size(1, false), 1024); + assert_eq!(prebuild_size(64, false), 13312); + assert_eq!(prebuild_size(16, true), 5120); + let compressed = 0x8102_0006u32.to_le_bytes(); + let rehydrated = 0x8002_0006u32.to_le_bytes(); + assert!(is_compressed_header(&compressed)); + assert!(!is_compressed_header(&rehydrated)); + assert!(!is_compressed_header(&[])); + } + + #[test] + fn grazing_axis_aligned_ray_and_nan_box() { + let mut data = vec![0u8; 256]; + let (c0, c1, c2, c3) = (0x10u32, 0x20u32, 0x30u32, 0x40u32); + put(&mut data, 0, &[c0, c1, c2, c3]); + let box_f = |mn: [f32; 3], mx: [f32; 3]| [mn[0], mn[1], mn[2], mx[0], mx[1], mx[2]].map(f32::to_bits); + // child 0: normal box [-1..1, -1..1, 5..6]; ray origin lies right on x = -1.0 with dx = 0 + put(&mut data, 16, &box_f([-1.0, -1.0, 5.0], [1.0, 1.0, 6.0])); + // child 1: NaN-disabled box (GPURT convention) + put(&mut data, 40, &box_f([f32::NAN, -1.0, 2.0], [1.0, 1.0, 3.0])); + // child 2: inverted empty box (mn.x > mx.x) + put(&mut data, 64, &box_f([2.0, -1.0, 2.0], [-2.0, 1.0, 3.0])); + // child 3: box missed along x (x in [0..1] while o.x = -1.0) + put(&mut data, 88, &box_f([0.0, -1.0, 5.0], [1.0, 1.0, 6.0])); + + let o = [-1.0, 0.0, 0.0]; + let d = [0.0, 0.0, 1.0]; + let inv = [f32::INFINITY, f32::INFINITY, 1.0]; + let got = intersect_node(&data, BOX32, 100.0, o, d, inv, true); + assert_eq!(got, [c0, INVALID, INVALID, INVALID]); + } } diff --git a/crates/xcl/src/gpu/desc.rs b/crates/xcl/src/gpu/desc.rs index 0f29069..a400a70 100644 --- a/crates/xcl/src/gpu/desc.rs +++ b/crates/xcl/src/gpu/desc.rs @@ -637,6 +637,10 @@ mod view_tests { let v = buffer(&buffer_words(0x5_1234_5670, 16, 100, 77)); assert_eq!((v.address, v.stride, v.num_records, v.format, v.dst_sel), (0x5_1234_5670, 16, 100, 77, [4, 5, 6, 7])); assert_eq!((format_bytes(22), format_bytes(29), format_bytes(71), format_bytes(77)), (4, 4, 8, 16)); + let b = bvh_words(0x12_3456_789A_00, true); + assert_eq!(b, [0x3456_789A, 0x8000_0012, u32::MAX, 0]); + assert!(b[3] >> 28 < 8, "BVH descriptor must not look like a T# image to CopyDescriptors"); + assert_eq!(bvh_words(0x12_3456_789A_00, false)[1], 0x12); } } @@ -659,3 +663,11 @@ pub fn buffer_words(address: u64, stride: u32, num_records: u32, format: u32) -> let oob = if stride == 0 { 3 } else { 0 }; [address as u32, (address >> 32) as u32 & 0xFFFF | (stride & 0x3FFF) << 16, num_records, 0xFAC | (format & 0x7F) << 12 | 1 << 24 | oob << 28] } + +/// An RDNA2 BVH resource descriptor (SRSRC, 4 dwords) for `image_bvh(64)_intersect_ray`: +/// word 0 = base address bits 39:8 (256-byte units), word 1 = bits 47:40 | box_sort << 31, +/// word 2 = size / max bounds, word 3 = 0 (type bits 31:28 < 8 so descriptor copies leave it +/// verbatim instead of treating it as a T# image). +pub fn bvh_words(address: u64, box_sort: bool) -> [u32; 4] { + [(address >> 8) as u32, ((address >> 40) as u32 & 0xFF) | (u32::from(box_sort) << 31), u32::MAX, 0] +} diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index a625d0a..e6f15ef 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -1489,6 +1489,7 @@ impl Em { let r = |s: &mut Self, j: u64| s.vreg(addr_reg(j)); let wide = base == "bvh64_intersect_ray"; let node = r(self, 0); + let node_hi = if wide { Some(r(self, 1)) } else { None }; let k = if wide { 2 } else { 1 }; let fl = |s: &mut Self, j: u64| format!("asfloat({})", r(s, j)); let extent = fl(self, k); @@ -1507,11 +1508,18 @@ impl Em { ) }; let (d0, d1) = (self.sreg(srsrc), self.sreg(srsrc + 1)); + let a = self.t(); let t = self.t(); let act = self.act(); - // descriptor: base address in 256-byte units (word 0), box sorting = word 1 bit 31 - self.window(&format!("{d0} >> 24")); - self.line(&format!("uint4 {t} = bvh_intersect({node}, {d0} << 8, {extent}, {origin}, {dir}, {inv}, ({d1} >> 31) != 0u);")); + // descriptor: 48-bit base address in 256-byte units (word 0 + word 1 [7:0]), + // box sorting = word 1 bit 31; node offset is 32-bit (bvh) or 64-bit (bvh64) in 8-byte units + let off = match node_hi { + Some(hi) => format!("((((uint64_t){hi} << 32) | (uint64_t)({node} & ~7u)) << 3)"), + None => format!("((uint64_t)({node} & ~7u) << 3)"), + }; + self.line(&format!("uint64_t {a} = ((((uint64_t)({d1} & 0xFFu) << 32) | (uint64_t){d0}) << 8) + {off};")); + self.window(&format!("(uint)({a} >> 32)")); + self.line(&format!("uint4 {t} = bvh_intersect({node} & 7u, (uint){a}, {extent}, {origin}, {dir}, {inv}, ({d1} >> 31) != 0u);")); let st: Vec = (0..4).map(|c| format!("{} = {t}.{};", self.vreg(vdata + c), ["x", "y", "z", "w"][c as usize])).collect(); self.line(&format!("if ({act}) {{ {} }}", st.join(" "))); return Ok(()); @@ -4274,24 +4282,27 @@ uint fmt_comp(uint4 r, uint info, uint c) { uint res = select(ty == 0u, f_un, select(ty == 1u, f_sn, select(ty == 2u, asuint(fv), select(ty == 3u, asuint(fsv), select(ty == 4u, v, select(ty == 5u, (uint)sv, flt)))))); return select(c >= n, select(c == 3u, select(isint, 1u, 0x3F800000u), 0u), res); } -// image_bvh(64)_intersect_ray: node = id (low 3 bits: type), at base + (id & ~7) * 8. +// image_bvh(64)_intersect_ray: type = node & 7, at = low 32 bits of base + (node & ~7) * 8. // box32 (5) / box16 (4): 4 child ids + boxes → hit children (closest first when sorting), // misses 0xFFFFFFFF; triangle (0..3): (t numerator, denominator, i, j numerators), miss t = inf; // instance / AABB nodes are left to the shader (all 0xFFFFFFFF). -uint4 bvh_intersect(uint node, uint base, float tmax, float3 o, float3 d, float3 inv, bool sort) { - uint type = node & 7u; - uint at = base + ((node & ~7u) << 3); +uint4 bvh_intersect(uint type, uint at, float tmax, float3 o, float3 d, float3 inv, bool sort) { if (type == 4u || type == 5u) { uint4 child = mem.Load4(at); float tn[4]; uint id[4]; + float3 ninf = asfloat(0xFF800000u), pinf = asfloat(0x7F800000u); [unroll] for (uint k = 0u; k < 4u; k++) { float3 mn, mx; if (type == 5u) { mn = asfloat(mem.Load3(at + 16u + 24u * k)); mx = asfloat(mem.Load3(at + 28u + 24u * k)); } else { uint3 h = mem.Load3(at + 16u + 12u * k); mn = float3(f16tof32(h.x), f16tof32(h.x >> 16), f16tof32(h.y)); mx = float3(f16tof32(h.y >> 16), f16tof32(h.z), f16tof32(h.z >> 16)); } float3 t1 = (mn - o) * inv, t2 = (mx - o) * inv; - float a = max(max(min(t1.x, t2.x), min(t1.y, t2.y)), min(t1.z, t2.z)); - float b = min(min(max(t1.x, t2.x), max(t1.y, t2.y)), max(t1.z, t2.z)); - bool hit = child[k] != 0xFFFFFFFFu && a <= b && b >= 0.0f && a <= tmax; + bool3 in_slab = and(o >= mn, o <= mx); + float3 lo = select(isinf(inv), select(in_slab, ninf, pinf), min(t1, t2)); + float3 hi = select(isinf(inv), select(in_slab, pinf, ninf), max(t1, t2)); + float a = max(max(lo.x, lo.y), lo.z); + float b = min(min(hi.x, hi.y), hi.z); + bool valid = and(child[k] != 0xFFFFFFFFu, all(mn <= mx)); + bool hit = and(and(valid, a <= b), and(b >= 0.0f, a <= tmax)); tn[k] = hit ? a : asfloat(0x7F800000u); id[k] = hit ? child[k] : 0xFFFFFFFFu; } diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 71eada5..2a1d77b 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -2650,6 +2650,90 @@ fn gpu_triangle_pair_and_box16_nodes() { assert!(checked > 5, "{checked} triangle hits"); } +/// Multi-window `image_bvh64_intersect_ray` (full 64-bit node pointer into UMA window 1 with +/// base = 0, plus 48-bit base in window 1) and axis-aligned grazing ray / NaN-disabled box. +#[test] +fn gpu_bvh64_intersect_ray_across_memory_windows_and_grazing() { + if !gpu_ready() { + return; + } + let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap(); + let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64); + assert_eq!(w1 - w0, 1 << 32); + let write_words = |addr: u64, vals: &[u32]| unsafe { + let p = addr as *mut u32; + for (k, &v) in vals.iter().enumerate() { + *p.add(k) = v; + } + }; + let ff = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::>(); + let base_off = 0x1000u64; + let bvh_addr = w1 + base_off; + let tri_rel = 0x80u32 >> 3; + let nan_child = 0xC0u32 >> 3; + let inv_child = 0x100u32 >> 3; + // Window 1 root box32 at bvh_addr: child 0 = normal box [-1..1, -1..1, 5..6], + // child 1 = NaN-disabled box, child 2 = inverted box (mn > mx), child 3 = invalid + write_words(bvh_addr, &[tri_rel, nan_child, inv_child, u32::MAX]); + write_words(bvh_addr + 16, &ff(&[-1.0, -1.0, 5.0, 1.0, 1.0, 6.0])); + write_words(bvh_addr + 40, &ff(&[f32::NAN, -1.0, 2.0, 1.0, 1.0, 3.0])); + write_words(bvh_addr + 64, &ff(&[2.0, -1.0, 2.0, -2.0, 1.0, 3.0])); + // Triangle at bvh_addr + 0x80 in z = 5 + write_words(bvh_addr + 0x80, &ff(&[-1.0, -1.0, 5.0, 1.0, -1.0, 5.0, -1.0, 1.0, 5.0])); + write_words(bvh_addr + 0x80 + 60, &[9]); + // Poison window 0 at the same low offset: reading window 0 would return bogus child 0xDEAD_BEEF + write_words(w0 + base_off, &[0xDEAD_BEEF, u32::MAX, u32::MAX, u32::MAX]); + write_words(w0 + base_off + 16, &ff(&[-100.0, -100.0, 1.0, 100.0, 100.0, 2.0])); + + let mimg = |n: &'static str, vdata: u64, vaddr: u64, srsrc: u64| encode(n, "ENC_MIMG", &[("VDATA", vdata), ("VADDR", vaddr), ("SRSRC", srsrc), ("DMASK", 15)], None).unwrap(); + let mut code = Vec::new(); + // s[8:11] = base 0 (box sort enabled), v[0:1] = full 64-bit node pointer into window 1 + code.extend(mimg("IMAGE_BVH64_INTERSECT_RAY", 100, 0, 2)); + // s[8:11] = base 0, v[20:21] = full 64-bit triangle node pointer in window 1 + code.extend(mimg("IMAGE_BVH64_INTERSECT_RAY", 104, 20, 2)); + // s[12:15] = 48-bit base pointing at window 1 (`bvh_words(bvh_addr, true)`), v40 = 32-bit root + code.extend(mimg("IMAGE_BVH_INTERSECT_RAY", 108, 40, 3)); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + + let t = translate(&code, &Options { mem_windows: 2, ..Default::default() }).unwrap(); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); + + let mut st = KernelState::default(); + st.sgpr[8..12].copy_from_slice(&crate::gpu::desc::bvh_words(0, true)); + st.sgpr[12..16].copy_from_slice(&crate::gpu::desc::bvh_words(bvh_addr, true)); + let root64 = (bvh_addr >> 3) | 5; + let tri64 = (bvh_addr + 0x80) >> 3; + for (l, r) in st.vgpr.iter_mut().enumerate() { + // Even lanes graze the box edge (o.x = -1.0 == mn.x, dx = 0, inv.x = +inf); + // odd lanes fire through the center (0, 0, 0) along +z. + let ox = if l % 2 == 0 { -1.0f32 } else { 0.0f32 }; + let ray = [100.0f32, ox, 0.0, 0.0, 0.0, 0.0, 1.0, f32::INFINITY, f32::INFINITY, 1.0]; + let put_ray = |r: &mut Vec, at: usize| { + for (k, x) in ray.iter().enumerate() { + r[at + k] = x.to_bits(); + } + }; + r[0] = root64 as u32; + r[1] = (root64 >> 32) as u32; + put_ray(r, 2); + r[20] = tri64 as u32; + r[21] = (tri64 >> 32) as u32; + put_ray(r, 22); + r[40] = 5; // relative root box32 at bvh_addr + put_ray(r, 41); + } + let res = runner::run_in_arena(&dxil, &st, &arena).unwrap(); + const F: u32 = u32::MAX; + for l in 0..64usize { + let v = &res.vgpr[l]; + let q = |at: usize| [v[at], v[at + 1], v[at + 2], v[at + 3]]; + assert_eq!(q(100), [tri_rel, F, F, F], "lane {l}: 64-bit box32 in window 1 (grazing/NaN/inverted)"); + assert_eq!(q(108), [tri_rel, F, F, F], "lane {l}: 48-bit base box32 in window 1"); + let tri = q(104).map(f32::from_bits); + assert!(!tri[0].is_infinite() && ((tri[0] / tri[1]) - 5.0).abs() < 1e-4, "lane {l}: 64-bit triangle in window 1 → {tri:?}"); + } +} + /// Instructions first met in XboxBvhBuilder.dll's shaders: global atomics (float min / max by /// a CAS loop), 8 / 16-bit buffer loads / stores and 8 / 16-bit LDS accesses – neighbouring /// lanes share dwords, so a non-atomic read-modify-write would lose writes. diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 349be23..1dd84c7 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -289,6 +289,22 @@ pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, } } +/// #148 AllocateUploadMemory(size, alignment) → CPU/GPU pointer in unified memory (used by +/// `XboxBvhBuilder.dll` and other console middleware on default title command lists). +/// Freed automatically when the list's command allocator is reset. +pub(super) unsafe extern "system" fn allocate_upload_memory(this: *mut c_void, size: usize, align: usize) -> *mut u8 { + let Some(u) = crate::gpu::uma::get() else { + return std::ptr::null_mut(); + }; + match u.alloc(size.max(16), align.max(16)) { + Some(p) => { + with(this, |s| s.uma.push(p as usize)); + p + } + None => std::ptr::null_mut(), + } +} + unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, x: u32, y: u32, z: u32) -> Result<(), String> { bind_abi(this, list, pso, false)?; list.Dispatch(x, y, z); diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index dda42ab..a1bb37c 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -153,6 +153,11 @@ mod tests { write(&s1, &[0x1234, 0, 64, 0x3101_6FAC, 0, 0, 0, 0]); copy_words(&s1, &s3); assert_eq!(words_at(rel(v + 96)).unwrap()[0], 0x1234); + // a raytracing BVH SRSRC keeps its base address and box-sort flag verbatim + let bvh = crate::gpu::desc::bvh_words(0x12_3456_7800, true); + write(&s1, &[bvh[0], bvh[1], bvh[2], bvh[3], 0, 0, 0, 0]); + copy_words(&s1, &s3); + assert_eq!(words_at(rel(v + 96)).unwrap()[..4], bvh); // samplers: 16-byte slots, S# word 3 [11:0] = sampler index let (q0, q1) = (slot(sm).unwrap(), slot(sm + 16).unwrap()); assert!(q1.sampler && q1.index == 1 && q1.pc_srv == 0x9010); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index c478b50..7d4fca1 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -306,6 +306,19 @@ pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u3 super::bind::dispatch(this, x, y, z); } +/// command list #146 console compute/UAV barrier (used by `XboxBvhBuilder.dll` between BVH +/// build passes): emits a global UAV barrier so UMA writes become visible to the next pass +pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, _n: u32, _barriers: *const c_void) { + let b = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: ManuallyDrop::new(None) }), + }, + }; + pc::(this, PC_RESOURCE_BARRIER)(this, 1, &b); +} + /// command list #84 CopyResourceX(destination, source, flags); in place (the console's /// compression operations) there is nothing to do on PC pub(super) unsafe extern "system" fn copy_resource_flags_x(this: *mut c_void, dst: usize, src: usize, _flags: u32) { diff --git a/crates/xcl/src/hle/d3d12x/null.rs b/crates/xcl/src/hle/d3d12x/null.rs index ec40879..bfaeb60 100644 --- a/crates/xcl/src/hle/d3d12x/null.rs +++ b/crates/xcl/src/hle/d3d12x/null.rs @@ -395,8 +395,13 @@ unsafe extern "system" fn Device_CreateCommandList(_t: *mut NullObj, _m: u32, _t unsafe extern "system" fn Device_CreateCommandList1(_t: *mut NullObj, _m: u32, _ty: u32, _f: u32, _r: *const c_void, ppv: *mut *mut c_void) -> HRESULT { out_obj(ppv, Kind::CommandList) } -unsafe extern "system" fn Device_CheckFeatureSupport(_t: *mut NullObj, feature: u32, _d: *mut c_void, _s: u32) -> HRESULT { +unsafe extern "system" fn Device_CheckFeatureSupport(_t: *mut NullObj, feature: u32, data: *mut c_void, size: u32) -> HRESULT { crate::xlog_debug!("D3D12.X null: CheckFeatureSupport({feature})"); + // D3D12_FEATURE_D3D12_OPTIONS5 = 27: RaytracingTier sits at +8 + if feature == 27 && !data.is_null() && size >= 12 { + let tier = crate::state::config().raytracing_tier_override().unwrap_or(0); + *((data as *mut u8).add(8) as *mut u32) = tier; + } S_OK } unsafe extern "system" fn Device_CreateDescriptorHeap(_t: *mut NullObj, desc: *const u8, _r: *const c_void, ppv: *mut *mut c_void) -> HRESULT { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 387d774..d422ec4 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -509,7 +509,13 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { scanned += 1; } let scanned = scanned.max(public); - let total = scanned + EXTRA_SLOTS; + let max_console = console_slots(kind) + .iter() + .map(|e| e.0 + 1) + .chain(console_remap(kind).iter().map(|e| e.0 + 1)) + .max() + .unwrap_or(0); + let total = (scanned + EXTRA_SLOTS).max(max_console); let mut v: Vec = Vec::with_capacity(total + 1); v.push(orig); for i in 0..scanned { @@ -740,6 +746,9 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (88, l::write32_top_x as usize), (89, l::write64_top_x as usize), (90, l::write32_bottom_of_shader_x as usize), + // console compute/BVH builder extensions (`XboxBvhBuilder.dll`) + (146, l::uav_barrier_x as usize), + (148, b::allocate_upload_memory as usize), ] } _ => vec![], @@ -1266,6 +1275,22 @@ unsafe extern "system" fn heap_release(this: *mut c_void) -> u32 { unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, cpu: u64) { let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, desc, cpu) }; + // Raytracing acceleration structure SRV (pResource == NULL, Location == console GPU VA): + // translated shaders read BVH nodes from UMA (`bvh_intersect`), never from a PC DXR SRV, + // so write the RDNA2 BVH descriptor directly and skip forwarding the console VA to PC. + if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE) { + let va = v.Anonymous.RaytracingAccelerationStructure.Location; + let in_uma = va != 0 && crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize)); + if in_uma { + let w = crate::gpu::desc::bvh_words(va, true); + return super::console_heap::write(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0]); + } + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: CreateShaderResourceView(RAYTRACING_ACCELERATION_STRUCTURE) at {va:#x} is not in unified memory – writing empty BVH descriptor"); + } + return super::console_heap::write(&slot, &[0; 8]); + } f(this, res, desc, slot.pc_srv); let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else { return super::console_heap::write(&slot, &[0; 8]); @@ -1565,6 +1590,23 @@ fn pc_feature_size(feature: i32) -> Option { }) } +/// Apply `config.raytracing` / `XCL_RAYTRACING` override (if any) to a successful +/// `CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5)` result and log the reported tier once. +unsafe fn adjust_raytracing_options5(feature: i32, data: *mut u8, size: u32) { + if D3D12_FEATURE(feature) != D3D12_FEATURE_D3D12_OPTIONS5 || data.is_null() || (size as usize) < std::mem::size_of::() { + return; + } + let opts = &mut *(data as *mut D3D12_FEATURE_DATA_D3D12_OPTIONS5); + let host = opts.RaytracingTier.0; + if let Some(tier) = crate::state::config().raytracing_tier_override() { + opts.RaytracingTier = D3D12_RAYTRACING_TIER(tier as i32); + } + static LOGGED: AtomicU64 = AtomicU64::new(0); + if LOGGED.fetch_add(1, Ordering::Relaxed) == 0 { + crate::xlog_info!("D3D12.X: CheckFeatureSupport(D3D12_OPTIONS5) → RaytracingTier {} (host {})", opts.RaytracingTier.0, host); + } +} + /// CheckFeatureSupport(feature, data, size): console structures can be larger than the PC's /// (XDefiant: D3D12_OPTIONS with 0x40 bytes, 0x3C on the PC – and the title stops on the /// error). A size the PC refuses is retried with the PC's, the console's extra bytes zero. @@ -1572,7 +1614,11 @@ unsafe extern "system" fn dev_check_feature_support(this: *mut c_void, feature: type F = unsafe extern "system" fn(*mut c_void, i32, *mut u8, u32) -> HRESULT; let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CheckFeatureSupport"))); let hr = f(this, feature, data, size); - let Some(pc) = pc_feature_size(feature).filter(|&pc| hr < 0 && !data.is_null() && pc != size as usize) else { return hr }; + if hr >= 0 { + adjust_raytracing_options5(feature, data, size); + return hr; + } + let Some(pc) = pc_feature_size(feature).filter(|&pc| !data.is_null() && pc != size as usize) else { return hr }; let n = pc.min(size as usize); let mut tmp = vec![0u8; pc]; std::ptr::copy_nonoverlapping(data, tmp.as_mut_ptr(), n); // input fields (format, sample count …) @@ -1580,6 +1626,7 @@ unsafe extern "system" fn dev_check_feature_support(this: *mut c_void, feature: if hr2 >= 0 { std::ptr::write_bytes(data, 0, size as usize); std::ptr::copy_nonoverlapping(tmp.as_ptr(), data, n); + adjust_raytracing_options5(feature, data, size); } static SEEN: Mutex> = Mutex::new(Vec::new()); let mut seen = SEEN.lock().unwrap(); diff --git a/tests/testtitle/src/gpu.rs b/tests/testtitle/src/gpu.rs index 71922eb..9377a35 100644 --- a/tests/testtitle/src/gpu.rs +++ b/tests/testtitle/src/gpu.rs @@ -498,6 +498,74 @@ pub fn console_list_methods() -> Result<(), String> { } } +/// Raytracing D3D12.X surface: CheckFeatureSupport(D3D12_OPTIONS5), console heap SRV for a +/// raytracing acceleration structure (writes an RDNA2 BVH descriptor instead of zeros), and +/// the command list extensions `XboxBvhBuilder.dll` uses on default title lists (#148 +/// AllocateUploadMemory, #146 UAV barrier). +pub fn raytracing_surface() -> Result<(), String> { + unsafe { + let dev = device()?; + // 1. CheckFeatureSupport(D3D12_OPTIONS5) — both PC size (12 B) and oversized console probe (16 B) + let mut opts5 = D3D12_FEATURE_DATA_D3D12_OPTIONS5::default(); + dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5, &mut opts5 as *mut _ as *mut c_void, std::mem::size_of_val(&opts5) as u32) + .map_err(e)?; + let mut wide = [0xAAu8; 16]; + dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5, wide.as_mut_ptr() as *mut c_void, wide.len() as u32) + .map_err(e)?; + ensure!(wide[12..16] == [0, 0, 0, 0], "oversized OPTIONS5 tail not zeroed: {:?}", &wide[12..16]); + + // 2. Acceleration-structure SRV in a console CBV/SRV/UAV descriptor heap (pResource = NULL) + let graphics = 1u64 << 29; + let tlas = crate::XMemAlloc(0x1_0000, graphics); + ensure!(!tlas.is_null(), "graphics memory for TLAS"); + let tlas_va = tlas as u64; + let heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .map_err(e)?; + // console heap start handle returns in rax + let start: unsafe extern "system" fn(*mut c_void) -> usize = transmute_copy(&(*(*(heap.as_raw() as *const *const usize)).add(9))); + let cpu = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start(heap.as_raw()) }; + let srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + RaytracingAccelerationStructure: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_SRV { Location: tlas_va }, + }, + }; + dev.CreateShaderResourceView(None, Some(&srv), cpu); + let words = std::slice::from_raw_parts(cpu.ptr as *const u32, 4); + let expected = [(tlas_va >> 8) as u32, (((tlas_va >> 40) as u32) & 0xFF) | (1 << 31), u32::MAX, 0]; + ensure!(words == expected, "AS SRV slot {words:x?} != expected {expected:x?}"); + crate::XMemFree(tlas, graphics); + + // 3. Default title command list: #148 AllocateUploadMemory + #146 UAV barrier + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).map_err(e)?; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(e)?; + let l = list.as_raw(); + let slot = |i: usize| *(*(l as *const *const usize)).add(i); + let alloc_upload: unsafe extern "system" fn(*mut c_void, usize, usize) -> *mut u8 = std::mem::transmute(slot(148)); + let uav_barrier: unsafe extern "system" fn(*mut c_void, u32, *const c_void) = std::mem::transmute(slot(146)); + let up = alloc_upload(l, 256, 256); + ensure!(!up.is_null() && (up as usize).is_multiple_of(256), "AllocateUploadMemory (#148) returned {up:?}"); + *(up as *mut u32) = 0x5A5A_1234; + ensure!(*(up as *const u32) == 0x5A5A_1234, "upload memory not writable"); + uav_barrier(l, 1, std::ptr::null()); + list.Close().map_err(e)?; + queue.ExecuteCommandLists(&[Some(list.cast::().map_err(e)?)]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?; + wait(&queue, &fence, 1)?; + alloc.Reset().map_err(e)?; + Ok(()) + } +} + /// The console's DirectStorage as a title uses it: a file queue reads the start of the title's /// own executable into memory, a status array entry reports it and a D3D12 fence is signalled. pub fn direct_storage() -> Result<(), String> { diff --git a/tests/testtitle/src/main.rs b/tests/testtitle/src/main.rs index 3adb304..a9204de 100644 --- a/tests/testtitle/src/main.rs +++ b/tests/testtitle/src/main.rs @@ -592,6 +592,7 @@ fn main() { check("D3D12.X: frame clock + PresentX of the title's back buffer", gpu::present_x_frame); check("D3D12.X: console device methods (placed title memory, DMA queue + list, page pools)", gpu::console_device_methods); check("D3D12.X: console command list memory methods (writes, timestamp, fill, copy)", gpu::console_list_methods); + check("D3D12.X: raytracing surface (OPTIONS5, AS SRV descriptor, #146/#148 BVH list slots)", gpu::raytracing_surface); check("DirectStorage (xcrdapi): a file read into memory, status + D3D12 fence", gpu::direct_storage); check("D3D12.X: a texture in title memory (XG layout, #44) follows CPU writes", gpu::title_texture); check("D3D12.X: a texture in a streaming pool gets its texels once pages are mapped in", gpu::streamed_texture);