Skip to content
Draft
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
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,14 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder
blob is left to the runtime instead of being compiled in the pass — those compiles take tens
of minutes and gigabytes and stopped the pass on the biggest programs. `XCL_PIPELINE_MAX_KB`
sets the cap in KiB (0 turns it off).
- **`--pipelines` static-sampler sets**: the pass writes the static-sampler sets of the
compute programs it translates (and those of an earlier file), sorted, to `sampler-sets.txt`
in the DXIL cache and makes their root signatures before any pipeline, in that order; a run
whose DXIL cache has the file makes the same root signatures first, in the same order, at
device creation. On an RTX 5070 Ti with XCL's blob files off (`XCL_PSO_DISK_CACHE=0`), six
compute pipelines with static samplers that an earlier pass had compiled took 28–73 s to
create again when these root signatures were made in the reverse order, and 15–34 ms in the
earlier pass's order.
- **Without a command line** (xcl.exe opened from Explorer) XCL shows a small menu: *Choose a
game…* (pick its exe or `MicrosoftGame.config`) or *Run again* (the last one). On an error the
window stays open until Enter.
Expand Down
73 changes: 71 additions & 2 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
//! directly indexed descriptor heaps (images / samplers). Mapping the title's root arguments
//! onto that ABI at draw time is the next step (needs the console runtime's user-data layout).

use std::collections::{HashMap, VecDeque};
use std::path::PathBuf;
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock, Weak};

use windows::Win32::Graphics::Direct3D::ID3DBlob;
Expand Down Expand Up @@ -1177,6 +1177,75 @@ pub fn static_sampler_desc(k: u32, (w, comparison): &StaticSampler) -> D3D12_STA
}
}

/// The DXIL cache's list of the static-sampler sets of a pack's compute programs, written by
/// `xcl shaders --precompile --pipelines`: one set per line, sorted by `sampler_key`, each
/// sampler `w0 w1 w2 w3 cmp` in hex, samplers separated by `;`. That pass and a title's run make
/// these root signatures first, in this order (`sampler_set_signatures`). On an RTX 5070 Ti,
/// with XCL's blob files off, six compute pipelines with static samplers that took 15-34 ms to
/// create took 28-73 s when these root signatures had been made in the reverse order.
pub const SAMPLER_SETS_FILE: &str = "sampler-sets.txt";

/// The key a static-sampler set's root signature is kept under (`real::abi_rs_for`,
/// `xcl shaders --pipelines`).
pub fn sampler_key(samplers: &[StaticSampler]) -> Vec<u32> {
samplers.iter().flat_map(|(w, c)| w.iter().copied().chain([*c as u32])).collect()
}

/// `SAMPLER_SETS_FILE`'s text for these sets: sorted by `sampler_key`, each once, without the
/// empty set (that one is the plain ABI root signature).
pub fn sampler_sets_text(sets: impl IntoIterator<Item = Vec<StaticSampler>>) -> String {
let sorted: BTreeMap<Vec<u32>, Vec<StaticSampler>> = sets.into_iter().filter(|s| !s.is_empty()).map(|s| (sampler_key(&s), s)).collect();
sorted
.values()
.map(|set| set.iter().map(|(w, c)| format!("{:x} {:x} {:x} {:x} {}", w[0], w[1], w[2], w[3], *c as u32)).collect::<Vec<_>>().join(";") + "\n")
.collect()
}

/// The sets of a `SAMPLER_SETS_FILE` text, in file order. A line that does not parse is left out.
pub fn parse_sampler_sets(text: &str) -> Vec<Vec<StaticSampler>> {
let sampler = |s: &str| -> Option<StaticSampler> {
let v: Vec<u32> = s.split_whitespace().map(|x| u32::from_str_radix(x, 16)).collect::<Result<_, _>>().ok()?;
match v[..] {
[a, b, c, d, cmp @ (0 | 1)] => Some(([a, b, c, d], cmp == 1)),
_ => None,
}
};
text.lines().filter(|l| !l.trim().is_empty()).filter_map(|l| l.split(';').map(sampler).collect()).collect()
}

/// The root signatures of the sets in `dir`'s `SAMPLER_SETS_FILE`, made on `dev` one after
/// another in file order, with their `sampler_key`s (none when there is no file).
pub fn sampler_set_signatures(dev: &ID3D12Device, dir: &Path) -> Result<Vec<(Vec<u32>, ID3D12RootSignature)>, String> {
let path = dir.join(SAMPLER_SETS_FILE);
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(format!("{}: {e}", path.display())),
};
parse_sampler_sets(&text).iter().map(|set| abi_root_signature_with(dev, true, set).map(|rs| (sampler_key(set), rs))).collect()
}

#[cfg(test)]
mod sampler_sets_tests {
use super::{parse_sampler_sets, sampler_key, sampler_sets_text, StaticSampler};

#[test]
fn sampler_sets_are_written_sorted_once_and_read_back_in_file_order() {
let a: Vec<StaticSampler> = vec![([0x3092, 0xc00000, 0x18500000, 0], true)];
let b: Vec<StaticSampler> = vec![([0x92, 0xc00000, 0x14500000, 0], false), ([0x3092, 0xc00000, 0x18500000, 0], true)];
let c: Vec<StaticSampler> = vec![([0, 0xc00000, 0x18500000, 0], false)];
let text = sampler_sets_text([a.clone(), vec![], b.clone(), c.clone(), a.clone()]);
assert_eq!(text, "0 c00000 18500000 0 0\n92 c00000 14500000 0 0;3092 c00000 18500000 0 1\n3092 c00000 18500000 0 1\n");
// the order does not depend on the order the sets were found in
assert_eq!(sampler_sets_text([c.clone(), a.clone(), b.clone()]), text);
let sets = parse_sampler_sets(&text);
assert_eq!(sets, vec![c, b, a]);
assert!(sets.windows(2).all(|w| sampler_key(&w[0]) < sampler_key(&w[1])));
// a line that does not parse is left out, the others keep their order
assert_eq!(parse_sampler_sets("1 2 3 4 0\n1 2 3 4 2\nzz 2 3 4 0\n\n5 6 7 8 1\n"), vec![vec![([1, 2, 3, 4], false)], vec![([5, 6, 7, 8], true)]]);
}
}

/// The ABI root signature with the pipeline's static samplers (registers 0.., space 1).
pub fn abi_root_signature_with(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler]) -> Result<ID3D12RootSignature, String> {
abi_signature(dev, graphics, samplers, false)
Expand Down
23 changes: 22 additions & 1 deletion crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,7 @@ pub fn init() -> Result<String, String> {
let _ = q.RegisterMessageCallback(Some(debug_message), D3D12_MESSAGE_CALLBACK_FLAG_NONE, std::ptr::null_mut(), &mut cookie);
}
}
make_sampler_set_signatures(&device);
open_uma(&device);
super::device_x::probe_dynamic_depth_bias(&device);
let raw = device.into_raw(); // one reference kept for the process lifetime
Expand Down Expand Up @@ -3872,12 +3873,32 @@ pub fn pso_root_signature(pso: usize) -> Option<usize> {
/// ABI root signatures with static samplers, by sampler set (owned here, never released).
static ABI_RS_SAMPLERS: Mutex<Option<HashMap<Vec<u32>, usize>>> = Mutex::new(None);

/// At device creation, before any pipeline: the root signatures of the DXIL cache's
/// `SAMPLER_SETS_FILE` (`xcl shaders --precompile --pipelines`) made in its order, as that pass
/// made them, and used for every pipeline with one of these sets (`abi_rs_for`).
fn make_sampler_set_signatures(device: &ID3D12Device) {
use crate::gpu::recomp::{dxc, pso};
match pso::sampler_set_signatures(device, &dxc::cache_dir()) {
Ok(made) if made.is_empty() => {}
Ok(made) => {
let n = made.len();
let mut g = ABI_RS_SAMPLERS.lock().unwrap();
let map = g.get_or_insert_with(HashMap::new);
for (key, rs) in made {
map.entry(key).or_insert(rs.into_raw() as usize);
}
crate::xlog_info!("D3D12.X: {n} static-sampler root signatures made first, in the order of {}", pso::SAMPLER_SETS_FILE);
}
Err(e) => crate::xlog_warn!("D3D12.X: static-sampler root signatures of {}: {e}", pso::SAMPLER_SETS_FILE),
}
}

/// The XCL ABI root signature with a pipeline's static samplers (the plain one without).
unsafe fn abi_rs_for(this: *mut c_void, samplers: &[crate::gpu::recomp::pso::StaticSampler]) -> Option<*mut c_void> {
if samplers.is_empty() {
return abi_rs_raw(this);
}
let key: Vec<u32> = samplers.iter().flat_map(|(w, c)| w.iter().copied().chain([*c as u32])).collect();
let key = crate::gpu::recomp::pso::sampler_key(samplers);
let mut g = ABI_RS_SAMPLERS.lock().unwrap();
let map = g.get_or_insert_with(HashMap::new);
if let Some(&rs) = map.get(&key) {
Expand Down
97 changes: 93 additions & 4 deletions crates/xcl/src/shaders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1117,7 +1117,9 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl
/// mesh pass-through, which the runtime builds for its pixel shader.
/// `--pipelines`: each compute program's pipeline made on the GPU as a title's would be (XCL's
/// ABI root signature with its static samplers). Save the driver's compiled blob in the same
/// cache the runtime reads at startup. Nothing runs on the GPU.
/// cache the runtime reads at startup. Nothing runs on the GPU. The pipelines are made once every
/// program is translated, after the root signatures of their static-sampler sets, in the order
/// the runtime makes them in too (`Pipelines::first_signatures`).
/// Programs whose DXIL is over `XCL_PIPELINE_MAX_KB` (8 MiB by default; 0 turns the cap off)
/// and that have no blob yet are counted as capped and left to the runtime: their driver
/// compile takes tens of minutes and gigabytes, and stopped the pass on the biggest programs
Expand Down Expand Up @@ -1202,6 +1204,50 @@ mod pipeline_cap_tests {
}
}

#[cfg(test)]
mod sampler_set_tests {
use super::{recomp, Pipelines};
use recomp::pso::{sampler_key, Compiled, StaticSampler};

#[test]
fn prebuild_and_runtime_make_the_sampler_set_root_signatures_in_one_order() {
struct Scratch(std::path::PathBuf);
impl Drop for Scratch {
fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); }
}
let pipelines = match Pipelines::new() {
Ok(pipelines) => pipelines,
Err(reason) => {
recomp::runner::skip_test(&format!("no D3D12 device: {reason}"));
return;
}
};
let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let scratch = Scratch(std::env::temp_dir().join(format!("xcl-sampler-sets-{}-{nonce}", std::process::id())));
let a: Vec<StaticSampler> = vec![([0x3092, 0xc00000, 0x18500000, 0], true)];
let b: Vec<StaticSampler> = vec![([0x92, 0xc00000, 0x14500000, 0], false), ([0x3092, 0xc00000, 0x18500000, 0], true)];
let c: Vec<StaticSampler> = vec![([0, 0xc00000, 0x18500000, 0], false)];
let program = |samplers: &Vec<StaticSampler>| Compiled { dispatch_chain: None, dxil: Vec::new(), samplers: samplers.clone() };
let sorted = vec![sampler_key(&c), sampler_key(&b), sampler_key(&a)];

// the pass, in the order the programs were translated, with one set twice and one program without samplers
let made = pipelines.first_signatures(&scratch.0, &[program(&a), program(&vec![]), program(&b), program(&a), program(&c)]).expect("first signatures");
assert_eq!(made, sorted);
let text = std::fs::read_to_string(scratch.0.join(recomp::pso::SAMPLER_SETS_FILE)).expect("sampler-sets file");
assert_eq!(text, recomp::pso::sampler_sets_text([c.clone(), b.clone(), a.clone()]));
assert_eq!(pipelines.signatures.lock().unwrap().len(), 3);

// a later pass over fewer programs keeps the earlier sets and their order
assert_eq!(pipelines.first_signatures(&scratch.0, &[program(&b)]).expect("second pass"), sorted);

// the runtime at device creation (`real::make_sampler_set_signatures`): the same sets, in the same order
let runtime: Vec<Vec<u32>> = recomp::pso::sampler_set_signatures(&pipelines.dev, &scratch.0).expect("runtime signatures").into_iter().map(|(key, _)| key).collect();
assert_eq!(runtime, sorted);
// no file: nothing made
assert!(recomp::pso::sampler_set_signatures(&pipelines.dev, &scratch.0.join("none")).expect("no file").is_empty());
}
}

// D3D12 devices and root signatures are free-threaded
unsafe impl Sync for Pipelines {}

Expand All @@ -1227,7 +1273,7 @@ impl Pipelines {

fn make_with_cache_path(&self, c: &recomp::pso::Compiled, path_override: Option<PathBuf>) {
use windows::Win32::Graphics::Direct3D12::*;
let key: Vec<u32> = c.samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect();
let key = recomp::pso::sampler_key(&c.samplers);
let rs = {
let mut g = self.signatures.lock().unwrap();
match g.get(&key) {
Expand Down Expand Up @@ -1318,6 +1364,38 @@ impl Pipelines {
eprintln!(" pipelines: {} made, {} refused", self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed));
}
}

/// The static-sampler sets of `compiled`, and those of `dir`'s earlier `SAMPLER_SETS_FILE`,
/// written to that file sorted, and their root signatures made first, in the file's order: the
/// order a title's run makes them in at device creation (`real::make_sampler_set_signatures`).
/// The keys, in the order they were made.
fn first_signatures(&self, dir: &Path, compiled: &[recomp::pso::Compiled]) -> Result<Vec<Vec<u32>>, String> {
let path = dir.join(recomp::pso::SAMPLER_SETS_FILE);
let earlier = match std::fs::read_to_string(&path) {
Ok(text) => recomp::pso::parse_sampler_sets(&text),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
Err(e) => return Err(format!("{}: {e}", path.display())),
};
let text = recomp::pso::sampler_sets_text(earlier.into_iter().chain(compiled.iter().map(|c| c.samplers.clone())));
std::fs::create_dir_all(dir).and_then(|()| std::fs::write(&path, text)).map_err(|e| format!("{}: {e}", path.display()))?;
let made = recomp::pso::sampler_set_signatures(&self.dev, dir)?;
let mut g = self.signatures.lock().unwrap();
Ok(made.into_iter().map(|(key, rs)| { g.entry(key.clone()).or_insert(rs); key }).collect())
}

/// The compute pipelines of `compiled`, on `most` threads.
fn make_all(&self, compiled: &[recomp::pso::Compiled]) {
let next = AtomicUsize::new(0);
std::thread::scope(|s| {
for _ in 0..self.most {
s.spawn(|| {
while let Some(c) = compiled.get(next.fetch_add(1, Ordering::Relaxed)) {
self.make(c);
}
});
}
});
}
}

/// A compute program a title used in an earlier run (`--used-only`): its pipeline's key, as the
Expand All @@ -1344,6 +1422,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on
let (done, compiled, cached, failed, skipped) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0));
let errors: Mutex<Vec<String>> = Mutex::new(Vec::new());
let unused = AtomicUsize::new(0);
// `--pipelines`: made once every program is translated, after their static-sampler root
// signatures (`Pipelines::first_signatures`)
let to_make: Mutex<Vec<recomp::pso::Compiled>> = Mutex::new(Vec::new());
if let Some(u) = used {
println!("--used-only: {} pipelines earlier runs used (used-pipelines.txt); compute programs of other pipelines are passed over", u.len());
}
Expand Down Expand Up @@ -1387,8 +1468,8 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on
}
match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) {
Ok(c) => {
if let Some(p) = pipelines {
p.make(&c);
if pipelines.is_some() {
to_make.lock().unwrap().push(c);
}
compiled.fetch_add(1, Ordering::Relaxed)
}
Expand Down Expand Up @@ -1450,6 +1531,14 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on
});
}
});
if let Some(p) = pipelines {
let to_make = to_make.into_inner().unwrap();
match p.first_signatures(&recomp::dxc::cache_dir(), &to_make) {
Ok(keys) => println!("static-sampler root signatures made first: {} (in the order of {})", keys.len(), recomp::pso::SAMPLER_SETS_FILE),
Err(e) => eprintln!("xcl shaders --pipelines: static-sampler root signatures: {e}"),
}
p.make_all(&to_make);
}
println!(
"compiled {}, already cached {}, errors {}, skipped (GS – paired at pipeline creation) {}, time {:.1} s",
compiled.into_inner(),
Expand Down
Loading