diff --git a/README.md b/README.md index 33ccbc64a0..d68751a45c 100644 --- a/README.md +++ b/README.md @@ -406,6 +406,11 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. 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. +- Single-sampled sRGB textures with unordered access use typeless storage where the adapter + supports the matching UNORM UAV. SRVs and RTVs retain sRGB conversion. `XCL_SRGB_TYPELESS=0` + restores the previous behavior of dropping unordered access. The log counts the textures + that keep or lose unordered access. PC D3D12 has no BGRX typed UAV, so BGRX retains sRGB + sampling and rendering with unordered access stripped. - `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/THIRD_PARTY.md b/THIRD_PARTY.md index db38e8a443..e810aeeadb 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -10,7 +10,7 @@ carry a note in their header about its origin and the date of changes (GPL-3.0 | [FFmpeg](https://ffmpeg.org/) | LGPL-2.1+ | XMA1/XMA2 decoder and tables (`crates/xcl/src/hle/xma2/`) – after `libavcodec/wmaprodec.c`, `wmaprodata.h`, `wma.c`, `sinewin_tablegen.h`, `libavutil/float_dsp.c`, `tx_template.c` | port to safe Rust with annotation | | [AMD Machine-Readable GPU ISA](https://gpuopen.com/machine-readable-isa/) | MIT | `crates/xcl/src/gpu/rdna2_spec.rs` (generated by `scripts/gen_rdna2.py`) | encoding and instruction tables | | [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation | -| [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables | +| [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT); the typeless sRGB UAV mapping in `d3d12x/device_x.rs`, after `victory-gpu/src/resource.rs` | port to Rust; tables; format mapping (code written independently) | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 62d5549b14..92a723aa62 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -4315,7 +4315,10 @@ unsafe fn trace_draw_kinds(this: *mut c_void, pso: usize, indirect: bool) { } let Some((vs, ps)) = super::real::pso_shaders(pso) else { return }; let rt = super::present::rt0_resource(this as usize).unwrap_or(0); - let desc = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0, d.SampleDesc.Count) }); + let desc = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { + let d = x.GetDesc(); + (d.Width, d.Height, super::real::console_format_of(r, d.Format.0 as u32) as i32, d.SampleDesc.Count) + }); // `XCL_TRACE_FORMATS=26,29` (DXGI format numbers): only draws into targets of those formats – // the first 160 kinds of a busy frame are its first passes, and the ones looked for (a // lighting target's) never got a line diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 8f2809df65..382c130b68 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -12,6 +12,9 @@ //! //! Console queue and list types add DMA (0x10, the copy engine); console queue priorities //! are mapped onto PC ones. +//! +//! The sRGB UAV typeless mapping follows VIctory's victory-gpu/src/resource.rs +//! (https://github.com/Marvisak/VIctory, GPL-3.0). use std::collections::HashMap; use std::ffi::{c_char, c_void, CStr, CString}; @@ -812,12 +815,40 @@ pub(super) unsafe fn strip_unsupported_uav_for_device(device: *mut c_void, mut d /// `pc_resource_desc` further validated against `device`'s `D3D12_FEATURE_FORMAT_SUPPORT` so /// `GetResourceAllocationInfo` never sees `ALLOW_UNORDERED_ACCESS` on an unsupported format. pub(super) unsafe fn pc_resource_desc_for_device(device: *mut c_void, x: &[u8; 0x38]) -> [u8; 0x38] { - strip_unsupported_uav_for_device(device, pc_resource_desc(x)) + let srgb = srgb_typeless_enabled() && srgb_uav_format(x).is_some_and(|f| { + device_format_supports_uav(device, srgb_uav_linear_format(f)) + }); + strip_unsupported_uav_for_device(device, pc_resource_desc_with_srgb_typeless(x, srgb)) +} + +pub(super) fn srgb_typeless_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_SRGB_TYPELESS").is_ok_and(|v| v.trim() == "0")) +} + +pub(super) fn srgb_typeless_family(format: u32) -> Option { + match format { + 29 => Some(27), + 91 => Some(90), + 93 => Some(92), + _ => None, + } +} + +pub(super) fn srgb_uav_format(x: &[u8; 0x38]) -> Option { + let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); + let format = u(0x20); + srgb_typeless_family(format)?; + (matches!(u(0), 2..=4) && u(0x24) == 1 && u(0x30) & 6 == 4).then_some(format) } /// the console resource desc (0x38 bytes, D3D12_RESOURCE_DESC) as a PC one: its tile layouts /// and console flag bits mean nothing to a PC driver pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { + pc_resource_desc_with_srgb_typeless(x, srgb_typeless_enabled()) +} + +fn pc_resource_desc_with_srgb_typeless(x: &[u8; 0x38], srgb_typeless: bool) -> [u8; 0x38] { let mut d = *x; let dim = u32::from_le_bytes(d[0..4].try_into().unwrap()); let mut flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); @@ -859,12 +890,21 @@ pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { if flags & 2 != 0 { flags &= !4; } + // Keep shader writes linear while the texture's SRVs and RTVs retain sRGB conversion. + // (only where the linear sibling takes typed UAVs: B8G8R8X8 has none on the PC, so a BGRX + // sRGB texture keeps its format and loses the flag as before) + let srgb_family = srgb_uav_format(x) + .filter(|&f| srgb_typeless && texture_format_allows_uav(srgb_uav_linear_format(f))) + .and_then(srgb_typeless_family); + if let Some(family) = srgb_family { + d[0x20..0x24].copy_from_slice(&family.to_le_bytes()); + } // Any non-buffer texture whose PC format cannot support typed UAVs (BC1–BC7, sRGB, depth, // 96-bit, A8, B5G6R5, B8G8R8X8, etc.) or that is multisampled must not carry // ALLOW_UNORDERED_ACCESS: PC D3D12 rejects even GetResourceAllocationInfo (id=599 / 0x887A0001). let pc_format = u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()); let samples = u32::from_le_bytes(d[0x24..0x28].try_into().unwrap()); - if dim != D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32 && (flags & 4) != 0 && (samples > 1 || !texture_format_allows_uav(pc_format)) { + if dim != D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32 && (flags & 4) != 0 && srgb_family.is_none() && (samples > 1 || !texture_format_allows_uav(pc_format)) { flags &= !4; } d[8..16].fill(0); // alignment: the driver's @@ -969,6 +1009,12 @@ pub fn pc_uav_linear_format(fmt: u32) -> u32 { } } +/// A typeless BGRX resource must use its own UNORM sibling. PC D3D12 has no BGRX typed UAV +/// support, so the device path drops its UAV flag; BGRA (87) is from a different family. +pub(super) fn srgb_uav_linear_format(fmt: u32) -> u32 { + if fmt == 93 { 88 } else { pc_uav_linear_format(fmt) } +} + /// Whether the host D3D12 device supports typed UAV views (`D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW`) /// for `fmt`. Queries `CheckFeatureSupport` once per `(adapter LUID, fmt)` and caches the answer. pub(super) unsafe fn pc_typed_uav_supported(dev_raw: *mut c_void, fmt: i32) -> bool { @@ -1023,15 +1069,18 @@ pub(super) fn pc_clear_format(pc_format: u32, clear_format: u32) -> u32 { } } -/// Like `pc_clear`, also aligning `clear.Format` with `pc_format` when `pc_resource_desc` promoted -/// a UAV-capable `B5G6R5` (`85 -> 28`) or `B8G8R8X8` (`88 -> 87`) resource. -pub(super) unsafe fn pc_clear_for_desc(clear: *const c_void, pc_format: u32, buf: &mut [u8; 24]) -> *const c_void { +/// Like `pc_clear`, also aligning the clear format for promoted UAV resources. An sRGB resource +/// made typeless keeps its original typed clear format. +pub(super) unsafe fn pc_clear_for_desc(clear: *const c_void, x: &[u8; 0x38], d: &[u8; 0x38], buf: &mut [u8; 24]) -> *const c_void { if clear.is_null() || !crate::gpu::shader::readable(clear as usize, 24) { return clear; } std::ptr::copy_nonoverlapping(clear as *const u8, buf.as_mut_ptr(), 24); let f = u32::from_le_bytes(buf[0..4].try_into().unwrap()); - buf[0..4].copy_from_slice(&pc_clear_format(pc_format, f).to_le_bytes()); + let pc_format = u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()); + let format = srgb_uav_format(x).filter(|&f| srgb_typeless_family(f) == Some(pc_format)) + .unwrap_or_else(|| pc_clear_format(pc_format, f)); + buf[0..4].copy_from_slice(&format.to_le_bytes()); buf.as_ptr() as *const c_void } @@ -1257,8 +1306,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, // PC's: the PC refused the resource (E_INVALIDARG) and the title threw let state = pc_initial_state(u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()), state); let mut clear_buf = [0u8; 24]; - let pc_format = u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()); - let clear = pc_clear_for_desc(clear, pc_format, &mut clear_buf); + let clear = pc_clear_for_desc(clear, &x, &d, &mut clear_buf); if buffer { if let Some(hr) = real::place_at_title_address(this, va as usize, &d, state, clear, riid, ppv) { return hr; @@ -1283,6 +1331,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, if super::vram::gpu_owned(flags) { if let Some(hr) = super::vram::place(this, va as usize, &pc, state, clear, console_bytes, riid, ppv) { if hr >= 0 && !(*ppv).is_null() { + real::note_srgb_texture(*ppv, &x); if super::title_textures::register_gpu_owned(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)).is_err() { if let Some(bytes) = console_bytes { super::title_textures::retire_overlapping(va as usize, bytes as usize); @@ -1308,6 +1357,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } }; if hr >= 0 && !buffer && !(*ppv).is_null() { + real::note_srgb_texture(*ppv, &x); static M: AtomicU64 = AtomicU64::new(0); match super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)) { Ok(()) => { @@ -1392,6 +1442,11 @@ pub(super) unsafe extern "system" fn get_copyable_footprints_x( return f(this, desc, first, num, base, layouts, rows, row_sizes, total); } let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); + if srgb_typeless_enabled() && srgb_uav_format(&x).is_some() { + // The layout is the same either way; keep the title's typed format in its footprints. + let d = pc_resource_desc_with_srgb_typeless(&x, false); + return f(this, d.as_ptr(), first, num, base, layouts, rows, row_sizes, total); + } let mut probe = u64::MAX; let t = if total.is_null() { &mut probe as *mut u64 } else { total }; *t = u64::MAX; @@ -1771,7 +1826,7 @@ mod tests { x[0x20..0x24].copy_from_slice(&fmt.to_le_bytes()); x[0x24..0x28].copy_from_slice(&samples.to_le_bytes()); x[0x30..0x34].copy_from_slice(&flags.to_le_bytes()); - let d = pc_resource_desc(&x); + let d = pc_resource_desc_with_srgb_typeless(&x, false); ( u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()), u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()), @@ -1958,6 +2013,67 @@ mod tests { assert_eq!(pc_uav_linear_format(28), 28); } + #[test] + fn srgb_uav_resource_desc_selects_typeless_only_for_eligible_textures() { + for (srgb, family, linear) in [(29u32, 27, 28), (91, 90, 87), (93, 93, 88)] { + assert_eq!(srgb_uav_linear_format(srgb), linear); + // BGRX: no typed UAV of its linear sibling on the PC, so never typeless with the flag + let uav = if srgb == 93 { 0 } else { 4 }; + let mut x = [0u8; 0x38]; + x[0x20..0x24].copy_from_slice(&srgb.to_le_bytes()); + for (dim, samples, flags, expected_format, expected_flags) in [ + (2, 1, 4, family, uav), + (3, 1, 5, family, 1 | uav), + (4, 1, 4, family, uav), + (3, 1, 1, srgb, 1), + (3, 4, 5, srgb, 1), + (3, 1, 6, srgb, 2), + (1, 1, 4, srgb, 4), + ] { + x[0] = dim; + x[0x24] = samples; + x[0x30] = flags; + let d = pc_resource_desc_with_srgb_typeless(&x, true); + assert_eq!((u32::from(d[0x20]), d[0x30]), (expected_format, expected_flags)); + } + x[0] = 3; + x[0x30] = 5; + let d = pc_resource_desc_with_srgb_typeless(&x, false); + assert_eq!((u32::from(d[0x20]), d[0x30]), (srgb, 1)); + if srgb == 93 { + let d = unsafe { pc_resource_desc_for_device(std::ptr::null_mut(), &x) }; + assert_eq!((d[0x20], d[0x30]), (93, 1), "BGRX has no PC typed UAV"); + } + } + } + + #[test] + fn srgb_uav_clear_value_keeps_the_title_format() { + // (BGRX sRGB, 93, is never made typeless: its clear follows the typed rule, as on main) + for (srgb, raw_format) in [(29u8, 28), (91, 0)] { + let mut x = [0u8; 0x38]; + x[0] = 3; + x[0x20] = srgb; + x[0x24] = 1; + x[0x30] = 5; + let d = pc_resource_desc_with_srgb_typeless(&x, true); + let mut raw = [0u8; 24]; + let mut buf = [0u8; 24]; + raw[0] = raw_format; + raw[4..8].copy_from_slice(&0.5f32.to_le_bytes()); + unsafe { pc_clear_for_desc(raw.as_ptr().cast(), &x, &d, &mut buf) }; + assert_eq!((buf[0], &buf[4..]), (srgb, &raw[4..])); + } + let mut x = [0u8; 0x38]; + (x[0], x[0x20], x[0x24], x[0x30]) = (3, 93, 1, 5); + let d = pc_resource_desc_with_srgb_typeless(&x, true); + assert_eq!((d[0x20], d[0x30]), (93, 1)); + let (mut raw, mut buf) = ([0u8; 24], [0u8; 24]); + raw[0] = 92; + unsafe { pc_clear_for_desc(raw.as_ptr().cast(), &x, &d, &mut buf) }; + assert_eq!(u32::from(buf[0]), pc_clear_format(93, 92)); + } + #[test] fn pc_clear_for_desc_aligns_promoted_uav_targets_only() { let desc_fmt = |fmt: u32, flags: u32| { @@ -1975,10 +2091,16 @@ mod tests { let (mut raw, mut buf) = ([0u8; 24], [0u8; 24]); raw[0..4].copy_from_slice(&85u32.to_le_bytes()); raw[4..8].copy_from_slice(&0.5f32.to_le_bytes()); + let mut x = [0u8; 0x38]; + x[0] = 3; + x[0x20] = 85; + x[0x24] = 1; + x[0x30] = 5; + let d = pc_resource_desc(&x); unsafe { - assert_eq!(pc_clear_for_desc(raw.as_ptr() as *const c_void, 28, &mut buf), buf.as_ptr() as *const c_void); + assert_eq!(pc_clear_for_desc(raw.as_ptr() as *const c_void, &x, &d, &mut buf), buf.as_ptr() as *const c_void); assert_eq!((u32::from_le_bytes(buf[0..4].try_into().unwrap()), &buf[4..24]), (28, &raw[4..24])); - assert!(pc_clear_for_desc(std::ptr::null(), 28, &mut buf).is_null()); + assert!(pc_clear_for_desc(std::ptr::null(), &x, &d, &mut buf).is_null()); } } @@ -2017,7 +2139,7 @@ mod tests { }; let (mut old_buf, mut new_buf) = ([0u8; 24], [0u8; 24]); let old_cv: D3D12_CLEAR_VALUE = std::ptr::read_unaligned(pc_clear(&clear as *const _ as *const c_void, &mut old_buf) as *const _); - let new_cv: D3D12_CLEAR_VALUE = std::ptr::read_unaligned(pc_clear_for_desc(&clear as *const _ as *const c_void, pc_fmt, &mut new_buf) as *const _); + let new_cv: D3D12_CLEAR_VALUE = std::ptr::read_unaligned(pc_clear_for_desc(&clear as *const _ as *const c_void, &x, &d_bytes, &mut new_buf) as *const _); let mut r: Option = None; assert!(dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, Some(&old_cv), &mut r).is_err()); assert_eq!(new_cv.Format.0 as u32, promoted_fmt); diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index cf37a356d8..5e206c9005 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -1512,7 +1512,8 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, let mut dumps = Vec::new(); for (tag, res, d) in targets.map_or(Vec::new(), |f| super::targets::to_dump(PRESENTS.load(Ordering::Relaxed), &f)) { if let Some((buffer, footprint)) = readback_copy(&p.list, &res, &d) { - dumps.push(FrameDump { _source: res, buffer, footprint, format: d.Format, tag }); + let format = DXGI_FORMAT(super::real::console_format_of(res.as_raw() as usize, d.Format.0 as u32) as i32); + dumps.push(FrameDump { _source: res, buffer, footprint, format, tag }); } } // and what each depth UAV twin holds (`depth_uav`; it rests in UNORDERED_ACCESS) @@ -1605,7 +1606,8 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, } if due { if let Some((buffer, footprint)) = readback_copy(&p.list, src, desc) { - dumps.push(FrameDump { _source: src.clone(), buffer, footprint, format: desc.Format, tag: "frame".into() }); + let format = DXGI_FORMAT(super::real::console_format_of(src.as_raw() as usize, desc.Format.0 as u32) as i32); + dumps.push(FrameDump { _source: src.clone(), buffer, footprint, format, tag: "frame".into() }); } } let b2 = [transition(&bb, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT)]; @@ -1626,7 +1628,8 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, return None; } let (buffer, footprint) = readback_copy(&p.list, &res, &d)?; - Some((res, buffer, footprint, d.Format)) + let format = DXGI_FORMAT(super::real::console_format_of(res.as_raw() as usize, d.Format.0 as u32) as i32); + Some((res, buffer, footprint, format)) }); for (k, (res, buffer, footprint, format)) in targets.enumerate() { let tag = if k == 0 { "rt".into() } else { format!("rt{k}") }; @@ -1758,7 +1761,7 @@ pub fn last_frame_dump() -> Option { } /// a copy of subresource 0 of `src` into a new readback buffer, recorded on `list` -unsafe fn readback_copy(list: &ID3D12GraphicsCommandList, src: &ID3D12Resource, desc: &D3D12_RESOURCE_DESC) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> { +pub(super) unsafe fn readback_copy(list: &ID3D12GraphicsCommandList, src: &ID3D12Resource, desc: &D3D12_RESOURCE_DESC) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> { let dev: ID3D12Device = { let mut d: Option = None; src.GetDevice(&mut d).ok()?; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a9dad2dd11..5af9a8498d 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -28,6 +28,7 @@ use windows::core::{Interface, PCSTR}; use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; use windows::Win32::Graphics::Direct3D::*; use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; use windows::Win32::Graphics::Dxgi::*; use windows_sys::core::GUID; @@ -1998,6 +1999,50 @@ fn buffer_view(res: usize, format: windows::Win32::Graphics::Dxgi::Common::DXGI_ /// and buffers, XCL's blocks outside its arena pool const COHERENT_KEPT: usize = 128 << 20; +static SRGB_TEXTURES: Sharded = Sharded::new(); +/// Live entries of `SRGB_TEXTURES`: 0 (no such texture, or `XCL_SRGB_TYPELESS=0`) keeps the +/// table's locks off the hot paths (resource release, view creation). +static SRGB_LIVE: AtomicUsize = AtomicUsize::new(0); + +fn srgb_textures_live() -> bool { + SRGB_LIVE.load(Ordering::Relaxed) != 0 +} + +fn srgb_texture_forget(res: usize) { + if srgb_textures_live() && SRGB_TEXTURES.remove(res).is_some() { + SRGB_LIVE.fetch_sub(1, Ordering::Relaxed); + } +} + +/// The title's typed format, for an sRGB texture XCL made typeless for UAVs. +fn srgb_view_format(res: usize, pc_format: u32) -> Option { + if matches!(pc_format, 27 | 90 | 92) && srgb_textures_live() { + return SRGB_TEXTURES.get(res).filter(|&f| super::device_x::srgb_typeless_family(f) == Some(pc_format)); + } + None +} + +pub(super) fn console_format_of(res: usize, pc_format: u32) -> u32 { + srgb_view_format(res, pc_format).unwrap_or(pc_format) +} + +pub(super) unsafe fn note_srgb_texture(res: *mut c_void, x: &[u8; 0x38]) { + let Some(format) = super::device_x::srgb_uav_format(x) else { return }; + let Some(rd) = desc_of(res) else { return }; + static KEPT: AtomicU64 = AtomicU64::new(0); + static STRIPPED: AtomicU64 = AtomicU64::new(0); + if rd.Flags.0 & 4 != 0 && super::device_x::srgb_typeless_family(format) == Some(rd.Format.0 as u32) { + if SRGB_TEXTURES.insert(res as usize, format).is_none() { + SRGB_LIVE.fetch_add(1, Ordering::Relaxed); + } + let n = KEPT.fetch_add(1, Ordering::Relaxed) + 1; + crate::xlog_info!("D3D12.X: sRGB texture {}x{} fmt {format} kept with unordered access as TYPELESS ({n} kept)", rd.Width, rd.Height); + } else if rd.Flags.0 & 4 == 0 { + let n = STRIPPED.fetch_add(1, Ordering::Relaxed) + 1; + crate::xlog_info!("D3D12.X: sRGB texture {}x{} fmt {format} stripped of unordered access ({n} stripped)", rd.Width, rd.Height); + } +} + unsafe fn place_console_texture(this: *mut c_void, desc: usize, state: usize, clear: usize, riid: *const GUID, ppv: *mut *mut c_void) -> Option { let u = crate::gpu::uma::get()?; if ppv.is_null() || !crate::gpu::shader::readable(desc, 0x38) { @@ -2545,6 +2590,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { super::small_tex::gone(this as usize); } super::depth_uav::forget(this as usize); + srgb_texture_forget(this as usize); super::barrier_groups::forget(this as usize); let final_state = super::title_textures::forget(this as usize); super::lut3d::forget(this as usize); @@ -3058,6 +3104,23 @@ fn default_uav_desc(rd: &D3D12_RESOURCE_DESC, fmt: u32) -> D3D12_UNORDERED_ACCES d } +/// The format of an SRV / RTV of a texture XCL made typeless for UAVs (`srgb` = the title's +/// sRGB format): with no format or the typeless family the title's sRGB one; an explicit typed +/// format of the family (e.g. UNORM to read the bytes raw) is the title's own and stays. +fn srgb_or_explicit(srgb: Option, resource: u32, view: u32) -> Option { + srgb.map(|s| if view == 0 || view == resource { s } else { view }) +} + +fn pc_uav_format(resource: u32, srgb: Option, view: u32) -> u32 { + if let Some(format) = srgb { + // no format, the typeless family or the sRGB one: the linear sibling; an explicit typed + // format of the family (UNORM, UINT, SNORM, SINT) is the title's own and stays + return if view == 0 || view == resource || view == format { super::device_x::srgb_uav_linear_format(format) } else { view }; + } + let mapped = super::device_x::pc_uav_linear_format(if view == 0 { resource } else { view }); + super::device_x::pc_shader_view_format(resource, mapped) +} + /// Device #19 wrapper: guards non-depth texture UAVs against sRGB or host-unsupported /// `D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW` formats (preventing `0x887A0001`) /// before delegating to `dev_create_uav_x`. @@ -3088,8 +3151,7 @@ unsafe fn dev_create_uav_checked_inner( let mut patched = desc.as_ref().copied(); let raw_fmt = patched.as_ref().map_or(0, |d| d.Format.0 as u32); let res_fmt = rd.Format.0 as u32; - let mapped_fmt = super::device_x::pc_uav_linear_format(if raw_fmt == 0 { res_fmt } else { raw_fmt }); - let eff_fmt = super::device_x::pc_shader_view_format(res_fmt, mapped_fmt); + let eff_fmt = pc_uav_format(res_fmt, srgb_view_format(res as usize, res_fmt), raw_fmt); if let Some(c) = patched.as_mut() { if eff_fmt != 0 && (eff_fmt != raw_fmt && (raw_fmt != 0 || eff_fmt != res_fmt)) { c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(eff_fmt as i32); @@ -3186,8 +3248,7 @@ fn default_dsv(d: &D3D12_RESOURCE_DESC) -> Option /// A shader view `v` (None: the resource's default one) of `rd` with the PC's format names /// (`device_x::pc_shader_view_format`) – None: as it is. -fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> Option { - use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; +fn pc_srv(rd: &D3D12_RESOURCE_DESC, srgb: Option, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> Option { if rd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { return None; } @@ -3195,24 +3256,34 @@ fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) let mut out = match v { Some(v) => *v, None => { - // only a typeless depth buffer needs a description of its own - if !matches!(rf, 19 | 39 | 44 | 53) { + if srgb.is_none() && !matches!(rf, 19 | 39 | 44 | 53) { return None; } let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ..Default::default() }; let slices = u32::from(rd.DepthOrArraySize); - // a multisampled depth buffer has only the MS view dimensions - match (rd.SampleDesc.Count > 1, slices > 1) { - (true, true) => { + match (rd.Dimension, rd.SampleDesc.Count > 1, slices > 1) { + (D3D12_RESOURCE_DIMENSION_TEXTURE1D, _, true) if srgb.is_some() => { + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1DARRAY; + v.Anonymous.Texture1DArray = D3D12_TEX1D_ARRAY_SRV { MipLevels: u32::MAX, ArraySize: slices, ..Default::default() }; + } + (D3D12_RESOURCE_DIMENSION_TEXTURE1D, _, false) if srgb.is_some() => { + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; + v.Anonymous.Texture1D = D3D12_TEX1D_SRV { MipLevels: u32::MAX, ..Default::default() }; + } + (D3D12_RESOURCE_DIMENSION_TEXTURE3D, _, _) if srgb.is_some() => { + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + v.Anonymous.Texture3D = D3D12_TEX3D_SRV { MipLevels: u32::MAX, ..Default::default() }; + } + (_, true, true) => { v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY; v.Anonymous.Texture2DMSArray = D3D12_TEX2DMS_ARRAY_SRV { FirstArraySlice: 0, ArraySize: slices }; } - (true, false) => v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMS, - (false, true) => { + (_, true, false) => v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMS, + (_, false, true) => { v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; v.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_SRV { MipLevels: u32::MAX, ArraySize: slices, ..Default::default() }; } - (false, false) => { + (_, false, false) => { v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; v.Anonymous.Texture2D = D3D12_TEX2D_SRV { MipLevels: u32::MAX, ..Default::default() }; } @@ -3223,7 +3294,7 @@ fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) if out.ViewDimension == D3D12_SRV_DIMENSION_BUFFER || out.ViewDimension == D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE { return None; } - let f = super::device_x::pc_shader_view_format(rf, out.Format.0 as u32); + let f = srgb_or_explicit(srgb, rf, out.Format.0 as u32).unwrap_or_else(|| super::device_x::pc_shader_view_format(rf, out.Format.0 as u32)); let stencil = super::device_x::stencil_view(rf, f); if v.is_some() && f == out.Format.0 as u32 && !stencil { return None; @@ -3272,7 +3343,7 @@ unsafe fn dev_create_srv_inner(this: *mut c_void, res: *mut c_void, desc: *const } // a depth buffer's view in the formats the PC has for it (a D24S8 format itself, R16_UNORM of // a D16S8 buffer …: an invalid call, the device removed) - if let Some(v) = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| pc_srv(&r.GetDesc(), copy.as_ref())) { + if let Some(v) = desc_of(res).and_then(|rd| pc_srv(&rd, srgb_view_format(res as usize, rd.Format.0 as u32), copy.as_ref())) { copy = Some(v); } let desc = copy.as_ref().map_or(desc, |c| c as *const _); @@ -3488,7 +3559,11 @@ unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u } let r = resource_at(this, rdesc, va); let _t = crate::hle::api_cost::time_if(super::look_stats::deep(), crate::hle::api_cost::Call::ViewDescriptor); - dev_create_uav_x(this, r, std::ptr::null_mut(), &v, cpu); + if srgb_textures_live() && SRGB_TEXTURES.contains(r as usize) { + dev_create_uav_checked_inner(this, r, std::ptr::null_mut(), &v, cpu); + } else { + dev_create_uav_x(this, r, std::ptr::null_mut(), &v, cpu); + } } /// V# of `n` elements from element `first` of the buffer at `va`, and the bytes it covers @@ -3687,7 +3762,7 @@ fn uav_companion_srv( }; if let Some(r) = rd.filter(|_| !null_resource) { - if let Some(v) = pc_srv(r, Some(&srv)) { + if let Some(v) = pc_srv(r, None, Some(&srv)) { srv = v; } } @@ -3805,7 +3880,9 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, }; // RDNA images have no SRV / UAV distinction: console shaders may read any image UAV slot // (`image_load`, `image_sample_*`, `image_get_resinfo` all index `ResourceDescriptorHeap[slot.index]`). - let deny_srv = rd.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 != 0; + // A stripped sRGB UAV's linear format may also be invalid as a view of the typed resource. + let deny_srv = rd.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 != 0 + || (no_uav && super::device_x::srgb_typeless_family(rd.Format.0 as u32).is_some() && super::device_x::srgb_typeless_enabled()); if let Some(srv) = uav_companion_srv(Some(&rd), desc.as_ref(), deny_srv) { let srv_res = if deny_srv { std::ptr::null_mut() } else { res }; let g: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); @@ -3847,12 +3924,23 @@ unsafe extern "system" fn dev_create_committed_resource_layout_x( /// PC it is a resource of its own. unsafe fn create_display_target(this: *mut c_void, props: usize, desc: usize, state: usize, clear: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); - let d = super::device_x::pc_resource_desc(&x); + let mut clear_buf = [0u8; 24]; + let mut clear = clear; + let mut state = state; + let d = if super::device_x::srgb_typeless_enabled() && super::device_x::srgb_uav_format(&x).is_some() { + let d = super::device_x::pc_resource_desc_for_device(this, &x); + state = super::device_x::pc_initial_state_for_desc(x[0x30] as u32, d[0x30] as u32, state as u32) as usize; + clear = super::device_x::pc_clear_for_desc(clear as *const c_void, &x, &d, &mut clear_buf) as usize; + d + } else { + super::device_x::pc_resource_desc(&x) + }; let hr = dev_create_committed_resource(this, props, 0, d.as_ptr() as usize, state, clear, riid, ppv); if hr < 0 || ppv.is_null() || (*ppv).is_null() { crate::xlog_warn!("D3D12.X: display target: {hr:#x}; desc {x:02x?}"); return hr; } + note_srgb_texture(*ppv, &x); let size = crate::hle::xg::Texture::new(&x).map_or(0, |t| t.size()) as usize; let at = if size > 0 { crate::hle::kernelx::runtime_alloc(size, crate::hle::kernelx::D3D_DISPLAY_TARGET) } else { None }; if let Some(p) = at { @@ -3909,25 +3997,27 @@ unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, pro // not placed in unified memory (e.g. its coherent window kept for readback heaps): a PC // resource of the PC's description – the console's flag bits (0x1000000, 0x300000 …) and // alignments made the PC refuse Fortnite's 3264x1836 scene targets (E_INVALIDARG, a crash) - let pc_full = (console_desc != 0 && crate::gpu::shader::readable(console_desc, 0x38)) - .then(|| super::device_x::pc_resource_desc_for_device(this, &(console_desc as *const [u8; 0x38]).read_unaligned())); + let x = (console_desc != 0 && crate::gpu::shader::readable(console_desc, 0x38)) + .then(|| (console_desc as *const [u8; 0x38]).read_unaligned()); + let pc_full = x.as_ref().map(|x| super::device_x::pc_resource_desc_for_device(this, x)); let desc = pc_full.as_ref().map_or(desc, |d| d.as_ptr() as usize); let mut clear_buf = [0u8; 24]; - let clear = match pc_full.as_ref() { - Some(d) => super::device_x::pc_clear_for_desc(clear as *const c_void, u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()), &mut clear_buf), + let clear = match x.as_ref().zip(pc_full.as_ref()) { + Some((x, d)) => super::device_x::pc_clear_for_desc(clear as *const c_void, x, d, &mut clear_buf), None => super::device_x::pc_clear(clear as *const c_void, &mut clear_buf), } as usize; // console-only state bits (e.g. 0x100000 on a display target) are not the PC's; a resource // the PC description took ALLOW_UNORDERED_ACCESS from does not start as a UAV - let st = pc_full.as_ref().map_or(state as u32 & PC_RESOURCE_STATES, |d| { - let orig_flags = u32::from_le_bytes((console_desc as *const [u8; 0x38]).read_unaligned()[0x30..0x34].try_into().unwrap()); + let st = x.as_ref().zip(pc_full.as_ref()).map_or(state as u32 & PC_RESOURCE_STATES, |(x, d)| { + let orig_flags = u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()); let pc_flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); super::device_x::pc_initial_state_for_desc(orig_flags, pc_flags, state as u32) }); let hr = dev_create_committed_resource(this, props, flags, desc, st as usize, clear, riid, ppv); - if hr >= 0 && pc_full.is_some() && !ppv.is_null() && !(*ppv).is_null() { - super::depth_uav::note_created(*ppv, &(console_desc as *const [u8; 0x38]).read_unaligned(), None, st); - super::lut3d::created("CreateCommittedResource (a PC resource: not in the title's memory)", *ppv, Some(&(console_desc as *const [u8; 0x38]).read_unaligned()), None, false, st); + if let Some(x) = x.as_ref().filter(|_| hr >= 0 && !ppv.is_null() && !(*ppv).is_null()) { + note_srgb_texture(*ppv, x); + super::depth_uav::note_created(*ppv, x, None, st); + super::lut3d::created("CreateCommittedResource (a PC resource: not in the title's memory)", *ppv, Some(x), None, false, st); } if hr < 0 { let pw = |o: usize| if props == 0 { 0 } else { *((props + o) as *const u32) }; @@ -4447,9 +4537,12 @@ pub(super) const PC_RESOURCE_STATES: u32 = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | /// bits dropped). Logged with the console's values. pub(super) unsafe extern "system" fn dev_create_placed_resource_x(this: *mut c_void, heap: usize, offset: usize, desc: usize, state: usize, clear: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let hr = placed_in_heap_x(this, heap, offset, desc, state, clear, riid, ppv); - if hr >= 0 && super::lut3d::created_on() && !ppv.is_null() && desc != 0 && crate::gpu::shader::readable(desc, 0x38) { + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() && desc != 0 && crate::gpu::shader::readable(desc, 0x38) { let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); - super::lut3d::created(&format!("CreatePlacedResource (heap {heap:#x} at {offset:#x}: the PC's memory, not kept in step)"), *ppv, Some(&x), None, false, state as u32 & PC_RESOURCE_STATES); + note_srgb_texture(*ppv, &x); + if super::lut3d::created_on() { + super::lut3d::created(&format!("CreatePlacedResource (heap {heap:#x} at {offset:#x}: the PC's memory, not kept in step)"), *ppv, Some(&x), None, false, state as u32 & PC_RESOURCE_STATES); + } } hr } @@ -4480,16 +4573,22 @@ unsafe fn placed_in_heap_x(this: *mut c_void, heap: usize, offset: usize, desc: if let Some(hr) = own_memory_if_larger_on_the_pc(this, heap, offset, desc, state, clear, riid, ppv) { return hr; } - let hr = dev_create_placed_resource(this, heap, offset, desc, state, clear, riid, ppv); - if hr >= 0 || desc == 0 || !crate::gpu::shader::readable(desc, 0x38) { - return hr; + if desc == 0 || !crate::gpu::shader::readable(desc, 0x38) { + return dev_create_placed_resource(this, heap, offset, desc, state, clear, riid, ppv); } let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); - let d = super::device_x::pc_resource_desc(&x); - let st = super::device_x::pc_initial_state(u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()), state as u32); + let srgb = super::device_x::srgb_typeless_enabled() && super::device_x::srgb_uav_format(&x).is_some(); + let original_hr = (!srgb).then(|| dev_create_placed_resource(this, heap, offset, desc, state, clear, riid, ppv)); + if let Some(hr) = original_hr.filter(|&hr| hr >= 0) { + return hr; + } + let (d, st) = pc_heap_placement_desc(this, &x, state as u32, srgb); let mut clear_buf2 = [0u8; 24]; - let clear_d = super::device_x::pc_clear_for_desc(clear as *const c_void, u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()), &mut clear_buf2) as usize; + let clear_d = super::device_x::pc_clear_for_desc(clear as *const c_void, &x, &d, &mut clear_buf2) as usize; let hr2 = dev_create_placed_resource(this, heap, offset, d.as_ptr() as usize, st as usize, clear_d, riid, ppv); + if srgb && hr2 >= 0 { + return hr2; + } let heap_desc = pc_heap_desc(heap); let pc_size = pc_allocation_size(this, &d); // A texture the title placed by the console's size (`get_resource_allocation_info_x` @@ -4502,7 +4601,7 @@ unsafe fn placed_in_heap_x(this: *mut c_void, heap: usize, offset: usize, desc: _ => None, }; static N: AtomicU64 = AtomicU64::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 8 { + if let Some(hr) = original_hr.filter(|_| N.fetch_add(1, Ordering::Relaxed) < 8) { let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); let sizes = format!( "heap {:#x} bytes, PC size {:#x}{}", @@ -4523,6 +4622,17 @@ unsafe fn placed_in_heap_x(this: *mut c_void, heap: usize, offset: usize, desc: hr } +unsafe fn pc_heap_placement_desc(this: *mut c_void, x: &[u8; 0x38], state: u32, srgb: bool) -> ([u8; 0x38], u32) { + let flags = u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()); + if srgb { + let d = super::device_x::pc_resource_desc_for_device(this, x); + let st = super::device_x::pc_initial_state_for_desc(flags, d[0x30] as u32, state); + (d, st) + } else { + (super::device_x::pc_resource_desc(x), super::device_x::pc_initial_state(flags, state)) + } +} + /// A texture the title placed in a heap by the console's size (`get_resource_allocation_info_x` /// answers with XG's), when the PC's is larger: placed at the console's offset it would cover /// the start of whatever the title placed after it, and each would write over the other. @@ -4540,15 +4650,15 @@ unsafe fn own_memory_if_larger_on_the_pc(this: *mut c_void, heap: usize, offset: return None; } let console = crate::hle::xg::Texture::new(&x).ok()?.size(); - let d = super::device_x::pc_resource_desc(&x); + let srgb = super::device_x::srgb_typeless_enabled() && super::device_x::srgb_uav_format(&x).is_some(); + let (d, st) = pc_heap_placement_desc(this, &x, state as u32, srgb); let pc = pc_allocation_size(this, &d); if console == u64::MAX || pc == u64::MAX || pc <= console { return None; } let h = pc_heap_desc(heap)?; - let st = super::device_x::pc_initial_state(u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()), state as u32); let mut clear_buf = [0u8; 24]; - let clear = super::device_x::pc_clear_for_desc(clear as *const c_void, u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()), &mut clear_buf) as usize; + let clear = super::device_x::pc_clear_for_desc(clear as *const c_void, &x, &d, &mut clear_buf) as usize; let mut hr = dev_create_committed_resource(this, &h.Properties as *const _ as usize, 0, d.as_ptr() as usize, st as usize, clear, riid, ppv); let mut made_in = st; if hr < 0 && st != 0 { @@ -11330,6 +11440,38 @@ mod root_signature_tests { // presentation tracking // --------------------------------------------------------------------------------------- +fn default_srgb_rtv(rd: &D3D12_RESOURCE_DESC, format: u32) -> D3D12_RENDER_TARGET_VIEW_DESC { + let slices = u32::from(rd.DepthOrArraySize); + let mut v = D3D12_RENDER_TARGET_VIEW_DESC { Format: DXGI_FORMAT(format as i32), ..Default::default() }; + match (rd.Dimension, slices > 1) { + (D3D12_RESOURCE_DIMENSION_TEXTURE1D, false) => v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1D, + (D3D12_RESOURCE_DIMENSION_TEXTURE1D, true) => { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1DARRAY; + v.Anonymous.Texture1DArray.ArraySize = slices; + } + (D3D12_RESOURCE_DIMENSION_TEXTURE3D, _) => { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D; + v.Anonymous.Texture3D.WSize = slices; + } + (_, false) => v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D, + (_, true) => { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; + v.Anonymous.Texture2DArray.ArraySize = slices; + } + } + v +} + +fn pc_rtv(rd: Option<&D3D12_RESOURCE_DESC>, srgb: Option, v: Option) -> Option { + if let Some(mut v) = v { + let rf = rd.map_or(0, |d| d.Format.0 as u32); + v.Format = DXGI_FORMAT(srgb_or_explicit(srgb, rf, v.Format.0 as u32).unwrap_or_else(|| super::device_x::pc_shader_view_format(rf, v.Format.0 as u32)) as i32); + Some(v) + } else { + rd.zip(srgb).map(|(d, f)| default_srgb_rtv(d, f)) + } +} + unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, desc: *const c_void, handle: usize) { let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailViewDescriptor); let _t = crate::hle::api_cost::time_if( @@ -11339,11 +11481,10 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de type F = unsafe extern "system" fn(*mut c_void, *mut c_void, *const c_void, usize); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateRenderTargetView"))); // a view in a console-only format, or of a target made R8G8B8A8 (`device_x::pc_resource_desc`) - let mut copy = (!desc.is_null()).then(|| (desc as *const D3D12_RENDER_TARGET_VIEW_DESC).read_unaligned()); - if let Some(c) = copy.as_mut() { - let rf = ID3D12Resource::from_raw_borrowed(&res).map_or(0, |r| r.GetDesc().Format.0 as u32); - c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32) as i32); - } + let rd = if !desc.is_null() || (srgb_textures_live() && SRGB_TEXTURES.contains(res as usize)) { desc_of(res) } else { None }; + let srgb = rd.as_ref().and_then(|d| srgb_view_format(res as usize, d.Format.0 as u32)); + let v = (!desc.is_null()).then(|| (desc as *const D3D12_RENDER_TARGET_VIEW_DESC).read_unaligned()); + let copy = pc_rtv(rd.as_ref(), srgb, v); let desc = copy.as_ref().map_or(desc, |c| c as *const _ as *const c_void); f(this, res, desc, handle); super::present::note_rtv(handle, res); @@ -13381,6 +13522,68 @@ mod srv_tests { use super::*; use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_BC1_UNORM_SRGB; + #[test] + fn srgb_typeless_views_keep_the_titles_explicit_formats() { + // R8G8B8A8_UNORM_SRGB (29) made R8G8B8A8_TYPELESS (27); B8G8R8A8_UNORM_SRGB (91) -> 90 + for (srgb, family, linear) in [(29u32, 27u32, 28u32), (91, 90, 87)] { + // SRV / RTV: no format or the typeless family -> the sRGB one; explicit stays + assert_eq!(srgb_or_explicit(Some(srgb), family, 0), Some(srgb)); + assert_eq!(srgb_or_explicit(Some(srgb), family, family), Some(srgb)); + assert_eq!(srgb_or_explicit(Some(srgb), family, srgb), Some(srgb)); + assert_eq!(srgb_or_explicit(Some(srgb), family, linear), Some(linear), "UNORM read of the raw bytes"); + // UAV: no format, the family or the sRGB one -> the linear sibling; explicit stays + assert_eq!(pc_uav_format(family, Some(srgb), 0), linear); + assert_eq!(pc_uav_format(family, Some(srgb), family), linear); + assert_eq!(pc_uav_format(family, Some(srgb), srgb), linear); + assert_eq!(pc_uav_format(family, Some(srgb), linear), linear); + } + assert_eq!(pc_uav_format(27, Some(29), 30), 30, "R8G8B8A8_UINT UAV"); + assert_eq!(pc_uav_format(27, Some(29), 32), 32, "R8G8B8A8_SINT UAV"); + assert_eq!(srgb_or_explicit(Some(29), 27, 30), Some(30), "R8G8B8A8_UINT SRV"); + assert_eq!(srgb_or_explicit(None, 28, 0), None, "not a typeless sRGB texture"); + } + + #[test] + fn srgb_typeless_views_use_typed_defaults_and_keep_explicit_ranges() { + for (srgb, family, linear) in [(29, 27, 28), (91, 90, 87), (93, 92, 88)] { + let rd = D3D12_RESOURCE_DESC { + Format: DXGI_FORMAT(family), + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + DepthOrArraySize: 4, + MipLevels: 3, + ..Default::default() + }; + let title = Some(srgb as u32); + let mut srv = pc_srv(&rd, title, None).unwrap(); + let mut rtv = pc_rtv(Some(&rd), title, None).unwrap(); + let fmt = pc_uav_format(family as u32, title, 0); + let uav = default_uav_desc(&rd, fmt); + assert_eq!((srv.Format.0, rtv.Format.0, uav.Format.0), (srgb, srgb, linear)); + assert_eq!(pc_uav_format(family as u32, title, srgb as u32), fmt); + assert_eq!(pc_uav_format(family as u32, title, linear as u32), fmt); + assert_eq!(srv.ViewDimension, D3D12_SRV_DIMENSION_TEXTURE2DARRAY); + assert_eq!(rtv.ViewDimension, D3D12_RTV_DIMENSION_TEXTURE2DARRAY); + assert_eq!(uav.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE2DARRAY); + unsafe { + assert_eq!(srv.Anonymous.Texture2DArray.MipLevels, u32::MAX); + assert_eq!(srv.Anonymous.Texture2DArray.ArraySize, 4); + assert_eq!(rtv.Anonymous.Texture2DArray.ArraySize, 4); + assert_eq!(uav.Anonymous.Texture2DArray.ArraySize, 4); + } + srv.Format = DXGI_FORMAT(0); + rtv.Format = DXGI_FORMAT(0); + srv.Anonymous.Texture2DArray.MostDetailedMip = 1; + rtv.Anonymous.Texture2DArray.FirstArraySlice = 2; + let srv = pc_srv(&rd, title, Some(&srv)).unwrap(); + let rtv = pc_rtv(Some(&rd), title, Some(rtv)).unwrap(); + assert_eq!((srv.Format.0, rtv.Format.0), (srgb, srgb)); + assert_eq!(unsafe { (srv.Anonymous.Texture2DArray.MostDetailedMip, rtv.Anonymous.Texture2DArray.FirstArraySlice) }, (1, 2)); + assert!(pc_srv(&rd, None, None).is_none()); + assert!(pc_rtv(Some(&rd), None, None).is_none()); + } + } + #[test] fn a_cube_view_becomes_the_cube_array_of_one_cube() { let cube = D3D12_SHADER_RESOURCE_VIEW_DESC { @@ -13425,7 +13628,7 @@ mod srv_tests { SampleDesc: DXGI_SAMPLE_DESC { Count: samples, Quality: 0 }, ..Default::default() }; - let v = pc_srv(&desc, None).expect("a typeless depth buffer gets a view of its own"); + let v = pc_srv(&desc, None, None).expect("a typeless depth buffer gets a view of its own"); assert_eq!(v.Format, DXGI_FORMAT_R24_UNORM_X8_TYPELESS); assert_eq!(v.ViewDimension, dimension, "{samples} samples, {slices} slices"); let a = &v.Anonymous; @@ -13475,6 +13678,81 @@ mod console_format_query_tests { dev } + #[test] + fn gpu_srgb_typeless_uav_clear_and_copy_to_srgb() { + use super::super::device_x as x; + if !x::srgb_typeless_enabled() { + return crate::gpu::recomp::runner::skip_test("XCL_SRGB_TYPELESS=0"); + } + let Some(dev) = device().or_else(|| unsafe { + let warp = CreateDXGIFactory1::().ok()?.EnumWarpAdapter::().ok()?; + let mut dev: Option = None; + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).ok()?; + dev + }) else { return crate::gpu::recomp::runner::skip_test("no GPU or WARP") }; + + unsafe { + if !x::pc_typed_uav_supported(dev.as_raw(), 28) { + return crate::gpu::recomp::runner::skip_test("no R8G8B8A8_UNORM typed UAVs"); + } + let mut src_desc = super::super::title_textures::tests::console_desc(3, 32, 32, 1, 1, 29, 0x105); + src_desc[0x30] = 5; + let d = x::pc_resource_desc_for_device(dev.as_raw(), &src_desc); + let rd: D3D12_RESOURCE_DESC = std::ptr::read_unaligned(d.as_ptr().cast()); + assert_eq!((rd.Format.0, rd.Flags.0 & 4), (27, 4)); + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let clear = D3D12_CLEAR_VALUE { Format: DXGI_FORMAT(29), Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0; 4] } }; + let mut src: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, Some(&clear), &mut src).unwrap(); + let src = src.unwrap(); + adopt(dev.as_raw(), Kind::Device); + adopt(src.as_raw(), Kind::Resource); + note_srgb_texture(src.as_raw(), &src_desc); + assert_eq!(console_format_of(src.as_raw() as usize, 27), 29); + let make_heap = |Type, Flags| -> ID3D12DescriptorHeap { + dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type, Flags, NumDescriptors: 1, NodeMask: 0 }).unwrap() + }; + let visible = make_heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE); + let cpu = make_heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE); + let rtv = make_heap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE); + let handle = cpu.GetCPUDescriptorHandleForHeapStart(); + dev_create_srv_inner(dev.as_raw(), src.as_raw(), std::ptr::null(), handle.ptr as u64); + dev_create_rtv(dev.as_raw(), src.as_raw(), std::ptr::null(), rtv.GetCPUDescriptorHandleForHeapStart().ptr); + for h in [handle, visible.GetCPUDescriptorHandleForHeapStart()] { + dev_create_uav_checked_inner(dev.as_raw(), src.as_raw(), std::ptr::null_mut(), std::ptr::null(), h.ptr as u64); + } + + let dst_desc = D3D12_RESOURCE_DESC { Format: DXGI_FORMAT(29), Flags: D3D12_RESOURCE_FLAG_NONE, ..rd }; + let mut dst: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &dst_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut dst).unwrap(); + let dst = dst.unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.SetDescriptorHeaps(&[Some(visible.clone())]); + let values = [128.0 / 255.0, 64.0 / 255.0, 0.0, 1.0]; + list.ClearUnorderedAccessViewFloat(visible.GetGPUDescriptorHandleForHeapStart(), handle, &src, &values, &[]); + let transition = |r: &ID3D12Resource, state| { + super::super::list_x::transition(list.as_raw(), r.as_raw() as usize, state, D3D12_RESOURCE_STATE_COPY_SOURCE); + }; + transition(&src, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.CopyResource(&dst, &src); + transition(&dst, D3D12_RESOURCE_STATE_COPY_DEST); + let (readback, footprint) = super::super::present::readback_copy(&list, &dst, &dst_desc).unwrap(); + list.Close().unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 10_000).unwrap(); + dev.GetDeviceRemovedReason().unwrap(); + let mut mapped = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let texel = (mapped as *const u8).add(footprint.Offset as usize).cast::<[u8; 4]>().read_unaligned(); + readback.Unmap(0, None); + assert_eq!(texel, [128, 64, 0, 255]); + } + } + /// CheckFeatureSupport of the PC device as `dev_check_feature_support` reaches it (vtable #13). fn pc_check(dev: &ID3D12Device) -> CheckFeatureSupportFn { unsafe { std::mem::transmute(*(*(dev.as_raw() as *const *const usize)).add(13)) } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d809b1c2a2..b1adcdd009 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -625,7 +625,9 @@ fn gpu_owned_layout(desc: &[u8; 0x38], pc: &D3D12_RESOURCE_DESC) -> Result