diff --git a/crates/xcl/src/hle/d3d12x/bvh_builder.rs b/crates/xcl/src/hle/d3d12x/bvh_builder.rs new file mode 100644 index 0000000000..d0a233682e --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/bvh_builder.rs @@ -0,0 +1,291 @@ +//! XboxBvhBuilder.dll's exports that build and copy acceleration structures, when the title +//! resolves them with `XCL_SPARSE_LAZY=1`: the ranges each call writes on the GPU are given +//! video memory (`sparse::will_write`) before the builder records its passes. +//! +//! With the switch, a tile the title commits has no video memory until the CPU's first bytes go +//! up to it or a placed buffer or a copy names it. The builder writes its structures with +//! compute programs through the sparse windows, which none of those see: in a retail title all +//! of a build's destination tiles and every compaction copy's had none, so what the builder +//! wrote went nowhere and the structures read as zeros (rays found nothing). + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::modules::MappedModule; +use crate::pe::{ExportTarget, ImportName}; + +const BATCHED: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z"; +const SINGLE: &str = "?BuildRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@IPEBUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC@@@Z"; +const COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z"; +const PREBUILD: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z"; + +/// the builder's own entry points (0: not resolved by the title yet) +static F_BATCHED: AtomicUsize = AtomicUsize::new(0); +static F_SINGLE: AtomicUsize = AtomicUsize::new(0); +static F_COPY: AtomicUsize = AtomicUsize::new(0); +/// its `GetRaytracingAccelerationStructurePrebuildInfo`, found in the module when a hook is made +static F_PREBUILD: AtomicUsize = AtomicUsize::new(0); + +type PrebuildFn = unsafe extern "system-unwind" fn( + *mut c_void, + *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS, + *const c_void, + *mut D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, +); + +/// destination -> the bytes its build may write: what a copy of it writes +static SIZES: Mutex>> = Mutex::new(None); + +/// One element of `BuildRaytracingAccelerationStructureBatched2X`'s array: the build's +/// description, then 32 bytes of the builder's (its postbuild infos and two words). +#[repr(C)] +#[derive(Clone, Copy)] +struct BatchedDesc { + build: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, + postbuild_count: u32, + _padding: u32, + postbuild: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC, + _tail: [u64; 2], +} + +/// The address the title gets for an export of `module` it resolves (`original`): one of +/// XboxBvhBuilder.dll's build and copy exports goes through its hook here, with +/// `XCL_SPARSE_LAZY=1` only. +pub(crate) fn intercept(module: &MappedModule, what: &ImportName, rva: u32, original: usize) -> usize { + if !module.name.eq_ignore_ascii_case("xboxbvhbuilder.dll") || !super::sparse::lazy_asked() { + return original; + } + let name = match what { + ImportName::Name { name, .. } => Some(name.as_str()), + ImportName::Ordinal(_) => module.exports.by_name.iter().find_map(|(n, t)| matches!(t, ExportTarget::Rva(v) if *v == rva).then_some(n.as_str())), + }; + let Some((slot, hook)) = hook_for(name.unwrap_or("")) else { return original }; + if let Some(ExportTarget::Rva(p)) = module.exports.by_name.get(PREBUILD) { + F_PREBUILD.store(module.base + *p as usize, Ordering::Release); + } + match slot.compare_exchange(0, original, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => { + crate::xlog_info!("D3D12.X: XboxBvhBuilder's {} gives the ranges it writes video memory (XCL_SPARSE_LAZY)", name.unwrap_or("?").split('@').next().unwrap_or("?").trim_start_matches('?')); + hook + } + Err(e) if e == original => hook, + Err(_) => original, + } +} + +/// the slot and hook of one of the exports hooked here +fn hook_for(name: &str) -> Option<(&'static AtomicUsize, usize)> { + match name { + BATCHED => Some((&F_BATCHED, batched as usize)), + SINGLE => Some((&F_SINGLE, single as usize)), + COPY => Some((&F_COPY, copy as usize)), + _ => None, + } +} + +/// The builder's own `prebuild` answer for build `b`'s inputs (asked without a stream). +unsafe fn prebuild_info(prebuild: PrebuildFn, this: *mut c_void, b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) -> D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO { + let mut info = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default(); + prebuild(this, &b.Inputs, std::ptr::null(), &mut info); + info +} + +/// What build `b` writes on the GPU, `info` being the builder's prebuild answer for it: its +/// destination, for the most the builder writes there (remembered in `sizes` for a copy of it; +/// with no size given, the destination's old one is forgotten). +fn build_writes(b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, info: &D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, sizes: &mut HashMap) -> Option<(u64, u64)> { + let dest = b.DestAccelerationStructureData; + if dest == 0 { + return None; + } + if info.ResultDataMaxSizeInBytes == 0 { + sizes.remove(&dest); + return None; + } + sizes.insert(dest, info.ResultDataMaxSizeInBytes); + Some((dest, info.ResultDataMaxSizeInBytes)) +} + +/// What a copy of `source` to `dest` writes: as much as `source`'s build (or the copy that made +/// it) could write, a clone or a compacted copy being no larger; that size becomes `dest`'s, for +/// a copy of the copy. Other modes, and sources of unknown size: None, and `dest`'s old size is +/// forgotten. +fn copy_writes(dest: u64, source: u64, mode: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE, sizes: &mut HashMap) -> Option<(u64, u64)> { + if dest == 0 { + return None; + } + let same_size = mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE || mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT; + match sizes.get(&source).copied().filter(|_| same_size) { + Some(n) => { + sizes.insert(dest, n); + Some((dest, n)) + } + None => { + sizes.remove(&dest); + None + } + } +} + +/// What a build's postbuild infos `posts` write on the GPU: each one's `DestBuffer`, for the +/// bytes of its info type (an unknown type: nothing). +pub(super) fn postbuild_writes(posts: &[D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC]) -> impl Iterator + '_ { + posts.iter().filter_map(|p| { + let n = match p.InfoType { + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE => std::mem::size_of::(), + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TOOLS_VISUALIZATION => std::mem::size_of::(), + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_SERIALIZATION => std::mem::size_of::(), + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE => std::mem::size_of::(), + _ => return None, + }; + (p.DestBuffer != 0).then_some((p.DestBuffer, n as u64)) + }) +} + +/// The GPU writes `[va, va + len)`: its tiles get video memory before the list runs. +fn give(va: u64, len: u64) { + super::sparse::will_write(va as usize, len as usize); +} + +unsafe fn give_build(this: *mut c_void, b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) { + let pf = F_PREBUILD.load(Ordering::Acquire); + if pf == 0 { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: XboxBvhBuilder exports no prebuild-info query: its builds get no video memory where they write")); + return; + } + if b.DestAccelerationStructureData == 0 { + return; + } + // asked before the lock: other lists' builds do not wait for this one's query + let info = prebuild_info(std::mem::transmute::(pf), this, b); + let writes = build_writes(b, &info, SIZES.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new)); + if let Some((va, len)) = writes { + give(va, len); + } +} + +/// a build's `count` postbuild infos at `posts` give what they write video memory +unsafe fn give_postbuild(count: u32, posts: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC) { + if count > 0 && crate::gpu::shader::readable(posts as usize, count as usize * std::mem::size_of::()) { + for (va, len) in postbuild_writes(std::slice::from_raw_parts(posts, count as usize)) { + give(va, len); + } + } +} + +unsafe extern "system-unwind" fn batched(this: *mut c_void, list: *mut c_void, count: u32, descs: *const BatchedDesc) { + if count > 0 && crate::gpu::shader::readable(descs as usize, count as usize * std::mem::size_of::()) { + for d in std::slice::from_raw_parts(descs, count as usize) { + give_build(this, &d.build); + give_postbuild(d.postbuild_count, d.postbuild); + } + } + let f: unsafe extern "system-unwind" fn(*mut c_void, *mut c_void, u32, *const BatchedDesc) = std::mem::transmute(F_BATCHED.load(Ordering::Acquire)); + f(this, list, count, descs) +} + +unsafe extern "system-unwind" fn single(this: *mut c_void, list: *mut c_void, desc: *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, pc: u32, posts: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC) { + if crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + give_build(this, &*desc); + } + give_postbuild(pc, posts); + let f: unsafe extern "system-unwind" fn(*mut c_void, *mut c_void, *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, u32, *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC) = std::mem::transmute(F_SINGLE.load(Ordering::Acquire)); + f(this, list, desc, pc, posts) +} + +unsafe extern "system-unwind" fn copy(this: *mut c_void, list: *mut c_void, dest: u64, source: u64, mode: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE) { + let writes = copy_writes(dest, source, mode, SIZES.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new)); + if let Some((va, len)) = writes { + give(va, len); + } + let f: unsafe extern "system-unwind" fn(*mut c_void, *mut c_void, u64, u64, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE) = std::mem::transmute(F_COPY.load(Ordering::Acquire)); + f(this, list, dest, source, mode) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// a builder's prebuild query: 0x3000 result bytes, 0x1800 scratch bytes for any input + unsafe extern "system-unwind" fn fake_prebuild( + _this: *mut c_void, + _inputs: *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS, + stream: *const c_void, + out: *mut D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, + ) { + assert!(stream.is_null(), "asked without a stream"); + *out = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO { ResultDataMaxSizeInBytes: 0x3000, ScratchDataSizeInBytes: 0x1800, UpdateScratchDataSizeInBytes: 0 }; + } + + /// A build writes its destination for the size the builder's own query gives, and that size + /// is what a compacted or cloned copy of it writes; other copy modes, unknown sources and + /// builds without a destination give nothing. + #[test] + fn a_build_and_its_copies_write_the_builders_own_result_size() { + let mut sizes = HashMap::new(); + let mut b = D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC { DestAccelerationStructureData: 0x10_4000_0000, ScratchAccelerationStructureData: 0x11_7051_0000, ..Default::default() }; + let info = unsafe { prebuild_info(fake_prebuild, std::ptr::null_mut(), &b) }; + assert_eq!(build_writes(&b, &info, &mut sizes), Some((0x10_4000_0000, 0x3000))); + b.DestAccelerationStructureData = 0; + assert_eq!(build_writes(&b, &info, &mut sizes), None, "no destination"); + assert_eq!(sizes.len(), 1); + assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), Some((0x10_5000_0000, 0x3000))); + assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE, &mut sizes), Some((0x10_5000_0000, 0x3000))); + assert_eq!(copy_writes(0x10_6000_0000, 0x10_5000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE, &mut sizes), Some((0x10_6000_0000, 0x3000)), "a copy of a copy writes its source's size"); + assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_SERIALIZE, &mut sizes), None, "a serialized copy has another size"); + assert!(!sizes.contains_key(&0x10_5000_0000), "and its destination's old size is forgotten"); + assert_eq!(copy_writes(0x10_6000_0000, 0x10_7000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), None, "a source whose build was not seen"); + assert!(!sizes.contains_key(&0x10_6000_0000), "and its destination's old size is forgotten"); + assert_eq!(copy_writes(0, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), None); + } + + /// A destination built smaller before takes the size of what is copied over it, so a copy of + /// it writes all of that; a build whose size the builder does not give forgets the old one. + #[test] + fn a_reused_destination_never_keeps_a_stale_size() { + let mut sizes = HashMap::new(); + let small = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO { ResultDataMaxSizeInBytes: 0x1000, ..Default::default() }; + let large = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO { ResultDataMaxSizeInBytes: 0x3_0000, ..Default::default() }; + let (a, b, c) = (0x10_4000_0000, 0x10_5000_0000, 0x10_6000_0000); + let built = |dest| D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC { DestAccelerationStructureData: dest, ..Default::default() }; + assert_eq!(build_writes(&built(b), &small, &mut sizes), Some((b, 0x1000))); + assert_eq!(build_writes(&built(a), &large, &mut sizes), Some((a, 0x3_0000))); + assert_eq!(copy_writes(b, a, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE, &mut sizes), Some((b, 0x3_0000))); + assert_eq!(copy_writes(c, b, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), Some((c, 0x3_0000)), "not the old build's 0x1000"); + assert_eq!(build_writes(&built(c), &D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default(), &mut sizes), None); + assert!(!sizes.contains_key(&c), "a build of unknown size forgets the old one"); + } + + /// Each postbuild info writes its own buffer, which may lie on a tile apart from the build's + /// destination, for its type's size; one without a buffer or of an unknown type writes nothing. + #[test] + fn postbuild_infos_write_their_own_buffers() { + let post = |va, t| D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC { DestBuffer: va, InfoType: t }; + let posts = [ + post(0x10_4002_0008, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE), + post(0x10_4003_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_SERIALIZATION), + post(0x10_4003_0010, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE), + post(0x10_4003_0018, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TOOLS_VISUALIZATION), + post(0, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE), + post(0x10_4004_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TYPE(7)), + ]; + assert_eq!(postbuild_writes(&posts).collect::>(), [(0x10_4002_0008, 8), (0x10_4003_0000, 16), (0x10_4003_0010, 8), (0x10_4003_0018, 8)]); + } + + /// Only the build and copy exports are hooked; the batched element is laid out as the + /// builder reads it. + #[test] + fn the_build_and_copy_exports_are_hooked() { + assert!(hook_for(BATCHED).is_some_and(|(s, _)| std::ptr::eq(s, &F_BATCHED))); + assert!(hook_for(SINGLE).is_some_and(|(s, _)| std::ptr::eq(s, &F_SINGLE))); + assert!(hook_for(COPY).is_some_and(|(s, _)| std::ptr::eq(s, &F_COPY))); + assert!(hook_for(PREBUILD).is_none(), "the query is called, not hooked"); + assert!(hook_for("?Rehydrate").is_none()); + assert_eq!(std::mem::size_of::(), std::mem::size_of::() + 32); + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 943bfec115..f766f64acb 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -14,6 +14,7 @@ pub use alloc_pool::AllocatorSubmitStats; mod barrier_groups; mod build_queue; pub mod bind; +pub(crate) mod bvh_builder; mod bvh_want; mod capture; pub mod console_heap; diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index cae13913f2..95eceb14f0 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -153,7 +153,7 @@ fn lazy_commits() -> bool { } /// `XCL_SPARSE_LAZY=1` was given -fn lazy_asked() -> bool { +pub(super) fn lazy_asked() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var("XCL_SPARSE_LAZY").is_ok_and(|v| v.trim() == "1")) } @@ -11385,6 +11385,27 @@ mod tests { drop(lazy); } + /// A ray-tracing build's compacted-size result on a tile of its own, apart from the build's + /// destination, gets that tile's memory before the build writes its eight bytes there. + #[test] + fn a_postbuild_result_on_a_tile_of_its_own_gets_memory() { + let lazy = Lazy::on(true); + unsafe { + let Some((base, mut s, _queue)) = lazy_state(3) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") }; + s.commit_range(base, 3 * TILE); + let posts = [D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC { + DestBuffer: (base + 2 * TILE + 8) as u64, + InfoType: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE, + }]; + let asks: Vec<(usize, usize)> = super::super::bvh_builder::postbuild_writes(&posts).map(|(va, n)| (va as usize, n as usize)).collect(); + s.give_memory(&asks); + assert_ne!(s.mapped[&(base + 2 * TILE)].pool, LAZY, "the result's tile got memory"); + assert_eq!(s.mapped[&base].pool, LAZY, "the destination's is left to its build"); + assert_eq!(s.mapped[&(base + TILE)].pool, LAZY, "the tile between is left"); + } + drop(lazy); + } + /// Decommitting a tile with no video memory frees and parks nothing; committed again it is /// listed again. With the switch off a commit maps at once, as before. #[test] diff --git a/crates/xcl/src/resolver.rs b/crates/xcl/src/resolver.rs index 72dbacae7b..e833420d7d 100644 --- a/crates/xcl/src/resolver.rs +++ b/crates/xcl/src/resolver.rs @@ -181,7 +181,7 @@ fn resolve_export_of_mapped_inner( ImportName::Ordinal(o) => m.exports.by_ordinal.get(&(*o as u32))?, }; match t { - ExportTarget::Rva(r) => Some(m.base + *r as usize), + ExportTarget::Rva(r) => Some(crate::hle::d3d12x::bvh_builder::intercept(m, what, *r, m.base + *r as usize)), ExportTarget::Forwarder(f) => { if depth > 8 { return None;