From d68c74e55cf5837d7fee81f8eee52472d91dd9b6 Mon Sep 17 00:00:00 2001 From: Decodere <98278826+Decodere@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:55:28 +0300 Subject: [PATCH] Shaders: warm runtime-selected graphics DXIL variants in --precompile Route console VS (hw == 4) and PS (hw == 5) FSSM variants in `xcl shaders --precompile` through `recomp::pso::console_to_dxil_in_outcome` instead of only the manual HLSL translate + compile_cached loop: - Warms the `translated/v2` cache used at runtime for both direct graphics (`XCL_DIRECT_DXIL=all`) and HLSL graphics (`XCL_DIRECT_DXIL=0`), warming at most one runtime VS and one runtime PS variant per container while keeping ES/GS skipped counting and Mode::Mesh handling unchanged. - Adds `recomp::pso::console_to_dxil_in_status` returning `(Compiled, bool)` and typed `recomp::pso::CompileOutcome` / `console_to_dxil_in_outcome` (sharing `INCOMPLETE_TRANSLATION_PREFIX` across both cold translations and `.err`-cached lookups) so `--precompile` increments `already cached` on in-memory or `translated/v2` disk cache hits and `compiled` only when translation or compilation actually runs. On `CompileOutcome::Incomplete`, falls through to the existing per-program `recomp::translate` loop (keeping `Mode::Vertex` / `Mode::Pixel` arms intact) so both standalone `--precompile` and hosted `prepare_for_launch` (#2555) preserve exact skip semantics without failing startup on unsupported shaders. - Reports explicit standalone PS `sampler_base=0` coverage alongside counts of PS and VS records carrying static samplers (which shift paired PS bases at pipeline creation). - Updates `crates/xcl/tests/shaders_e2e.rs` for `#1942`'s shared `container` helper and adds fresh-process end-to-end tests covering direct VS/PS warming, HLSL static-sampler `sampler_base=0` hit vs `sampler_base=1` miss, and incomplete VS (`v_cvt_off_f32_i4`) skip + supported VS warming across cold and warm `.err`-cached runs. Part of #2600 Part of #2508 Part of #1833 Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/recomp/pso.rs | 53 +++++- crates/xcl/src/shaders.rs | 59 ++++++- crates/xcl/tests/shaders_e2e.rs | 281 +++++++++++++++++++++++++++++++ 3 files changed, 383 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 5d000775ef..ba2a1dc8cc 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -153,10 +153,49 @@ fn shader_cache() -> &'static Mutex { /// `console_to_dxil_for` with the title's memory windows given (`xcl shaders --precompile` /// fills the caches without a title: the same keys as at its run). pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result { - let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64); + console_to_dxil_in_status(blob, stage, sampler_base, split_wave64, windows).map(|(c, _)| c) +} + +/// Shared prefix emitted when a shader contains unsupported instructions (`!Translation::complete()`) +/// and persisted in `translated/v2/*.err`, so both cold and cached lookups classify incomplete +/// translations consistently. +const INCOMPLETE_TRANSLATION_PREFIX: &str = "incomplete translation, "; + +/// Outcome of `console_to_dxil_in_outcome`: separates compiled/cached shaders from incomplete +/// translations (`!Translation::complete()`, including `.err`-cached hits) and hard failures. +pub enum CompileOutcome { + Compiled { compiled: Compiled, from_cache: bool }, + Incomplete(String), + Failed(String), +} + +/// Like `console_to_dxil_in_status`, classifying incomplete translations (`!Translation::complete()`) +/// separately from hard compilation/container failures. +pub fn console_to_dxil_in_outcome( + blob: &[u8], + stage: Stage, + sampler_base: u32, + split_wave64: bool, + windows: u32, +) -> CompileOutcome { + match console_to_dxil_in_status(blob, stage, sampler_base, split_wave64, windows) { + Ok((compiled, from_cache)) => CompileOutcome::Compiled { compiled, from_cache }, + Err(e) if e.starts_with(INCOMPLETE_TRANSLATION_PREFIX) => CompileOutcome::Incomplete(e), + Err(e) => CompileOutcome::Failed(e), + } +} + +/// Like `console_to_dxil_in`, also returning whether the result came from the in-memory or +/// translated disk cache (`true` = cache hit, `false` = newly translated/compiled). +pub fn console_to_dxil_in_status(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result<(Compiled, bool), String> { if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { - return compile_one().map(|(c, _)| c); + return compile_console_shader(blob, stage, sampler_base, windows, split_wave64).map(|(c, _)| (c, false)); } + let mut from_cache = true; + let compile_one = || { + from_cache = false; + compile_console_shader(blob, stage, sampler_base, windows, split_wave64) + }; let key = ShaderKey { hash: crate::gpu::shader::fnv64(blob), stage, @@ -168,7 +207,7 @@ pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wa // with `XCL_DIRECT_DXIL` the disk entries live under their own identity (backend tag, // direct translator version, routing mode): never mixed with the HLSL path's entries let from_disk = || translated::cached(&dxc::cache_dir(), blob, stage, sampler_base, windows, split_wave64, compile_one); - cached_shader(shader_cache(), key, blob, from_disk).map(|shader| shader.as_ref().clone()) + cached_shader(shader_cache(), key, blob, from_disk).map(|shader| (shader.as_ref().clone(), from_cache)) } /// Translations on disk: a console program's (DXIL, static samplers) by its bytes, so a run @@ -1021,7 +1060,7 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, let t = translate(f.code, &Options { mode: Mode::Compute(cs), wave64: super::detect_wave64(f.code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); - return Err(format!("incomplete translation, missing: {missing:?}")); + return Err(format!("{INCOMPLETE_TRANSLATION_PREFIX}missing: {missing:?}")); } return Ok((t, "cs_6_6")); } @@ -1050,7 +1089,7 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, let t = translate(code, &Options { mode, wave64: super::fssm_wave64(f, code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); - return Err(format!("incomplete translation, missing: {missing:?}")); + return Err(format!("{INCOMPLETE_TRANSLATION_PREFIX}missing: {missing:?}")); } Ok((t, profile)) } @@ -1081,7 +1120,7 @@ fn finish_two_pass_compiled(cs: Compiled, record: super::MsInterface, ps: Option fn finish_two_pass(t: super::Translation, record: super::MsInterface, ps: Option<&[u8]>) -> Result { if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); - return Err(format!("incomplete translation, missing: {missing:?}")); + return Err(format!("{INCOMPLETE_TRANSLATION_PREFIX}missing: {missing:?}")); } let cs = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; finish_two_pass_compiled(Compiled { dispatch_chain: None, dxil: cs, samplers: t.static_samplers }, record, ps) @@ -1118,7 +1157,7 @@ fn compile_console_mesh( let t = super::translate_mesh(code, ms.clone(), wave64, split_wave64, windows)?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); - return Err(format!("incomplete translation, missing: {missing:?}")); + return Err(format!("{INCOMPLETE_TRANSLATION_PREFIX}missing: {missing:?}")); } let dxil = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; Ok(Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers }) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 0cd2ed7b3a..220cb6dc7a 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1606,6 +1606,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on let n = input.len().min(limit); let next = AtomicUsize::new(0); let (done, compiled, cached, failed, skipped) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); + let (ps_base0, ps_static_samplers, vs_static_samplers) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); let errors: Mutex> = Mutex::new(Vec::new()); let unused = AtomicUsize::new(0); if let Some(u) = used { @@ -1649,12 +1650,16 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on done.fetch_add(1, Ordering::Relaxed); continue; } - match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { - Ok(c) => { + match recomp::pso::console_to_dxil_in_status(&blob, recomp::pso::Stage::Compute, 0, split, windows) { + Ok((c, from_cache)) => { if let Some(p) = pipelines { p.make(&c); } - compiled.fetch_add(1, Ordering::Relaxed) + if from_cache { + cached.fetch_add(1, Ordering::Relaxed) + } else { + compiled.fetch_add(1, Ordering::Relaxed) + } } Err(e) => { let mut g = errors.lock().unwrap(); @@ -1670,8 +1675,50 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } continue; } + let (mut warmed_vs, mut warmed_ps) = (false, false); for f in &sh.fssm { let Some(mode) = recomp::interface(&blob, &sh, f) else { continue }; + let runtime_stage = match (&mode, f.stages.first().map(|s| s.hw)) { + (recomp::Mode::Vertex(_), Some(4)) => Some((recomp::pso::Stage::Vertex, &mut warmed_vs)), + (recomp::Mode::Pixel(_), Some(5)) => Some((recomp::pso::Stage::Pixel, &mut warmed_ps)), + _ => None, + }; + if let Some((stage, warmed)) = runtime_stage { + if *warmed || f.programs.is_empty() { + continue; + } + *warmed = true; + match recomp::pso::console_to_dxil_in_outcome(&blob, stage, 0, graphics_split, windows) { + recomp::pso::CompileOutcome::Compiled { compiled: c, from_cache } => { + if stage == recomp::pso::Stage::Pixel { + ps_base0.fetch_add(1, Ordering::Relaxed); + if !c.samplers.is_empty() { + ps_static_samplers.fetch_add(1, Ordering::Relaxed); + } + } else if !c.samplers.is_empty() { + vs_static_samplers.fetch_add(1, Ordering::Relaxed); + } + if from_cache { + cached.fetch_add(1, Ordering::Relaxed); + } else { + compiled.fetch_add(1, Ordering::Relaxed); + } + continue; + } + // Incomplete translation (`!t.complete()`): fall through to the existing + // per-program loop below so standalone `--precompile` and hosted + // `prepare_for_launch` keep their exact skip behavior without errors. + recomp::pso::CompileOutcome::Incomplete(_) => {} + recomp::pso::CompileOutcome::Failed(e) => { + let mut g = errors.lock().unwrap(); + if g.len() < 10 { + g.push(format!("{name}: {}", e.lines().find(|l| l.contains("error")).unwrap_or(e.lines().next().unwrap_or("")))); + } + failed.fetch_add(1, Ordering::Relaxed); + continue; + } + } + } let jobs: Vec<(&str, Option)> = match &mode { recomp::Mode::Vertex(_) => vec![("vs_6_6", None)], recomp::Mode::Pixel(_) => vec![("ps_6_6", None)], @@ -1722,6 +1769,12 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on skipped.into_inner(), t0.elapsed().as_secs_f64() ); + let (ps_base0, ps_static_samplers, vs_static_samplers) = (ps_base0.into_inner(), ps_static_samplers.into_inner(), vs_static_samplers.into_inner()); + if ps_base0 > 0 || vs_static_samplers > 0 { + println!( + "graphics variants (runtime path): PS warmed at assumed sampler_base=0: {ps_base0} ({ps_static_samplers} with static samplers); VS with static samplers shifting paired PS base: {vs_static_samplers}" + ); + } if used.is_some() { println!("compute programs passed over (no earlier run used their pipeline): {}", unused.into_inner()); } diff --git a/crates/xcl/tests/shaders_e2e.rs b/crates/xcl/tests/shaders_e2e.rs index 337b4fe6b0..32f34b9612 100644 --- a/crates/xcl/tests/shaders_e2e.rs +++ b/crates/xcl/tests/shaders_e2e.rs @@ -37,6 +37,13 @@ fn xbox_shader(kind: u32, fssms: &[Vec]) -> Vec { container(&[(b"SFI0", &[0; 8]), (b"HASH", &[0; 20]), (b"DXIL", &dxil_part(kind, fssms)), (b"PRIV", &[7; 16])]) } +fn xbox_shader_with_osg(kind: u32, fssms: &[Vec], osg: &[u8]) -> Vec { + let base = xbox_shader(kind, fssms); + let dxil = xcl::gpu::shader::container_parts(&base).unwrap().into_iter().find(|p| p.fourcc == "DXIL").unwrap(); + let dxil_bytes = &base[dxil.offset..dxil.offset + dxil.size]; + container(&[(b"SFI0", &[0; 8]), (b"OSG1", osg), (b"HASH", &[0; 20]), (b"DXIL", dxil_bytes), (b"PRIV", &[7; 16])]) +} + fn rpf9_record(name: &str, payload: &[u8], usize_override: Option) -> Vec { let z = miniz_oxide::deflate::compress_to_vec(payload, 6); let mut v = vec![(name.len() + 1) as u8]; @@ -290,3 +297,277 @@ fn shaders_rejects_unknown_options_missing_values_and_mistyped_values() { assert!(out.stdout.is_empty(), "args {args:?}: unexpected stdout {:?}", String::from_utf8_lossy(&out.stdout)); } } + +/// Constant S# in s[24:27] (point/clamp) + image_sample_lz -> v[10:13] + export (keeps sampler live) + s_endpgm. +fn static_sampler_code(exp_w0: u32) -> Vec { + let words: [u32; 11] = [ + 0xBE98_03FF, 0x0000_0092, 0xBE99_03FF, 0x00FF_F000, 0xBE9A_0380, 0xBE9B_0380, + 0xF09C_0F08, 0x00C4_0A00, exp_w0, 0x0D0C_0B0A, 0xBF81_0000, + ]; + words.iter().flat_map(|w| w.to_le_bytes()).collect() +} + +fn find_files_named(dir: &Path, needle: &str) -> Vec { + let mut out = Vec::new(); + let Ok(rd) = std::fs::read_dir(dir) else { return out }; + for entry in rd.flatten() { + let p = entry.path(); + if p.is_dir() { + out.extend(find_files_named(&p, needle)); + } else if p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.contains(needle)) { + out.push(p); + } + } + out +} + +fn time_native_graphics_pso(vs: &xcl::gpu::recomp::pso::Compiled, ps: &xcl::gpu::recomp::pso::Compiled) -> Result, String> { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, IDXGIAdapter1, IDXGIFactory6, DXGI_CREATE_FACTORY_FLAGS}; + let Ok(factory) = (unsafe { CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) }) else { + return Ok(None); + }; + let sel = xcl::gpu::adapter::Selector::from_env_or("auto"); + let adapter: IDXGIAdapter1 = if sel == xcl::gpu::adapter::Selector::Warp { + let Ok(a) = (unsafe { factory.EnumWarpAdapter() }) else { return Ok(None) }; + a + } else { + let Some(a) = xcl::gpu::adapter::candidates(&factory, &sel) + .into_iter() + .next() + .map(|(a, _)| a) + .or_else(|| unsafe { factory.EnumWarpAdapter().ok() }) + else { + return Ok(None); + }; + a + }; + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + return Ok(None); + } + let Some(dev) = dev else { return Ok(None) }; + let mut samplers = vs.samplers.clone(); + samplers.extend_from_slice(&ps.samplers); + let rs = xcl::gpu::recomp::pso::abi_root_signature_with(&dev, true, &samplers) + .map_err(|e| format!("abi_root_signature_with failed: {e}"))?; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs)), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.dxil.as_ptr().cast(), BytecodeLength: vs.dxil.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.dxil.as_ptr().cast(), BytecodeLength: ps.dxil.len() }, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, ..Default::default() }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let t0 = std::time::Instant::now(); + let pso: Result = unsafe { dev.CreateGraphicsPipelineState(&desc) }; + let ms = t0.elapsed().as_secs_f64() * 1e3; + unsafe { std::mem::ManuallyDrop::drop(&mut desc.pRootSignature) }; + pso.map(|_| Some(ms)) + .map_err(|e| format!("CreateGraphicsPipelineState failed: {e} ({:#x})", e.code().0 as u32)) +} + +fn spawn_child_check(test_name: &str, dir: &Path, cache: &Path, direct: &str) -> Output { + Command::new(std::env::current_exe().unwrap()) + .args(["--exact", test_name, "--nocapture"]) + .env("XCL_SHADERS_E2E_CHILD", "1") + .env("XCL_SHADERS_E2E_DIR", dir) + .env("XCL_DIRECT_DXIL", direct) + .env("XCL_DXIL_CACHE", cache) + .env_remove("XCL_TRANSLATED_CACHE") + .output() + .expect("spawn fresh child test process") +} + +#[test] +fn precompile_warms_direct_vs_ps_and_hits_in_fresh_process() { + use xcl::gpu::recomp::{dxc, pso}; + if std::env::var_os("XCL_SHADERS_E2E_CHILD").is_some() { + let dir = PathBuf::from(std::env::var_os("XCL_SHADERS_E2E_DIR").unwrap()); + let (vs_blob, ps_blob) = (std::fs::read(dir.join("vs.bin")).unwrap(), std::fs::read(dir.join("ps.bin")).unwrap()); + let t0 = std::time::Instant::now(); + let (vs_res, vs_missed) = dxc::cached_only(|| pso::console_to_dxil_in(&vs_blob, pso::Stage::Vertex, 0, false, 1)); + let (ps_res, ps_missed) = dxc::cached_only(|| pso::console_to_dxil_in(&ps_blob, pso::Stage::Pixel, 0, false, 1)); + let warm_ms = t0.elapsed().as_secs_f64() * 1e3; + let (vs_c, ps_c) = (vs_res.expect("warm direct VS hit"), ps_res.expect("warm direct PS hit")); + assert!(!vs_missed && !ps_missed, "fresh process must hit translated/v2 cache"); + assert_eq!(dxc::compile_counts().1, 0, "fresh process direct hit must invoke 0 DXC compiles"); + match time_native_graphics_pso(&vs_c, &ps_c).expect("direct graphics PSO creation failed") { + Some(pso_ms) => println!("fresh_child_timing: mode=direct warm_translate_dxc_ms={warm_ms:.3} native_pso_ms={pso_ms:.3}"), + None => { + xcl::gpu::recomp::runner::skip_test("no D3D12 device"); + println!("fresh_child_timing: mode=direct warm_translate_dxc_ms={warm_ms:.3} native_pso_ms=skipped(no_gpu)"); + } + } + return; + } + let (dir, cache) = (TempDir::new("direct-gfx"), TempDir::new("direct-gfx-cache")); + std::fs::write(dir.path().join("vs.bin"), xbox_shader(1, &[fssm(&CODE, &[(4, 0)])])).unwrap(); + std::fs::write(dir.path().join("ps.bin"), xbox_shader(0, &[fssm(&CODE, &[(5, 1)])])).unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_xcl")) + .args(["shaders", dir.path().to_str().unwrap(), "--precompile", "--windows", "1", "--split", "0"]) + .env("XCL_DIRECT_DXIL", "all") + .env("XCL_DXIL_CACHE", cache.path()) + .env_remove("XCL_TRANSLATED_CACHE") + .output() + .expect("spawn xcl shaders --precompile"); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success(), "precompile failed: {out:?}"); + assert!(stdout.contains("compiled 2, already cached 0, errors 0"), "{stdout}"); + assert!(stdout.contains("PS warmed at assumed sampler_base=0: 1"), "{stdout}"); + let warm_out = Command::new(env!("CARGO_BIN_EXE_xcl")) + .args(["shaders", dir.path().to_str().unwrap(), "--precompile", "--windows", "1", "--split", "0"]) + .env("XCL_DIRECT_DXIL", "all") + .env("XCL_DXIL_CACHE", cache.path()) + .env_remove("XCL_TRANSLATED_CACHE") + .output() + .expect("spawn warm xcl shaders --precompile"); + let warm_stdout = String::from_utf8_lossy(&warm_out.stdout); + assert!(warm_out.status.success(), "warm precompile failed: {warm_out:?}"); + assert!(warm_stdout.contains("compiled 0, already cached 2, errors 0"), "{warm_stdout}"); + let v2 = cache.path().join("translated").join("v2"); + assert!(!find_files_named(&v2, "_Vertex_0_").is_empty(), "missing _Vertex_0_ in {}", v2.display()); + assert!(!find_files_named(&v2, "_Pixel_0_").is_empty(), "missing _Pixel_0_ in {}", v2.display()); + let child = spawn_child_check("precompile_warms_direct_vs_ps_and_hits_in_fresh_process", dir.path(), cache.path(), "all"); + let c_out = String::from_utf8_lossy(&child.stdout); + print!("{c_out}"); + assert!(child.status.success(), "fresh child failed: {child:?}\n{c_out}"); + assert!(c_out.contains("fresh_child_timing: mode=direct"), "{c_out}"); +} + +#[test] +fn precompile_warms_hlsl_static_samplers_and_reports_base_shift() { + use xcl::gpu::recomp::{dxc, pso}; + if std::env::var_os("XCL_SHADERS_E2E_CHILD").is_some() { + let dir = PathBuf::from(std::env::var_os("XCL_SHADERS_E2E_DIR").unwrap()); + let (vs_blob, ps_blob) = (std::fs::read(dir.join("vs.bin")).unwrap(), std::fs::read(dir.join("ps.bin")).unwrap()); + let t0 = std::time::Instant::now(); + let (vs_res, vs_missed) = dxc::cached_only(|| pso::console_to_dxil_in(&vs_blob, pso::Stage::Vertex, 0, false, 1)); + let (ps0_res, ps0_missed) = dxc::cached_only(|| pso::console_to_dxil_in(&ps_blob, pso::Stage::Pixel, 0, false, 1)); + let warm_ms = t0.elapsed().as_secs_f64() * 1e3; + let (vs_c, ps0_c) = (vs_res.expect("warm HLSL VS hit"), ps0_res.expect("warm HLSL PS base=0 hit")); + assert!(!vs_missed && !ps0_missed, "fresh process must hit VS and PS(base=0)"); + assert_eq!((vs_c.samplers.len(), ps0_c.samplers.len()), (1, 1)); + assert_eq!(dxc::compile_counts().1, 0, "warm hits must not invoke DXC"); + let (_ps1_probe, ps1_missed) = dxc::cached_only(|| pso::console_to_dxil_in(&ps_blob, pso::Stage::Pixel, 1, false, 1)); + assert!(ps1_missed, "paired PS(base=1) must miss base=0 entry"); + let ps1_c = pso::console_to_dxil_in(&ps_blob, pso::Stage::Pixel, 1, false, 1).expect("PS base=1 compile"); + assert_eq!(ps1_c.samplers.len(), 1); + assert_ne!(ps1_c.dxil, ps0_c.dxil, "PS(base=1) DXIL must differ from PS(base=0)"); + match time_native_graphics_pso(&vs_c, &ps1_c).expect("HLSL graphics PSO creation failed") { + Some(pso_ms) => println!("fresh_child_timing: mode=hlsl warm_translate_dxc_ms={warm_ms:.3} native_pso_ms={pso_ms:.3}"), + None => { + xcl::gpu::recomp::runner::skip_test("no D3D12 device"); + println!("fresh_child_timing: mode=hlsl warm_translate_dxc_ms={warm_ms:.3} native_pso_ms=skipped(no_gpu)"); + } + } + return; + } + if dxc::location().is_err() { + xcl::gpu::recomp::runner::skip_test("no DXC"); + return; + } + let (dir, cache) = (TempDir::new("hlsl-gfx"), TempDir::new("hlsl-gfx-cache")); + use xcl::gpu::dxil::container::{signature_part, SigPartElement}; + let ps_osg = signature_part(&[SigPartElement { stream: 0, name: "SV_Target".into(), index: 0, system_value: 64, comp_type: 3, register: 0, mask: 0xF, rw_mask: 0, min_precision: 0 }], &[]); + // exp pos0 (TGT=12, DONE=1, EN=0xf) for VS and exp mrt0 (TGT=0, VM=1, DONE=1, EN=0xf) for PS. + std::fs::write(dir.path().join("vs.bin"), xbox_shader(1, &[fssm(&static_sampler_code(0xF800_08CF), &[(4, 0)])])).unwrap(); + std::fs::write(dir.path().join("ps.bin"), xbox_shader_with_osg(0, &[fssm(&static_sampler_code(0xF800_180F), &[(5, 1)])], &ps_osg)).unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_xcl")) + .args(["shaders", dir.path().to_str().unwrap(), "--precompile", "--windows", "1", "--split", "0"]) + .env("XCL_DIRECT_DXIL", "0") + .env("XCL_DXIL_CACHE", cache.path()) + .env_remove("XCL_TRANSLATED_CACHE") + .output() + .expect("spawn xcl shaders --precompile"); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success(), "precompile failed: {out:?}"); + assert!(stdout.contains("compiled 2, already cached 0, errors 0"), "{stdout}"); + assert!(stdout.contains("PS warmed at assumed sampler_base=0: 1 (1 with static samplers); VS with static samplers shifting paired PS base: 1"), "{stdout}"); + let warm_out = Command::new(env!("CARGO_BIN_EXE_xcl")) + .args(["shaders", dir.path().to_str().unwrap(), "--precompile", "--windows", "1", "--split", "0"]) + .env("XCL_DIRECT_DXIL", "0") + .env("XCL_DXIL_CACHE", cache.path()) + .env_remove("XCL_TRANSLATED_CACHE") + .output() + .expect("spawn warm hlsl xcl shaders --precompile"); + let warm_stdout = String::from_utf8_lossy(&warm_out.stdout); + assert!(warm_out.status.success(), "warm hlsl precompile failed: {warm_out:?}"); + assert!(warm_stdout.contains("compiled 0, already cached 2, errors 0"), "{warm_stdout}"); + let child = spawn_child_check("precompile_warms_hlsl_static_samplers_and_reports_base_shift", dir.path(), cache.path(), "0"); + let c_out = String::from_utf8_lossy(&child.stdout); + print!("{c_out}"); + assert!(child.status.success(), "fresh child failed: {child:?}\n{c_out}"); + assert!(c_out.contains("fresh_child_timing: mode=hlsl"), "{c_out}"); +} + +#[test] +fn precompile_skips_incomplete_vs_while_warming_supported_vs() { + use xcl::gpu::recomp::{dxc, pso}; + if std::env::var_os("XCL_SHADERS_E2E_CHILD").is_some() { + let dir = PathBuf::from(std::env::var_os("XCL_SHADERS_E2E_DIR").unwrap()); + let supported = std::fs::read(dir.join("supported_vs.bin")).unwrap(); + let unsupported = std::fs::read(dir.join("unsupported_vs.bin")).unwrap(); + let (vs_res, vs_missed) = dxc::cached_only(|| pso::console_to_dxil_in(&supported, pso::Stage::Vertex, 0, false, 1)); + vs_res.expect("supported VS must hit warmed translated/v2 cache"); + assert!(!vs_missed, "fresh process must hit warmed VS cache"); + assert_eq!(dxc::compile_counts().1, 0, "fresh process direct hit must invoke 0 DXC compiles"); + match pso::console_to_dxil_in_outcome(&unsupported, pso::Stage::Vertex, 0, false, 1) { + pso::CompileOutcome::Incomplete(msg) => assert!(msg.contains("v_cvt_off_f32_i4"), "unexpected incomplete msg: {msg}"), + pso::CompileOutcome::Compiled { .. } => panic!("unsupported VS unexpectedly compiled"), + pso::CompileOutcome::Failed(e) => panic!("unsupported VS should be Incomplete, got Failed: {e}"), + } + return; + } + + let (dir, cache) = (TempDir::new("incomplete-vs"), TempDir::new("incomplete-vs-cache")); + let supported_vs = xbox_shader(1, &[fssm(&CODE, &[(4, 0)])]); + let mut unsupported_code = xcl::gpu::rdna2::encode("V_CVT_OFF_F32_I4", "ENC_VOP1", &[("VDST", 0), ("SRC0", 256)], None) + .expect("encode V_CVT_OFF_F32_I4"); + unsupported_code.extend_from_slice(&0xBF81_0000u32.to_le_bytes()); // s_endpgm + let unsupported_vs = xbox_shader(1, &[fssm(&unsupported_code, &[(4, 0)])]); + std::fs::write(dir.path().join("supported_vs.bin"), &supported_vs).unwrap(); + std::fs::write(dir.path().join("unsupported_vs.bin"), &unsupported_vs).unwrap(); + + let cold = Command::new(env!("CARGO_BIN_EXE_xcl")) + .args(["shaders", dir.path().to_str().unwrap(), "--precompile", "--windows", "1", "--split", "0"]) + .env("XCL_DIRECT_DXIL", "all") + .env("XCL_DXIL_CACHE", cache.path()) + .env_remove("XCL_TRANSLATED_CACHE") + .output() + .expect("spawn cold xcl shaders --precompile"); + let cold_stdout = String::from_utf8_lossy(&cold.stdout); + assert!(cold.status.success(), "cold precompile failed: {cold:?}\n{cold_stdout}"); + assert!( + cold_stdout.contains("compiled 1, already cached 0, errors 0, skipped (GS – paired at pipeline creation) 0"), + "{cold_stdout}" + ); + + let warm = Command::new(env!("CARGO_BIN_EXE_xcl")) + .args(["shaders", dir.path().to_str().unwrap(), "--precompile", "--windows", "1", "--split", "0"]) + .env("XCL_DIRECT_DXIL", "all") + .env("XCL_DXIL_CACHE", cache.path()) + .env_remove("XCL_TRANSLATED_CACHE") + .output() + .expect("spawn warm xcl shaders --precompile"); + let warm_stdout = String::from_utf8_lossy(&warm.stdout); + assert!(warm.status.success(), "warm precompile failed: {warm:?}\n{warm_stdout}"); + assert!( + warm_stdout.contains("compiled 0, already cached 1, errors 0, skipped (GS – paired at pipeline creation) 0"), + "{warm_stdout}" + ); + + let v2 = cache.path().join("translated").join("v2"); + assert!(!find_files_named(&v2, "_Vertex_0_").is_empty(), "missing warmed _Vertex_0_ in {}", v2.display()); + + let child = spawn_child_check("precompile_skips_incomplete_vs_while_warming_supported_vs", dir.path(), cache.path(), "all"); + let c_out = String::from_utf8_lossy(&child.stdout); + assert!(child.status.success(), "fresh child failed: {child:?}\n{c_out}\n{}", String::from_utf8_lossy(&child.stderr)); +}