XG metadata planes; the console shader compiler as a recompiler test generator

XG: render targets get a CMASK plane, depth buffers HTILE + depth + stencil,
depth-stencil formats two planes, as the console library lays them out
(checked on 1 872 render target / depth descs).

tests/console_shaders.rs (XCL_SAMPLE_DXC = the console's dxcompiler_xs.dll):
HLSL kernels compiled by the console compiler, run through XCL's translation
on the PC GPU next to the PC compile of the same source - the same memory.
It found two bugs, fixed:
- root arguments: the console passes them in user SGPRs s4..s15 while they
  fit, only the rest in the table at s[0:1] (console list dispatches);
- the high 32x32 multiply as a 64-bit product made DXC emit
  umul.with.overflow (invalid DXIL); now from 16-bit parts.
This commit is contained in:
ivall
2026-11-21 22:20:01 +01:00
parent fd746622e9
commit 18cb400400
8 changed files with 888 additions and 73 deletions
+31 -1
View File
@@ -363,6 +363,28 @@ amd_fidelityfx_loader_xbox / amd_fidelityfx_upscaler_xbox, XboxBvhBuilder. The g
Descriptor tables – not seen yet (the builder does not use them). Group ids after the user SGPRs (s4 = TGID.x with 4 user SGPRs).
- For XCL: on a dispatch with a translated PSO – assemble this array in UMA from the remembered root arguments, s0/s1 = its address
in `io`, the rest as in Compute mode.
- **Corrected with the console's own compiler** (`tests/console_shaders.rs`, `print_root_argument_placement`): s0…s3 are
the driver's; the parameters go into user SGPRs **s4…s15 in order while each fits whole** (descriptor 2, constant 1 each,
descriptor table 1 = 32-bit address of its first descriptor, high half 0); from the first one that does not fit, it and
all after it go to the table at s[0:1], packed from offset 0 (19 / 20 constants first → everything in the table, as
in the builder). E.g. 11 constants + UAV: constants s4…s14, UAV at table +0; UAV + 11 constants: UAV s[4:5],
constants at table +0. Group ids follow the user SGPRs. `console_list::Layout::inline` / `user_data` do this for
console-list dispatches.
### Console shader compiler as a test generator (`tests/console_shaders.rs`, `XCL_SAMPLE_DXC`)
- The console's `dxcompiler_xs.dll` loads on the PC with plain LoadLibrary (only API-set imports); its back end
`xbsc_xs.dll` (and `newbe_xs.dll`) is loaded by name at Compile, so the test loads them first from the same directory.
Its output is a full console container (DXIL + XDAT → XBCH → FSSM with the RDNA2 code, RTS0). Nothing of it goes into
the repo; the test runs only with `XCL_SAMPLE_DXC` set.
- `console_compiled_kernels_match_the_pc_compile`: HLSL kernels (integers, conversions, float math, per-lane loops and
branches, groupshared + barriers, atomics, 64-bit integers) through the console compiler → XCL's translation → PC GPU,
next to the PC compile of the same source: the same memory. Found and fixed: the root argument placement above, and
`v_mul_hi_u32` / `s_mul_hi_u32` as `(uint64)a * b >> 32` – DXC turns it (compared with 0 in the console's division
code) into umul.with.overflow and DXIL validation fails; now from 16-bit parts (`mul_hi_u32` in the prelude).
- The console compiler multiplies by constants with `v_mul_legacy_f32` where the HLSL allows it (DXIL fast math, no
signed zeros): -0 × c = +0 on the console, -0 on the PC – the conversions kernel compares up to the sign of zero.
- Not yet: three kernels (local arrays indexed per lane, switch in nested loops, 16-bit types) made the run hang –
removed from the list until it is known which step (console compile, translation, DXC or the GPU) hangs.
### D3D12.X: the command list is partly "compiled into" the title's code (probe `XCL_PROBE_BVH_RECORD=1`)
- Recording `BuildRaytracingAccelerationStructure` on a list from the XCL device: the builder calls **console list method #148**
@@ -643,7 +665,15 @@ The EXE (+ EOSSDK) imports 31 functions from console libraries: MFPlat `MFResetD
of 0x8000 / 0x8000 for the 64KB Z/S/D/R_X modes); it follows the reported device type.
- Modes the library takes for 2D: 1 2 5 6 9 10 17 18 21 22 25 26 27, 24 (and VAR 28) for ≤ 8-byte non-BC elements,
VAR 31; `Layout` 0 / 2 = its choice (64KB_D for 2, 4KB_S, UAVs 4KB_S_X up to 64 KB else 64KB_R_X). Not modelled
(E_NOTIMPL): render targets / depth (CMASK / HTILE planes), planar depth-stencil formats, MSAA, 1D / 3D, VAR modes.
(E_NOTIMPL): MSAA, 1D / 3D, VAR modes.
- **Planes** (`xg::Texture::planes`, checked by `render_target_and_depth_layouts_match`, 1 872 descs): usage 1 color,
2 CMASK, 4 HTILE, 5 / 6 depth / stencil of a depth-stencil format, 7 / 8 the same in a depth buffer. A render target
of one level gets a CMASK after its texels (align 0x2000, size = pixels padded to 1024 × 1024 / 128 per slice; not
for layout 2 or the _T modes); a depth buffer (DS flag, one level) is HTILE first (align 64 KB, same padding / 16),
then depth, then stencil (1-byte elements), all in mode 24; RT + DS of a color or D32 format is a render target in
mode 24 (CMASK, no HTILE). Left empty (size 0, offset 0): the texels of a one-level BCn RT / DS and the depth of a
DS in a color format – with DS the whole resource then reports size 0. D32_S8X24 picks its optimal mode by 64 bits a
pixel. Title textures that have metadata planes are not mirrored (`title_textures`: GPU-owned).
- **Textures in title memory** (`d3d12x/title_textures.rs`): CreatePlacedResourceX of a texture gets a PC texture kept in
step with the title's memory – every mip and slice detiled with the XG layout (`hle::xg`) and uploaded at creation;
unified memory is reserved with MEM_WRITE_WATCH (OpenExistingHeapFromAddress takes it), and before each
+11 -2
View File
@@ -823,7 +823,7 @@ impl Em {
"s_add_i32" => (format!("{a} + {b}"), Some(format!("((({a} ^ {t}) & ({b} ^ {t})) >> 31) != 0u"))),
"s_sub_i32" => (format!("{a} - {b}"), Some(format!("((({a} ^ {b}) & ({a} ^ {t})) >> 31) != 0u"))),
"s_mul_i32" => (format!("(uint)((int){a} * (int){b})"), None),
"s_mul_hi_u32" => (format!("(uint)(((uint64_t){a} * (uint64_t){b}) >> 32)"), None),
"s_mul_hi_u32" => (format!("mul_hi_u32({a}, {b})"), None),
"s_mul_hi_i32" => (format!("(uint)(((int64_t)(int){a} * (int64_t)(int){b}) >> 32)"), None),
"s_lshl_b32" => (format!("{a} << ({b} & 31u)"), Some(format!("{t} != 0u"))),
"s_lshr_b32" => (format!("{a} >> ({b} & 31u)"), Some(format!("{t} != 0u"))),
@@ -2687,7 +2687,7 @@ impl Em {
"v_sub_nc_u32" => format!("{a} - {b}"),
"v_subrev_nc_u32" => format!("{b} - {a}"),
"v_mul_lo_u32" => format!("{a} * {b}"),
"v_mul_hi_u32" => format!("(uint)(((uint64_t){a} * (uint64_t){b}) >> 32)"),
"v_mul_hi_u32" => format!("mul_hi_u32({a}, {b})"),
"v_mul_hi_i32" => format!("(uint)(((int64_t)(int){a} * (int64_t)(int){b}) >> 32)"),
"v_mul_u32_u24" => format!("({a} & 0xFFFFFFu) * ({b} & 0xFFFFFFu)"),
"v_mul_hi_u32_u24" => format!("(uint)(((uint64_t)({a} & 0xFFFFFFu) * (uint64_t)({b} & 0xFFFFFFu)) >> 32)"),
@@ -4359,6 +4359,15 @@ uint dst_sel(uint4 c, uint sel, bool isint) { return select(sel == 0u, 0u, selec
const PRELUDE: &str = r#"
static uint lane_id;
// the high half of a 32 x 32-bit product, from 16-bit parts: DXC turns
// `(uint)(((uint64_t)a * b) >> 32) != 0` (the console's integer division code) into
// umul.with.overflow, which DXIL does not allow (validation fails)
uint mul_hi_u32(uint a, uint b) {
uint al = a & 0xFFFFu, ah = a >> 16, bl = b & 0xFFFFu, bh = b >> 16;
uint lh = al * bh, hl = ah * bl;
uint mid = ((al * bl) >> 16) + (lh & 0xFFFFu) + (hl & 0xFFFFu);
return ah * bh + (lh >> 16) + (hl >> 16) + (mid >> 16);
}
// wave32 program in a 64-lane hardware wave: each half is its own wave (xcl_half = 0 / 1)
static bool xcl_w32 = false;
static uint xcl_half = 0u;
+72 -7
View File
@@ -5,8 +5,9 @@
//! bounds, +0x344 + 4·i root parameter headers (filled by SetComputeRootSignature), and it
//! copies 28 bytes from +0x10 of the pipeline state object into the stream. So the title gets
//! XCL objects with that layout; the records are turned into PC commands at `close`:
//! each Dispatch gets the root arguments packed into a table in unified memory (user SGPRs
//! s[0:1] point at it, as on the console) and runs the translated pipeline on XCL's shader ABI.
//! each Dispatch gets the root arguments as the console passes them (`user_data`: the ones
//! that fit in user SGPRs s4…s15, the rest in a table in unified memory that s[0:1] points at)
//! and runs the translated pipeline on XCL's shader ABI.
//!
//! Compute only, and opt-in (`XCL_CONSOLE_LISTS=1`) until the graphics records are known.
@@ -64,12 +65,18 @@ pub enum Param {
Table { at: u32 },
}
/// Where a root signature's arguments go: all of them packed in order (`at`, `size` bytes);
/// the first `inline` bytes of that are passed in user SGPRs from s4, the rest is the table.
#[derive(Debug, Default)]
pub struct Layout {
pub params: Vec<Param>,
pub size: u32,
pub inline: u32,
}
/// User SGPRs the console's compiler gives root arguments: s4…s15 (s0…s3 are the driver's).
const INLINE_SGPRS: u32 = 12;
/// Layout from a serialized root signature: a DXBC container with RTS0 or a bare RTS0.
pub fn layout_from_blob(blob: &[u8]) -> Option<Layout> {
let rts0 = match crate::gpu::shader::container_parts(blob) {
@@ -82,6 +89,10 @@ pub fn layout_from_blob(blob: &[u8]) -> Option<Layout> {
let r = |o: usize| rts0.get(o..o + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap()));
let (n, poff) = (r(4)? as usize, r(8)? as usize);
let mut l = Layout::default();
// the parameters go into user SGPRs in order while each fits whole; from the first one
// that does not, the rest go to the table (packed from its start) – as the console's
// compiler expects them (HANDOFF: root argument binding)
let mut spilled = false;
for k in 0..n {
let (ty, pay) = (r(poff + 12 * k)?, r(poff + 12 * k + 8)? as usize);
let p = match ty {
@@ -89,16 +100,34 @@ pub fn layout_from_blob(blob: &[u8]) -> Option<Layout> {
2..=4 => Param::Descriptor { at: l.size },
_ => Param::Table { at: l.size },
};
l.size += match p {
let bytes = match p {
Param::Constants { count, .. } => 4 * count,
Param::Table { .. } => 4,
Param::Descriptor { .. } => 8,
};
spilled |= l.inline + bytes > 4 * INLINE_SGPRS;
if !spilled {
l.inline += bytes;
}
l.size += bytes;
l.params.push(p);
}
Some(l)
}
/// The user SGPRs of a dispatch: s[0:1] = `table_at` (where the bytes of `args` past the
/// inline part are), from s4 the inline part of `args` (all arguments packed by `l`).
pub fn user_data(l: &Layout, args: &[u8], table_at: u64) -> Vec<u32> {
let mut s = vec![table_at as u32, (table_at >> 32) as u32, 0, 0];
let inline = &args[..(l.inline as usize).min(args.len())];
s.extend(inline.chunks(4).map(|c| {
let mut w = [0u8; 4];
w[..c.len()].copy_from_slice(c);
u32::from_le_bytes(w)
}));
s
}
static LAYOUTS: Mutex<Option<HashMap<usize, Arc<Layout>>>> = Mutex::new(None);
/// A root signature was created from `blob`: remember its argument layout.
@@ -680,10 +709,13 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> {
at += 4;
match pso {
Some(p) if (*p).translated => {
let table_at = uma_copy(st, &table).ok_or("UMA: argument table")?;
let mut io = vec![0u32; crate::gpu::recomp::KERNEL_SGPRS];
io[0] = table_at as u32;
io[1] = (table_at >> 32) as u32;
let inline = layout.as_ref().map_or(0, |l| l.inline as usize).min(table.len());
let table_at = uma_copy(st, &table[inline..]).ok_or("UMA: argument table")?;
let mut io = match layout.as_ref() {
Some(l) => user_data(l, &table, table_at as u64),
None => vec![table_at as u32, (table_at >> 32) as u32],
};
io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0);
let io_at = uma_copy(st, bytemuck_u32(&io)).ok_or("UMA: io")?;
let res_at = uma_copy(st, &[0u8; 256]).ok_or("UMA: res")?;
// a pipeline still being built in the background is waited for
@@ -785,5 +817,38 @@ mod tests {
let l = layout_from_blob(&bytes).unwrap();
assert_eq!(l.params, vec![Param::Constants { at: 0, count: 19 }, Param::Descriptor { at: 76 }, Param::Descriptor { at: 84 }, Param::Descriptor { at: 92 }]);
assert_eq!(l.size, 100);
assert_eq!(l.inline, 0, "19 constants do not fit in user SGPRs: everything in the table");
}
/// RTS0 v2 of parameters (type: 0 table, 1 constants, 2–4 CBV / SRV / UAV; constant count)
fn rts0(params: &[(u32, u32)]) -> Vec<u8> {
let n = params.len() as u32;
let mut r = vec![2u32, n, 24, 0, 0, 0];
let pay = 24 + 12 * n;
for (k, &(ty, _)) in params.iter().enumerate() {
r.extend([ty, 0, pay + 12 * k as u32]);
}
for &(_, count) in params {
r.extend([0, 0, count]);
}
r.iter().flat_map(|w| w.to_le_bytes()).collect()
}
/// What the console's compiler does (its output on these root signatures): parameters in
/// user SGPRs s4… while each fits whole, the rest in the table from its start.
#[test]
fn arguments_that_fit_go_in_user_sgprs() {
let inline = |p: &[(u32, u32)]| layout_from_blob(&rts0(p)).unwrap().inline;
assert_eq!(inline(&[(4, 0)]), 8);
assert_eq!(inline(&[(1, 2), (4, 0)]), 16);
assert_eq!(inline(&[(0, 0)]), 4);
assert_eq!(inline(&[(4, 0); 6]), 48);
assert_eq!(inline(&[(1, 10), (4, 0)]), 48);
assert_eq!(inline(&[(1, 11), (4, 0)]), 44, "the UAV goes to the table");
assert_eq!(inline(&[(4, 0), (1, 11)]), 8, "the constants go to the table, whole");
assert_eq!(inline(&[(1, 20), (4, 0)]), 0, "once one goes to the table, the rest follow");
let l = layout_from_blob(&rts0(&[(1, 1), (4, 0), (1, 11)])).unwrap();
let args: Vec<u8> = [7u32, 0x1000, 4].iter().flat_map(|w| w.to_le_bytes()).chain([0u8; 44]).collect();
assert_eq!(user_data(&l, &args, 0x4_0000_0100), vec![0x100, 4, 0, 0, 7, 0x1000, 4]);
}
}
@@ -57,6 +57,10 @@ pub fn counts() -> (usize, u64) {
/// A texture the title placed at `va` (its console desc `desc`): kept in step with the memory.
pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, desc: &[u8; 0x38], state: D3D12_RESOURCE_STATES) -> Result<(), String> {
let tex = xg::Texture::new(desc).map_err(|hr| format!("layout {hr:#x}"))?;
// render targets and depth buffers are the GPU's (their metadata planes, empty planes)
if tex.planes.len() != 1 || tex.texels().is_none() {
return Err("a render target / depth buffer".into());
}
let bytes = tex.size() as usize;
let e = Entry { device: device as usize, va, tex: Arc::new(tex), state };
if crate::gpu::uma::get().is_some_and(|u| u.contains(va)) || crate::hle::kernelx::in_graphics_reservation(va) {
@@ -159,6 +163,7 @@ unsafe fn read_committed(at: usize, len: usize) -> Vec<u8> {
/// Every subresource (D3D12 order) of a texture from the title's memory at `va`.
unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec<Subresource> {
let Some(tex) = tex.texels() else { return Vec::new() };
let c = &tex.chain;
let bpe = tex.bpe as usize;
let mut out = Vec::with_capacity(tex.array as usize * c.levels.len());
+211 -54
View File
@@ -38,6 +38,7 @@ pub const LAYOUT_BYTES: usize = 0x1B40;
const PLANE: usize = 0x18;
const MIP: usize = 0x38;
const MIP_BYTES: usize = 0x70;
const PLANE_BYTES: usize = MIP + 15 * MIP_BYTES;
const MAX_MIPS: usize = 15;
pub fn exports() -> Vec<(&'static str, usize)> {
@@ -64,8 +65,8 @@ pub fn optimal_mode(layout: u32, flags: u32, bits_per_pixel: u64, width: u64, he
}
}
/// A 2D texture as the console lays it out.
pub struct Texture {
/// One tiled surface of a texture (color, depth or stencil) as the console lays it out.
pub struct Surface {
pub chain: Chain,
pub mode: u32,
pub bpe: u32,
@@ -77,6 +78,33 @@ pub struct Texture {
pub first_tail: usize,
}
/// What a plane of a texture holds.
pub enum PlaneKind {
Surface(Surface),
/// compression metadata (CMASK of a render target, HTILE of a depth buffer): only its size
Meta { bytes: u64, align: u64 },
/// a plane the library leaves empty (the texels of a BCn render target, the depth of a
/// depth buffer in a color format)
Blank,
}
/// A plane of a texture: its usage code in XG_RESOURCE_LAYOUT (1 color, 2 CMASK, 4 HTILE,
/// 5 / 6 depth / stencil, 7 / 8 depth / stencil of a depth buffer) and offset in the resource.
pub struct Plane {
pub usage: u32,
pub offset: u64,
pub kind: PlaneKind,
}
/// A 2D texture as the console lays it out: its planes, and the one the texels are in.
pub struct Texture {
pub planes: Vec<Plane>,
pub main: usize,
pub mips: u32,
/// a depth buffer in a color format: the library reports a size of 0
pub empty: bool,
}
/// (log2 bytes per element, pixels per element side) of a DXGI format; None for the 96-bit
/// and packed 4:2:2 ones (not tiled) and unknown formats
pub fn element(f: u32) -> Option<(u32, u32)> {
@@ -109,24 +137,168 @@ impl Texture {
let w16 = |o: usize| u16::from_le_bytes(d[o..o + 2].try_into().unwrap()) as u32;
let (dim, width, height, array, mips, format, samples, layout, flags) =
(u(0), u64::from_le_bytes(d[0x10..0x18].try_into().unwrap()), u(0x18), w16(0x1C), w16(0x1E), u(0x20), u(0x24), u(0x2C), u(0x30));
// 1D / 3D / buffers, MSAA, and render targets / depth (their metadata planes: CMASK,
// HTILE) are not modelled
if dim != 3 || samples > 1 || flags & 3 != 0 {
// 1D / 3D / buffers and MSAA are not modelled
if dim != 3 || samples > 1 {
return Err(E_NOTIMPL);
}
if matches!(format, 19..=22 | 44..=47) {
return Err(E_NOTIMPL); // depth + stencil: two planes
}
if width == 0 || width > 16384 || height == 0 || height > 16384 || array == 0 {
return Err(E_INVALIDARG);
}
let (e, side) = element(format).ok_or(E_INVALIDARG)?;
// depth + stencil formats: a 4-byte depth plane and a 1-byte stencil plane
let planar = matches!(format, 19..=22 | 44..=47);
let (e, side) = if planar { (2, 1) } else { element(format).ok_or(E_INVALIDARG)? };
let mode = match layout {
1 => 0,
0x100..=0x11F => layout & 0x1F,
0 | 2 => optimal_mode(layout, flags, (8u64 << e) / (side * side) as u64, width, height),
// the choice goes by the whole format's size (D32_S8X24: 64 bits a pixel)
0 | 2 => optimal_mode(layout, flags, if matches!(format, 19..=22) { 64 } else { (8u64 << e) / (side * side) as u64 }, width, height),
_ => return Err(E_INVALIDARG),
};
let full = 32 - (width as u32).max(height).leading_zeros();
let mips = if mips == 0 { full } else { mips };
if mips as usize > MAX_MIPS {
return Err(E_INVALIDARG);
}
let surface = |e: u32, side: u32| Surface::new(mode, e, side, width as u32, height, array, mips, pipes);
let (rt, ds) = (flags & 1 != 0, flags & 2 != 0);
if planar && layout == 2 {
return Err(E_INVALIDARG); // a stencil format with the 64KB_D choice
}
// a depth buffer (one level: it gets an HTILE) is in the Z modes; in a color format it
// is left empty. Render target + depth flags: a render target in a Z mode, unless the
// format has a stencil
let depth_buffer = ds && mips == 1 && (planar || !rt);
if depth_buffer && mode != 24 {
return Err(E_INVALIDARG);
}
let depth_format = planar || matches!(format, 39 | 40 | 53 | 55);
// the texels of a BCn render target / depth buffer of one level are left out too
let blank = (depth_buffer && !depth_format) || ((rt || ds) && side > 1 && mips == 1);
// and then the resource is empty – except a render target's CMASK
let empty = blank && ds;
let main = if blank { PlaneKind::Blank } else { PlaneKind::Surface(surface(e, side)?) };
let stencil = if planar { Some(surface(0, 1)?) } else { None };
// metadata planes, per slice: CMASK 1 byte per 128 pixels, HTILE per 16, of the size
// padded to 1024 × 1024
let meta = |div: u64| (width.div_ceil(1024) * 1024) * (height.div_ceil(1024) * 1024) as u64 / div * array as u64;
let mut planes: Vec<(u32, PlaneKind)> = Vec::new();
let (main_usage, stencil_usage) = if ds { (7, 8) } else if planar { (5, 6) } else { (1, 0) };
if depth_buffer {
planes.push((4, PlaneKind::Meta { bytes: meta(16), align: 0x1_0000 }));
}
let main_at = planes.len();
planes.push((if ds && !planar && !depth_buffer { 1 } else { main_usage }, main));
if let Some(s) = stencil {
planes.push((stencil_usage, PlaneKind::Surface(s)));
}
// a render target of one level gets a CMASK (not with the 64KB_D choice or the _T modes)
if rt && !depth_buffer && !planar && !empty && mips == 1 && layout != 2 && !(0x110..=0x113).contains(&layout) {
planes.push((2, PlaneKind::Meta { bytes: meta(128), align: 0x2000 }));
}
let mut offset = 0u64;
let planes = planes
.into_iter()
.map(|(usage, kind)| {
let (bytes, align) = match &kind {
PlaneKind::Surface(s) => (s.size(), s.alignment()),
PlaneKind::Meta { bytes, align } => (*bytes, *align),
PlaneKind::Blank => (0, 0),
};
// an empty plane is at 0 and takes no room
let at = if matches!(kind, PlaneKind::Blank) { 0 } else { offset.div_ceil(align) * align };
offset = offset.max(at + bytes);
Plane { usage, offset: at, kind }
})
.collect();
Ok(Texture { planes, main: main_at, mips, empty })
}
pub fn size(&self) -> u64 {
if self.empty {
return 0;
}
self.planes.iter().map(|p| p.offset + p.bytes()).max().unwrap_or(0)
}
pub fn alignment(&self) -> u64 {
self.planes.iter().map(|p| p.align()).max().unwrap_or(0x100)
}
/// the surface of plane `plane` and where it starts (None: metadata or no such plane)
pub fn plane_surface(&self, plane: u32) -> Option<(&Surface, u64)> {
let p = self.planes.get(plane as usize)?;
match &p.kind {
PlaneKind::Surface(s) => Some((s, p.offset)),
PlaneKind::Meta { .. } | PlaneKind::Blank => None,
}
}
/// the surface the texels are in (None: the library leaves them out)
pub fn texels(&self) -> Option<&Surface> {
self.plane_surface(self.main as u32).map(|(s, _)| s)
}
/// byte offset of level `i` of the texels from the start of the resource's first slice
pub fn mip_offset(&self, i: usize) -> u64 {
self.plane_surface(self.main as u32).map_or(0, |(s, at)| at + s.mip_offset(i))
}
/// byte offset of element (x, y) of level `i` in slice `slice` of the texels
pub fn element_offset(&self, i: usize, x: usize, y: usize, slice: usize) -> u64 {
self.plane_surface(self.main as u32).map_or(0, |(s, at)| at + s.element_offset(i, x, y, slice))
}
/// XG_RESOURCE_LAYOUT
pub fn write(&self, b: &mut [u8; LAYOUT_BYTES]) {
b.fill(0);
let q = |b: &mut [u8; LAYOUT_BYTES], o: usize, v: u64| b[o..o + 8].copy_from_slice(&v.to_le_bytes());
let w = |b: &mut [u8; LAYOUT_BYTES], o: usize, v: u32| b[o..o + 4].copy_from_slice(&v.to_le_bytes());
q(b, 0, self.size());
q(b, 8, self.alignment());
w(b, 0x10, self.mips);
w(b, 0x14, self.planes.len() as u32);
w(b, 0x1B38, 3);
for (k, p) in self.planes.iter().enumerate() {
let pb = PLANE + k * PLANE_BYTES;
w(b, pb, p.usage);
q(b, pb + 0x18, p.offset);
match &p.kind {
PlaneKind::Surface(s) => s.write_plane(b, pb),
PlaneKind::Blank => {}
PlaneKind::Meta { bytes, align } => {
q(b, pb + 8, *bytes);
q(b, pb + 0x20, *align);
q(b, pb + MIP, *bytes);
w(b, pb + MIP + 0x20, *align as u32);
}
}
}
}
}
impl Plane {
fn bytes(&self) -> u64 {
match &self.kind {
PlaneKind::Surface(s) => s.size(),
PlaneKind::Meta { bytes, .. } => *bytes,
PlaneKind::Blank => 0,
}
}
fn align(&self) -> u64 {
match &self.kind {
PlaneKind::Surface(s) => s.alignment(),
PlaneKind::Meta { align, .. } => *align,
PlaneKind::Blank => 0,
}
}
}
impl Surface {
/// `width` × `height` pixels, `array` slices, `mips` levels of `1 << e`-byte elements in
/// swizzle mode `mode`.
#[allow(clippy::too_many_arguments)]
fn new(mode: u32, e: u32, side: u32, width: u32, height: u32, array: u32, mips: u32, pipes: crate::gpu::tiling::PipeConfig) -> Result<Surface, HRESULT> {
// the modes the console's library takes for a 2D texture (VAR 28 / 31: not modelled)
let bc = side > 1;
match mode {
@@ -136,14 +308,9 @@ impl Texture {
_ => return Err(E_INVALIDARG),
}
let l = Layout::new(mode, e, pipes).ok_or(E_INVALIDARG)?;
let full = 32 - (width as u32).max(height).leading_zeros();
let mips = if mips == 0 { full } else { mips };
if mips as usize > MAX_MIPS {
return Err(E_INVALIDARG);
}
let chain = Chain::new(l, width as u32, height, side, mips);
let chain = Chain::new(l, width, height, side, mips);
let first_tail = chain.levels.iter().position(|m| m.tail.is_some()).unwrap_or(chain.levels.len());
Ok(Texture { chain, mode, bpe: 1 << e, side, width: width as u32, height, array, first_tail })
Ok(Surface { chain, mode, bpe: 1 << e, side, width, height, array, first_tail })
}
pub fn size(&self) -> u64 {
@@ -180,27 +347,20 @@ impl Texture {
(slice * self.chain.slice_bytes + m.offset + self.chain.layout.offset_z(x + m.origin.0, y + m.origin.1, slice, m.pitch)) as u64
}
/// XG_RESOURCE_LAYOUT
pub fn write(&self, b: &mut [u8; LAYOUT_BYTES]) {
b.fill(0);
/// this surface's plane of XG_RESOURCE_LAYOUT (its header at `pb`)
fn write_plane(&self, b: &mut [u8; LAYOUT_BYTES], pb: usize) {
let q = |b: &mut [u8; LAYOUT_BYTES], o: usize, v: u64| b[o..o + 8].copy_from_slice(&v.to_le_bytes());
let w = |b: &mut [u8; LAYOUT_BYTES], o: usize, v: u32| b[o..o + 4].copy_from_slice(&v.to_le_bytes());
let mips = self.chain.levels.len();
q(b, 0, self.size());
q(b, 8, self.alignment());
w(b, 0x10, mips as u32);
w(b, 0x14, 1);
w(b, 0x1B38, 3);
w(b, PLANE, 1);
q(b, PLANE + 8, self.size());
q(b, PLANE + 0x10, self.chain.slice_bytes as u64);
q(b, PLANE + 0x20, self.alignment());
w(b, PLANE + 0x28, self.bpe);
w(b, PLANE + 0x2C, self.first_tail as u32);
w(b, PLANE + 0x30, (mips - self.first_tail) as u32);
q(b, pb + 8, self.size());
q(b, pb + 0x10, self.chain.slice_bytes as u64);
q(b, pb + 0x20, self.alignment());
w(b, pb + 0x28, self.bpe);
w(b, pb + 0x2C, self.first_tail as u32);
w(b, pb + 0x30, (mips - self.first_tail) as u32);
for i in 0..mips {
let m = &self.chain.levels[i];
let r = PLANE + MIP + i * MIP_BYTES;
let r = pb + MIP + i * MIP_BYTES;
let tail = i >= self.first_tail;
let (pw, ph) = self.padded(i);
let bytes = (pw * ph) as u64 * self.bpe as u64;
@@ -321,58 +481,55 @@ unsafe extern "system" fn get_alignment(p: *mut c_void) -> u64 {
}
unsafe extern "system" fn get_mip_offset(p: *mut c_void, plane: u32, mip: u32) -> u64 {
let t = tex(p);
if plane != 0 || mip as usize >= t.chain.levels.len() {
return 0;
match tex(p).plane_surface(plane) {
Some((s, at)) if (mip as usize) < s.chain.levels.len() => at + s.mip_offset(mip as usize),
_ => 0,
}
t.mip_offset(mip as usize)
}
unsafe extern "system" fn get_texel_offset(p: *mut c_void, plane: u32, mip: u32, x: u64, y: u32, slice: u32, _sample: u32, bit: *mut u32) -> u64 {
let t = tex(p);
if !bit.is_null() {
*bit = 0;
}
if plane != 0 || mip as usize >= t.chain.levels.len() || slice >= t.array {
return 0;
match tex(p).plane_surface(plane) {
Some((s, at)) if (mip as usize) < s.chain.levels.len() && slice < s.array => at + s.element_offset(mip as usize, x as usize, y as usize, slice as usize),
_ => 0,
}
t.element_offset(mip as usize, x as usize, y as usize, slice as usize)
}
unsafe extern "system" fn not_implemented(_p: *mut c_void) -> HRESULT {
E_NOTIMPL
}
/// (level, slice) of a subresource (mip + slice × mips)
fn subresource(t: &Texture, sub: u32) -> Option<(usize, usize)> {
let mips = t.chain.levels.len();
let (i, s) = (sub as usize % mips, sub as usize / mips);
(s < t.array as usize).then_some((i, s))
/// (surface, its offset, level, slice) of a subresource (mip + slice × mips) of a plane
fn subresource(t: &Texture, plane: u32, sub: u32) -> Option<(&Surface, u64, usize, usize)> {
let (s, at) = t.plane_surface(plane)?;
let mips = s.chain.levels.len();
let (i, k) = (sub as usize % mips, sub as usize / mips);
(k < s.array as usize).then_some((s, at, i, k))
}
/// rows of `src` (`row_pitch` apart) → the level's place in `dst` (the whole resource)
unsafe extern "system" fn copy_into(p: *mut c_void, dst: *mut u8, plane: u32, sub: u32, src: *const u8, row_pitch: u32, _slice_pitch: u32) -> HRESULT {
let t = tex(p);
let Some((i, s)) = subresource(t, sub).filter(|_| plane == 0 && !dst.is_null() && !src.is_null()) else { return E_INVALIDARG };
let Some((t, at, i, k)) = subresource(tex(p), plane, sub).filter(|_| !dst.is_null() && !src.is_null()) else { return E_INVALIDARG };
let m = t.chain.levels[i];
let row = m.width * t.bpe as usize;
let mut linear = vec![0u8; row * m.height];
for y in 0..m.height {
linear[y * row..(y + 1) * row].copy_from_slice(std::slice::from_raw_parts(src.add(y * row_pitch as usize), row));
}
let slice = std::slice::from_raw_parts_mut(dst.add(s * t.chain.slice_bytes), t.chain.slice_bytes);
t.chain.tile_level(slice, i, s, &linear);
let slice = std::slice::from_raw_parts_mut(dst.add(at as usize + k * t.chain.slice_bytes), t.chain.slice_bytes);
t.chain.tile_level(slice, i, k, &linear);
S_OK
}
/// the level's place in `src` (the whole resource) → rows of `dst` (`row_pitch` apart)
unsafe extern "system" fn copy_from(p: *mut c_void, dst: *mut u8, plane: u32, sub: u32, src: *const u8, row_pitch: u32, _slice_pitch: u32) -> HRESULT {
let t = tex(p);
let Some((i, s)) = subresource(t, sub).filter(|_| plane == 0 && !dst.is_null() && !src.is_null()) else { return E_INVALIDARG };
let Some((t, at, i, k)) = subresource(tex(p), plane, sub).filter(|_| !dst.is_null() && !src.is_null()) else { return E_INVALIDARG };
let m = t.chain.levels[i];
let row = m.width * t.bpe as usize;
let slice = std::slice::from_raw_parts(src.add(s * t.chain.slice_bytes), t.chain.slice_bytes);
let linear = t.chain.detile_level(slice, i, s);
let slice = std::slice::from_raw_parts(src.add(at as usize + k * t.chain.slice_bytes), t.chain.slice_bytes);
let linear = t.chain.detile_level(slice, i, k);
for y in 0..m.height {
std::ptr::copy_nonoverlapping(linear[y * row..].as_ptr(), dst.add(y * row_pitch as usize), row);
}
+388
View File
@@ -0,0 +1,388 @@
//! The console's shader compiler as a test generator for the recompiler: HLSL compiled by the
//! console's `dxcompiler_xs.dll` (DXIL + the native RDNA2 code in XDAT → XBCH → FSSM) goes
//! through XCL's RDNA2 → HLSL translation and runs on the PC GPU; the same HLSL compiled by the
//! PC compiler runs next to it, and the two must write the same memory.
//!
//! The compiler is the console's own file and stays outside the repo: the tests run only when
//! `XCL_SAMPLE_DXC` names `dxcompiler_xs.dll` (with its `xbsc_xs.dll` next to it), e.g. from
//! the system directory of a console OS image.
use std::ffi::c_void;
use windows::core::{Interface, GUID, HRESULT, PCWSTR};
use windows::Win32::Graphics::Direct3D::Dxc::{DxcBuffer, IDxcBlob, IDxcCompiler3, IDxcResult, CLSID_DxcCompiler, DXC_CP_UTF8};
use xcl::gpu::recomp::{dxc, pso, runner};
use xcl::hle::d3d12x::console_list;
type CreateInstance = unsafe extern "system" fn(*const GUID, *const GUID, *mut *mut c_void) -> HRESULT;
/// The console compiler (None: `XCL_SAMPLE_DXC` not set).
fn console_compiler() -> Option<IDxcCompiler3> {
let path = std::env::var("XCL_SAMPLE_DXC").ok()?;
let wide: Vec<u16> = path.encode_utf16().chain([0]).collect();
unsafe {
// its back end is loaded by name when it compiles: loaded first from the same directory
// (LOAD_WITH_ALTERED_SEARCH_PATH)
let dir = std::path::Path::new(&path).parent().map(|d| d.to_path_buf()).unwrap_or_default();
for name in ["xbsc_xs.dll", "newbe_xs.dll"] {
let w: Vec<u16> = dir.join(name).to_string_lossy().encode_utf16().chain([0]).collect();
windows_sys::Win32::System::LibraryLoader::LoadLibraryExW(w.as_ptr(), std::ptr::null_mut(), 0x8);
}
let h = windows_sys::Win32::System::LibraryLoader::LoadLibraryExW(wide.as_ptr(), std::ptr::null_mut(), 0x8);
assert!(!h.is_null(), "LoadLibraryExW({path}) failed");
let f = windows_sys::Win32::System::LibraryLoader::GetProcAddress(h, b"DxcCreateInstance\0".as_ptr()).expect("DxcCreateInstance");
let create: CreateInstance = std::mem::transmute(f);
let mut p = std::ptr::null_mut();
let hr = create(&CLSID_DxcCompiler, &IDxcCompiler3::IID, &mut p);
assert!(hr.is_ok() && !p.is_null(), "DxcCreateInstance: {hr:?}");
Some(IDxcCompiler3::from_raw(p))
}
}
/// HLSL → the console compiler's container
fn console_compile(c: &IDxcCompiler3, src: &str, args: &[&str]) -> Result<Vec<u8>, String> {
let args: Vec<Vec<u16>> = args.iter().map(|a| a.encode_utf16().chain([0]).collect()).collect();
let ptrs: Vec<PCWSTR> = args.iter().map(|a| PCWSTR(a.as_ptr())).collect();
let buf = DxcBuffer { Ptr: src.as_ptr() as *const c_void, Size: src.len(), Encoding: DXC_CP_UTF8.0 };
unsafe {
let r: IDxcResult = c.Compile(&buf, Some(&ptrs), None).map_err(|e| format!("Compile: {e}"))?;
let status = r.GetStatus().map_err(|e| format!("{e}"))?;
let errors = r
.GetErrorBuffer()
.ok()
.filter(|b| !b.GetBufferPointer().is_null() && b.GetBufferSize() > 0)
.map(|b| String::from_utf8_lossy(std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize())).trim_end_matches('\0').to_string())
.unwrap_or_default();
if status.is_err() {
return Err(format!("console dxc: {errors}"));
}
let blob: IDxcBlob = r.GetResult().map_err(|e| format!("{e}"))?;
Ok(std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec())
}
}
/// The parts of a DXBC container (fourcc, size)
fn parts(blob: &[u8]) -> Vec<(String, usize)> {
let u = |o: usize| u32::from_le_bytes(blob[o..o + 4].try_into().unwrap()) as usize;
if blob.len() < 32 || &blob[0..4] != b"DXBC" {
return Vec::new();
}
(0..u(28))
.map(|i| {
let o = u(32 + 4 * i);
(String::from_utf8_lossy(&blob[o..o + 4]).into_owned(), u(o + 4))
})
.collect()
}
/// The buffer every kernel works on: inputs, then outputs (byte offsets).
const INTS: u32 = 0;
const FLOATS: u32 = 0x1000;
const OUT: u32 = 0x2000;
const BUF_BYTES: u32 = 0x4000;
/// thread groups of 64 threads
const GROUPS: u32 = 4;
/// The kernel source around `body`: one RWByteAddressBuffer `buf` – a root UAV on the console
/// (its address in the root argument array), u2 (the runner's flat memory) on the PC.
fn kernel(body: &str) -> String {
format!(
r#"#ifdef XCL_CONSOLE
RWByteAddressBuffer buf : register(u0);
#define ROOT [RootSignature("UAV(u0)")]
#else
RWByteAddressBuffer buf : register(u2);
#define ROOT
#endif
#define OUT_AT(i) ({OUT}u + 4u * (i))
groupshared uint lds[64];
uint in_u(uint i) {{ return buf.Load({INTS}u + (i & 1023u) * 4u); }}
float in_f(uint i) {{ return asfloat(buf.Load({FLOATS}u + (i & 1023u) * 4u)); }}
void out_u(uint i, uint v) {{ buf.Store(OUT_AT(i), v); }}
void out_f(uint i, float v) {{ out_u(i, asuint(v)); }}
ROOT [numthreads(64, 1, 1)]
void main(uint3 tid : SV_DispatchThreadID, uint3 gtid : SV_GroupThreadID, uint3 gid : SV_GroupID) {{
{body}
}}
"#
)
}
/// How the two runs' words must agree.
#[derive(Clone, Copy, PartialEq)]
enum Compare {
Exact,
/// up to the sign of zero (also of the halves of a word: packed f16): the console's
/// compiler multiplies by constants with v_mul_legacy_f32 where the HLSL allows it (DXIL
/// fast math: no signed zeros), and there -0 × c = +0 – on the PC -0
SignOfZero,
/// floats, relative error 2e-5 (the console's transcendental and division code)
Float,
}
use Compare::*;
/// (name, body, how the outputs are compared)
const KERNELS: &[(&str, &str, Compare)] = &[
(
"integer arithmetic",
"uint a = in_u(tid.x), b = in_u(tid.x + 256u), c = in_u(tid.x + 512u); uint o = tid.x * 8u;
out_u(o, a * b + c);
out_u(o + 1u, (a >> (b & 31u)) ^ (c << 3u));
out_u(o + 2u, countbits(a) + firstbithigh(b) * 100u + firstbitlow(c) * 10000u);
out_u(o + 3u, reversebits(a));
out_u(o + 4u, (uint)((int)a / max(1, (int)(b & 0xFFFFu))));
out_u(o + 5u, a % max(1u, b & 0xFFFu));
out_u(o + 6u, min(a, b) + (uint)max((int)b, (int)c));
out_u(o + 7u, (uint)(((uint64_t)a * b) >> 32));",
Exact,
),
(
"conversions",
"float x = in_f(tid.x) * 1000.0f; uint a = in_u(tid.x); uint o = tid.x * 8u;
out_u(o, (uint)(int)x);
out_f(o + 1u, (float)a);
out_f(o + 2u, (float)(int)a);
out_u(o + 3u, f32tof16(x) | f32tof16(-x * 0.001f) << 16);
out_f(o + 4u, f16tof32(a));
out_f(o + 5u, floor(x) + ceil(x * 0.5f) * 3.0f);
out_f(o + 6u, round(x * 0.37f));
out_f(o + 7u, saturate(x * 0.001f) + trunc(x));",
SignOfZero,
),
(
"float math",
"float x = in_f(tid.x), y = in_f(tid.x + 256u); uint o = tid.x * 8u;
out_f(o, x * y + 1.0f);
out_f(o + 1u, sqrt(abs(x)));
out_f(o + 2u, rsqrt(abs(x) + 1.0f));
out_f(o + 3u, exp2(x * 0.5f));
out_f(o + 4u, log2(abs(y) + 1.0f));
out_f(o + 5u, sin(x) + cos(y));
out_f(o + 6u, x / (y + 20.0f));
out_f(o + 7u, frac(x * 3.7f) + min(x, y) - max(x, y));",
Float,
),
(
"loops and branches per lane",
"uint a = in_u(tid.x); uint n = a & 63u; uint acc = tid.x;
for (uint i = 0u; i < n; i++) {
acc = acc * 31u + i;
if ((acc & 7u) == 3u) continue;
if (acc > 0xF0000000u) break;
acc ^= in_u(i + tid.x);
}
if (a & 1u) acc += 5u; else acc = ~acc;
out_u(tid.x * 8u, acc);
out_u(tid.x * 8u + 1u, n);",
Exact,
),
(
"groupshared memory and barriers",
"lds[gtid.x] = in_u(tid.x);
GroupMemoryBarrierWithGroupSync();
uint s = 0u;
for (uint i = 0u; i < 64u; i++) s += lds[(gtid.x + i) & 63u] * (i + 1u);
GroupMemoryBarrierWithGroupSync();
lds[63u - gtid.x] = s;
GroupMemoryBarrierWithGroupSync();
out_u(tid.x * 8u, lds[gtid.x]);
out_u(tid.x * 8u + 1u, gid.x);",
Exact,
),
(
"atomics",
"uint a = in_u(tid.x); uint old;
buf.InterlockedAdd(OUT_AT(a & 15u), 1u, old);
buf.InterlockedMax(OUT_AT(16u + (a >> 28)), a, old);
buf.InterlockedXor(OUT_AT(32u + (tid.x & 7u)), a);
buf.InterlockedOr(OUT_AT(40u), 1u << (a & 31u));
buf.InterlockedMax(OUT_AT(41u), a | 0x80000000u);",
Exact,
),
(
"64-bit integers",
"uint64_t a = ((uint64_t)in_u(tid.x) << 32) | in_u(tid.x + 256u);
uint64_t b = ((uint64_t)in_u(tid.x + 512u) << 32) | in_u(tid.x + 768u);
uint64_t r = (a * b + (a >> 7)) ^ (b << 13);
int64_t d = (int64_t)a / (int64_t)((b & 0xFFFFFFull) | 1ull);
uint o = tid.x * 8u;
out_u(o, (uint)r); out_u(o + 1u, (uint)(r >> 32));
out_u(o + 2u, (uint)d); out_u(o + 3u, (uint)((uint64_t)d >> 32));
out_u(o + 4u, (uint)min(a, b)); out_u(o + 5u, (uint)(max(a, b) >> 32));",
Exact,
),
];
/// The inputs: 1024 integers (varied bit patterns), 1024 floats (-10 … 10 and a few special
/// values).
fn inputs() -> Vec<u32> {
let mut v = vec![0u32; (BUF_BYTES / 4) as usize];
let mut x = 0x2545_F491u32;
for i in 0..1024 {
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
v[(INTS / 4) as usize + i] = match i % 16 {
0 => 0,
1 => u32::MAX,
2 => 0x8000_0000,
3 => i as u32,
_ => x,
};
let f = match i % 32 {
0 => 0.0f32,
1 => -0.0,
2 => 1.0,
3 => 1e-30,
_ => (x >> 8) as f32 / (1u32 << 24) as f32 * 20.0 - 10.0,
};
v[(FLOATS / 4) as usize + i] = f.to_bits();
}
v
}
/// One kernel through the console compiler + XCL's translation and through the PC compiler:
/// the output part of the buffer after each.
fn run_both(c: &IDxcCompiler3, body: &str) -> Result<(Vec<u32>, Vec<u32>), String> {
let src = kernel(body);
let blob = console_compile(c, &src, &["-E", "main", "-T", "cs_6_6", "-enable-16bit-types", "-D", "XCL_CONSOLE=1"])?;
let translated = pso::console_to_dxil(&blob, pso::Stage::Compute, 0).map_err(|e| format!("translation: {e}"))?;
// the console run: the buffer at 0x1_0000, its address the one root argument – in user
// SGPRs or in a table at 0x100, as XCL passes them on a console list's dispatch
let (table_at, base) = (0x100usize, 0x1_0000usize);
let layout = console_list::layout_from_blob(&blob).ok_or("no RTS0")?;
let args = (base as u64).to_le_bytes();
let data = inputs();
let mut mem = vec![0u32; (base + BUF_BYTES as usize) / 4];
for (k, b) in args[layout.inline as usize..].iter().enumerate() {
mem[(table_at + k) / 4] |= (*b as u32) << (8 * (k % 4));
}
mem[base / 4..].copy_from_slice(&data);
let sgprs = console_list::user_data(&layout, &args, table_at as u64);
let console = runner::dispatch(&translated.dxil, [GROUPS, 1, 1], &sgprs, &mem)?;
let pc_dxil = dxc::compile(&src, "main", "cs_6_6", &["-enable-16bit-types"])?;
let pc = runner::dispatch(&pc_dxil, [GROUPS, 1, 1], &[], &data)?;
let out = |m: &[u32], at: usize| m[(at + OUT as usize) / 4..(at + BUF_BYTES as usize) / 4].to_vec();
Ok((out(&console, base), out(&pc, 0)))
}
/// Every kernel of `KERNELS`: the console's code as XCL runs it writes what the PC compile of
/// the same source writes.
#[test]
fn console_compiled_kernels_match_the_pc_compile() {
let Some(c) = console_compiler() else { return };
if runner::adapter().is_err() {
return;
}
let mut failed = Vec::new();
for &(name, body, how) in KERNELS {
match run_both(&c, body) {
Err(e) => failed.push(format!("{name}: {e}")),
Ok((console, pc)) => {
let zero = |w: u32| {
let w = if w == 0x8000_0000 { 0 } else { w };
let half = |h: u32| if h == 0x8000 { 0 } else { h };
half(w & 0xFFFF) | half(w >> 16) << 16
};
let same = |a: u32, b: u32| match how {
_ if a == b => true,
Exact => false,
SignOfZero => zero(a) == zero(b),
Float => {
let (x, y) = (f32::from_bits(a), f32::from_bits(b));
(x.is_nan() && y.is_nan()) || (x - y).abs() <= 2e-5 * y.abs().max(1.0)
}
};
let bad: Vec<usize> = (0..pc.len()).filter(|&i| !same(console[i], pc[i])).collect();
println!("{name}: {} of {} words differ", bad.len(), pc.len());
if let Some(&i) = bad.first() {
let mut outputs: Vec<usize> = bad.iter().map(|i| i % 8).collect();
outputs.dedup();
outputs.sort();
outputs.dedup();
failed.push(format!("{name}: {} words differ (outputs {outputs:?}), e.g. word {i} (thread {}, output {}): console {:#x}, PC {:#x}", bad.len(), i / 8, i % 8, console[i], pc[i]));
}
}
}
}
assert!(failed.is_empty(), "{}", failed.join("\n"));
}
/// Kernel `XCL_KERNEL` (index in `KERNELS`) through the console compiler: its parts, its
/// hardware interface, its disassembly; with `XCL_KERNEL_HLSL` set the translated HLSL.
#[test]
#[ignore]
fn print_a_console_compile() {
let Some(c) = console_compiler() else { return };
let which = std::env::var("XCL_KERNEL").ok().and_then(|k| k.parse::<usize>().ok()).unwrap_or(0);
let src = kernel(KERNELS[which].1);
let blob = console_compile(&c, &src, &["-E", "main", "-T", "cs_6_6", "-D", "XCL_CONSOLE=1"]).unwrap_or_else(|e| panic!("{e}"));
println!("{}: {} bytes, parts {:?}", KERNELS[which].0, blob.len(), parts(&blob));
match xcl::gpu::xbox::parse(&blob) {
Some(sh) => {
for f in &sh.fssm {
println!("FSSM: stages {:?}, programs {}", f.stages.iter().map(|s| xcl::gpu::xbox::hw_stage_name(s.hw)).collect::<Vec<_>>(), f.programs.len());
if let Some(st) = f.stages.first() {
println!(" {:?}", xcl::gpu::recomp::CsInterface::from_descriptor(&f.data, st.offset));
}
if let Some(p) = f.programs.first() {
for l in xcl::gpu::rdna2::disassemble(&f.data[p.offset..p.offset + p.len], 0, true) {
println!(" {:4x}: {}", l.pc, l.text);
}
}
}
}
None => println!("not a console container"),
}
match pso::console_to_hlsl(&blob, pso::Stage::Compute) {
Ok((h, _)) => {
println!("translated: {} bytes of HLSL", h.len());
if std::env::var("XCL_KERNEL_HLSL").is_ok() {
for (i, l) in h.lines().enumerate() {
println!("{:4} {l}", i + 1);
}
}
}
Err(e) => println!("translation: {e}"),
}
}
/// Where the console puts root arguments: a few root signatures, the first instructions of
/// each compiled kernel and its user SGPR count.
#[test]
#[ignore]
fn print_root_argument_placement() {
let Some(c) = console_compiler() else { return };
let cases = [
("UAV only", "UAV(u0)", "RWByteAddressBuffer o : register(u0);", "o.Store(tid.x * 4u, tid.x);"),
("2 constants, UAV", "RootConstants(num32BitConstants=2, b0), UAV(u0)", "RWByteAddressBuffer o : register(u0); cbuffer k : register(b0) { uint k0; uint k1; };", "o.Store(tid.x * 4u, k0 + k1 * tid.x);"),
("UAV, 2 constants", "UAV(u0), RootConstants(num32BitConstants=2, b0)", "RWByteAddressBuffer o : register(u0); cbuffer k : register(b0) { uint k0; uint k1; };", "o.Store(tid.x * 4u, k0 + k1 * tid.x);"),
("CBV, UAV", "CBV(b0), UAV(u0)", "RWByteAddressBuffer o : register(u0); cbuffer k : register(b0) { uint k0; uint k1; };", "o.Store(tid.x * 4u, k0 + k1 * tid.x);"),
("SRV, UAV", "SRV(t0), UAV(u0)", "RWByteAddressBuffer o : register(u0); ByteAddressBuffer i : register(t0);", "o.Store(tid.x * 4u, i.Load(tid.x * 4u));"),
("table UAV", "DescriptorTable(UAV(u0))", "RWByteAddressBuffer o : register(u0);", "o.Store(tid.x * 4u, tid.x);"),
("20 constants, UAV", "RootConstants(num32BitConstants=20, b0), UAV(u0)", "RWByteAddressBuffer o : register(u0); cbuffer k : register(b0) { uint4 k[5]; };", "o.Store(tid.x * 4u, k[0].x + k[4].w * tid.x);"),
("10 constants, UAV", "RootConstants(num32BitConstants=10, b0), UAV(u0)", "RWByteAddressBuffer o : register(u0); cbuffer k : register(b0) { uint4 k[2]; uint2 k2; };", "o.Store(tid.x * 4u, k[0].x + k2.y * tid.x);"),
("11 constants, UAV", "RootConstants(num32BitConstants=11, b0), UAV(u0)", "RWByteAddressBuffer o : register(u0); cbuffer k : register(b0) { uint4 k[2]; uint3 k2; };", "o.Store(tid.x * 4u, k[0].x + k2.z * tid.x);"),
("UAV, 11 constants", "UAV(u0), RootConstants(num32BitConstants=11, b0)", "RWByteAddressBuffer o : register(u0); cbuffer k : register(b0) { uint4 k[2]; uint3 k2; };", "o.Store(tid.x * 4u, k[0].x + k2.z * tid.x);"),
("6 UAVs", "UAV(u0), UAV(u1), UAV(u2), UAV(u3), UAV(u4), UAV(u5)", "RWByteAddressBuffer o0 : register(u0); RWByteAddressBuffer o1 : register(u1); RWByteAddressBuffer o2 : register(u2); RWByteAddressBuffer o3 : register(u3); RWByteAddressBuffer o4 : register(u4); RWByteAddressBuffer o5 : register(u5);", "o0.Store(tid.x * 4u, 1u); o5.Store(tid.x * 4u, 2u); o3.Store(tid.x * 4u, 3u);"),
];
for (name, rs, decls, body) in cases {
let src = format!("{decls}\n[RootSignature(\"{rs}\")]\n[numthreads(64, 1, 1)]\nvoid main(uint3 tid : SV_DispatchThreadID) {{ {body} }}\n");
let blob = match console_compile(&c, &src, &["-E", "main", "-T", "cs_6_6"]) {
Ok(b) => b,
Err(e) => {
println!("{name}: {e}");
continue;
}
};
let Some(sh) = xcl::gpu::xbox::parse(&blob) else { continue };
for f in &sh.fssm {
let cs = f.stages.first().and_then(|st| xcl::gpu::recomp::CsInterface::from_descriptor(&f.data, st.offset));
println!("{name} [{rs}]: user SGPRs {:?}", cs.map(|c| c.user_sgprs));
if let Some(p) = f.programs.first() {
for l in xcl::gpu::rdna2::disassemble(&f.data[p.offset..p.offset + p.len], 0, true).iter().skip(2).take(14) {
println!(" {}", l.text);
}
}
}
}
}
+169 -8
View File
@@ -221,8 +221,8 @@ fn texel_offsets_and_the_console_pipe_configuration() {
.filter(|cfg| {
let t = xcl::hle::xg::Texture::with_pipes(&d, **cfg).unwrap();
let mut good = true;
for i in 0..t.chain.levels.len() {
let l = t.chain.levels[i];
for i in 0..t.texels().unwrap().chain.levels.len() {
let l = t.texels().unwrap().chain.levels[i];
for k in 0..24 {
let (x, y, s) = match k {
0 => (0, 0, 0),
@@ -291,8 +291,8 @@ fn print_xor_64kb_parts() {
let off: Offset = unsafe { std::mem::transmute(*(*(c as *const *const usize)).add(6)) };
let t = xcl::hle::xg::Texture::with_pipes(&d, cfg).unwrap();
let mut bad = std::collections::BTreeMap::<String, (usize, String)>::new();
for i in 0..t.chain.levels.len() {
let l = t.chain.levels[i];
for i in 0..t.texels().unwrap().chain.levels.len() {
let l = t.texels().unwrap().chain.levels[i];
for s in 0..2usize {
for y in (0..l.height).step_by(7) {
for x in (0..l.width).step_by(5) {
@@ -382,11 +382,11 @@ fn subresource_copies_match_the_console_library() {
let t = xcl::hle::xg::Texture::new(&d).unwrap();
let size = t.size() as usize;
let (mut a, mut b) = (vec![0u8; size], vec![0u8; size]);
let mips = t.chain.levels.len();
let mips = t.texels().unwrap().chain.levels.len();
for s in 0..array as usize {
for i in 0..mips {
let l = t.chain.levels[i];
let row = l.width * t.bpe as usize;
let l = t.texels().unwrap().chain.levels[i];
let row = l.width * t.texels().unwrap().bpe as usize;
let pitch = row + 16;
let lin: Vec<u8> = (0..pitch * l.height)
.map(|_| {
@@ -440,5 +440,166 @@ fn print_odd_offsets() {
}
}
}
println!("{n} texels of mip 0 differ; pitch {} block {}x{}", t.chain.levels[0].pitch, t.chain.layout.block_w, t.chain.layout.block_h);
println!("{n} texels of mip 0 differ; pitch {} block {}x{}", t.texels().unwrap().chain.levels[0].pitch, t.texels().unwrap().chain.layout.block_w, t.texels().unwrap().chain.layout.block_h);
}
#[test]
#[ignore]
fn print_planes() {
let Some(m) = console() else { return };
let create = proc(m, "XGCreateTextureComputer");
for (name, d) in [
("rgba8 1x1 RT+DS optimal", desc(3, 1, 1, 1, 1, 28, 0, 3)),
("rgba8 256x256 RT+DS optimal", desc(3, 256, 256, 1, 1, 28, 0, 3)),
("d32 256x256 RT+DS optimal", desc(3, 256, 256, 1, 1, 40, 0, 3)),
("d24s8 256x256 RT+DS optimal", desc(3, 256, 256, 1, 1, 45, 0, 3)),
("bc1 256x256 RT+DS optimal", desc(3, 256, 256, 1, 1, 71, 0, 3)),
("bc1 256x256 DS optimal", desc(3, 256, 256, 1, 1, 71, 0, 2)),
("rgba8 256x256 DS 0x119", desc(3, 256, 256, 1, 1, 28, 0x119, 2)),
("rgba8 256x256 DS 0x118", desc(3, 256, 256, 1, 1, 28, 0x118, 2)),
("rgba8 256x256 DS optimal", desc(3, 256, 256, 1, 1, 28, 0, 2)),
("rgba8 1x1 DS optimal", desc(3, 1, 1, 1, 0, 28, 0, 2)),
("bc1 256x256 RT optimal", desc(3, 256, 256, 1, 1, 71, 0, 1)),
("d24s8 256x256 RT optimal", desc(3, 256, 256, 1, 1, 45, 0, 1)),
("d32s8 256x256 DS optimal", desc(3, 256, 256, 1, 1, 20, 0, 2)),
("r32f 256x256 DS optimal", desc(3, 256, 256, 1, 1, 41, 0, 2)),
("rgba8 256x256 RT optimal", desc(3, 256, 256, 1, 1, 28, 0, 1)),
("rgba8 1000x333 RT optimal", desc(3, 1000, 333, 1, 1, 28, 0, 1)),
("rgba8 256x256 RT 0x119", desc(3, 256, 256, 1, 1, 28, 0x119, 1)),
("rgba8 256x256 RT optimal 3 mips", desc(3, 256, 256, 1, 3, 28, 0, 1)),
("rgba8 256x256 RT optimal array 4", desc(3, 256, 256, 4, 1, 28, 0, 1)),
("d32 256x256 depth", desc(3, 256, 256, 1, 1, 40, 0, 2)),
("d32 1000x333 depth", desc(3, 1000, 333, 1, 1, 40, 0, 2)),
("d24s8 256x256 depth", desc(3, 256, 256, 1, 1, 45, 0, 2)),
("d16 256x256 depth", desc(3, 256, 256, 1, 1, 55, 0, 2)),
("d24s8 256x256 no flags", desc(3, 256, 256, 1, 1, 45, 0x109, 0)),
] {
let (hr, l) = unsafe { layout(create, &d) };
let q = |o: usize| u64::from_le_bytes(l[o..o + 8].try_into().unwrap());
let w = |o: usize| u32::from_le_bytes(l[o..o + 4].try_into().unwrap());
println!("{name}: hr {hr:#x} size {:#x} align {:#x} mips {} planes {}", q(0), q(8), w(0x10), w(0x14));
for p in 0..w(0x14).min(4) as usize {
let b = 0x18 + p * 0x6C8;
let head: Vec<String> = (0..0x38).step_by(4).map(|k| format!("{:x}", w(b + k))).collect();
println!(" plane {p}: {}", head.join(" "));
let r = b + 0x38;
let row: Vec<String> = (0..0x70).step_by(4).map(|k| format!("{:x}", w(r + k))).collect();
println!(" mip0: {}", row.join(" "));
}
}
}
#[test]
#[ignore]
fn print_htile_sizes() {
let Some(m) = console() else { return };
let create = proc(m, "XGCreateTextureComputer");
for &(w, h) in &[(64u64, 64u32), (128, 128), (256, 256), (512, 512), (1024, 1024), (2048, 2048), (4096, 4096), (8192, 8192), (1920, 1080), (3840, 2160), (1000, 333), (16384, 16), (16, 16384)] {
for &(array, mips) in &[(1u16, 1u16), (6, 1), (1, 3)] {
for f in [40u32, 45] {
let (hr, l) = unsafe { layout(create, &desc(3, w, h, array, mips, f, 0, 2)) };
let q = |o: usize| u64::from_le_bytes(l[o..o + 8].try_into().unwrap());
let wd = |o: usize| u32::from_le_bytes(l[o..o + 4].try_into().unwrap());
let planes: Vec<String> = (0..wd(0x14).min(4) as usize).map(|p| { let b = 0x18 + p * 0x6C8; format!("u{} size {:#x} off {:#x} al {:#x}", wd(b), q(b + 8), q(b + 0x18), q(b + 0x20)) }).collect();
println!("fmt {f} {w}x{h} a{array} m{mips}: hr {hr:#x} total {:#x} | {}", q(0), planes.join(" | "));
}
}
}
}
/// Render targets (CMASK), depth buffers (HTILE, depth, stencil) and the depth + stencil
/// formats against the console library.
#[test]
fn render_target_and_depth_layouts_match() {
let Some(m) = console() else { return };
let theirs = proc(m, "XGCreateTextureComputer");
let ours = xcl::hle::xg::XGCreateTextureComputer as *const () as usize;
let mut bad = std::collections::BTreeMap::<String, (usize, String)>::new();
let (mut cases, mut same) = (0, 0);
for f in [28u32, 71, 40, 55, 45, 20, 41, 39, 44] {
for (w, h) in [(1u64, 1u32), (100, 60), (256, 256), (1920, 1080)] {
for mips in [1u16, 3] {
for array in [1u16, 6] {
for (lay, flags) in [(0u32, 1u32), (0, 2), (0x118, 2), (0x119, 2), (0x119, 1), (0x111, 1), (2, 1), (2, 2), (0, 5), (0x109, 2), (0, 3), (0, 4), (0, 0)] {
let d = desc(3, w, h, array, mips, f, lay, flags);
let (hc, lc) = unsafe { layout(theirs, &d) };
let (ho, lo) = unsafe { layout(ours, &d) };
cases += 1;
let k = if (hc < 0) != (ho < 0) {
Some((format!("HRESULT {hc:#x} vs ours {ho:#x}"), String::new()))
} else if hc >= 0 {
(0..0x1B40).step_by(4).find(|&o| lc[o..o + 4] != lo[o..o + 4]).map(|o| {
let v = |l: &[u8]| u32::from_le_bytes(l[o..o + 4].try_into().unwrap());
(field(o), format!(": console {:#x}, ours {:#x}", v(&lc), v(&lo)))
})
} else {
None
};
match k {
None => same += 1,
Some((name, val)) => {
let e = bad.entry(name).or_default();
e.0 += 1;
if e.1.is_empty() {
e.1 = format!("fmt {f} {w}x{h} mips {mips} array {array} layout {lay:#x} flags {flags:#x}{val}");
}
}
}
}
}
}
}
}
println!("{cases} render target / depth cases: {same} the same");
for (k, (n, ex)) in &bad {
println!(" {k}: {n}× – e.g. {ex}");
}
assert!(bad.is_empty());
}
#[test]
#[ignore]
fn print_volumes_lines_and_samples() {
let Some(m) = console() else { return };
let create = proc(m, "XGCreateTextureComputer");
let samples = |mut d: [u8; 0x38], n: u32| {
d[0x24..0x28].copy_from_slice(&n.to_le_bytes());
d
};
for (name, d) in [
("3D rgba8 64x64x16 optimal", desc(4, 64, 64, 16, 1, 28, 0, 0)),
("3D rgba8 64x64x16 0x109", desc(4, 64, 64, 16, 1, 28, 0x109, 0)),
("3D rgba8 64x64x16 0x119", desc(4, 64, 64, 16, 1, 28, 0x119, 0)),
("3D rgba8 64x64x16 0x11A", desc(4, 64, 64, 16, 1, 28, 0x11A, 0)),
("3D rgba8 64x64x16 0x115", desc(4, 64, 64, 16, 1, 28, 0x115, 0)),
("3D rgba8 64x64x16 0x116", desc(4, 64, 64, 16, 1, 28, 0x116, 0)),
("3D rgba8 64x64x16 linear", desc(4, 64, 64, 16, 1, 28, 1, 0)),
("3D rgba8 64x64x16 4 mips", desc(4, 64, 64, 16, 4, 28, 0, 0)),
("3D r8 32x32x32 optimal", desc(4, 32, 32, 32, 1, 61, 0, 0)),
("3D rgba8 64x64x16 UAV", desc(4, 64, 64, 16, 1, 28, 0, 4)),
("1D rgba8 256 optimal", desc(2, 256, 1, 1, 1, 28, 0, 0)),
("1D rgba8 256 0x119", desc(2, 256, 1, 1, 1, 28, 0x119, 0)),
("1D rgba8 256 linear", desc(2, 256, 1, 1, 1, 28, 1, 0)),
("1D rgba8 256 array 4 9 mips", desc(2, 256, 1, 4, 0, 28, 0, 0)),
("2D rgba8 256x256 4x RT", samples(desc(3, 256, 256, 1, 1, 28, 0, 1), 4)),
("2D rgba8 256x256 4x", samples(desc(3, 256, 256, 1, 1, 28, 0, 0), 4)),
("2D d32 256x256 4x DS", samples(desc(3, 256, 256, 1, 1, 40, 0, 2), 4)),
("2D rgba8 256x256 2x RT", samples(desc(3, 256, 256, 1, 1, 28, 0, 1), 2)),
("2D rgba8 256x256 8x RT", samples(desc(3, 256, 256, 1, 1, 28, 0, 1), 8)),
] {
let (hr, l) = unsafe { layout(create, &d) };
let q = |o: usize| u64::from_le_bytes(l[o..o + 8].try_into().unwrap());
let w = |o: usize| u32::from_le_bytes(l[o..o + 4].try_into().unwrap());
println!("{name}: hr {hr:#x} size {:#x} align {:#x} mips {} planes {} dim {}", q(0), q(8), w(0x10), w(0x14), w(0x1B38));
for p in 0..w(0x14).min(4) as usize {
let b = 0x18 + p * 0x6C8;
let head: Vec<String> = (0..0x38).step_by(4).map(|k| format!("{:x}", w(b + k))).collect();
println!(" plane {p}: {}", head.join(" "));
for i in 0..w(0x10).min(4) as usize {
let r = b + 0x38 + i * 0x70;
let row: Vec<String> = (0..0x70).step_by(4).map(|k| format!("{:x}", w(r + k))).collect();
println!(" mip{i}: {}", row.join(" "));
}
}
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
# tests on game data pass without running anything when their variable is not set
$missing = 'XCL_SAMPLE_RPF', 'XCL_SAMPLE_DLLS', 'XCL_SAMPLE_TTPF', 'XCL_SAMPLE_BK2', 'XCL_SAMPLE_BVH4', 'XCL_SAMPLE_AWC', 'XCL_SAMPLE_XG' | Where-Object { -not (Test-Path "env:$_") }
$missing = 'XCL_SAMPLE_RPF', 'XCL_SAMPLE_DLLS', 'XCL_SAMPLE_TTPF', 'XCL_SAMPLE_BK2', 'XCL_SAMPLE_BVH4', 'XCL_SAMPLE_AWC', 'XCL_SAMPLE_XG', 'XCL_SAMPLE_DXC' | Where-Object { -not (Test-Path "env:$_") }
if ($missing) { Write-Host "not set, their tests are skipped: $($missing -join ', ')" }
cargo build --workspace
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }