From 7c0d9f9bb344fdb2cc2a93bd7a1e924d74b7faa3 Mon Sep 17 00:00:00 2001 From: gdemontalivet Date: Thu, 26 Nov 2026 18:30:28 +0000 Subject: [PATCH 1/2] perf(gpu): detile and upload only touched rows on tracked texture writes Port dirty-row partial texture detiling and upload so a tracked write into a subresource that owns a changed page reads, detiles, and copies only the affected element-row band through a block-aligned D3D12_BOX instead of re-reading and detiling the entire mip: - victory-formats: add Layout::touched_rows and Layout::detile_rows, extending the paired-row walk_runs loop to support arbitrary (including odd-starting) row ranges without breaking row-pair alignment. - victory-gpu (watch): add Tracked::retry to requeue taken pages when staging allocation or detiling fails so dirty updates are never dropped. - victory-gpu (texture): plan per-subresource row bands on tracked writes (with VICTORY_DIRTY_ROWS=0 opt-out for A/B testing), exclude subresources overlapping untracked memory from partial-row skipping so ordinary-memory rows never go stale, scale block-compressed D3D12_BOX row bounds by block size, and requeue failed uploads via Tracked::retry. - Add format parity/timing tests and D3D12/D3DMetal GPU tests covering partial RGBA8 and BC1/BC7 row uploads, mixed tracked+untracked mips, and deferred staging retry. --- crates/victory-formats/src/texture.rs | 292 ++++++++++++++- crates/victory-gpu/src/draw.rs | 68 ++++ .../src/draw/tests/tracked_rows.rs | 249 +++++++++++++ crates/victory-gpu/src/texture.rs | 331 +++++++++++++++--- crates/victory-gpu/src/watch.rs | 10 + 5 files changed, 897 insertions(+), 53 deletions(-) create mode 100644 crates/victory-gpu/src/draw/tests/tracked_rows.rs diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 08f5f96c..7f98b8e6 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -623,9 +623,108 @@ impl Layout { slice, row_pitch, depth_pitch, + None, ) } + /// As [`Layout::detile`], but only rows `rows` (in elements, of every + /// depth slice) are written; the other rows of `linear` keep what they + /// held. The tiled bytes read lie in the span [`Layout::touched_rows`] + /// gives for those rows. + #[allow(clippy::too_many_arguments)] + pub fn detile_rows( + &self, + tiled: &[u8], + mip: u32, + slice: u32, + linear: &mut [u8], + row_pitch: usize, + depth_pitch: usize, + rows: std::ops::Range, + ) -> Result<(), Error> { + self.walk( + Buffers::Detile { tiled, linear }, + mip, + slice, + row_pitch, + depth_pitch, + Some(rows), + ) + } + + /// The rows (in elements, the same for every depth slice) of mip `mip` + /// of array slice `slice` (3D: 0) whose tiled bytes overlap `ranges` + /// (byte offsets into the texture's memory, sorted and disjoint), and + /// the bytes of the memory those rows read. An empty row range if none + /// do; `None` if the layout cannot say. + pub fn touched_rows( + &self, + mip: u32, + slice: u32, + ranges: &[(usize, usize)], + ) -> Option<(std::ops::Range, std::ops::Range)> { + let m = self.mips.get(mip as usize)?; + let first = if self.desc.dimension == Dimension::Tex3d { + (slice == 0).then_some(0)? + } else { + slice + }; + if first >= self.slices || !self.addressable() { + return None; + } + let n = self.desc.element_bytes as usize; + let linear = self.desc.swizzle == Swizzle::LINEAR; + // A row's bytes lie in [row start + lo, row start + hi). + let (lo, hi) = if linear { + (0, m.width as usize * n) + } else { + let (mut lo, mut hi) = (usize::MAX, 0usize); + for x in 0..m.width { + let c = self.column(m, x) as usize; + lo = lo.min(c); + hi = hi.max(c + n); + } + if lo >= hi { + return None; + } + (lo, hi) + }; + let start = |z: u32, y: u32| { + let (s, inner) = self.split(first + z); + let base = u64::from(s) * self.slice_size + m.offset; + (if linear { + base + u64::from(y) * u64::from(m.pitch) * n as u64 + } else { + base + self.row(m, y, inner) + }) as usize + }; + let hit = |a: usize, b: usize| { + ranges + .get(ranges.partition_point(|r| r.1 <= a)) + .is_some_and(|r| r.0 < b) + }; + let (mut y0, mut y1) = (u32::MAX, 0); + for z in 0..m.depth { + for y in 0..m.height { + let at = start(z, y); + if hit(at + lo, at + hi) { + (y0, y1) = (y0.min(y), y1.max(y + 1)); + } + } + } + if y0 >= y1 { + return Some((0..0, 0..0)); + } + let (mut a, mut b) = (usize::MAX, 0); + for z in 0..m.depth { + for y in y0..y1 { + let at = start(z, y); + (a, b) = (a.min(at + lo), b.max(at + hi)); + } + } + Some((y0..y1, a..b)) + } + /// The reverse of [`Layout::detile`]: linear rows into tiled memory. pub fn tile( &self, @@ -642,6 +741,7 @@ impl Layout { slice, row_pitch, depth_pitch, + None, ) } @@ -653,6 +753,7 @@ impl Layout { slice: u32, row_pitch: usize, depth_pitch: usize, + rows: Option>, ) -> Result<(), Error> { let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; let depth = m.depth; @@ -693,10 +794,17 @@ impl Layout { if tiled_len < self.size as usize || linear_len < need || row_pitch < bytes { return Err(Error::TooSmall); } + let row_range = match rows { + Some(r) => r.start.min(m.height)..r.end.min(m.height), + None => 0..m.height, + }; + if row_range.is_empty() { + return Ok(()); + } if self.desc.swizzle == Swizzle::LINEAR { for z in 0..depth { let base = (u64::from(first + z) * self.slice_size + m.offset) as usize; - for y in 0..m.height as usize { + for y in row_range.start as usize..row_range.end as usize { copy.span( base + y * m.pitch as usize * n, z as usize * depth_pitch + y * row_pitch, @@ -716,10 +824,10 @@ impl Layout { .take_while(|&(x, &offset)| offset as usize == x * n) .count(); match run * n { - 4 => self.walk_runs::<4>(m, first, row_pitch, depth_pitch, &mut copy), - 8 => self.walk_runs::<8>(m, first, row_pitch, depth_pitch, &mut copy), - 16 => self.walk_runs::<16>(m, first, row_pitch, depth_pitch, &mut copy), - 32 => self.walk_runs::<32>(m, first, row_pitch, depth_pitch, &mut copy), + 4 => self.walk_runs::<4>(m, first, row_pitch, depth_pitch, row_range, &mut copy), + 8 => self.walk_runs::<8>(m, first, row_pitch, depth_pitch, row_range, &mut copy), + 16 => self.walk_runs::<16>(m, first, row_pitch, depth_pitch, row_range, &mut copy), + 32 => self.walk_runs::<32>(m, first, row_pitch, depth_pitch, row_range, &mut copy), _ => unreachable!("GFX10 contiguous run width"), } Ok(()) @@ -731,6 +839,7 @@ impl Layout { first: u32, row_pitch: usize, depth_pitch: usize, + row_range: std::ops::Range, copy: &mut Buffers<'_>, ) { let n = self.desc.element_bytes as usize; @@ -749,10 +858,12 @@ impl Layout { for slab in (0..m.depth).step_by(bd as usize) { let (slice, _) = self.split(first + slab); let base = u64::from(slice) * self.slice_size + m.offset; - for y in (0..m.height).step_by(rows) { + let mut y = row_range.start; + while y < row_range.end { // Tail origins and row pairs both start on even y. The low y // bit gives the distance to the second row in this block. - let second = (rows == 2 && y + 1 < m.height).then(|| self.pattern[1][1] as usize); + let pair = rows == 2 && (y & 1) == 0 && y + 1 < row_range.end; + let second = pair.then(|| self.pattern[1][1] as usize); let row = base + self.row(m, y, 0); // Depth slices in this slab share the same physical blocks. for inner in 0..bd.min(m.depth - slab) { @@ -766,6 +877,7 @@ impl Layout { } } } + y += if pair { 2 } else { 1 }; } } } @@ -1235,6 +1347,172 @@ mod tests { assert_eq!((l.size, l.alignment), (65536, 65536)); } + #[test] + fn detiling_the_touched_rows_matches_detiling_all() { + let cases = [ + desc(30, 20, 5, 4, Swizzle::LINEAR), + desc(83, 31, 6, 1, Swizzle::SW_256B_S), + Desc { + block: 4, + ..desc(109, 71, 6, 16, Swizzle::SW_256B_D) + }, + Desc { + depth: 3, + ..desc(70, 70, 4, 16, Swizzle::SW_4KB_S) + }, + desc(512, 300, 4, 4, Swizzle::SW_64KB_S), + Desc { + block: 4, + ..desc(256, 256, 7, 16, Swizzle::SW_64KB_D) + }, + Desc { + dimension: Dimension::Tex3d, + depth: 16, + ..desc(64, 32, 7, 4, Swizzle::SW_4KB_S) + }, + ]; + let mut seed = 0x9e37_79b9_u32; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed + }; + let mut partial = 0; + let mut odd_start = 0; + for d in cases { + let l = Layout::new(&d).unwrap(); + let size = l.size as usize; + let a: Vec = (0..size).map(|_| next() as u8).collect(); + let n = d.element_bytes as usize; + let slices = if d.dimension == Dimension::Tex3d { + 1 + } else { + d.depth + }; + for page in [256usize, 4096, 65536] { + for _ in 0..6 { + let from = (next() as usize % size) / page * page; + let ranges = [(from, (from + page).min(size))]; + let mut b = a.clone(); + for x in &mut b[ranges[0].0..ranges[0].1] { + *x = x.wrapping_add(1); + } + for slice in 0..slices { + for mip in 0..l.mips.len() as u32 { + let m = l.mips[mip as usize]; + let row = m.width as usize * n + 5; + let plane = row * m.height as usize + 3; + let len = plane * m.depth as usize; + let (mut la, mut lb) = (vec![0u8; len], vec![0u8; len]); + l.detile(&a, mip, slice, &mut la, row, plane).unwrap(); + l.detile(&b, mip, slice, &mut lb, row, plane).unwrap(); + let (rows, span) = l.touched_rows(mip, slice, &ranges).unwrap(); + assert!(span.end <= size, "{d:?} mip {mip}"); + partial += usize::from(!rows.is_empty() && rows.len() < m.height as usize); + // Only the bytes of the span are read: the rest garbage. + let mut tiled = vec![0xcc; size]; + tiled[span.clone()].copy_from_slice(&b[span.clone()]); + let mut part = vec![0xcc; len]; + l.detile_rows(&tiled, mip, slice, &mut part, row, plane, rows.clone()) + .unwrap(); + for z in 0..m.depth as usize { + for y in 0..m.height { + let at = z * plane + y as usize * row; + let r = at..at + m.width as usize * n; + if rows.contains(&y) { + assert_eq!( + part[r.clone()], + lb[r], + "{d:?} mip {mip} slice {slice} row {y}" + ); + } else { + assert_eq!( + la[r.clone()], + lb[r.clone()], + "{d:?} mip {mip} row {y} changed outside {rows:?}" + ); + assert!(part[r].iter().all(|&x| x == 0xcc)); + } + } + } + // Also exercise an explicit odd-starting row slice on + // paired-row tiled layouts. + if m.height >= 4 && slice == 0 && mip == 0 { + let odd = 1..m.height - 1; + let mut odd_out = vec![0xcc; len]; + l.detile_rows(&b, mip, slice, &mut odd_out, row, plane, odd.clone()) + .unwrap(); + for z in 0..m.depth as usize { + for y in 0..m.height { + let at = z * plane + y as usize * row; + let r = at..at + m.width as usize * n; + if odd.contains(&y) { + assert_eq!( + odd_out[r.clone()], + lb[r], + "odd slice {d:?} row {y}" + ); + } else { + assert!(odd_out[r].iter().all(|&x| x == 0xcc)); + } + } + } + odd_start += 1; + } + } + } + } + } + } + assert!(partial > 50, "only {partial} partial row ranges"); + assert!(odd_start > 0); + } + + /// Timing (run with --release --ignored --nocapture): one 64 KiB page + /// written into mip 0 of a 4096x4096 BC7 texture, detiled whole (as a + /// changed subresource is without the rows) and as its touched rows. + #[test] + #[ignore] + fn detile_the_rows_of_one_written_page_of_a_4k_bc7_texture() { + let d = Desc { + block: 4, + ..desc(4096, 4096, 13, 16, Swizzle::SW_64KB_S) + }; + let l = Layout::new(&d).unwrap(); + let m = l.mips[0]; + let tiled: Vec = (0..l.size as usize).map(|i| (i * 31) as u8).collect(); + let row = m.width as usize * 16; + let mut linear = vec![0u8; row * m.height as usize]; + let from = (l.mips[0].offset as usize + + (m.width as usize * 16 * m.height as usize) / 2) + / 65536 + * 65536; + let ranges = [(from, from + 65536)]; + let runs = 20; + let t = std::time::Instant::now(); + for _ in 0..runs { + l.detile(&tiled, 0, 0, &mut linear, row, 0).unwrap(); + } + let whole = t.elapsed() / runs; + let t = std::time::Instant::now(); + let mut band = (0..0, 0..0); + for _ in 0..runs { + band = l.touched_rows(0, 0, &ranges).unwrap(); + l.detile_rows(&tiled, 0, 0, &mut linear, row, 0, band.0.clone()) + .unwrap(); + } + let rows = t.elapsed() / runs; + println!( + "BC7 4096x4096 mip 0 ({} rows, {} KiB): whole {whole:?}; rows {:?} ({} rows, {} KiB of tiled memory read) {rows:?}", + m.height, + row * m.height as usize / 1024, + band.0, + band.0.len(), + band.1.len() / 1024 + ); + } + /// Every element of every mip and slice lands on its own address, inside /// the texture, and tiling then detiling gives the rows back. #[test] diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e774813a..410cf3c1 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2113,6 +2113,8 @@ const QUAD_STRIP: u32 = 20; #[cfg(test)] mod tests { + mod tracked_rows; + use super::*; /// A root signature that indexes the heaps directly needs one of each @@ -3598,6 +3600,72 @@ void main(uint3 id : SV_DispatchThreadID) { assert_eq!(submit(Some(0x80)).0, 0, "the same bytes in a shared page: not uploaded"); } + /// A title write into one page of a large mip detiles and copies the + /// rows of that page alone: the rows written arrive, the other rows + /// keep what the host texture held. + #[test] + fn a_write_into_one_page_uploads_its_rows_alone() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let slots = Slots::new(2); + let read = compile_cs(READ, READS); + let (out, data) = host.shared_buffer(64 * 64 * 16).unwrap(); + // RGBA8 512x512, one mip, linear, in memory the journal follows. + let address = crate::watch::tests::pool(32) as u64; + let object = texture_at_address(address, &texture_words(512, 512, 28, 0x100, 0)); + let (_, desc) = crate::resource::texture_memory(object).unwrap(); + let layout = crate::resource::texture_layout(&desc) + .unwrap() + .planes[0] + .layout + .clone(); + let row = |y: u32| layout.offset(0, 0, y, 0).unwrap() as usize; + assert_eq!(row(32) % crate::watch::PAGE, 0, "rows 32.. start a page"); + assert!( + row(64) - row(32) <= crate::watch::PAGE, + "rows 32..64 within one page" + ); + // SAFETY: the texture's memory (its layout's size). + unsafe { std::ptr::write_bytes(address as *mut u8, 0x40, layout.size as usize) }; + let mut view = [0u32; 10]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + let view = View::Shader(object as usize, Some(view)); + slots.make(0, &view); + let submit = || { + let list = host.new_list().unwrap(); + readable(&list, &used(ResourceType::Srv), &view, false); + run(&list, &slots, &read, 0, Some(&out), (8, 8)); + list.close(); + let before = crate::texture::copied(object); + host.execute(&[&list]); + // SAFETY: inside the mapped output, 64x64 texels of 16 bytes. + let rows: Vec = (0..64) + .map(|y| unsafe { (data as *const [f32; 4]).add(y * 64).read()[0] }) + .collect(); + (crate::texture::copied(object) - before, rows) + }; + let is = |x: f32, b: u8| (x - f32::from(b) / 255.0).abs() < 1e-6; + let (n, rows) = submit(); + assert_eq!(n, 1); + assert!(rows.iter().all(|&x| is(x, 0x40)), "{rows:?}"); + let page = crate::watch::PAGE; + // SAFETY: one page of the texture's memory, rows 32.. . + unsafe { std::ptr::write_bytes((address as usize + row(32)) as *mut u8, 0x80, page) }; + let (n, rows) = submit(); + assert_eq!(n, 1); + for (y, &x) in rows.iter().enumerate() { + assert!(is(x, if y < 32 { 0x40 } else { 0x80 }), "row {y}: {x}"); + } + // SAFETY: the first page, rows ..32. + unsafe { std::ptr::write_bytes(address as *mut u8, 0xc0, page) }; + let (n, rows) = submit(); + assert_eq!(n, 1); + for (y, &x) in rows.iter().enumerate() { + assert!(is(x, if y < 32 { 0xc0 } else { 0x80 }), "row {y}: {x}"); + } + } + /// A list recorded before another whose host copy writes a texture it /// reads, but run after it, reads the host's texels: whether its upload /// from title memory is still due is decided when its submission is diff --git a/crates/victory-gpu/src/draw/tests/tracked_rows.rs b/crates/victory-gpu/src/draw/tests/tracked_rows.rs new file mode 100644 index 00000000..d7b189a7 --- /dev/null +++ b/crates/victory-gpu/src/draw/tests/tracked_rows.rs @@ -0,0 +1,249 @@ +use super::*; +use crate::watch::PAGE; +use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, +}; + +/// Two adjacent live allocations, ordinary committed memory followed by a +/// write-watched pool. +fn mixed_pages() -> usize { + let flags = MEM_RESERVE | MEM_COMMIT; + for _ in 0..16 { + // SAFETY: ask Windows for a candidate address. Another allocator + // may win it after release, so check both following reservations. + unsafe { + let slot = VirtualAlloc(std::ptr::null(), 3 * PAGE, MEM_RESERVE, PAGE_READWRITE); + assert!(!slot.is_null()); + assert_ne!(VirtualFree(slot, 0, MEM_RELEASE), 0); + let ordinary = VirtualAlloc(slot, PAGE, flags, PAGE_READWRITE); + if ordinary.is_null() { + continue; + } + let pool = (ordinary as usize + PAGE) as *mut std::ffi::c_void; + if !VirtualAlloc( + pool, + 2 * PAGE, + flags | crate::watch::tests::MEM_WRITE_WATCH, + PAGE_READWRITE, + ) + .is_null() + { + return ordinary as usize; + } + assert_ne!(VirtualFree(ordinary, 0, MEM_RELEASE), 0); + } + } + panic!("could not allocate adjacent watched and ordinary pages"); +} + +fn check_rows(address: usize, mixed: bool) { + let host = crate::host::host().unwrap(); + const WIDTH: usize = 64; + const ROWS_PER_PAGE: usize = PAGE / (WIDTH * 4); + const HEIGHT: usize = 3 * ROWS_PER_PAGE; + let fill = |page: usize, value: u8| { + let at = address + page * PAGE; + let _writing = crate::watch::writing(at, PAGE); + // SAFETY: each of the three pages is a live allocation owned by this test. + unsafe { std::ptr::write_bytes(at as *mut u8, value, PAGE) }; + }; + let object = + texture_at_address(address as u64, &texture_words(WIDTH as u32, HEIGHT as u32, 28, 0x100, 0)); + let (_, desc) = crate::resource::texture_memory(object).unwrap(); + let layout = crate::resource::texture_layout(&desc).unwrap(); + let layout = &layout.planes[0].layout; + assert_eq!(layout.offset(0, 0, ROWS_PER_PAGE as u32, 0).unwrap(), PAGE as u64); + assert_eq!(layout.size, (3 * PAGE) as u64); + let copy = crate::resource::host_copy(object).unwrap(); + let staging = crate::texture::staging(object, ©.texture).unwrap(); + let ordinary = crate::texture::tests::untracked_bytes(&staging); + if mixed { + assert_eq!(ordinary, [(address, address + PAGE)]); + } else { + assert!(ordinary.is_empty()); + } + for page in 0..3 { + fill(page, 0x33); + } + let read = compile_cs(READ, READS); + let slots = Slots::new(1); + let mut srv = [0; 10]; + srv[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + let view = View::Shader(object as usize, Some(srv)); + slots.make(0, &view); + let (output, mapped) = host.shared_buffer((WIDTH * HEIGHT * 16) as u64).unwrap(); + let submit = |expected: [u8; 3], copies| { + let list = host.new_list().unwrap(); + readable(&list, &used(ResourceType::Srv), &view, false); + run(&list, &slots, &read, 0, Some(&output), (8, HEIGHT as u32 / 8)); + list.close(); + let before = crate::texture::copied(object); + host.execute(&[&list]); + // SAFETY: the completed dispatch wrote WIDTH * HEIGHT float4s. + let pixels = unsafe { std::slice::from_raw_parts(mapped.cast::<[f32; 4]>(), WIDTH * HEIGHT) }; + for (page, group) in pixels.chunks(WIDTH * ROWS_PER_PAGE).enumerate() { + let want = f32::from(expected[page]) / 255.0; + let wrong = group + .iter() + .filter(|p| !p.iter().all(|&v| (v - want).abs() <= 1e-6)) + .count(); + assert_eq!(wrong, 0, "page {page}, expected {expected:02x?}"); + } + assert_eq!(crate::texture::copied(object) - before, copies); + }; + submit([0x33; 3], 1); + if mixed { + fill(0, 0x99); + submit([0x99, 0x33, 0x33], 1); + submit([0x99, 0x33, 0x33], 0); + } else { + fill(0, 0x66); + crate::texture::tests::defer_one_upload(&staging); + submit([0x66, 0x33, 0x33], 1); + fill(0, 0x77); + crate::texture::tests::defer_one_upload(&staging); + fill(1, 0x88); + submit([0x77, 0x88, 0x33], 1); + submit([0x77, 0x88, 0x33], 0); + } + drop(staging); + drop(copy); + crate::object::release(object); +} + +#[test] +fn mixed_pages_and_deferred_rows_reach_the_sampled_texture() { + if crate::host::host().is_none() { + return; + } + // Both stay allocated, as in the other draw tests: the tracked pages' guards + // outlive the textures, and a later test's pool at a freed address would + // never see its writes. + let mixed = mixed_pages(); + let tracked = crate::watch::tests::pool(3); + check_rows(mixed, true); + check_rows(tracked, false); +} + +/// BC1 colors as RGB565 endpoints, and what they decode to. +const RED: u16 = 0xF800; +const GREEN: u16 = 0x07E0; +const BLUE: u16 = 0x001F; +const YELLOW: u16 = 0xFFE0; +const WHITE: u16 = 0xFFFF; + +fn decoded(color: u16) -> [f32; 4] { + let (r, g, b) = ( + f32::from(color >> 11), + f32::from(color >> 5 & 63), + f32::from(color & 31), + ); + [r / 31.0, g / 63.0, b / 31.0, 1.0] +} + +/// A block-compressed texture whose block rows span the page boundaries: a +/// write into one page copies only the 4x4 block rows it covers, and the +/// other pages keep what they had. +fn check_block_rows(address: usize, mixed: bool) { + let host = crate::host::host().unwrap(); + const WIDTH: usize = 64; + let words = |height: usize| texture_words(WIDTH as u32, height as u32, 71, 0x100, 0); + // Layout rows of a block-compressed texture are 4x4 block rows, and the + // pitch (bytes of one) is the layout's, so the page geometry follows it. + let probe = texture_at_address(address as u64, &words(32)); + let (_, desc) = crate::resource::texture_memory(probe).unwrap(); + let pitch = crate::resource::texture_layout(&desc) + .unwrap() + .planes[0] + .layout + .offset(0, 0, 1, 0) + .unwrap() as usize; + crate::object::release(probe); + assert!( + pitch >= WIDTH / 4 * 8 && PAGE.is_multiple_of(pitch), + "block row pitch {pitch}" + ); + let rows_per_page = PAGE / pitch * 4; + let height = 3 * rows_per_page; + let fill = |page: usize, color: u16| { + let at = address + page * PAGE; + let block = [color.to_le_bytes(), color.to_le_bytes(), [0; 2], [0; 2]].concat(); + let _writing = crate::watch::writing(at, PAGE); + for offset in (0..PAGE).step_by(8) { + // SAFETY: each of the three pages is a live allocation owned by this test. + unsafe { std::ptr::copy_nonoverlapping(block.as_ptr(), (at + offset) as *mut u8, 8) }; + } + }; + let object = texture_at_address(address as u64, &words(height)); + let (_, desc) = crate::resource::texture_memory(object).unwrap(); + let layout = crate::resource::texture_layout(&desc).unwrap(); + let layout = &layout.planes[0].layout; + assert_eq!(layout.offset(0, 0, rows_per_page as u32 / 4, 0).unwrap(), PAGE as u64); + assert_eq!(layout.size, (3 * PAGE) as u64); + let copy = crate::resource::host_copy(object).unwrap(); + let staging = crate::texture::staging(object, ©.texture).unwrap(); + let ordinary = crate::texture::tests::untracked_bytes(&staging); + if mixed { + assert_eq!(ordinary, [(address, address + PAGE)]); + } else { + assert!(ordinary.is_empty()); + } + for page in 0..3 { + fill(page, [RED, GREEN, BLUE][page]); + } + let read = compile_cs(READ, READS); + let slots = Slots::new(1); + let mut srv = [0; 10]; + srv[..6].copy_from_slice(&[71, 4, 0x1688, 0, 0, 1]); + let view = View::Shader(object as usize, Some(srv)); + slots.make(0, &view); + let (output, mapped) = host.shared_buffer((WIDTH * height * 16) as u64).unwrap(); + let submit = |expected: [u16; 3], copies| { + let list = host.new_list().unwrap(); + readable(&list, &used(ResourceType::Srv), &view, false); + run(&list, &slots, &read, 0, Some(&output), (8, height as u32 / 8)); + list.close(); + let before = crate::texture::copied(object); + host.execute(&[&list]); + // SAFETY: the completed dispatch wrote WIDTH * height float4s. + let pixels = unsafe { std::slice::from_raw_parts(mapped.cast::<[f32; 4]>(), WIDTH * height) }; + for (page, group) in pixels.chunks(WIDTH * rows_per_page).enumerate() { + let want = decoded(expected[page]); + let wrong = group + .iter() + .filter(|p| !p.iter().zip(want).all(|(&v, w)| (v - w).abs() <= 1e-6)) + .count(); + assert_eq!(wrong, 0, "page {page}, expected {:04x}", expected[page]); + } + assert_eq!(crate::texture::copied(object) - before, copies); + }; + submit([RED, GREEN, BLUE], 1); + if mixed { + fill(0, YELLOW); + submit([YELLOW, GREEN, BLUE], 1); + submit([YELLOW, GREEN, BLUE], 0); + } else { + fill(1, YELLOW); + submit([RED, YELLOW, BLUE], 1); + fill(2, WHITE); + crate::texture::tests::defer_one_upload(&staging); + fill(0, WHITE); + submit([WHITE, YELLOW, WHITE], 1); + submit([WHITE, YELLOW, WHITE], 0); + } + drop(staging); + drop(copy); + crate::object::release(object); +} + +#[test] +fn block_compressed_rows_keep_their_block_alignment_across_pages() { + if crate::host::host().is_none() { + return; + } + // The pools stay allocated, as in the test above. + let mixed = mixed_pages(); + let tracked = crate::watch::tests::pool(3); + check_block_rows(mixed, true); + check_block_rows(tracked, false); +} diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 99924b37..9b207e0d 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -12,8 +12,13 @@ //! //! Both refresh paths detile only the subresources whose bytes changed: the //! tracked one those whose bytes hash differently from the bytes last -//! detiled, the compared one those that a differing run touches. A change -//! inside one mip does not detile the others. +//! detiled (or, for a subresource that owns a changed page, only the rows +//! whose tiled bytes changed, copied through a `D3D12_BOX`), the compared +//! one those that a differing run touches. A change inside one mip does not +//! detile the others. +//! +//! shortcut: a change to an untracked texture, or to a page the subresource +//! shares with other data, detiles the whole subresource. //! //! Textures read through descriptor tables are brought up to date, and for //! shaders that index the heap themselves every texture with a resource @@ -486,10 +491,10 @@ fn copies( texture: &ID3D12Resource, staging: &Staging, (buffer, at): (&ID3D12Resource, u64), - subresources: &[u32], + subresources: &[Sub], ) { - for &i in subresources { - let i = i as usize; + for (i, band) in subresources { + let i = *i as usize; let mut footprint = staging.footprints[i]; footprint.Offset += at; let footprint = &footprint; @@ -536,14 +541,42 @@ fn copies( PlacedFootprint: *footprint, }, }; - // SAFETY: an open list; both locations name live resources. - unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + // Only the rows detiled: the staging buffer's other rows hold whatever + // its last user left. + let f = footprint.Footprint; + let block = staging.layout.desc.block.max(1); + match band { + Some(r) if *r != (0..staging.rows[i]) => { + let (top, bottom) = (r.start * block, (r.end * block).min(f.Height)); + if top >= bottom { + continue; + } + let rows = D3D12_BOX { + left: 0, + top, + front: 0, + right: f.Width, + bottom, + back: f.Depth, + }; + // SAFETY: an open list; both locations name live resources, + // and the box lies inside the footprint. + unsafe { list.list.CopyTextureRegion(&to, 0, top, 0, &from, Some(&rows)) }; + } + // SAFETY: an open list; both locations name live resources. + _ => unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }, + } } } /// What a refresh gives: a staging buffer, where its space starts in it, -/// and the subresources detiled into it. -pub(crate) type Upload = (ID3D12Resource, u64, Vec); +/// and the subresources detiled into it with the rows (in elements) if only +/// those were. +pub(crate) type Upload = (ID3D12Resource, u64, Vec); + +/// A subresource a refresh detiled, and its rows (in elements, every depth +/// slice) if only those were. +pub(crate) type Sub = (u32, Option>); /// The texture workers: up to a quarter of the CPUs (four at most), none /// where that is fewer than two. @@ -616,7 +649,7 @@ impl Staging { pub(crate) fn refresh(&self) -> Option { use std::sync::atomic::Ordering::Relaxed; let started = std::time::Instant::now(); - let (read, buffer) = self.refresh_now(); + let (read, buffer) = self.refresh_now(Self::detile); let preparing = &crate::host::PREPARING; preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed); preparing[3].fetch_add(read as u64, Relaxed); @@ -625,7 +658,10 @@ impl Staging { /// Returns the bytes of title memory read, and the buffer it detiled /// into with the subresources detiled. - fn refresh_now(&self) -> (usize, Option) { + fn refresh_now( + &self, + detile: impl FnOnce(&Self, &[u8], &[Sub]) -> Option<(ID3D12Resource, u64)>, + ) -> (usize, Option) { if self.tracked.is_none() && once_per_frame() && skip_same_frame( @@ -636,7 +672,11 @@ impl Staging { { return (0, None); } - let all = || (0..self.footprints.len() as u32).collect::>(); + let all = || { + (0..self.footprints.len() as u32) + .map(|i| (i, None)) + .collect::>() + }; let size = self.layout.size as usize; let start = self.memory as usize; let mut guard = self.last.lock().unwrap_or_else(|e| e.into_inner()); @@ -648,7 +688,8 @@ impl Staging { return (0, None); } let ranges = t.take(start, start + size); - if ranges.is_empty() { + let untracked = t.untracked(start, start + size); + if ranges.is_empty() && untracked.is_empty() { return (0, None); } // Only the subresources in the pages that changed (streamed @@ -659,51 +700,110 @@ impl Staging { let touched: Vec = (0..n) .filter(|&i| { let (a, b) = span(i); - ranges.iter().any(|&(f, e)| f - start < b && a < e - start) + ranges + .iter() + .chain(&untracked) + .any(|&(f, e)| f - start < b && a < e - start) + }) + .collect(); + // A changed page that holds only the subresource's bytes says it + // changed: of it, only the rows whose tiled bytes the change + // touches are read and detiled (one page written into mip 0 of a + // 4K texture re-read and detiled all 16 MiB of it). Pages it + // shares with other data the title writes (small textures): its + // own bytes decide, and it is detiled whole. (Hashing a movie + // frame cost 8 ms a frame.) + let page = crate::watch::PAGE; + let own = |i: usize| { + let (a, b) = span(i); + let (a0, b0) = (start + a, start + b); + // A mip spanning ordinary title memory must consider those + // bytes even when no tracked page was written. + !untracked.iter().any(|&(f, e)| f < b0 && a0 < e) + && ranges + .iter() + .any(|&(f, e)| f.max(a0).next_multiple_of(page) + page <= e.min(b0)) + }; + // The changed bytes as offsets into the memory, for the layout. + let changed: Vec<(usize, usize)> = ranges + .iter() + .map(|&(f, e)| (f.max(start) - start, e.min(start + size) - start)) + .filter(|r| r.0 < r.1) + .collect(); + let use_rows = dirty_rows_enabled(); + type Band = Option<(std::ops::Range, std::ops::Range)>; + let plan: Vec<(usize, Band)> = touched + .into_iter() + .map(|i| { + let s = i as u32; + let band = if use_rows && own(i) { + self.layout + .touched_rows(s % self.mips, s / self.mips, &changed) + } else { + None + }; + (i, band) }) .collect(); + if plan + .iter() + .all(|(_, band)| matches!(band, Some((rows, _)) if rows.is_empty())) + { + return (0, None); + } // Read through the copy, which stands unmapped pages: memory of // big pools is too slow to ask page by page. Not kept: it would - // double each texture's system memory. Only the touched spans + // double each texture's system memory. Only the bytes detiled // are written, and only they are hashed and detiled. let mut scratch = Scratch::take(size); let read = &mut scratch.0[..size]; let mut bytes = 0; let mut done: Vec<(usize, usize)> = Vec::new(); - for &i in &touched { - let (a, b) = span(i); - if !done.contains(&(a, b)) { + for (i, band) in &plan { + let (a, b) = match band { + Some((rows, _)) if rows.is_empty() => continue, + Some((_, tiled)) => (tiled.start, tiled.end.min(size)), + None => span(*i), + }; + if a < b && !done.contains(&(a, b)) { // SAFETY: inside the buffer of the texture's size. - crate::host::copy_mapped(unsafe { read.as_mut_ptr().add(a) }, self.memory.wrapping_add(a), b - a, false); + crate::host::copy_mapped( + unsafe { read.as_mut_ptr().add(a) }, + self.memory.wrapping_add(a), + b - a, + false, + ); (bytes, _) = (bytes + b - a, done.push((a, b))); } } - // A changed page that holds only the subresource's bytes says it - // changed. Pages it shares with other data the title writes - // (small textures): its own bytes decide. (Hashing a movie frame - // cost 8 ms a frame.) - let page = crate::watch::PAGE; last.hashes.resize(n, None); - let fresh: Vec = touched + let fresh: Vec = plan .into_iter() - .filter(|&i| { - let (a, b) = span(i); - let (a0, b0) = (start + a, start + b); - if ranges.iter().any(|&(f, e)| f.max(a0).next_multiple_of(page) + page <= e.min(b0)) { + .filter_map(|(i, band)| match band { + // None of its rows read the bytes changed. + Some((rows, _)) if rows.is_empty() => None, + Some((rows, _)) => { + last.hashes[i] = None; + Some((i as u32, Some(rows))) + } + None if own(i) => { last.hashes[i] = None; - return true; + Some((i as u32, None)) + } + None => { + let (a, b) = span(i); + let hash = blake3::hash(&read[a..b]); + (last.hashes[i].replace(hash) != Some(hash)).then_some((i as u32, None)) } - let hash = blake3::hash(&read[a..b]); - last.hashes[i].replace(hash) != Some(hash) }) - .map(|i| i as u32) .collect(); if fresh.is_empty() { return (bytes, None); } - let buffer = self.detile(read, &fresh); + let buffer = detile(self, read, &fresh); if buffer.is_none() { - for &i in &fresh { + t.retry(&ranges); + for &(i, _) in &fresh { last.hashes[i as usize] = None; } } @@ -761,7 +861,7 @@ impl Staging { } let zeros = vec![0u8; size]; let every = all(); - let buffer = self.detile(&zeros, &every); + let buffer = detile(self, &zeros, &every); last.uploaded = buffer.is_some(); return (0, buffer.map(|(b, at)| (b, at, every))); }; @@ -776,14 +876,18 @@ impl Staging { // no subresource lies in touch nothing, and detile nothing.) let n = self.footprints.len(); let span = |i: usize| self.spans.get(i).copied().unwrap_or((0, size)); - let fresh: Vec = (0..n) + let fresh: Vec = (0..n) .filter(|&i| { let (a, b) = span(i); touches(&runs, a, b) }) - .map(|i| i as u32) + .map(|i| (i as u32, None)) .collect(); - let buffer = if fresh.is_empty() { None } else { self.detile(&last.read, &fresh) }; + let buffer = if fresh.is_empty() { + None + } else { + detile(self, &last.read, &fresh) + }; if buffer.is_some() { self.uploaded_once .store(true, std::sync::atomic::Ordering::Relaxed); @@ -801,7 +905,7 @@ impl Staging { /// Detiles `subresources` of `tiled` (the texture's memory) into a /// staging buffer (`None` if none could be had or a subresource could /// not be read). - fn detile(&self, tiled: &[u8], subresources: &[u32]) -> Option<(ID3D12Resource, u64)> { + fn detile(&self, tiled: &[u8], subresources: &[Sub]) -> Option<(ID3D12Resource, u64)> { let (buffer, at, data) = staging_space(self.size)?; #[cfg(feature = "diagnostics")] // Scanned only when its message is wanted: a pass over every @@ -817,7 +921,8 @@ impl Staging { tracing::debug!(memory = ?self.memory, desc = ?self.layout.desc, "a sampled texture detiled"); } } - for &i in subresources { + for (i, band) in subresources { + let i = *i; let (footprint, rows) = (&self.footprints[i as usize], self.rows[i as usize]); let (mip, slice) = (i % self.mips, i / self.mips); let f = footprint.Footprint; @@ -827,10 +932,21 @@ impl Staging { // keeping the slice strictly inside the mapped staging buffer even when // GetCopyableFootprints does not pad the final row of the last subresource. let linear = unsafe { std::slice::from_raw_parts_mut(data.add(footprint.Offset as usize), len) }; - if let Err(e) = - self.layout - .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize) - { + let done = match band { + Some(r) => self.layout.detile_rows( + tiled, + mip, + slice, + linear, + pitch, + pitch * rows as usize, + r.clone(), + ), + None => self + .layout + .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize), + }; + if let Err(e) = done { tracing::warn!(?e, mip, slice, "texture not detiled"); return None; } @@ -1152,6 +1268,18 @@ pub(crate) fn staging(resource: This, texture: &ID3D12Resource) -> Option bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| dirty_rows_from_env(std::env::var_os("VICTORY_DIRTY_ROWS").as_deref())) +} + +fn dirty_rows_from_env(value: Option<&std::ffi::OsStr>) -> bool { + value.is_none_or(|v| v != "0") +} + /// Opt-in (`VICTORY_TEXTURE_ONCE_PER_FRAME=1`): check already-uploaded /// untracked textures at most once per presented frame instead of on every /// command-list submission (~35x/frame in GTA VI under Rosetta/Wine where @@ -1172,9 +1300,120 @@ fn skip_same_frame( } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; + pub(crate) fn untracked_bytes(staging: &Staging) -> Vec<(usize, usize)> { + let start = staging.memory as usize; + staging + .tracked + .as_ref() + .unwrap() + .untracked(start, start + staging.layout.size as usize) + } + + /// Simulates unavailable staging space after the texture took its pages. + pub(crate) fn defer_one_upload(staging: &Staging) { + let mut attempted = false; + let (read, upload) = staging.refresh_now(|_, _, _| { + attempted = true; + None + }); + assert!(attempted && read > 0 && upload.is_none()); + } + + #[test] + fn dirty_rows_switch_defaults_on_and_honors_zero() { + use std::ffi::OsStr; + assert!(dirty_rows_from_env(None)); + assert!(dirty_rows_from_env(Some(OsStr::new("1")))); + assert!(!dirty_rows_from_env(Some(OsStr::new("0")))); + } + + #[test] + fn single_page_write_in_bc7_mip_uploads_only_touched_block_rows() { + let Some(_host) = host() else { + return; // no host GPU here + }; + let page = crate::watch::PAGE; + // 512x512 BC7 (format 98, 16 bytes/4x4 block = 128x128 block rows, + // 256 KiB = 4 pages in SW_64KB_S layout = 0x109). + let address = crate::watch::tests::pool(8); + let words: [u32; 14] = [ + 3, + 0, + 0, + 0, + 512, + 0, + 512, + 1 | (1 << 16), + 98, // DXGI_FORMAT_BC7_UNORM + 1, + 0, + 0x109, // SW_64KB_S + 0, + 0, + ]; + let iid = crate::object::guid( + 0x696442be, + 0xa72e, + 0x4059, + [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad], + ); + let mut out = std::ptr::null(); + let hr = crate::resource::create_at_address( + std::ptr::null(), + address as u64, + words.as_ptr().cast(), + 0, + std::ptr::null(), + &iid, + &mut out, + ); + assert_eq!(hr, 0); + let tex = crate::resource::host_resource(out).expect("host texture"); + let s = staging(out, &tex).expect("staging"); + assert!(s.tracked.is_some()); + assert_eq!(s.layout.size as usize, 4 * page); + assert_eq!(s.rows[0], 128, "512 px / 4 px per BC7 block"); + + // Initial refresh uploads the entire mip. + let (read0, upload0) = s.refresh_now(Staging::detile); + assert_eq!(read0, 4 * page); + let (_, _, subs0) = upload0.expect("initial upload"); + assert_eq!(subs0, vec![(0, Some(0..128))]); + + // Writing one 64 KiB page (page 2 of 4) touches only half the block rows + // (64 of 128) and reads only the 2 pages covering that row band (128 KiB), + // rather than all 256 KiB. + // SAFETY: page 2 of our 8-page pool. + unsafe { ((address + 2 * page) as *mut u8).write_bytes(0x5a, page) }; + let (read1, upload1) = s.refresh_now(Staging::detile); + let (_, _, subs1) = upload1.expect("partial upload"); + assert_eq!(subs1.len(), 1); + let (sub, band) = &subs1[0]; + assert_eq!(*sub, 0); + let band = band.as_ref().expect("partial row band"); + assert!( + !band.is_empty() && band.len() < s.rows[0] as usize, + "expected partial block-row band, got {band:?} of {}", + s.rows[0] + ); + assert!( + read1 < 4 * page, + "expected fewer tiled bytes read ({read1}) than full mip ({})", + 4 * page + ); + + // Clean up tracker reference. + if let Some(copy) = crate::resource::host_copy(out) { + copy.staging.lock().unwrap_or_else(|e| e.into_inner()).take(); + } + drop(s); + crate::object::release(out); + } + #[test] fn texture_scratch_reuses_growing_buffers_within_the_retained_capacity() { let mib = 1 << 20; diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index e0afc0f7..2fa6bad9 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -624,6 +624,16 @@ impl Tracked { merged } + /// Requeues the tracked pages returned by `take` when their copy could + /// not be staged. Writes since the take stay in the set too. + pub(crate) fn retry(&self, taken: &[(usize, usize)]) { + let mut changed = self.changed.0.lock().unwrap_or_else(|e| e.into_inner()); + for &(from, to) in taken { + changed.extend(from / PAGE..to.div_ceil(PAGE)); + } + set_dirty(self.changed.2, !changed.is_empty()); + } + /// [`Tracked::take`], the runs on pages with nothing mapped apart: they /// read as zeros, with no copy to try (each such page cost a dozen /// failing kernel reads, 7-30 ms a frame in run perf4). From d5ec0d6ab8841b13599c52ceeb12e3605ab28dcf Mon Sep 17 00:00:00 2001 From: Pragyaan Gaur Date: Fri, 27 Nov 2026 08:35:09 +0530 Subject: [PATCH 2/2] Fit the touched rows upload to the unmapped page tracking from main --- crates/victory-gpu/src/texture.rs | 37 +++++++++++++++---------------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 84fddccf..e6430c40 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -884,7 +884,6 @@ impl Staging { for &(i, _) in &fresh { last.states[i as usize] = TrackedSubresource::Unknown; } - } } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexWatched, bytes as u64); @@ -2205,18 +2204,18 @@ pub(crate) mod tests { // First refresh: slice 0 is mapped (0x42), slice 1 is unmapped (zeros). let fb0 = crate::host::copy_mapped_fallbacks(); - let (bytes, upload) = s.refresh_now(); + let (bytes, upload) = s.refresh_now(Staging::detile); assert_eq!(crate::host::copy_mapped_fallbacks(), fb0, "no copy_mapped fallback on unmapped slice"); assert_eq!(bytes, page, "only mapped slice read via copy_mapped"); let upload = upload.expect("first upload initializes both slices"); - assert_eq!(upload.2, vec![0, 1]); + assert_eq!(upload.2.iter().map(|s| s.0).collect::>(), vec![0, 1]); assert_eq!(staging_byte(&upload, &s, 0, 0), 0x42); assert_eq!(staging_byte(&upload, &s, 1, 0), 0x00); // Redundant remap notification on still-unmapped slice 1: skipped completely. crate::watch::title_memory_remapped(mem.base + page, page); let fb1 = crate::host::copy_mapped_fallbacks(); - let (bytes, upload) = s.refresh_now(); + let (bytes, upload) = s.refresh_now(Staging::detile); assert_eq!(crate::host::copy_mapped_fallbacks(), fb1); assert_eq!(bytes, 0); assert!(upload.is_none(), "already-zero unmapped slice must not re-upload"); @@ -2224,27 +2223,27 @@ pub(crate) mod tests { // Unmap previously non-zero slice 0: must upload zeros once without fallback. mem.unmap(0); let fb2 = crate::host::copy_mapped_fallbacks(); - let (bytes, upload) = s.refresh_now(); + let (bytes, upload) = s.refresh_now(Staging::detile); assert_eq!(crate::host::copy_mapped_fallbacks(), fb2); assert_eq!(bytes, 0, "unmapped slice zeroed directly without copy_mapped"); let upload = upload.expect("unmapping non-zero slice must clear host texture"); - assert_eq!(upload.2, vec![0]); + assert_eq!(upload.2.iter().map(|s| s.0).collect::>(), vec![0]); assert_eq!(staging_byte(&upload, &s, 0, 0), 0x00); // A second remap notification on now-zero slice 0 is skipped. crate::watch::title_memory_remapped(mem.base, page); - let (bytes, upload) = s.refresh_now(); + let (bytes, upload) = s.refresh_now(Staging::detile); assert_eq!(bytes, 0); assert!(upload.is_none()); // Map slice 1 with non-zero bytes: reads and uploads slice 1 cleanly. mem.map(1, 0x99); let fb3 = crate::host::copy_mapped_fallbacks(); - let (bytes, upload) = s.refresh_now(); + let (bytes, upload) = s.refresh_now(Staging::detile); assert_eq!(crate::host::copy_mapped_fallbacks(), fb3); assert_eq!(bytes, page); let upload = upload.expect("newly mapped slice must upload"); - assert_eq!(upload.2, vec![1]); + assert_eq!(upload.2.iter().map(|s| s.0).collect::>(), vec![1]); assert_eq!(staging_byte(&upload, &s, 1, 0), 0x99); release_staging(obj, s); @@ -2267,11 +2266,11 @@ pub(crate) mod tests { // First refresh: page 0 mapped (0x33), page 1 unmapped (zeros). let fb0 = crate::host::copy_mapped_fallbacks(); - let (bytes, upload) = s.refresh_now(); + let (bytes, upload) = s.refresh_now(Staging::detile); assert_eq!(crate::host::copy_mapped_fallbacks(), fb0); assert_eq!(bytes, page); let upload = upload.expect("initial partial upload"); - assert_eq!(upload.2, vec![0]); + assert_eq!(upload.2.iter().map(|s| s.0).collect::>(), vec![0]); assert_eq!(staging_byte(&upload, &s, 0, 0), 0x33); assert_eq!(staging_byte(&upload, &s, 0, page), 0x00); @@ -2280,23 +2279,23 @@ pub(crate) mod tests { // SAFETY: page 0 is mapped and writable (write fault opens guard). unsafe { (mem.base as *mut u8).write_bytes(0x55, page) }; let fb1 = crate::host::copy_mapped_fallbacks(); - let (bytes, upload) = s.refresh_now(); + let (bytes, upload) = s.refresh_now(Staging::detile); assert_eq!(crate::host::copy_mapped_fallbacks(), fb1); assert_eq!(bytes, page); let upload = upload.expect("prefix write re-uploads subresource"); - assert_eq!(upload.2, vec![0]); + assert_eq!(upload.2.iter().map(|s| s.0).collect::>(), vec![0]); assert_eq!(staging_byte(&upload, &s, 0, 0), 0x55); - assert_eq!(staging_byte(&upload, &s, 0, page), 0x00); + // (Page 1's rows are not detiled: the host texture keeps its zeros.) - // Map page 1 with 0x77: both pages are now read and uploaded. + // Map page 1 with 0x77: only the rows in page 1 are read and uploaded + // (page 0's rows keep what the host texture holds). mem.map(1, 0x77); let fb2 = crate::host::copy_mapped_fallbacks(); - let (bytes, upload) = s.refresh_now(); + let (bytes, upload) = s.refresh_now(Staging::detile); assert_eq!(crate::host::copy_mapped_fallbacks(), fb2); - assert_eq!(bytes, 2 * page); + assert_eq!(bytes, page); let upload = upload.expect("mapping tail re-uploads subresource"); - assert_eq!(upload.2, vec![0]); - assert_eq!(staging_byte(&upload, &s, 0, 0), 0x55); + assert_eq!(upload.2.iter().map(|s| s.0).collect::>(), vec![0]); assert_eq!(staging_byte(&upload, &s, 0, page), 0x77); release_staging(obj, s);