Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
0f4117c
D3D12.X: reuse staging buffers and command lists for async title text…
gsucristo Nov 23, 2026
7d1c466
xg: guard CopyFromSubresource destination span and log invalid arguments
gsucristo Nov 23, 2026
ad67ee3
tiling: copy linear mip levels a row at a time
gsucristo Nov 23, 2026
9c4c3e6
xg: fix CopyFromSubresource 7-argument ABI (extra u32 before src)
gsucristo Nov 24, 2026
dc74a88
tiling/title_textures: hoisted tiled detiling and parallel batch deti…
gsucristo Nov 24, 2026
3a23ed4
vram: coalesce page-queue fence signals and throttle idle-page sweeps
gsucristo Nov 24, 2026
a5c4937
pso_async: pre-compile compute PSOs in the background while keeping g…
gsucristo Nov 24, 2026
924670f
title_textures: cache VirtualQuery region spans in sorted recheck_gpu…
gsucristo Nov 24, 2026
0eca36e
pso_async: route big compute driver compiles to dedicated pool withou…
gsucristo Nov 24, 2026
d37cf80
tiling: cache Layout offset tables with Arc slices and trim unused hi…
gsucristo Nov 24, 2026
e61f3f7
pso_async: run background PSO worker threads at BELOW_NORMAL priority
gsucristo Nov 24, 2026
63de074
bind/pso_async: skip draws on pending graphics PSOs instead of blocki…
gsucristo Nov 24, 2026
07dba95
pso_async: give bound lazy graphics PSOs a dedicated urgent worker pool
gsucristo Nov 24, 2026
ab84322
pso_async/bind: add opt-in XCL_ASYNC_COMPUTE=1 non-blocking compute P…
gsucristo Nov 24, 2026
d419af8
D3D12.X: bridge monotonic Wait64BitValueX to GPU queue.Wait/Signal fe…
gsucristo Nov 24, 2026
4ff33f0
D3D12.X: detect cross-queue Wait64 cycles, bypass same-queue FIFO, an…
gsucristo Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
719 changes: 710 additions & 9 deletions crates/xcl/src/gpu/texture.rs

Large diffs are not rendered by default.

193 changes: 172 additions & 21 deletions crates/xcl/src/gpu/tiling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@
//! offset is linear over GF(2): `offset(x, y, z) = ox[x] ^ oy[y] ^ oz[z]`, small tables per
//! layout. Blocks (256 B / 4 KB / 64 KB) are laid out row-major; `Chain` lays out the mips.

use std::collections::HashMap;
use std::sync::{Arc, OnceLock, RwLock};

use super::tiling_tables::{NIBBLE01, NIBBLE2, NIBBLE3, NIBBLE4, PATTERNS, PATTERNS_3D};

/// The part of GB_ADDR_CONFIG the XOR modes depend on (number of pipes and packers, log2).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PipeConfig {
pub pipes_log2: u32,
pub pkrs_log2: u32,
Expand Down Expand Up @@ -63,28 +66,46 @@ pub struct Layout {
/// XORed into every in-block byte offset: the pipe / bank swizzle a T# base address carries
/// in its low bits (`base & (block_bytes - 1)`), 0 otherwise
pub base_xor: usize,
ox: Vec<u32>,
oy: Vec<u32>,
oz: Vec<u32>,
ox: Arc<[u32]>,
oy: Arc<[u32]>,
oz: Arc<[u32]>,
/// the in-block bits the coordinates above the block give (XOR modes with many pipes take
/// pipe bits from neighbouring blocks' coordinates), by `x >> log2(block_w)` etc.
hx: Vec<u32>,
hy: Vec<u32>,
hz: Vec<u32>,
hx: Arc<[u32]>,
hy: Arc<[u32]>,
hz: Arc<[u32]>,
}

type LayoutKey = (bool, u32, u32, PipeConfig);

fn layout_cache() -> &'static RwLock<HashMap<LayoutKey, Option<Layout>>> {
static CACHE: OnceLock<RwLock<HashMap<LayoutKey, Option<Layout>>>> = OnceLock::new();
CACHE.get_or_init(|| RwLock::new(HashMap::new()))
}

impl Layout {
/// A 2D surface (or one slice of an array). `None` for unknown / reserved modes and
/// elements over 16 B. Linear (0): rows padded to 256 bytes (addrlib
/// Gfx10Lib::HwlComputeSurfaceInfoLinear), a "block" of 256 B, one row high.
pub fn new(mode: u32, elem_log2: u32, cfg: PipeConfig) -> Option<Layout> {
let key = (false, mode, elem_log2, cfg);
if let Some(hit) = layout_cache().read().unwrap().get(&key) {
return hit.clone();
}
let built = Self::build_2d(mode, elem_log2, cfg);
layout_cache().write().unwrap().insert(key, built.clone());
built
}

fn build_2d(mode: u32, elem_log2: u32, cfg: PipeConfig) -> Option<Layout> {
if elem_log2 > 4 {
return None;
}
if mode == 0 {
let bw = 256 >> elem_log2;
let ox = (0..bw as u32).map(|x| x << elem_log2).collect();
return Some(Layout { mode, elem_log2, block_w: bw, block_h: 1, block_d: 1, block_bytes: 256, base_xor: 0, ox, oy: vec![0], oz: vec![0], hx: vec![0], hy: vec![0], hz: vec![0] });
let ox: Arc<[u32]> = (0..bw as u32).map(|x| x << elem_log2).collect::<Vec<_>>().into();
let z: Arc<[u32]> = Arc::from([0u32]);
return Some(Layout { mode, elem_log2, block_w: bw, block_h: 1, block_d: 1, block_bytes: 256, base_xor: 0, ox, oy: Arc::clone(&z), oz: Arc::clone(&z), hx: Arc::clone(&z), hy: Arc::clone(&z), hz: z });
}
let blk = block_log2(mode)?;
let bits = pattern_bits(PATTERNS, mode, elem_log2, cfg)?;
Expand All @@ -99,7 +120,11 @@ impl Layout {
/// each depth slice as a 2D surface. `None`: a mode 3D textures cannot have (addrlib
/// Gfx10Rsrc3dSwModeMask) or no pattern.
pub fn new_3d(mode: u32, elem_log2: u32, cfg: PipeConfig) -> Option<Layout> {
match mode {
let key = (true, mode, elem_log2, cfg);
if let Some(hit) = layout_cache().read().unwrap().get(&key) {
return hit.clone();
}
let built = match mode {
0 | 24 | 27 => Self::new(mode, elem_log2, cfg),
5 | 9 | 17 | 21 | 25 | 26 if elem_log2 <= 4 => {
let blk = block_log2(mode)?;
Expand All @@ -111,14 +136,16 @@ impl Layout {
Some(Self::from_bits(mode, elem_log2, blk, &bits, (w1k + avg, h1k + avg + rest / 2, d1k + avg + u32::from(rest != 0))))
}
_ => None,
}
};
layout_cache().write().unwrap().insert(key, built.clone());
built
}

/// The offset tables of a block `1 << wl` × `1 << hl` × `1 << dl` elements.
fn from_bits(mode: u32, elem_log2: u32, blk: u32, bits: &[u64; 20], (wl, hl, dl): (u32, u32, u32)) -> Layout {
// the in-block offset bits coordinate `c << lo` gives
let table = |n: usize, shift: u32, lo: u32| -> Vec<u32> {
(0..n as u32)
let table = |n: usize, shift: u32, lo: u32| -> Arc<[u32]> {
let v: Vec<u32> = (0..n as u32)
.map(|c| {
let mut off = 0u32;
for (i, &b) in bits[..blk as usize].iter().enumerate() {
Expand All @@ -127,11 +154,19 @@ impl Layout {
}
off
})
.collect()
.collect();
v.into()
};
let (bw, bh, bd) = (1usize << wl, 1usize << hl, 1usize << dl);
// the pattern masks are 16 bits: coordinates above them do not matter
let high = |l: u32, shift: u32| table(1 << (16 - l.min(16)), shift, l);
// the pattern masks are 16 bits: only allocate up to the highest actually used bit above `l`
let high = |l: u32, shift: u32| -> Arc<[u32]> {
let used_hi = bits[..blk as usize].iter().fold(0u32, |acc, &b| acc | ((((b >> shift) & 0xFFFF) as u32) >> l.min(16)));
if used_hi == 0 {
return Arc::from([0u32]);
}
let hi_bits = 32 - used_hi.leading_zeros();
table(1usize << hi_bits, shift, l)
};
Layout {
mode,
elem_log2,
Expand Down Expand Up @@ -365,6 +400,23 @@ impl Chain {
let l = self.levels[i];
let e = 1usize << self.layout.elem_log2;
let mut out = vec![0u8; l.width * l.height * l.depth * e];
if self.layout.mode == 0 && self.layout.base_xor == 0 && l.origin == (0, 0) {
let row_bytes = l.width * e;
let stride = l.pitch.div_ceil(self.layout.block_w) * self.layout.block_bytes;
for z in 0..l.depth {
let z_off = z * self.slice_bytes + l.offset;
for y in 0..l.height {
let o = z_off + y * stride;
if let Some(avail) = mem.len().checked_sub(o) {
let n = (avail.min(row_bytes) / e) * e;
if n > 0 {
out[(z * l.height + y) * row_bytes..][..n].copy_from_slice(&mem[o..o + n]);
}
}
}
}
return out;
}
for z in 0..l.depth {
for y in 0..l.height {
for x in 0..l.width {
Expand Down Expand Up @@ -398,11 +450,101 @@ impl Chain {
let l = self.levels[i];
let e = 1usize << self.layout.elem_log2;
let mut out = vec![0u8; l.width * l.height * e];
for y in 0..l.height {
for x in 0..l.width {
let o = self.element_at(&l, x, y, slice);
if let Some(s) = src.get(o..o + e) {
out[(y * l.width + x) * e..][..e].copy_from_slice(s);
if l.width == 0 || l.height == 0 {
return out;
}
if self.layout.mode == 0 && self.layout.base_xor == 0 && l.origin == (0, 0) {
let row_bytes = l.width * e;
let stride = l.pitch.div_ceil(self.layout.block_w) * self.layout.block_bytes;
for y in 0..l.height {
let o = l.offset + y * stride;
if let Some(avail) = src.len().checked_sub(o) {
let n = (avail.min(row_bytes) / e) * e;
if n > 0 {
out[y * row_bytes..][..n].copy_from_slice(&src[o..o + n]);
}
}
}
return out;
}
let lay = &self.layout;
let bw_shift = lay.block_w.trailing_zeros();
let bw_mask = lay.block_w - 1;
let bh_shift = lay.block_h.trailing_zeros();
let bh_mask = lay.block_h - 1;
let bd_shift = lay.block_d.trailing_zeros();
let bd_mask = lay.block_d - 1;
let blk_shift = lay.block_bytes.trailing_zeros();
let hx_mask = lay.hx.len() - 1;
let hy_mask = lay.hy.len() - 1;
let hz_mask = lay.hz.len() - 1;
let pitch_bytes = l.pitch.div_ceil(lay.block_w) << blk_shift;
let z_xor = (lay.oz[slice & bd_mask] ^ lay.hz[(slice >> bd_shift) & hz_mask]) as usize ^ lay.base_xor;
let ox0 = l.origin.0;
let oy0 = l.origin.1;

let mut x_blk = Vec::with_capacity(l.width);
let mut x_xor = Vec::with_capacity(l.width);
for x in 0..l.width {
let gx = x + ox0;
let bx = gx >> bw_shift;
x_blk.push(bx << blk_shift);
x_xor.push((lay.ox[gx & bw_mask] ^ lay.hx[bx & hx_mask]) as usize);
}

let src_len = src.len();
let max_gy = oy0 + l.height - 1;
let max_gx = ox0 + l.width - 1;
let max_end = l.offset + ((max_gy >> bh_shift) * pitch_bytes) + (((max_gx >> bw_shift) + 1) << blk_shift);
let all_in_bounds = max_end <= src_len && (lay.base_xor & (e - 1)) == 0;

macro_rules! detile_elem {
($n:literal) => {{
let row_bytes = l.width * $n;
if all_in_bounds {
for y in 0..l.height {
let gy = y + oy0;
let by = gy >> bh_shift;
let row_base = l.offset + by * pitch_bytes;
let y_xor = (lay.oy[gy & bh_mask] ^ lay.hy[by & hy_mask]) as usize ^ z_xor;
let dst_row = &mut out[y * row_bytes..][..row_bytes];
for x in 0..l.width {
let o = row_base + x_blk[x] + (x_xor[x] ^ y_xor);
dst_row[x * $n..x * $n + $n].copy_from_slice(&src[o..o + $n]);
}
}
} else {
for y in 0..l.height {
let gy = y + oy0;
let by = gy >> bh_shift;
let row_base = l.offset + by * pitch_bytes;
let y_xor = (lay.oy[gy & bh_mask] ^ lay.hy[by & hy_mask]) as usize ^ z_xor;
let dst_row = &mut out[y * row_bytes..][..row_bytes];
for x in 0..l.width {
let o = row_base + x_blk[x] + (x_xor[x] ^ y_xor);
if let Some(s) = src.get(o..o + $n) {
dst_row[x * $n..x * $n + $n].copy_from_slice(s);
}
}
}
}
}};
}

match e {
1 => detile_elem!(1),
2 => detile_elem!(2),
4 => detile_elem!(4),
8 => detile_elem!(8),
16 => detile_elem!(16),
_ => {
for y in 0..l.height {
for x in 0..l.width {
let o = self.element_at(&l, x, y, slice);
if let Some(s) = src.get(o..o + e) {
out[(y * l.width + x) * e..][..e].copy_from_slice(s);
}
}
}
}
}
Expand All @@ -413,6 +555,15 @@ impl Chain {
pub fn tile_level(&self, dst: &mut [u8], i: usize, slice: usize, linear: &[u8]) {
let l = self.levels[i];
let e = 1usize << self.layout.elem_log2;
if self.layout.mode == 0 && self.layout.base_xor == 0 && l.origin == (0, 0) {
let row_bytes = l.width * e;
let stride = l.pitch.div_ceil(self.layout.block_w) * self.layout.block_bytes;
for y in 0..l.height {
let o = l.offset + y * stride;
dst[o..o + row_bytes].copy_from_slice(&linear[y * row_bytes..][..row_bytes]);
}
return;
}
for y in 0..l.height {
for x in 0..l.width {
let o = self.element_at(&l, x, y, slice);
Expand Down
26 changes: 18 additions & 8 deletions crates/xcl/src/hle/d3d12x/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,10 @@ pub(super) fn note_root_changing_signature(sig: usize) {
pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) {
type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64);
let pc: F = std::mem::transmute(super::real::orig_fn(this, 59));
let pso = super::pso_async::resolve_wait(with(this, |s| s.pso));
let Some(pso) = super::pso_async::resolve_indirect(with(this, |s| s.pso)) else {
count(DRAWS_SKIPPED);
return;
};
let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso));
let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf));
if !gfx && !compute {
Expand Down Expand Up @@ -367,20 +370,24 @@ pub(super) unsafe fn emit_prepared_indexed_draw(
unsafe fn graphics_bound(this: *mut c_void) -> Option<ID3D12GraphicsCommandList> {
let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone();
let pso = with(this, |s| s.pso);
// a pipeline still being built in the background is waited for (its stand-in draws nothing)
if !super::real::is_translated_graphics(super::pso_async::resolve_wait(pso)) {
// Graphics pipelines compile asynchronously (`pso_async`): skip draws while still building
// instead of stalling the render thread (compute pipelines still wait in `dispatch`).
let Some(resolved) = super::pso_async::resolve_nonblocking(pso) else {
count(DRAWS_SKIPPED);
return None;
};
if !super::real::is_translated_graphics(resolved) {
count(DRAWS_PC);
if super::present::trace_frame() {
// which pipelines draw without a translation (first 12 distinct)
static SEEN: Mutex<Vec<usize>> = Mutex::new(Vec::new());
let mut g = SEEN.lock().unwrap();
if !g.contains(&pso) && g.len() < 12 {
g.push(pso);
let real = super::pso_async::resolve_wait(pso);
crate::xlog_info!(
"frame trace: draw with an untranslated pipeline {pso:#x} (resolves to {real:#x}; pending {}, two-pass {}, RT0 {:?})",
"frame trace: draw with an untranslated pipeline {pso:#x} (resolves to {resolved:#x}; pending {}, two-pass {}, RT0 {:?})",
super::pso_async::is_pending(pso),
super::real::two_pass_of(real).is_some(),
super::real::two_pass_of(resolved).is_some(),
super::present::rt0_resource(this as usize).map(|r| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0) }))
);
}
Expand All @@ -397,7 +404,7 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option<ID3D12GraphicsCommandList>
if super::present::trace_frame() {
trace_ui_draw(this, pso);
}
match bind_abi(this, &list, pso, true) {
match bind_abi(this, &list, resolved, true) {
Ok(()) => {
count(DRAWS);
Some(list)
Expand Down Expand Up @@ -673,7 +680,10 @@ pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso:

/// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments
pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) {
let pso = super::pso_async::resolve_wait(with(this, |s| s.pso));
let Some(pso) = super::pso_async::resolve_compute(with(this, |s| s.pso)) else {
count(DISPATCHES_SKIPPED);
return;
};
let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return };
if !super::real::is_translated_compute(pso) {
// a console pipeline without a translation (including a background build that
Expand Down
Loading
Loading