From 4ee69042d4ed96e3b2ccaabc04ac7f6574043e0b Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 04:08:26 +0000 Subject: [PATCH 1/4] GPU: shard the pipeline library so saves write only changes Port the relevant part of upstream Marvisak/VIctory#1653 onto the fork's newer parallel-load design. A save serialised the whole host pipeline library and wrote it as one blob even when only a few pipelines changed. The cache is now split into 16 stable shards chosen from each pipeline's hash, so steady-state saves serialise and publish only dirty shards. Same-name loads remain serialised as required by D3D12, while different pipelines can still load in parallel. Stores and serialisation remain under each shard's lock; dirty counts are lowered only after that shard's bytes are published. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/pipeline/library.rs | 157 ++++++++++++++------- 1 file changed, 108 insertions(+), 49 deletions(-) diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index 691cb9f..85f0764 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -5,8 +5,11 @@ //! a hash of all that its host description holds (the translated //! shaders' code, which changes when a translation does, our root //! signature, the graphics state). The library is saved under the cache -//! folder; the host refuses a library of another adapter or driver, and -//! an entry whose description differs, so neither is ever used. +//! folder in [`SHARDS`] files, chosen by that name; the host refuses a +//! library of another adapter or driver, and an entry whose description +//! differs, so neither is ever used. A save serialises and writes only +//! the shards that gained pipelines, because the host can only serialise +//! a library whole and one blob of the world's pipelines is over 600 MB. //! 2. The title pipelines a run drew or dispatched with are listed by a key //! known when the title creates them (their shader containers and //! graphics state); the next run hands those to the workers at @@ -54,7 +57,9 @@ struct Library { // the mutex that holds the library. unsafe impl Send for Library {} -const LIBRARY_FILE: &str = "host-pipelines.bin"; +/// How many files the library is split into. A save serialises and writes +/// only the shards that gained pipelines; see the module comment. +const SHARDS: usize = 16; const EARLY_FILE: &str = "early-pipelines.txt"; /// Loads of the same pipeline serialise (the host documents that one as not /// thread-safe); loads of different pipelines may overlap. @@ -63,20 +68,38 @@ static LOADS: LazyLock>>>> = /// Title pipelines listed for an early start, at most. const EARLY_MAX: usize = 8192; -fn library() -> Option<&'static Mutex> { - static LIBRARY: OnceLock>> = OnceLock::new(); - LIBRARY +/// The file shard `shard` is kept in. +fn shard_file(shard: usize) -> String { + format!("host-pipelines.{shard:02}.bin") +} + +/// The shard a pipeline named `name` belongs to. The name is a hash, so this +/// is spread and stable across runs: a pipeline always lands in the same +/// file, which is what lets a save write only the files that changed. +fn shard_of(name: &str) -> usize { + let mut h = 0u32; + for b in name.bytes() { + h = h.wrapping_mul(31).wrapping_add(u32::from(b)); + } + h as usize % SHARDS +} + +/// One save at a time: serialising and publishing must not interleave, or an +/// older complete snapshot could be published over a newer one. +static SAVING: Mutex<()> = Mutex::new(()); + +fn libraries() -> Option<&'static [Mutex; SHARDS]> { + static LIBRARIES: OnceLock; SHARDS]>> = OnceLock::new(); + LIBRARIES .get_or_init(|| { let device = crate::host::host()?.device.cast::().ok()?; - let blob = DIR - .get() - .and_then(|d| std::fs::read(d.join(LIBRARY_FILE)).ok()) - .unwrap_or_default(); - let library = open(&device, blob); - if library.is_none() { - tracing::warn!("no host pipeline library: pipelines are not kept"); + let read = |file| DIR.get().and_then(|d| std::fs::read(d.join(file)).ok()); + let mut shards = Vec::with_capacity(SHARDS); + for shard in 0..SHARDS { + let blob = read(shard_file(shard)).unwrap_or_default(); + shards.push(Mutex::new(open(&device, blob)?)); } - library.map(Mutex::new) + shards.try_into().ok() }) .as_ref() } @@ -157,15 +180,16 @@ pub(crate) fn pipeline( create: impl FnOnce() -> windows::core::Result, ) -> windows::core::Result { let wide = HSTRING::from(name); - let Some(library) = library() else { + let Some(libraries) = libraries() else { MADE.fetch_add(1, Ordering::Relaxed); return create(); }; + let shard = &libraries[shard_of(name)]; // A load can be a whole compile under vkd3d-proton, whose library keeps // no compiled code; do not hold the store/serialise lock across it. The // host requires only same-name loads to serialise, so those get a lock of // their own and different pipelines still load in parallel. - let handle = library + let handle = shard .lock() .unwrap_or_else(|e| e.into_inner()) .library @@ -184,7 +208,7 @@ pub(crate) fn pipeline( // Compiled outside the lock: compiles take up to seconds. let pso = create()?; MADE.fetch_add(1, Ordering::Relaxed); - let mut l = library.lock().unwrap_or_else(|e| e.into_inner()); + let mut l = shard.lock().unwrap_or_else(|e| e.into_inner()); if l.stored.insert(name.to_owned()) { // SAFETY: a live pipeline; a name already stored in an earlier run // is refused, which leaves the library as it was. @@ -195,12 +219,12 @@ pub(crate) fn pipeline( Ok(pso) } -/// Writes the library and the early list if pipelines were added since the -/// last save and `SAVE_EVERY` has passed (or `now`). +/// Writes the shards that gained pipelines since the last save, and the +/// early list if it changed, when `SAVE_EVERY` has passed (or `now`). pub(crate) fn save(now: bool) { static LAST: Mutex> = Mutex::new(None); const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(20); - let (Some(dir), Some(library)) = (DIR.get(), library()) else { + let (Some(dir), Some(libraries)) = (DIR.get(), libraries()) else { return; }; { @@ -210,27 +234,14 @@ pub(crate) fn save(now: bool) { } *last = Some(std::time::Instant::now()); } - let blob = { - let mut l = library.lock().unwrap_or_else(|e| e.into_inner()); - if l.added == 0 && !USED_CHANGED.swap(false, Ordering::Relaxed) { - return; - } - // SAFETY: a buffer of the size the library asks for. - let bytes = unsafe { - let mut bytes = vec![0u8; l.library.GetSerializedSize()]; - l.library.Serialize(&mut bytes).map(|()| bytes) - }; - match bytes { - Ok(bytes) => { - l.added = 0; - bytes - } - Err(e) => { - tracing::warn!(error = %e, "host pipeline library not serialised"); - return; - } - } - }; + // Serialising and publishing are both inside this lock, so two saves + // cannot interleave and publish an older snapshot over a newer one. + let _saving = SAVING.lock().unwrap_or_else(|e| e.into_inner()); + if let Err(e) = std::fs::create_dir_all(dir) { + tracing::warn!(error = %e, "host pipeline library folder not made"); + return; + } + let used_changed = USED_CHANGED.load(Ordering::Relaxed); let used: Vec = USED .lock() .unwrap_or_else(|e| e.into_inner()) @@ -238,19 +249,56 @@ pub(crate) fn save(now: bool) { .flatten() .cloned() .collect(); - let written = std::fs::create_dir_all(dir) - .and_then(|()| write_atomically(&dir.join(LIBRARY_FILE), &blob)) - .and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes())); - match written { - Ok(()) => tracing::info!( - bytes = blob.len(), + let mut saved = 0u32; + let mut total = 0usize; + for (shard, library) in libraries.iter().enumerate() { + let (blob, added) = { + let l = library.lock().unwrap_or_else(|e| e.into_inner()); + if l.added == 0 { + continue; + } + // SAFETY: a buffer of the size the library asks for. + let bytes = unsafe { + let mut bytes = vec![0u8; l.library.GetSerializedSize()]; + l.library.Serialize(&mut bytes).map(|()| bytes) + }; + match bytes { + Ok(bytes) => (bytes, l.added), + Err(e) => { + tracing::warn!(error = %e, shard, "host pipeline library shard not serialised"); + continue; + } + } + }; + match write_atomically(&dir.join(shard_file(shard)), &blob) { + Ok(()) => { + // Cleared only once the bytes are published, by what was + // serialised: a failed write leaves the shard dirty for the + // next save, and a store during the write keeps it dirty. + let mut l = library.lock().unwrap_or_else(|e| e.into_inner()); + l.added = l.added.saturating_sub(added); + saved += 1; + total += blob.len(); + } + Err(e) => tracing::warn!(error = %e, shard, "host pipeline library shard not saved"), + } + } + if used_changed || saved > 0 { + match write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes()) { + Ok(()) => USED_CHANGED.store(false, Ordering::Relaxed), + Err(e) => tracing::warn!(error = %e, "early pipeline list not saved"), + } + } + if saved > 0 { + tracing::info!( + shards = saved, + bytes = total, early = used.len(), made = MADE.load(Ordering::Relaxed), loaded = LOADED.load(Ordering::Relaxed), started_early = EARLY.load(Ordering::Relaxed), "host pipeline library saved" - ), - Err(e) => tracing::warn!(error = %e, "host pipeline library not saved"), + ); } } @@ -314,6 +362,17 @@ mod tests { assert_ne!(a, name("graphics", b"root", &[b"vsp", b"s"], "state")); } + #[test] + fn a_pipeline_lands_in_one_shard_and_the_shards_spread() { + let first = name("graphics", b"root", &[b"vs", b"ps"], "state"); + assert_eq!(shard_of(&first), shard_of(&first), "stable across runs"); + let mut seen = [0usize; SHARDS]; + for i in 0..2048u32 { + seen[shard_of(&format!("{i:032x}"))] += 1; + } + assert!(seen.iter().all(|&n| n > 0), "every shard is used: {seen:?}"); + } + #[test] fn a_rejected_blob_gives_an_empty_library() { let Some(device) = crate::host::host().and_then(|h| h.device.cast::().ok()) From 843147361d0a01cfc7c71d6df31e8354c00ad4fd Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 04:09:37 +0000 Subject: [PATCH 2/4] GPU: share one aligned copy for unaligned buffer SRVs Port upstream Marvisak/VIctory#1260 (including its #986 base). Structured buffer SRVs whose shadow offset is not divisible by their element stride cannot be addressed with FirstElement on the shared shadow buffer. Their bytes now go into element-aligned upload memory and are bound through fresh dynamic descriptors. Copies are cached per command list by source range and alignment, so repeated draws of the same view share one upload instead of copying the same bytes for every draw. The upstream follow-up measured this as avoiding 286k copies / 35 GB in a few minutes of world rendering and keeping GTT around 4.6 GB on RADV. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/descriptor/host.rs | 103 ++++++++++++++++++++++ crates/victory-gpu/src/draw.rs | 25 +++++- crates/victory-gpu/src/host.rs | 56 ++++++++++-- 3 files changed, 173 insertions(+), 11 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 39e8a5a..4d60db8 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -545,6 +545,22 @@ impl HostHeap { }; } + /// Makes slot `index` (a dynamic one) a shader resource view of `resource`. + pub(crate) fn srv_at( + &self, + index: u32, + resource: &ID3D12Resource, + desc: &D3D12_SHADER_RESOURCE_VIEW_DESC, + ) { + let Some(host) = host() else { return }; + // SAFETY: a live resource and a slot of our heap. + unsafe { + host.device + .CreateShaderResourceView(resource, Some(desc), self.cpu(index)) + }; + self.keep(index, Some(resource.clone())); + } + fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { D3D12_CPU_DESCRIPTOR_HANDLE { ptr: self.cpu + index as usize * self.step as usize, @@ -722,6 +738,55 @@ fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> { )) } +/// If `view` is a buffer SRV whose offset in its shadow buffer is not a +/// multiple of its element stride (so `FirstElement` cannot address it on the +/// shared shadow buffer), returns `(title_src, byte_len, element_stride, desc)` +/// so the caller can copy the elements into an element-aligned scratch buffer. +pub(crate) fn unaligned_srv( + view: &View, +) -> Option<(u64, u64, u64, D3D12_SHADER_RESOURCE_VIEW_DESC)> { + let (address, len, words): (u64, u64, &[u32; 10]) = match view { + View::Shader(r, Some(words)) => { + if crate::resource::host_resource(*r as crate::object::This).is_some() { + return None; + } + let (data, len) = crate::resource::buffer_bytes(*r as crate::object::This)?; + (data as u64, len, words) + } + View::Placed(false, resource, desc) if resource[0] == 1 => ( + u64::from(desc[10]) | u64::from(desc[11]) << 32, + u64::from(resource[4]) | u64::from(resource[5]) << 32, + desc[..10].try_into().ok()?, + ), + _ => return None, + }; + let mut desc = srv_desc(words); + if desc.ViewDimension != D3D12_SRV_DIMENSION_BUFFER { + return None; + } + let element = element_size(&desc); + if element == 0 { + return None; + } + let shadow = crate::shadow::find(address, len)?; + if shadow.offset(address) % element == 0 { + return None; + } + // SAFETY: checked ViewDimension == BUFFER. + let buffer = unsafe { &mut desc.Anonymous.Buffer }; + let first_bytes = buffer.FirstElement.checked_mul(element)?; + let avail = len.saturating_sub(first_bytes); + let max_elems = (avail / element).min(u64::from(u32::MAX)) as u32; + if buffer.NumElements > max_elems { + buffer.NumElements = max_elems; + } + let bytes = u64::from(buffer.NumElements) * element; + if bytes == 0 { + return None; + } + Some((address + first_bytes, bytes, element, desc)) +} + /// The host resource a slot made by [`make`] views, if any. type Kept = Option; @@ -1237,4 +1302,42 @@ mod tests { assert_eq!(heap.dynamic(50), Some(4)); assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); } + + /// A placed structured buffer SRV whose offset in its shadow buffer is not + /// a multiple of its stride is flagged for element-aligned copying. + #[test] + fn unaligned_buffer_srv_is_detected() { + if host().is_none() { + return; // no host GPU + } + let start = 0x7000_0000u64; + let resource_id = 0xDEAD_BEEF_usize; + crate::shadow::register(resource_id, start, 4096); + + let placed = |addr: u64, num_elements: u32, stride: u32| { + let mut res = [0u32; 14]; + res[0] = 1; // BUFFER + res[4] = num_elements * stride; + let mut desc = [0u32; 16]; + desc[1] = 1; // D3D12_SRV_DIMENSION_BUFFER + desc[2] = 5768; // default component mapping + desc[6] = num_elements; + desc[7] = stride; + desc[10] = addr as u32; + desc[11] = (addr >> 32) as u32; + View::Placed(false, res, desc) + }; + + // Offset 112 is a multiple of stride 56 -> aligned on the shadow buffer. + assert!(unaligned_srv(&placed(start + 112, 2, 56)).is_none()); + + // Offset 16 is not a multiple of stride 56 -> must be copied aligned. + let (src, bytes, align, desc) = + unaligned_srv(&placed(start + 16, 2, 56)).expect("unaligned"); + assert_eq!((src, bytes, align), (start + 16, 112, 56)); + // SAFETY: checked BUFFER dimension. + assert_eq!(unsafe { desc.Anonymous.Buffer.NumElements }, 2); + + crate::shadow::unregister(resource_id, start); + } } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index a25f9e7..30e5c6c 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -902,7 +902,13 @@ impl State { let (Some(host), Some(index)) = (heap.host(), heap.index(end)) else { continue; }; - if index >= host.count() { + if index >= host.count() + || (u.kind == ResourceType::Srv + && crate::descriptor::view(end) + .as_ref() + .and_then(crate::descriptor::host::unaligned_srv) + .is_some()) + { fresh.push(u.slot); } } @@ -985,9 +991,20 @@ impl State { host.constant_at(index, gpu, size); } Some(view) => { - host.make_at(index, &view); - if let Some(u) = used { - readable(list, u, &view); + if let Some((src, len, align, mut desc)) = + crate::descriptor::host::unaligned_srv(&view) + { + if let Some((buf, at)) = list.aligned_copy(src, len, align) { + desc.Anonymous.Buffer.FirstElement = at / align; + host.srv_at(index, &buf, &desc); + } else { + host.make_null(index); + } + } else { + host.make_at(index, &view); + if let Some(u) = used { + readable(list, u, &view); + } } } None => { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 0a57b81..00769ed 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -367,6 +367,10 @@ struct Scratch { chunks: Vec<(ID3D12Resource, usize, u64)>, current: usize, used: u64, + /// Element-aligned copies of title bytes made for this list, by + /// (source, length, alignment): every draw reading the same view range + /// shares one copy instead of making its own. + copies: std::collections::HashMap<(u64, u64, u64), (ID3D12Resource, u64)>, } // SAFETY: the chunk pointers are persistent mappings of upload buffers. @@ -956,6 +960,7 @@ impl HostList { { let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); (scratch.current, scratch.used) = (0, 0); + scratch.copies.clear(); } // SAFETY: the list is not executing. let reset = unsafe { @@ -1241,18 +1246,54 @@ impl HostList { /// `len` bytes of upload memory (256-byte aligned) until the list is /// reset: the host GPU address and the CPU pointer. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> { + let (_, at, gpu, data) = self.scratch_in(len.max(1).next_multiple_of(256), 256)?; + Some((gpu + at, data)) + } + + /// `len` bytes of upload memory aligned to `align` until the list is + /// reset: the host resource, byte offset within it, and CPU pointer. + pub(crate) fn scratch_aligned( + &self, + len: u64, + align: u64, + ) -> Option<(ID3D12Resource, u64, *mut u8)> { + let (buf, at, _, data) = self.scratch_in(len.max(1), align.max(1))?; + Some((buf, at, data)) + } + + /// An element-aligned copy of `len` title bytes at `src`, filled at + /// submission and shared by every use in this list until it is reset: + /// the host buffer and the copy's byte offset in it. + pub(crate) fn aligned_copy( + &self, + src: u64, + len: u64, + align: u64, + ) -> Option<(ID3D12Resource, u64)> { + let key = (src, len, align); + let scratch = || self.scratch.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(hit) = scratch().copies.get(&key) { + return Some(hit.clone()); + } + let (buf, at, to) = self.scratch_aligned(len, align)?; + self.defer_fill(to, src as *const u8, len as usize); + scratch().copies.insert(key, (buf.clone(), at)); + Some((buf, at)) + } + + fn scratch_in(&self, len: u64, align: u64) -> Option<(ID3D12Resource, u64, u64, *mut u8)> { let host = host()?; let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); - let len = len.max(1).next_multiple_of(256); if len > SCRATCH_CHUNK { let (buffer, data) = host.upload_buffer(len)?; name(&buffer, || format!("list scratch {len:#x}")); // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; - self.deferred().uploads.push(buffer); - return Some((gpu, data)); + self.deferred().uploads.push(buffer.clone()); + return Some((buffer, 0, gpu, data)); } - if s.used + len > SCRATCH_CHUNK && s.current < s.chunks.len() { + let at = s.used.next_multiple_of(align); + if at + len > SCRATCH_CHUNK && s.current < s.chunks.len() { (s.current, s.used) = (s.current + 1, 0); } if s.current == s.chunks.len() { @@ -1263,10 +1304,11 @@ impl HostList { s.chunks.push((buffer, data as usize, gpu)); s.used = 0; } + let buffer = s.chunks[s.current].0.clone(); let (_, data, gpu) = s.chunks[s.current]; - let at = s.used; - s.used += len; - Some((gpu + at, (data + at as usize) as *mut u8)) + let at = s.used.next_multiple_of(align); + s.used = at + len; + Some((buffer, at, gpu, (data + at as usize) as *mut u8)) } /// The host address of the list's indirect-work budget, zeroed at each From 6e173496a3c503ebd2e3fda33e9e2f3a819805eb Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 04:09:47 +0000 Subject: [PATCH 3/4] Formats: inline uniform micro-tile runs in texture copies Port upstream Marvisak/VIctory#603. Rows made of uniform micro-tile runs now copy those runs with compile-time lengths (8/16/32 bytes), letting the compiler inline small copies instead of using a variable-length copy for every run. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-formats/src/texture.rs | 28 +++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 5daa839..e5681fa 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -744,6 +744,13 @@ impl Layout { } runs.push((first_tiled, first_linear, bytes - first_linear)); } + // A mip can end partway through the last run. Check the other runs + // once so each row can copy them with a compile-time length. + let (body, last) = runs.split_at(runs.len().saturating_sub(1)); + let run_len = body + .first() + .map(|run| run.2) + .filter(|&len| body.iter().all(|run| run.2 == len)); for z in 0..depth { let (s, inner) = self.split(first + z); let base = u64::from(s) * self.slice_size + m.offset; @@ -754,9 +761,13 @@ impl Layout { copy(tiled_row as usize, linear_row, bytes); } else { let tiled_row = (base + self.row(m, y, inner)) as usize; - for &(tiled, linear, len) in &runs { - copy(tiled_row + tiled, linear_row + linear, len); + match run_len { + Some(8) => copy_runs::<8>(body, tiled_row, linear_row, &mut copy), + Some(16) => copy_runs::<16>(body, tiled_row, linear_row, &mut copy), + Some(32) => copy_runs::<32>(body, tiled_row, linear_row, &mut copy), + _ => copy_runs::<0>(body, tiled_row, linear_row, &mut copy), } + copy_runs::<0>(last, tiled_row, linear_row, &mut copy); } } } @@ -764,6 +775,19 @@ impl Layout { } } +/// Copy micro-tile runs inline at a known width, or use each run's length for N = 0. +fn copy_runs( + runs: &[(usize, usize, usize)], + tiled_row: usize, + linear_row: usize, + copy: &mut impl FnMut(usize, usize, usize), +) { + for &(tiled, linear, len) in runs { + let len = if N == 0 { len } else { N }; + copy(tiled_row + tiled, linear_row + linear, len); + } +} + /// What a DXGI format stores per element: bytes, texels per element side /// (4 for block compression), and whether its stencil is a second plane /// (the GPU keeps depth and stencil apart). From 845df6cf6b7e08e7a417b4fd378baf2e36a81d87 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 04:10:08 +0000 Subject: [PATCH 4/4] Formats: share immutable texture swizzle tables Port upstream Marvisak/VIctory#993. Swizzle coordinate tables depend only on tile kind, block size and element size, not on texture dimensions. Layouts now share those immutable tables through keyed OnceLock slots instead of allocating identical vectors for every texture layout. Includes the upstream benchmark example and regression test that layouts with the same key share table storage. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../examples/texture_layout_bench.rs | 89 +++++++++++++++++++ crates/victory-formats/src/texture.rs | 64 +++++++++++-- 2 files changed, 147 insertions(+), 6 deletions(-) create mode 100644 crates/victory-formats/examples/texture_layout_bench.rs diff --git a/crates/victory-formats/examples/texture_layout_bench.rs b/crates/victory-formats/examples/texture_layout_bench.rs new file mode 100644 index 0000000..53c3936 --- /dev/null +++ b/crates/victory-formats/examples/texture_layout_bench.rs @@ -0,0 +1,89 @@ +//! Run with `cargo run --release -p victory-formats --example texture_layout_bench`. + +use std::hint::black_box; +use std::time::Instant; + +use victory_formats::texture::{Dimension, Swizzle, Texture, TextureDesc}; + +fn main() { + const CALLS: u64 = 50_000; + let base = TextureDesc { + dimension: Dimension::Tex2d, + width: 512, + height: 512, + depth_or_array: 1, + mips: 0, + format: 98, // BC7 + samples: 1, + swizzle: Swizzle::SW_64KB_D, + }; + let cases = [ + ("BC7 64KB_D", base), + ( + "BC1 64KB_S", + TextureDesc { + format: 71, + swizzle: Swizzle::SW_64KB_S, + ..base + }, + ), + ( + "RGBA8 4KB_D", + TextureDesc { + format: 28, + swizzle: Swizzle::SW_4KB_D, + ..base + }, + ), + ( + "R8 64KB_S", + TextureDesc { + format: 61, + swizzle: Swizzle::SW_64KB_S, + ..base + }, + ), + ( + "RGBA8 volume 64KB_S", + TextureDesc { + dimension: Dimension::Tex3d, + width: 128, + height: 128, + depth_or_array: 64, + format: 28, + swizzle: Swizzle::SW_64KB_S, + ..base + }, + ), + ( + "RGBA8 linear", + TextureDesc { + format: 28, + swizzle: Swizzle::LINEAR, + ..base + }, + ), + ]; + + for (name, desc) in cases { + let mut samples = [0.0; 7]; + black_box(Texture::new(black_box(&desc)).unwrap()); + let mut checksum = 0u64; + for sample in &mut samples { + let start = Instant::now(); + for i in 0..CALLS { + let desc = TextureDesc { + width: desc.width + (i % 32) as u32, + ..desc + }; + let texture = black_box(Texture::new(black_box(&desc)).unwrap()); + let layout = &texture.planes[0].layout; + checksum = + checksum.wrapping_add(texture.size + layout.offset(0, 7, 11, 0).unwrap()); + } + *sample = start.elapsed().as_secs_f64() * 1e9 / CALLS as f64; + } + samples.sort_by(f64::total_cmp); + println!("{name:22} {:8.1} ns/layout {checksum}", samples[3]); + } +} diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index e5681fa..e31bea3 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -30,6 +30,8 @@ //! Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, //! EXPRESS OR IMPLIED. +use std::sync::OnceLock; + /// A swizzle mode, by its hardware number (addrlib's `ADDR_SW_*` order). #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Swizzle(pub u32); @@ -174,11 +176,14 @@ pub struct Layout { /// The first mip in the tail; `mips.len()` without one. pub first_tail_mip: u32, pub mips: Vec, - /// Byte offsets inside a block of each element coordinate bit, per - /// axis; empty for linear and unsupported modes. - pattern: [Vec; 3], + /// Byte offsets inside a block for each coordinate, per axis. + /// Empty for linear and unsupported modes. + pattern: &'static SwizzlePattern, } +type SwizzlePattern = [Vec; 3]; +static EMPTY_PATTERN: SwizzlePattern = [const { Vec::new() }; 3]; + /// Micro tile (256 bytes) patterns by log2 of the element size: for each /// address bit, the element coordinate bit it takes (`x0`, `y1`, `z0`...), /// `--` for the bits inside an element. Thin `S`, thin `D`, thick `S` @@ -247,6 +252,18 @@ fn spread(bits: &[u32]) -> Vec { .collect() } +/// Tables depend only on the micro-tile kind, block size and element size. +/// Texture extents, mip placement and array slices only affect the base +/// address, so layouts with the same key can share these immutable tables. +fn shared_pattern(kind: usize, element_log2: u32, block_log2: u32) -> &'static SwizzlePattern { + // Indexed by MICRO kind, block size (256 B, 4 KiB, 64 KiB), then element size. + static PATTERNS: [[[OnceLock; 5]; 3]; 3] = + [const { [const { [const { OnceLock::new() }; 5] }; 3] }; 3]; + let block_index = ((block_log2 - 8) / 4) as usize; + PATTERNS[kind][block_index][element_log2 as usize] + .get_or_init(|| pattern(kind, element_log2, block_log2).map(|bits| spread(&bits))) +} + const MAX_MIPS: u32 = 16; /// The largest width, height and depth (or array size) accepted, in texels. @@ -322,7 +339,7 @@ impl Layout { alignment: 256, first_tail_mip: d.mips, mips, - pattern: Default::default(), + pattern: &EMPTY_PATTERN, } } @@ -498,9 +515,9 @@ impl Layout { } else { usize::from(d.swizzle.display()) }; - pattern(kind, element_log2, block_log2).map(|bits| spread(&bits)) + shared_pattern(kind, element_log2, block_log2) } else { - Default::default() + &EMPTY_PATTERN }; Layout { desc: d, @@ -1155,6 +1172,41 @@ mod tests { assert_eq!(l.offset(0, 0, 16, 0), Ok(8192)); } + #[test] + fn layouts_share_identical_swizzle_tables() { + for (swizzle, kind, dimension, block_log2) in [ + (Swizzle::SW_256B_S, 0, Dimension::Tex2d, 8), + (Swizzle::SW_256B_D, 1, Dimension::Tex2d, 8), + (Swizzle::SW_4KB_S, 0, Dimension::Tex2d, 12), + (Swizzle::SW_4KB_D, 1, Dimension::Tex2d, 12), + (Swizzle::SW_64KB_S, 0, Dimension::Tex2d, 16), + (Swizzle::SW_64KB_D, 1, Dimension::Tex2d, 16), + (Swizzle::SW_4KB_S, 2, Dimension::Tex3d, 12), + (Swizzle::SW_64KB_S, 2, Dimension::Tex3d, 16), + ] { + for element_log2 in 0..5 { + let d = Desc { + dimension, + depth: 8, + ..desc(128, 96, 7, 1 << element_log2, swizzle) + }; + let first = Layout::new(&d).unwrap(); + let second = Layout::new(&Desc { + width: 32, + height: 24, + mips: 3, + depth: 1, + ..d + }) + .unwrap(); + let expected = pattern(kind, element_log2, block_log2).map(|bits| spread(&bits)); + assert_eq!(first.pattern, &expected); + assert!(std::ptr::eq(first.pattern, second.pattern)); + assert!(std::ptr::eq(first.pattern, first.clone().pattern)); + } + } + } + /// A 256x256 BC7 chain in 64 KiB `D`: one tail block holding mips 1-8, /// then mip 0; mip 1 sits at x = 32 elements, 32 KiB into the tail. #[test]