diff --git a/README.md b/README.md index d0a0f82..5058449 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ What each part does today and what it still needs: | Audio | Menu, video and loading sound; XMA voices and Opus streams decode | Reverb is silent; Opus results unverified against the title | | GPU: menus | Draws, compute and presentation on host D3D12; only changed title memory is copied | Frame pacing drifts on one screen in release builds | | GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes, indirect execution (arguments clamped), pipelines made by worker threads and kept on disk | Most of the scene is still missing (untranslated shaders drop draws); frames take seconds; real queries, depth bounds, HDR and scaling are missing | -| Shaders | Console GPU code recompiled to DXIL at first use, cached on disk. Menus: all. World: mesh 8,191 of 8,506, vertex/pixel 10,617 of 12,346, compute 1,643 of 2,539 | 64-bit image atomics, merged geometry stages, the ray-tracing builder's shaders; some compute programs need a GPU with 64-lane waves | +| Shaders | Console GPU code recompiled to DXIL at first use, cached on disk. Menus: all. World: mesh 8,191 of 8,506, vertex/pixel 10,617 of 12,346, compute 1,643 of 2,539 | Merged geometry stages, the ray-tracing builder's shaders; some compute programs need a GPU with 64-lane waves | | Textures | Console tiled layouts and detiling for the modes the title uses | Render-target metadata planes | | Series S mode | Runs through the menus to the loading screen | The world, as above | diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index e186e8e..1f7ac7b 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -27,7 +27,7 @@ diagnostics = [] workspace = true [target.'cfg(windows)'.dependencies] -windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } windows = { workspace = true, features = [ "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D_Dxc", diff --git a/crates/victory-gpu/src/address_map.rs b/crates/victory-gpu/src/address_map.rs new file mode 100644 index 0000000..794e71f --- /dev/null +++ b/crates/victory-gpu/src/address_map.rs @@ -0,0 +1,195 @@ +//! The address map translated shaders read title memory through when they +//! compute its address (a pointer they load, the BVH a ray-tracing pass +//! walks): see `victory_shader::emit::address_map` for its layout. It +//! lists the host copies of title memory made so far ([`crate::shadow`]), +//! each through raw views in dynamic slots of the view heap a list binds. +//! +//! shortcut: every copy is brought up to date (the pages the title wrote +//! since) once per list that binds the map, and what shaders write through +//! it stays in the copies (it is not copied back to title memory: the BVH +//! the title builds on the GPU is only read on the GPU). A list of copies +//! that grows into the thousands makes that refresh the cost to watch. + +use std::sync::Arc; + +use victory_shader::emit::address_map::{ENTRY, HEADER, Range, encode}; + +use crate::descriptor::host::HostHeap; +use crate::host::HostList; +use crate::shadow::Shadow; + +/// The most bytes one raw view holds: D3D12 buffer views have at most 2^27 +/// elements. +const VIEW_BYTES: u64 = 4 << 27; + +/// Pieces of title memory the spans `(start, len)` cover, sorted and not +/// overlapping, each with the span that holds it: where spans overlap, the +/// one starting last (the innermost buffer, as [`crate::shadow::find`] +/// picks) holds the piece. +pub(crate) fn pieces(spans: &[(u64, u64)]) -> Vec<(u64, u64, usize)> { + // (address, whether a span starts there, span): ends before starts. + let mut points: Vec<(u64, bool, usize)> = Vec::with_capacity(2 * spans.len()); + for (i, &(start, len)) in spans.iter().enumerate() { + if len > 0 { + points.push((start, true, i)); + points.push((start.saturating_add(len), false, i)); + } + } + points.sort_unstable(); + let mut active = std::collections::BTreeSet::new(); + let mut out: Vec<(u64, u64, usize)> = Vec::new(); + let mut at = 0; + for (x, starts, i) in points { + if x > at + && let Some(&(_, holder)) = active.iter().next_back() + { + match out.last_mut() { + Some(last) if last.2 == holder && last.0 + last.1 == at => last.1 += x - at, + _ => out.push((at, x - at, holder)), + } + } + if starts { + active.insert((spans[i].0, i)); + } else { + active.remove(&(spans[i].0, i)); + } + at = x; + } + out +} + +/// The map's entries for `pieces` of the spans: each piece cut where its +/// span's views ([`VIEW_BYTES`] each) end, with the view (span, view number +/// within the span) and the piece's offset in that view. +fn entries( + spans: &[(u64, u64)], + pieces: &[(u64, u64, usize)], +) -> Vec<(u64, u32, (usize, u64), u32)> { + let mut out = Vec::new(); + for &(start, len, span) in pieces { + let mut at = start; + let end = start + len; + while at < end { + let rel = at - spans[span].0; + let view = rel / VIEW_BYTES; + let view_end = spans[span].0 + (view + 1) * VIEW_BYTES; + let next = end.min(view_end); + out.push(( + at, + (next - at) as u32, + (span, view), + (rel - view * VIEW_BYTES) as u32, + )); + at = next; + } + } + out +} + +/// The address map for draws of `list` while `heap` is its view heap: its +/// host GPU address, and the dynamic slots its views take (to give back +/// when the list is reset). Each copy is brought up to date when the list +/// is submitted. +pub(crate) fn make(list: &HostList, heap: &HostHeap) -> Option<(u64, (u32, u32))> { + let copies: Vec> = crate::shadow::all(); + let spans: Vec<(u64, u64)> = copies.iter().map(|c| c.span()).collect(); + let pieces = pieces(&spans); + let entries = entries(&spans, &pieces); + let mut views: Vec<(usize, u64)> = entries.iter().map(|e| e.2).collect(); + views.sort_unstable(); + views.dedup(); + let n = views.len() as u32; + let first = if n == 0 { 0 } else { heap.dynamic(n)? }; + for (k, &(span, view)) in views.iter().enumerate() { + let copy = &copies[span]; + let offset = view * VIEW_BYTES; + let bytes = (copy.span().1 - offset).min(VIEW_BYTES).next_multiple_of(4); + heap.raw_uav_at( + first + k as u32, + ©.buffer, + offset / 4, + (bytes / 4) as u32, + ); + } + for c in &copies { + if list.first_use(Arc::as_ptr(c) as usize ^ MAP_KEY) { + let (start, len) = c.span(); + c.refresh(list, start, len); + } + } + let ranges: Vec = entries + .iter() + .map(|&(start, len, view, view_offset)| Range { + start, + len, + view: first + views.binary_search(&view).expect("listed") as u32, + view_offset, + }) + .collect(); + let words = encode(&ranges); + // Room for one entry even when there is none: the shader reads it. + let bytes = u64::from(HEADER) + u64::from(ENTRY) * ranges.len().max(1) as u64; + let (gpu, to) = list.scratch(bytes)?; + // SAFETY: `bytes` of the list's upload memory, which outlives the + // list's run; the words fit. + unsafe { + std::ptr::write_bytes(to, 0, bytes as usize); + std::ptr::copy_nonoverlapping(words.as_ptr().cast::(), to, words.len() * 4); + } + Some((gpu, (first, n))) +} + +/// Keeps the map's refreshes apart from other first uses the list asks +/// about (texture keys are addresses too). +const MAP_KEY: usize = 0x5; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn inner_buffers_win_and_pieces_do_not_overlap() { + // A heap-sized buffer with two placed inside it, one past its end, + // and an empty one. + let spans = [ + (0x1000, 0x1000), + (0x1200, 0x100), + (0x1800, 0x100), + (0x3000, 0x40), + (0x5000, 0), + ]; + assert_eq!( + pieces(&spans), + [ + (0x1000, 0x200, 0), + (0x1200, 0x100, 1), + (0x1300, 0x500, 0), + (0x1800, 0x100, 2), + (0x1900, 0x700, 0), + (0x3000, 0x40, 3), + ] + ); + } + + #[test] + fn the_same_span_twice_is_one_piece() { + assert_eq!( + pieces(&[(0x100, 0x100), (0x100, 0x100)]), + [(0x100, 0x100, 1)] + ); + } + + #[test] + fn pieces_are_cut_where_views_end() { + let spans = [(0x10, 2 * VIEW_BYTES + 8)]; + let e = entries(&spans, &pieces(&spans)); + assert_eq!( + e, + [ + (0x10, VIEW_BYTES as u32, (0, 0), 0), + (0x10 + VIEW_BYTES, VIEW_BYTES as u32, (0, 1), 0), + (0x10 + 2 * VIEW_BYTES, 8, (0, 2), 0), + ] + ); + } +} diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 0d94ac0..a34c0c6 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -33,6 +33,58 @@ pub(crate) struct HostHeap { /// Where the search for free dynamic slots starts, and which are taken /// (by lists not yet reset). next: Mutex<(u32, Vec)>, + /// View heaps: the console words of each slot's descriptor, 8 dwords + /// per slot, for shaders that read descriptors as numbers: the buffer, + /// its mapping and its host GPU address. + words: Option<(ID3D12Resource, usize, u64)>, +} + +/// A GFX10 buffer descriptor's dword 3 for raw access: X Y Z W selects, a +/// 32-bit float format, raw out-of-range checking, resource level 1. The +/// address and size in dwords 0 to 2 are what programs read. +const RAW_DWORD3: u32 = 0x3101_6FAC; + +/// The console words of a descriptor for `view`, as far as programs read +/// them as numbers: a buffer descriptor's address, stride and record count +/// for buffer views, constant buffers and acceleration structures (whose +/// descriptor is a buffer at the structure); zero otherwise. +pub(crate) fn console_words(view: &View) -> [u32; 8] { + let (address, len, stride) = match view { + View::Constant(address, size) => (*address, u64::from(*size), 0), + // An acceleration structure (dimension 11) names no resource: its + // location is the union's first quadword. + View::Shader(0, Some(d)) if d[1] == 11 => ( + u64::from(d[4]) | u64::from(d[5]) << 32, + u64::from(u32::MAX), + 0, + ), + v => match buffer_range(v) { + Some((address, len)) => { + let stride = match v { + View::Shader(_, Some(d)) | View::Unordered(_, _, Some(d)) => d[7], + View::Placed(_, _, d) => d[7], + _ => 0, + }; + (address, len, stride) + } + None => return [0; 8], + }, + }; + let records = if stride > 0 { + len / u64::from(stride) + } else { + len + }; + [ + address as u32, + (address >> 32) as u32 & 0xFFFF | (stride & 0x3FFF) << 16, + records.min(u64::from(u32::MAX)) as u32, + RAW_DWORD3, + 0, + 0, + 0, + 0, + ] } /// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for @@ -144,6 +196,20 @@ impl HostHeap { u64::from(step), sampler, )); + let words = if sampler { + None + } else { + let bytes = u64::from(count + extra) * 32; + host.shared_buffer(bytes).map(|(buffer, data)| { + crate::host::name(&buffer, || format!("descriptor words {count}+{extra}")); + // SAFETY: a fresh mapping of `bytes`; a live buffer. + unsafe { + std::ptr::write_bytes(data, 0, bytes as usize); + let gpu = buffer.GetGPUVirtualAddress(); + (buffer, data as usize, gpu) + } + }) + }; let h = HostHeap { heap, cpu, @@ -154,6 +220,7 @@ impl HostHeap { made: Mutex::new(vec![0; count as usize]), kept: Mutex::new(vec![None; (count + extra) as usize]), next: Mutex::new((0, vec![false; extra as usize])), + words, }; // A slot never written is undefined: shaders reading one (a slot // the title wrote in a way we do not know, or a table entry no @@ -302,6 +369,7 @@ impl HostHeap { null_for(view, self.cpu(index)); } self.keep(index, kept.flatten()); + self.write_words(index, console_words(view)); } /// Makes slot `index` read nothing: a null view, or a plain sampler. @@ -312,6 +380,55 @@ impl HostHeap { null_view(self.cpu(index)); } self.keep(index, None); + self.write_words(index, [0; 8]); + } + + /// The host GPU address of the heap's descriptor words (view heaps). + pub(crate) fn words(&self) -> Option { + self.words.as_ref().map(|w| w.2) + } + + fn write_words(&self, index: u32, words: [u32; 8]) { + let Some((_, data, _)) = self.words else { + return; + }; + if index >= self.count + self.dynamic { + return; + } + // SAFETY: slot `index` of the mapping, 32 bytes each. + unsafe { + std::ptr::copy_nonoverlapping( + words.as_ptr(), + (data as *mut u32).add(index as usize * 8), + 8, + ); + } + } + + /// Makes slot `index` (a dynamic one) a raw unordered access view of + /// `n` dwords of `buffer` from dword `first` on, holding the buffer + /// while the slot does. + pub(crate) fn raw_uav_at(&self, index: u32, buffer: &ID3D12Resource, first: u64, n: u32) { + let Some(host) = host() else { return }; + let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + FirstElement: first, + NumElements: n, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + ..Default::default() + }, + }, + }; + // SAFETY: a slot of our heap and a live buffer. + unsafe { + host.device + .CreateUnorderedAccessView(buffer, None, Some(&desc), self.cpu(index)) + }; + self.keep(index, Some(buffer.clone())); + self.write_words(index, [0; 8]); } /// Slot `index` now views `resource` (or nothing of the host's). @@ -361,6 +478,7 @@ impl HostHeap { /// memory (the list's own, which it holds). pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) { self.keep(index, None); + self.write_words(index, [0; 8]); let Some(host) = host() else { return }; let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu, @@ -413,6 +531,8 @@ impl HostHeap { } return None; }; + // Even buffer views made only for draws have their words now. + self.write_words(index, console_words(&view)); if made[index as usize] != key { let later = !for_draw && view.is_buffer(); made[index as usize] = if later { 0 } else { key }; diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 8d36c12..16c6151 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -82,6 +82,8 @@ pub(crate) struct State { dynamic: Vec<(usize, u32, u32)>, /// A fresh table of the stage being bound could not be made. table_failed: bool, + /// Address maps made in this list: title view heap, host GPU address. + maps: Vec<(usize, u64)>, } impl Drop for State { @@ -502,6 +504,50 @@ impl State { } } } + // The address map and the descriptor words belong to the view + // heap: without them the shader would read nothing it expects. + let heap = (self.heaps[0] != 0) + .then(|| crate::descriptor::heap(self.heaps[0] as This).host()) + .flatten(); + let mut extra = Vec::new(); + if let Some(param) = stage.address_map { + let made = self.maps.iter().find(|m| m.0 == self.heaps[0]).map(|m| m.1); + let gpu = match (made, heap) { + (Some(gpu), _) => Some(gpu), + (None, Some(h)) => { + crate::address_map::make(list, h).map(|(gpu, (first, n))| { + if n > 0 { + self.dynamic.push((self.heaps[0], first, n)); + } + self.maps.push((self.heaps[0], gpu)); + gpu + }) + } + (None, None) => None, + }; + let Some(gpu) = gpu else { + once!("a draw or dispatch dropped: no address map for its view heap"); + return false; + }; + extra.push((param, gpu)); + } + if let Some(param) = stage.descriptor_words { + let Some(gpu) = heap.and_then(|h| h.words()) else { + once!("a draw or dispatch dropped: no descriptor words for its view heap"); + return false; + }; + extra.push((param, gpu)); + } + for (param, gpu) in extra { + // SAFETY: an open list; the buffers live as long as it runs. + unsafe { + if compute { + l.SetComputeRootShaderResourceView(param, gpu); + } else { + l.SetGraphicsRootShaderResourceView(param, gpu); + } + } + } for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] { for &(slot, param) in views { // Root SRVs are bounded one-view tables (see the host diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 39741ce..d5214fe 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1366,7 +1366,7 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b 2 => return, _ => {} } - if len == 0 || title_dst && !crate::texture::committed(dst, len) { + if len == 0 { return; } if title_dst { @@ -1384,6 +1384,13 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b if whole { return; } + // The kernel reports an unmapped destination as it does a source, so + // `VirtualQuery` (which walks page tables to the region's end, ~1 ms a + // copy in the title's pools, ~100 ms per world frame) is asked only + // after a failure: a destination not all mapped is left alone. + if title_dst && !crate::texture::committed(dst, len) { + return; + } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Fallbacks, 1); // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece @@ -1421,17 +1428,64 @@ fn read(src: *const u8, dst: *mut u8, len: usize) -> bool { unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 } } +/// `NtWriteVirtualMemory`, looked up once. `WriteProcessMemory` asks the +/// kernel about the destination's region first (to flush the instruction +/// cache of executable memory), which in the title's big pools walks page +/// tables for about 2 ms a call: the copy back after a world submission +/// spent over a second there. The system call itself writes the same bytes +/// and reports a page it cannot write the same way. +fn nt_write_virtual_memory() -> Option { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + static CALL: std::sync::OnceLock> = std::sync::OnceLock::new(); + *CALL.get_or_init(|| { + // SAFETY: ntdll is always loaded; the symbol has this signature. + unsafe { + let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr().cast()); + let f = GetProcAddress(ntdll, c"NtWriteVirtualMemory".as_ptr().cast())?; + Some(std::mem::transmute::< + unsafe extern "system" fn() -> isize, + NtWrite, + >(f)) + } + }) +} + +type NtWrite = unsafe extern "system" fn( + process: isize, + base: *mut core::ffi::c_void, + buffer: *const core::ffi::c_void, + len: usize, + written: *mut usize, +) -> i32; + /// Copies host memory into title memory after a submission (what shaders /// wrote), leaving pages that are not mapped alone. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) { use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; + let nt = nt_write_virtual_memory(); let write = |at: usize, n: usize| { let from = src.wrapping_add(at - dst as usize); let mut done = 0; // SAFETY: the source is our mapped host copy; the kernel checks the // destination. - unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 } + unsafe { + match nt { + // STATUS_SUCCESS only: a partial copy is a failure here too. + Some(call) => { + call( + GetCurrentProcess() as isize, + at as _, + from.cast(), + n, + &mut done, + ) == 0 + } + None => { + WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 + } + } + } }; if len == 0 || write(dst as usize, len) { return; @@ -1544,6 +1598,8 @@ struct Meter { impl Meter { fn new() -> Self { + #[cfg(feature = "diagnostics")] + crate::profile::start(); let now = std::time::Instant::now(); Meter { since: now, @@ -2137,3 +2193,55 @@ mod batch { ); } } + +#[cfg(test)] +mod title_memory_io { + use super::{copy_mapped, write_mapped}; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + + const PAGE: usize = 4096; + + /// Two committed pages followed by one reserved (not committed) page. + fn region() -> *mut u8 { + // SAFETY: a fresh reservation of ours, of which two pages are committed. + unsafe { + let base = VirtualAlloc(std::ptr::null(), 3 * PAGE, MEM_RESERVE, PAGE_READWRITE); + assert!(!base.is_null()); + let committed = VirtualAlloc(base, 2 * PAGE, MEM_COMMIT, PAGE_READWRITE); + assert!(!committed.is_null()); + base.cast() + } + } + + fn release(base: *mut u8) { + // SAFETY: the reservation made by `region`. + unsafe { VirtualFree(base.cast(), 0, MEM_RELEASE) }; + } + + #[test] + fn write_mapped_writes_mapped_pages_and_skips_the_rest() { + let base = region(); + let data = vec![0xabu8; 3 * PAGE]; + // The third page is not committed: its piece is skipped, the others land. + write_mapped(base, data.as_ptr(), 3 * PAGE); + // SAFETY: the two committed pages of `region`. + let written = unsafe { std::slice::from_raw_parts(base, 2 * PAGE) }; + assert!(written.iter().all(|&b| b == 0xab)); + release(base); + } + + #[test] + fn copy_into_title_memory_that_is_not_all_mapped_is_left_alone() { + let base = region(); + let from = vec![0x5au8; 3 * PAGE]; + copy_mapped(base, from.as_ptr(), 3 * PAGE, true); + // A whole copy into mapped memory works without asking the system first. + copy_mapped(base, from.as_ptr(), 2 * PAGE, true); + // SAFETY: the two committed pages of `region`. + let now = unsafe { std::slice::from_raw_parts(base, 2 * PAGE) }; + assert!(now.iter().all(|&b| b == 0x5a)); + release(base); + } +} diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index f91782d..7238755 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -15,6 +15,8 @@ //! share, [`console`] which console model the title sees. Planned: //! `present` (swap chain). +#[cfg(windows)] +mod address_map; #[cfg(all(windows, feature = "diagnostics"))] mod capture; pub mod console; @@ -36,6 +38,8 @@ pub mod object; pub mod pipeline; #[cfg(windows)] mod primitive; +#[cfg(all(windows, feature = "diagnostics"))] +mod profile; pub mod query; pub mod queue; pub mod resource; @@ -55,4 +59,4 @@ mod watch; #[cfg(windows)] pub use host::on_failure; #[cfg(windows)] -pub use watch::{title_memory_remapped, writing as kernel_will_write}; +pub use watch::{set_alias_lookup, title_memory_remapped, writing as kernel_will_write}; diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 650216d..60bb05c 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -8,7 +8,9 @@ use std::ffi::{CStr, CString}; use std::sync::Arc; -use victory_shader::emit::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; +use victory_shader::emit::{ + ADDRESS_MAP_SPACE, DESCRIPTOR_WORDS_SPACE, ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE, +}; use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; @@ -265,6 +267,10 @@ pub(crate) struct Stage { /// Root parameters of its root views: (title root parameter, ours). pub(crate) root_cbvs: Vec<(u8, u32)>, pub(crate) root_srvs: Vec<(u8, u32)>, + /// The root parameters of the address map and of the descriptor words, + /// when it reads them. + pub(crate) address_map: Option, + pub(crate) descriptor_words: Option, } impl Stage { @@ -421,6 +427,8 @@ impl HostPipeline { user_data: None, root_cbvs: Vec::new(), root_srvs: Vec::new(), + address_map: None, + descriptor_words: None, }; let dwords = t.user_data_dwords(); if dwords > 0 { @@ -494,6 +502,29 @@ impl HostPipeline { }); } } + for (wanted, space, out) in [ + (t.address_map, ADDRESS_MAP_SPACE, &mut stage.address_map), + ( + t.descriptor_words, + DESCRIPTOR_WORDS_SPACE, + &mut stage.descriptor_words, + ), + ] { + if wanted { + *out = Some(params.len() as u32); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, + RegisterSpace: space, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: visibility, + }); + } + } for (n, s) in t.static_samplers.iter().enumerate() { samplers.push(D3D12_STATIC_SAMPLER_DESC { Filter: D3D12_FILTER(s.filter as i32), diff --git a/crates/victory-gpu/src/profile.rs b/crates/victory-gpu/src/profile.rs new file mode 100644 index 0000000..f5b4b08 --- /dev/null +++ b/crates/victory-gpu/src/profile.rs @@ -0,0 +1,329 @@ +//! Diagnostics: a sampling profiler of the whole process (title threads, +//! our workers, the driver), switched on by `VICTORY_PROFILE=` (the +//! sampling period of busy threads, 4 by default; idle threads are looked at +//! every 25 periods). Every 5 s it logs, per thread, the CPU time spent and +//! the most frequent call stacks (module!function+offset, innermost first), +//! so a frame's time can be told apart: title code, write watching, +//! translation, driver, or waiting (and where). +//! +//! A sampled thread is suspended for a few microseconds; nothing is +//! allocated or locked while it is. The title's own code shows as +//! `module+rva` (no symbols), ours and the system's by name. + +use std::collections::HashMap; +use std::time::{Duration, Instant}; +use windows_sys::Win32::Foundation::{CloseHandle, FILETIME, HANDLE, INVALID_HANDLE_VALUE}; +use windows_sys::Win32::System::Diagnostics::Debug::{ + CONTEXT, GetThreadContext, RtlLookupFunctionEntry, RtlVirtualUnwind, SYMBOL_INFO, SymFromAddr, + SymInitialize, SymSetOptions, +}; +use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, +}; +use windows_sys::Win32::System::LibraryLoader::GetModuleFileNameW; +use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, GetCurrentProcessId, GetCurrentThreadId, GetThreadDescription, + GetThreadTimes, OpenThread, ResumeThread, SuspendThread, +}; + +const CONTEXT_FULL: u32 = 0x10_0003; +const THREAD_SUSPEND_RESUME: u32 = 0x2; +const THREAD_GET_CONTEXT: u32 = 0x8; +const THREAD_QUERY_INFORMATION: u32 = 0x40; +const DEPTH: usize = 8; +const REPORT: Duration = Duration::from_secs(5); +/// A thread using at least this much CPU per second is "busy". +const BUSY_MS: u64 = 30; + +type Stack = [u64; DEPTH]; + +struct Tracked { + handle: HANDLE, + name: String, + last_cpu_100ns: u64, + cpu_ms_second: u64, + cpu_ms_report: u64, + samples: u64, + stacks: HashMap, +} + +/// Starts the profiler thread when `VICTORY_PROFILE` is set; once. +pub(crate) fn start() { + static ONCE: std::sync::Once = std::sync::Once::new(); + let Some(period) = std::env::var("VICTORY_PROFILE") + .ok() + .map(|v| v.parse::().unwrap_or(4).max(1)) + else { + return; + }; + ONCE.call_once(|| { + let _ = std::thread::Builder::new() + .name("victory-prof".into()) + .spawn(move || run(Duration::from_millis(period))); + }); +} + +fn filetime(t: &FILETIME) -> u64 { + u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime) +} + +fn thread_ids() -> Vec { + let mut ids = Vec::new(); + // SAFETY: a snapshot of our own process's threads, walked and closed. + unsafe { + let snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if snap == INVALID_HANDLE_VALUE { + return ids; + } + let mut e: THREADENTRY32 = std::mem::zeroed(); + e.dwSize = size_of::() as u32; + let pid = GetCurrentProcessId(); + let mut more = Thread32First(snap, &mut e) != 0; + while more { + if e.th32OwnerProcessID == pid { + ids.push(e.th32ThreadID); + } + more = Thread32Next(snap, &mut e) != 0; + } + CloseHandle(snap); + } + ids +} + +fn thread_name(handle: HANDLE, tid: u32) -> String { + let mut text: *mut u16 = std::ptr::null_mut(); + // SAFETY: an open thread handle and an out pointer; the text is read + // to its NUL (and left allocated: a few bytes per thread). + unsafe { + if GetThreadDescription(handle, &mut text) >= 0 && !text.is_null() { + let mut n = 0; + while *text.add(n) != 0 { + n += 1; + } + let name = String::from_utf16_lossy(std::slice::from_raw_parts(text, n)); + if !name.is_empty() { + return format!("{name}#{tid}"); + } + } + } + format!("thread#{tid}") +} + +fn cpu_100ns(handle: HANDLE) -> u64 { + let mut t: [FILETIME; 4] = [FILETIME { + dwLowDateTime: 0, + dwHighDateTime: 0, + }; 4]; + // SAFETY: an open thread handle and four time structures. + unsafe { + GetThreadTimes(handle, &mut t[0], &mut t[1], &mut t[2], &mut t[3]); + } + filetime(&t[2]) + filetime(&t[3]) +} + +/// The call stack of a thread, innermost first, zero-padded. The thread is +/// suspended meanwhile; nothing here allocates or locks. +fn capture(handle: HANDLE) -> Option { + let mut stack = [0u64; DEPTH]; + // SAFETY: an open thread handle with the rights; the context is ours; + // the unwinding reads the thread's stack, which is stopped. + unsafe { + if SuspendThread(handle) == u32::MAX { + return None; + } + let mut ctx: CONTEXT = std::mem::zeroed(); + ctx.ContextFlags = CONTEXT_FULL; + if GetThreadContext(handle, &mut ctx) != 0 { + for slot in &mut stack { + if ctx.Rip == 0 { + break; + } + *slot = ctx.Rip; + let mut base = 0u64; + let entry = RtlLookupFunctionEntry(ctx.Rip, &mut base, std::ptr::null_mut()); + if entry.is_null() { + // A leaf without unwind data: the return address is on top. + ctx.Rip = *(ctx.Rsp as *const u64); + ctx.Rsp += 8; + } else { + let mut data = std::ptr::null_mut(); + let mut frame = 0u64; + RtlVirtualUnwind( + 0, + base, + ctx.Rip, + entry, + &mut ctx, + &mut data, + &mut frame, + std::ptr::null_mut(), + ); + } + } + } + ResumeThread(handle); + } + (stack[0] != 0).then_some(stack) +} + +/// `module!function+offset`, or `module+rva`. +fn describe(addr: u64, cache: &mut HashMap) -> String { + if let Some(s) = cache.get(&addr) { + return s.clone(); + } + let text = symbolize(addr); + cache.insert(addr, text.clone()); + text +} + +fn symbolize(addr: u64) -> String { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; + // SAFETY: plain queries with our buffers. + unsafe { + let mut base = 0u64; + RtlLookupFunctionEntry(addr, &mut base, std::ptr::null_mut()); + let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + VirtualQuery(addr as *const _, &mut info, size_of_val(&info)); + let region = if base != 0 { + base + } else { + info.AllocationBase as u64 + }; + let mut path = [0u16; 260]; + let n = GetModuleFileNameW(region as *mut _, path.as_mut_ptr(), 260) as usize; + let module = String::from_utf16_lossy(&path[..n]); + let module = module.rsplit('\\').next().unwrap_or("").to_string(); + let module = if module.is_empty() { + format!("{region:#x}") + } else { + module + }; + let mut buf = vec![0u8; size_of::() + 256]; + let sym = buf.as_mut_ptr().cast::(); + (*sym).SizeOfStruct = size_of::() as u32; + (*sym).MaxNameLen = 255; + let mut displacement = 0u64; + if SymFromAddr(GetCurrentProcess(), addr, &mut displacement, sym) != 0 { + let name = std::slice::from_raw_parts( + (*sym).Name.as_ptr().cast::(), + (*sym).NameLen as usize, + ); + let name = String::from_utf8_lossy(name); + let short: String = name.chars().take(90).collect(); + return format!("{module}!{short}+{displacement:#x}"); + } + format!("{module}+{:#x}", addr - region) + } +} + +fn run(period: Duration) { + // SAFETY: symbol handling for our own process, used from this thread only. + unsafe { + SymSetOptions(0x2 | 0x4); // SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS + SymInitialize(GetCurrentProcess(), std::ptr::null(), 1); + } + // SAFETY: no preconditions; returns the caller's thread id. + let me = unsafe { GetCurrentThreadId() }; + let mut threads: HashMap = HashMap::new(); + let mut cache = HashMap::new(); + let (mut refreshed, mut second, mut reported) = ( + Instant::now() - Duration::from_secs(9), + Instant::now(), + Instant::now(), + ); + let mut tick = 0u64; + tracing::info!(period_ms = period.as_millis() as u64, "profiler started"); + loop { + std::thread::sleep(period); + tick += 1; + if refreshed.elapsed() >= Duration::from_secs(1) { + refreshed = Instant::now(); + let ids = thread_ids(); + threads.retain(|tid, t| { + let keep = ids.contains(tid); + if !keep { + // SAFETY: a handle we opened. + unsafe { CloseHandle(t.handle) }; + } + keep + }); + for tid in ids { + if tid == me || threads.contains_key(&tid) { + continue; + } + // SAFETY: opening a thread of our process. + let handle = unsafe { + OpenThread( + THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, + 0, + tid, + ) + }; + if handle.is_null() { + continue; + } + threads.insert( + tid, + Tracked { + handle, + name: thread_name(handle, tid), + last_cpu_100ns: cpu_100ns(handle), + cpu_ms_second: BUSY_MS, + cpu_ms_report: 0, + samples: 0, + stacks: HashMap::new(), + }, + ); + } + } + if second.elapsed() >= Duration::from_secs(1) { + second = Instant::now(); + for t in threads.values_mut() { + let now = cpu_100ns(t.handle); + t.cpu_ms_second = (now - t.last_cpu_100ns.min(now)) / 10_000; + t.cpu_ms_report += t.cpu_ms_second; + t.last_cpu_100ns = now; + } + } + for t in threads.values_mut() { + if t.cpu_ms_second < BUSY_MS && !tick.is_multiple_of(25) { + continue; + } + if let Some(stack) = capture(t.handle) { + t.samples += 1; + *t.stacks.entry(stack).or_insert(0) += 1; + } + } + if reported.elapsed() >= REPORT { + let secs = reported.elapsed().as_secs_f64(); + reported = Instant::now(); + let mut list: Vec<&mut Tracked> = + threads.values_mut().filter(|t| t.samples > 0).collect(); + list.sort_by_key(|t| std::cmp::Reverse((t.cpu_ms_report, t.samples))); + for t in list.into_iter().take(10) { + tracing::info!( + "prof {}: cpu {:.0}% ({} ms), {} samples", + t.name, + t.cpu_ms_report as f64 / 10.0 / secs, + t.cpu_ms_report, + t.samples + ); + let mut stacks: Vec<_> = std::mem::take(&mut t.stacks).into_iter().collect(); + stacks.sort_by_key(|&(_, n)| std::cmp::Reverse(n)); + for (stack, n) in stacks.into_iter().take(4) { + let frames: Vec = stack + .iter() + .take_while(|&&a| a != 0) + .map(|&a| describe(a, &mut cache)) + .collect(); + tracing::info!("prof {:>4}x {}", n, frames.join(" < ")); + } + (t.cpu_ms_report, t.samples) = (0, 0); + } + for t in threads.values_mut() { + (t.cpu_ms_report, t.samples) = (0, 0); + t.stacks.clear(); + } + } + } +} diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 998ec71..e6b7360 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -131,7 +131,7 @@ fn cached( (converter.translate)(container) } -const MAGIC: &[u8; 4] = b"VSH1"; +const MAGIC: &[u8; 4] = b"VSH2"; const STAGES: [HwStage; 8] = [ HwStage::Ls, HwStage::Hs, @@ -210,6 +210,8 @@ fn encode(s: &HostShader) -> Vec { word(&mut out, slots.len() as u32); out.extend(slots); } + word(&mut out, u32::from(s.address_map)); + word(&mut out, u32::from(s.descriptor_words)); out } @@ -266,6 +268,13 @@ fn decode(bytes: &[u8]) -> Option { } let root_cbvs = r.list()?; let root_srvs = r.list()?; + let flag = |w: u32| match w { + 0 => Some(false), + 1 => Some(true), + _ => None, + }; + let address_map = flag(r.word()?)?; + let descriptor_words = flag(r.word()?)?; r.0.is_empty().then_some(HostShader { stage, dxil, @@ -274,6 +283,8 @@ fn decode(bytes: &[u8]) -> Option { static_samplers, root_cbvs, root_srvs, + address_map, + descriptor_words, }) } @@ -300,6 +311,8 @@ mod tests { ])], root_cbvs: vec![2], root_srvs: vec![0, 3], + address_map: true, + descriptor_words: true, } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 351b9a4..d992aac 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -99,6 +99,11 @@ impl Shadow { address - self.start } + /// The title memory the copy holds: its first address and length. + pub(crate) fn span(&self) -> (u64, u64) { + (self.start, self.len) + } + /// Brings `len` bytes at `address` up to date when `list` is submitted, /// and keeps the copy alive until the list is reset. pub(crate) fn refresh(self: &Arc, list: &HostList, address: u64, len: u64) { @@ -467,6 +472,23 @@ fn loose(address: u64, end: u64) -> Option> { Some(shadow) } +/// Every host copy of title memory made so far (buffers' and loose +/// windows'), for the address map. +pub(crate) fn all() -> Vec> { + let mut out: Vec> = buffers() + .values() + .filter_map(|e| e.shadow.clone()) + .collect(); + out.extend( + LOOSE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .values() + .cloned(), + ); + out +} + /// For device-removed reports: the copy of title memory whose host range /// starts closest below host GPU address `va`, and where `va` is in it. pub(crate) fn near(va: u64) -> String { diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 7322689..6d29824 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -287,17 +287,46 @@ struct Guards { protected: BTreeSet, /// Of those, the ones not written since a copy took them. clean: BTreeSet, + /// Blocks whose aliases (other views of the same pages) we made + /// read-only, so a write here opens them. + aliased: BTreeSet, } static GUARDS: Mutex = Mutex::new(Guards { protected: BTreeSet::new(), clean: BTreeSet::new(), + aliased: BTreeSet::new(), }); fn guards() -> std::sync::MutexGuard<'static, Guards> { GUARDS.lock().unwrap_or_else(|e| e.into_inner()) } +/// The runtime's answer to "which other addresses show the physical page +/// mapped at this page address" (the same page in several views). +static ALIAS_LOOKUP: std::sync::OnceLock)> = std::sync::OnceLock::new(); + +/// The runtime tells where else view memory's physical pages show: a write +/// through any of those views is a write to all of them, so guarding a +/// block guards its aliases too, and a write to one opens them all (else a +/// copy of one view keeps what it first took while the title writes the +/// page through another). +pub fn set_alias_lookup(lookup: fn(usize, &mut Vec)) { + let _ = ALIAS_LOOKUP.set(lookup); +} + +/// The blocks showing the same physical memory as `block` (not itself). +fn aliases_of(block: usize, out: &mut Vec) { + out.clear(); + if let Some(lookup) = ALIAS_LOOKUP.get() { + lookup(block * BLOCK, out); + for at in out.iter_mut() { + *at /= BLOCK; + } + out.retain(|&b| b != block); + } +} + /// For view memory: the pages of `[start, end)`'s blocks written since /// they were last guarded (all of a block's pages), guarding them again /// before the caller copies them. `None` if the memory is not a view. @@ -358,11 +387,25 @@ fn protect(g: &mut Guards, from: usize, to: usize) { }; if set(from, to) { note(g, from, to); - return; + } else { + for block in from..to { + if set(block, block + 1) { + note(g, block, block + 1); + } + } } + // Their aliases read-only too, so a write through them faults; not + // clean, though: a copy of an alias has not taken them yet. + let mut others = Vec::new(); for block in from..to { - if set(block, block + 1) { - note(g, block, block + 1); + aliases_of(block, &mut others); + for &other in &others { + if !g.protected.contains(&other) && set(other, other + 1) { + g.protected.insert(other); + } + // Both ways: a write through either opens the other. + g.aliased.insert(block); + g.aliased.insert(other); } } } @@ -376,12 +419,31 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { .range(start / BLOCK..end.div_ceil(BLOCK)) .copied() .collect(); - for &block in &blocks { - g.protected.remove(&block); + let unguard = |g: &mut Guards, block: usize| { g.clean.remove(&block); - let mut old = 0; - // SAFETY: a block we made read-only. - unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) }; + if g.protected.remove(&block) { + let mut old = 0; + // SAFETY: a block we made read-only. + unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) }; + } + }; + // A write here is a write to every view of the same pages. Only blocks + // with guarded aliases are looked up: a write range can be huge. + let aliased: Vec = g + .aliased + .range(start / BLOCK..end.div_ceil(BLOCK)) + .copied() + .collect(); + let mut others = Vec::new(); + for block in aliased { + g.aliased.remove(&block); + aliases_of(block, &mut others); + for &other in &others { + unguard(g, other); + } + } + for &block in &blocks { + unguard(g, block); } !blocks.is_empty() } @@ -409,6 +471,12 @@ pub fn title_memory_remapped(at: usize, len: usize) { g.protected.remove(&block); g.clean.remove(&block); } + let first = at / BLOCK; + let end = at.saturating_add(len).div_ceil(BLOCK); + let aliased: Vec = g.aliased.range(first..end).copied().collect(); + for block in aliased { + g.aliased.remove(&block); + } } /// Registers the handler that takes writes to guarded blocks, once, ahead @@ -614,4 +682,69 @@ mod tests { writing(top, PAGE); title_memory_remapped(top, usize::MAX); } + + #[test] + fn a_write_through_an_alias_view_is_seen_by_a_guard_on_the_other() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile, + UnmapViewOfFile, + }; + static A: AtomicUsize = AtomicUsize::new(0); + static B: AtomicUsize = AtomicUsize::new(0); + fn lookup(at: usize, out: &mut Vec) { + let (a, b) = (A.load(Ordering::Relaxed), B.load(Ordering::Relaxed)); + let page = at - at % BLOCK; + if page == a { + out.push(b); + } else if page == b { + out.push(a); + } + } + // SAFETY: one pagefile section of a block, mapped twice read-write. + let (a, b) = unsafe { + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + BLOCK as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + ( + MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, BLOCK).Value as usize, + MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, BLOCK).Value as usize, + ) + }; + assert!(a != 0 && b != 0 && a % BLOCK == 0 && b % BLOCK == 0); + A.store(a, Ordering::Relaxed); + B.store(b, Ordering::Relaxed); + set_alias_lookup(lookup); + // A copy of view `a` takes the block and guards it (and `b`). + assert_eq!(guard(a, a + BLOCK, true), Some(vec![a / PAGE])); + assert_eq!(guard(a, a + BLOCK, true), Some(vec![]), "clean"); + // The title writes the page through `b`: `a` shows it written. + // SAFETY: our view; the guard's handler opens it. + unsafe { ((b + 8) as *mut u8).write_volatile(7) }; + // SAFETY: the same byte through the other view. + assert_eq!(unsafe { ((a + 8) as *const u8).read_volatile() }, 7); + assert_eq!( + guard(a, a + BLOCK, true), + Some(vec![a / PAGE]), + "written through the alias" + ); + // And the other way round: a kernel write into `a` opens `b`. + assert_eq!(guard(b, b + BLOCK, true), Some(vec![b / PAGE])); + assert_eq!(guard(b, b + BLOCK, true), Some(vec![])); + writing(a + 16, 4); + assert_eq!(guard(b, b + BLOCK, true), Some(vec![b / PAGE])); + A.store(0, Ordering::Relaxed); + B.store(0, Ordering::Relaxed); + for v in [a, b] { + // SAFETY: our views. + unsafe { UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: v as *mut _ }) }; + title_memory_remapped(v, BLOCK); + } + } } diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index a441c91..0734e75 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -384,6 +384,65 @@ fn physical() -> MutexGuard<'static, Physical> { PHYSICAL.lock().unwrap_or_else(|e| e.into_inner()) } +/// Every address a physical page shows at, and the page each mapped +/// address shows, for the GPU side's write guards (`victory_gpu` +/// `set_alias_lookup`): the title writes a page through one view (a pool) +/// while the GPU reads it through another (its tiled heap, `map_alias`), +/// and a read-only guard on one view does not see writes through the +/// other. Its lock is taken last (inside `PHYSICAL` and the guards' lock) +/// and nothing is called while it is held. +#[derive(Default)] +struct Aliases { + /// (section, page index) to the addresses showing it. + by_page: HashMap<(usize, usize), Vec>, + /// Address to (section, page index). + by_address: HashMap, +} + +static ALIASES: LazyLock> = LazyLock::new(Mutex::default); + +fn aliases() -> MutexGuard<'static, Aliases> { + ALIASES.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Notes `[base, base + len)` as showing `slice` and the slices after it +/// (`shown`), or as no longer showing them. +fn note_aliases(base: usize, len: usize, slice: &Slice, shown: bool) { + let section = Arc::as_ptr(&slice.section) as usize; + let mut a = aliases(); + for k in 0..len / PAGE { + let (at, key) = (base + k * PAGE, (section, slice.index + k)); + if shown { + if let Some(old) = a.by_address.insert(at, key) + && let Some(list) = a.by_page.get_mut(&old) + { + list.retain(|&x| x != at); + } + a.by_page.entry(key).or_default().push(at); + } else if a.by_address.get(&at) == Some(&key) { + a.by_address.remove(&at); + if let Some(list) = a.by_page.get_mut(&key) { + list.retain(|&x| x != at); + if list.is_empty() { + a.by_page.remove(&key); + } + } + } + } +} + +/// The other addresses showing the physical page mapped at page address +/// `at` (`victory_gpu`'s write guards). +fn other_views(at: usize, out: &mut Vec) { + let page = at - at % PAGE; + let a = aliases(); + if let Some(key) = a.by_address.get(&page) + && let Some(list) = a.by_page.get(key) + { + out.extend(list.iter().copied().filter(|&x| x != page)); + } +} + /// `count` is in and out (pages wanted, pages given); all or nothing here. pub extern "system" fn XMemAllocatePhysicalPages( flags: u64, @@ -728,6 +787,9 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { } // New contents, read-write: the GPU side's copies no longer guard it. victory_gpu::title_memory_remapped(base, len); + static LOOKUP: std::sync::Once = std::sync::Once::new(); + LOOKUP.call_once(|| victory_gpu::set_alias_lookup(other_views)); + note_aliases(base, len, &slice, true); physical.views.insert(base, (len, slice)); true } @@ -807,6 +869,7 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { continue; }; victory_gpu::title_memory_remapped(at, size); + note_aliases(at, size, &slice, false); // SAFETY: a view we mapped; it becomes a placeholder again. unsafe { UnmapViewOfFile2( diff --git a/crates/victory-shader/src/emit/address_map.rs b/crates/victory-shader/src/emit/address_map.rs new file mode 100644 index 0000000..ef3ee7e --- /dev/null +++ b/crates/victory-shader/src/emit/address_map.rs @@ -0,0 +1,61 @@ +//! The address map: how a translated shader finds title memory at an +//! address it computes ([`crate::resource::GLOBAL`]), for the host to fill. +//! +//! A raw buffer bound as a root SRV, `t0` in +//! [`super::ADDRESS_MAP_SPACE`], when [`super::HostShader::address_map`] +//! is set: +//! +//! * a header of [`HEADER`] bytes: dword 0 is the number of ranges `n`, the +//! rest zero; +//! * then `n` entries of [`ENTRY`] bytes, sorted by start address and not +//! overlapping: the range's first title address (dwords 0 and 1, low +//! first), its length in bytes (dword 2), the descriptor heap index of a +//! raw UAV view (`R32_TYPELESS`, raw flag) holding its bytes (dword 3), +//! and the byte offset of the range's first byte in that view (dword 4); +//! dwords 5 to 7 are zero. +//! +//! The shader finds the last range starting at or below an address with a +//! binary search and reads through `ResourceDescriptorHeap[view]` (a +//! non-uniform index when lanes differ), so the views must be in the heap +//! bound with the map. An address no range covers reads zero. Root +//! descriptors are not bounds-checked: the buffer must hold all `n` +//! entries. + +/// Bytes before the first entry. +pub const HEADER: u32 = 16; +/// Bytes per entry. +pub const ENTRY: u32 = 32; + +/// One range of title memory and the view that holds it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Range { + pub start: u64, + pub len: u32, + pub view: u32, + pub view_offset: u32, +} + +/// The map's dwords for `ranges`, which must be sorted by start and not +/// overlap. +pub fn encode(ranges: &[Range]) -> Vec { + debug_assert!( + ranges + .windows(2) + .all(|w| w[0].start + u64::from(w[0].len) <= w[1].start) + ); + let mut out = vec![0; (HEADER / 4) as usize]; + out[0] = ranges.len() as u32; + for r in ranges { + out.extend([ + r.start as u32, + (r.start >> 32) as u32, + r.len, + r.view, + r.view_offset, + 0, + 0, + 0, + ]); + } + out +} diff --git a/crates/victory-shader/src/emit/bvh_tests.rs b/crates/victory-shader/src/emit/bvh_tests.rs new file mode 100644 index 0000000..1b1ba26 --- /dev/null +++ b/crates/victory-shader/src/emit/bvh_tests.rs @@ -0,0 +1,608 @@ +//! The ray intersection emulation (`lower/bvh.rs`) and title memory through +//! the address map (`lower/global.rs`), against a CPU model of the +//! instruction: Microsoft's software model in the XDXR traversal headers +//! (`SoftwareBvhIntersectRay`, `TestXboxBvh4Node`, `TestXboxBvh4Leaf`), +//! transcribed. On a GPU, a program reads rays through the map, tests +//! them against hand-built nodes and stores the results through the map. + +const INF: u32 = 0x7F80_0000; +const ONE: u32 = 0x3F80_0000; +const INVALID: u32 = u32::MAX; + +#[derive(Debug, Clone, Copy)] +struct Ray { + origin: [f32; 3], + dir: [f32; 3], + inv: [f32; 3], + extent: f32, +} + +impl Ray { + fn new(origin: [f32; 3], dir: [f32; 3], extent: f32) -> Ray { + Ray { + origin, + dir, + inv: dir.map(|d| 1.0 / d), + extent, + } + } +} + +/// HLSL's min and max: a NaN operand gives the other. +fn min(a: f32, b: f32) -> f32 { + if a.is_nan() || b < a { b } else { a } +} + +fn max(a: f32, b: f32) -> f32 { + if a.is_nan() || b > a { b } else { a } +} + +fn half(h: u32) -> f32 { + let h = h & 0xFFFF; + let sign = if h >> 15 != 0 { -1.0 } else { 1.0 }; + let (e, m) = ((h >> 10) & 0x1F, h & 0x3FF); + match e { + 0 => sign * m as f32 * (2f32).powi(-24), + 31 => f32::from_bits((h >> 15) << 31 | 0x7F80_0000 | m << 13), + _ => f32::from_bits((h >> 15) << 31 | (e + 112) << 23 | m << 13), + } +} + +fn ray_box(r: &Ray, lo: [f32; 3], hi: [f32; 3]) -> f32 { + if (0..3).any(|i| lo[i] > hi[i]) { + return f32::INFINITY; + } + let (mut near, mut far) = (0.0f32, r.extent); + for i in 0..3 { + if r.dir[i] == 0.0 { + if r.origin[i] < lo[i] || r.origin[i] > hi[i] { + return f32::INFINITY; + } + } else { + let t1 = (lo[i] - r.origin[i]) * r.inv[i]; + let t2 = (hi[i] - r.origin[i]) * r.inv[i]; + near = max(near, min(t1, t2)); + far = min(far, max(t1, t2)); + if far < near { + return f32::INFINITY; + } + } + } + near +} + +fn test_box(n: &[u32], small: bool, r: &Ray, sort: bool) -> [u32; 4] { + let f = |w: u32| f32::from_bits(w); + let clamp = |x: f32| max(min(x, f32::MAX), -f32::MAX); + let mut d = [0.0f32; 4]; + let mut p = [n[0], n[1], n[2], n[3]]; + for k in 0..4 { + let (lo, hi) = if small { + let w = [n[4 + 3 * k], n[5 + 3 * k], n[6 + 3 * k]]; + ( + [half(w[0]), half(w[0] >> 16), half(w[1])].map(clamp), + [half(w[1] >> 16), half(w[2]), half(w[2] >> 16)].map(clamp), + ) + } else { + let b = &n[4 + 6 * k..]; + ([f(b[0]), f(b[1]), f(b[2])], [f(b[3]), f(b[4]), f(b[5])]) + }; + d[k] = ray_box(r, lo, hi); + if d[k].is_nan() || d[k] > r.extent { + p[k] = INVALID; + } + } + if sort { + for (x, y) in [(0, 2), (1, 3), (0, 1), (2, 3), (1, 2)] { + if d[x] > d[y] { + d.swap(x, y); + p.swap(x, y); + } + } + } + p +} + +const TRIANGLES: [[usize; 3]; 4] = [[0, 1, 2], [1, 3, 2], [2, 3, 4], [2, 4, 0]]; + +fn yzx(v: [f32; 3]) -> [f32; 3] { + [v[1], v[2], v[0]] +} + +fn zxy(v: [f32; 3]) -> [f32; 3] { + [v[2], v[0], v[1]] +} + +fn break_tie(ay: f32, by: f32, cy: f32, winding: bool, missed: &mut bool) { + if by.abs() == 0.0 && cy.abs() == 0.0 { + *missed |= ay > 0.0; + } else { + let below = by < 0.0 || (by.abs() == 0.0 && cy > 0.0); + *missed |= below ^ winding; + } +} + +fn test_leaf(n: &[u32], tri: usize, r: &Ray, ij: bool) -> [u32; 4] { + let vert = |k: usize| [0, 1, 2].map(|j| f32::from_bits(n[3 * k + j])); + let [ia, ib, ic] = TRIANGLES[tri]; + let (mut v0, mut v1, mut v2) = (vert(ia), vert(ib), vert(ic)); + let remap = n[15] >> (8 * tri); + let (mut dir, mut origin) = (r.dir, r.origin); + let mag = dir.map(f32::abs); + let m = max(mag[0], max(mag[1], mag[2])); + let sw: Option [f32; 3]> = if mag[0] == m { + Some(yzx) + } else if mag[1] == m { + Some(zxy) + } else { + None + }; + if let Some(s) = sw { + (dir, origin, v0, v1, v2) = (s(dir), s(origin), s(v0), s(v1), s(v2)); + } + let sub = |a: [f32; 3]| [a[0] - origin[0], a[1] - origin[1], a[2] - origin[2]]; + let (v0, v1, v2) = (sub(v0), sub(v1), sub(v2)); + let shear = |v: [f32; 3]| { + [ + v[0] * dir[2] - dir[0] * v[2], + v[1] * dir[2] - dir[1] * v[2], + v[2], + ] + }; + let (a, b, c) = (shear(v0), shear(v1), shear(v2)); + let u = c[0] * b[1] - c[1] * b[0]; + let v = a[0] * c[1] - a[1] * c[0]; + let w = b[0] * a[1] - b[1] * a[0]; + let t_num = u * a[2] + v * b[2] + w * c[2]; + let t_den = u * dir[2] + v * dir[2] + w * dir[2]; + let mut missed = (u < 0.0 || v < 0.0 || w < 0.0) && (u > 0.0 || v > 0.0 || w > 0.0); + missed |= t_den.abs() == 0.0; + missed |= t_num * f32::from_bits(t_den.to_bits() & 0x8000_0000 | ONE) <= 0.0; + missed |= t_num.is_nan(); + let winding = t_den > 0.0; + if u.abs() == 0.0 { + break_tie(a[1], b[1], c[1], winding, &mut missed); + } + if v.abs() == 0.0 { + break_tie(b[1], c[1], a[1], winding, &mut missed); + } + if w.abs() == 0.0 { + break_tie(c[1], a[1], b[1], winding, &mut missed); + } + if missed { + return [INF, ONE, 0, 0]; + } + let pick = |s: u32| match s & 3 { + 1 => v, + 2 => w, + _ => u, + }; + let (mut i, mut j) = (pick(remap), pick(remap >> 2)); + if (i < 0.0 && t_den > 0.0) || (i > 0.0 && t_den < 0.0) { + (i, j) = (-i, -j); + } + if ij { + [t_num.to_bits(), t_den.to_bits(), i.to_bits(), j.to_bits()] + } else { + [t_num.to_bits(), t_den.to_bits(), n[15], 1] + } +} + +/// The model of `image_bvh_intersect_ray` on `node` (a pointer into +/// `bvh`, a buffer of dwords at the descriptor's base). +fn intersect(bvh: &[u32], node: u32, r: &Ray, sort: bool, ij: bool) -> [u32; 4] { + let at = ((node >> 3) * 16) as usize; + let mut n = bvh[at..].to_vec(); + n.resize(28, 0); + match node & 7 { + t @ 0..=3 => test_leaf(&n, t as usize, r, ij), + t => test_box(&n, t == 4, r, sort), + } +} + +fn f3(v: [f32; 3]) -> [u32; 3] { + v.map(f32::to_bits) +} + +/// Six halves of a box: min x y, min z max x, max y z. +fn box16(lo: [f32; 3], hi: [f32; 3]) -> [u32; 3] { + let h = |x: f32| -> u32 { + // Exact for the small dyadic values the tests use. + let b = x.to_bits(); + if x == 0.0 { + return (b >> 16) & 0x8000; + } + let e = ((b >> 23) & 0xFF) as i32 - 127 + 15; + assert!( + (1..31).contains(&e) && b & 0x1FFF == 0, + "{x} is no exact half" + ); + (b >> 16) & 0x8000 | (e as u32) << 10 | (b >> 13) & 0x3FF + }; + [ + h(lo[0]) | h(lo[1]) << 16, + h(lo[2]) | h(hi[0]) << 16, + h(hi[1]) | h(hi[2]) << 16, + ] +} + +/// The test BVH: a leaf (unit 0), a float box node (units 2-3) and a +/// half box node (unit 4), with their pointers. +fn scene() -> (Vec, [u32; 4], u32, u32) { + let mut bvh = vec![0u32; 16 * 6]; + let verts: [[f32; 3]; 5] = [ + [0.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [1.0, 1.0, 0.0], + [0.0, 0.0, 1.0], + ]; + for (k, v) in verts.iter().enumerate() { + bvh[3 * k..3 * k + 3].copy_from_slice(&f3(*v)); + } + // TRI0 i=V j=W, TRI1 i=W j=U, TRI2 i=U j=V, TRI3 i=V j=U. + bvh[15] = 0x09 | 0x02 << 8 | 0x04 << 16 | 0x01 << 24; + let boxes: [([f32; 3], [f32; 3]); 4] = [ + ([0.0, 0.0, -3.0], [1.0, 1.0, -2.0]), + ([0.0, 0.0, -1.0], [1.0, 1.0, 0.0]), + // Inverted: never hit. + ([1.0, 1.0, 1.0], [0.0, 0.0, 0.0]), + ([0.0, 0.0, -6.0], [1.0, 1.0, -5.0]), + ]; + let children = [0x105, 0x204, 0x300, 0x401]; + let full = 2 * 16; + bvh[full..full + 4].copy_from_slice(&children); + for (k, (lo, hi)) in boxes.iter().enumerate() { + let b = full + 4 + 6 * k; + bvh[b..b + 3].copy_from_slice(&f3(*lo)); + bvh[b + 3..b + 6].copy_from_slice(&f3(*hi)); + } + let small = 4 * 16; + bvh[small..small + 4].copy_from_slice(&children); + for (k, (lo, hi)) in boxes.iter().enumerate() { + let b = small + 4 + 3 * k; + bvh[b..b + 3].copy_from_slice(&box16(*lo, *hi)); + } + let leaf = [0, 1, 2, 3]; + (bvh, leaf, (2 << 3) | 5, (4 << 3) | 4) +} + +/// 32 (node, ray) cases: every triangle, shared edges, parallel and +/// backward rays, back faces, both box kinds with sorting, a short extent +/// and misses, then seeded random rays at the boxes. +fn cases() -> Vec<(u32, Ray)> { + let (_, tri, full, small) = scene(); + let down = |x, y| Ray::new([x, y, 5.0], [0.0, 0.0, -1.0], 100.0); + let mut c = vec![ + (tri[0], down(0.25, 0.25)), + (tri[1], down(0.25, 0.25)), + (tri[0], down(0.75, 0.75)), + (tri[1], down(0.75, 0.75)), + // On the edge TRI0 and TRI1 share: exactly one owns it. + (tri[0], down(0.5, 0.5)), + (tri[1], down(0.5, 0.5)), + (tri[2], down(0.25, 0.5)), + (tri[3], Ray::new([-1.0, 0.25, 0.25], [1.0, 0.0, 0.0], 100.0)), + // In the triangle's plane, and moving away from it. + (tri[0], Ray::new([-1.0, 0.25, 0.0], [1.0, 0.0, 0.0], 100.0)), + ( + tri[0], + Ray::new([0.25, 0.25, -5.0], [0.0, 0.0, -1.0], 100.0), + ), + // From below: the back face. + (tri[0], Ray::new([0.25, 0.25, -5.0], [0.0, 0.0, 1.0], 100.0)), + ( + tri[1], + Ray::new([0.5, 0.25, 4.0], [0.125, 0.25, -1.0], 100.0), + ), + (full, down(0.5, 0.5)), + (full, Ray::new([0.5, 0.5, 5.0], [0.0, 0.0, -1.0], 6.0)), + (full, down(1.5, 0.5)), + (full, Ray::new([0.5, 0.5, -2.5], [1.0, 0.0, 0.0], 100.0)), + (small, down(0.5, 0.5)), + (small, Ray::new([0.5, 0.5, 5.0], [0.0, 0.0, -1.0], 6.0)), + (small, down(1.5, 0.5)), + (small, Ray::new([0.5, 0.5, -2.5], [1.0, 0.0, 0.0], 100.0)), + ]; + let mut seed = 0x1234_5678u32; + let mut rand = || { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 8) as f32 / (1u32 << 24) as f32 * 4.0 - 2.0 + }; + while c.len() < 32 { + let node = if c.len() % 2 == 0 { full } else { small }; + // Over the boxes' footprint (x, y in [0, 1]), give or take. + let origin = [0.5 + rand() * 0.35, 0.5 + rand() * 0.35, rand() + 4.0]; + let dir = [rand() * 0.25, rand() * 0.25, -1.0 - rand().abs()]; + c.push((node, Ray::new(origin, dir, 2.0 + rand().abs() * 4.0))); + } + c +} + +#[test] +fn model_hits_and_orders_as_expected() { + let (bvh, tri, full, _) = scene(); + let r = Ray::new([0.25, 0.25, 5.0], [0.0, 0.0, -1.0], 100.0); + let hit = intersect(&bvh, tri[0], &r, true, true); + let t = f32::from_bits(hit[0]) / f32::from_bits(hit[1]); + assert_eq!(t, 5.0); + assert_eq!(intersect(&bvh, tri[1], &r, true, true), [INF, ONE, 0, 0]); + // Barycentrics: TRI0 remaps i to V, j to W. + let (i, j) = ( + f32::from_bits(hit[2]) / f32::from_bits(hit[1]), + f32::from_bits(hit[3]) / f32::from_bits(hit[1]), + ); + assert!( + (i - 0.25).abs() < 1e-6 && (j - 0.25).abs() < 1e-6, + "{i} {j}" + ); + let mid = Ray::new([0.5, 0.5, 5.0], [0.0, 0.0, -1.0], 100.0); + let owners = [tri[0], tri[1]] + .iter() + .filter(|&&n| intersect(&bvh, n, &mid, true, true)[0] != INF) + .count(); + assert_eq!(owners, 1, "a shared edge belongs to one triangle"); + let mid = Ray::new([0.5, 0.5, 5.0], [0.0, 0.0, -1.0], 100.0); + assert_eq!( + intersect(&bvh, full, &mid, true, true), + [0x204, 0x105, 0x401, INVALID] + ); + assert_eq!( + intersect(&bvh, full, &mid, false, true), + [0x105, 0x204, INVALID, 0x401] + ); +} + +#[test] +fn the_cases_cover_hits_misses_and_boxes() { + let (bvh, ..) = scene(); + let (mut hits, mut misses, mut box_hits, mut box_misses) = (0, 0, 0, 0); + for (node, r) in cases() { + let got = intersect(&bvh, node, &r, true, true); + match (node & 7 > 3, got[0] == INF || got == [INVALID; 4]) { + (false, false) => hits += 1, + (false, true) => misses += 1, + (true, false) => box_hits += 1, + (true, true) => box_misses += 1, + } + } + assert!(hits >= 5 && misses >= 4, "{hits} hits, {misses} misses"); + assert!( + box_hits >= 10 && box_misses >= 2, + "{box_hits} box hits, {box_misses} misses" + ); +} + +#[cfg(windows)] +mod gpu { + use super::super::host::{Dispatch, Host, Root, View}; + use super::super::{HostShader, address_map, lower, validator}; + use super::*; + use crate::native::{ComputeIo, HwStage, NativeProgram, RootParam, RootType, StageIo}; + use crate::{io, ir, resource, structure}; + + const RAYS: u64 = 0x1_0000_0000; + const BVH: u64 = 0x2_0000_0100; + const OUT: u64 = 0x3_0000_0000; + + /// Per lane: 12 dwords of ray at `s[0:1] + 48 * lane` (node, extent, + /// origin, direction, inverse direction), the intersection with the + /// descriptor `s[4:7]`, 4 dwords stored at `s[2:3] + 16 * lane`. + fn program() -> Vec { + let load = |vdst: u32, offset: u32| [0xDC38_8000 | offset, vdst << 24 | 1]; + let mut w = vec![ + 0x1602_00B0, // v_mul_u32_u24 v1, 48, v0 + ]; + w.extend(load(2, 0)); // global_load_dwordx4 v[2:5], v1, s[0:1] + w.extend(load(6, 16)); // ... v[6:9], offset:16 + w.extend(load(10, 32)); // ... v[10:13], offset:32 + w.extend([ + 0xF198_9F01, // image_bvh_intersect_ray v[14:17], v[2:12], s[4:7] + 0x0001_0E02, + 0x3402_0084, // v_lshlrev_b32 v1, 4, v0 + 0xDC78_8000, // global_store_dwordx4 v1, v[14:17], s[2:3] + 0x0002_0E01, + 0xBF81_0000, // s_endpgm + ]); + let names: Vec<_> = + crate::gfx10::decode(&w.iter().flat_map(|x| x.to_le_bytes()).collect::>()) + .expect("decode") + .iter() + .map(|i| i.name().unwrap_or("?")) + .collect(); + assert_eq!( + names, + [ + "v_mul_u32_u24", + "global_load_dwordx4", + "global_load_dwordx4", + "global_load_dwordx4", + "image_bvh_intersect_ray", + "v_lshlrev_b32", + "global_store_dwordx4", + "s_endpgm" + ] + ); + w + } + + fn build() -> HostShader { + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 32, + layout: vec![RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 8, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: Vec::new(), + io: StageIo::Cs(ComputeIo { + rsrc2: 8 << 1, + threads: [32, 1, 1], + }), + code: program().iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); + assert!(res.scalar.iter().all(|s| s.1.param == resource::GLOBAL)); + let io = io::raise(&p, &native).expect("io::raise"); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower"); + assert!(lowered.address_map); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + address_map: lowered.address_map, + descriptor_words: lowered.descriptor_words, + }; + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } else { + eprintln!("no dxil.dll; validation skipped"); + } + shader + } + + fn close(a: f32, b: f32) -> bool { + (a - b).abs() <= 1e-5 * a.abs().max(b.abs()).max(1.0) + } + + #[test] + fn bvh_intersection_matches_the_model_on_the_gpu() { + let shader = build(); + let (bvh, ..) = scene(); + let cases = cases(); + let rays: Vec = cases + .iter() + .flat_map(|(node, r)| { + let mut w = vec![*node, r.extent.to_bits()]; + w.extend(f3(r.origin)); + w.extend(f3(r.dir)); + w.extend(f3(r.inv)); + w.push(0); + w + }) + .collect(); + let map = address_map::encode(&[ + address_map::Range { + start: RAYS, + len: rays.len() as u32 * 4, + view: 0, + view_offset: 0, + }, + address_map::Range { + start: BVH, + len: bvh.len() as u32 * 4, + view: 1, + view_offset: 0, + }, + address_map::Range { + start: OUT, + len: 32 * 16, + view: 2, + view_offset: 0, + }, + ]); + let _one = super::super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + 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 (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{label}: {e}")); + for (sort, ij) in [(true, true), (false, false)] { + let base = BVH >> 8; + let desc = [ + base as u32, + (base >> 32) as u32 & 0xFF | u32::from(sort) << 31, + u32::MAX, + 0x88FF_FFFF | u32::from(ij) << 24, + ]; + let consts = [ + RAYS as u32, + (RAYS >> 32) as u32, + OUT as u32, + (OUT >> 32) as u32, + desc[0], + desc[1], + desc[2], + desc[3], + ]; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = consts[u.dword as usize]; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(ud)), + ( + 1, + Root::View { + srv: true, + data: map.clone(), + }, + ), + ], + views: &[View::RawData(&rays), View::RawData(&bvh), View::RawUav(128)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: {e}")); + let got = &out[2]; + for (lane, (node, r)) in cases.iter().enumerate() { + let want = intersect(&bvh, *node, r, sort, ij); + let g = &got[4 * lane..4 * lane + 4]; + let what = format!( + "{label} sort={sort} ij={ij} lane {lane} node {node:#x}: got {g:x?}, want {want:x?}" + ); + if node & 7 > 3 || want[0] == INF { + assert_eq!(g, want, "{what}"); + continue; + } + assert_ne!(g[0], INF, "{what}"); + let f = |x: u32| f32::from_bits(x); + let (gd, wd) = (f(g[1]), f(want[1])); + assert!(close(f(g[0]) / gd, f(want[0]) / wd), "{what}: t"); + if ij { + assert!(close(f(g[2]) / gd, f(want[2]) / wd), "{what}: i"); + assert!(close(f(g[3]) / gd, f(want[3]) / wd), "{what}: j"); + } else { + assert_eq!(g[2..], want[2..], "{what}"); + } + } + } + } + } +} diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index dabd4a4..4f41295 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -158,6 +158,31 @@ impl Host { ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }); } + // The address map, then the descriptor words, come last. + for (wanted, space) in [ + ( + stages.iter().any(|(s, _)| s.address_map), + super::ADDRESS_MAP_SPACE, + ), + ( + stages.iter().any(|(s, _)| s.descriptor_words), + super::DESCRIPTOR_WORDS_SPACE, + ), + ] { + if wanted { + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, + RegisterSpace: space, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + } + } let mut samplers = Vec::new(); for &(s, vis) in stages { for (n, d) in s.static_samplers.iter().enumerate() { @@ -528,6 +553,8 @@ fn stub(pixel: bool, outputs: Vec) -> HostShader { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + address_map: false, + descriptor_words: false, } } @@ -914,6 +941,8 @@ pub enum View<'a> { Cube(u32, &'a [[f32; 4]]), /// A raw buffer UAV of this many dwords, zeroed. RawUav(u32), + /// A raw buffer UAV holding these dwords (read back like `RawUav`). + RawData(&'a [u32]), /// An RGBA32F texture UAV (width, height), zeroed. TextureUav(u32, u32), /// An R32_UINT texture UAV (width, height), zeroed (atomics). @@ -1152,7 +1181,7 @@ impl Host { ); keep.push(tex); } - View::RawUav(_) | View::HalfUav(_) => { + View::RawUav(_) | View::HalfUav(_) | View::RawData(_) => { // (dwords, format, elements, flags) let (n, format, elements, flags) = match *v { View::HalfUav(e) => ( @@ -1164,6 +1193,10 @@ impl Host { View::RawUav(n) => { (n, DXGI_FORMAT_R32_TYPELESS, n, D3D12_BUFFER_UAV_FLAG_RAW) } + View::RawData(d) => { + let n = d.len() as u32; + (n, DXGI_FORMAT_R32_TYPELESS, n, D3D12_BUFFER_UAV_FLAG_RAW) + } _ => unreachable!(), }; let bytes = u64::from(n) * 4; @@ -1184,6 +1217,17 @@ impl Host { }, }; dev.CreateUnorderedAccessView(&b, None, Some(&desc), at); + if let View::RawData(d) = *v { + // The copy promotes the buffer to a copy target. + let up = upload(d)?; + list.CopyBufferRegion(&b, 0, &up, 0, bytes); + list.ResourceBarrier(&[transition( + &b, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + keep.push(up); + } let rb = make( D3D12_HEAP_TYPE_READBACK, &buffer(bytes, D3D12_RESOURCE_FLAG_NONE), diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index eb2e9a3..4cb536f 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -22,6 +22,9 @@ use crate::structure::{Atom, Bool, LaneExit, Structured}; type Why = &'static str; +mod bvh; +mod global; + #[derive(Debug, Clone, Copy)] enum Val { I32(V), @@ -35,6 +38,10 @@ pub(crate) struct Lowered { pub cmp_samplers: u64, pub root_cbvs: Vec, pub root_srvs: Vec, + /// Reads title memory through the address map. + pub address_map: bool, + /// Reads descriptor words. + pub descriptor_words: bool, pub user_data: Vec, pub samplers: Vec<[u32; 4]>, /// Heap handles made with a non-uniform index. @@ -173,7 +180,7 @@ struct Lower<'a> { scalar: HashMap, exports: HashMap, interps: HashMap, - handles: HashMap<(usize, Site, u8, bool, u32), V>, + handles: HashMap<(usize, Site, u8, bool, u32, u32), V>, /// Blocks splitting the edge from one IR block to another. edges: HashMap<(usize, usize), usize>, /// Per IR block: a `done` export is behind every lane entering it. @@ -360,8 +367,10 @@ impl<'a> Lower<'a> { s.outputs = x.outputs.clone(); let insts = || p.blocks.iter().flat_map(|b| &b.insts); let writes_uavs = insts().any(|i| { - matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. }) - && (i.name().contains("store") || i.name().contains("atomic")) + matches!( + i.fields, + Fields::Image { .. } | Fields::Buffer { .. } | Fields::Flat { .. } + ) && (i.name().contains("store") || i.name().contains("atomic")) }); let mut console_lanes = false; if let StageIo::Cs(cs) = x.native.io { @@ -589,6 +598,17 @@ impl<'a> Lower<'a> { unreachable!() }; let name = inst.name(); + if self.is_global((b, i)) { + return if name.starts_with("global_load_") { + self.global_load(inst, b, i) + } else if name.starts_with("global_store_") { + self.global_store(inst, b, i) + } else if name.starts_with("global_atomic_") { + self.global_atomic(inst, b, i) + } else { + Err("a global access to title memory") + }; + } let rest = name .strip_prefix("global_load_") .ok_or("a global memory write")?; @@ -907,10 +927,14 @@ impl<'a> Lower<'a> { let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect(); let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect(); let cmp_samplers = self.s.cmp_samplers; + let address_map = self.s.address_map.is_some(); + let descriptor_words = self.s.descriptor_words.is_some(); Ok(Lowered { cmp_samplers, root_cbvs, root_srvs, + address_map, + descriptor_words, #[cfg(test)] nonuniform_handles: self.s.nonuniform_handles, #[cfg(test)] @@ -2300,6 +2324,7 @@ impl<'a> Lower<'a> { Fields::Valu(_) if name.starts_with("v_interp_") => self.interp(inst, (b, i)), Fields::Valu(_) => self.valu(inst, b, i), Fields::Vintrp { .. } => self.interp(inst, (b, i)), + Fields::Image { .. } if name.starts_with("image_bvh") => self.bvh(inst, b, i), Fields::Image { .. } => self.image(inst, b, i), Fields::Buffer { .. } => self.buffer(inst, b, i), Fields::Exp { .. } => self.export(b, i), @@ -2814,6 +2839,9 @@ impl<'a> Lower<'a> { if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) { return self.code_smem(inst, a); } + if self.is_global(site) { + return self.global_smem(inst); + } let Some(rest) = name.strip_prefix("s_buffer_load_dword") else { return self.descriptor_data(inst, site); }; @@ -2962,7 +2990,12 @@ impl<'a> Lower<'a> { }) }); let Some((at, first)) = use_at else { - return Err("a descriptor read only as data"); + // No access names it: the console words are all there is. + let words = self.descriptor_words(site, count)?; + for (k, x) in words.into_iter().enumerate() { + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); }; let src = Source::Loaded { load: site, first }; let used = self.used_kind(&src); @@ -3054,11 +3087,15 @@ impl<'a> Lower<'a> { } None => vec![(2, field(self, 0))], }; + // Fields the host view gives are rebuilt from it; the console's + // other words (addresses, formats) come from the descriptor words. + let console = self.descriptor_words(site, count).ok(); for k in 0..count { let rel = k.wrapping_sub(u32::from(first)); - match words.iter().find(|w| w.0 == rel) { - Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None), - None => { + match (words.iter().find(|w| w.0 == rel), &console) { + (Some(&(_, x)), _) => self.write(inst, Reg::S(code + k as u8), x, None), + (None, Some(c)) => self.write(inst, Reg::S(code + k as u8), c[k as usize], None), + (None, None) => { if let Some(v) = inst.write(Reg::S(code + k as u8)) { self.vals.insert(v, Val::Missing(OTHER)); } @@ -3313,7 +3350,7 @@ impl<'a> Lower<'a> { ) -> Result { match src { Source::Loaded { load, first } => { - let key = (self.cur, *load, *first, sampler, props.0); + let key = (self.cur, *load, *first, sampler, props.0, props.1); if let Some(&h) = self.handles.get(&key) { return Ok(h); } @@ -5679,11 +5716,11 @@ impl<'a> Lower<'a> { return Err("a 16-bit image atomic"); } // dmask: the data dwords (cmpswap: twice the value's). - // shortcut: 64-bit image atomics (two dwords, an R32G32 view) - // need the host's 64-bit typed atomics; they stop the program. - if *dmask != if code == u32::MAX { 3 } else { 1 } { - return Err("a 64-bit image atomic"); - } + let is_64 = match (code == u32::MAX, *dmask) { + (false, 1) | (true, 3) => false, + (false, 3) | (true, 0xF) => true, + _ => return Err("an unsupported image atomic dmask"), + }; let iu = self.s.m.undef(self.s.t.i32); let mut cs = vec![iu; 3]; for (k, slot) in cs.iter_mut().enumerate().take(coords) { @@ -5692,8 +5729,78 @@ impl<'a> Lower<'a> { let Operand::Vector { reg, .. } = *data else { return Err("image atomic data"); }; + let h = self.handle( + site, + src, + false, + (kind | 0x1000, if is_64 { 0x107 } else { 0x105 }), + )?; + let at = self.begin_guarded(guard); + if is_64 { + let i64t = self.s.m.int(64); + self.s.flags |= flags::INT64 | flags::ATOMIC_INT64_ON_TYPED_RESOURCE; + if self.s.flags & flags::RESOURCE_HEAP != 0 { + self.s.flags |= flags::ATOMIC_INT64_ON_HEAP_RESOURCE; + } + let pack64 = |s: &mut Self, lo: V, hi: V| { + let lo = s.s.m.cast(c, Cast::ZExt, lo, i64t); + let hi = s.s.m.cast(c, Cast::ZExt, hi, i64t); + let k32 = s.s.m.int_const(i64t, 32); + let hi = s.s.m.bin(c, Bin::Shl, hi, k32); + s.s.m.bin(c, Bin::Or, lo, hi) + }; + let old = if cache.glc { + let lo = match inst.read(Reg::V(reg)) { + Some(v) => self.i32_of(v)?, + None => self.s.m.i32(0), + }; + let hi = match inst.read(Reg::V(reg + 1)) { + Some(v) => self.i32_of(v)?, + None => self.s.m.i32(0), + }; + pack64(self, lo, hi) + } else { + self.s.m.int_const(i64t, 0) + }; + let vals = self.vgprs(inst, data, if code == u32::MAX { 4 } else { 2 })?; + let mut args = vec![h]; + let op_res = if code == u32::MAX { + // cmpswap: data is (new, compare). + let new_val = pack64(self, vals[0], vals[1]); + let cmp_val = pack64(self, vals[2], vals[3]); + args.extend(cs); + args.extend([cmp_val, new_val]); + self.s.op( + self.cur, + "atomicCompareExchange.i64", + Attr::NoUnwind, + i64t, + 79, + &args, + ) + } else { + let mut value = pack64(self, vals[0], vals[1]); + if op == "sub" { + let z = self.s.m.int_const(i64t, 0); + value = self.s.m.bin(c, Bin::Sub, z, value); + } + args.push(self.s.m.i32(code)); + args.extend(cs); + args.push(value); + self.s + .op(self.cur, "atomicBinOp.i64", Attr::NoUnwind, i64t, 78, &args) + }; + let res = self.end_guarded(at, &[(op_res, old)])[0]; + if cache.glc { + let (lo, hi) = self.split64(res); + self.write(inst, Reg::V(reg), lo, None); + self.write(inst, Reg::V(reg + 1), hi, None); + } + return Ok(()); + } let vals = self.vgprs(inst, data, if code == u32::MAX { 2 } else { 1 })?; let mut value = vals[0]; + let i32t = self.s.t.i32; if op == "sub" { let z = self.s.m.i32(0); value = self.s.m.bin(c, Bin::Sub, z, value); @@ -5702,9 +5809,6 @@ impl<'a> Lower<'a> { Some(v) if cache.glc => self.i32_of(v)?, _ => self.s.m.i32(0), }; - let h = self.handle(site, src, false, (kind | 0x1000, 0x105))?; - let at = self.begin_guarded(guard); - let i32t = self.s.t.i32; let mut args = vec![h]; let r = if code == u32::MAX { // cmpswap: data is (new, compare). @@ -7217,6 +7321,97 @@ mod tests { lower_with(&words, layout(), used()).unwrap(); } + #[test] + fn image_atomic_64_bit_lowers_with_int64_feature() { + // Table address at s0 loaded into s[2:3], s_load_dwordx8 s[0:7], s[2:3], null + // then MIMG image_atomic_add v[0:1], v[2:3], s[0:7] dmask:0x3 dim:SQ_RSRC_IMG_2D + let words = [ + 0xBE82_0300, // s_mov_b32 s2, s0 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0001, + 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null + 0xF044_0308, + 0x0000_0002, // image_atomic_add v[0:1], v[2:3], s[0:7] dmask:0x3 dim:SQ_RSRC_IMG_2D + S_ENDPGM, + ]; + let layout = || vec![root(RootType::Table, 0, 0)]; + let used = || { + vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }] + }; + let l = lower_with(&words, layout(), used()).unwrap(); + #[cfg(windows)] + if let Ok(mut v) = crate::emit::validator::Validator::load( + crate::emit::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut l.dxil.clone()).unwrap(); + } + let container = crate::Container::parse(&l.dxil).unwrap(); + let features = container.part(crate::FourCC::SFI0).unwrap(); + let sfi0 = u64::from_le_bytes(features.data.try_into().unwrap()); + assert_ne!( + sfi0 & 0x8000, + 0, + "64-bit image atomic must declare INT64 feature" + ); + assert_ne!( + sfi0 & 0x40_0000, + 0, + "64-bit image atomic must declare ATOMIC_INT64_ON_TYPED_RESOURCE" + ); + assert_ne!( + sfi0 & 0x1000_0000, + 0, + "64-bit image atomic from descriptor heap must declare ATOMIC_INT64_ON_HEAP_RESOURCE" + ); + } + + #[test] + fn image_atomic_32_and_64_handles_do_not_collide_in_cache() { + // Table address at s0 loaded into s[2:3], s_load_dwordx8 s[0:7], s[2:3], null + // then 32-bit image_atomic_add v0, v2, s[0:7] dmask:0x1 + // then 64-bit image_atomic_add v[0:1], v[2:3], s[0:7] dmask:0x3 + let words = [ + 0xBE82_0300, // s_mov_b32 s2, s0 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0001, + 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null + 0xF044_0108, + 0x0000_0002, // image_atomic_add v0, v2, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D + 0xF044_0308, + 0x0000_0002, // image_atomic_add v[0:1], v[2:3], s[0:7] dmask:0x3 dim:SQ_RSRC_IMG_2D + S_ENDPGM, + ]; + let layout = || vec![root(RootType::Table, 0, 0)]; + let used = || { + vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }] + }; + let _l = lower_with(&words, layout(), used()).unwrap(); + #[cfg(windows)] + if let Ok(mut v) = crate::emit::validator::Validator::load( + crate::emit::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut _l.dxil.clone()).unwrap(); + } + } + /// Tables of 2D textures at s0 and samplers at s1. fn texture_tables() -> (Vec, Vec) { let range = |kind, user_data, slot| UsedResource { diff --git a/crates/victory-shader/src/emit/lower/bvh.rs b/crates/victory-shader/src/emit/lower/bvh.rs new file mode 100644 index 0000000..96aaf2f --- /dev/null +++ b/crates/victory-shader/src/emit/lower/bvh.rs @@ -0,0 +1,523 @@ +//! The console's ray intersection instructions (`image_bvh_intersect_ray`, +//! `image_bvh64_intersect_ray`), which no host shader model has: the +//! program walks the BVH itself and asks the hardware to test one node. +//! The node is read from title memory through the address map +//! ([`super::global`]) and tested here, as Microsoft's software model of +//! the instruction does (`SoftwareBvhIntersectRay` in the XDXR traversal +//! headers): a box node gives its four children ordered by distance, a +//! leaf gives the hit's distance as a fraction. +//! +//! Node pointer: the type in bits 0-2 (0-3 the triangles of a leaf, 4 a +//! box with half-float bounds, 5 one with float bounds; the model treats +//! 6 and 7 as float boxes too), and the node's address over 64 in the +//! rest, added to the descriptor's base. Descriptor: base address over +//! 256 in bits 0-39, box sorting at bit 63, the triangle return mode at +//! bit 120 (1: the barycentric numerators, 0: the leaf's id dword and a +//! hit flag). +//! +//! Layouts (`XboxBvh4Node16`, `XboxBvh4Node32`, `XboxBvh4Leaf`): four +//! child pointers, then four boxes of six halves (16) or floats (32); a +//! leaf holds five vertices (TRI0 uses 0, 1, 2; TRI1 1, 3, 2; TRI2 2, 3, +//! 4; TRI3 2, 4, 0) and in its last dword two bits of barycentric remap +//! per triangle. +//! +//! shortcut: the triangle test's products are not marked precise; a host +//! compiler that fuses them into FMAs changes results on edges, where the +//! test is meant to be watertight. + +use super::*; + +/// What a node of each kind gives back when the ray misses it. +const INVALID: u32 = 0xFFFF_FFFF; +const INF: u32 = 0x7F80_0000; +const ONE: u32 = 0x3F80_0000; +const FLT_MAX: u32 = 0x7F7F_FFFF; +/// Dwords read per node: a float box node's children and bounds. +const NODE_DWORDS: u32 = 28; + +impl Lower<'_> { + pub(super) fn bvh(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Image { + data, + addr, + rsrc, + a16, + .. + } = &inst.fields + else { + unreachable!() + }; + let Operand::Vector { reg: out, .. } = *data else { + return Err("a ray intersection result"); + }; + let Operand::Scalar { code: desc, .. } = *rsrc else { + return Err("a BVH descriptor not in SGPRs"); + }; + let wide = inst.name() == "image_bvh64_intersect_ray"; + let mut regs = Vec::new(); + for a in addr { + if let Operand::Vector { reg, dwords } = *a { + regs.extend((0..dwords).map(|k| reg + k)); + } + } + let guard = self.guard(b, i)?; + let dword = |l: &mut Self, k: usize| -> Result { + let r = *regs.get(k).ok_or("a ray intersection address")?; + let v = inst.read(Reg::V(r)).ok_or("a ray intersection address")?; + l.i32_of(v) + }; + let mut k = 0; + let mut next = |l: &mut Self| { + k += 1; + dword(l, k - 1) + }; + let node_lo = next(self)?; + let node_hi = if wide { Some(next(self)?) } else { None }; + let extent = next(self)?; + let extent = self.as_float(extent); + let mut origin = [self.s.m.i32(0); 3]; + for o in &mut origin { + let x = next(self)?; + *o = self.as_float(x); + } + let (dir, inv) = if *a16 { + // Halves, low first: dir x y, dir z and inverse x, inverse y z. + let w = [next(self)?, next(self)?, next(self)?]; + let h: Vec = (0..6).map(|n| self.half(w[n / 2], n % 2 == 1)).collect(); + ([h[0], h[1], h[2]], [h[3], h[4], h[5]]) + } else { + let mut d = [self.s.m.i32(0); 6]; + for x in &mut d { + let y = next(self)?; + *x = self.as_float(y); + } + ([d[0], d[1], d[2]], [d[3], d[4], d[5]]) + }; + let mut words = [self.s.m.i32(0); 4]; + for (k, w) in words.iter_mut().enumerate() { + let v = inst + .read(Reg::S(desc + k as u8)) + .ok_or("a BVH descriptor")?; + *w = self.i32_of(v)?; + } + + let c = self.cur; + // The node's address: the descriptor's base plus the pointer's + // index of 64-byte units. + let ff = self.s.m.i32(0xFF); + let base_hi = self.s.m.bin(c, Bin::And, words[1], ff); + let base = self.wide(words[0], base_hi); + let t = self.s.m.int(64); + let eight = self.s.m.int_const(t, 8); + let base = self.s.m.bin(c, Bin::Shl, base, eight); + let node = match node_hi { + Some(hi) => self.wide(node_lo, hi), + None => self.widen(node_lo, false), + }; + let three = self.s.m.int_const(t, 3); + let six = self.s.m.int_const(t, 6); + let units = self.s.m.bin(c, Bin::LShr, node, three); + let offset = self.s.m.bin(c, Bin::Shl, units, six); + let va = self.s.m.bin(c, Bin::Add, base, offset); + let seven = self.s.m.i32(7); + let kind = self.s.m.bin(c, Bin::And, node_lo, seven); + let n = self.global_read(va, NODE_DWORDS, false); + + let boxes = self.box_node(&n, kind, extent, origin, dir, inv, words[1]); + let leaf = self.leaf_node(&n, kind, origin, dir, words[3]); + let c = self.cur; + let three = self.s.m.i32(3); + let is_leaf = self.s.m.cmp(c, pred::IULE, kind, three); + for k in 0..4 { + let x = self.s.m.select(c, is_leaf, leaf[k], boxes[k]); + self.write(inst, Reg::V(out + k as u8), x, guard); + } + Ok(()) + } + + /// Half `hi` or the low half of `w`, as a float. + fn half(&mut self, w: V, hi: bool) -> V { + let c = self.cur; + let h = if hi { + let sh = self.s.m.i32(16); + self.s.m.bin(c, Bin::LShr, w, sh) + } else { + w + }; + let mask = self.s.m.i32(0xFFFF); + let h = self.s.m.bin(c, Bin::And, h, mask); + self.s + .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]) + } + + fn fconst(&mut self, bits: u32) -> V { + self.s.m.f32(bits) + } + + fn fmin(&mut self, a: V, b: V) -> V { + self.binary(36, a, b) + } + + fn fmax(&mut self, a: V, b: V) -> V { + self.binary(35, a, b) + } + + fn fop(&mut self, op: Bin, a: V, b: V) -> V { + self.s.m.bin(self.cur, op, a, b) + } + + fn fcmp(&mut self, p: u8, a: V, b: V) -> V { + self.s.m.cmp(self.cur, p, a, b) + } + + fn or(&mut self, a: V, b: V) -> V { + self.s.m.bin(self.cur, Bin::Or, a, b) + } + + fn and(&mut self, a: V, b: V) -> V { + self.s.m.bin(self.cur, Bin::And, a, b) + } + + fn not(&mut self, a: V) -> V { + let t = self.s.m.bool(true); + self.s.m.bin(self.cur, Bin::Xor, a, t) + } + + /// `XdxrDecompressBox16`'s clamp of a widened half to the finite range. + fn finite(&mut self, x: V) -> V { + let (max, min) = (self.fconst(FLT_MAX), self.fconst(FLT_MAX | 0x8000_0000)); + let x = self.fmin(x, max); + self.fmax(x, min) + } + + /// A box node's result: the four child pointers whose boxes the ray + /// meets within `extent`, the others invalid, ordered by entry + /// distance when the descriptor asks (`TestXboxBvh4Node`). + #[allow(clippy::too_many_arguments)] + fn box_node( + &mut self, + n: &[V], + kind: V, + extent: V, + origin: [V; 3], + dir: [V; 3], + inv: [V; 3], + desc1: V, + ) -> [V; 4] { + let c = self.cur; + let four = self.s.m.i32(4); + let half_box = self.s.m.cmp(c, pred::EQ, kind, four); + let mut dist = [self.fconst(0); 4]; + let mut ptrs = [self.s.m.i32(0); 4]; + for k in 0..4 { + // Float bounds: six floats from dword 4 + 6k. + let full: Vec = (0..6).map(|j| self.as_float(n[4 + 6 * k + j])).collect(); + // Half bounds: three dwords from 4 + 3k, min x y, min z max x, + // max y z. + let w = [n[4 + 3 * k], n[5 + 3 * k], n[6 + 3 * k]]; + let small: Vec = (0..6) + .map(|j| { + let h = self.half(w[j / 2], j % 2 == 1); + self.finite(h) + }) + .collect(); + let c = self.cur; + let b: Vec = (0..6) + .map(|j| self.s.m.select(c, half_box, small[j], full[j])) + .collect(); + let t = self.ray_box( + extent, + origin, + dir, + inv, + [b[0], b[1], b[2]], + [b[3], b[4], b[5]], + ); + let c = self.cur; + let within = self.s.m.cmp(c, pred::OLE, t, extent); + let invalid = self.s.m.i32(INVALID); + ptrs[k] = self.s.m.select(c, within, n[k], invalid); + dist[k] = t; + } + let c = self.cur; + let one = self.s.m.i32(1); + let shifted = self.s.m.i32(31); + let sort = self.s.m.bin(c, Bin::LShr, desc1, shifted); + let sort = self.s.m.bin(c, Bin::And, sort, one); + let nil = self.s.m.i32(0); + let sort = self.s.m.cmp(c, pred::NE, sort, nil); + let (mut d, mut p) = (dist, ptrs); + for (x, y) in [(0, 2), (1, 3), (0, 1), (2, 3), (1, 2)] { + let c = self.cur; + let later = self.s.m.cmp(c, pred::OGT, d[x], d[y]); + let swap = self.s.m.bin(c, Bin::And, later, sort); + let (dx, dy) = ( + self.s.m.select(c, swap, d[y], d[x]), + self.s.m.select(c, swap, d[x], d[y]), + ); + let (px, py) = ( + self.s.m.select(c, swap, p[y], p[x]), + self.s.m.select(c, swap, p[x], p[y]), + ); + (d[x], d[y], p[x], p[y]) = (dx, dy, px, py); + } + p + } + + /// The distance at which the ray enters the box, within + /// `[0, extent]`, or infinity (`RayBoxTest`). + fn ray_box( + &mut self, + extent: V, + origin: [V; 3], + dir: [V; 3], + inv: [V; 3], + min: [V; 3], + max: [V; 3], + ) -> V { + let mut miss = self.s.m.bool(false); + for a in 0..3 { + let flipped = self.fcmp(pred::OGT, min[a], max[a]); + miss = self.or(miss, flipped); + } + let mut near = self.fconst(0); + let mut far = extent; + for a in 0..3 { + let zero = self.fconst(0); + let flat = self.fcmp(pred::OEQ, dir[a], zero); + let below = self.fcmp(pred::OLT, origin[a], min[a]); + let above = self.fcmp(pred::OGT, origin[a], max[a]); + let outside = self.or(below, above); + let out = self.and(flat, outside); + miss = self.or(miss, out); + let d1 = self.fop(Bin::Sub, min[a], origin[a]); + let t1 = self.fop(Bin::Mul, d1, inv[a]); + let d2 = self.fop(Bin::Sub, max[a], origin[a]); + let t2 = self.fop(Bin::Mul, d2, inv[a]); + let lo = self.fmin(t1, t2); + let hi = self.fmax(t1, t2); + let n = self.fmax(near, lo); + let f = self.fmin(far, hi); + let c = self.cur; + near = self.s.m.select(c, flat, near, n); + far = self.s.m.select(c, flat, far, f); + } + let crossed = self.fcmp(pred::OLT, far, near); + miss = self.or(miss, crossed); + let inf = self.fconst(INF); + self.s.m.select(self.cur, miss, inf, near) + } + + /// A leaf's result for triangle `kind` (`TestXboxBvh4Leaf`): the hit + /// distance's numerator and denominator, then the barycentric + /// numerators (return mode 1, descriptor bit 120) or the leaf's id + /// dword and a hit flag (mode 0); a miss gives infinity over one. + fn leaf_node(&mut self, n: &[V], kind: V, origin: [V; 3], dir: [V; 3], desc3: V) -> [V; 4] { + let c = self.cur; + let verts: Vec<[V; 3]> = (0..5) + .map(|v| { + [ + self.as_float(n[3 * v]), + self.as_float(n[3 * v + 1]), + self.as_float(n[3 * v + 2]), + ] + }) + .collect(); + let is = |l: &mut Self, k: u32| { + let kk = l.s.m.i32(k); + l.s.m.cmp(c, pred::EQ, kind, kk) + }; + let (t0, t1, t2) = (is(self, 0), is(self, 1), is(self, 2)); + let pick3 = |l: &mut Self, sel: &[(V, usize)], last: usize| -> [V; 3] { + let mut out = verts[last]; + for &(cond, v) in sel.iter().rev() { + for j in 0..3 { + out[j] = l.s.m.select(c, cond, verts[v][j], out[j]); + } + } + out + }; + // TRI0 (0, 1, 2), TRI1 (1, 3, 2), TRI2 (2, 3, 4), TRI3 (2, 4, 0). + let mut va = pick3(self, &[(t0, 0), (t1, 1)], 2); + let t12 = self.or(t1, t2); + let mut vb = pick3(self, &[(t0, 1), (t12, 3)], 4); + let t01 = self.or(t0, t1); + let mut vc = pick3(self, &[(t01, 2), (t2, 4)], 0); + let eight = self.s.m.i32(8); + let sh = self.s.m.bin(c, Bin::Mul, kind, eight); + let remap = self.s.m.bin(c, Bin::LShr, n[15], sh); + + // The axis the ray moves most along becomes z. + let mag: Vec = dir.iter().map(|&d| self.unary(6, d)).collect(); + let m = self.fmax(mag[1], mag[2]); + let m = self.fmax(mag[0], m); + let on_x = self.fcmp(pred::OEQ, mag[0], m); + let on_y = self.fcmp(pred::OEQ, mag[1], m); + let not_x = self.not(on_x); + let on_y = self.and(not_x, on_y); + let c = self.cur; + let swizzle = |l: &mut Self, v: [V; 3]| -> [V; 3] { + // On x: (y, z, x); on y: (z, x, y). + let yzx = [v[1], v[2], v[0]]; + let zxy = [v[2], v[0], v[1]]; + let mut out = v; + for j in 0..3 { + out[j] = l.s.m.select(c, on_y, zxy[j], out[j]); + out[j] = l.s.m.select(c, on_x, yzx[j], out[j]); + } + out + }; + let d = swizzle(self, dir); + let o = swizzle(self, origin); + va = swizzle(self, va); + vb = swizzle(self, vb); + vc = swizzle(self, vc); + let rel = |l: &mut Self, v: [V; 3]| -> [V; 3] { + [ + l.fop(Bin::Sub, v[0], o[0]), + l.fop(Bin::Sub, v[1], o[1]), + l.fop(Bin::Sub, v[2], o[2]), + ] + }; + let (va, vb, vc) = (rel(self, va), rel(self, vb), rel(self, vc)); + let shear = |l: &mut Self, v: [V; 3]| -> [V; 3] { + let x1 = l.fop(Bin::Mul, v[0], d[2]); + let x2 = l.fop(Bin::Mul, d[0], v[2]); + let y1 = l.fop(Bin::Mul, v[1], d[2]); + let y2 = l.fop(Bin::Mul, d[1], v[2]); + [l.fop(Bin::Sub, x1, x2), l.fop(Bin::Sub, y1, y2), v[2]] + }; + let (a, bb, cc) = (shear(self, va), shear(self, vb), shear(self, vc)); + let cross = |l: &mut Self, p: [V; 3], q: [V; 3]| { + let m1 = l.fop(Bin::Mul, p[0], q[1]); + let m2 = l.fop(Bin::Mul, p[1], q[0]); + l.fop(Bin::Sub, m1, m2) + }; + let u = cross(self, cc, bb); + let v = cross(self, a, cc); + let w = cross(self, bb, a); + let dot = |l: &mut Self, x: [V; 3]| { + let p = l.fop(Bin::Mul, u, x[0]); + let q = l.fop(Bin::Mul, v, x[1]); + let r = l.fop(Bin::Mul, w, x[2]); + let pq = l.fop(Bin::Add, p, q); + l.fop(Bin::Add, pq, r) + }; + let t_num = dot(self, [a[2], bb[2], cc[2]]); + let t_den = dot(self, [d[2], d[2], d[2]]); + + let zero = self.fconst(0); + let sign = |l: &mut Self, x: V, p: u8| l.fcmp(p, x, zero); + let (un, vn, wn) = ( + sign(self, u, pred::OLT), + sign(self, v, pred::OLT), + sign(self, w, pred::OLT), + ); + let (up, vp, wp) = ( + sign(self, u, pred::OGT), + sign(self, v, pred::OGT), + sign(self, w, pred::OGT), + ); + let any_neg = self.or(un, vn); + let any_neg = self.or(any_neg, wn); + let any_pos = self.or(up, vp); + let any_pos = self.or(any_pos, wp); + let mut missed = self.and(any_neg, any_pos); + let den_abs = self.unary(6, t_den); + let flat = self.fcmp(pred::OEQ, den_abs, zero); + missed = self.or(missed, flat); + let c = self.cur; + let den_bits = self.as_int(t_den); + let sign_bit = self.s.m.i32(0x8000_0000); + let den_sign = self.s.m.bin(c, Bin::And, den_bits, sign_bit); + let one_bits = self.s.m.i32(ONE); + let unit = self.s.m.bin(c, Bin::Or, den_sign, one_bits); + let unit = self.as_float(unit); + let ahead = self.fop(Bin::Mul, t_num, unit); + let behind = self.fcmp(pred::OLE, ahead, zero); + missed = self.or(missed, behind); + let nan = self.fcmp(pred::UNO, t_num, t_num); + missed = self.or(missed, nan); + let winding = self.fcmp(pred::OGT, t_den, zero); + // `BreakTieOnEdge`: which of two triangles sharing an edge owns it. + let tie = |l: &mut Self, ay: V, by: V, cy: V| -> V { + let (ba, ca) = (l.unary(6, by), l.unary(6, cy)); + let b0 = l.fcmp(pred::OEQ, ba, zero); + let c0 = l.fcmp(pred::OEQ, ca, zero); + let both = l.and(b0, c0); + let bottom = l.fcmp(pred::OGT, ay, zero); + let b_neg = l.fcmp(pred::OLT, by, zero); + let c_pos = l.fcmp(pred::OGT, cy, zero); + let b0c = l.and(b0, c_pos); + let below = l.or(b_neg, b0c); + let right = l.s.m.bin(l.cur, Bin::Xor, below, winding); + l.s.m.select(l.cur, both, bottom, right) + }; + for (e, (p, q, r)) in [(u, (a, bb, cc)), (v, (bb, cc, a)), (w, (cc, a, bb))] { + let ea = self.unary(6, e); + let on = self.fcmp(pred::OEQ, ea, zero); + let lost = tie(self, p[1], q[1], r[1]); + let lost = self.and(on, lost); + missed = self.or(missed, lost); + } + + let c = self.cur; + let pick = |l: &mut Self, sel: V| -> V { + let (one, two) = (l.s.m.i32(1), l.s.m.i32(2)); + let is1 = l.s.m.cmp(c, pred::EQ, sel, one); + let is2 = l.s.m.cmp(c, pred::EQ, sel, two); + let x = l.s.m.select(c, is1, v, u); + l.s.m.select(c, is2, w, x) + }; + let three = self.s.m.i32(3); + let i_sel = self.s.m.bin(c, Bin::And, remap, three); + let two = self.s.m.i32(2); + let j_sel = self.s.m.bin(c, Bin::LShr, remap, two); + let j_sel = self.s.m.bin(c, Bin::And, j_sel, three); + let i_num = pick(self, i_sel); + let j_num = pick(self, j_sel); + let i_neg = self.fcmp(pred::OLT, i_num, zero); + let i_pos = self.fcmp(pred::OGT, i_num, zero); + let den_neg = self.fcmp(pred::OLT, t_den, zero); + let f1 = self.and(i_neg, winding); + let f2 = self.and(i_pos, den_neg); + let flip = self.or(f1, f2); + let c = self.cur; + let negate = |l: &mut Self, x: V| { + let bits = l.as_int(x); + let s = l.s.m.i32(0x8000_0000); + let bits = l.s.m.bin(c, Bin::Xor, bits, s); + let flipped = l.as_float(bits); + l.s.m.select(c, flip, flipped, x) + }; + let i_num = negate(self, i_num); + let j_num = negate(self, j_num); + + let c = self.cur; + let shift = self.s.m.i32(24); + let mode = self.s.m.bin(c, Bin::LShr, desc3, shift); + let one = self.s.m.i32(1); + let mode = self.s.m.bin(c, Bin::And, mode, one); + let nil = self.s.m.i32(0); + let ij = self.s.m.cmp(c, pred::NE, mode, nil); + let (tn, td, ii, jj) = ( + self.as_int(t_num), + self.as_int(t_den), + self.as_int(i_num), + self.as_int(j_num), + ); + let c = self.cur; + // shortcut: in mode 0 the id dword is the leaf's last (the remap + // bytes) and the flag 1; what the hardware returns there is not + // modelled by the XDXR headers, which always ask for mode 1. + let z = self.s.m.select(c, ij, ii, n[15]); + let w_out = self.s.m.select(c, ij, jj, one); + let (inf, unit, nil) = (self.s.m.i32(INF), self.s.m.i32(ONE), self.s.m.i32(0)); + [ + self.s.m.select(c, missed, inf, tn), + self.s.m.select(c, missed, unit, td), + self.s.m.select(c, missed, nil, z), + self.s.m.select(c, missed, nil, w_out), + ] + } +} diff --git a/crates/victory-shader/src/emit/lower/global.rs b/crates/victory-shader/src/emit/lower/global.rs new file mode 100644 index 0000000..52ea4a9 --- /dev/null +++ b/crates/victory-shader/src/emit/lower/global.rs @@ -0,0 +1,463 @@ +//! Title memory at addresses a program computes ([`GLOBAL`]): pointers it +//! loads, picks by control flow or builds, and the nodes of a BVH it walks. +//! Such an address names no root parameter, so the host binds the address +//! map ([`crate::emit::address_map`]) and a read looks the address up in it +//! (a binary search over its ranges) and loads through the raw view the +//! range names. An address no range covers reads zero. + +use super::*; +use crate::emit::address_map::{ENTRY, HEADER}; +use crate::resource::GLOBAL; + +/// A raw UAV (`RWByteAddressBuffer`): the map's views are UAVs so that the +/// same view serves the program's stores. +const RAW_UAV: (u32, u32) = (11 | 0x1000, 0); + +impl Lower<'_> { + /// Whether the access at `site` reads title memory through the map. + pub(super) fn is_global(&self, site: Site) -> bool { + self.scalar.get(&site).is_some_and(|a| a.param == GLOBAL) + } + + /// `lo | hi << 32`, an i64. + pub(super) fn wide(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let t = self.s.m.int(64); + self.s.flags |= flags::INT64; + let lo = self.s.m.cast(c, Cast::ZExt, lo, t); + let hi = self.s.m.cast(c, Cast::ZExt, hi, t); + let k = self.s.m.int_const(t, 32); + let hi = self.s.m.bin(c, Bin::Shl, hi, k); + self.s.m.bin(c, Bin::Or, hi, lo) + } + + /// `x` (an i32) widened to i64, sign-extended when `signed`. + pub(super) fn widen(&mut self, x: V, signed: bool) -> V { + let t = self.s.m.int(64); + let op = if signed { Cast::SExt } else { Cast::ZExt }; + self.s.m.cast(self.cur, op, x, t) + } + + /// `n` (at most 4) dwords of the address map from byte `at`. + fn map_dwords(&mut self, at: V, n: u32) -> Vec { + let h = self.s.address_map_handle(); + self.raw_dwords(h, at, n) + } + + /// `n` (at most 4) dwords of raw buffer `h` from byte `at`. + pub(super) fn raw_dwords(&mut self, h: V, at: V, n: u32) -> Vec { + debug_assert!((1..=4).contains(&n)); + let c = self.cur; + let (u, mask, al) = ( + self.s.m.undef(self.s.t.i32), + self.s.m.i8((1 << n) - 1), + self.s.m.i32(4), + ); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, at, u, mask, al], + ); + (0..n) + .map(|k| { + let x = self.s.m.extract(self.cur, r, k); + self.as_int(x) + }) + .collect() + } + + /// Looks up title address `va` (an i64) in the address map: whether a + /// range covers it, the heap index of the range's view, and the byte + /// in that view `va` is at. + pub(super) fn map_lookup(&mut self, va: V) -> (V, V, V) { + let i32t = self.s.t.i32; + let zero = self.s.m.i32(0); + let count = self.map_dwords(zero, 1)[0]; + // The last range starting at or below `va`: halve the candidates + // [lo, lo + len) until one is left. + let pre = self.cur; + let (head, body, done) = ( + self.s.m.new_block(), + self.s.m.new_block(), + self.s.m.new_block(), + ); + self.s.m.terminate(pre, Term::Br(head)); + let lo = self.s.m.phi(head, i32t); + let len = self.s.m.phi(head, i32t); + let one = self.s.m.i32(1); + let more = self.s.m.cmp(head, pred::IUGT, len, one); + self.s.m.terminate(head, Term::CondBr(more, body, done)); + self.cur = body; + let half = self.s.m.bin(body, Bin::LShr, len, one); + let mid = self.s.m.bin(body, Bin::Add, lo, half); + let start = self.entry_dwords(mid, 0, 2); + let start = self.wide(start[0], start[1]); + let below = self.s.m.cmp(self.cur, pred::IULE, start, va); + let next_lo = self.s.m.select(self.cur, below, mid, lo); + let next_len = self.s.m.bin(self.cur, Bin::Sub, len, half); + let tail = self.cur; + self.s.m.terminate(tail, Term::Br(head)); + self.s.m.set_phi(lo, vec![(zero, pre), (next_lo, tail)]); + self.s.m.set_phi(len, vec![(count, pre), (next_len, tail)]); + self.cur = done; + let e = self.entry_dwords(lo, 0, 4); + let view_offset = self.entry_dwords(lo, 16, 1)[0]; + let c = self.cur; + let start = self.wide(e[0], e[1]); + let rel = self.s.m.bin(c, Bin::Sub, va, start); + let size = self.widen(e[2], false); + let some = self.s.m.cmp(c, pred::NE, count, zero); + let after = self.s.m.cmp(c, pred::IUGE, va, start); + let inside = self.s.m.cmp(c, pred::IULT, rel, size); + let hit = self.s.m.bin(c, Bin::And, after, inside); + let hit = self.s.m.bin(c, Bin::And, hit, some); + let rel = self.s.m.cast(c, Cast::Trunc, rel, i32t); + let byte = self.s.m.bin(c, Bin::Add, rel, view_offset); + (hit, e[3], byte) + } + + /// Dwords `first / 4..` (`n`, at most 4) of map entry `index`. + fn entry_dwords(&mut self, index: V, first: u32, n: u32) -> Vec { + let c = self.cur; + let size = self.s.m.i32(ENTRY); + let at = self.s.m.bin(c, Bin::Mul, index, size); + let base = self.s.m.i32(HEADER + first); + let at = self.s.m.bin(c, Bin::Add, at, base); + self.map_dwords(at, n) + } + + /// `n` dwords of title memory from address `va` (an i64), zero where + /// no range of the map covers `va`. `uniform`: the same address in + /// every lane (a scalar load). The dwords are taken to lie in the range + /// that holds the first. + pub(super) fn global_read(&mut self, va: V, n: u32, uniform: bool) -> Vec { + let (hit, view, byte) = self.map_lookup(va); + let at = self.begin_guarded(Some(hit)); + let h = self.s.heap_handle(self.cur, view, false, !uniform, RAW_UAV); + let mut out = Vec::with_capacity(n as usize); + let mut k = 0; + while k < n { + let chunk = (n - k).min(4); + let off = self.s.m.i32(4 * k); + let from = self.s.m.bin(self.cur, Bin::Add, byte, off); + out.extend(self.raw_dwords(h, from, chunk)); + k += chunk; + } + let zero = self.s.m.i32(0); + let pairs: Vec<(V, V)> = out.iter().map(|&x| (x, zero)).collect(); + self.end_guarded(at, &pairs) + } + + /// `s_load_dword*` from an address the program computes. + pub(super) fn global_smem(&mut self, inst: &Inst) -> Result<(), Why> { + let Fields::Smem { + base, + data, + offset, + soffset, + .. + } = &inst.fields + else { + unreachable!() + }; + let count = match inst.name().strip_prefix("s_load_dword") { + Some("") => 1, + Some("x2") => 2, + Some("x4") => 4, + Some("x8") => 8, + Some("x16") => 16, + _ => return Err("a scalar access to title memory"), + }; + let (Operand::Scalar { code: b, .. }, Some(Operand::Scalar { code: d, .. })) = + (*base, *data) + else { + return Err("a scalar load from title memory"); + }; + let lo = inst.read(Reg::S(b)).ok_or("an unread address")?; + let hi = inst.read(Reg::S(b + 1)).ok_or("an unread address")?; + let (lo, hi) = (self.i32_of(lo)?, self.i32_of(hi)?); + let mut va = self.wide(lo, hi); + let c = self.cur; + let imm = self.s.m.i32(*offset as u32); + let imm = self.widen(imm, true); + va = self.s.m.bin(c, Bin::Add, va, imm); + if !matches!(soffset, Operand::Scalar { code: NULL, .. }) { + let so = self.operand(inst, soffset)?; + let so = self.widen(so, false); + va = self.s.m.bin(self.cur, Bin::Add, va, so); + } + // Scalar loads ignore the address's two low bits. + let t = self.s.m.int(64); + let aligned = self.s.m.int_const(t, !3); + va = self.s.m.bin(self.cur, Bin::And, va, aligned); + let vals = self.global_read(va, count, true); + for (k, x) in vals.into_iter().enumerate() { + self.write(inst, Reg::S(d + k as u8), x, None); + } + Ok(()) + } + + /// The address a `global_*` instruction accesses: its SGPR base plus + /// its VGPR offset, or its VGPR pair, plus its immediate (an i64). + pub(super) fn global_address(&mut self, inst: &Inst) -> Result { + let Fields::Flat { + addr, + saddr, + offset, + .. + } = &inst.fields + else { + unreachable!() + }; + let Some(Operand::Vector { reg, .. }) = *addr else { + return Err("a global address not in VGPRs"); + }; + let vreg = |l: &mut Self, r: u8| -> Result { + let v = inst.read(Reg::V(r)).ok_or("an unread address")?; + l.i32_of(v) + }; + let va = match *saddr { + Some(Operand::Scalar { code, .. }) if code != NULL => { + let lo = inst.read(Reg::S(code)).ok_or("an unread address")?; + let hi = inst.read(Reg::S(code + 1)).ok_or("an unread address")?; + let (lo, hi) = (self.i32_of(lo)?, self.i32_of(hi)?); + let base = self.wide(lo, hi); + let v = vreg(self, reg)?; + let v = self.widen(v, false); + self.s.m.bin(self.cur, Bin::Add, base, v) + } + _ => { + let (lo, hi) = (vreg(self, reg)?, vreg(self, reg + 1)?); + self.wide(lo, hi) + } + }; + let imm = self.s.m.i32(*offset as i32 as u32); + let imm = self.widen(imm, true); + Ok(self.s.m.bin(self.cur, Bin::Add, va, imm)) + } + + /// `global_load_*` from an address the program computes. + pub(super) fn global_load(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Flat { dst, .. } = &inst.fields else { + unreachable!() + }; + let (n, sub) = match inst.name().strip_prefix("global_load_") { + Some("dword") => (1, None), + Some("dwordx2") => (2, None), + Some("dwordx3") => (3, None), + Some("dwordx4") => (4, None), + Some("ubyte") => (1, Some((8, false))), + Some("sbyte") => (1, Some((8, true))), + Some("ushort") => (1, Some((16, false))), + Some("sshort") => (1, Some((16, true))), + _ => return Err("a global access to title memory"), + }; + let Some(Operand::Vector { reg, .. }) = *dst else { + return Err("a global load result"); + }; + let guard = self.guard(b, i)?; + let va = self.global_address(inst)?; + let vals = match sub { + None => self.global_read(va, n, false), + Some((width, signed)) => { + // shortcut: the field is taken not to cross a dword. + let t = self.s.m.int(64); + let aligned = self.s.m.int_const(t, !3); + let at = self.s.m.bin(self.cur, Bin::And, va, aligned); + let w = self.global_read(at, 1, false)[0]; + let c = self.cur; + let i32t = self.s.t.i32; + let low = self.s.m.cast(c, Cast::Trunc, va, i32t); + let three = self.s.m.i32(3); + let byte = self.s.m.bin(c, Bin::And, low, three); + let sh = self.s.m.bin(c, Bin::Shl, byte, three); + let x = self.s.m.bin(c, Bin::LShr, w, sh); + let left = self.s.m.i32(32 - width); + let x = self.s.m.bin(c, Bin::Shl, x, left); + let op = if signed { Bin::AShr } else { Bin::LShr }; + vec![self.s.m.bin(c, op, x, left)] + } + }; + for (k, x) in vals.into_iter().enumerate() { + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + Ok(()) + } + + /// The VGPR dwords `n` from `reg` that `inst` reads. + fn data_dwords(&mut self, inst: &Inst, reg: u8, n: u32) -> Result, Why> { + (0..n) + .map(|k| { + let v = inst + .read(Reg::V(reg + k as u8)) + .ok_or("an unread store operand")?; + self.i32_of(v) + }) + .collect() + } + + /// `global_store_dword*` to an address the program computes. Lanes + /// whose address no range covers store nothing. + pub(super) fn global_store(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Flat { data, .. } = &inst.fields else { + unreachable!() + }; + let n = match inst.name().strip_prefix("global_store_") { + Some("dword") => 1, + Some("dwordx2") => 2, + Some("dwordx3") => 3, + Some("dwordx4") => 4, + _ => return Err("a byte or half store to title memory"), + }; + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a global store's data"); + }; + let vals = self.data_dwords(inst, reg, n)?; + let guard = self.guard(b, i)?; + let va = self.global_address(inst)?; + let (hit, view, byte) = self.map_lookup(va); + let go = match guard { + Some(g) => self.s.m.bin(self.cur, Bin::And, hit, g), + None => hit, + }; + let at = self.begin_guarded(Some(go)); + let h = self.s.heap_handle(self.cur, view, false, true, RAW_UAV); + let iu = self.s.m.undef(self.s.t.i32); + let mut args = vec![h, byte, iu]; + args.extend(&vals); + args.resize(3 + 4, iu); + args.push(self.s.m.i8((1u8 << n) - 1)); + args.push(self.s.m.i32(4)); + let void = self.s.t.void; + self.s.op( + self.cur, + "rawBufferStore.i32", + Attr::NoUnwind, + void, + 140, + &args, + ); + self.end_guarded(at, &[]); + Ok(()) + } + + /// `global_atomic_*` (32-bit) at an address the program computes. A + /// lane whose address no range covers changes nothing and gets 0. + pub(super) fn global_atomic(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Flat { data, dst, .. } = &inst.fields else { + unreachable!() + }; + // DXIL's atomic operations; cmpswap is u32::MAX. + let op = match inst.name().strip_prefix("global_atomic_") { + Some("add") => 0, + Some("and") => 1, + Some("or") => 2, + Some("xor") => 3, + Some("smin") => 4, + Some("smax") => 5, + Some("umin") => 6, + Some("umax") => 7, + Some("swap") => 8, + Some("sub") => u32::MAX - 1, + Some("cmpswap") => u32::MAX, + _ => return Err("a global atomic of that kind"), + }; + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a global atomic's data"); + }; + let vals = self.data_dwords(inst, reg, if op == u32::MAX { 2 } else { 1 })?; + let guard = self.guard(b, i)?; + let va = self.global_address(inst)?; + let (hit, view, byte) = self.map_lookup(va); + let go = match guard { + Some(g) => self.s.m.bin(self.cur, Bin::And, hit, g), + None => hit, + }; + let at = self.begin_guarded(Some(go)); + let h = self.s.heap_handle(self.cur, view, false, true, RAW_UAV); + let iu = self.s.m.undef(self.s.t.i32); + let i32t = self.s.t.i32; + let r = if op == u32::MAX { + // Data is (new, compare). + let args = [h, byte, iu, iu, vals[1], vals[0]]; + self.s.op( + self.cur, + "atomicCompareExchange.i32", + Attr::NoUnwind, + i32t, + 79, + &args, + ) + } else { + let (op, x) = if op == u32::MAX - 1 { + let zero = self.s.m.i32(0); + (0, self.s.m.bin(self.cur, Bin::Sub, zero, vals[0])) + } else { + (op, vals[0]) + }; + let opv = self.s.m.i32(op); + let args = [h, opv, byte, iu, iu, x]; + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args) + }; + let zero = self.s.m.i32(0); + let r = self.end_guarded(at, &[(r, zero)])[0]; + if let Some(Operand::Vector { reg, .. }) = *dst { + self.write(inst, Reg::V(reg), r, guard); + } + Ok(()) + } + + /// The console words of the `count` dwords the descriptor load at + /// `site` reads, from the descriptor words the host binds: a table's + /// user data is the byte offset of its first descriptor in the view + /// heap (32 bytes each, as the console's), the heap's own base 0. + pub(super) fn descriptor_words(&mut self, site: Site, count: u32) -> Result, Why> { + let a = *self + .scalar + .get(&site) + .ok_or("an untracked descriptor load")?; + let rp = *self + .x + .native + .layout + .get(a.param) + .ok_or("a descriptor read as data from no table")?; + let samplers = self + .x + .native + .used + .iter() + .any(|u| u.slot == rp.slot && u.kind == ResourceType::Sampler); + let base = match rp.root { + RootType::Table if !samplers => match self.user(a.param, 0) { + Val::I32(x) => x, + Val::Missing(why) => return Err(why), + Val::Bit(_) => return Err("a table offset"), + }, + RootType::ResourceHeap => self.s.m.i32(0), + _ => return Err("a sampler descriptor read as data"), + }; + let c = self.cur; + let off = self.s.m.i32(a.offset); + let mut byte = self.s.m.bin(c, Bin::Add, base, off); + if let Some(d) = a.dynamic { + let d = self.i32_of(d)?; + byte = self.s.m.bin(self.cur, Bin::Add, byte, d); + } + let h = self.s.descriptor_words_handle(); + let mut out = Vec::with_capacity(count as usize); + let mut k = 0; + while k < count { + let chunk = (count - k).min(4); + let four = self.s.m.i32(4 * k); + let at = self.s.m.bin(self.cur, Bin::Add, byte, four); + out.extend(self.raw_dwords(h, at, chunk)); + k += chunk; + } + Ok(out) + } +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index c388e1e..9767590 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -75,7 +75,10 @@ //! the console's, without `SV_PrimitiveID` and `SV_CullPrimitive` (the //! console never exports them). +pub mod address_map; mod bitcode; +#[cfg(test)] +mod bvh_tests; mod container; #[cfg(all(test, windows))] mod diff_tests; @@ -97,7 +100,9 @@ use crate::native::{HwStage, NativeProgram, RootType}; use crate::{ShaderError, io, ir, resource, structure}; pub use sampler::StaticSampler; -pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; +pub use shader::{ + ADDRESS_MAP_SPACE, DESCRIPTOR_WORDS_SPACE, ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE, +}; /// The loop limit without an override: 2^20. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; @@ -156,6 +161,17 @@ pub struct HostShader { /// Root SRVs (raw buffers) the shader reads: `t` in /// [`ROOT_CBV_SPACE`]. pub root_srvs: Vec, + /// The shader reads title memory at addresses it computes (pointers + /// it loads, a BVH it walks): the host binds the address map as a + /// root SRV, `t0` in [`ADDRESS_MAP_SPACE`]. See [`address_map`] for + /// its layout. + pub address_map: bool, + /// The shader reads descriptors as numbers (a buffer's address, say): + /// the host binds the console words of the view heap's descriptors, 32 + /// bytes per slot as the console lays them out, as a root SRV, `t0` in + /// [`DESCRIPTOR_WORDS_SPACE`]. A slot whose words the host cannot give + /// reads zero. + pub descriptor_words: bool, } impl HostShader { @@ -308,6 +324,8 @@ pub fn emit( samplers: l.samplers, root_cbvs: l.root_cbvs, root_srvs: l.root_srvs, + address_map: l.address_map, + descriptor_words: l.descriptor_words, }) } @@ -482,6 +500,8 @@ pub fn debug_ps(targets: u32) -> HostShader { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + address_map: false, + descriptor_words: false, } } @@ -662,6 +682,8 @@ mod tests { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + address_map: false, + descriptor_words: false, }; let file = |var: &str, stage| { std::env::var(var).ok().map(|p| super::HostShader { @@ -672,6 +694,8 @@ mod tests { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + address_map: false, + descriptor_words: false, }) }; let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps); diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index dd2eb75..0e7f2e2 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -12,6 +12,14 @@ pub const SAMPLER_SPACE: u32 = 0; /// Where root CBVs and SRVs are bound: `b` and /// `t` in this space. pub const ROOT_CBV_SPACE: u32 = 1; +/// Where the address map is bound: `t0` in this space (a root SRV), when +/// the shader reads title memory at addresses it computes +/// ([`crate::resource::GLOBAL`]; see [`super::HostShader::address_map`]). +pub const ADDRESS_MAP_SPACE: u32 = 2; +/// Where the descriptor words are bound: `t0` in this space (a root SRV), +/// when the shader reads descriptors as numbers beyond what host views +/// tell (see [`super::HostShader::descriptor_words`]). +pub const DESCRIPTOR_WORDS_SPACE: u32 = 3; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { @@ -20,8 +28,10 @@ pub(crate) mod flags { pub const TYPED_UAV_LOADS: u64 = 1 << 13; pub const WAVE_OPS: u64 = 1 << 19; pub const INT64: u64 = 1 << 20; + pub const ATOMIC_INT64_ON_TYPED_RESOURCE: u64 = 1 << 27; pub const RESOURCE_HEAP: u64 = 1 << 30; pub const SAMPLER_HEAP: u64 = 1 << 31; + pub const ATOMIC_INT64_ON_HEAP_RESOURCE: u64 = 1 << 32; } pub(crate) struct Types { @@ -65,6 +75,10 @@ pub(crate) struct Shader { pub root_cbvs: Vec<(u8, V)>, /// Root SRVs (raw buffers) read, likewise. pub root_srvs: Vec<(u8, V)>, + /// The address map's handle, once made ([`Shader::address_map_handle`]). + pub address_map: Option, + /// The descriptor words' handle, once made. + pub descriptor_words: Option, pub flags: u64, /// Heap handles made with a non-uniform index. pub nonuniform_handles: u32, @@ -120,6 +134,8 @@ impl Shader { cmp_samplers: 0, root_cbvs: Vec::new(), root_srvs: Vec::new(), + address_map: None, + descriptor_words: None, flags: 0, nonuniform_handles: 0, threads: None, @@ -236,6 +252,48 @@ impl Shader { h } + /// The handle of the address map (`t0` in [`ADDRESS_MAP_SPACE`], a raw + /// buffer), made in the entry block. + pub fn address_map_handle(&mut self) -> V { + if let Some(h) = self.address_map { + return h; + } + let h = self.space_handle(ADDRESS_MAP_SPACE); + self.address_map = Some(h); + h + } + + /// The handle of the descriptor words (`t0` in + /// [`DESCRIPTOR_WORDS_SPACE`], a raw buffer), made in the entry block. + pub fn descriptor_words_handle(&mut self) -> V { + if let Some(h) = self.descriptor_words { + return h; + } + let h = self.space_handle(DESCRIPTOR_WORDS_SPACE); + self.descriptor_words = Some(h); + h + } + + /// A raw buffer bound at `t0` in `space`, made in the entry block. + fn space_handle(&mut self, space: u32) -> V { + let r = self.m.i32(0); + let bind = [r, r, self.m.i32(space), self.m.i8(0)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, r, f], + ); + let h = self.annotate(block, h, 11, 0); + self.flags |= flags::RAW_BUFFERS; + h + } + /// The handle of immediate sampler `n` (a comparison sampler when its /// bit in `cmp_samplers` is set). pub fn sampler_handle(&mut self, block: usize, n: u32) -> V { @@ -318,6 +376,8 @@ impl Shader { || self.samplers > 0 || !self.root_cbvs.is_empty() || !self.root_srvs.is_empty() + || self.address_map.is_some() + || self.descriptor_words.is_some() { let empty = self.m.md_str(""); let mut cbvs = None; @@ -372,20 +432,32 @@ impl Shader { cbvs = Some(self.m.md_node(cbv_list)); } let mut srvs = None; - if !self.root_srvs.is_empty() { + // Raw buffers: root SRVs, then the address map. + let mut raw: Vec<(u32, u32)> = self + .root_srvs + .iter() + .map(|&(slot, _)| (ROOT_CBV_SPACE, u32::from(slot))) + .collect(); + if self.address_map.is_some() { + raw.push((ADDRESS_MAP_SPACE, 0)); + } + if self.descriptor_words.is_some() { + raw.push((DESCRIPTOR_WORDS_SPACE, 0)); + } + if !raw.is_empty() { let ty = self .m .named_struct("struct.ByteAddressBuffer", vec![self.t.i32]); let p = self.m.ptr(ty); let u = self.m.undef(p); let mut list = Vec::new(); - for (n, (slot, _)) in self.root_srvs.clone().into_iter().enumerate() { + for (n, (space, register)) in raw.into_iter().enumerate() { let ops = vec![ Some(i32c(&mut self, n as u32)), Some(self.m.md_value(u)), Some(empty), - Some(i32c(&mut self, ROOT_CBV_SPACE)), - Some(i32c(&mut self, u32::from(slot))), + Some(i32c(&mut self, space)), + Some(i32c(&mut self, register)), Some(i32c(&mut self, 1)), Some(i32c(&mut self, 11)), Some(i32c(&mut self, 0)), @@ -394,8 +466,8 @@ impl Shader { list.push(Some(self.m.md_node(ops))); bindings.push(Binding { kind: 4, - space: ROOT_CBV_SPACE, - register: u32::from(slot), + space, + register, dxil_kind: 11, }); } @@ -578,12 +650,18 @@ impl Shader { if self.flags & flags::INT64 != 0 { features |= 0x8000; } + if self.flags & flags::ATOMIC_INT64_ON_TYPED_RESOURCE != 0 { + features |= 0x40_0000; + } if self.flags & flags::RESOURCE_HEAP != 0 { features |= 0x200_0000; } if self.flags & flags::SAMPLER_HEAP != 0 { features |= 0x400_0000; } + if self.flags & flags::ATOMIC_INT64_ON_HEAP_RESOURCE != 0 { + features |= 0x1000_0000; + } let sfi0 = features.to_le_bytes(); let isg1 = container::signature(&self.inputs, true); let osg1 = container::signature(&self.outputs, false); diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index b4ee77d..027a865 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -148,6 +148,8 @@ fn build_valu_cs(body: &[u32]) -> HostShader { static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, + address_map: lowered.address_map, + descriptor_words: lowered.descriptor_words, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index 104fc6d..c9c5ce2 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -82,6 +82,8 @@ fn build(words: &[u32], buffers: bool) -> HostShader { static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, + address_map: lowered.address_map, + descriptor_words: lowered.descriptor_words, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index c35e5ef..1b2bf98 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -38,6 +38,43 @@ pub struct Address { /// offset is then the byte offset in the code. pub const CODE: usize = usize::MAX; +/// [`Address::param`] of an address only known when the program runs: a +/// pointer it loads from memory, picks by control flow or computes (a +/// ray-tracing traversal follows the pointers in its BVH). The lowering +/// rebuilds the 64-bit address from the instruction's own operands and +/// reads title memory through the address map; `offset` and `dynamic` +/// are unused. +pub const GLOBAL: usize = usize::MAX - 1; + +/// Why an address has no root parameter, when the program computes it +/// from values a translation can reproduce: such an access reads title +/// memory at that address ([`GLOBAL`]). An address in an SGPR the +/// hardware fills (the console's spill table, say) has no host value, so +/// that case stays a refusal, as do the code-relative ones. +fn runtime_address(why: &str) -> bool { + matches!( + why, + "an address not from a root parameter" + | "an address from a phi" + | "an address loaded from memory" + | "an address with two computed terms" + | "an address from a root parameter that is no address" + ) +} + +/// The address of a memory access, or [`GLOBAL`] when [`runtime_address`] +/// says why it has none. +fn or_global(a: Result) -> Result { + match a { + Err(why) if runtime_address(why) => Ok(Address { + param: GLOBAL, + offset: 0, + dynamic: None, + }), + a => a, + } +} + #[derive(Debug, Clone, PartialEq, Eq)] pub enum Source { /// Dwords `first..` of what the scalar load at `load` reads (see @@ -192,6 +229,9 @@ pub fn track( Ok(()) }; match &inst.fields { + // The BVH descriptor is read as data (its base address and + // flags): no host view stands for it. + Fields::Image { .. } if inst.name().starts_with("image_bvh") => {} Fields::Image { rsrc, sampler, .. } => { descriptor(rsrc, Role::Resource)?; if let Some(s) = sampler { @@ -208,7 +248,8 @@ pub fn track( soffset, .. } if inst.name().contains("_load_") || inst.name().contains("_store_") => { - let address = t.smem_address(inst, base, *offset, soffset).map_err(fail)?; + let address = + or_global(t.smem_address(inst, base, *offset, soffset)).map_err(fail)?; out.scalar.push((site, address)); } Fields::Flat { @@ -217,9 +258,9 @@ pub fn track( offset, .. } if inst.name().starts_with("global_") => { - let address = t - .flat_address(inst, addr.as_ref(), saddr.as_ref(), *offset) - .map_err(fail)?; + let address = + or_global(t.flat_address(inst, addr.as_ref(), saddr.as_ref(), *offset)) + .map_err(fail)?; out.scalar.push((site, address)); } _ => {} diff --git a/docs/architecture.md b/docs/architecture.md index 4952df3..e6015d2 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -97,3 +97,16 @@ the lanes take, from structurisation), and accessed with a non-uniform heap index in one pass. `victory translate` runs every shader it finds (containers, SGD5 files) through these and lists what they cannot handle yet. + +An address the program computes itself (a pointer it loads, picks by +control flow or builds) traces to no root parameter. Such accesses go +through the address map (`victory_shader::emit::address_map`): the host +copies of title memory sorted by address, which the shader searches, then +reads or writes through a raw view in the descriptor heap. The ray-tracing +passes walk the BVH this way and test each node with +`image_bvh_intersect_ray`, which no host shader model has: the translation +reads the node through the map and tests it as Microsoft's software model +of the instruction does (`SoftwareBvhIntersectRay` in the XDXR traversal +headers). Descriptor words a program reads as numbers (a buffer's address, +say) come from a copy of the view heap in the console's layout, 32 bytes a +slot, that the host keeps beside it.