From bf26412d368fcf6aecf7cc9ba9804aaf2ad3fc92 Mon Sep 17 00:00:00 2001 From: theaustinayers <153482135+theaustinayers@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:15:59 -0500 Subject: [PATCH 1/3] Retail game shows its first menus: depth views, buffers outside unified memory, rect lists Includes open PRs #163, #170 (Sr-0w) and #168 (ShyVortex) as they are; this does not work without them. - d3d12x: CreateDepthStencilView hooked; view and clear-value formats mapped; shader views of depth buffers get the PC's format names, stencil views plane 1; a UAV of a texture without ALLOW_UNORDERED_ACCESS is a null UAV. - list_x: index / vertex buffers in title memory outside the unified-memory windows are mirrored in unified memory, each draw copies what it reads. - bind: DrawInstanced of a rect list is two triangles a rectangle, the fourth corner (v0 + v2 - v1) made on the CPU. - xg: XGTextureAddressComputer #10 as GetResourceTiling (not checked against the console's library). - GetGPUVirtualAddress of a committed texture gives memory to write through. - Debug layer log: 8 messages per id. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/bind.rs | 64 ++++ crates/xcl/src/hle/d3d12x/device_x.rs | 78 ++++- crates/xcl/src/hle/d3d12x/list_x.rs | 183 ++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 443 +++++++++++++++++++++++++- crates/xcl/src/hle/xg.rs | 80 +++++ 5 files changed, 830 insertions(+), 18 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index f2323c5819..22fc6ab6de 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -237,10 +237,73 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } } +/// A DrawInstanced of the console's rect list (three corners of each rectangle, the fourth +/// implied) as two triangles a rectangle; false: not a rect list, or one this cannot expand +/// (the caller draws the three vertices as a triangle – half of each rectangle). +/// +/// The PC has no rect lists. The fourth corner is made here, on the CPU, from the title's +/// vertex data: v3 = v0 + v2 − v1 (seen in a retail title's full-screen passes: (−1,1) (−1,−1) +/// (1,−1) with texture coordinates (0,0) (0,1) (1,1) – the missing corner is (1,1), (1,0)). +/// The vertex layout is not looked at: each 4-byte word that is the same in all three vertices +/// is kept (a packed colour), any other is taken as a float. Vertices a shader makes from the +/// vertex index alone (no vertex buffer) are not expanded. +unsafe fn draw_rects(this: *mut c_void, list: &ID3D12GraphicsCommandList, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) -> bool { + let Some(vbs) = super::list_x::rect_list_state(this) else { return false }; + let rects = (vertices / 3) as usize; + if vbs.is_empty() || rects == 0 || rects > 4096 { + return false; + } + let mut views = Vec::new(); + for &(slot, (va, bytes, stride), _) in &vbs { + let (s, at) = (stride as usize, va as usize + first_vertex as usize * stride as usize); + let len = rects * 3 * s; + if va == 0 || s == 0 || s % 4 != 0 || first_vertex as usize * s + len > bytes as usize || !crate::gpu::shader::readable(at, len) { + return false; + } + let p = allocate_upload_memory(this, rects * 6 * s, 16); + if p.is_null() { + return false; + } + let word = |v: usize, w: usize| (at as *const u8).add(v * s + w * 4).cast::().read_unaligned(); + for r in 0..rects { + let out = p.add(r * 6 * s); + let src = (at as *const u8).add(r * 3 * s); + // v0 v1 v2, then v0 v2 v3 + std::ptr::copy_nonoverlapping(src, out, 3 * s); + std::ptr::copy_nonoverlapping(src, out.add(3 * s), s); + std::ptr::copy_nonoverlapping(src.add(2 * s), out.add(4 * s), s); + for w in 0..s / 4 { + let (a, b, c) = (word(r * 3, w), word(r * 3 + 1, w), word(r * 3 + 2, w)); + let d = if a == b && b == c { a } else { (f32::from_bits(a) + f32::from_bits(c) - f32::from_bits(b)).to_bits() }; + out.add(5 * s + w * 4).cast::().write_unaligned(d); + } + } + views.push((slot, D3D12_VERTEX_BUFFER_VIEW { BufferLocation: super::list_x::pc_va_of(p as u64), SizeInBytes: (rects * 6 * s) as u32, StrideInBytes: stride })); + } + for (slot, v) in &views { + list.IASetVertexBuffers(*slot, Some(&[*v])); + } + list.DrawInstanced(rects as u32 * 6, instances, 0, first_instance); + for &(slot, _, pc) in &vbs { + if let Some(v) = pc { + list.IASetVertexBuffers(slot, Some(&[v])); + } + } + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) == 0 { + crate::xlog_info!("D3D12.X: rect lists are drawn as two triangles a rectangle, the fourth corner made on the CPU"); + } + true +} + /// #12 DrawInstanced pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) { DRAW_ARGS.with(|d| d.set((false, vertices, instances, first_vertex, 0))); if let Some(list) = graphics_bound(this) { + if draw_rects(this, &list, vertices, instances, first_vertex, first_instance) { + return; + } + super::list_x::sync_title_buffers(this, None, first_vertex, vertices, instances); list.DrawInstanced(vertices, instances, first_vertex, first_instance); } } @@ -253,6 +316,7 @@ thread_local! { /// #13 DrawIndexedInstanced pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) { if let Some(list) = prepare_indexed_draw(this, indices, instances, first_index, base_vertex) { + super::list_x::sync_title_buffers(this, Some((first_index, indices, base_vertex)), 0, 0, instances); emit_prepared_indexed_draw(&list, indices, instances, first_index, base_vertex, first_instance); } } diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 403b7af299..16d76f69b9 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -654,10 +654,37 @@ pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { d[8..16].fill(0); // alignment: the driver's let layout = if dim == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32 { D3D12_TEXTURE_LAYOUT_ROW_MAJOR.0 } else { D3D12_TEXTURE_LAYOUT_UNKNOWN.0 }; d[0x2C..0x30].copy_from_slice(&(layout as u32).to_le_bytes()); - d[0x30..0x34].copy_from_slice(&(flags & 0xFF).to_le_bytes()); + // a depth buffer the console also writes as a UAV (GTA VI's 2560x1440 D16S8): the PC refuses + // depth + unordered access together, and the resource got no size + let pc_flags = if flags & 0x2 != 0 { flags & 0xFF & !0x4 } else { flags & 0xFF }; + d[0x30..0x34].copy_from_slice(&pc_flags.to_le_bytes()); + let format = u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()); + d[0x20..0x24].copy_from_slice(&pc_format(format).to_le_bytes()); d } +/// A DXGI format of the console only as the PC's nearest: the 16-bit depth + 8-bit stencil +/// family (118 D16_UNORM_S8_UINT, 119 R16_UNORM_X8_TYPELESS, 120 X16_TYPELESS_G8_UINT) as the +/// 24-bit one (45, 46, 47). The PC driver refuses them: GTA VI's depth buffer got no size +/// (GetResourceAllocationInfo) and the title stopped on its assertion. +/// +/// 86 (B5G5R5A1_UNORM) is a PC format, but not one a PC driver takes for a render target that +/// is also a UAV (a retail title's 2560x1440 target, flags 0x5: CreatePlacedResource refused it, +/// E_INVALIDARG, and the title stopped). It becomes R8G8B8A8_UNORM (28): what shaders write to +/// it and read from it is the same, with more bits; its memory is twice the console's. +pub fn pc_format(f: u32) -> u32 { + match f { + // B5G5R5A1 (86) and B4G4R4A4 (115) render targets (the same title's 2560x1440 ones) + 86 | 115 => 28, + // the console's R10G10B10_7E3_A2_FLOAT / _6E4_A2_FLOAT: half floats hold them + 116 | 117 => 10, + 118 => 45, + 119 => 46, + 120 => 47, + f => f, + } +} + /// device #25 GetResourceAllocationInfo(visible mask, count, descs) → {size, alignment}, /// returned through a hidden pointer. Called the C way – (return buffer, device, …), XDefiant – /// or the C++ way – (device, return buffer, …): whichever argument is the device is `this`. @@ -680,6 +707,10 @@ pub(super) unsafe extern "system" fn get_resource_allocation_info_x(a: *mut c_vo } }; if s == u64::MAX || a == 0 { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: GetResourceAllocationInfo: no size for {:x?} (as the PC's: {:x?})", &x[..0x34], &pc_resource_desc(&x)[..0x34]); + } size = u64::MAX; break; } @@ -752,6 +783,22 @@ fn note_alias(va: usize, x: &[u8; 0x38]) { } } +/// A D3D12_CLEAR_VALUE (format, then 16 bytes of colour or depth + stencil) with a console-only +/// format as the PC's (`pc_format`); None: nothing to change (or no clear value). +pub(super) unsafe fn pc_clear_value(clear: *const c_void) -> Option<[u8; 20]> { + if clear.is_null() || !crate::gpu::shader::readable(clear as usize, 20) { + return None; + } + let mut c = (clear as *const [u8; 20]).read_unaligned(); + let f = u32::from_le_bytes(c[0..4].try_into().unwrap()); + let pc = pc_format(f); + if pc == f { + return None; + } + c[0..4].copy_from_slice(&pc.to_le_bytes()); + Some(c) +} + /// device #44 CreatePlacedResourceX(address, desc, initial state, clear value, riid, resource): /// a resource in title memory. A buffer at a 64 KiB-aligned address in unified memory is that /// memory (placed in its UMA heap); a texture gets a PC texture kept in step with the memory @@ -764,10 +811,19 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); let d = pc_resource_desc(&x); let buffer = u32::from_le_bytes(d[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32; + // the clear value names the console's format too (a 1024x1024 D16S8 depth buffer: 118 with + // the desc already 45 – the PC refused the pair, E_INVALIDARG, and the title stopped) + let pc_clear = pc_clear_value(clear); + let clear = pc_clear.as_ref().map_or(clear, |c| c.as_ptr() as *const c_void); note_alias(va as usize, &x); // console-only state bits (Unicorn Overlord's 4K display target: 0x100000) are not the // PC's: the PC refused the resource (E_INVALIDARG) and the title threw - let state = state & real::PC_RESOURCE_STATES; + let mut state = state & real::PC_RESOURCE_STATES; + // a depth buffer is no UAV on the PC (`pc_resource_desc`): its unordered-access initial state + // (GTA VI's 768x768x6 shadow maps: 0x8) is refused – it starts as a depth target + if u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()) & 0x2 != 0 && state & 0x8 != 0 { + state = (state & !0x8) | 0x10; + } if buffer { if let Some(hr) = real::place_at_title_address(this, va as usize, &d, state, clear, riid, ppv) { return hr; @@ -811,6 +867,10 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, w(0x20), w(0x30) ); + if hr < 0 { + let cf = if clear.is_null() { -1 } else { *(clear as *const i32) }; + crate::xlog_info!("D3D12.X: … its state {state:#x}, clear value format {cf}, as the PC's {:x?}", &d[..0x34]); + } } hr } @@ -916,6 +976,20 @@ mod tests { assert_eq!(u32::from_le_bytes(pc_resource_desc(&x)[0x2C..0x30].try_into().unwrap()), 0); } + #[test] + fn console_depth_buffers_become_pc_ones() { + let mut x = [0u8; 0x38]; + x[0] = 3; // texture 2D + x[0x20] = 118; // D16_UNORM_S8_UINT + x[0x30..0x34].copy_from_slice(&0x8030_0006u32.to_le_bytes()); // depth + UAV + console bits + let d = pc_resource_desc(&x); + let u = |o: usize| u32::from_le_bytes(d[o..o + 4].try_into().unwrap()); + assert_eq!((u(0x20), u(0x30)), (45, 0x2)); + x[0x30..0x34].copy_from_slice(&0x4u32.to_le_bytes()); // a UAV texture keeps it + assert_eq!(u32::from_le_bytes(pc_resource_desc(&x)[0x30..0x34].try_into().unwrap()), 0x4); + assert_eq!((pc_format(119), pc_format(120), pc_format(28)), (46, 47, 28)); + } + #[test] fn derived_pipeline_patches_land_on_the_desc_parts() { use std::mem::{offset_of, size_of}; diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 68cfd4d2e4..e6400ef09e 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -257,6 +257,20 @@ struct Bindings { vertex_titles: std::collections::BTreeMap, /// the title's (address, bytes, format) of the index buffer (`XCL_TRACE_FRAME`) index_title: Option<(u64, u32, i32)>, + /// the title set the console's rect list topology + rect_list: bool, +} + +/// Whether `list` draws rect lists now, and the title's vertex buffers (slot, (address, bytes, stride)). +pub(super) fn rect_list_state(list: *mut c_void) -> Option)>> { + let g = LISTS.lock().unwrap(); + let b = &g.as_ref()?.get(&(list as usize))?.bindings; + b.rect_list.then(|| b.vertex_titles.iter().map(|(&k, &v)| (k, v, b.vertex_buffers.get(&k).copied())).collect()) +} + +/// `pc_va` for other modules. +pub(super) fn pc_va_of(va: u64) -> u64 { + pc_va(va) } /// `XCL_TRACE_FRAME`: the fixed-function state a list last set (topology, first viewport and @@ -415,8 +429,12 @@ pub(super) unsafe extern "system" fn ia_set_topology_x(this: *mut c_void, t: u32 crate::xlog_warn!("D3D12.X: IASetPrimitiveTopology({t}) – a console topology the PC does not have{}", if t == RECT_LIST { ": rect lists are drawn as triangle lists (each rect's first half only)" } else { "" }); } } + let rect = t == RECT_LIST; let t = if t == RECT_LIST { windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32 } else { t }; - with_bindings(this, |b| b.topology = Some(t)); + with_bindings(this, |b| { + b.topology = Some(t); + b.rect_list = rect; + }); pc::(this, PC_IA_SET_PRIMITIVE_TOPOLOGY)(this, t) } @@ -1516,6 +1534,158 @@ fn pc_va(va: u64) -> u64 { real::uma_va_of(va as usize).unwrap_or(va) } +/// `pc_va` for an index or vertex buffer of `bytes` bytes bound on `list`. A retail title also +/// binds buffers in its ordinary memory (a private allocation outside the unified-memory +/// windows – on the console the GPU reads all of the title's memory). The PC's GPU has no +/// address for that (IASetIndexBuffer of it: debug layer message 725, then the device hangs, +/// 0x887a0006), so the bytes are copied into the list's upload memory as they are at the bind; +/// what the title writes there afterwards is not seen. +/// +/// A buffer that stays bound (`mirror`) gets one block of unified memory for good – its +/// *mirror*, the same for every bind of that address and size – and each draw copies the part +/// it reads there first (`sync_title_buffers`), as the title wrote it by then. (A copy of the +/// whole buffer at every bind filled unified memory within two minutes of a retail title's +/// menus, and missed what the title wrote after the bind.) +unsafe fn gpu_va(list: *mut c_void, va: u64, bytes: usize, what: &str, mirror: bool) -> u64 { + let t = pc_va(va); + if t != va || va == 0 || bytes == 0 { + return t; + } + // in a window by number: a PC resource's GPU address + if crate::gpu::uma::get().is_none_or(|u| u.contains(va as usize)) || !crate::gpu::shader::readable(va as usize, bytes) { + return t; + } + if mirror { + if let Some(p) = mirror_of(va, bytes, what) { + return pc_va(p as u64); + } + } + let p = super::bind::allocate_upload_memory(list, bytes, 16); + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if p.is_null() { + if n < 4 { + crate::xlog_warn!("D3D12.X: {what} at {va:#x} ({bytes} bytes) is outside unified memory and there is no room for a copy"); + } + return t; + } + std::ptr::copy_nonoverlapping(va as *const u8, p, bytes); + if n < 4 || n.is_power_of_two() { + crate::xlog_warn!("D3D12.X: {what} at {va:#x} ({bytes} bytes) is outside unified memory – bound as a copy made now (#{n})"); + } + pc_va(p as u64) +} + +/// Ranges of the title's memory with a mirror in unified memory: (start, bytes, mirror). A +/// title binds one buffer at many offsets (a ring it fills through the frame: a retail title's +/// views all end at the buffer's end), so a mirror covers a 64 KiB-aligned range and a view +/// inside a mirrored range uses that mirror at its offset. +static MIRRORS: Mutex> = Mutex::new(Vec::new()); +/// bytes of mirrors made (never freed) +static MIRROR_BYTES: AtomicU64 = AtomicU64::new(0); + +/// Where `[va, va + bytes)` is in a mirror, if it is in one. +fn mirrored(va: u64, bytes: usize) -> Option { + MIRRORS.lock().unwrap().iter().find(|&&(s, l, _)| va >= s && va + bytes as u64 <= s + l as u64).map(|&(s, _, m)| m + (va - s) as usize) +} + +/// The mirror address of the title's buffer at `va`; its range's mirror is made (and filled +/// once) the first time. +unsafe fn mirror_of(va: u64, bytes: usize, what: &str) -> Option { + if let Some(p) = mirrored(va, bytes) { + return Some(p); + } + let mut g = MIRRORS.lock().unwrap(); + let start = va & !0xffff; + let len = ((va + bytes as u64 + 0xffff) & !0xffff) - start; + // only as much as is the title's readable memory (the view itself is) + let (start, len) = if crate::gpu::shader::readable(start as usize, len as usize) { (start, len as usize) } else { (va, bytes) }; + if MIRROR_BYTES.load(Ordering::Relaxed) + len as u64 > 2 << 30 { + return None; + } + let u = crate::gpu::uma::get()?; + let p = match u.has_sparse().then(|| super::sparse::alloc(len, 0x1_0000)).flatten() { + Some((p, _)) => p, + None => u.alloc(len, 0x1_0000)? as usize, + }; + std::ptr::copy_nonoverlapping(start as *const u8, p as *mut u8, len); + g.push((start, len, p)); + let total = MIRROR_BYTES.fetch_add(len as u64, Ordering::Relaxed) + len as u64; + if g.len() <= 8 || g.len().is_power_of_two() { + crate::xlog_warn!("D3D12.X: {what} at {va:#x} ({bytes} bytes) is outside unified memory – {start:#x}..{:#x} mirrored at {p:#x}, each draw copies what it reads ({} mirrors, {} MB)", start + len as u64, g.len(), total >> 20); + } + Some(p + (va - start) as usize) +} + +/// Before a draw on `list`: the parts of mirrored buffers it reads are copied from the title's +/// memory. `indexed`: (first index, index count, base vertex); else `first_vertex`, `vertices`. +pub(super) unsafe fn sync_title_buffers(list: *mut c_void, indexed: Option<(u32, u32, i32)>, first_vertex: u32, vertices: u32, instances: u32) { + if MIRROR_BYTES.load(Ordering::Relaxed) == 0 { + return; + } + let (vbs, ib) = { + let g = LISTS.lock().unwrap(); + let Some(b) = g.as_ref().and_then(|m| m.get(&(list as usize))).map(|s| &s.bindings) else { return }; + (b.vertex_titles.values().copied().collect::>(), b.index_title) + }; + let mirrors: Vec> = { + let mut v: Vec> = vbs.iter().map(|&(va, bytes, _)| mirrored(va, bytes as usize)).collect(); + v.push(ib.and_then(|(va, bytes, _)| mirrored(va, bytes as usize))); + if v.iter().all(Option::is_none) { + return; + } + v + }; + let copy = |va: u64, mirror: usize, bytes: u32, from: u64, len: u64| { + let from = from.min(bytes as u64); + let len = len.min(bytes as u64 - from) as usize; + if len > 0 && crate::gpu::shader::readable(va as usize + from as usize, len) { + std::ptr::copy_nonoverlapping((va + from) as *const u8, (mirror + from as usize) as *mut u8, len); + } + }; + // the vertices read: [lo, hi) + let (lo, hi) = match (indexed, ib) { + (Some((first, count, base)), Some((va, bytes, format))) => { + let size: u64 = if format == DXGI_FORMAT_R32_UINT.0 { 4 } else { 2 }; + let (from, len) = (first as u64 * size, count as u64 * size); + if let Some(m) = mirrors[vbs.len()] { + copy(va, m, bytes, from, len); + } + let n = (len.min((bytes as u64).saturating_sub(from)) / size) as usize; + if n == 0 || !crate::gpu::shader::readable((va + from) as usize, n * size as usize) { + (0, u64::MAX) + } else { + let at = (va + from) as *const u8; + let (mut lo, mut hi) = (u32::MAX, 0u32); + for k in 0..n { + let i = if size == 4 { at.add(4 * k).cast::().read_unaligned() } else { at.add(2 * k).cast::().read_unaligned() as u32 }; + // strip cut values are not vertices + if i == u32::MAX || (size == 2 && i == 0xffff) { + continue; + } + lo = lo.min(i); + hi = hi.max(i); + } + if lo > hi { + return; + } + ((lo as i64 + base as i64).max(0) as u64, (hi as i64 + base as i64 + 1).max(0) as u64) + } + } + (Some(_), None) => (0, u64::MAX), + (None, _) => (first_vertex as u64, first_vertex as u64 + vertices as u64), + }; + for (k, &(va, bytes, stride)) in vbs.iter().enumerate() { + let Some(m) = mirrors[k] else { continue }; + // a buffer stepped by instance is not told apart: with instances, all of it + if instances > 1 || hi == u64::MAX || stride == 0 { + copy(va, m, bytes, 0, bytes as u64); + } else { + copy(va, m, bytes, lo * stride as u64, (hi - lo) * stride as u64); + } + } +} + unsafe fn set_index_buffer(list: *mut c_void, view: Option<&D3D12_INDEX_BUFFER_VIEW>) { let f = pc::(list, PC_IA_SET_INDEX_BUFFER); f(list, view.map_or(std::ptr::null(), |v| v as *const _)); @@ -1580,7 +1750,7 @@ pub(super) unsafe extern "system" fn ia_set_vertex_buffers_x(this: *mut c_void, .map(|k| { let mut v = views.add(k).read_unaligned(); let title = v.BufferLocation; - v.BufferLocation = pc_va(v.BufferLocation); + v.BufferLocation = gpu_va(this, v.BufferLocation, v.SizeInBytes as usize, "vertex buffer", true); if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); let i = N.fetch_add(1, Ordering::Relaxed); @@ -1626,9 +1796,11 @@ pub(super) unsafe extern "system" fn ia_set_index_buffer_x(this: *mut c_void, vi } let mut v = view.read_unaligned(); s.bindings.index_title = Some((v.BufferLocation, v.SizeInBytes, v.Format.0)); - v.BufferLocation = pc_va(v.BufferLocation); - s.index_buffer = Some(v); drop(g); + v.BufferLocation = gpu_va(this, v.BufferLocation, v.SizeInBytes as usize, "index buffer", true); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { + s.index_buffer = Some(v); + } set_index_buffer(this, Some(&v)); } @@ -1648,7 +1820,8 @@ pub(super) unsafe extern "system" fn draw_indexed_x(this: *mut c_void, va: u64, return; }; let bound = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).and_then(|s| s.index_buffer)); - let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: pc_va(va), SizeInBytes: count.saturating_mul(stride), Format: format }; + sync_title_buffers(this, None, 0, 0, 2); + let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: gpu_va(this, va, count.saturating_mul(stride) as usize, "DrawIndexedX indices", false), SizeInBytes: count.saturating_mul(stride), Format: format }; set_index_buffer(this, Some(&view)); super::bind::emit_prepared_indexed_draw(&list, count, 1, 0, 0, 0); set_index_buffer(this, bound.as_ref()); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 408901615a..c3e29bb6f7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -419,10 +419,24 @@ pub fn init() -> Result { } } -/// A debug layer message: errors and warnings into the log (the first 200). +/// A debug layer message: errors and warnings into the log – the first 8 of each message id +/// (3 000 in all). One cap for all of them (200) was used up in seconds by two per-frame state +/// errors of a retail title, 14 s before the message that came with its device removal. unsafe extern "system" fn debug_message(_category: D3D12_MESSAGE_CATEGORY, severity: D3D12_MESSAGE_SEVERITY, id: D3D12_MESSAGE_ID, text: windows::core::PCSTR, _context: *mut c_void) { static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if severity.0 > D3D12_MESSAGE_SEVERITY_WARNING.0 || N.fetch_add(1, Ordering::Relaxed) >= 200 { + static PER_ID: Mutex>> = Mutex::new(None); + if severity.0 > D3D12_MESSAGE_SEVERITY_WARNING.0 { + return; + } + { + let mut g = PER_ID.lock().unwrap(); + let n = g.get_or_insert_with(HashMap::new).entry(id.0).or_insert(0); + *n += 1; + if *n > 8 { + return; + } + } + if N.fetch_add(1, Ordering::Relaxed) >= 3000 { return; } let t = if text.is_null() { String::new() } else { String::from_utf8_lossy(text.as_bytes()).into_owned() }; @@ -1488,13 +1502,94 @@ fn forget_pso(pso: usize) { drop(gone); } -/// resource #11 GetGPUVirtualAddress for console code +/// resource #11 GetGPUVirtualAddress for console code. On the console a texture has an address +/// too: a texture the title placed at its own address answers with it (`title_address`) where +/// the PC's answer is 0 – a retail game turns a texture's address into the CPU pointer it +/// clears it through, and wrote 256 KB at address 0. +/// Memory for a texture the title did not place itself (a committed one), given the first time +/// the title asks for its address. On the console every texture is in unified memory and has +/// an address; a retail title uses it as the CPU pointer it clears the texture through +/// (`memset(address, 0, w * h * 4)` – with the PC's 0, a write to address 0). +/// +/// The block is plain zeroed process memory of a generous size for the PC description: the +/// title's writes land somewhere, but they are NOT uploaded to the texture (it is not one of +/// `title_textures`) – enough for the clears of GPU-written targets seen so far, not for a +/// texture the title fills on the CPU. It is not freed with the resource. +unsafe fn texture_memory(res: *mut c_void) -> Option { + use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE}; + static LOCK: Mutex<()> = Mutex::new(()); + let _g = LOCK.lock().unwrap(); + if let Some(p) = title_address(res as usize) { + return Some(p); + } + let r = ID3D12Resource::from_raw_borrowed(&res)?; + let d = r.GetDesc(); + if d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + return None; + } + // bytes per texel, rounded up by format family (block-compressed: at most 1) + let bpt: u64 = match d.Format.0 { + 1..=4 => 16, + 5..=8 => 12, + 9..=22 => 8, + 23..=47 => 4, + 48..=59 => 2, + 60..=65 => 1, + 70..=84 | 94..=99 => 1, + 85..=93 => 4, + _ => 16, + }; + let texels = d.Width.checked_mul(d.Height as u64)?.checked_mul(d.DepthOrArraySize.max(1) as u64)?; + // + a third for the mips, + a 64 KiB block for the layout's padding + let bytes = (texels.checked_mul(bpt)? * 4 / 3 + 0x1_0000).next_multiple_of(0x1_0000); + if bytes > 1 << 30 { + return None; + } + let p = VirtualAlloc(std::ptr::null(), bytes as usize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as usize; + if p == 0 { + return None; + } + note_title_address(res as usize, p); + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 16 { + crate::xlog_info!( + "D3D12.X: GetGPUVirtualAddress of a committed {}x{} texture (format {}, flags {:#x}, {} mips): {bytes:#x} bytes of memory at {p:#x} for the title to write through (not uploaded)", + d.Width, + d.Height, + d.Format.0, + d.Flags.0, + d.MipLevels + ); + } + Some(p) +} + unsafe extern "system" fn res_gpu_va_x(this: *mut c_void) -> u64 { if let Some((p, _)) = console_buffer(this as usize) { return p as u64; } let f: unsafe extern "system" fn(*mut c_void) -> u64 = std::mem::transmute(orig_fn(this, 11)); - f(this) + match f(this) { + 0 => { + let mut va = title_address(this as usize).map_or(0, |va| va as u64); + if va == 0 { + va = texture_memory(this).map_or(0, |p| p as u64); + } + if va == 0 { + // a texture with no address for the title: it may go on to write through it + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 12 { + let d = ID3D12Resource::from_raw_borrowed(&this).map(|r| r.GetDesc()); + crate::xlog_warn!( + "D3D12.X: GetGPUVirtualAddress of {this:p} is 0 – not a buffer, not placed at a title address: {:?}", + d.map(|d| (d.Dimension.0, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels, d.Format.0, d.Flags.0)) + ); + } + } + va + } + va => va, + } } fn note_buffer_view() { @@ -1626,7 +1721,78 @@ unsafe extern "system" fn heap_release(this: *mut c_void) -> u32 { n } +/// A view description (its format is its first field) whose format is one `pc_format` replaces, +/// with the PC's: the resource was made with it, and a view in the console's format is refused. +unsafe fn pc_view_format(desc: *const T) -> Option { + if desc.is_null() { + return None; + } + let f = (desc as *const u32).read_unaligned(); + let pc = super::device_x::pc_format(f); + if pc == f { + return None; + } + let mut v = std::ptr::read_unaligned(desc); + (&mut v as *mut T as *mut u32).write_unaligned(pc); + Some(v) +} + +/// The format name the PC wants for a shader's view of a depth buffer. The console takes the +/// plain names (R32_FLOAT of a D32S8 buffer, R16_UNORM of a D16S8 one that is D24S8 here); the +/// PC wants the family's own (R32_FLOAT_X8X24_TYPELESS, R24_UNORM_X8_TYPELESS …) and treats +/// the plain ones as an illegal call (a retail title: device removal). `view` 0 is "the +/// resource's format", which no typeless or depth resource can be viewed as. +fn pc_depth_view_format(resource: i32, view: i32) -> i32 { + match (resource, view) { + // R32G8X24_TYPELESS / D32_FLOAT_S8X24_UINT: depth as 21, stencil as 22 + (19..=22, 0 | 19 | 20 | 39 | 40 | 41) => 21, + (19..=22, 61 | 62) => 22, + // R24G8_TYPELESS / D24_UNORM_S8_UINT: depth as 46, stencil as 47 + (44..=47, 0 | 44 | 45 | 41 | 53 | 54 | 55 | 56) => 46, + (44..=47, 61 | 62) => 47, + // R32_TYPELESS / D32_FLOAT, R16_TYPELESS / D16_UNORM + (39 | 40, 0 | 39 | 40) => 41, + (53 | 55, 0 | 53 | 55) => 56, + (_, v) => v, + } +} + +/// `desc` with the PC's format name for a view of the depth buffer `res` (None: as it is). +unsafe fn pc_depth_srv(res: *mut c_void, desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC) -> Option { + let d = desc.as_ref()?; + let rf = ID3D12Resource::from_raw_borrowed(&res)?.GetDesc().Format.0; + let f = pc_depth_view_format(rf, d.Format.0); + // the PC reads stencil from plane 1; the console takes plane 0 with a stencil format + let stencil = matches!(f, 22 | 47) && matches!(rf, 19..=22 | 44..=47); + if f == d.Format.0 && !stencil { + return None; + } + let mut v = std::ptr::read(d); + v.Format.0 = f; + if stencil { + if v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D { + v.Anonymous.Texture2D.PlaneSlice = 1; + } else if v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY { + v.Anonymous.Texture2DArray.PlaneSlice = 1; + } + } + Some(v) +} + +/// The PC's CreateDepthStencilView: a view in a console-only format (D16S8, 118) as the PC's. +unsafe extern "system" fn dev_create_dsv(this: *mut c_void, res: *mut c_void, desc: *const D3D12_DEPTH_STENCIL_VIEW_DESC, handle: usize) { + type F = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_DEPTH_STENCIL_VIEW_DESC, usize); + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateDepthStencilView"))); + let pc_view = pc_view_format(desc); + let desc = pc_view.as_ref().map_or(desc, |d| d as *const D3D12_DEPTH_STENCIL_VIEW_DESC); + f(this, res, desc, handle) +} + unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, cpu: u64) { + let pc_view = pc_view_format(desc); + let desc = pc_view.as_ref().map_or(desc, |d| d as *const D3D12_SHADER_RESOURCE_VIEW_DESC); + let pc_depth = pc_depth_srv(res, desc); + let desc = pc_depth.as_ref().map_or(desc, |d| d as *const D3D12_SHADER_RESOURCE_VIEW_DESC); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, desc, cpu) }; // Raytracing acceleration structure SRV (pResource == NULL, Location == console GPU VA): @@ -1775,7 +1941,71 @@ fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI crate::gpu::desc::buffer_words(va + first * elem as u64, stride, records, fmt) } +/// The view to create with no resource (a null UAV: writes go nowhere, reads give 0) when +/// `res` is a texture the PC did not make with ALLOW_UNORDERED_ACCESS; None: `res` takes UAVs. +/// +/// A retail title makes UAVs of its depth buffers (2560x1440 D16S8, 768² - 2048² shadow maps +/// that are depth + UAV on the console). CreateUnorderedAccessView of them is "an illegal +/// operation" to D3D12 and the device is removed (0x887a0001) – seen with the debug layer as +/// message 340 just before RemoveDevice. What compute writes to those buffers is lost until +/// they get a UAV twin kept in step with the depth buffer. +unsafe fn pc_null_uav(res: *mut c_void, desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC) -> Option { + use windows::Win32::Graphics::Dxgi::Common::*; + let r = ID3D12Resource::from_raw_borrowed(&res)?; + let rd = r.GetDesc(); + if rd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || rd.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0 { + return None; + } + let mut v: D3D12_UNORDERED_ACCESS_VIEW_DESC = match desc.as_ref() { + Some(d) => std::ptr::read(d), + None => { + let mut v: D3D12_UNORDERED_ACCESS_VIEW_DESC = std::mem::zeroed(); + if rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { + v.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + v.Anonymous.Texture3D.WSize = rd.DepthOrArraySize as u32; + } else if rd.DepthOrArraySize > 1 { + v.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + v.Anonymous.Texture2DArray.ArraySize = rd.DepthOrArraySize as u32; + } else { + v.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + } + v + } + }; + // a format a UAV may have: the view's own when it is a colour format, else by the family + // of the resource's (16-bit depth → R16_UNORM, the others → R32_FLOAT) + let f = if v.Format == DXGI_FORMAT_UNKNOWN { rd.Format } else { v.Format }; + v.Format = match f.0 { + 53..=55 => DXGI_FORMAT_R16_UNORM, // R16_TYPELESS, R16_FLOAT (kept below), D16_UNORM + 19..=22 | 39 | 40 | 44..=47 | 0 => DXGI_FORMAT_R32_FLOAT, // D32S8 / D32 / D24S8 families, unknown + _ => f, + }; + if f == DXGI_FORMAT_R16_FLOAT { + v.Format = f; + } + // a view of the stencil plane (plane 1): a null view has one plane + if v.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2D { + v.Anonymous.Texture2D.PlaneSlice = 0; + } else if v.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY { + v.Anonymous.Texture2DArray.PlaneSlice = 0; + } + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 6 { + crate::xlog_warn!( + "D3D12.X: UAV of a {}x{} texture (format {}, flags {:#x}) the PC made without ALLOW_UNORDERED_ACCESS – a null UAV (format {}): compute writes to it are lost", + rd.Width, + rd.Height, + rd.Format.0, + rd.Flags.0, + v.Format.0 + ); + } + Some(v) +} + unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, counter: *mut c_void, desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, cpu: u64) { + let pc_view = pc_view_format(desc); + let desc = pc_view.as_ref().map_or(desc, |d| d as *const D3D12_UNORDERED_ACCESS_VIEW_DESC); super::present::note_use(res as usize, super::present::USE_UAV); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 19)); if super::present::trace_frame() { @@ -1785,8 +2015,16 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, crate::xlog_info!("frame trace: UAV of render target {res:p} {:?} at {cpu:#x}: console slot {:?}, view {:?}", d.map(|d| (d.Width, d.Height, d.Format.0)), s.as_ref().map(|s| (s.index, s.pc_uav, s.at)), desc.as_ref().map(|v| (v.Format.0, v.ViewDimension.0))); } } - let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, counter, desc, cpu) }; - f(this, res, counter, desc, slot.pc_uav); + // a UAV of a resource that is no UAV resource on the PC (a console depth buffer that is + // also written by compute – `pc_resource_desc` drops the flag, the PC refuses the pair): + // the call is illegal there and removes the device. The slot gets a null UAV instead. + let null_view = pc_null_uav(res, desc); + let (res_pc, counter_pc, desc_pc) = match &null_view { + Some(v) => (std::ptr::null_mut(), std::ptr::null_mut(), v as *const D3D12_UNORDERED_ACCESS_VIEW_DESC), + None => (res, counter, desc), + }; + let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res_pc, counter_pc, desc_pc, cpu) }; + f(this, res_pc, counter_pc, desc_pc, slot.pc_uav); super::console_heap::publish(&slot, true); super::console_heap::note_resource(&slot, res as usize); let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else { @@ -1820,11 +2058,14 @@ 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 this slot too if dim == 4 { + let sf = pc_depth_view_format(rd.Format.0, if format == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN { rd.Format.0 } else { format.0 }); + // the stencil of a depth buffer is the PC's plane 1 + let plane = u32::from(matches!(sf, 22 | 47) && matches!(rd.Format.0, 19..=22 | 44..=47)); let srv = D3D12_SHADER_RESOURCE_VIEW_DESC { - Format: if format == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN { rd.Format } else { format }, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(sf), ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, - Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: mip, MipLevels: 1, PlaneSlice: 0, ResourceMinLODClamp: 0.0 } }, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: mip, MipLevels: 1, PlaneSlice: plane, ResourceMinLODClamp: 0.0 } }, }; 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)); g(this, res, &srv, slot.pc_srv); @@ -1901,6 +2142,9 @@ unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, pro ); crate::xlog_info!(" desc (dwords): {:x?}", (0..16).map(|k| w(4 * k)).collect::>()); } + // a clear value in a console-only format (D16S8) as the PC's, like the desc's + let pc_clear = super::device_x::pc_clear_value(clear as *const c_void); + let clear = pc_clear.as_ref().map_or(clear, |c| c.as_ptr() as usize); // console texture layouts (seen: 0x101, with 3 at +52) are not PC ones: the driver picks // its own (UNKNOWN); the console layout matters only where console code reads the memory let mut pc_desc = [0u8; 56]; @@ -1976,6 +2220,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ("CreateDescriptorHeap", dev_create_descriptor_heap as usize), ("CreateRootSignature", dev_create_root_signature as usize), ("CreateRenderTargetView", dev_create_rtv as usize), + ("CreateDepthStencilView", dev_create_dsv as usize), ("CreateCommittedResource", dev_create_committed_resource as usize), ("CreateHeap", dev_create_heap as usize), ("CreatePlacedResource", dev_create_placed_resource as usize), @@ -3478,12 +3723,25 @@ unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: * } if let Some(a) = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS.0 as u32).and_then(|s| payload_shader(s.1)) { let types: Vec = subs.iter().map(|s| s.0).collect(); + // Refused, the title got no pipeline and wrote to address 0 a moment later (a retail + // title, ~3 minutes in, five such pipelines). Its shader pack has no amplification + // programs at all – what sits in the AS slot is another mesh-stage container – so until + // the console's numbering here is known the pipeline is made from the MS slot alone: + // it exists (the title goes on), what it draws may be wrong. note_translation_error(format!( - "mesh pipeline with AS {:016x} (MS {:016x}) – not supported yet; subobjects {types:?}", + "mesh pipeline with AS {:016x} (MS {:016x}) – the AS slot is ignored; subobjects {types:?}", crate::gpu::shader::fnv64(a), crate::gpu::shader::fnv64(ms) )); - return Some(E_INVALIDARG); + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!( + "D3D12.X: mesh pipeline with a shader in the AS slot ({} B, console: {}) – made from its MS slot only ({} B)", + a.len(), + is_console(a), + ms.len() + ); + } } let ps = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32).and_then(|s| payload_shader(s.1)); let (tp, (ps, ps_samplers)) = match (console_mesh(ms, ps, wave32_only(this)), two_pass_ps(ps, wave32_only(this))) { @@ -3586,6 +3844,106 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE finish_two_pass(this, &out, tp, rs, "GS", riid, ppv) } +/// A copy of the stream with its amplification / mesh shader subobjects numbered as the PC's +/// (AS 24, MS 25) by the program kind in their bytecode, when the title's differ. GTA VI's +/// mesh pipelines carry their mesh shader (kind 13) as type 24: XCL found no MS, did not +/// translate them and the driver refused them ("CreateAmplificationShader: ms_6_6"). +unsafe fn pc_stream_types(desc: *const c_void) -> Option> { + if !crate::gpu::shader::readable(desc as usize, 16) { + return None; + } + let (size, base) = (*(desc as *const usize), *((desc as usize + 8) as *const usize)); + if !crate::gpu::shader::readable(base, size) { + return None; + } + let mut buf = std::slice::from_raw_parts(base as *const u8, size).to_vec(); + let mut changed = false; + let mut off = 0usize; + while off + 8 <= size { + let ty = u32::from_le_bytes(buf[off..off + 4].try_into().ok()?); + let Some((psize, palign)) = super::null::subobject_payload(ty) else { break }; + let poff = if palign == 8 { 8 } else { 4 }; + if ty == 24 || ty == 25 { + let want = buf.get(off + poff..off + poff + psize).and_then(|p| payload_shader(p)).and_then(program_kind).and_then(|k| match k { + 13 => Some(25u32), + 14 => Some(24u32), + _ => None, + }); + if let Some(w) = want.filter(|&w| w != ty) { + buf[off..off + 4].copy_from_slice(&w.to_le_bytes()); + changed = true; + } + } + // the console's formats (D16S8: 118) and rect-list topology type (19) as the PC's + let at = off + poff; + let words = match ty { + 15 => 8, // RENDER_TARGET_FORMATS: RTFormats[8], NumRenderTargets + 16 => 1, // DEPTH_STENCIL_FORMAT + _ => 0, + }; + for k in 0..words { + let o = at + 4 * k; + let f = u32::from_le_bytes(buf.get(o..o + 4)?.try_into().ok()?); + let pc = super::device_x::pc_format(f); + if pc != f { + buf[o..o + 4].copy_from_slice(&pc.to_le_bytes()); + changed = true; + } + } + if ty == 14 && buf.get(at..at + 4)? == 19u32.to_le_bytes() { + buf[at..at + 4].copy_from_slice(&3u32.to_le_bytes()); // TRIANGLE + changed = true; + } + off += (poff + psize + 7) & !7; + } + if changed { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) == 0 { + crate::xlog_info!("D3D12.X: pipeline streams with the console's numbering (mesh shader as subobject 24), formats or topology type – made the PC's"); + } + Some(buf) + } else { + None + } +} + +/// A refused stream's subobject types and, for its shaders, the program kind in their bytecode +/// (DXIL / DXBC version word: 0 PS, 1 VS, 2 GS, 3 HS, 4 DS, 5 CS, 13 MS, 14 AS). +unsafe fn log_stream_shapes(desc: *const c_void) { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) >= 6 || !crate::gpu::shader::readable(desc as usize, 16) { + return; + } + let (size, base) = (*(desc as *const usize), *((desc as usize + 8) as *const usize)); + if !crate::gpu::shader::readable(base, size) { + return; + } + let subs = known_subobjects(std::slice::from_raw_parts(base as *const u8, size)); + let shapes: Vec = subs + .iter() + .map(|(ty, p)| match [1, 2, 3, 4, 5, 6, 24, 25].contains(ty).then(|| payload_shader(p)).flatten() { + Some(code) => format!("{ty}:kind {}", program_kind(code).map_or("?".to_string(), |k| k.to_string())), + None => ty.to_string(), + }) + .collect(); + crate::xlog_warn!("D3D12.X: refused PSO stream ({size:#x} bytes): subobjects {shapes:?}"); +} + +/// The program kind of a DXIL / DXBC container (its first program part's version word >> 16). +fn program_kind(code: &[u8]) -> Option { + let u = |o: usize| code.get(o..o + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); + if code.get(0..4)? != b"DXBC" { + return None; + } + for k in 0..u(28)? as usize { + let off = u(32 + 4 * k)? as usize; + if matches!(code.get(off..off + 4)?, b"DXIL" | b"SHDR" | b"SHEX") { + return Some(u(off + 8)? >> 16); + } + } + None +} + /// Rewrite a pipeline state stream with stand-in shaders. None if not possible. unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { let size = *(desc as *const usize); @@ -3604,7 +3962,10 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { let poff = if palign == 8 { 8 } else { 4 }; let at = off + poff; let put = |buf: &mut Vec, b: &[u8]| { - buf[at..at + 8].copy_from_slice(&(b.as_ptr() as u64).to_le_bytes()); + // no shader: a null pointer – an empty slice's is dangling (0x1), which the driver + // refused (GTA VI's mesh stand-ins, 0x80070057) and the debug layer read + let ptr = if b.is_empty() { 0 } else { b.as_ptr() as u64 }; + buf[at..at + 8].copy_from_slice(&ptr.to_le_bytes()); buf[at + 8..at + 16].copy_from_slice(&(b.len() as u64).to_le_bytes()); }; match ty { @@ -3626,6 +3987,12 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { /// `list_x::RECT_LIST`) is TRIANGLE, as those draws become triangle lists; UNDEFINED (a stream /// without one) is TRIANGLE, or PATCH with a hull shader – the PC refuses both with a VS. fn pc_topology_type(g: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC) { + // the console's own depth format DXGI_FORMAT_D16_UNORM_S8_UINT (118) is not the PC's: the + // driver refuses the pipeline (GTA VI's); D24_UNORM_S8_UINT has the depth and the stencil + g.DSVFormat.0 = super::device_x::pc_format(g.DSVFormat.0 as u32) as i32; + for f in g.RTVFormats.iter_mut() { + f.0 = super::device_x::pc_format(f.0 as u32) as i32; + } if !(1..=4).contains(&g.PrimitiveTopologyType.0) { g.PrimitiveTopologyType = if g.HS.pShaderBytecode.is_null() { D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE } else { D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH }; } @@ -3769,6 +4136,10 @@ unsafe fn put(to: &mut T, from: &[u8]) { pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { super::null::capture_stream_desc(desc as *const u8); + // the console's stream numbers its mesh shader 24 (the PC's AS): as the PC's from here on + let pc_types = pc_stream_types(desc); + let pc_desc: [usize; 2] = pc_types.as_ref().map_or([0, 0], |b| [b.len(), b.as_ptr() as usize]); + let desc = if pc_types.is_some() { pc_desc.as_ptr() as *const c_void } else { desc }; let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_mesh_stream(this, desc, riid, ppv)) } else { (translated_mesh_stream(this, desc, riid, ppv), false) }; if missed { @@ -3797,6 +4168,9 @@ pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void let new_desc: [usize; 2] = [buf.len(), buf.as_ptr() as usize]; let hr2 = finish_pso(this, f, new_desc.as_ptr() as *const c_void, riid, ppv); note_fallback("PSO stream", hr, hr2 >= 0); + if hr2 < 0 { + log_stream_shapes(desc); + } if hr2 >= 0 { hr2 } else { @@ -3847,6 +4221,8 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, desc: *const c_void, handle: usize) { 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"))); + let pc_view = pc_view_format(desc as *const D3D12_RENDER_TARGET_VIEW_DESC); + let desc = pc_view.as_ref().map_or(desc, |d| d as *const D3D12_RENDER_TARGET_VIEW_DESC as *const c_void); f(this, res, desc, handle); super::present::note_rtv(handle, res); if super::present::trace_frame() { @@ -4583,3 +4959,48 @@ mod queue_tests { QUEUE_OLDER.store(false, Ordering::Release); } } + +#[cfg(test)] +mod stream_tests { + use super::*; + + /// a DXBC container with one DXIL part of program kind `kind` + fn container(kind: u32) -> Vec { + let mut c = Vec::new(); + c.extend_from_slice(b"DXBC"); + c.extend_from_slice(&[0; 16]); // hash + c.extend_from_slice(&1u32.to_le_bytes()); // version + c.extend_from_slice(&64u32.to_le_bytes()); // size + c.extend_from_slice(&1u32.to_le_bytes()); // parts + c.extend_from_slice(&36u32.to_le_bytes()); // part 0 at 36 + c.extend_from_slice(b"DXIL"); + c.extend_from_slice(&20u32.to_le_bytes()); + c.extend_from_slice(&(kind << 16 | 0x66).to_le_bytes()); + c.resize(64, 0); + c + } + + #[test] + fn console_mesh_streams_become_pc_ones() { + let ms = container(13); + assert_eq!(program_kind(&ms), Some(13)); + assert_eq!(program_kind(b"not a shader"), None); + // MS as type 24, DSV format 118, topology type 19 + let mut out = StreamOut::default(); + out.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, &ms); + out.raw(16, &118u32.to_le_bytes(), false); + out.raw(14, &19u32.to_le_bytes(), false); + let desc: [usize; 2] = [out.0.len(), out.0.as_ptr() as usize]; + let buf = unsafe { pc_stream_types(desc.as_ptr() as *const c_void) }.expect("renumbered"); + let subs = stream_subobjects(&buf).unwrap(); + let types: Vec = subs.iter().map(|s| s.0).collect(); + assert_eq!(types, [25, 16, 14]); + assert_eq!(u32::from_le_bytes(subs[1].1.try_into().unwrap()), 45); + assert_eq!(u32::from_le_bytes(subs[2].1.try_into().unwrap()), 3); + // a PC stream is left alone + let mut pc = StreamOut::default(); + pc.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, &ms); + let desc: [usize; 2] = [pc.0.len(), pc.0.as_ptr() as usize]; + assert!(unsafe { pc_stream_types(desc.as_ptr() as *const c_void) }.is_none()); + } +} diff --git a/crates/xcl/src/hle/xg.rs b/crates/xcl/src/hle/xg.rs index 234f964921..e2b0a210a1 100644 --- a/crates/xcl/src/hle/xg.rs +++ b/crates/xcl/src/hle/xg.rs @@ -484,6 +484,7 @@ fn vtbl() -> &'static [usize] { not_implemented as usize, copy_into as usize, copy_from as usize, + get_resource_tiling as usize, ]; for i in v.len()..12 { let (stub, _) = crate::stubs::make_stub_info("xg_xs.dll", &format!("XGTextureAddressComputer::#{i}"), E_NOTIMPL as u32 as u64); @@ -497,6 +498,85 @@ unsafe fn tex<'a>(p: *mut c_void) -> &'a Texture { &(*(p as *const Computer)).tex } +/// #10, as a retail game calls it: D3D12's `GetResourceTiling(&tiles, &packed mips, &tile shape, +/// &count, first, tilings)` – how a texture the title keeps partly resident (streaming) is cut +/// into tiles. As a stub its outputs stayed zero and the title's allocator stopped at a +/// breakpoint minutes later. +/// +/// NOT checked against the console's library (the other answers are): it is derived from the +/// same GFX10 model, so it agrees with the offsets `GetResourceLayout` gives – a tile is one +/// block of the texture's swizzle mode, the levels in the mip tail are the packed mips (one +/// tile), a level's tiles are its padded size in blocks and start at its offset. +unsafe extern "system" fn get_resource_tiling(this: *mut c_void, tiles: *mut u32, packed: *mut u8, shape: *mut u32, count: *mut u32, first: u32, out: *mut u8) -> HRESULT { + let Some(s) = tex(this).texels() else { return E_NOTIMPL }; + let l = &s.chain.layout; + let block = l.block_bytes as u64; + if block == 0 || l.block_w == 0 || l.block_h == 0 { + return E_NOTIMPL; + } + let mips = s.chain.levels.len(); + let standard = s.first_tail.min(mips); + let slices = s.array.max(1) as usize; + let slice_tiles = (s.chain.slice_bytes as u64 / block) as u32; + let total = (s.size() / block) as u32; + if !tiles.is_null() { + *tiles = total; + } + if !packed.is_null() { + // D3D12_PACKED_MIP_INFO: u8 standard mips, u8 packed mips, u32 tiles for them, u32 their first tile + let p = std::slice::from_raw_parts_mut(packed, 12); + p.fill(0); + p[0] = standard as u8; + p[1] = (mips - standard) as u8; + if let Some(m) = s.chain.levels.get(standard) { + p[4..8].copy_from_slice(&1u32.to_le_bytes()); + p[8..12].copy_from_slice(&((m.tail.unwrap_or(m.offset) as u64 / block) as u32).to_le_bytes()); + } + } + if !shape.is_null() { + *shape = l.block_w as u32 * s.side; + *shape.add(1) = l.block_h as u32 * s.side; + *shape.add(2) = 1; + } + let mut written = 0u32; + if !count.is_null() { + let cap = *count; + if !out.is_null() { + let subresources = (mips * slices) as u32; + while written < cap && first.saturating_add(written) < subresources { + let sub = (first + written) as usize; + let (mip, slice) = (sub % mips, sub / mips); + // D3D12_SUBRESOURCE_TILING: u32 width, u16 height, u16 depth in tiles, u32 first tile + let (w, h, d, start) = if mip < standard { + let (pw, ph) = s.padded(mip); + ((pw / l.block_w) as u32, (ph / l.block_h) as u16, 1u16, slice as u32 * slice_tiles + (s.chain.levels[mip].offset as u64 / block) as u32) + } else { + (0, 0, 0, u32::MAX) // a packed mip + }; + let o = std::slice::from_raw_parts_mut(out.add(written as usize * 12), 12); + o[0..4].copy_from_slice(&w.to_le_bytes()); + o[4..6].copy_from_slice(&h.to_le_bytes()); + o[6..8].copy_from_slice(&d.to_le_bytes()); + o[8..12].copy_from_slice(&start.to_le_bytes()); + written += 1; + } + } + *count = written; + } + static N: AtomicU32 = AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 6 { + crate::xlog_info!( + "xg: GetResourceTiling of a {}x{} texture ({mips} mips, {slices} slices, mode {}): {total} tiles of {}x{} pixels, {standard} standard mips, {written} tilings written (from XCL's layout model – not checked against the console's library)", + s.width, + s.height, + s.mode, + l.block_w as u32 * s.side, + l.block_h as u32 * s.side + ); + } + S_OK +} + /// `HRESULT XGCreateTextureComputer(const D3D12_RESOURCE_DESC*, XGTextureAddressComputer**)` /// `HRESULT XGSuggestSwizzleMode(const D3D12_RESOURCE_DESC*, UINT, D3D12_TEXTURE_LAYOUT* out)` /// (a newer library's; a retail game passes 0 and its desc's own layout field as `out`): the explicit From fa79d460360145827dbd61e29f8b06ff0c7e4eb5 Mon Sep 17 00:00:00 2001 From: theaustinayers <153482135+theaustinayers@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:39:02 -0500 Subject: [PATCH 2/3] Buffer mirrors: review fixes (Kalmarv on ivall/xcl#195) - mirror_of looks again under the lock: two lists binding one new range at once shared no mirror, and the second was never synced. - A draw with a first instance other than 0 copies the whole buffer (a per-instance buffer was synced by the vertex range). - 0xffff / 0xffffffff count as indices (they are cut values only for strips; a wider range only copies more). - A vertex range past the buffer copies the whole buffer. - The 2 GiB cap is logged when it is reached. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/bind.rs | 4 ++-- crates/xcl/src/hle/d3d12x/list_x.rs | 23 ++++++++++++++++------- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 22fc6ab6de..b95e975719 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -303,7 +303,7 @@ pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: if draw_rects(this, &list, vertices, instances, first_vertex, first_instance) { return; } - super::list_x::sync_title_buffers(this, None, first_vertex, vertices, instances); + super::list_x::sync_title_buffers(this, None, first_vertex, vertices, if first_instance != 0 { instances.max(2) } else { instances }); list.DrawInstanced(vertices, instances, first_vertex, first_instance); } } @@ -316,7 +316,7 @@ thread_local! { /// #13 DrawIndexedInstanced pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) { if let Some(list) = prepare_indexed_draw(this, indices, instances, first_index, base_vertex) { - super::list_x::sync_title_buffers(this, Some((first_index, indices, base_vertex)), 0, 0, instances); + super::list_x::sync_title_buffers(this, Some((first_index, indices, base_vertex)), 0, 0, if first_instance != 0 { instances.max(2) } else { instances }); emit_prepared_indexed_draw(&list, indices, instances, first_index, base_vertex, first_instance); } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index e6400ef09e..0370f303d6 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -948,15 +948,16 @@ pub(super) unsafe fn execute_with_waits(lists: &[*mut c_void], mut submit: impl /// command list #60 CopyMemoryToMemoryX(destination, source, size, flags) pub(super) unsafe extern "system" fn copy_memory_x(this: *mut c_void, dst: u64, src: u64, size: u64, _flags: u32) { - note_gpu_write("CopyMemoryToMemoryX", dst as usize, size); static N: AtomicU64 = AtomicU64::new(0); const W: &str = "CopyMemoryToMemoryX"; if size == 0 || !size.is_multiple_of(4) { return warn(&N, W, format_args!("size {size:#x} is not a non-zero multiple of 4")); } let (Some((d, doff)), Some((s, soff))) = (real::uma_window_buffer(dst as usize, size as usize), real::uma_window_buffer(src as usize, size as usize)) else { + note_gpu_write("CopyMemoryToMemoryX", dst as usize, size); return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) is not in unified memory")); }; + note_gpu_write("CopyMemoryToMemoryX", dst as usize, size); if d == s && dst < src + size && src < dst + size { return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) overlap")); } @@ -1596,11 +1597,20 @@ unsafe fn mirror_of(va: u64, bytes: usize, what: &str) -> Option { return Some(p); } let mut g = MIRRORS.lock().unwrap(); + // again under the lock: two lists binding one new range at once must share a mirror (a + // second one would never be synced – every later lookup finds the first) + if let Some(&(s, _, m)) = g.iter().find(|&&(s, l, _)| va >= s && va + bytes as u64 <= s + l as u64) { + return Some(m + (va - s) as usize); + } let start = va & !0xffff; let len = ((va + bytes as u64 + 0xffff) & !0xffff) - start; // only as much as is the title's readable memory (the view itself is) let (start, len) = if crate::gpu::shader::readable(start as usize, len as usize) { (start, len as usize) } else { (va, bytes) }; if MIRROR_BYTES.load(Ordering::Relaxed) + len as u64 > 2 << 30 { + static FULL: AtomicBool = AtomicBool::new(false); + if !FULL.swap(true, Ordering::Relaxed) { + crate::xlog_warn!("D3D12.X: 2 GiB of mirrors for buffers outside unified memory – further ones ({what} at {va:#x}) are bound as a copy made at the bind, which later writes do not reach"); + } return None; } let u = crate::gpu::uma::get()?; @@ -1659,10 +1669,8 @@ pub(super) unsafe fn sync_title_buffers(list: *mut c_void, indexed: Option<(u32, let (mut lo, mut hi) = (u32::MAX, 0u32); for k in 0..n { let i = if size == 4 { at.add(4 * k).cast::().read_unaligned() } else { at.add(2 * k).cast::().read_unaligned() as u32 }; - // strip cut values are not vertices - if i == u32::MAX || (size == 2 && i == 0xffff) { - continue; - } + // (a strip's cut value counts as an index: whether 0xffff is one is the + // topology's to say, and a range too wide only copies more) lo = lo.min(i); hi = hi.max(i); } @@ -1677,8 +1685,9 @@ pub(super) unsafe fn sync_title_buffers(list: *mut c_void, indexed: Option<(u32, }; for (k, &(va, bytes, stride)) in vbs.iter().enumerate() { let Some(m) = mirrors[k] else { continue }; - // a buffer stepped by instance is not told apart: with instances, all of it - if instances > 1 || hi == u64::MAX || stride == 0 { + // a buffer stepped by instance is not told apart: with instances (callers pass more + // than 1 for a first instance other than 0 too), all of it + if instances > 1 || hi == u64::MAX || stride == 0 || hi.saturating_mul(stride as u64) > bytes as u64 { copy(va, m, bytes, 0, bytes as u64); } else { copy(va, m, bytes, lo * stride as u64, (hi - lo) * stride as u64); From f26a230c6474e420149663c65654a580d45d358b Mon Sep 17 00:00:00 2001 From: theaustinayers <153482135+theaustinayers@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:39:30 -0500 Subject: [PATCH 3/3] xg: XGTextureAddressComputer #10 left to #192 #192 reads the method from the console library; the version here was derived from the layout model and differs from it for 4 KiB modes, 3D textures and packed levels (review on #195). Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/xg.rs | 80 ---------------------------------------- 1 file changed, 80 deletions(-) diff --git a/crates/xcl/src/hle/xg.rs b/crates/xcl/src/hle/xg.rs index e2b0a210a1..234f964921 100644 --- a/crates/xcl/src/hle/xg.rs +++ b/crates/xcl/src/hle/xg.rs @@ -484,7 +484,6 @@ fn vtbl() -> &'static [usize] { not_implemented as usize, copy_into as usize, copy_from as usize, - get_resource_tiling as usize, ]; for i in v.len()..12 { let (stub, _) = crate::stubs::make_stub_info("xg_xs.dll", &format!("XGTextureAddressComputer::#{i}"), E_NOTIMPL as u32 as u64); @@ -498,85 +497,6 @@ unsafe fn tex<'a>(p: *mut c_void) -> &'a Texture { &(*(p as *const Computer)).tex } -/// #10, as a retail game calls it: D3D12's `GetResourceTiling(&tiles, &packed mips, &tile shape, -/// &count, first, tilings)` – how a texture the title keeps partly resident (streaming) is cut -/// into tiles. As a stub its outputs stayed zero and the title's allocator stopped at a -/// breakpoint minutes later. -/// -/// NOT checked against the console's library (the other answers are): it is derived from the -/// same GFX10 model, so it agrees with the offsets `GetResourceLayout` gives – a tile is one -/// block of the texture's swizzle mode, the levels in the mip tail are the packed mips (one -/// tile), a level's tiles are its padded size in blocks and start at its offset. -unsafe extern "system" fn get_resource_tiling(this: *mut c_void, tiles: *mut u32, packed: *mut u8, shape: *mut u32, count: *mut u32, first: u32, out: *mut u8) -> HRESULT { - let Some(s) = tex(this).texels() else { return E_NOTIMPL }; - let l = &s.chain.layout; - let block = l.block_bytes as u64; - if block == 0 || l.block_w == 0 || l.block_h == 0 { - return E_NOTIMPL; - } - let mips = s.chain.levels.len(); - let standard = s.first_tail.min(mips); - let slices = s.array.max(1) as usize; - let slice_tiles = (s.chain.slice_bytes as u64 / block) as u32; - let total = (s.size() / block) as u32; - if !tiles.is_null() { - *tiles = total; - } - if !packed.is_null() { - // D3D12_PACKED_MIP_INFO: u8 standard mips, u8 packed mips, u32 tiles for them, u32 their first tile - let p = std::slice::from_raw_parts_mut(packed, 12); - p.fill(0); - p[0] = standard as u8; - p[1] = (mips - standard) as u8; - if let Some(m) = s.chain.levels.get(standard) { - p[4..8].copy_from_slice(&1u32.to_le_bytes()); - p[8..12].copy_from_slice(&((m.tail.unwrap_or(m.offset) as u64 / block) as u32).to_le_bytes()); - } - } - if !shape.is_null() { - *shape = l.block_w as u32 * s.side; - *shape.add(1) = l.block_h as u32 * s.side; - *shape.add(2) = 1; - } - let mut written = 0u32; - if !count.is_null() { - let cap = *count; - if !out.is_null() { - let subresources = (mips * slices) as u32; - while written < cap && first.saturating_add(written) < subresources { - let sub = (first + written) as usize; - let (mip, slice) = (sub % mips, sub / mips); - // D3D12_SUBRESOURCE_TILING: u32 width, u16 height, u16 depth in tiles, u32 first tile - let (w, h, d, start) = if mip < standard { - let (pw, ph) = s.padded(mip); - ((pw / l.block_w) as u32, (ph / l.block_h) as u16, 1u16, slice as u32 * slice_tiles + (s.chain.levels[mip].offset as u64 / block) as u32) - } else { - (0, 0, 0, u32::MAX) // a packed mip - }; - let o = std::slice::from_raw_parts_mut(out.add(written as usize * 12), 12); - o[0..4].copy_from_slice(&w.to_le_bytes()); - o[4..6].copy_from_slice(&h.to_le_bytes()); - o[6..8].copy_from_slice(&d.to_le_bytes()); - o[8..12].copy_from_slice(&start.to_le_bytes()); - written += 1; - } - } - *count = written; - } - static N: AtomicU32 = AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 6 { - crate::xlog_info!( - "xg: GetResourceTiling of a {}x{} texture ({mips} mips, {slices} slices, mode {}): {total} tiles of {}x{} pixels, {standard} standard mips, {written} tilings written (from XCL's layout model – not checked against the console's library)", - s.width, - s.height, - s.mode, - l.block_w as u32 * s.side, - l.block_h as u32 * s.side - ); - } - S_OK -} - /// `HRESULT XGCreateTextureComputer(const D3D12_RESOURCE_DESC*, XGTextureAddressComputer**)` /// `HRESULT XGSuggestSwizzleMode(const D3D12_RESOURCE_DESC*, UINT, D3D12_TEXTURE_LAYOUT* out)` /// (a newer library's; a retail game passes 0 and its desc's own layout field as `out`): the explicit