Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,11 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o
a shader the direct translator cannot handle yet goes through HLSL and DXC instead.
`XCL_DIRECT_DXIL=1` keeps vertex and pixel shaders on the HLSL path, `XCL_DIRECT_DXIL=0` every
shader (except very large compute programs, `XCL_DIRECT_HUGE`).
- **Ray-tracing programs left out:** `XCL_RT_LEAVE_OUT=<fragment>[,<fragment>…]` (off by default) leaves
out the compute programs whose shader container holds one of the fragments (names from its debug
data, `xcl rpf <pack> --find`): their dispatches are skipped and the shader preparation passes them
over. Meant for a title's ray-tracing programs while it has built no acceleration structure; XCL
warns once when one of the title's structures gets a root node.
- **DXC:** 1.8 or newer is recommended, from the
[DirectXShaderCompiler releases](https://github.com/microsoft/DirectXShaderCompiler/releases): unpack one
and point `XCL_DXC_DIR` at its `bin\x64`. A Windows SDK may hold an older one (the same `10.0.26100.0`
Expand Down
1 change: 1 addition & 0 deletions THIRD_PARTY.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ carry a note in their header about its origin and the date of changes (GPL-3.0
| [AMD Machine-Readable GPU ISA](https://gpuopen.com/machine-readable-isa/) | MIT | `crates/xcl/src/gpu/rdna2_spec.rs` (generated by `scripts/gen_rdna2.py`) | encoding and instruction tables |
| [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation |
| [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables |
| [Vice-Tay](https://github.com/TaynanGT/Vice-Tay) | GPL-3.0-or-later | `crates/xcl/src/gpu/rt_leave_out.rs` (the programs left out, after `left_out` in `crates/victory-gpu/src/pipeline/make.rs`, commit 1f69d67) | port, 2026-11-27 |
| [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts |
| [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only |
| [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification |
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/gpu/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub(crate) mod fence;
pub mod pack;
pub mod rdna2;
pub mod recomp;
pub mod rt_leave_out;
mod rdna2_spec;
mod rdna2_xbox;
pub mod shader;
Expand Down
181 changes: 181 additions & 0 deletions crates/xcl/src/gpu/rt_leave_out.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
//! `XCL_RT_LEAVE_OUT=<fragment>[,<fragment>…]` (off by default): compute programs whose shader
//! container holds one of the fragments are left out – the title's pipeline gets the dummy
//! compute program a console shader that cannot be translated gets, so its dispatches are
//! skipped, and the shader preparation and `xcl shaders --precompile` pass them over.
//!
//! What it is for: a title's ray-tracing programs that shade the hits of rays or start rays
//! (on a retail title about 1,000 programs, ~1 MB of DXIL each, the largest of its cold driver
//! compiles) do nothing while the title has built no acceleration structure: every ray misses.
//! The fragments name those programs (a name in the container's debug data; find it with
//! `xcl rpf <pack> --find`); XCL's source names no title's programs.
//!
//! So that leaving them out stays harmless, XCL watches the acceleration structures the
//! title's views name (`D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE` in unified
//! memory) and warns once when one of them gets a root node: from then on rays can hit, and
//! the programs left out would have shaded those hits.
//!
//! Ported from Vice-Tay (https://github.com/TaynanGT/Vice-Tay, GPL-3.0-or-later; THIRD_PARTY.md).
//! Changes (2026-11-27): the programs are named by the user's fragments instead of names in
//! the source; one switch; the structure watch and its warning are new; the preparation and
//! the precompile pass the programs over.

use std::collections::BTreeSet;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};

/// Fragments shorter than this are refused: they would match bytes of any container.
const SHORTEST: usize = 6;
/// Acceleration structures remembered for the watch (distinct addresses).
const MOST_STRUCTURES: usize = 4096;

/// The fragments of a `XCL_RT_LEAVE_OUT` value: comma-separated, trimmed, at least
/// [`SHORTEST`] bytes each (shorter ones are dropped).
pub fn fragments_of(value: &str) -> Vec<Vec<u8>> {
value.split(',').map(str::trim).filter(|f| f.len() >= SHORTEST).map(|f| f.as_bytes().to_vec()).collect()
}

/// Whether `container` holds one of `fragments`.
pub fn holds_any(container: &[u8], fragments: &[Vec<u8>]) -> bool {
fragments.iter().any(|f| container.windows(f.len()).any(|w| w == f.as_slice()))
}

fn fragments() -> &'static [Vec<u8>] {
static F: OnceLock<Vec<Vec<u8>>> = OnceLock::new();
F.get_or_init(|| {
let Ok(v) = std::env::var("XCL_RT_LEAVE_OUT") else { return Vec::new() };
let f = fragments_of(&v);
let dropped = v.split(',').map(str::trim).filter(|s| !s.is_empty() && s.len() < SHORTEST).count();
if f.is_empty() {
crate::xlog_warn!("XCL_RT_LEAVE_OUT: no fragment of at least {SHORTEST} bytes – nothing is left out");
} else {
crate::xlog_info!(
"XCL_RT_LEAVE_OUT: compute programs holding one of {} fragment(s) are left out while rays cannot hit{}",
f.len(),
if dropped > 0 { format!(" ({dropped} shorter than {SHORTEST} bytes ignored)") } else { String::new() }
);
}
f
})
}

/// Whether the switch is on (at least one usable fragment).
pub fn enabled() -> bool {
!fragments().is_empty()
}

static LEFT_OUT: AtomicU64 = AtomicU64::new(0);

/// Whether the compute program in `container` is left out; counts and logs the first few.
pub fn left_out(container: &[u8]) -> bool {
if !enabled() || !holds_any(container, fragments()) {
return false;
}
let n = LEFT_OUT.fetch_add(1, Ordering::Relaxed) + 1;
if n <= 3 || n.is_power_of_two() {
crate::xlog_info!(
"XCL_RT_LEAVE_OUT: compute program of record {:016x} left out (#{n}): its dispatches are skipped",
crate::gpu::shader::fnv64(container)
);
}
true
}

/// How many compute programs were left out so far.
pub fn left_out_count() -> u64 {
LEFT_OUT.load(Ordering::Relaxed)
}

static STRUCTURES: Mutex<BTreeSet<u64>> = Mutex::new(BTreeSet::new());

/// An acceleration structure in unified memory that a title's view names (only kept while the
/// switch is on).
pub fn note_structure(va: u64) {
if enabled() {
let mut s = STRUCTURES.lock().unwrap();
if s.len() < MOST_STRUCTURES {
s.insert(va);
}
}
}

/// The root node id in an acceleration structure's header: `None` while it has none (0 or
/// all ones, as before a build).
pub fn root_of(header: &[u8]) -> Option<u32> {
let at = crate::gpu::bvh::ROOT_AT;
let root = u32::from_le_bytes(header.get(at..at + 4)?.try_into().ok()?);
(root != 0 && root != u32::MAX).then_some(root)
}

/// Looks at the structures views named (called every few hundred frames): warns once when one
/// has a root node, since the programs left out would then have hits to shade.
pub fn check_structures() {
static WARNED: AtomicBool = AtomicBool::new(false);
if !enabled() || WARNED.load(Ordering::Relaxed) {
return;
}
let all: Vec<u64> = STRUCTURES.lock().unwrap().iter().copied().collect();
let header = crate::gpu::bvh::HEADER_BYTES;
for va in all {
let p = va as usize;
if !crate::gpu::shader::readable(p, header) {
continue;
}
// SAFETY: `readable` just checked the range; title memory, only read
let bytes = unsafe { std::slice::from_raw_parts(p as *const u8, header) };
if let Some(root) = root_of(bytes) {
if !WARNED.swap(true, Ordering::Relaxed) {
crate::xlog_warn!(
"XCL_RT_LEAVE_OUT: the acceleration structure at {va:#x} has a root node ({root:#x}) now – rays can hit, and the {} compute program(s) left out would shade those hits; run without XCL_RT_LEAVE_OUT for this title",
left_out_count()
);
}
return;
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn fragments_are_trimmed_and_short_ones_dropped() {
let f = fragments_of(" ResolveA ,abc, ,LongerName,");
assert_eq!(f, vec![b"ResolveA".to_vec(), b"LongerName".to_vec()]);
assert!(fragments_of("").is_empty());
assert!(fragments_of("short").is_empty());
}

#[test]
fn a_container_is_matched_by_any_fragment_anywhere() {
let mut container = vec![0u8; 64];
container.extend_from_slice(b"\x00prog_Example_Name_x\x00");
container.extend_from_slice(&[0xFF; 32]);
assert!(holds_any(&container, &fragments_of("Other_Name,Example_Name")));
assert!(!holds_any(&container, &fragments_of("Example_Names")));
assert!(!holds_any(&container, &[]));
// a fragment at the very end still matches
assert!(holds_any(b"xxxxEnd_of_it", &fragments_of("End_of_it")));
}

#[test]
fn a_header_without_a_root_has_none() {
let mut h = vec![0u8; crate::gpu::bvh::HEADER_BYTES];
assert_eq!(root_of(&h), None);
let at = crate::gpu::bvh::ROOT_AT;
h[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes());
assert_eq!(root_of(&h), None);
h[at..at + 4].copy_from_slice(&0x25u32.to_le_bytes());
assert_eq!(root_of(&h), Some(0x25));
assert_eq!(root_of(&h[..at]), None, "a header too short to hold the root");
}

#[test]
fn a_built_structure_from_the_builder_has_a_root() {
// XCL's own builder writes the console layout the watch reads
let tris = crate::gpu::bvh::tests::random_tris(8, 3);
let b = crate::gpu::bvh::build(&tris, 0);
let root = root_of(&b.data).expect("a built structure has a root id");
assert_eq!(root, b.root);
}
}
1 change: 1 addition & 0 deletions crates/xcl/src/hle/d3d12x/present.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u
if let Some(t) = LAST.lock().unwrap().replace(now) {
crate::xlog_info!("D3D12.X: {frames} frames presented, {:.1} fps over the last 300", 300.0 / (now - t).as_secs_f64());
}
crate::gpu::rt_leave_out::check_structures();
}
super::real::stop_if_device_removed();
if !PRESENTX.swap(true, Ordering::Relaxed) {
Expand Down
19 changes: 18 additions & 1 deletion crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3266,6 +3266,7 @@ unsafe fn dev_create_srv_inner(this: *mut c_void, res: *mut c_void, desc: *const
// and what rays read past it: the rest of the top level, its bottom levels, the
// parent pointers (`bvh_want`; `XCL_BVH_WALK=0`: the 64 KiB above only)
super::bvh_want::view_made(va);
crate::gpu::rt_leave_out::note_structure(va);
let w = crate::gpu::desc::bvh_words(va, true);
return super::console_heap::write(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0]);
}
Expand Down Expand Up @@ -8720,11 +8721,27 @@ unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const
hr
}

/// Whether `desc`'s console compute program is one `XCL_RT_LEAVE_OUT` leaves out.
unsafe fn rt_left_out(desc: *const c_void) -> bool {
if !crate::gpu::rt_leave_out::enabled() || !crate::gpu::shader::readable(desc as usize, std::mem::size_of::<D3D12_COMPUTE_PIPELINE_STATE_DESC>()) {
return false;
}
let d = &*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC);
shader_bytes(&d.CS).is_some_and(|cs| crate::gpu::recomp::pso::is_console(cs) && crate::gpu::rt_leave_out::left_out(cs))
}

unsafe fn compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
let _cost = crate::hle::api_cost::time(crate::hle::api_cost::Call::Pipeline);
super::null::capture_compute_desc(desc as *const u8);
let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState")));
let (mut console, missed) = if super::pso_async::enabled() { attempt(|| translated_compute_pso(this, f, desc, riid, ppv)) } else { (translated_compute_pso(this, f, desc, riid, ppv), false) };
// `XCL_RT_LEAVE_OUT`: not translated or built; the dummy program below, its dispatches skipped
let (mut console, missed) = if rt_left_out(desc) {
(Some(Err(())), false)
} else if super::pso_async::enabled() {
attempt(|| translated_compute_pso(this, f, desc, riid, ppv))
} else {
(translated_compute_pso(this, f, desc, riid, ppv), false)
};
if missed {
if let Some(hr) = own_compute(desc).and_then(|o| go_background(this, f, desc, riid, ppv, true, o, standin_compute, compute_key, build_compute)) {
// a console program the worker is translating (its root signature comes with it);
Expand Down
8 changes: 8 additions & 0 deletions crates/xcl/src/shaders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3495,6 +3495,11 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on
// a compute program as a title's pipeline translates it (`pso::console_to_dxil_in`):
// into the translation cache too, so the title does not translate it again
if sh.fssm.iter().any(|f| matches!(recomp::interface(&blob, &sh, f), Some(recomp::Mode::Compute(_)))) {
// the title's pipeline would leave it out too (`gpu::rt_leave_out`)
if crate::gpu::rt_leave_out::left_out(&blob) {
record_done();
continue;
}
if let Some(coverage) = coverage {
match coverage.covers(i, &blob) {
Ok(true) => { record_done(); continue; }
Expand Down Expand Up @@ -3631,6 +3636,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on
skipped.into_inner(),
t0.elapsed().as_secs_f64()
);
if crate::gpu::rt_leave_out::enabled() {
println!("compute programs passed over (XCL_RT_LEAVE_OUT): {}", crate::gpu::rt_leave_out::left_out_count());
}
if let Some(p) = pipelines {
if startup.is_none() {
make_pipelines(p, pipeline_jobs.into_inner().unwrap());
Expand Down
Loading