Merge pull request #451 from 1984742628/perf/reuse-upload-memory

D3D12.X: faster title texture uploads (reused upload memory, faster detiling)
This commit is contained in:
Austin Ayers
2026-11-23 20:56:08 -05:00
committed by GitHub
3 changed files with 365 additions and 28 deletions
+186 -20
View File
@@ -201,30 +201,113 @@ pub unsafe fn upload(dev: &ID3D12Device, queue: &ID3D12CommandQueue, res: &ID3D1
r
}
/// What `upload_batch` keeps for a queue between batches: its allocator and list, a fence, and
/// one persistently mapped upload buffer the batches' texels go through. Making them for every
/// batch – an upload buffer per texture, an allocator, a list and a fence per batch – cost a
/// retail game most of its frame once it streamed textures: each of those D3D12 calls waits for
/// the video memory manager, 200 – 650 ms apiece then.
struct Uploader {
alloc: ID3D12CommandAllocator,
list: ID3D12GraphicsCommandList,
fence: ID3D12Fence,
value: u64,
/// (buffer, its mapped bytes, capacity)
staging: Option<(ID3D12Resource, *mut u8, u64)>,
}
// D3D12 objects are free-threaded; the mapped pointer is only used by the holder of the uploader
unsafe impl Send for Uploader {}
/// queue (raw pointer) → its uploader, while no batch uses it
static UPLOADERS: std::sync::Mutex<Option<std::collections::HashMap<usize, Uploader>>> = std::sync::Mutex::new(None);
/// the smallest upload buffer made, and the placement alignment of texture data in it
const STAGING_MIN: u64 = 4 << 20;
const PLACEMENT: u64 = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT as u64;
impl Uploader {
unsafe fn new(dev: &ID3D12Device) -> Result<Uploader, String> {
let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(err)?;
let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?;
list.Close().map_err(err)?;
let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(err)?;
Ok(Uploader { alloc, list, fence, value: 0, staging: None })
}
/// An upload buffer of at least `bytes`, mapped: the one kept, or a bigger one.
unsafe fn staging(&mut self, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, *mut u8), String> {
if let Some((b, p, cap)) = &self.staging {
if *cap >= bytes {
return Ok((b.clone(), *p));
}
}
let cap = bytes.max(STAGING_MIN).next_power_of_two();
let b = buffer(dev, cap)?;
let mut p = std::ptr::null_mut();
b.Map(0, None, Some(&mut p)).map_err(err)?;
self.staging = Some((b.clone(), p as *mut u8, cap));
Ok((b, p as *mut u8))
}
}
/// Several uploads on one list, one wait: (resource, subresources, states) each – the states
/// the texture is in and is left in: one for every subresource, or one per subresource (D3D12
/// order). A failure of one is returned with its index; the others still run.
/// order). A failure of one is returned with its index; the others still run. The texels go
/// through the queue's kept upload buffer (`Uploader`).
pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec<Subresource>, Vec<D3D12_RESOURCE_STATES>)]) -> Result<Vec<(usize, String)>, String> {
if items.is_empty() {
return Ok(Vec::new());
}
let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(err)?;
let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?;
let mut staging = Vec::with_capacity(items.len());
let key = windows::core::Interface::as_raw(queue) as usize;
let taken = UPLOADERS.lock().unwrap().as_mut().and_then(|m| m.remove(&key));
let mut up = match taken {
Some(u) => u,
None => Uploader::new(dev)?,
};
// where each texture's texels go in the upload buffer
let mut failed = Vec::new();
let mut planned = Vec::with_capacity(items.len());
let mut total = 0u64;
for (k, (res, subs, states)) in items.iter().enumerate() {
match record_upload_states(dev, &list, res, subs, states, states) {
Ok(s) => staging.push(s),
match layout(dev, res, subs, states, states) {
Ok(l) => {
let base = total.div_ceil(PLACEMENT) * PLACEMENT;
total = base + l.total;
planned.push((k, l, base));
}
Err(e) => failed.push((k, e)),
}
}
list.Close().map_err(err)?;
queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).map_err(err)?)]);
wait(dev, queue)?;
drop(staging);
if planned.is_empty() {
put_back(key, up);
return Ok(failed);
}
let (staging, mapped) = up.staging(dev, total)?;
up.alloc.Reset().map_err(err)?;
up.list.Reset(&up.alloc, None).map_err(err)?;
for (k, l, base) in &planned {
let (res, subs, states) = &items[*k];
record_into(&up.list, res, subs, l, states, states, &staging, mapped, *base);
}
up.list.Close().map_err(err)?;
queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&up.list).map_err(err)?)]);
up.value += 1;
let copy_error = |e| format!("texture copy: {e}");
queue.Signal(&up.fence, up.value).map_err(|e| copy_error(fence::api_error(dev, "Signal", e)))?;
if let Err(e) = fence::wait(&up.fence, up.value, dev, None, 10_000) {
// the GPU may still read the upload buffer and run the list: they stay alive (a fresh
// uploader next time) – freeing them under the GPU removed the device
std::mem::forget(up);
return Err(copy_error(e));
}
put_back(key, up);
Ok(failed)
}
fn put_back(key: usize, up: Uploader) {
UPLOADERS.lock().unwrap().get_or_insert_with(Default::default).insert(key, up);
}
/// Record the copy of `subs` into `res` on `list` (barriers from `before` and back to `after`);
/// the staging buffer returned must live until the list has run.
pub unsafe fn record_upload(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, subs: &[Subresource], before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> Result<ID3D12Resource, String> {
@@ -242,6 +325,25 @@ pub unsafe fn record_upload_states(
before: &[D3D12_RESOURCE_STATES],
after: &[D3D12_RESOURCE_STATES],
) -> Result<ID3D12Resource, String> {
let l = layout(dev, res, subs, before, after)?;
let up = buffer(dev, l.total)?;
let mut p = std::ptr::null_mut();
up.Map(0, None, Some(&mut p)).map_err(err)?;
record_into(list, res, subs, &l, before, after, &up, p as *mut u8, 0);
up.Unmap(0, None);
Ok(up)
}
/// Where the texels of an upload go in an upload buffer: each subresource's footprint (offsets
/// from 0) and rows, and the bytes of all of them.
struct Layout {
fps: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>,
rows: Vec<u32>,
total: u64,
}
/// The `Layout` of uploading `subs` into `res`, checked against the resource.
unsafe fn layout(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES]) -> Result<Layout, String> {
validate_subresources(subs)?;
let rd = res.GetDesc();
let n = subs.len();
@@ -264,40 +366,45 @@ pub unsafe fn record_upload_states(
));
}
}
let up = buffer(dev, total)?;
let mut p = std::ptr::null_mut();
up.Map(0, None, Some(&mut p)).map_err(err)?;
for ((s, fp), &nrows) in subs.iter().zip(&fps).zip(&rows) {
Ok(Layout { fps, rows, total })
}
/// Write `subs` into the mapped upload buffer `up` (`mapped`) from `base` (a multiple of
/// D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT) as `l` places them, and record their copies into
/// `res` on `list` (barriers from `before` and back to `after`).
#[allow(clippy::too_many_arguments)]
unsafe fn record_into(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, subs: &[Subresource], l: &Layout, before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES], up: &ID3D12Resource, mapped: *mut u8, base: u64) {
let n = subs.len();
for ((s, fp), &nrows) in subs.iter().zip(&l.fps).zip(&l.rows) {
let pitch = fp.Footprint.RowPitch as usize;
let row = s.row_bytes.min(pitch);
// depth slices are NumRows rows apart (rows of 4×4 blocks for BCn)
let slice_pitch = pitch * nrows as usize;
for z in 0..(fp.Footprint.Depth as usize).min(s.depth) {
for y in 0..(nrows as usize).min(s.rows) {
let at = fp.Offset as usize + z * slice_pitch + y * pitch;
std::ptr::copy_nonoverlapping(s.data[(z * s.rows + y) * s.row_bytes..].as_ptr(), (p as *mut u8).add(at), row);
let at = base as usize + fp.Offset as usize + z * slice_pitch + y * pitch;
std::ptr::copy_nonoverlapping(s.data[(z * s.rows + y) * s.row_bytes..].as_ptr(), mapped.add(at), row);
}
}
}
up.Unmap(0, None);
let to_copy = transitions(res, before, &[D3D12_RESOURCE_STATE_COPY_DEST], n);
if !to_copy.is_empty() {
list.ResourceBarrier(&to_copy);
}
for (k, fp) in fps.iter().enumerate() {
for (k, fp) in l.fps.iter().enumerate() {
let dst = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(res),
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 },
};
let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&up), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *fp } };
let placed = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: base + fp.Offset, Footprint: fp.Footprint };
let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(up), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: placed } };
list.CopyTextureRegion(&dst, 0, 0, 0, &src, None);
}
let back = transitions(res, &[D3D12_RESOURCE_STATE_COPY_DEST], after, n);
if !back.is_empty() {
list.ResourceBarrier(&back);
}
Ok(up)
}
/// The transitions of `r`'s `n` subresources from `from` to `to` (each one state for all, or one
@@ -631,6 +738,65 @@ mod tests {
}
}
/// Batches through one queue share its upload buffer (`Uploader`): two batches of three
/// textures (mips, an odd size, BC7) each read back what was uploaded, and the second batch
/// made no new upload buffer.
#[test]
fn gpu_upload_batches_reuse_the_queues_upload_buffer() {
let Some((dev, queue)) = device() else {
println!("no D3D12 device – skipping");
crate::gpu::recomp::runner::skip_test("no GPU");
return;
};
unsafe {
let make = |w: u64, h: u32, mips: u16, format| -> ID3D12Resource {
let rd = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: w,
Height: h,
DepthOrArraySize: 1,
MipLevels: mips,
Format: format,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
..Default::default()
};
let mut r: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rd, SHADER_READ, None, &mut r).unwrap();
r.unwrap()
};
// every subresource of `r`, filled with a pattern of `seed`
let subs = |r: &ID3D12Resource, seed: u8| -> Vec<Subresource> {
let rd = r.GetDesc();
let n = rd.MipLevels as usize;
let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n];
let (mut rows, mut row_bytes) = (vec![0u32; n], vec![0u64; n]);
dev.GetCopyableFootprints(&rd, 0, n as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), None);
(0..n)
.map(|k| {
let (r, b, d) = (rows[k] as usize, row_bytes[k] as usize, fps[k].Footprint.Depth as usize);
Subresource { rows: r, row_bytes: b, depth: d, data: (0..r * b * d).map(|i| (i as u8).wrapping_mul(31) ^ seed ^ k as u8).collect() }
})
.collect()
};
let textures = [make(64, 64, 7, DXGI_FORMAT_R8G8B8A8_UNORM), make(100, 30, 1, DXGI_FORMAT_R8G8B8A8_UNORM), make(256, 256, 9, DXGI_FORMAT_BC7_UNORM)];
let key = windows::core::Interface::as_raw(&queue) as usize;
let kept = || UPLOADERS.lock().unwrap().as_ref().and_then(|m| m.get(&key)).and_then(|u| u.staging.as_ref()).map(|s| (windows::core::Interface::as_raw(&s.0) as usize, s.2));
let mut buffers = Vec::new();
for round in 0..2u8 {
let items: Vec<_> = textures.iter().enumerate().map(|(i, r)| (r.clone(), subs(r, round * 16 + i as u8), vec![SHADER_READ])).collect();
assert!(upload_batch(&dev, &queue, &items).unwrap().is_empty(), "round {round}: an upload failed");
for (i, (r, want, _)) in items.iter().enumerate() {
let got = read_back(&dev, &queue, r, want);
for (k, (g, w)) in got.iter().zip(want).enumerate() {
assert!(g == w, "round {round}, texture {i}, subresource {k} differs");
}
}
buffers.push(kept().expect("the queue's upload buffer is kept"));
}
assert_eq!(buffers[0], buffers[1], "the second batch made a new upload buffer");
}
}
/// Mean |level `k` - level `k - 1` scaled down 2×| per channel (0..255 scale) of a texture
/// with `ch` channels of `cb` bytes (unorm); None when the sizes do not halve.
fn mip_error(big: &Subresource, small: &Subresource, ch: usize, cb: usize) -> Option<f64> {
+102 -5
View File
@@ -396,13 +396,43 @@ impl Chain {
/// bytes past the end of `src` read as 0
pub fn detile_level(&self, src: &[u8], i: usize, slice: usize) -> Vec<u8> {
let l = self.levels[i];
let e = 1usize << self.layout.elem_log2;
let t = &self.layout;
let e = 1usize << t.elem_log2;
let mut out = vec![0u8; l.width * l.height * e];
for y in 0..l.height {
for x in 0..l.width {
let o = self.element_at(&l, x, y, slice);
if t.mode == 0 && t.base_xor == 0 && l.origin == (0, 0) {
// linear: a row's elements are contiguous, so it is copied whole (the elements that
// are all in `src`, as below) – a video plane of 3840×2160 is 2160 copies, not 8 M
let row = l.width * e;
for y in 0..l.height {
let o = self.element_at(&l, 0, y, slice);
let n = src.len().saturating_sub(o).min(row) / e * e;
if n > 0 {
out[y * row..][..n].copy_from_slice(&src[o..o + n]);
}
}
return out;
}
// `element_at` (`Layout::offset_z`) split: what depends on x alone once per level, what
// depends on y (and the slice) once per row – per element only two lookups and an XOR.
// Element by element it was most of a retail game's render thread while it streamed
// textures the CPU writes.
let hi = |tab: &[u32], c: usize, b: usize| tab[(c / b) % tab.len()];
let pitch_blocks = l.pitch.div_ceil(t.block_w);
let columns: Vec<(usize, u32)> = (0..l.width)
.map(|x| {
let x = x + l.origin.0;
(x / t.block_w, t.ox[x % t.block_w] ^ hi(&t.hx, x, t.block_w))
})
.collect();
let z = t.oz[slice % t.block_d] ^ hi(&t.hz, slice, t.block_d);
for (y, row) in out.chunks_exact_mut(l.width * e).enumerate() {
let y = y + l.origin.1;
let row_blocks = (y / t.block_h) * pitch_blocks;
let yz = t.oy[y % t.block_h] ^ hi(&t.hy, y, t.block_h) ^ z;
for (&(block_x, x), dst) in columns.iter().zip(row.chunks_exact_mut(e)) {
let o = l.offset + (row_blocks + block_x) * t.block_bytes + ((x ^ yz) as usize ^ t.base_xor);
if let Some(s) = src.get(o..o + e) {
out[(y * l.width + x) * e..][..e].copy_from_slice(s);
dst.copy_from_slice(s);
}
}
}
@@ -447,6 +477,73 @@ mod tests {
v
}
/// Linear levels are copied a row at a time: the same bytes as element by element, for every
/// element size, padded rows, every mip and a source cut short (inside a row and inside an
/// element).
#[test]
fn linear_levels_detile_by_rows_as_by_elements() {
let by_elements = |c: &Chain, src: &[u8], i: usize| {
let l = c.levels[i];
let e = 1usize << c.layout.elem_log2;
let mut out = vec![0u8; l.width * l.height * e];
for y in 0..l.height {
for x in 0..l.width {
let o = c.element_at(&l, x, y, 0);
if let Some(s) = src.get(o..o + e) {
out[(y * l.width + x) * e..][..e].copy_from_slice(s);
}
}
}
out
};
for e in 0..5u32 {
for (w, h, mips) in [(3840u32, 4u32, 1u32), (1920, 3, 1), (77, 13, 4), (1, 1, 1), (300, 200, 9)] {
let c = Chain::new(Layout::new(0, e, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }).unwrap(), w, h, 1, mips);
let full: Vec<u8> = (0..c.slice_bytes).map(|k| (k * 7 + 3) as u8 | 1).collect();
for cut in [full.len(), full.len() / 2 + 1, 5, 0] {
let src = &full[..cut];
for i in 0..c.levels.len() {
assert_eq!(c.detile_level(src, i, 0), by_elements(&c, src, i), "e{e} {w}x{h} level {i} src {cut} B");
}
}
}
}
}
/// `detile_level` (offsets split by row and column) gives the bytes element-by-element
/// `element_at` does: every mode, element size and pipe configuration, every level (mip
/// tails too), a base swizzle and a slice, and a source cut short (bytes past it read as 0).
#[test]
fn detile_level_matches_element_by_element() {
for mode in MODES {
for e in 0..5u32 {
for cfg in configs() {
let mut lay = Layout::new(mode, e, cfg).unwrap();
lay.base_xor = (lay.block_bytes / 2) & !((1 << e) - 1);
let c = Chain::new(lay, 77, 45, 1, 7);
let mem: Vec<u8> = (0..c.slice_bytes * 2).map(|i| (i * 131 % 251) as u8).collect();
let short = &mem[..mem.len() * 3 / 5];
let es = 1usize << e;
for (k, l) in c.levels.iter().enumerate() {
for (slice, src) in [(0, &mem[..]), (3, short)] {
let mut want = vec![0u8; l.width * l.height * es];
for y in 0..l.height {
for x in 0..l.width {
let o = c.element_at(l, x, y, slice);
if let Some(s) = src.get(o..o + es) {
want[(y * l.width + x) * es..][..es].copy_from_slice(s);
}
}
}
assert!(c.detile_level(src, k, slice) == want, "mode {mode} e {e} {cfg:?} level {k} slice {slice}");
}
}
}
}
}
}
/// every mode, element size and pipe configuration: the in-block mapping is a permutation
/// of the block's elements (catches a mis-parsed table or a wrong block shape)
#[test]
+77 -3
View File
@@ -816,11 +816,11 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) {
};
let mut todo = todo.into_iter().peekable();
while todo.peek().is_some() {
let mut batch = Vec::new();
let mut picked = Vec::new();
let mut bytes = 0usize;
let mut device = 0usize;
while let Some((_, (dev, _, tex, _))) = todo.peek() {
if !batch.is_empty() && (bytes + tex.size() as usize > BATCH_BYTES || *dev != device) {
if !picked.is_empty() && (bytes + tex.size() as usize > BATCH_BYTES || *dev != device) {
break;
}
let (r, (dev, va, tex, states)) = todo.next().unwrap();
@@ -840,7 +840,11 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) {
}
device = dev;
bytes += tex.size() as usize;
let subs = subresources(va, &tex);
picked.push((r, va, tex, states));
}
let subs = subresources_of_all(&picked, bytes);
let mut batch = Vec::with_capacity(picked.len());
for ((r, va, _, states), subs) in picked.into_iter().zip(subs) {
if super::present::trace_frame() {
note_content(va, &r, &subs);
}
@@ -1046,6 +1050,50 @@ unsafe fn read_committed(at: usize, len: usize) -> Vec<u8> {
out
}
/// Batches of at least this many bytes are detiled on several threads (`subresources_of_all`)
const PARALLEL_BYTES: usize = 1 << 20;
/// `subresources` of every texture of a batch (`bytes` of them), in order: on several threads
/// when the batch is big. They were read and detiled one after another in the title's own
/// submit – most of a retail game's render thread while it streamed textures the CPU writes.
unsafe fn subresources_of_all(picked: &[(ID3D12Resource, usize, Arc<xg::Texture>, Vec<D3D12_RESOURCE_STATES>)], bytes: usize) -> Vec<Vec<Subresource>> {
let picked: Vec<(usize, &xg::Texture)> = picked.iter().map(|(_, va, tex, _)| (*va, &**tex)).collect();
let threads = if bytes < PARALLEL_BYTES { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get() / 2).clamp(1, 8) };
subresources_on(&picked, threads)
}
/// `subresources` of each (address, texture), in order, on up to `threads` threads.
unsafe fn subresources_on(picked: &[(usize, &xg::Texture)], threads: usize) -> Vec<Vec<Subresource>> {
let threads = threads.min(picked.len());
if threads <= 1 {
return picked.iter().map(|&(va, tex)| subresources(va, tex)).collect();
}
// the next texture to take; each thread hands back (index, subresources)
let next = std::sync::atomic::AtomicUsize::new(0);
let mut out: Vec<Vec<Subresource>> = (0..picked.len()).map(|_| Vec::new()).collect();
let done: Vec<Vec<(usize, Vec<Subresource>)>> = std::thread::scope(|s| {
let workers: Vec<_> = (0..threads)
.map(|_| {
s.spawn(|| {
let mut mine = Vec::new();
loop {
let k = next.fetch_add(1, Ordering::Relaxed);
let Some(&(va, tex)) = picked.get(k) else { break };
// SAFETY: as in the serial path – the title's memory is only read
mine.push((k, unsafe { subresources(va, tex) }));
}
mine
})
})
.collect();
workers.into_iter().map(|w| w.join().unwrap_or_default()).collect()
});
for (k, subs) in done.into_iter().flatten() {
out[k] = subs;
}
out
}
/// Every subresource (D3D12 order) of a texture from the title's memory at `va`.
unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec<Subresource> {
let Some(tex) = tex.texels() else { return Vec::new() };
@@ -1375,6 +1423,32 @@ mod tests {
assert_eq!(watch_ranges(&regions, wanted), vec![(0x1000_0000, 0x8_1000), (0x1100_0000, 0x1000)]);
}
/// The textures of a batch detiled on several threads come back as on one: complete and in
/// order (2D with mips and slices, 3D, BC7, a tiny one; more textures than threads).
#[test]
fn a_batch_detiled_on_several_threads_matches_one_thread() {
let descs = [
console_desc(3, 64, 64, 2, 3, 28, 0x105),
console_desc(3, 200, 72, 1, 5, 28, 0x105),
console_desc(4, 40, 24, 6, 3, 28, 0x105),
console_desc(3, 256, 256, 1, 9, 98, 0x10A),
console_desc(3, 4, 4, 1, 1, 28, 0x105),
console_desc(3, 128, 32, 3, 2, 28, 0x105),
console_desc(3, 64, 64, 1, 1, 28, 0x105),
];
let textures: Vec<xg::Texture> = descs.iter().map(|d| xg::Texture::new(d).unwrap()).collect();
// each texture's console memory: distinct bytes per texture
let mems: Vec<Vec<u8>> = textures.iter().enumerate().map(|(t, x)| (0..x.size() as usize).map(|i| (i * 7 + t * 61) as u8).collect()).collect();
let picked: Vec<(usize, &xg::Texture)> = mems.iter().zip(&textures).map(|(m, x)| (m.as_ptr() as usize, x)).collect();
unsafe {
let one = subresources_on(&picked, 1);
assert!(one.iter().all(|s| !s.is_empty()), "a texture gave no subresources");
for threads in [2, 3, 8] {
assert!(subresources_on(&picked, threads) == one, "{threads} threads differ from one");
}
}
}
fn console_desc(dim: u32, w: u64, h: u32, array_or_depth: u16, mips: u16, format: u32, layout: u32) -> [u8; 0x38] {
let mut d = [0u8; 0x38];
d[0..4].copy_from_slice(&dim.to_le_bytes());