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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2678,6 +2678,11 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void,
// view becomes the cube array of that one cube (a dimension mismatch is undefined in D3D12)
let cube = desc.as_ref().and_then(cube_as_cube_array);
let desc = cube.as_ref().map_or(desc, |v| v as *const _);
// `XCL_TEXTURE_DROP_LEVELS`: a texture whose largest levels have no video memory is sampled
// from the next level on
let dropped = if res.is_null() { 0 } else { super::vram::dropped_levels(res as usize) };
let clamped = if dropped > 0 { clamp_view_to_level(desc.as_ref(), dropped) } else { None };
let desc = clamped.as_ref().map_or(desc, |v| v as *const _);
if buf_delta_null {
let null_buf = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT,
Expand Down Expand Up @@ -2735,6 +2740,31 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void,
}
}

/// A 2D view `v` whose level of detail is clamped to `level` or coarser (`ResourceMinLODClamp`,
/// in the resource's levels): None for other views and for none given (counted: the default
/// view of such a texture samples its largest level, which reads zeros).
fn clamp_view_to_level(v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>, level: u32) -> Option<D3D12_SHADER_RESOURCE_VIEW_DESC> {
let Some(v) = v else {
static N: AtomicU64 = AtomicU64::new(0);
let n = N.fetch_add(1, Ordering::Relaxed) + 1;
if n.is_power_of_two() {
crate::xlog_warn!("D3D12.X: {n} default views of textures that leave out their largest levels (XCL_TEXTURE_DROP_LEVELS) are not clamped");
}
return None;
};
let lod = level as f32;
let mut out = *v;
// SAFETY: the union member the view dimension names
unsafe {
match v.ViewDimension {
D3D12_SRV_DIMENSION_TEXTURE2D => out.Anonymous.Texture2D.ResourceMinLODClamp = v.Anonymous.Texture2D.ResourceMinLODClamp.max(lod),
D3D12_SRV_DIMENSION_TEXTURE2DARRAY => out.Anonymous.Texture2DArray.ResourceMinLODClamp = v.Anonymous.Texture2DArray.ResourceMinLODClamp.max(lod),
_ => return None,
}
}
Some(out)
}

/// A TEXTURECUBE view as the TEXTURECUBEARRAY of its one cube (None: any other view).
fn cube_as_cube_array(v: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> Option<D3D12_SHADER_RESOURCE_VIEW_DESC> {
if v.ViewDimension != D3D12_SRV_DIMENSION_TEXTURECUBE {
Expand Down Expand Up @@ -8022,6 +8052,25 @@ mod pso_blend_and_tsharp_tests {
use super::*;
use windows::Win32::Graphics::Dxgi::Common::*;

/// `XCL_TEXTURE_DROP_LEVELS`: a 2D view is clamped to the first level kept (a coarser clamp it
/// had stays); other views and a default view are left as they are.
#[test]
fn a_view_of_a_texture_without_its_largest_level_samples_from_the_next() {
let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, ..Default::default() };
unsafe {
v.Anonymous.Texture2D.MipLevels = 11;
assert_eq!(clamp_view_to_level(Some(&v), 1).unwrap().Anonymous.Texture2D.ResourceMinLODClamp, 1.0);
assert_eq!(clamp_view_to_level(Some(&v), 1).unwrap().Anonymous.Texture2D.MipLevels, 11);
v.Anonymous.Texture2D.ResourceMinLODClamp = 3.0;
assert_eq!(clamp_view_to_level(Some(&v), 1).unwrap().Anonymous.Texture2D.ResourceMinLODClamp, 3.0);
let a = D3D12_SHADER_RESOURCE_VIEW_DESC { ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, ..Default::default() };
assert_eq!(clamp_view_to_level(Some(&a), 2).unwrap().Anonymous.Texture2DArray.ResourceMinLODClamp, 2.0);
}
let b = D3D12_SHADER_RESOURCE_VIEW_DESC { ViewDimension: D3D12_SRV_DIMENSION_BUFFER, ..Default::default() };
assert!(clamp_view_to_level(Some(&b), 1).is_none());
assert!(clamp_view_to_level(None, 1).is_none());
}

#[test]
fn integer_rtv_blend_sanitization_clears_uint_sint_and_preserves_float() {
assert!(is_integer_dxgi_format(DXGI_FORMAT_R8_UINT));
Expand Down
15 changes: 15 additions & 0 deletions crates/xcl/src/hle/d3d12x/title_textures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4599,6 +4599,21 @@ pub(super) mod tests {
assert_eq!(map_levels_with_texels(&full, &subresources(at, &tex)), vec![0], "mip 0 got its pages again");
assert_eq!(super::super::vram::mapped_level_tiles(full_key), Some(all as u64));
assert!(read_sub(&full, 0) == want[0].data, "mip 0 on the pages the other texture kept");
// `XCL_TEXTURE_DROP_LEVELS=1`: a texture placed then leaves its largest level without
// pages though it has texels, and does not count it as a level still to map
super::super::vram::DROP_FOR_TEST.store(1, Ordering::Relaxed);
let soft = place_tex(at);
let soft_key = soft.as_raw() as usize;
assert_eq!(super::super::vram::dropped_levels(soft_key), 1);
let got = map_levels_with_texels(&soft, &subresources(at, &tex));
assert!(!got.is_empty() && !got.contains(&0), "the smaller levels got pages, the largest none: {got:?}");
assert_eq!(super::super::vram::mapped_level_tiles(soft_key), Some((all - top_tiles) as u64));
assert!(!super::super::vram::has_unmapped_levels(soft_key), "a level left out is not one still to map");
// (a GPU write needs pages under all of it)
note_gpu_write(0, soft_key);
assert_eq!(super::super::vram::mapped_level_tiles(soft_key), Some(all as u64));
super::super::vram::DROP_FOR_TEST.store(0, Ordering::Relaxed);
drop(soft);
super::super::vram::LEVEL_PAGES_FOR_TEST.store(false, Ordering::Relaxed);
drop((small, full));
VirtualFree(at as *mut c_void, 0, MEM_RELEASE);
Expand Down
61 changes: 57 additions & 4 deletions crates/xcl/src/hle/d3d12x/vram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,9 @@ struct Target {
used_extra: Vec<(usize, usize)>,
/// its levels get their pages one by one (`map_levels`); None: all of it has pages
levels: Option<Levels>,
/// its largest levels left without pages (`dropped_levels_for`; their views sample from the
/// next one, `dropped_levels`)
dropped: u32,
}

/// The tiles of a texture whose levels get video memory when an upload first has texels for
Expand Down Expand Up @@ -1034,10 +1037,11 @@ unsafe fn place_on_pages(
// nothing mapped yet: a level gets its pages with its first texels (`map_levels`)
LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed);
pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels });
let dropped = levels.as_ref().map_or(0, |_| dropped_levels_for(desc));
pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels, dropped });
true
} else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) {
pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None });
pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None, dropped: 0 });
true
} else {
false
Expand Down Expand Up @@ -1397,8 +1401,9 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) ->
let Some(pages) = pages.as_mut() else { continue };
let Some(t) = pages.targets.get(&key) else { continue };
let Some(lv) = t.levels.as_ref().filter(|_| t.mapped) else { return Vec::new() };
// (the largest levels a texture leaves out get pages only for a GPU write, `levels` None)
let mut wanted: Vec<usize> = match levels {
Some(l) => l.iter().map(|&x| lv.group_of(x)).collect(),
Some(l) => l.iter().map(|&x| lv.group_of(x)).filter(|&k| lv.levels_of(k).end > t.dropped).collect(),
None => (0..lv.groups.len()).collect(),
};
wanted.sort_unstable();
Expand Down Expand Up @@ -1522,7 +1527,55 @@ pub(super) fn has_lazy_levels(resource: usize) -> bool {

/// Whether `resource` is a texture with lazy levels of which some have no pages yet.
pub(super) fn has_unmapped_levels(resource: usize) -> bool {
PAGES.lock().unwrap().values().flatten().any(|p| p.targets.get(&resource).and_then(|t| t.levels.as_ref()).is_some_and(|l| l.groups.iter().any(|g| !g.3)))
PAGES.lock().unwrap().values().flatten().any(|p| {
p.targets.get(&resource).is_some_and(|t| t.levels.as_ref().is_some_and(|l| (0..l.groups.len()).any(|k| !l.groups[k].3 && l.levels_of(k).end > t.dropped)))
})
}

/// `XCL_TEXTURE_DROP_LEVELS=n` (1 to 4; off by default, trial): a sampled texture with lazy levels
/// whose largest level is `XCL_TEXTURE_DROP_MIN` texels or more on a side (1024 by default) leaves
/// its `n` largest levels without video memory, and its views sample from the next level on
/// (`ResourceMinLODClamp`, `dropped_levels`). Softer textures up close for about three quarters
/// of such a texture's memory a level.
fn drop_setting() -> (u32, u64) {
#[cfg(test)]
{
let n = DROP_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed);
if n > 0 {
return (n, 1024);
}
}
static S: std::sync::OnceLock<(u32, u64)> = std::sync::OnceLock::new();
*S.get_or_init(|| {
let n = std::env::var("XCL_TEXTURE_DROP_LEVELS").ok().and_then(|v| v.trim().parse::<u32>().ok()).filter(|n| (1..=4).contains(n)).unwrap_or(0);
let min = std::env::var("XCL_TEXTURE_DROP_MIN").ok().and_then(|v| v.trim().parse::<u64>().ok()).filter(|&m| m >= 64).unwrap_or(1024);
if n > 0 {
crate::xlog_info!("D3D12.X: XCL_TEXTURE_DROP_LEVELS={n}: sampled textures of {min} texels or more on a side leave their {n} largest level(s) without video memory and are sampled from the next one");
}
(n, min)
})
}

/// `drop_setting`'s levels for a test (under `VRAM_TEST_LOCK`; 0: the variable's)
#[cfg(test)]
pub(super) static DROP_FOR_TEST: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);

/// The largest levels a texture of `desc` with lazy levels leaves out (`drop_setting`).
fn dropped_levels_for(desc: &D3D12_RESOURCE_DESC) -> u32 {
let (n, min) = drop_setting();
if n == 0 || desc.Width.max(desc.Height as u64) < min || (desc.MipLevels as u32) <= n {
return 0;
}
n
}

/// The largest levels texture `resource` leaves without pages: its views clamp their level of
/// detail to this (0: none).
pub(super) fn dropped_levels(resource: usize) -> u32 {
if drop_setting().0 == 0 {
return 0;
}
PAGES.lock().unwrap().values().flatten().find_map(|p| p.targets.get(&resource).map(|t| t.dropped)).unwrap_or(0)
}

/// XG and the PC driver pack volume mip tails differently. Keep these textures on the
Expand Down
Loading