diff --git a/README.md b/README.md index 5c4761d4f4..dbdb81c2cb 100644 --- a/README.md +++ b/README.md @@ -296,6 +296,8 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder those on which the GPU completed at least one operation. For each, it names the translated pipeline bound at the last operation DRED saw complete and those bound after it, by their console shaders' hashes (`cs`, `vs` / `ps`, `ms` / `ps`, `vs` / `gs` / `ps`). +- `XCL_TEXTURE_LEVEL_PAGES=1` gives sampled title textures backing as their mip levels stream in. + Zero-filled mip uploads in a batch share one staging span and still clear any mapped tiles. - `XCL_DSTORAGE_PARALLEL_DECOMPRESS=1` enables parallel CPU decompression for file-backed zlib requests with virtual destinations. Defaults: four workers and a shared 32 MiB staging budget (`XCL_DSTORAGE_WORKERS`, `XCL_DSTORAGE_MEMORY_BUDGET_MIB`). Requests retire in queue order. diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index 64222650d6..55393ca6a8 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -263,11 +263,24 @@ impl Uploader { } } +pub(crate) type UploadBatchItem = (ID3D12Resource, Vec, Vec); + /// 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. The texels go /// through the queue's kept upload buffer (`Uploader`). pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> { + upload_batch_with_zero_mips(dev, queue, items, &[]) +} + +/// As `upload_batch`, with an optional mask per item for subresources already verified to be all +/// zero. The copies still run, but these subresources all source the same zeroed staging span. +pub(crate) unsafe fn upload_batch_with_zero_mips( + dev: &ID3D12Device, + queue: &ID3D12CommandQueue, + items: &[UploadBatchItem], + zero_mips: &[Vec], +) -> Result, String> { if items.is_empty() { return Ok(Vec::new()); } @@ -278,17 +291,18 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items None => Uploader::new(dev)?, }; // where each texture's texels go in the upload buffer - let (failed, planned, total) = plan_batch(dev, items); + let (failed, planned, zero) = plan_batch(dev, items, zero_mips)?; if planned.is_empty() { put_back(key, up); return Ok(failed); } - let (staging, mapped) = up.staging(dev, total)?; + let (staging, mapped) = up.staging(dev, zero.end)?; + clear_staging_span(mapped, &zero); 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); + for (k, l, offsets) in planned { + let (res, subs, states) = &items[k]; + record_into(&up.list, res, subs, &l, states, states, &staging, mapped, offsets); } up.list.Close().map_err(err)?; queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&up.list).map_err(err)?)]); @@ -305,21 +319,38 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items Ok(failed) } -unsafe fn plan_batch(dev: &ID3D12Device, items: &[(ID3D12Resource, Vec, Vec)]) -> (Vec<(usize, String)>, Vec<(usize, Layout, u64)>, u64) { +unsafe fn plan_batch<'a>( + dev: &ID3D12Device, + items: &[UploadBatchItem], + zero_mips: &'a [Vec], +) -> Result<(Vec<(usize, String)>, Vec<(usize, Layout, StagingOffsets<'a>)>, std::ops::Range), String> { let mut failed = Vec::new(); - let mut planned = Vec::with_capacity(items.len()); - let mut total = 0u64; + let mut laid_out = Vec::with_capacity(items.len()); for (k, (res, subs, states)) in items.iter().enumerate() { + let zeros = zero_mips.get(k).map(Vec::as_slice).unwrap_or_default(); 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)); - } + Ok(l) if zeros.is_empty() || zeros.len() == l.fps.len() => laid_out.push((k, l, zeros)), + Ok(_) => failed.push((k, "texture upload zero mask does not match its subresources".into())), + Err(e) => failed.push((k, e)), + } + } + // A lone valid zero source cannot share and reserving its last row's padding could grow + // staging. Count after validation so a failed item cannot enable that padded path. + let share_zeros = laid_out.iter().flat_map(|(_, _, zeros)| *zeros).filter(|&&zero| zero).nth(1).is_some(); + let mut planned = Vec::with_capacity(laid_out.len()); + let mut storage = BatchStaging::default(); + for (k, mut l, zeros) in laid_out { + let zeros = if share_zeros { zeros } else { &[] }; + match storage.add(&mut l, zeros) { + Ok(base) => planned.push((k, l, StagingOffsets { base, zero: 0, zero_mips: zeros })), Err(e) => failed.push((k, e)), } } - (failed, planned, total) + let zero = storage.zero_span()?; + for (_, _, offsets) in &mut planned { + offsets.zero = zero.start; + } + Ok((failed, planned, zero)) } pub struct InFlight { @@ -330,23 +361,33 @@ pub struct InFlight { } pub unsafe fn submit_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result<(Vec<(usize, String)>, Option), String> { - let (failed, planned, bytes) = plan_batch(dev, items); + submit_batch_with_zero_mips(dev, queue, items, &[]) +} + +pub(crate) unsafe fn submit_batch_with_zero_mips( + dev: &ID3D12Device, + queue: &ID3D12CommandQueue, + items: &[UploadBatchItem], + zero_mips: &[Vec], +) -> Result<(Vec<(usize, String)>, Option), String> { + let (failed, planned, zero) = plan_batch(dev, items, zero_mips)?; if planned.is_empty() { return Ok((failed, None)); } 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 staging = buffer(dev, bytes)?; + let staging = buffer(dev, zero.end)?; let mut mapped = std::ptr::null_mut(); staging.Map(0, None, Some(&mut mapped)).map_err(err)?; - for (k, layout, base) in &planned { - let (res, subs, states) = &items[*k]; - record_into(&list, res, subs, layout, states, states, &staging, mapped as *mut u8, *base); + clear_staging_span(mapped as *mut u8, &zero); + for (k, layout, offsets) in planned { + let (res, subs, states) = &items[k]; + record_into(&list, res, subs, &layout, states, states, &staging, mapped as *mut u8, offsets); } staging.Unmap(0, None); list.Close().map_err(err)?; queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).map_err(err)?)]); - Ok((failed, Some(InFlight { _alloc: alloc, _list: list, _staging: staging, bytes }))) + Ok((failed, Some(InFlight { _alloc: alloc, _list: list, _staging: staging, bytes: zero.end }))) } fn put_back(key: usize, up: Uploader) { @@ -374,7 +415,7 @@ pub unsafe fn record_upload_states( 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); + record_into(list, res, subs, &l, before, after, &up, p as *mut u8, StagingOffsets::default()); up.Unmap(0, None); Ok(up) } @@ -387,6 +428,83 @@ struct Layout { total: u64, } +#[derive(Default)] +struct BatchStaging { + data_bytes: u64, + zero_bytes: u64, +} + +impl BatchStaging { + /// Keep the driver's dimensions and pitches. Only repack offsets when an item can share the + /// zero span. Each ordinary footprint keeps at least the byte range supplied by the driver. + fn add(&mut self, l: &mut Layout, zeros: &[bool]) -> Result { + let overflow = || "texture upload staging size overflow".to_string(); + if !zeros.is_empty() && zeros.len() != l.fps.len() { + return Err("texture upload zero mask does not match its subresources".into()); + } + let base = self.data_bytes.checked_next_multiple_of(PLACEMENT).ok_or_else(overflow)?; + let mut next = l.total; + let mut zero_bytes = self.zero_bytes; + if zeros.contains(&true) { + next = 0; + for (k, &zero) in zeros.iter().enumerate() { + let fp = l.fps[k]; + let end = l.fps.get(k + 1).map_or(l.total, |next| next.Offset); + let bytes = end.checked_sub(fp.Offset).ok_or_else(overflow)?; + if zero { + // Zero full pitched rows, including padding on the last row of each slice. + let pitched_bytes = u64::from(fp.Footprint.RowPitch) + .checked_mul(u64::from(l.rows[k])) + .and_then(|bytes| bytes.checked_mul(u64::from(fp.Footprint.Depth))) + .ok_or_else(overflow)?; + zero_bytes = zero_bytes.max(pitched_bytes.max(bytes)); + } else { + let at = next.checked_next_multiple_of(PLACEMENT).ok_or_else(overflow)?; + next = at.checked_add(bytes).ok_or_else(overflow)?; + l.fps[k].Offset = at; + } + } + } + self.data_bytes = base.checked_add(next).ok_or_else(overflow)?; + self.zero_bytes = zero_bytes; + Ok(base) + } + + fn zero_span(&self) -> Result, String> { + if self.zero_bytes == 0 { + return Ok(self.data_bytes..self.data_bytes); + } + let overflow = || "texture upload staging size overflow".to_string(); + let start = self.data_bytes.checked_next_multiple_of(PLACEMENT).ok_or_else(overflow)?; + let end = start.checked_add(self.zero_bytes).ok_or_else(overflow)?; + Ok(start..end) + } +} + +/// The mapped staging buffer covers `span`, which can contain data from an earlier batch. +unsafe fn clear_staging_span(mapped: *mut u8, span: &std::ops::Range) { + if !span.is_empty() { + mapped.add(span.start as usize).write_bytes(0, (span.end - span.start) as usize); + } +} + +#[derive(Default)] +struct StagingOffsets<'a> { + base: u64, + zero: u64, + zero_mips: &'a [bool], +} + +impl StagingOffsets<'_> { + fn is_zero(&self, sub: usize) -> bool { + self.zero_mips.get(sub) == Some(&true) + } + + fn at(&self, sub: usize, offset: u64) -> u64 { + if self.is_zero(sub) { self.zero } else { self.base + offset } + } +} + /// 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 { validate_subresources(subs)?; @@ -403,6 +521,9 @@ unsafe fn layout(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], let mut row_bytes = vec![0u64; n]; let mut total = 0u64; dev.GetCopyableFootprints(&rd, 0, n as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), Some(&mut total)); + if total == u64::MAX { + return Err("invalid texture copy footprints".into()); + } for (i, ((s, fp), (&nrows, &nbytes))) in subs.iter().zip(&fps).zip(rows.iter().zip(&row_bytes)).enumerate() { if s.rows != nrows as usize || s.depth != fp.Footprint.Depth as usize || s.row_bytes != nbytes as usize { return Err(format!( @@ -414,20 +535,23 @@ unsafe fn layout(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], 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`). +/// Write `subs` into the mapped upload buffer `up` (`mapped`) where `l` and `offsets` place them, +/// and record every copy 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) { +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, offsets: StagingOffsets<'_>) { let n = subs.len(); - for ((s, fp), &nrows) in subs.iter().zip(&l.fps).zip(&l.rows) { + for (k, ((s, fp), &nrows)) in subs.iter().zip(&l.fps).zip(&l.rows).enumerate() { + if offsets.is_zero(k) { + continue; + } + let start = offsets.at(k, fp.Offset) as usize; 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 = base as usize + fp.Offset as usize + z * slice_pitch + y * pitch; + let at = start + z * slice_pitch + y * pitch; std::ptr::copy_nonoverlapping(s.data[(z * s.rows + y) * s.row_bytes..].as_ptr(), mapped.add(at), row); } } @@ -442,7 +566,7 @@ unsafe fn record_into(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, su Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 }, }; - let placed = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: base + fp.Offset, Footprint: fp.Footprint }; + let placed = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: offsets.at(k, 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); } @@ -513,6 +637,76 @@ mod tests { use super::*; use windows::Win32::Graphics::Dxgi::Common::*; + #[test] + fn shared_zero_mip_staging_compacts_and_clears_the_full_span() { + // A 1024² R8 texture with five mips, including the driver's row and placement alignment. + let layout = || Layout { + fps: [0, 1_048_576, 1_310_720, 1_376_256, 1_409_024].into_iter() + .zip([1024, 512, 256, 128, 64]) + .map(|(offset, width)| D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: offset, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R8_UNORM, + Width: width, + Height: width, + Depth: 1, + RowPitch: width.max(256), + }, + }).collect(), + rows: vec![1024, 512, 256, 128, 64], + total: 1_425_216, + }; + let zeros = [true, false, false, false, false]; + let mut original = BatchStaging::default(); + let mut shared = BatchStaging::default(); + let mut items = Vec::new(); + for _ in 0..8 { + original.add(&mut layout(), &[]).unwrap(); + let mut l = layout(); + let base = shared.add(&mut l, &zeros).unwrap(); + items.push((l, base)); + } + let old = original.zero_span().unwrap(); + let zero = shared.zero_span().unwrap(); + assert!(old.is_empty()); + assert_eq!(old.end, 11_403_072); + assert_eq!(zero.end, 4_063_232); + assert_eq!(staging_capacity(old.end), Some(16 << 20)); + assert_eq!(staging_capacity(zero.end), Some(4 << 20)); + for (l, base) in items { + let offsets = StagingOffsets { base, zero: zero.start, zero_mips: &zeros }; + assert_eq!(offsets.at(0, l.fps[0].Offset), zero.start); + for (k, fp) in l.fps.iter().enumerate().skip(1) { + let at = offsets.at(k, fp.Offset); + assert_eq!(at % PLACEMENT, 0); + assert!(at + u64::from(fp.Footprint.RowPitch * l.rows[k]) <= zero.start); + assert_eq!(fp.Footprint, layout().fps[k].Footprint); + } + } + + // A fully zero footprint uses whole pitched rows, including the last row of the + // last slice, even when GetCopyableFootprints reports a shorter last row. + let mut volume = Layout { + fps: vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R8_UNORM, Width: 13, Height: 2, Depth: 3, RowPitch: 256, + }, + }], + rows: vec![2], + total: 5 * 256 + 13, + }; + let mut volume_batch = BatchStaging { data_bytes: 268, zero_bytes: 0 }; + volume_batch.add(&mut volume, &[true]).unwrap(); + let zero = volume_batch.zero_span().unwrap(); + assert_eq!(zero, 512..2048); + let mut bytes = vec![0x72; 2049]; + unsafe { clear_staging_span(bytes.as_mut_ptr(), &zero); } + assert!(bytes[..512].iter().all(|&b| b == 0x72)); + assert!(bytes[512..2048].iter().all(|&b| b == 0)); + assert_eq!(bytes[2048], 0x72); + } + fn image(format: u32, ty: ImageType, w: u32, h: u32, slices: u32, mips: u32, mode: u32, address: u64) -> Image { Image { address, diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 111ede86d6..d25aac7a64 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1125,13 +1125,18 @@ unsafe fn reclaim(dev: &ID3D12Device, q: &mut QueueUploads, cap: u64, wait_ms: u } } -unsafe fn submit_on_title_queue(dev: &ID3D12Device, queue: &ID3D12CommandQueue, batch: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> { +unsafe fn submit_on_title_queue( + dev: &ID3D12Device, + queue: &ID3D12CommandQueue, + batch: &[texture::UploadBatchItem], + zero_mips: &[Vec], +) -> Result, String> { // The textures' tile mappings made since the title queue last waited for them (a texture // made on another thread after `refresh_once`'s wait, or its levels mapped just now by // `map_levels_with_texels`): a copy into a tile still unmapped is a copy-engine page fault // on NVIDIA (`DmaPageFaultWrite`), as the upload queue's own path already waits for. super::vram::before_execute(queue); - let (failed, f) = texture::submit_batch(dev, queue, batch)?; + let (failed, f) = texture::submit_batch_with_zero_mips(dev, queue, batch, zero_mips)?; let Some(f) = f else { return Ok(failed) }; let mut g = ON_QUEUE.lock().unwrap(); let key = queue.as_raw() as usize; @@ -1203,20 +1208,22 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>, title: Option<&ID3D12C } let subs = subresources_of_all(&picked, bytes); let mut batch = Vec::with_capacity(picked.len()); + let mut zero_mips = Vec::new(); + let level_pages = super::vram::level_pages(); for ((r, va, _, states), subs) in picked.into_iter().zip(subs) { if super::present::trace_frame() { note_content(va, &r, &subs); } - if super::vram::level_pages() { + if level_pages { // (the queue waits for these mappings before the copies: `vram::before_execute` below) - map_levels_with_texels(&r, &subs); + zero_mips.push(map_levels_with_texels(&r, &subs)); } batch.push((r, subs, states)); } let d = device as *mut c_void; let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { continue }; if let Some(tq) = title_queue_for(dev, title) { - match own_work(|| submit_on_title_queue(dev, &tq, &batch)) { + match own_work(|| submit_on_title_queue(dev, &tq, &batch, &zero_mips)) { Ok(failed) => { for (_, e) in failed { warn(&e); @@ -1236,7 +1243,7 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>, title: Option<&ID3D12C }; match own_work(|| { super::vram::before_execute(&queue); - texture::upload_batch(dev, &queue, &batch) + texture::upload_batch_with_zero_mips(dev, &queue, &batch, &zero_mips) }) { Ok(failed) => { for (_, e) in failed { @@ -1251,17 +1258,18 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>, title: Option<&ID3D12C /// (`vram::level_pages`) Before an upload of title texture `r`: its levels with texels in `subs` /// (its subresources as they go up) get their video memory pages if they have none - a texture -/// placed with lazy levels; any other: nothing to do. A level of zeros has no texels: a streamed -/// texture's larger levels before the title has memory behind them (read as zeros, -/// `read_committed`). It keeps no pages, reads as zeros as it would with them, and its copy goes -/// to tiles that are not mapped, which drops it (tiled resources tier 2). -unsafe fn map_levels_with_texels(r: &ID3D12Resource, subs: &[Subresource]) { +/// placed with lazy levels. Return a mask of zero levels so their copies can share staging. +/// A level of zeros needs no new pages. Its copy still clears any existing tiles, including a +/// previously streamed level or tiles mapped for other levels in the same packed tail. +unsafe fn map_levels_with_texels(r: &ID3D12Resource, subs: &[Subresource]) -> Vec { if !super::vram::has_lazy_levels(r.as_raw() as usize) { - return; + return Vec::new(); } // (one slice: its subresources are its levels) - let present: Vec = subs.iter().enumerate().filter(|(_, s)| !all_zero(&s.data)).map(|(i, _)| i as u32).collect(); + let zero: Vec = subs.iter().map(|s| all_zero(&s.data)).collect(); + let present: Vec = zero.iter().enumerate().filter_map(|(i, &zero)| (!zero).then_some(i as u32)).collect(); super::vram::map_levels(r, Some(&present)); + zero } /// Whether every byte of `b` is zero (eight at a time: gigabytes a second where it is). @@ -1743,7 +1751,7 @@ mod tests { let _queue_uploads = DirectQueueUploads::new(&queue); let upload = |value: u8| { let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![value; 64 * 64] }]; - own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])], &[])).unwrap(); }; for value in [0x21, 0xC4] { upload(value); @@ -1793,7 +1801,7 @@ mod tests { ).unwrap(); let texture: ID3D12Resource = texture.unwrap(); let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![0x3C; 64 * 64] }]; - own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])], &[])).unwrap(); assert_eq!( super::super::vram::waited_for_test(raw_device as usize, key), mapped, @@ -1829,7 +1837,7 @@ mod tests { let texture: ID3D12Resource = texture.unwrap(); let key = queue.as_raw() as usize; let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![0x77; 64 * 64] }]; - own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])], &[])).unwrap(); { let mut g = ON_QUEUE.lock().unwrap(); let q = g.get_mut(&key).unwrap(); @@ -2766,7 +2774,8 @@ mod tests { /// first upload, then pages for those levels only and their texels right, zeros where there /// are none. With memory under the largest level too, a texture placed there again (as a /// title does) takes that level's pages - the others are shared - and holds all of it. A - /// texture the GPU writes gets the pages of all its levels. + /// texture the GPU writes gets the pages of all its levels. A mapped level also clears when + /// the CPU's next upload sources zeros from shared staging. #[test] fn a_placed_texture_gets_the_pages_of_a_level_with_its_texels() { let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); @@ -2892,6 +2901,23 @@ mod tests { note_gpu_write(small.as_raw() as usize); assert_eq!(dev_pages() - p0, (all as usize) << 16, "the same pages"); assert!(read_sub(&small, 0) == want[0].data, "a GPU-written texture has pages under all its levels"); + std::ptr::write_bytes((at + top) as *mut u8, 0, size - top); + let cpu = std::slice::from_raw_parts_mut(at as *mut u8, chain.slice_bytes); + chain.tile_level(cpu, 10, 0, &vec![0u8; want[10].data.len()]); + // The synthetic allocation here is not write-watched. Queue the normal batch update. + { + let mut t = TEXTURES.lock().unwrap(); + let e = t.by_res.get_mut(&(full.as_raw() as usize)).unwrap(); + assert!(!e.pending, "the preceding refresh uploaded this texture"); + e.pending = true; + adjust_pending(1); + } + refresh(queue.as_raw()); + assert_eq!(dev_pages() - p0, (all as usize) << 16, "clearing a level keeps its backing"); + assert!(read_sub(&full, 0).iter().all(|&b| b == 0), "the previously streamed level was cleared"); + assert!(read_sub(&full, 10).iter().all(|&b| b == 0), "a small level sharing the zero span was cleared"); + assert!(read_sub(&full, 1) == want[1].data, "a nonzero mip kept its texels"); + assert!(read_sub(&full, 9) == want[9].data, "the small level's neighbour kept its texels"); super::super::vram::LEVEL_PAGES_FOR_TEST.store(false, Ordering::Relaxed); drop((small, full)); VirtualFree(at as *mut c_void, 0, MEM_RELEASE);