Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ loads the world and shows it: slowly, and with rendering defects.

Tested on one machine: Windows 11, AMD RX 6700 XT.

NVIDIA GPUs cap shader-visible view heaps at 10^6 slots, and the world uses
more (slot 1,236,191 and up). On such a GPU, shaders clamp indices below the
cap instead of faulting the device, and a slot past the kept ones reads an
empty or unrelated view (until 2026-11-25 the run ended
with "device removed", DXGI_ERROR_INVALID_CALL). Expect missing or wrong
objects. The shader cache is kept per heap size, so run `translate --cache`
again after switching GPUs.

> **Warning.** Entering the world on a real GPU has hung it in earlier
> builds, and Windows then resets the display driver (every monitor goes
> black for a moment). The latest runs did not, but it is not ruled out; a
Expand Down
188 changes: 147 additions & 41 deletions crates/victory-gpu/src/descriptor/host.rs

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion crates/victory-gpu/src/draw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2465,7 +2465,10 @@ void main(uint3 id : SV_DispatchThreadID) {
// SAFETY: a live buffer.
unsafe { made.GetDesc() }.Width
};
assert_eq!(width(start + 456), 1 << 16, "on an element: the buffer's copy");
// Host views of structured buffers are raw: on an element 16 bytes
// in (912), the buffer's copy; on one that is not (456), its own.
assert_eq!(width(start + 912), 1 << 16, "on an element: the buffer's copy");
assert_eq!(width(start + 456), (4 * 456u64).next_multiple_of(256), "off 16 bytes: its own bytes");
assert_eq!(width(start + 100), (4 * 456u64).next_multiple_of(256), "off: its own bytes");
let (copy, address, len) = crate::descriptor::host::view_copy(&view(start + 100)).unwrap();
assert_eq!((copy.range(), address, len), ((start + 100, 4 * 456), start + 100, 4 * 456));
Expand Down
18 changes: 18 additions & 0 deletions crates/victory-gpu/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,24 @@ fn create() -> windows::core::Result<Host> {
let cpu_view_size =
device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
tracing::info!("host D3D12 device ready");
// A host whose shader-visible view heaps stop below `HEAP_VIEWS`
// (NVIDIA): translated shaders clamp their heap indices below its
// cap instead, so a title slot past it reads null, not a fault.
let views = victory_shader::emit::HEAP_VIEWS;
if let Err(e) = device.CreateDescriptorHeap::<ID3D12DescriptorHeap>(
&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: views,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
},
) {
let cap = crate::descriptor::host::PORTABLE_VIEWS;
tracing::warn!(error = %e, views, cap, "host view heaps capped: shaders read slots past the cap as null");
if !victory_shader::emit::set_heap_views(cap) {
tracing::error!(cap, "view-heap cap set after shaders read it");
}
}
// The console fuses its multiply-adds (`v_fma_f32`, `v_fmac_f32`,
// `v_fma_mix*`); the lowering's DXIL `FMad` is fused only where the
// host chooses (the RX 6700 XT does, WARP does not).
Expand Down
2 changes: 2 additions & 0 deletions crates/victory-gpu/src/pipeline/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,13 +183,15 @@ fn open(device: &ID3D12Device1, blob: Vec<u8>) -> Option<Library> {
/// host descriptions).
fn tag(blob: &[u8]) -> String {
let limit = victory_shader::emit::loop_limit().to_le_bytes();
let views = victory_shader::emit::heap_views().to_le_bytes();
let translator = victory_shader::SOURCE_HASH.as_bytes();
let mut h = blake3::Hasher::new();
for part in [
blob,
translator,
include_bytes!("../shader_cache.rs"),
&limit,
&views,
include_bytes!("host.rs"),
include_bytes!("library.rs"),
] {
Expand Down
28 changes: 18 additions & 10 deletions crates/victory-gpu/src/shader_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ static MISSES: AtomicU64 = AtomicU64::new(0);
/// Keeps translated shaders in a folder of `dir` from now on: the folder
/// of this translator, `None` if it cannot be opened.
pub fn use_shader_cache(dir: PathBuf) -> Option<PathBuf> {
// The folder's key holds the host's heap cap, set as the host is made.
crate::host::host();
let dir = dir.join(&blake3::Hash::from(*build()).to_hex()[..16]);
match Cache::open(&dir) {
Ok(cache) => {
Expand All @@ -53,7 +55,8 @@ pub fn counts() -> (u64, u64) {
/// (`victory_shader::SOURCE_HASH`: its sources, manifest, the lock file and
/// the compiler), the entry's encoding (this file's text) and the
/// translation settings (the loop limit, which a diagnostics build can
/// change at run time).
/// change at run time; the view-heap slots shaders index, smaller on a host
/// that caps its heaps).
fn build() -> &'static [u8; 32] {
static BUILD: OnceLock<[u8; 32]> = OnceLock::new();
BUILD.get_or_init(|| {
Expand All @@ -64,24 +67,27 @@ fn build() -> &'static [u8; 32] {
"VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner"
);
}
key(victory_shader::SOURCE_HASH, ENCODING, limit)
key(victory_shader::SOURCE_HASH, ENCODING, limit, victory_shader::emit::heap_views())
})
}

/// This file, whose `encode` and `decode` define the entries.
const ENCODING: &[u8] = include_bytes!("shader_cache.rs");

fn key(translator: &str, encoding: &[u8], limit: u32) -> [u8; 32] {
fn key(translator: &str, encoding: &[u8], limit: u32, views: u32) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(translator.as_bytes());
h.update(blake3::hash(encoding).as_bytes());
h.update(&limit.to_le_bytes());
h.update(&views.to_le_bytes());
*h.finalize().as_bytes()
}

/// The translation of a console shader container, from the cache when
/// there is one, and whether it came from there.
pub fn host_shader(container: &[u8]) -> (Result<HostShader, String>, bool) {
// The host's heap cap is a translation setting, set as it is made.
crate::host::host();
// Writes through views mark their pages: copy-backs compare only those
// (`crate::shadow::copy_back_marks`).
let options = victory_shader::emit::Options { view_marks: true };
Expand Down Expand Up @@ -431,21 +437,23 @@ mod tests {
}

/// The key's parts: a change to any of them (the translator's sources,
/// this file's encoding, the loop limit) makes another key, so no entry
/// this file's encoding, the loop limit, the heap size) makes another key, so no entry
/// written before it is read.
#[test]
fn the_key_covers_translator_encoding_and_settings() {
let k = key("0123456789abcdef", b"encoding", 1 << 20);
assert_eq!(k, key("0123456789abcdef", b"encoding", 1 << 20));
assert_ne!(k, key("0123456789abcdee", b"encoding", 1 << 20));
assert_ne!(k, key("0123456789abcdef", b"encoding.", 1 << 20));
assert_ne!(k, key("0123456789abcdef", b"encoding", 1 << 19));
let k = key("0123456789abcdef", b"encoding", 1 << 20, 1 << 21);
assert_eq!(k, key("0123456789abcdef", b"encoding", 1 << 20, 1 << 21));
assert_ne!(k, key("0123456789abcdee", b"encoding", 1 << 20, 1 << 21));
assert_ne!(k, key("0123456789abcdef", b"encoding.", 1 << 20, 1 << 21));
assert_ne!(k, key("0123456789abcdef", b"encoding", 1 << 19, 1 << 21));
assert_ne!(k, key("0123456789abcdef", b"encoding", 1 << 20, 1_000_000));
assert_eq!(
*build(),
key(
victory_shader::SOURCE_HASH,
ENCODING,
victory_shader::emit::loop_limit()
victory_shader::emit::loop_limit(),
victory_shader::emit::heap_views()
)
);
// The encoding part is this file as built.
Expand Down
27 changes: 23 additions & 4 deletions crates/victory-shader/src/emit/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,23 @@ impl Host {
}
}

/// Whether the device takes a shader-visible view heap of
/// [`super::HEAP_VIEWS`] slots, as [`View::NullBuffers`] needs (NVIDIA
/// stops at 10^6).
pub fn takes_full_view_heap(&self) -> bool {
// SAFETY: a plain heap creation on a live device.
unsafe {
self.device
.CreateDescriptorHeap::<ID3D12DescriptorHeap>(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: super::HEAP_VIEWS,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
..Default::default()
})
.is_ok()
}
}

/// The root signature translated shaders expect: user data per stage
/// at `b0`, immediate samplers per stage at `s<n>`, heaps directly
/// indexed.
Expand Down Expand Up @@ -1642,11 +1659,13 @@ impl Host {
0,
D3D12_BUFFER_SRV_FLAG_NONE,
),
// Raw, as the runtime makes a structured view
// (its stride is in the view-stride table).
Stride::Structured(s) => (
DXGI_FORMAT_UNKNOWN,
data.len() * 4 / s as usize,
s,
D3D12_BUFFER_SRV_FLAG_NONE,
DXGI_FORMAT_R32_TYPELESS,
data.len() * 4 / s as usize * s as usize / 4,
0,
D3D12_BUFFER_SRV_FLAG_RAW,
),
Stride::Format(f, bytes) => (
f,
Expand Down
78 changes: 62 additions & 16 deletions crates/victory-shader/src/emit/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4067,6 +4067,8 @@ impl<'a> Lower<'a> {
|| un.contains("atomic")
|| used.is_some_and(|u| u.kind == ResourceType::Uav);
let u = if uav { 0x1000 } else { 0 };
// The bytes of a record, for a buffer counted in records.
let mut per = 0;
let (props, image) = match &ui.fields {
Fields::Image { dim, .. } => {
let kind = match dim {
Expand All @@ -4086,7 +4088,9 @@ impl<'a> Lower<'a> {
{
(10 | u, 0x409)
} else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) {
(12 | u, stride)
// Host buffer views are raw: bytes, counted in records below.
per = stride;
(11 | u, 0)
} else {
(11 | u, 0)
};
Expand All @@ -4105,7 +4109,10 @@ impl<'a> Lower<'a> {
}
let props = match used.stride {
0 | 1 => (11 | u, 0),
s if s.is_multiple_of(4) => (12 | u, s),
s if s.is_multiple_of(4) => {
per = s;
(11 | u, 0)
}
_ => return Err("a scalar-loaded buffer of odd stride read as data"),
};
(props, None)
Expand Down Expand Up @@ -4162,6 +4169,11 @@ impl<'a> Lower<'a> {
let d3 = self.s.m.bin(c, Bin::Or, base, last);
vec![(1, d1), (2, d2), (3, d3), (4, depth)]
}
None if per > 0 => {
let per = self.s.m.i32(per);
let bytes = field(self, 0);
vec![(2, self.s.m.bin(c, Bin::UDiv, bytes, per))]
}
None => vec![(2, field(self, 0))],
};
for k in 0..count {
Expand Down Expand Up @@ -5032,12 +5044,13 @@ impl<'a> Lower<'a> {
/// buffer one (a wild address: the texture's address shifted 8 bits
/// down) and faulted the device.
fn buffer_guard(&mut self, src: &Source, index: V, sampler: bool, props: (u32, u32)) -> V {
let index = self.title_guard(src, index, sampler);
// Typed, raw and structured buffers (DXIL resource kinds 10-12).
if sampler || !(10..=12).contains(&(props.0 & 0xFF)) || !self.is_heap_direct(src) {
return index;
}
let c = self.cur;
let last = self.s.m.i32(super::HEAP_VIEWS - 1);
let last = self.s.m.i32(super::heap_views() - 1);
let over = self.s.m.cmp(c, pred::IUGT, index, last);
let index = self.s.m.select(c, over, last, index);
let four = self.s.m.i32(4);
Expand All @@ -5050,22 +5063,51 @@ impl<'a> Lower<'a> {
let zero = self.s.m.i32(0);
let none = self.s.m.cmp(c, pred::EQ, stride, zero);
// The null unordered access view sits just below the null SRV.
let null = super::NULL_BUFFER_VIEW - u32::from(props.0 & 0x1000 != 0);
let null = super::null_buffer_view() - u32::from(props.0 & 0x1000 != 0);
let null = self.s.m.i32(null);
self.s.m.select(c, none, null, index)
}

/// Whether a descriptor comes from the resource heap itself (root type
/// 5, not a table) on some path.
fn is_heap_direct(&self, src: &Source) -> bool {
src.leaves().iter().any(|l| match l {
/// `index`, or the heap's last slot (null) where a capped host heap
/// keeps no title slot there (module notes, "Heap indices"): for a
/// view taken from the resource heap itself on every path, an index at
/// or past [`super::title_views`] would read a dynamic slot, another
/// draw's view, perhaps of another kind (a GPU hang on NVIDIA, with no
/// page fault). Tables hold dynamic slots' indices and are left alone.
fn title_guard(&mut self, src: &Source, index: V, sampler: bool) -> V {
let title = super::title_views();
if sampler || title == super::heap_views() || !self.all_heap_direct(src) {
return index;
}
let c = self.cur;
let first = self.s.m.i32(title);
let past = self.s.m.cmp(c, pred::IUGE, index, first);
let null = self.s.m.i32(super::heap_views() - 1);
self.s.m.select(c, past, null, index)
}

/// Whether a descriptor comes from the resource heap itself on every
/// path.
fn all_heap_direct(&self, src: &Source) -> bool {
let leaves = src.leaves();
!leaves.is_empty() && leaves.iter().all(|l| self.leaf_heap_direct(l))
}

fn leaf_heap_direct(&self, l: &Source) -> bool {
match l {
Source::Loaded { load, .. } | Source::Fetched { load, .. } => self
.scalar
.get(load)
.and_then(|a| self.x.native.layout.get(a.param))
.is_some_and(|p| p.root == RootType::ResourceHeap),
_ => false,
})
}
}

/// Whether a descriptor comes from the resource heap itself (root type
/// 5, not a table) on some path.
fn is_heap_direct(&self, src: &Source) -> bool {
src.leaves().iter().any(|l| self.leaf_heap_direct(l))
}

/// The heap index of a descriptor that may differ between lanes,
Expand Down Expand Up @@ -8812,11 +8854,11 @@ impl<'a> Lower<'a> {
if stride < 4 || !stride.is_multiple_of(4) {
return Err("a structured buffer of unknown stride");
}
let h = self.handle(site, src, false, (12 | u, stride))?;
let h = self.handle(site, src, false, (11 | u, 0))?;
let s = self.s.m.i32(stride);
let row = self.s.m.bin(self.cur, Bin::Mul, index, s);
let byte = self.s.m.bin(self.cur, Bin::Add, row, off);
(h, [index, off, iu], byte)
(h, [byte, iu, iu], byte)
}
None => {
let (h, off) = self.raw_view(site, src, off, 4, (11 | u, 0), true, guard)?;
Expand Down Expand Up @@ -8946,11 +8988,12 @@ impl<'a> Lower<'a> {
if stride < 4 || !stride.is_multiple_of(4) {
return Err("a structured buffer of unknown stride");
}
args.push(self.handle(site, src, false, (12 | u, stride))?);
args.extend([index, off]);
args.push(self.handle(site, src, false, (11 | u, 0))?);
let s = self.s.m.i32(stride);
let row = self.s.m.bin(self.cur, Bin::Mul, index, s);
(byte, bytes) = (self.s.m.bin(self.cur, Bin::Add, row, off), 4 * count);
byte = self.s.m.bin(self.cur, Bin::Add, row, off);
args.extend([byte, iu]);
bytes = 4 * count;
}
None => {
let n = 4 * count;
Expand Down Expand Up @@ -9054,14 +9097,17 @@ impl<'a> Lower<'a> {
if stride < 4 || !stride.is_multiple_of(4) {
return Err("a structured buffer of unknown stride");
}
let h = self.handle(site, src, false, (12 | u, stride))?;
let h = self.handle(site, src, false, (11 | u, 0))?;
let s = self.s.m.i32(stride);
let row = self.s.m.bin(c, Bin::Mul, index, s);
let byte = self.s.m.bin(c, Bin::Add, row, off);
self.s.op(
c,
"rawBufferLoad.f32",
Attr::ReadOnly,
self.s.t.res_ret,
139,
&[h, index, off, mask, align],
&[h, byte, iu, mask, align],
)
}
None => {
Expand Down
Loading