diff --git a/README.md b/README.md index 5a854de..3f30d48 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,8 @@ cargo build --profile diag -p victory --features diagnostics # target\diag\vic | `VICTORY_PIPELINE_WORKERS=16` | use this many pipeline worker threads (1-64) instead of half the logical processors, 2-8 by default | | `VICTORY_SKIP_PIPELINES=,...` | omit draws and dispatches, including indirect ones, whose pipeline contains a listed 16-digit shader hash | | `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands | +| `VICTORY_TEXTURE_MIP_DROP=0..=3` | override texture mip dropping (default: 1 on adapters with at most 8.5 GiB dedicated VRAM, then raised after allocation out-of-memory) | +| `VICTORY_TEXTURE_MIP_DROP_MIN_SIZE=1024` | smallest post-drop texture dimension eligible for mip dropping | | `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) | | `VICTORY_SHADER_LOOP_LIMIT=` | translated shader loops stop after `n` iterations per lane instead of 2^14 (own shader cache entries); if a lower `n` makes world frames much faster, loops hitting the limit are what makes them slow | | `VICTORY_AUDIO_CAPTURE=` | records what the title plays (our process only) | diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index a4a04a0..33c16f5 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1016,6 +1016,127 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere true } +/// Re-bases a console SRV mip window onto a host texture whose top `drop` +/// mips were omitted (`host_mips` surviving levels, console levels +/// `drop..drop + host_mips`). +fn rebase_mip_window( + most_detailed: u32, + mip_levels: u32, + min_lod: f32, + drop: u32, + host_mips: u32, +) -> (u32, u32, f32) { + if drop == 0 { + return (most_detailed, mip_levels, min_lod); + } + let host_mips = host_mips.max(1); + let title_mips = host_mips.saturating_add(drop); + let min_lod = (min_lod - drop as f32).max(0.0); + if mip_levels == u32::MAX { + let start = most_detailed.saturating_sub(drop).min(host_mips - 1); + return (start, u32::MAX, min_lod); + } + let end = most_detailed.saturating_add(mip_levels).min(title_mips); + let start = most_detailed.max(drop); + if start < end { + (start - drop, end - start, min_lod) + } else { + // A view naming only dropped mips stays valid at the first surviving + // mip; one past the chain uses the smallest survivor. + let start = if most_detailed < drop { + 0 + } else { + host_mips - 1 + }; + (start, 1, min_lod) + } +} + +/// Adjusts an explicit SRV description for a texture whose top `drop` mips +/// were omitted on the host. +fn adjust_srv_for_mip_drop(srv: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, drop: u32, host_mips: u32) { + if drop == 0 { + return; + } + // SAFETY: each branch reads and writes only the union arm named by + // `srv.ViewDimension`. + unsafe { + match srv.ViewDimension { + D3D12_SRV_DIMENSION_TEXTURE1D => { + let t = &mut srv.Anonymous.Texture1D; + (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) = rebase_mip_window( + t.MostDetailedMip, + t.MipLevels, + t.ResourceMinLODClamp, + drop, + host_mips, + ); + } + D3D12_SRV_DIMENSION_TEXTURE1DARRAY => { + let t = &mut srv.Anonymous.Texture1DArray; + (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) = rebase_mip_window( + t.MostDetailedMip, + t.MipLevels, + t.ResourceMinLODClamp, + drop, + host_mips, + ); + } + D3D12_SRV_DIMENSION_TEXTURE2D => { + let t = &mut srv.Anonymous.Texture2D; + (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) = rebase_mip_window( + t.MostDetailedMip, + t.MipLevels, + t.ResourceMinLODClamp, + drop, + host_mips, + ); + } + D3D12_SRV_DIMENSION_TEXTURE2DARRAY => { + let t = &mut srv.Anonymous.Texture2DArray; + (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) = rebase_mip_window( + t.MostDetailedMip, + t.MipLevels, + t.ResourceMinLODClamp, + drop, + host_mips, + ); + } + D3D12_SRV_DIMENSION_TEXTURE3D => { + let t = &mut srv.Anonymous.Texture3D; + (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) = rebase_mip_window( + t.MostDetailedMip, + t.MipLevels, + t.ResourceMinLODClamp, + drop, + host_mips, + ); + } + D3D12_SRV_DIMENSION_TEXTURECUBE => { + let t = &mut srv.Anonymous.TextureCube; + (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) = rebase_mip_window( + t.MostDetailedMip, + t.MipLevels, + t.ResourceMinLODClamp, + drop, + host_mips, + ); + } + D3D12_SRV_DIMENSION_TEXTURECUBEARRAY => { + let t = &mut srv.Anonymous.TextureCubeArray; + (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) = rebase_mip_window( + t.MostDetailedMip, + t.MipLevels, + t.ResourceMinLODClamp, + drop, + host_mips, + ); + } + _ => {} + } + } +} + /// Makes the host descriptor for `view` at `at`: the host resource it /// views, or `None` if it cannot. fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { @@ -1071,6 +1192,10 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) { return None; } + let (drop, host_mips) = crate::resource::host_mip_info(resource); + if let Some(srv) = desc.as_mut() { + adjust_srv_for_mip_drop(srv, drop, host_mips); + } // SAFETY: a live texture and a slot of our heap. unsafe { device.CreateShaderResourceView( @@ -1433,4 +1558,16 @@ mod tests { crate::shadow::unregister(resource_id, start); } + + #[test] + fn srv_mip_window_rebasing_handles_partial_full_and_dropped_ranges() { + assert_eq!(rebase_mip_window(1, 3, 3.5, 2, 5), (0, 2, 1.5)); + assert_eq!(rebase_mip_window(3, 2, 1.0, 2, 5), (1, 2, 0.0)); + assert_eq!( + rebase_mip_window(0, u32::MAX, 0.0, 2, 5), + (0, u32::MAX, 0.0) + ); + assert_eq!(rebase_mip_window(0, 1, 0.0, 2, 5), (0, 1, 0.0)); + assert_eq!(rebase_mip_window(1, 3, 1.5, 0, 7), (1, 3, 1.5)); + } } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 7ce96a8..9b18ba2 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -37,6 +37,8 @@ const RTV_RING: u32 = 1024; pub(crate) struct Host { pub(crate) device: ID3D12Device, + /// Dedicated video memory of the adapter the device is on, in bytes. + memory: u64, queue: ID3D12CommandQueue, fence: ID3D12Fence, /// The last value signalled on `fence`, behind the submission lock. @@ -187,10 +189,23 @@ fn create() -> windows::core::Result { let adapter = warp_adapter()?; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; tracing::info!("host device on the software adapter (WARP)"); + } else if let Some((adapter, memory, name)) = hardware_adapter() { + match D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device) { + Ok(()) => tracing::info!( + adapter = name, + memory_gb = format_args!("{:.1}", memory as f64 / f64::powi(1024.0, 3)), + "host device on the largest-memory hardware adapter" + ), + Err(e) => { + tracing::warn!(error = %e, adapter = name, "hardware adapter refused D3D12; using the default adapter"); + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; + } + } } else { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; } let device = device.ok_or_else(windows::core::Error::empty)?; + let memory = adapter_memory(&device); let messages = debug .then(|| device.cast::().ok()) .flatten(); @@ -217,6 +232,7 @@ fn create() -> windows::core::Result { tracing::info!("host D3D12 device ready"); Ok(Host { device, + memory, queue, fence, submitted: Mutex::new(0), @@ -233,6 +249,75 @@ fn create() -> windows::core::Result { } } +/// The hardware adapter with the most dedicated video memory, if DXGI knows +/// one: a Ryzen APU plus a discrete card must not default to the APU's small +/// shared-memory device. +fn hardware_adapter() -> Option<(IDXGIAdapter, u64, String)> { + // SAFETY: plain DXGI factory and adapter queries. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let mut best = None; + for i in 0.. { + let Ok(adapter1) = factory.EnumAdapters1(i) else { + break; + }; + let Ok(desc) = adapter1.GetDesc1() else { + continue; + }; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { + continue; + } + let memory = desc.DedicatedVideoMemory as u64; + let end = desc + .Description + .iter() + .position(|&c| c == 0) + .unwrap_or(desc.Description.len()); + let name = String::from_utf16_lossy(&desc.Description[..end]); + let better = best + .as_ref() + .is_none_or(|(_, old, _): &(IDXGIAdapter, u64, String)| memory > *old); + if better { + best = adapter1 + .cast::() + .ok() + .map(|a| (a, memory, name)); + } + } + best + } +} + +/// Dedicated video memory of `device`'s adapter in bytes, zero if DXGI does +/// not say. Matching by LUID also covers a device made on the default adapter. +fn adapter_memory(device: &ID3D12Device) -> u64 { + // SAFETY: plain device and DXGI queries. + unsafe { + let luid = device.GetAdapterLuid(); + let Ok(factory) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) else { + return 0; + }; + for i in 0.. { + let Ok(adapter) = factory.EnumAdapters1(i) else { + break; + }; + let Ok(desc) = adapter.GetDesc1() else { + continue; + }; + if desc.AdapterLuid == luid { + return desc.DedicatedVideoMemory as u64; + } + } + 0 + } +} + +/// Dedicated video memory of the host adapter in bytes (`None` without a +/// host device). +pub(crate) fn device_memory() -> Option { + host().map(|h| h.memory) +} + /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton). /// Reject it before creating a device in diagnostics' software-only mode. fn warp_adapter() -> windows::core::Result { diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 19b19de..072b11f 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -462,20 +462,88 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { let Some(list) = host_list(this) else { return; }; - if let (Some(to), Some(from)) = ( - crate::resource::host_resource(dst), - crate::resource::host_resource(src), + if let (Some(dst_copy), Some(src_copy)) = ( + crate::resource::host_copy(dst), + crate::resource::host_copy(src), ) { + let (to, from) = (&dst_copy.texture, &src_copy.texture); if crate::texture::title_written(from) { crate::texture::upload(list, src, from); } ensure_state(list, dst, COPY_DEST); ensure_state(list, src, COPY_SOURCE); - crate::texture::host_written(dst); #[cfg(feature = "diagnostics")] list.note_op(|| format!("copy resource {src:?} to {dst:?}")); - // SAFETY: an open list and live textures. - unsafe { list.list.CopyResource(to, from) }; + // SAFETY: live textures. + let (a, b) = unsafe { (to.GetDesc(), from.GetDesc()) }; + if a.Dimension == b.Dimension + && a.Width == b.Width + && a.Height == b.Height + && a.DepthOrArraySize == b.DepthOrArraySize + && a.MipLevels == b.MipLevels + { + crate::texture::host_written(dst); + // SAFETY: an open list and matching live textures. + unsafe { list.list.CopyResource(to, from) }; + } else { + use windows::Win32::Graphics::Direct3D12::{ + D3D12_RESOURCE_DIMENSION_TEXTURE3D, D3D12_TEXTURE_COPY_LOCATION, + D3D12_TEXTURE_COPY_LOCATION_0, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + }; + let start = dst_copy.mip_drop().max(src_copy.mip_drop()); + let end = dst_copy.title_mips.min(src_copy.title_mips); + let slices = if a.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { + 1 + } else { + u32::from(a.DepthOrArraySize.min(b.DepthOrArraySize)) + }; + let mut copied = false; + for slice in 0..slices { + for mip in start..end { + let console_dst = slice * dst_copy.title_mips + mip; + let console_src = slice * src_copy.title_mips + mip; + let (Some(dst_sub), Some(src_sub)) = ( + dst_copy.host_subresource(console_dst), + src_copy.host_subresource(console_src), + ) else { + continue; + }; + let dst_mip = dst_sub % dst_copy.host_mips(); + let src_mip = src_sub % src_copy.host_mips(); + if (a.Width >> dst_mip).max(1) != (b.Width >> src_mip).max(1) + || (u64::from(a.Height) >> dst_mip).max(1) + != (u64::from(b.Height) >> src_mip).max(1) + { + continue; + } + let to_location = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(to) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: dst_sub, + }, + }; + let from_location = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(from) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: src_sub, + }, + }; + copied = true; + // SAFETY: an open list and matching surviving subresources. + unsafe { + list.list + .CopyTextureRegion(&to_location, 0, 0, 0, &from_location, None) + }; + } + } + if copied { + crate::texture::host_written(dst); + } + } } else if let (Some((to, a)), Some((from, b))) = ( crate::resource::buffer_bytes(dst), crate::resource::buffer_bytes(src), @@ -526,11 +594,20 @@ extern "system" fn copy_texture_region( else { return; }; - let Some(to) = crate::resource::host_resource(dst.resource) else { + let Some(dst_copy) = crate::resource::host_copy(dst.resource) else { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| tracing::warn!("texture to buffer copies not implemented")); return; }; + let to = &dst_copy.texture; + let mut to_location = dst; + if dst.kind != FOOTPRINT { + let console_sub = dst.footprint.offset as u32; + let Some(host_sub) = dst_copy.host_subresource(console_sub) else { + return; + }; + to_location.footprint.offset = u64::from(host_sub); + } let mut from = src; let _upload; // keeps the source alive while this call records it #[cfg(feature = "diagnostics")] @@ -557,9 +634,15 @@ extern "system" fn copy_texture_region( } _upload = buffer; } else { - let Some(texture) = crate::resource::host_resource(src.resource) else { + let Some(src_copy) = crate::resource::host_copy(src.resource) else { + return; + }; + let texture = &src_copy.texture; + let console_sub = src.footprint.offset as u32; + let Some(host_sub) = src_copy.host_subresource(console_sub) else { return; }; + from.footprint.offset = u64::from(host_sub); if crate::texture::title_written(texture) { crate::texture::upload(list, src.resource, texture); } @@ -568,7 +651,6 @@ extern "system" fn copy_texture_region( } ensure_state(list, dst.resource, COPY_DEST); crate::texture::host_written(dst.resource); - let mut to_location = dst; to_location.resource = to.as_raw().cast_const().cast(); let host_box = (!source_box.is_null()).then(|| source_box.cast::()); #[cfg(feature = "diagnostics")] @@ -636,11 +718,18 @@ extern "system" fn resolve( ) { #[cfg(windows)] if let Some(list) = host_list(this) - && let (Some(to), Some(from)) = ( - crate::resource::host_resource(dst), - crate::resource::host_resource(src), + && let (Some(dst_copy), Some(src_copy)) = ( + crate::resource::host_copy(dst), + crate::resource::host_copy(src), ) { + let (Some(dst_sub), Some(src_sub)) = ( + dst_copy.host_subresource(dst_sub), + src_copy.host_subresource(src_sub), + ) else { + return; + }; + let (to, from) = (&dst_copy.texture, &src_copy.texture); use windows::Win32::Foundation::RECT; use windows::Win32::Graphics::Direct3D12::{ D3D12_RESOLVE_MODE_AVERAGE, ID3D12GraphicsCommandList1, @@ -657,8 +746,14 @@ extern "system" fn resolve( // SAFETY: an open list and live textures; the region is inside both. unsafe { let (a, b) = (to.GetDesc(), from.GetDesc()); + let dst_mip = dst_sub % u32::from(a.MipLevels).max(1); + let src_mip = src_sub % u32::from(b.MipLevels).max(1); + let dst_w = (a.Width >> dst_mip).max(1); + let dst_h = (u64::from(a.Height) >> dst_mip).max(1); + let src_w = (b.Width >> src_mip).max(1); + let src_h = (u64::from(b.Height) >> src_mip).max(1); let format = DXGI_FORMAT(format as i32); - if (a.Width, a.Height) == (b.Width, b.Height) { + if (dst_w, dst_h) == (src_w, src_h) { list.list .ResolveSubresource(to, dst_sub, from, src_sub, format); } else if let Ok(list1) = list.list.cast::() { @@ -666,8 +761,8 @@ extern "system" fn resolve( let rect = RECT { left: 0, top: 0, - right: a.Width.min(b.Width) as i32, - bottom: a.Height.min(b.Height) as i32, + right: dst_w.min(src_w) as i32, + bottom: dst_h.min(src_h) as i32, }; list1.ResolveSubresourceRegion( to, diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index bf3e79e..65f5ee6 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -767,6 +767,174 @@ struct Resource { pub(crate) struct HostTexture { pub(crate) texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, pub(crate) state: std::sync::atomic::AtomicU32, + /// Mip levels in the title texture. + pub(crate) title_mips: u32, + /// Top title mips omitted from the host copy. + mip_drop: u32, + is_3d: bool, +} + +#[cfg(windows)] +impl HostTexture { + pub(crate) fn mip_drop(&self) -> u32 { + self.mip_drop + } + + pub(crate) fn host_mips(&self) -> u32 { + self.title_mips.saturating_sub(self.mip_drop).max(1) + } + + /// The host subresource of a console subresource, or `None` when it + /// names one of the dropped top mips. + pub(crate) fn host_subresource(&self, console_sub: u32) -> Option { + remap_subresource(console_sub, self.title_mips, self.mip_drop, self.is_3d) + } +} + +/// A console subresource index as the index of the host texture whose top +/// `mip_drop` mips were omitted; `None` for a dropped mip. +#[cfg(windows)] +pub(crate) fn remap_subresource( + console_sub: u32, + title_mips: u32, + mip_drop: u32, + is_3d: bool, +) -> Option { + if mip_drop == 0 { + return Some(console_sub); + } + let title_mips = title_mips.max(1); + let host_mips = title_mips.saturating_sub(mip_drop).max(1); + if is_3d { + if !(mip_drop..title_mips).contains(&console_sub) { + return None; + } + return Some(console_sub - mip_drop); + } + let mip = console_sub % title_mips; + let slice = console_sub / title_mips; + if mip < mip_drop { + return None; + } + Some(slice * host_mips + mip - mip_drop) +} + +/// A texture's host mip-drop count and surviving host mip count. +#[cfg(windows)] +pub(crate) fn host_mip_info(this: This) -> (u32, u32) { + host_copy(this).map_or((0, 0), |h| (h.mip_drop, h.host_mips())) +} + +/// Most top mips a sampled texture may lose. +const MAX_MIP_DROP: u32 = 3; + +/// Automatic mip-drop pressure raised when a host texture allocation runs +/// out of memory. +#[cfg(windows)] +static OOM_MIP_PRESSURE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// `VICTORY_TEXTURE_MIP_DROP`, if set (`0..=3`; invalid values count as unset). +#[cfg(windows)] +fn configured_mip_drop() -> Option { + static CONFIGURED: std::sync::OnceLock> = std::sync::OnceLock::new(); + *CONFIGURED.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_MIP_DROP") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map(|n| n.min(MAX_MIP_DROP)) + }) +} + +/// Baseline mip drop: the user's setting, otherwise one level on adapters +/// with at most 8.5 GiB of dedicated memory (RX 580-class budgets). +#[cfg(windows)] +fn requested_mip_drop() -> u32 { + let automatic = match crate::host::device_memory() { + Some(memory) if memory > 0 && memory <= (17 << 29) => 1, + _ => 0, + }; + configured_mip_drop() + .unwrap_or(automatic) + .max(OOM_MIP_PRESSURE.load(std::sync::atomic::Ordering::Relaxed)) + .min(MAX_MIP_DROP) +} + +/// Smallest largest-dimension a texture may keep after a drop +/// (`VICTORY_TEXTURE_MIP_DROP_MIN_SIZE`, default 1024): smaller textures cost +/// little memory, and dropping them mostly costs UI/detail quality. +#[cfg(windows)] +fn mip_drop_floor() -> u64 { + static FLOOR: std::sync::OnceLock = std::sync::OnceLock::new(); + *FLOOR.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_MIP_DROP_MIN_SIZE") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(1024) + .max(64) + }) +} + +/// How many of `requested` top mips may be dropped without touching render +/// targets, depth textures, UAVs, MSAA, non-power-of-two UI/artwork, small +/// textures or BC-misaligned mips. +#[cfg(windows)] +pub(crate) fn compute_mip_drop(desc: &ResourceDesc, requested: u32) -> u32 { + const TEXTURE_1D: u32 = 2; + if requested == 0 || desc.dimension == BUFFER || desc.flags & 0x7 != 0 || desc.sample_count > 1 + { + return 0; + } + let height = u64::from(desc.height); + let depth = u64::from(desc.depth_or_array_size); + if !desc.width.is_power_of_two() + || (desc.dimension != TEXTURE_1D && !height.is_power_of_two()) + || (desc.dimension == TEXTURE_3D && !depth.is_power_of_two()) + { + return 0; + } + let total_mips = mip_count(desc); + if total_mips <= 1 { + return 0; + } + let block = element(pc_format(desc.format)).map_or(1, |(_, block)| block); + let cap = requested.min(total_mips - 1); + let mut best = 0; + for drop in 1..=cap { + let width = (desc.width >> drop).max(1); + let height = if desc.dimension == TEXTURE_1D { + 1 + } else { + (height >> drop).max(1) + }; + let depth = if desc.dimension == TEXTURE_3D { + (depth >> drop).max(1) + } else { + 1 + }; + let large_enough = width.max(height).max(depth) >= mip_drop_floor(); + let aligned = width.is_multiple_of(block) && height.is_multiple_of(block); + if large_enough && aligned { + best = drop; + } + } + best +} + +/// Shrinks `desc` to the mip that survives as host mip 0. +#[cfg(windows)] +fn apply_mip_drop(desc: &mut ResourceDesc, title_mips: u32, drop: u32) { + const TEXTURE_1D: u32 = 2; + if drop == 0 { + return; + } + desc.width = (desc.width >> drop).max(1); + if desc.dimension != TEXTURE_1D { + desc.height = (desc.height >> drop).max(1); + } + if desc.dimension == TEXTURE_3D { + desc.depth_or_array_size = (desc.depth_or_array_size >> drop).max(1); + } + desc.mip_levels = u16::try_from(title_mips.saturating_sub(drop).max(1)).unwrap_or(1); } /// Moves the host texture to `wanted` (a host texture state); the host @@ -808,7 +976,7 @@ fn host_texture( desc: &ResourceDesc, state: u32, clear: *const c_void, -) -> Option { +) -> Option<(windows::Win32::Graphics::Direct3D12::ID3D12Resource, u32)> { use windows::Win32::Graphics::Direct3D12::*; const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access if desc.dimension == BUFFER { @@ -881,28 +1049,58 @@ fn host_texture( value[0] = pc_format(value[0]); value }); + let title_mips = mip_count(desc); + let base = d; + let mut drop = compute_mip_drop(&base, requested_mip_drop()); + apply_mip_drop(&mut d, title_mips, drop); let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; - let mut texture: Option = None; - // SAFETY: the description has the host layout (checked size, same - // fields); the out pointer is ours. - let made = unsafe { - host.device.CreateCommittedResource( - &heap, - D3D12_HEAP_FLAG_NONE, - (&raw const d).cast(), - D3D12_RESOURCE_STATES( - crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, - ), - // The same layout: format, then color or depth and stencil. - clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()), - &mut texture, - ) + let mut texture = None; + let made = loop { + let mut attempt = None; + // SAFETY: the description has the host layout (checked size, same + // fields); the out pointer is ours. + let made = unsafe { + host.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + (&raw const d).cast(), + D3D12_RESOURCE_STATES(crate::host::legal_for( + d.flags, + crate::host::texture_state(state), + ) as i32), + // The same layout: format, then color or depth and stencil. + clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()), + &mut attempt, + ) + }; + if made.is_ok() { + texture = attempt; + break made; + } + let Err(e) = &made else { unreachable!() }; + if e.code().0 != E_OUTOFMEMORY || drop >= MAX_MIP_DROP { + break made; + } + let pressure = OOM_MIP_PRESSURE + .fetch_max(drop + 1, std::sync::atomic::Ordering::Relaxed) + .max(drop + 1); + let next = compute_mip_drop(&base, requested_mip_drop().max(pressure)); + if next <= drop { + break made; + } + drop = next; + d = base; + apply_mip_drop(&mut d, title_mips, drop); + tracing::warn!( + drop, + "host texture allocation out of memory; dropping another top mip" + ); }; if let Err(e) = made { - tracing::warn!(error = %e, desc = ?d, "no host texture"); + tracing::warn!(error = %e, desc = ?d, drop, "no host texture"); } if let Some(t) = &texture { crate::host::name(t, || { @@ -912,7 +1110,7 @@ fn host_texture( ) }); } - texture + texture.map(|texture| (texture, drop)) } /// A texture's console memory and description; `None` for buffers. @@ -979,11 +1177,14 @@ fn hand_out_resource( heap_flags, backing, #[cfg(windows)] - host: host.map(|texture| { + host: host.map(|(texture, mip_drop)| { let state = crate::host::legal_state(&texture, crate::host::texture_state(state)); std::sync::Arc::new(HostTexture { texture, state: state.into(), + title_mips: mip_count(&desc), + mip_drop, + is_3d: desc.dimension == TEXTURE_3D, }) }), }); @@ -1939,6 +2140,7 @@ mod tests { .is_ok() && support.Support1.0 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0 != 0; let b5g5r5a1 = host_texture(&make(86, 5), 0, std::ptr::null()) + .map(|(texture, _)| texture) .expect("B5G5R5A1_UNORM texture should be created"); // SAFETY: live D3D12 resource. let d = unsafe { b5g5r5a1.GetDesc() }; @@ -1971,6 +2173,7 @@ mod tests { && support.Support1.0 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET.0 != 0; let clear = [115u32, 0, 0, 0, 0]; let b4g4r4a4 = host_texture(&make(115, 1), 0, clear.as_ptr().cast()) + .map(|(texture, _)| texture) .expect("B4G4R4A4_UNORM texture should succeed"); // SAFETY: live D3D12 resource. let bd = unsafe { b4g4r4a4.GetDesc() }; @@ -1985,9 +2188,39 @@ mod tests { // R8G8B8A8_TYPELESS (27) with flags=5 must keep ALLOW_UNORDERED_ACCESS. let typeless = host_texture(&make(27, 5), 0, std::ptr::null()) + .map(|(texture, _)| texture) .expect("R8G8B8A8_TYPELESS texture should succeed"); // SAFETY: live D3D12 resource. let td = unsafe { typeless.GetDesc() }; assert_ne!(td.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0, 0); } + + #[cfg(windows)] + #[test] + fn mip_drop_eligibility_and_subresource_remapping() { + let tex2d = |width, height, mips, format, flags| ResourceDesc { + dimension: 3, + alignment: 0, + width, + height, + depth_or_array_size: 1, + mip_levels: mips, + format, + sample_count: 1, + sample_quality: 0, + layout: 0, + flags, + }; + assert_eq!(compute_mip_drop(&tex2d(2048, 2048, 0, 28, 0), 1), 1); + assert_eq!(compute_mip_drop(&tex2d(1024, 1024, 0, 28, 0), 2), 0); + assert_eq!(compute_mip_drop(&tex2d(1920, 1080, 0, 28, 0), 1), 0); + assert_eq!(compute_mip_drop(&tex2d(2048, 2048, 0, 28, 1), 1), 0); + assert_eq!(compute_mip_drop(&tex2d(2048, 2048, 1, 28, 0), 1), 0); + assert_eq!(remap_subresource(0, 11, 2, false), None); + assert_eq!(remap_subresource(2, 11, 2, false), Some(0)); + assert_eq!(remap_subresource(13, 11, 2, false), Some(9)); + assert_eq!(remap_subresource(4, 11, 0, false), Some(4)); + assert_eq!(remap_subresource(2, 11, 2, true), Some(0)); + assert_eq!(remap_subresource(1, 11, 2, true), None); + } } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 10b0702..ee8e49c 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -50,6 +50,8 @@ pub(crate) struct Staging { mips: u32, /// Per subresource, the byte ranges of the memory it is detiled from. extents: Vec>>, + /// Top console mips omitted from the host copy. + mip_drop: u32, memory: *const u8, last: Mutex, } @@ -312,7 +314,7 @@ pub(crate) fn fingerprint(at: u64, len: u64) -> u64 { pub(crate) fn staged_memory(resource: This) -> Option<(u64, u64)> { let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); let staging = map.as_ref()?.get(&(resource as usize))?; - Some((staging.memory as u64, staging.size as u64)) + Some((staging.memory as u64, staging.layout.size)) } /// Frames after a whole upload of a texture at which its memory is looked @@ -592,7 +594,8 @@ impl Staging { if changed.is_some_and(|c| !overlaps(&self.extents[i], c)) { continue; } - let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); + let (host_mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); + let mip = host_mip + self.mip_drop; // SAFETY: the upload buffer is mapped for exactly this range. let linear = unsafe { std::slice::from_raw_parts_mut(self.data, self.size) }; if let Err(e) = self.layout.detile( @@ -747,9 +750,10 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { }); tracing::debug!(?desc, total, "texture contents uploaded from title memory"); let mips = u32::from(d.MipLevels).max(1); + let (mip_drop, _) = crate::resource::host_mip_info(resource); let whole: Vec<_> = std::iter::once(0..layout.size as usize).collect(); let extents = (0..count) - .map(|i| match layout.extents(i % mips, i / mips) { + .map(|i| match layout.extents(i % mips + mip_drop, i / mips) { Ok(e) => e .into_iter() .map(|r| r.start as usize..r.end as usize) @@ -766,6 +770,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { layout, mips: u32::from(d.MipLevels), extents, + mip_drop, memory, last: Mutex::default(), });