From 710a5f4fe38763a8f901e70eeff212c32544e3d1 Mon Sep 17 00:00:00 2001 From: Eterst Date: Sat, 28 Nov 2026 12:54:58 -0600 Subject: [PATCH] Shaders: apply the console's pixel shader export patches A pixel shader's render-target exports are stored for one export format, the compiler's default FP16 (v_cvt_pkrtz_f16_f32 and a compressed exp). The console patches them at pipeline creation for each target's SPI_SHADER_COL_FORMAT from a table in the PS stage data: per render target, the code offset and ten variants of the export code. XCL never applied it, so a target of 32 bits a channel got the FP16 conversion of its value: a packed R32_UINT lighting target of a retail title held f16(asfloat(bits)), 0x7BFF where the packed value was large, instead of its bits. On screen: a blue-white glow on skin and lit surfaces. Every target is patched to the 32_ABGR variant: the channels leave the shader unconverted and the PC target converts them, which is right for every PC format. A table that is implausible (no PS record, a size of 0 or over ten dwords, a patch past the code, an empty variant) changes nothing. XCL_PS_EXPORT_PATCH=0 keeps the stored exports. The table layout (record at payload + 0x30, stage data at record + 0x54, size at + 0x148, eight entries from + 0x14C) is as VIctory documents it in victory-shader/src/native.rs (GPL-3.0); the code is written independently. THIRD_PARTY.md says so. A pixel shader's entry in the translated-shader cache names its export mode (translated::exports_mode): neither the shader's bytes nor the translator's identity record XCL_PS_EXPORT_PATCH, so a warm cache handed one mode's translation to the other. Older unlabelled pixel entries are not read. Found and fixed by andrewDoing in review. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 + THIRD_PARTY.md | 2 +- crates/xcl/src/gpu/recomp/pso.rs | 22 ++++- crates/xcl/src/gpu/xbox.rs | 138 +++++++++++++++++++++++++++++++ 4 files changed, 164 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3f76544f6a..278ada5394 100644 --- a/README.md +++ b/README.md @@ -400,6 +400,10 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. 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`). +- Pixel shaders get the render-target export patches the console applies at pipeline creation: + every target exports 32 bits a channel, and the PC target converts. Without them a 32-bit target + (a packed `R32_UINT` lighting target) got the FP16 conversion of its values. `XCL_PS_EXPORT_PATCH=0` + keeps the exports as stored. - `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 diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index db38e8a443..3fca7822e1 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 layout of the pixel-shader export patch table in an FSSM's stage data (`patch_ps_exports` in `crates/xcl/src/gpu/xbox.rs`), after its `victory-shader/src/native.rs` | port to Rust; tables; table layout (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/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 69a926ee0b..e648343c16 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -398,10 +398,23 @@ mod translated { pub(super) fn file_for(dir: &Path, ident: u64, blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split: bool, rt32_mask: u8) -> PathBuf { let suffix = if rt32_mask != 0 { format!("_rt32_{rt32_mask:02x}") } else { String::new() }; + let exports = exports_mode(stage, crate::gpu::xbox::ps_exports_patched()); dir.join("translated") .join("v2") .join(format!("{ident:016x}")) - .join(format!("{:016x}_{stage:?}_{sampler_base}_{windows}_{}{suffix}.bin", crate::gpu::shader::fnv64(blob), split as u8)) + .join(format!("{:016x}_{stage:?}_{sampler_base}_{windows}_{}{exports}{suffix}.bin", crate::gpu::shader::fnv64(blob), split as u8)) + } + + /// A pixel shader's translation depends on `XCL_PS_EXPORT_PATCH` (`xbox::ps_exports_patched`), + /// which neither its bytes nor the translator's identity record: its entry names the mode, so + /// a warm cache does not hand one mode's translation to the other. Older pixel entries do not + /// say which mode made them and are not read. (From andrewDoing's review of #3209.) + pub(super) fn exports_mode(stage: Stage, patched: bool) -> &'static str { + match stage { + Stage::Pixel if patched => "_exports_patched", + Stage::Pixel => "_exports_stored", + _ => "", + } } fn header(ident: u64, blob: &[u8]) -> Vec { @@ -2022,6 +2035,13 @@ mod shader_cache_tests { ]; assert_eq!(paths.iter().collect::>().len(), paths.len()); assert!(base.starts_with(dir.join("translated").join("v2").join("000000000000002a"))); + // a pixel shader's entry names its export mode (`XCL_PS_EXPORT_PATCH`); other stages' do not + assert_ne!(translated::exports_mode(Stage::Pixel, true), translated::exports_mode(Stage::Pixel, false)); + assert_eq!(translated::exports_mode(Stage::Vertex, true), ""); + assert_eq!(translated::exports_mode(Stage::Compute, false), ""); + let pixel = translated::file(&dir, 42, b"console", Stage::Pixel, 3, 2, false); + let mode = translated::exports_mode(Stage::Pixel, crate::gpu::xbox::ps_exports_patched()); + assert!(pixel.to_string_lossy().ends_with(&format!("{mode}.bin")), "{}", pixel.display()); } /// A translation on disk comes back for the same bytes and semantic identity only: other diff --git a/crates/xcl/src/gpu/xbox.rs b/crates/xcl/src/gpu/xbox.rs index 91afa7f952..21e49d48b7 100644 --- a/crates/xcl/src/gpu/xbox.rs +++ b/crates/xcl/src/gpu/xbox.rs @@ -336,6 +336,11 @@ fn analyze_fssm(f: &mut Fssm) { if f.code.is_none() { f.code = scan_code_region(d); } + if f.code_from_header && f.version == 0x101 && ps_exports_patched() { + if let Some((o, l)) = f.code { + patch_ps_exports(&mut f.data, o, l); + } + } if let Some((o, l)) = f.code { let code = &f.data[o..o + l]; // Segments end at s_endpgm. One that is linked to the previous program by a @@ -379,6 +384,64 @@ fn analyze_fssm(f: &mut Fssm) { } } +/// `XCL_PS_EXPORT_PATCH=0` leaves pixel shaders' render-target exports as the compiler stored them. +/// (Part of a pixel shader's translation cache entry: `recomp::pso::translated::file`.) +pub(crate) fn ps_exports_patched() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_PS_EXPORT_PATCH").is_ok_and(|v| v.trim() == "0")) +} + +/// Size of one render target's entry in a pixel shader's export patch table: its code offset +/// (dwords, `u32::MAX`: no export), then ten variants of ten dwords. +const EXPORT_PATCH_BYTES: usize = 4 + 10 * 10 * 4; +/// The variant that exports every channel as a raw 32-bit value (SPI_SHADER_32_ABGR). +const EXPORT_PATCH_32_ABGR: usize = 9; + +/// A pixel shader's render-target exports are stored for one export format (the compiler's +/// default, FP16: `v_cvt_pkrtz_f16_f32` and a compressed `exp`). The console patches them at +/// pipeline creation for each target's format from a table in the PS stage data: per render +/// target, the code offset and the export code for each of the ten SPI_SHADER_COL_FORMAT +/// values (ZERO, 32_R, 32_GR, 32_AR, FP16_ABGR, UNORM16, SNORM16, UINT16, SINT16, 32_ABGR). +/// Left unpatched, a target of 32 bits a channel gets the FP16 conversion of its value: a +/// packed R32_UINT lighting target held `f16(asfloat(bits))` (0x7BFF where the packed value +/// was large) instead of its bits. Every target is patched to 32_ABGR: the channels leave the +/// shader unconverted and the PC target converts them, which is right for every PC format. +/// Layout (payload = FSSM + 0x10): payload + 0x30 the PS record offset (0xDEADBEEF… when the +/// FSSM has no PS); stage data E = record + 0x54; E + 0x148 the patch size in dwords; E + 0x14C +/// eight entries of `EXPORT_PATCH_BYTES`. Layout as documented by VIctory +/// (https://github.com/Marvisak/VIctory, crates/victory-shader/src/native.rs, GPL-3.0; the same +/// in its VIctory-NVIDIA fork), checked against a retail pack's pixel shaders; the code here is +/// written independently. Returns the number of exports patched. +fn patch_ps_exports(d: &mut [u8], code_at: usize, code_len: usize) -> usize { + let Some(record) = rd64(d, 0x10 + 0x30) else { return 0 }; + if record == 0xDEAD_BEEF_DEAD_BEEF { + return 0; + } + let Some(e) = usize::try_from(record).ok().and_then(|r| r.checked_add(0x10 + 0x54)) else { return 0 }; + let Some(size) = rd32(d, e + 0x148).map(|n| n as usize) else { return 0 }; + if size == 0 || size > 10 { + return 0; + } + let mut patched = 0; + for mrt in 0..8 { + let at = e + 0x14C + mrt * EXPORT_PATCH_BYTES; + let Some(offset) = rd32(d, at) else { break }; + if offset == u32::MAX || (offset as usize + size) * 4 > code_len { + continue; + } + let src = at + 4 + EXPORT_PATCH_32_ABGR * 40; + let Some(words) = d.get(src..src + size * 4).map(<[u8]>::to_vec) else { continue }; + // a variant that is all zeros was not filled in: keep the code as it is + if words.iter().all(|&b| b == 0) { + continue; + } + let dst = code_at + offset as usize * 4; + d[dst..dst + size * 4].copy_from_slice(&words); + patched += 1; + } + patched +} + /// Static branch targets of a code segment (PCs in the same space as `pc`), far jumps included. fn branch_targets(seg: &[u8], pc: u64) -> Vec { let mut insts = Vec::new(); @@ -1127,3 +1190,78 @@ mod merged_es_tests { assert!(is_setpc(0xBE80_2020) && !is_setpc(S_ENDPGM)); } } + +#[cfg(test)] +mod ps_export_patch_tests { + use super::*; + + /// An FSSM-shaped buffer: the PS record at payload 0xB0 (data 0xC0), its patch table with + /// MRT 0 at code dword 1 and MRT 1 absent, 3 dwords a variant; code at data 0x1000. + fn fssm_with_patch(size: u32, abgr: [u32; 3]) -> (Vec, usize) { + let mut d = vec![0u8; 0x1100]; + let put = |d: &mut Vec, at: usize, w: u32| d[at..at + 4].copy_from_slice(&w.to_le_bytes()); + d[0x40..0x48].copy_from_slice(&0xB0u64.to_le_bytes()); + let e = 0xC0 + 0x54; + put(&mut d, e + 0x148, size); + let mrt0 = e + 0x14C; + put(&mut d, mrt0, 1); + // variant 4 (FP16, what the code holds) and variant 9 (32_ABGR) + for (k, w) in [0x5E04_170Eu32, 0xBF80_0000, 0xF800_040F].iter().enumerate() { + put(&mut d, mrt0 + 4 + 4 * 40 + 4 * k, *w); + } + for (k, w) in abgr.iter().enumerate() { + put(&mut d, mrt0 + 4 + 9 * 40 + 4 * k, *w); + } + put(&mut d, mrt0 + EXPORT_PATCH_BYTES, u32::MAX); + for m in 2..8 { + put(&mut d, mrt0 + m * EXPORT_PATCH_BYTES, u32::MAX); + } + // code: s_nop, then the FP16 export sequence, then s_endpgm + for (k, w) in [0xBF80_0000u32, 0x5E04_170E, 0xBF80_0000, 0xF800_040F, S_ENDPGM].iter().enumerate() { + put(&mut d, 0x1000 + 4 * k, *w); + } + (d, 0x1000) + } + + fn word(d: &[u8], at: usize) -> u32 { + rd32(d, at).unwrap() + } + + #[test] + fn each_target_gets_the_32_abgr_export() { + let abgr = [0xBF80_0000, 0xF800_000F, 0x0910_0B0E]; + let (mut d, code) = fssm_with_patch(3, abgr); + assert_eq!(patch_ps_exports(&mut d, code, 0x14), 1); + assert_eq!([word(&d, code + 4), word(&d, code + 8), word(&d, code + 12)], abgr); + // the dwords around the patch are left alone + assert_eq!((word(&d, code), word(&d, code + 16)), (0xBF80_0000, S_ENDPGM)); + } + + #[test] + fn implausible_tables_change_nothing() { + let abgr = [0xBF80_0000, 0xF800_000F, 0x0910_0B0E]; + // no PS record + let (mut d, code) = fssm_with_patch(3, abgr); + d[0x40..0x48].copy_from_slice(&0xDEAD_BEEF_DEAD_BEEFu64.to_le_bytes()); + let before = d.clone(); + assert_eq!(patch_ps_exports(&mut d, code, 0x14), 0); + assert_eq!(d, before); + // a patch size over ten dwords, or zero + for size in [0, 11] { + let (mut d, code) = fssm_with_patch(size, abgr); + let before = d.clone(); + assert_eq!(patch_ps_exports(&mut d, code, 0x14), 0); + assert_eq!(d, before); + } + // a patch running past the end of the code + let (mut d, code) = fssm_with_patch(3, abgr); + let before = d.clone(); + assert_eq!(patch_ps_exports(&mut d, code, 0x0C), 0); + assert_eq!(d, before); + // a 32_ABGR variant left empty + let (mut d, code) = fssm_with_patch(3, [0; 3]); + let before = d.clone(); + assert_eq!(patch_ps_exports(&mut d, code, 0x14), 0); + assert_eq!(d, before); + } +}