diff --git a/d3d12/README.md b/d3d12/README.md index bdb2084392..fa6ae23754 100644 --- a/d3d12/README.md +++ b/d3d12/README.md @@ -4,6 +4,16 @@ This is Leonida's Direct3D 12 runtime: it builds as `leonida.exe`, takes `LEONID still work) and is launched by Leonida's `scripts/play-d3d12.ps1` on Windows and `scripts/play-linux.sh` on Linux (with VKD3D-Proton bundled, `docs/linux.md`). +**Runtime shaders on Wine.** Put the matching x64 `dxcompiler.dll` and `dxil.dll` from one +[Microsoft DirectX Shader Compiler release](https://github.com/microsoft/DirectXShaderCompiler/releases) +next to the Windows executable actually launched (`leonida.exe`, or the file selected by `LEONIDA_RUNTIME`; +for Rust tests, next to their `.exe` in `target/.../deps/`). The Linux launcher installs VKD3D-Proton into +its prefix separately; do not put the DXC pair in the prefix's System32 directory. If the prefix overrides +either DLL to builtin-only, prefer the native pair (`WINEDLLOVERRIDES='dxcompiler,dxil=n'`). +Wine's built-in FXC can compile a shader without preserving its embedded root signature. When the app-local +DXC pair is missing or cannot load, the runtime warns once and uses FXC; affected passes may still fail. +Native Windows continues to use the system FXC and does not require either DLL. + It grew from the VIctory runtime: Marvisak/VIctory, through trustno1-coder/VIctory-NVIDIA (merged into Leonida at `bafb0e25b`) and the forks credited below. Like them it is GPL-3.0-or-later (`LICENSE`). Leonida renamed it and adds its own work on top; everything below this section is trustno1-coder/VIctory-NVIDIA's README as it came, with the diff --git a/d3d12/crates/leonida-gpu/Cargo.toml b/d3d12/crates/leonida-gpu/Cargo.toml index b7806fe009..1dcbe89215 100644 --- a/d3d12/crates/leonida-gpu/Cargo.toml +++ b/d3d12/crates/leonida-gpu/Cargo.toml @@ -41,6 +41,7 @@ workspace = true windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] } windows = { workspace = true, features = [ "Win32_Graphics_Direct3D", + "Win32_Graphics_Direct3D_Dxc", "Win32_Graphics_Direct3D_Fxc", "Win32_Graphics_Direct3D12", "Win32_Graphics_Dxgi", diff --git a/d3d12/crates/leonida-gpu/src/ambient_readback.rs b/d3d12/crates/leonida-gpu/src/ambient_readback.rs new file mode 100644 index 0000000000..0dde913f06 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/ambient_readback.rs @@ -0,0 +1,97 @@ +//! An opt-in, synthetic hardware readback through the actual radiance and fog passes. + +use crate::ambient::{self, Role, Views}; +use crate::host::{host, transition}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R11G11B10_FLOAT, DXGI_SAMPLE_DESC}; +use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, DXGI_ADAPTER_FLAG_SOFTWARE, IDXGIAdapter1, IDXGIFactory4}; + +// R11G11B10_FLOAT uses an exponent bias of 15 and 6/6/5 mantissa bits. +fn grey(exponent: u32, half: bool) -> u32 { + let r = exponent << 6 | u32::from(half) << 5; + let b = exponent << 5 | u32::from(half) << 4; + r | r << 11 | b << 22 +} + +#[test] +#[ignore = "run alone on hardware with LEONIDA_AMBIENT=1 and LEONIDA_AMBIENT_AIR=1"] +fn radiance_changes_the_fog_readback() { + for var in ["LEONIDA_AMBIENT", "LEONIDA_AMBIENT_AIR"] { + assert_eq!(std::env::var(var).as_deref(), Ok("1"), "{var} must be 1"); + } + let host = host().expect("physical D3D12 device"); + let dev = &host.device; + let run = host.new_list().expect("command list"); + let list = &run.list; + // SAFETY: local D3D12 objects are kept through the synchronous submission. Copy locations + // borrow their resource; all rows start at aligned offsets and fit the staging allocations. + unsafe { + let dxgi: IDXGIFactory4 = CreateDXGIFactory2(Default::default()).unwrap(); + let adapter: IDXGIAdapter1 = dxgi.EnumAdapterByLuid(dev.GetAdapterLuid()).unwrap(); + let info = adapter.GetDesc1().unwrap(); + assert_eq!(info.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32, 0, "software adapter"); + let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { Format: DXGI_FORMAT_R11G11B10_FLOAT, ..Default::default() }; + dev.CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, (&raw mut support).cast(), std::mem::size_of_val(&support) as u32).unwrap(); + assert!(support.Support2.contains(D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD | D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE)); + let heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, ..Default::default() + }).unwrap(); + let step = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + let (up, data) = host.upload_buffer(1024).unwrap(); + let back = host.read_back_buffer(256).unwrap(); + let tex = |dimension, width: u64, slot: usize| { + let desc = D3D12_RESOURCE_DESC { + Dimension: dimension, Width: width, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + Format: DXGI_FORMAT_R11G11B10_FLOAT, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default() + }; + let mut out: Option = None; + let mem = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + dev.CreateCommittedResource(&mem, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut out).unwrap(); + let out = out.unwrap(); + let mut cpu = heap.GetCPUDescriptorHandleForHeapStart(); + cpu.ptr += slot * step as usize; + dev.CreateUnorderedAccessView(&out, None::<&ID3D12Resource>, None, cpu); + out + }; + let image = tex(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 2, 0); + let fog = tex(D3D12_RESOURCE_DIMENSION_TEXTURE3D, 4, 1); + let sub = |res: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(res), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + let row = |res: &ID3D12Resource, offset, width| D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(res), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: offset, Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: DXGI_FORMAT_R11G11B10_FLOAT, + Width: width, Height: 1, Depth: 1, RowPitch: 256 }, + } }, + }; + let light = [grey(15, false), grey(16, true)]; // Half the cells see 1; the other half see 3. + let input = [grey(18, false), grey(14, false), grey(31, false), grey(15, false)]; // 8, 0.5, +inf, 1 + data.cast::().copy_from_nonoverlapping(light.as_ptr(), light.len()); + data.add(512).cast::().copy_from_nonoverlapping(input.as_ptr(), input.len()); + list.CopyTextureRegion(&sub(&image), 0, 0, 0, &row(&up, 0, 2), None); + list.CopyTextureRegion(&sub(&fog), 0, 0, 0, &row(&up, 512, 4), None); + list.ResourceBarrier(&[transition(&image, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + transition(&fog, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + list.SetDescriptorHeaps(&[Some(heap.clone())]); + for (slot, role, width) in [(0, Role::Radiance, 2), (1, Role::Air, 4)] { + let mut handle = heap.GetGPUDescriptorHandleForHeapStart(); + handle.ptr += slot * u64::from(step); + assert!(ambient::after(&run, role, &Views { image: handle, depth: None, size: [width, 1], slices: 1 }), "{role:?} was not recorded"); + } + list.ResourceBarrier(&[transition(&fog, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyTextureRegion(&row(&back, 0, 4), 0, 0, 0, &sub(&fog), None); + run.close(); + host.execute_sync_internal(&run); + dev.GetDeviceRemovedReason().unwrap(); + let mut mapped = std::ptr::null_mut(); + back.Map(0, Some(&D3D12_RANGE { Begin: 0, End: 16 }), Some(&mut mapped)).unwrap(); + let got = mapped.cast::<[u32; 4]>().read(); + back.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); + assert_eq!(got, [grey(16, false), input[1], 0, input[3]], "radiance mean caps 8 at 2; fog clears infinity"); + eprintln!("physical {:04x}:{:04x}, packed fog readback: {got:08x?}", info.VendorId, info.DeviceId); + } +} diff --git a/d3d12/crates/leonida-gpu/src/compiler.rs b/d3d12/crates/leonida-gpu/src/compiler.rs new file mode 100644 index 0000000000..a472ec5673 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/compiler.rs @@ -0,0 +1,340 @@ +//! In-process compilation of the runtime's own, self-contained HLSL. + +use std::ffi::c_void; +use std::os::windows::ffi::OsStrExt; +use std::path::Path; +use std::sync::LazyLock; + +use windows::Win32::Foundation::{E_FAIL, E_INVALIDARG, FreeLibrary, HMODULE}; +use windows::Win32::Graphics::Direct3D::Dxc::{ + CLSID_DxcCompiler, DXC_CP_UTF8, DXC_OUT_ERRORS, DxcBuffer, IDxcBlob, IDxcBlobUtf8, IDxcBlobUtf16, IDxcCompiler3, + IDxcIncludeHandler, IDxcResult, +}; +use windows::Win32::Graphics::Direct3D::Fxc::{D3DCOMPILE_ENABLE_UNBOUNDED_DESCRIPTOR_TABLES, D3DCompile}; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::System::LibraryLoader::{ + GetModuleHandleW, GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW, +}; +use windows::core::{Error, GUID, HRESULT, Interface, PCSTR, PCWSTR, Result, s, w}; + +pub(super) enum CompiledShader { + Fxc(ID3DBlob), + Dxc(IDxcBlob), +} + +impl CompiledShader { + pub(super) fn bytes(&self) -> Result<&[u8]> { + // SAFETY: each pointer and size describe the bytes of the compiler blob we still own. + unsafe { + match self { + Self::Fxc(blob) => blob_bytes(blob, blob.GetBufferPointer(), blob.GetBufferSize()), + Self::Dxc(blob) => blob_bytes(blob, blob.GetBufferPointer(), blob.GetBufferSize()), + } + } + .ok_or_else(Error::empty) + } +} + +/// Compiles owned runtime HLSL as native Windows does, or through app-local DXC on Wine. +/// This diagnostics entry point uses the same path as the runtime's SM 5.1 helpers. +/// +/// # Safety +/// `entry` and `target` must point to readable NUL-terminated names for the duration of the call. +#[cfg(feature = "diagnostics")] +#[doc(hidden)] +pub unsafe fn compile_runtime_hlsl(source: &str, entry: PCSTR, target: PCSTR, flags: u32) -> Result> { + // SAFETY: the caller supplies valid entry and target names; the source name is optional. + let code = unsafe { compile_named(source, PCSTR::null(), entry, target, flags)? }; + Ok(code.bytes()?.to_vec()) +} + +/// # Safety +/// `entry`, `target`, and a non-null `name` must be readable NUL-terminated names. +pub(super) unsafe fn compile_named(source: &str, name: PCSTR, entry: PCSTR, target: PCSTR, flags: u32) -> Result { + // DXC supports unbounded descriptor tables by default. Leave profiles and flags we + // don't translate to FXC so they are not silently changed. + if flags & !D3DCOMPILE_ENABLE_UNBOUNDED_DESCRIPTOR_TABLES == 0 && on_wine() { + // SAFETY: target is a null-terminated profile as required above. + let profile = match unsafe { target.as_bytes() } { + b"cs_5_1" => Some(w!("cs_6_0")), + b"ps_5_1" => Some(w!("ps_6_0")), + b"vs_5_1" => Some(w!("vs_6_0")), + _ => None, + }; + if let Some(profile) = profile { + static DXC: LazyLock> = LazyLock::new(|| match load_dxc() { + Ok(create) => Some(create), + Err(error) => { + tracing::warn!(%error, "app-local DXC unavailable; using FXC on Wine (embedded root signatures may be missing)"); + None + } + }); + if let Some(create) = *DXC { + // SAFETY: entry is a null-terminated name as required above. + let entry = std::str::from_utf8(unsafe { entry.as_bytes() }) + .map_err(|_| Error::new(E_INVALIDARG, "DXC entry point must be UTF-8"))?; + return compile_dxc(create, source, entry, profile); + } + } + } + + let (mut code, mut errors): (Option, Option) = (None, None); + // SAFETY: the source and names live through the call, and both out pointers are ours. + let compiled = unsafe { + D3DCompile(source.as_ptr().cast(), source.len(), name, None, None, entry, target, flags, 0, &mut code, Some(&mut errors)) + }; + if let Err(error) = compiled { + if let Some(errors) = errors { + // SAFETY: pointer and size refer to this live compiler blob. + if let Some(text) = unsafe { blob_bytes(&errors, errors.GetBufferPointer(), errors.GetBufferSize()) } { + tracing::warn!("FXC: {}", String::from_utf8_lossy(text).trim_end_matches('\0')); + } + } + return Err(error); + } + code.map(CompiledShader::Fxc).ok_or_else(Error::empty) +} + +fn on_wine() -> bool { + static WINE: LazyLock = LazyLock::new(|| { + // SAFETY: ntdll is loaded for the lifetime of the process; these names are terminated. + unsafe { + GetModuleHandleW(w!("ntdll.dll")) + .is_ok_and(|ntdll| GetProcAddress(ntdll, s!("wine_get_version")).is_some()) + } + }); + *WINE +} + +type CreateInstance = unsafe extern "system" fn(*const GUID, *const GUID, *mut *mut c_void) -> HRESULT; + +fn load_app_dll(path: &Path) -> Result { + let name: Vec = path.as_os_str().encode_wide().chain([0]).collect(); + // SAFETY: called with a fully qualified path beside the executable, encoded with a NUL. + unsafe { LoadLibraryExW(PCWSTR(name.as_ptr()), None, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32) } + .map_err(|error| Error::new(error.code(), format!("{}: {error}", path.display()))) +} + +fn load_dxc() -> Result { + let exe = std::env::current_exe().map_err(|error| Error::new(E_FAIL, error.to_string()))?; + let dir = exe.parent().filter(|dir| dir.is_absolute()).ok_or_else(|| Error::new(E_FAIL, "no executable directory"))?; + load_dxc_from(dir) +} + +fn load_dxc_from(dir: &Path) -> Result { + let compiler = load_app_dll(&dir.join("dxcompiler.dll"))?; + // SAFETY: initialized module and NUL-terminated export name. + let factory = unsafe { GetProcAddress(compiler, s!("DxcCreateInstance")) } + .ok_or_else(|| Error::new(Error::from_thread().code(), "dxcompiler.dll has no DxcCreateInstance export")) + .and_then(|factory| { + // Keep both DLL references for the life of the process. Preload the matching validator + // by absolute path so DXC's later lookup by base name finds it without a path search. + load_app_dll(&dir.join("dxil.dll"))?; + // SAFETY: resolved the named DXC export; CreateInstance matches dxcapi.h. + Ok(unsafe { std::mem::transmute:: isize, CreateInstance>(factory) }) + }); + if factory.is_err() { + // SAFETY: we own this reference and won't use the address after an unsuccessful load. + let _ = unsafe { FreeLibrary(compiler) }; + } + factory +} + +fn invoke_dxc(create: CreateInstance, source: &str, entry: &str, profile: PCWSTR) -> Result { + let mut compiler = None::; + // SAFETY: the factory is from the retained DLL, and Option is its nullable out pointer. + unsafe { create(&CLSID_DxcCompiler, &IDxcCompiler3::IID, (&mut compiler as *mut Option).cast()).ok()? }; + let compiler = compiler.ok_or_else(Error::empty)?; + let entry: Vec = entry.encode_utf16().chain([0]).collect(); + let buffer = DxcBuffer { Ptr: source.as_ptr().cast(), Size: source.len(), Encoding: DXC_CP_UTF8.0 }; + let args = [ + w!("leonida.hlsl"), w!("-E"), PCWSTR(entry.as_ptr()), w!("-T"), profile, + w!("-HV"), w!("2016"), w!("-flegacy-macro-expansion"), w!("-O1"), + ]; + // SAFETY: buffer and arguments are readable and live for this synchronous compile. No includes. + unsafe { compiler.Compile(&buffer, Some(&args), None::<&IDxcIncludeHandler>) } +} + +fn compile_dxc(create: CreateInstance, source: &str, entry: &str, profile: PCWSTR) -> Result { + let result = invoke_dxc(create, source, entry, profile)?; + // SAFETY: result is a live DXC result from the synchronous call above. + unsafe { + let status = result.GetStatus()?; + if let Err(error) = status.ok() { + if let Some(message) = dxc_errors(&result) { + tracing::warn!("DXC: {message}"); + return Err(Error::new(status, message)); + } + return Err(error); + } + result.GetResult().map(CompiledShader::Dxc) + } +} + +/// # Safety +/// `result` must be a live DXC compile result on the current thread. +unsafe fn dxc_errors(result: &IDxcResult) -> Option { + if unsafe { result.HasOutput(DXC_OUT_ERRORS) }.as_bool() { + let mut output_name = None::; + let mut errors = None::; + if unsafe { result.GetOutput(DXC_OUT_ERRORS, &mut output_name, &mut errors) }.is_ok() + && let Some(errors) = errors + { + // SAFETY: pointer and length describe the UTF-8 bytes owned by `errors`. + if let Some(text) = unsafe { + blob_bytes(&errors, errors.GetStringPointer().0.cast_mut().cast(), errors.GetStringLength()) + } { + let message = String::from_utf8_lossy(text).trim_end_matches('\0').trim_end().to_owned(); + if !message.is_empty() { + return Some(message); + } + } + } + } + if let Ok(errors) = unsafe { result.GetErrorBuffer() } { + // SAFETY: pointer and size describe the fallback diagnostic blob owned by `errors`. + if let Some(text) = unsafe { blob_bytes(&errors, errors.GetBufferPointer(), errors.GetBufferSize()) } { + let message = String::from_utf8_lossy(text).trim_end_matches('\0').trim_end().to_owned(); + if !message.is_empty() { + return Some(message); + } + } + } + None +} + +/// # Safety +/// The pointer and size must describe the immutable bytes of `blob`. +unsafe fn blob_bytes(_blob: &impl Interface, pointer: *mut c_void, size: usize) -> Option<&[u8]> { + if pointer.is_null() || size == 0 || size > isize::MAX as usize { + return None; + } + // SAFETY: the caller ties the range to the owning blob, and its length and pointer were checked. + Some(unsafe { std::slice::from_raw_parts(pointer.cast(), size) }) +} + +#[cfg(test)] +fn test_dxc_factory() -> Option { + static TEST_DXC: LazyLock> = LazyLock::new(|| { + let pair = |dir: &Path| dir.is_absolute() && dir.join("dxcompiler.dll").is_file() && dir.join("dxil.dll").is_file(); + if let Some(dir) = std::env::var_os("LEONIDA_TEST_DXC_DIR").map(std::path::PathBuf::from).filter(|d| pair(d)) { + return load_dxc_from(&dir).ok(); + } + if let Ok(create) = load_dxc() { + return Some(create); + } + let kits = std::path::PathBuf::from(std::env::var_os("ProgramFiles(x86)")?).join("Windows Kits").join("10").join("bin"); + let mut candidates: Vec = std::fs::read_dir(kits) + .ok()? + .filter_map(|e| e.ok().map(|e| e.path().join("x64"))) + .filter(|d| pair(d)) + .collect(); + candidates.sort(); + candidates.into_iter().rev().find_map(|dir| load_dxc_from(&dir).ok()) + }); + *TEST_DXC +} + +#[cfg(test)] +pub(crate) fn test_dxc_compile(source: &str, entry: &str, profile: PCWSTR) -> Option>> { + let create = test_dxc_factory()?; + Some(compile_dxc(create, source, entry, profile).and_then(|code| Ok(code.bytes()?.to_vec()))) +} + +#[cfg(test)] +mod tests { + use super::*; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_COMPUTE_PIPELINE_STATE_DESC, D3D12_SHADER_BYTECODE, ID3D12PipelineState, ID3D12RootSignature, + }; + + #[test] + fn native_compile_preserves_embedded_root_signatures_and_reports_invalid_hlsl() { + // SAFETY: literal NUL-terminated names. + let cs = unsafe { + compile_named(crate::host::CARD_COMPARE, s!("card compare"), s!("main"), s!("cs_5_1"), 0) + } + .expect("CARD_COMPARE compiles with FXC"); + let bytes = cs.bytes().expect("compiled bytes"); + assert!(!bytes.is_empty()); + + let unbounded = r#" +#define RS "DescriptorTable(SRV(t0, numDescriptors=unbounded))" +ByteAddressBuffer tables[] : register(t0); +RWByteAddressBuffer out_buf : register(u0); +[RootSignature("UAV(u0), " RS)] +[numthreads(1, 1, 1)] +void main() { out_buf.Store(0, tables[0].Load(0)); } +"#; + // SAFETY: literal NUL-terminated names. + let table_cs = unsafe { + compile_named( + unbounded, + s!("unbounded"), + s!("main"), + s!("cs_5_1"), + D3DCOMPILE_ENABLE_UNBOUNDED_DESCRIPTOR_TABLES, + ) + } + .expect("unbounded descriptor table shader compiles"); + let table_bytes = table_cs.bytes().expect("compiled bytes"); + + if let Some(host) = crate::host::host() { + // SAFETY: valid compiled blobs with embedded root signatures. + unsafe { + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, bytes).expect("CARD_COMPARE root signature"); + let _pso: ID3D12PipelineState = host + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }, + ..Default::default() + }) + .expect("CARD_COMPARE compute PSO"); + let _table_root: ID3D12RootSignature = + host.device.CreateRootSignature(0, table_bytes).expect("unbounded table root signature"); + } + } + + // SAFETY: literal NUL-terminated names. + let bad = unsafe { compile_named("void main( {", s!("invalid"), s!("main"), s!("cs_5_1"), 0) }; + assert!(bad.is_err(), "invalid HLSL must fail compilation"); + } + + #[test] + fn dxc_compiles_card_compare_with_embedded_root_signature_and_utf8_errors() { + let Some(create) = test_dxc_factory() else { + eprintln!("skipping DXC unit check: no dxcompiler.dll + dxil.dll pair found"); + return; + }; + let compiled = compile_dxc(create, crate::host::CARD_COMPARE, "main", w!("cs_6_0")) + .expect("DXC compiles CARD_COMPARE as cs_6_0"); + let bytes = compiled.bytes().expect("compiled bytes"); + assert!(!bytes.is_empty()); + if let Some(host) = crate::host::host() { + // SAFETY: signed DXIL blob with embedded root signature. + unsafe { + let root: ID3D12RootSignature = + host.device.CreateRootSignature(0, bytes).expect("DXC CARD_COMPARE root signature"); + let _pso: ID3D12PipelineState = host + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }, + ..Default::default() + }) + .expect("DXC CARD_COMPARE compute PSO"); + } + } + + let bad = invoke_dxc(create, "void main( { not_hlsl;", "main", w!("cs_6_0")) + .expect("DXC returns a result for invalid HLSL"); + // Check DXC's own output directly because Wine may not preserve extended Error::new text. + // SAFETY: bad is a live DXC result from the call above. + let status = unsafe { bad.GetStatus() }.expect("DXC compile status"); + assert!(status.is_err(), "invalid HLSL must fail DXC compilation"); + let msg = unsafe { dxc_errors(&bad) }.expect("DXC diagnostic text"); + assert!(msg.contains("error:"), "expected UTF-8 DXC diagnostic, got: {msg:?}"); + assert!(compile_dxc(create, "void main( { not_hlsl;", "main", w!("cs_6_0")).is_err()); + } +} diff --git a/d3d12/crates/leonida-gpu/src/compose.rs b/d3d12/crates/leonida-gpu/src/compose.rs index 798db1d8da..5861eae7a1 100644 --- a/d3d12/crates/leonida-gpu/src/compose.rs +++ b/d3d12/crates/leonida-gpu/src/compose.rs @@ -1,9 +1,7 @@ -//! Two presented planes as one image: the console's display puts the second +//! Two presented planes as one image: the console's display puts the second //! (the interface) over the first (the scene), each scaled to the screen. //! Grand Theft Auto VI presents so on Series S. -use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; -use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; use windows::core::{PCSTR, s}; @@ -103,30 +101,14 @@ unsafe impl Send for Composer {} // SAFETY: as above. unsafe impl Sync for Composer {} -fn compile(entry: PCSTR, target: PCSTR) -> windows::core::Result { +fn compile(entry: PCSTR, target: PCSTR) -> windows::core::Result> { compile_source(&source(sharpen(), clean()), entry, target) } -fn compile_source(source: &str, entry: PCSTR, target: PCSTR) -> windows::core::Result { - let mut code: Option = None; - // SAFETY: the source and names live through the call; the out pointer is - // ours. - unsafe { - D3DCompile( - source.as_ptr().cast(), - source.len(), - s!("compose"), - None, - None, - entry, - target, - 0, - 0, - &mut code, - None, - )?; - } - code.ok_or_else(windows::core::Error::empty) +fn compile_source(source: &str, entry: PCSTR, target: PCSTR) -> windows::core::Result> { + // SAFETY: callers pass static NUL-terminated HLSL names from `s!`. + let code = unsafe { crate::compiler::compile_named(source, s!("compose"), entry, target, 0)? }; + Ok(code.bytes()?.to_vec()) } impl Composer { @@ -135,17 +117,14 @@ impl Composer { compile(s!("vs"), s!("vs_5_1"))?, compile(s!("ps"), s!("ps_5_1"))?, ); - // SAFETY: the blobs' own bytes, alive through the calls. + let code = |b: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: b.as_ptr().cast(), + BytecodeLength: b.len(), + }; + // SAFETY: `vs` and `ps` stay alive through root-signature and PSO creation. unsafe { - let bytes = |b: &ID3DBlob| { - std::slice::from_raw_parts(b.GetBufferPointer().cast::(), b.GetBufferSize()) - }; let device = &host.device; - let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes(&vs))?; - let code = |b: &ID3DBlob| D3D12_SHADER_BYTECODE { - pShaderBytecode: b.GetBufferPointer(), - BytecodeLength: b.GetBufferSize(), - }; + let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs)?; let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), VS: code(&vs), @@ -290,9 +269,7 @@ mod source_tests { #[test] fn the_composer_compiles_with_and_without_the_nan_clamp() { let bytes = |source: &str| { - let blob = compile_source(source, s!("ps"), s!("ps_5_1")).expect("the composer's pixel program compiles"); - // SAFETY: the blob's own bytes, copied while it lives. - unsafe { std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()).to_vec() } + compile_source(source, s!("ps"), s!("ps_5_1")).expect("the composer's pixel program compiles") }; for sharpen in [0.0, 0.6] { let (with, without) = (bytes(&source(sharpen, true)), bytes(&source(sharpen, false))); @@ -301,6 +278,22 @@ mod source_tests { compile_source(&source(0.6, true), s!("vs"), s!("vs_5_1")).expect("the vertex program compiles"); assert!(source(0.25, true).starts_with("#define SHARPEN 0.250\n#define CLEAN 1\n")); assert!(source(0.0, false).contains("#define CLEAN 0\n")); + + let src = source(0.6, true); + if let Some(vs) = crate::compiler::test_dxc_compile(&src, "vs", windows::core::w!("vs_6_0")) { + let vs = vs.expect("DXC compiles composer vs_6_0"); + let ps = crate::compiler::test_dxc_compile(&src, "ps", windows::core::w!("ps_6_0")) + .unwrap() + .expect("DXC compiles composer ps_6_0"); + assert!(!ps.is_empty()); + if let Some(host) = crate::host::host() { + // SAFETY: signed DXIL blob with embedded root signature. + unsafe { + let _root: ID3D12RootSignature = + host.device.CreateRootSignature(0, &vs).expect("DXC composer root signature"); + } + } + } } } diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index 263d0e4f38..43ea6f1b61 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -1641,52 +1641,15 @@ fn plane_pass() -> Option<&'static PlanePass> { Some(PASS.get_or_init(|| PlanePass { made: Mutex::default() })) } -/// Compiles function `entry` of `source` for `target` with the system's -/// compiler, as the indirect-argument clamp is (`crate::indirect`). +/// Compiles `entry` of one of our runtime shaders. Callers use `s!` names. pub(crate) fn compile( source: &str, entry: windows::core::PCSTR, target: windows::core::PCSTR, ) -> windows::core::Result> { - use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; - use windows::Win32::Graphics::Direct3D::ID3DBlob; - let mut code: Option = None; - let mut errors: Option = None; - // SAFETY: the source and names live through the call; out pointers ours. - let compiled = unsafe { - D3DCompile( - source.as_ptr().cast(), - source.len(), - windows::core::s!("leonida"), - None, - None, - entry, - target, - 0, - 0, - &mut code, - Some(&mut errors), - ) - }; - if let Err(e) = compiled { - if let Some(errors) = errors { - // SAFETY: the blob's own bytes. - let text = unsafe { - std::slice::from_raw_parts( - errors.GetBufferPointer().cast::(), - errors.GetBufferSize(), - ) - }; - tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text)); - } - return Err(e); - } - let code = code.ok_or_else(windows::core::Error::empty)?; - // SAFETY: the blob's own bytes. - let bytes = unsafe { - std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) - }; - Ok(bytes.to_vec()) + // SAFETY: callers pass static NUL-terminated HLSL names from `s!`. + let code = unsafe { crate::compiler::compile_named(source, windows::core::s!("leonida"), entry, target, 0)? }; + Ok(code.bytes()?.to_vec()) } impl PlanePass { @@ -5587,37 +5550,26 @@ impl Host { } fn make_card_work(&self) -> windows::core::Result { - use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; - use windows::Win32::Graphics::Direct3D::ID3DBlob; - let mut code: Option = None; - // SAFETY: the source and names live through the call; the out - // pointer is ours. - unsafe { - D3DCompile( - CARD_COMPARE.as_ptr().cast(), - CARD_COMPARE.len(), + // SAFETY: literal names are NUL-terminated. + let code = unsafe { + crate::compiler::compile_named( + CARD_COMPARE, windows::core::s!("card compare"), - None, - None, windows::core::s!("main"), windows::core::s!("cs_5_1"), 0, - 0, - &mut code, - None, - )?; - } - let code = code.ok_or_else(windows::core::Error::empty)?; + )? + }; + let bytes = code.bytes()?; let list = || self.make_prelude().ok_or_else(windows::core::Error::empty); // A megabyte of results: 262,144 pieces, 16 GB of declared ranges // in one submission. const RESULTS: u64 = 1 << 20; let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?; name(&differs, || "card compare results".into()); - // SAFETY: the blob's own bytes; the root signature is inside the - // shader. + // SAFETY: `code` owns `bytes` through root-signature and PSO creation; + // the root signature is inside the shader. unsafe { - let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), diff --git a/d3d12/crates/leonida-gpu/src/host/trainer.rs b/d3d12/crates/leonida-gpu/src/host/trainer.rs index f0c4d4fa33..81e4c5d14d 100644 --- a/d3d12/crates/leonida-gpu/src/host/trainer.rs +++ b/d3d12/crates/leonida-gpu/src/host/trainer.rs @@ -24,8 +24,7 @@ use std::time::Instant; -use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; -use windows::Win32::Graphics::Direct3D::{D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, ID3DBlob}; +use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; use windows::core::{IUnknown, Interface}; @@ -70,46 +69,18 @@ const AWAY: f32 = 0.25; fn compile( entry: windows::core::PCSTR, target: windows::core::PCSTR, -) -> windows::core::Result { - let mut code: Option = None; - let mut errors: Option = None; - // SAFETY: the source and names live through the call; out pointers are ours. - let made = unsafe { - D3DCompile( - SOURCE.as_ptr().cast(), - SOURCE.len(), +) -> windows::core::Result> { + // SAFETY: callers pass static NUL-terminated HLSL names from `s!`. + let code = unsafe { + crate::compiler::compile_named( + SOURCE, windows::core::s!("leonida trainer menu"), - None, - None, entry, target, 0, - 0, - &mut code, - Some(&mut errors), - ) + )? }; - if let Err(e) = made { - if let Some(errors) = errors { - // SAFETY: the blob's own bytes. - let text = unsafe { - std::slice::from_raw_parts( - errors.GetBufferPointer().cast::(), - errors.GetBufferSize(), - ) - }; - tracing::warn!(errors = %String::from_utf8_lossy(text), "trainer menu shader not compiled"); - } - return Err(e); - } - code.ok_or_else(windows::core::Error::empty) -} - -fn bytes(blob: &ID3DBlob) -> &[u8] { - // SAFETY: the blob's own bytes, alive as long as it is. - unsafe { - std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()) - } + Ok(code.bytes()?.to_vec()) } /// The pipeline for one target format. @@ -122,10 +93,10 @@ struct Pipeline { fn pipeline(device: &ID3D12Device, format: DXGI_FORMAT) -> windows::core::Result { let vs = compile(windows::core::s!("vs"), windows::core::s!("vs_5_1"))?; let ps = compile(windows::core::s!("ps"), windows::core::s!("ps_5_1"))?; - // SAFETY: the blobs' own bytes (the root signature is inside them); - // plain object creation. + // SAFETY: `vs` and `ps` hold the compiled bytecode (and embedded root + // signature) through root-signature and PSO creation. unsafe { - let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes(&vs))?; + let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs)?; let mut blend = D3D12_BLEND_DESC::default(); blend.RenderTarget[0] = D3D12_RENDER_TARGET_BLEND_DESC { BlendEnable: true.into(), @@ -144,12 +115,12 @@ fn pipeline(device: &ID3D12Device, format: DXGI_FORMAT) -> windows::core::Result let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), VS: D3D12_SHADER_BYTECODE { - pShaderBytecode: vs.GetBufferPointer(), - BytecodeLength: vs.GetBufferSize(), + pShaderBytecode: vs.as_ptr().cast(), + BytecodeLength: vs.len(), }, PS: D3D12_SHADER_BYTECODE { - pShaderBytecode: ps.GetBufferPointer(), - BytecodeLength: ps.GetBufferSize(), + pShaderBytecode: ps.as_ptr().cast(), + BytecodeLength: ps.len(), }, BlendState: blend, SampleMask: u32::MAX, @@ -1142,4 +1113,25 @@ mod tests { assert_eq!(sharpness_of(Some("nan")), 0.0); assert_eq!(sharpness_of(Some("3")), 1.0); } + + #[test] + fn trainer_menu_shaders_compile_with_embedded_root_signature() { + let vs = compile(windows::core::s!("vs"), windows::core::s!("vs_5_1")).expect("trainer vs_5_1"); + let ps = compile(windows::core::s!("ps"), windows::core::s!("ps_5_1")).expect("trainer ps_5_1"); + assert!(!vs.is_empty() && !ps.is_empty()); + if let Some(dxc_vs) = crate::compiler::test_dxc_compile(SOURCE, "vs", windows::core::w!("vs_6_0")) { + let dxc_vs = dxc_vs.expect("DXC compiles trainer vs_6_0"); + let dxc_ps = crate::compiler::test_dxc_compile(SOURCE, "ps", windows::core::w!("ps_6_0")) + .unwrap() + .expect("DXC compiles trainer ps_6_0"); + assert!(!dxc_ps.is_empty()); + if let Some(host) = crate::host::host() { + // SAFETY: signed DXIL blob with embedded root signature. + unsafe { + let _root: ID3D12RootSignature = + host.device.CreateRootSignature(0, &dxc_vs).expect("DXC trainer root signature"); + } + } + } + } } diff --git a/d3d12/crates/leonida-gpu/src/indirect.rs b/d3d12/crates/leonida-gpu/src/indirect.rs index 9c5c6873bc..a952f6fd88 100644 --- a/d3d12/crates/leonida-gpu/src/indirect.rs +++ b/d3d12/crates/leonida-gpu/src/indirect.rs @@ -4,9 +4,8 @@ //! billion vertices or a dispatch past the host's limits runs until the //! host resets the display driver. So active records are copied and clamped //! on the GPU into a device-local scratch buffer, just before execution, by a -//! compute shader of ours (HLSL compiled by the system's compiler; a 5.1 -//! shader with its root signature inside), leaving the title's argument and -//! count buffers untouched. +//! compute shader of ours (with its root signature inside), leaving the +//! title's argument and count buffers untouched. //! //! The scratch buffer is left readable as indirect arguments after a clamp //! and stays so until the next clamp into it, which moves it straight back @@ -33,8 +32,6 @@ //! dispatches, the budget) cut legitimate work beyond them; raise them if //! the title needs more. -use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; -use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; use windows::core::s; @@ -432,26 +429,11 @@ fn ask_wide(device: &ID3D12Device, groups: u32) -> windows::core::Result<[u32; 4 } made }; - // SAFETY: the source and names live through the compile; the root signature is inside the - // shader; a queue, list and buffers of our own, which nothing else knows; the list is run - // and waited for before anything of it is read or given up. + // SAFETY: the literal names are NUL-terminated, the root signature is inside the shader, + // and the private queue, list, and buffers live until the work finishes. unsafe { - let mut code: Option = None; - D3DCompile( - WIDE_PROBE.as_ptr().cast(), - WIDE_PROBE.len(), - s!("wide"), - None, - None, - s!("main"), - s!("cs_5_1"), - 0, - 0, - &mut code, - None, - )?; - let code = code.ok_or_else(windows::core::Error::empty)?; - let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let code = crate::compiler::compile_named(WIDE_PROBE, s!("wide"), s!("main"), s!("cs_5_1"), 0)?; + let bytes = code.bytes()?; let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; let pso: ID3D12PipelineState = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), @@ -528,42 +510,10 @@ fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result = None; - let mut errors: Option = None; - // SAFETY: the source and names live through the call; out pointers ours. - let compiled = unsafe { - D3DCompile( - source.as_ptr().cast(), - source.len(), - s!("clamp"), - None, - None, - s!("main"), - s!("cs_5_1"), - 0, - 0, - &mut code, - Some(&mut errors), - ) - }; - if let Err(e) = compiled { - if let Some(errors) = errors { - // SAFETY: the blob's own bytes. - let text = unsafe { - std::slice::from_raw_parts( - errors.GetBufferPointer().cast::(), - errors.GetBufferSize(), - ) - }; - tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text)); - } - return Err(e); - } - let code = code.ok_or_else(windows::core::Error::empty)?; - // SAFETY: the blob's own bytes; the root signature is inside the shader. + // SAFETY: the literal names are NUL-terminated; the root signature is inside the shader. unsafe { - let bytes = - std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let code = crate::compiler::compile_named(source, s!("clamp"), s!("main"), s!("cs_5_1"), 0)?; + let bytes = code.bytes()?; let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), @@ -1151,27 +1101,10 @@ void main() { } fn compile_cs(device: &ID3D12Device, source: &str) -> windows::core::Result { - let mut code: Option = None; - // SAFETY: source and entry names outlive `D3DCompile`. + // SAFETY: the literal names are NUL-terminated; the root signature is inside the shader. unsafe { - D3DCompile( - source.as_ptr().cast(), - source.len(), - s!("worker"), - None, - None, - s!("main"), - s!("cs_5_1"), - 0, - 0, - &mut code, - None, - )?; - let code = code.unwrap(); - let bytes = std::slice::from_raw_parts( - code.GetBufferPointer().cast::(), - code.GetBufferSize(), - ); + let code = crate::compiler::compile_named(source, s!("worker"), s!("main"), s!("cs_5_1"), 0)?; + let bytes = code.bytes()?; let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), diff --git a/d3d12/crates/leonida-gpu/src/indirect/bench.rs b/d3d12/crates/leonida-gpu/src/indirect/bench.rs index 6db6515a51..11e14298b3 100644 --- a/d3d12/crates/leonida-gpu/src/indirect/bench.rs +++ b/d3d12/crates/leonida-gpu/src/indirect/bench.rs @@ -33,28 +33,13 @@ return float4(p, 0.5, 1); float4 ps() : SV_Target { return float4(1, 0.5, 0.25, 1); } "#; -fn compile(entry: &str, target: &str) -> Vec { - let entry = std::ffi::CString::new(entry).unwrap(); - let target = std::ffi::CString::new(target).unwrap(); - let mut code: Option = None; - // SAFETY: the source and names outlive the call. +fn compile(entry: PCSTR, target: PCSTR) -> Vec { + // SAFETY: callers pass static NUL-terminated HLSL names from `s!`. unsafe { - D3DCompile( - SHADERS.as_ptr().cast(), - SHADERS.len(), - s!("bench"), - None, - None, - PCSTR(entry.as_ptr().cast()), - PCSTR(target.as_ptr().cast()), - 0, - 0, - &mut code, - None, - ) - .unwrap(); - let code = code.unwrap(); - std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) + crate::compiler::compile_named(SHADERS, s!("bench"), entry, target, 0) + .unwrap() + .bytes() + .unwrap() .to_vec() } } @@ -226,7 +211,7 @@ fn bench_indirect_draw_barriers() { let frequency = queue.GetTimestampFrequency().unwrap() as f64; // The pipeline: tiny triangles into a small target. - let (vs, ps) = (compile("vs", "vs_5_1"), compile("ps", "ps_5_1")); + let (vs, ps) = (compile(s!("vs"), s!("vs_5_1")), compile(s!("ps"), s!("ps_5_1"))); let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap(); let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), diff --git a/d3d12/crates/leonida-gpu/src/inplace.rs b/d3d12/crates/leonida-gpu/src/inplace.rs index 61a43bb239..b294124b26 100644 --- a/d3d12/crates/leonida-gpu/src/inplace.rs +++ b/d3d12/crates/leonida-gpu/src/inplace.rs @@ -40,8 +40,6 @@ use std::ffi::c_void; use std::sync::atomic::{AtomicU64, Ordering}; use windows::Win32::Foundation::HANDLE; -use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; -use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; @@ -766,14 +764,11 @@ impl Rig { /// A compute shader stores, through a root unordered-access view at /// `gpu`, the sum of the buffer's first two words in its third. fn shade(&mut self, gpu: u64) -> windows::core::Result<()> { - const SOURCE: &str = "#define RS \"UAV(u0)\"\nRWByteAddressBuffer b : register(u0);\n[RootSignature(RS)]\n[numthreads(1, 1, 1)]\nvoid main() { b.Store(8, b.Load(0) + b.Load(4)); }\n"; - let mut code: Option = None; - // SAFETY: the source and names live through the call; then the - // blob's own bytes, which hold the root signature too. + // SAFETY: literal names are NUL-terminated; `code` owns `bytes` + // through root-signature and PSO creation. let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { - D3DCompile(SOURCE.as_ptr().cast(), SOURCE.len(), s!("inplace"), None, None, s!("main"), s!("cs_5_1"), 0, 0, &mut code, None)?; - let code = code.ok_or_else(windows::core::Error::empty)?; - let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let code = crate::compiler::compile_named(SHADE_SOURCE, s!("inplace"), s!("main"), s!("cs_5_1"), 0)?; + let bytes = code.bytes()?; let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; let pso = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), @@ -812,6 +807,8 @@ impl Rig { } } +const SHADE_SOURCE: &str = "#define RS \"UAV(u0)\"\nRWByteAddressBuffer b : register(u0);\n[RootSignature(RS)]\n[numthreads(1, 1, 1)]\nvoid main() { b.Store(8, b.Load(0) + b.Load(4)); }\n"; + fn fill(at: *mut u8, len: usize, seed: u8) { for i in 0..len { // SAFETY: the caller's own committed memory of `len` bytes. @@ -1537,4 +1534,22 @@ pub(crate) mod tests { mem::VirtualFree(base as *mut c_void, 0, mem::MEM_RELEASE); } } + + #[test] + fn inplace_probe_shader_compiles_with_embedded_root_signature() { + // SAFETY: literal NUL-terminated names. + let fxc = unsafe { crate::compiler::compile_named(SHADE_SOURCE, s!("inplace"), s!("main"), s!("cs_5_1"), 0) } + .expect("inplace probe cs_5_1 compiles"); + assert!(!fxc.bytes().unwrap().is_empty()); + if let Some(dxc) = crate::compiler::test_dxc_compile(SHADE_SOURCE, "main", windows::core::w!("cs_6_0")) { + let bytes = dxc.expect("DXC compiles inplace probe cs_6_0"); + if let Some(host) = crate::host::host() { + // SAFETY: signed DXIL blob with embedded root signature. + unsafe { + let _root: ID3D12RootSignature = + host.device.CreateRootSignature(0, &bytes).expect("DXC inplace probe root signature"); + } + } + } + } } diff --git a/d3d12/crates/leonida-gpu/src/lib.rs b/d3d12/crates/leonida-gpu/src/lib.rs index 3aa021b01d..9b64191c30 100644 --- a/d3d12/crates/leonida-gpu/src/lib.rs +++ b/d3d12/crates/leonida-gpu/src/lib.rs @@ -23,11 +23,15 @@ static HEAP: mimalloc::MiMalloc = mimalloc::MiMalloc; #[cfg(windows)] mod ambient; +#[cfg(all(windows, test))] +mod ambient_readback; #[cfg(all(windows, feature = "diagnostics"))] mod capture; #[cfg(all(windows, feature = "diagnostics"))] mod census; #[cfg(windows)] +mod compiler; +#[cfg(windows)] mod compose; pub mod console; #[cfg(all(windows, feature = "diagnostics"))] @@ -131,6 +135,10 @@ mod watch; #[cfg(windows)] mod texback; +#[cfg(all(windows, feature = "diagnostics"))] +#[doc(hidden)] +pub use compiler::compile_runtime_hlsl; + #[cfg(windows)] pub use host::on_failure; diff --git a/d3d12/crates/leonida-gpu/src/replay/play/merge.rs b/d3d12/crates/leonida-gpu/src/replay/play/merge.rs index daddcd02ef..3fd1235f65 100644 --- a/d3d12/crates/leonida-gpu/src/replay/play/merge.rs +++ b/d3d12/crates/leonida-gpu/src/replay/play/merge.rs @@ -9,9 +9,6 @@ //! CPU to a buffer the card writes, words the card has written since the //! start of the frame (which are not what was last put there) stay. -use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; -use windows::Win32::Graphics::Direct3D::ID3DBlob; - use super::*; const SOURCE: &str = r#" @@ -152,28 +149,17 @@ impl Player { if !on || self.merger.is_some() { return Ok(()); } - let mut code: Option = None; - // SAFETY: the source and names live through the call; the blob's own - // bytes. + // SAFETY: literal names are NUL-terminated; `code` owns `bytes` through + // root-signature and PSO creation. let (root, pso) = unsafe { - D3DCompile( - SOURCE.as_ptr().cast(), - SOURCE.len(), - None, - None, - None, + let code = crate::compiler::compile_named( + SOURCE, + windows::core::s!("replay merge"), windows::core::s!("main"), windows::core::s!("cs_5_1"), 0, - 0, - &mut code, - None, )?; - let code = code.context("no merge shader")?; - let bytes = std::slice::from_raw_parts( - code.GetBufferPointer().cast::(), - code.GetBufferSize(), - ); + let bytes = code.bytes()?; let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; let pso = self.device @@ -289,3 +275,46 @@ impl Player { Ok(out) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn merge_shader_compiles_with_embedded_root_signature() { + // SAFETY: literal NUL-terminated names. + let fxc = unsafe { + crate::compiler::compile_named( + SOURCE, + windows::core::s!("replay merge"), + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + 0, + ) + } + .expect("merge cs_5_1 compiles"); + assert!(!fxc.bytes().unwrap().is_empty()); + + if let Some(dxc) = crate::compiler::test_dxc_compile(SOURCE, "main", windows::core::w!("cs_6_0")) { + let bytes = dxc.expect("DXC compiles merge cs_6_0"); + if let Some(host) = crate::host::host() { + // SAFETY: signed DXIL blob with embedded root signature. + unsafe { + let root: ID3D12RootSignature = + host.device.CreateRootSignature(0, &bytes).expect("DXC merge root signature"); + let _pso: ID3D12PipelineState = host + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + }) + .expect("DXC merge compute PSO"); + } + } + } + } +} diff --git a/d3d12/crates/leonida-gpu/tests/replay.rs b/d3d12/crates/leonida-gpu/tests/replay.rs index 675b80a336..2020c5cb6e 100644 --- a/d3d12/crates/leonida-gpu/tests/replay.rs +++ b/d3d12/crates/leonida-gpu/tests/replay.rs @@ -6,17 +6,17 @@ //! picture and buffer must be the same. //! //! `LEONIDA_TEST_D3D_DEBUG=1` runs it under the debug layer. +//! The separate offscreen compiler regression uses `LEONIDA_TEST_D3D_ADAPTER` +//! (a zero-based DXGI hardware adapter index). It does not attach the recorder. #![cfg(all(windows, feature = "diagnostics"))] use std::mem::ManuallyDrop; +use leonida_gpu::compile_runtime_hlsl; use leonida_gpu::replay::play::{self, Buffers, Options, Player}; use leonida_gpu::replay::record::{self, At, Settings}; use windows::Win32::Foundation::{HANDLE, HWND, RECT}; -use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; -use windows::Win32::Graphics::Direct3D::{ - D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, ID3DBlob, -}; +use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; use windows::Win32::Graphics::Dxgi::*; @@ -278,33 +278,9 @@ struct Made { } fn compile(source: &str, entry: PCSTR, target: PCSTR) -> Vec { - let (mut code, mut errors): (Option, Option) = (None, None); - // SAFETY: the source and names live through the call; the blobs' own - // bytes. - unsafe { - let r = D3DCompile( - source.as_ptr().cast(), - source.len(), - None, - None, - None, - entry, - target, - 1 << 20, - 0, - &mut code, - Some(&mut errors), - ); - if r.is_err() { - let e = errors.unwrap(); - let text = - std::slice::from_raw_parts(e.GetBufferPointer().cast::(), e.GetBufferSize()); - panic!("{}", String::from_utf8_lossy(text)); - } - let code = code.unwrap(); - std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) - .to_vec() - } + // SAFETY: the entry and target are static, NUL-terminated s! literals. + // Keep the fixture's native FXC flags, including unbounded descriptor tables. + unsafe { compile_runtime_hlsl(source, entry, target, 1 << 20) }.expect("synthetic replay HLSL") } fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE { @@ -536,7 +512,7 @@ struct Scene { } impl Scene { - fn new(device: &ID3D12Device, window: bool) -> Scene { + fn new(device: &ID3D12Device, window: bool, with_mesh: bool) -> Scene { // SAFETY: plain creation throughout. unsafe { let queue: ID3D12CommandQueue = device @@ -837,7 +813,7 @@ impl Scene { lists, draw, plain, - mesh: mesh(device, blend), + mesh: if with_mesh { mesh(device, blend) } else { None }, vertices, samplers, still: still.to_vec(), @@ -1394,8 +1370,16 @@ impl Scene { l.Dispatch(2, 2, 1); l.ResourceBarrier(&[uav_barrier()]); } - // The card writes memory the CPU sees. - l.ResourceBarrier(&[moved(&self.sum, UAV, FROM)]); + // Different byte ranges of shared still have one buffer state. + // Its compute SRV promotion has not decayed within this submission. + l.ResourceBarrier(&[ + moved(&self.sum, UAV, FROM), + moved( + &self.shared.0, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + TO, + ), + ]); l.CopyBufferRegion(&self.shared.0, 30_000, &self.sum, 0, 1024); l.ResourceBarrier(&[moved(&self.target, TARGET, FROM)]); l.Close().unwrap(); @@ -1593,31 +1577,83 @@ fn check(player: &mut Player, options: &Options, expected: &Outcome, what: &str) report } -#[test] -fn a_frame_is_recorded_and_replayed() { - let debug = std::env::var_os("LEONIDA_TEST_D3D_DEBUG").is_some(); - let mut device: Option = None; - // SAFETY: plain creation. +fn enable_debug_layer() { + // SAFETY: plain creation, only before creating a D3D12 device. unsafe { - if debug { - let mut layer: Option = None; - D3D12GetDebugInterface(&mut layer).unwrap(); - layer.unwrap().EnableDebugLayer(); - } - let _ = D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device); + let mut layer: Option = None; + D3D12GetDebugInterface(&mut layer).unwrap(); + layer.unwrap().EnableDebugLayer(); } - let Some(device) = device else { - eprintln!("no adapter: skipped"); - return; - }; - let own = table_of(&device); - // Without the recorder. - let without = { - let mut scene = Scene::new(&device, false); - (0..5).for_each(|n| scene.frame(n)); - scene.outcome() +} + +fn ordinary_device() -> ID3D12Device { + let index: u32 = std::env::var("LEONIDA_TEST_D3D_ADAPTER") + .expect("set LEONIDA_TEST_D3D_ADAPTER to a zero-based DXGI hardware adapter index") + .parse() + .expect("LEONIDA_TEST_D3D_ADAPTER must be a DXGI adapter index"); + // SAFETY: plain adapter queries and device creation with an explicit adapter. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap(); + let adapter = factory.EnumAdapters1(index).expect("selected DXGI adapter"); + let desc = adapter.GetDesc1().unwrap(); + let ids = (desc.VendorId, desc.DeviceId); + let non_physical = (DXGI_ADAPTER_FLAG_SOFTWARE | DXGI_ADAPTER_FLAG_REMOTE).0 as u32; + assert_eq!( + desc.Flags & non_physical, + 0, + "adapter #{index} is not physical" + ); + let mut device: Option = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device) + .expect("selected physical D3D12 device"); + let device = device.unwrap(); + let luid = device.GetAdapterLuid(); + assert_eq!( + (luid.HighPart, luid.LowPart), + (desc.AdapterLuid.HighPart, desc.AdapterLuid.LowPart), + "D3D12 device is not on the selected adapter" + ); + let name = String::from_utf16_lossy(&desc.Description); + println!( + "offscreen adapter #{index}: {} vendor={:04x} device={:04x} flags={:x} luid={:08x}:{:08x}", + name.trim_end_matches('\0'), + ids.0, + ids.1, + desc.Flags, + luid.HighPart, + luid.LowPart, + ); + device + } +} + +fn require_typed_image(device: &ID3D12Device) { + let mut format = D3D12_FEATURE_DATA_FORMAT_SUPPORT { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ..Default::default() }; - eprintln!("ran without the recorder"); + // SAFETY: each feature's ABI struct is live and correctly sized. + unsafe { + device + .CheckFeatureSupport( + D3D12_FEATURE_FORMAT_SUPPORT, + (&raw mut format).cast(), + size_of_val(&format) as u32, + ) + .expect("R8G8B8A8_UNORM format support"); + } + let typed = D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD | D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE; + assert_eq!( + format.Support2 & typed, + typed, + "the image requires R8G8B8A8_UNORM typed UAV load/store" + ); +} + +fn offscreen_frame(device: &ID3D12Device, with_mesh: bool) -> Outcome { + let mut scene = Scene::new(device, false, with_mesh); + (0..5).for_each(|n| scene.frame(n)); + let without = scene.outcome(); // Something is in the picture. assert!(without.sum.iter().any(|&b| b != 0)); for s in &without.still { @@ -1643,9 +1679,14 @@ fn a_frame_is_recorded_and_replayed() { .map(|c| [c[0], c[1], c[2], c[3]]) .collect(); assert!(colors.len() > 30, "{}", colors.len()); + without +} + +fn capture_frame(device: &ID3D12Device) -> (tempfile::TempDir, std::path::PathBuf, Outcome) { + let own = table_of(device); + let without = offscreen_frame(device, true); - // With it: armed at the first present, the fourth frame is captured (a - // frame whose lists are all recorded comes first). + // The capture starts after a fully recorded frame and ends on scene frame 3. assert!(!record::on()); let dir = tempfile::tempdir().unwrap(); let settings = Settings { @@ -1654,9 +1695,9 @@ fn a_frame_is_recorded_and_replayed() { frames: 1, always: false, }; - let folder = record::start(settings, &device).unwrap(); + let folder = record::start(settings, device).unwrap(); assert!(record::on()); - assert_ne!(table_of(&device), own, "the device is hooked"); + assert_ne!(table_of(device), own, "the device is hooked"); assert!( record::start( Settings { @@ -1665,13 +1706,13 @@ fn a_frame_is_recorded_and_replayed() { frames: 1, always: false }, - &device + device ) .is_err(), "one recorder a process" ); eprintln!("recorder on"); - let mut scene = Scene::new(&device, true); + let mut scene = Scene::new(device, true, true); eprintln!("scene made"); (0..4).for_each(|n| scene.frame(n)); assert_eq!( @@ -1689,8 +1730,8 @@ fn a_frame_is_recorded_and_replayed() { "the recorder changed what the program makes" ); drop(scene); - record::unhook(&device); - assert_eq!(table_of(&device), own, "the device is as it was"); + record::unhook(device); + assert_eq!(table_of(device), own, "the device is as it was"); for name in [ "frame.bin", "contents.bin", @@ -1706,6 +1747,56 @@ fn a_frame_is_recorded_and_replayed() { "{}", std::fs::read_to_string(folder.join("notes.txt")).unwrap() ); + (dir, folder, expected) +} + +// ID3D12DXVKInteropDevice, from vkd3d_device_vkd3d_ext.idl, derives from IUnknown. +fn requires_native_lists(device: &ID3D12Device) -> bool { + let iid = windows::core::GUID::from_u128(0x39da4e09_bd1c_4198_9fae_86bbe3be41fd); + let mut marker: Option = None; + // SAFETY: the requested interface has an IUnknown prefix; the owning option releases it. + unsafe { device.query(&iid, (&raw mut marker).cast()).is_ok() } +} + +#[test] +#[ignore = "requires an explicitly selected physical D3D12 adapter"] +fn the_offscreen_draw_samples_its_unbounded_texture_table() { + if std::env::var_os("LEONIDA_TEST_D3D_DEBUG").is_some() { + enable_debug_layer(); + } + let device = ordinary_device(); + require_typed_image(&device); + let frame = offscreen_frame(&device, false); + // The green channel varies by texel. Red and blue identify which of + // the two synthetic textures the pixel shader actually sampled. + let count = |r, b| frame.picture.chunks_exact(4) + .filter(|p| p[0] == r && p[2] == b && p[3] == 255).count(); + let fixed = count(200, 30); + let other = count(10, 220); + assert!(fixed > 0 && other > 0, "sampled texels: fixed={fixed} other={other}"); + assert_eq!(&frame.shared[30_000..31_024], frame.sum.as_slice()); + eprintln!("offscreen: fixed={fixed} other={other}; {} target bytes, {} sum bytes; native-list backend={}", + frame.picture.len(), frame.sum.len(), requires_native_lists(&device)); +} + +#[test] +fn a_frame_is_recorded_and_replayed() { + let debug = std::env::var_os("LEONIDA_TEST_D3D_DEBUG").is_some(); + if debug { + enable_debug_layer(); + } + let mut device: Option = None; + // SAFETY: plain creation. + let _ = unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device) }; + let Some(device) = device else { + eprintln!("no adapter: skipped"); + return; + }; + // A native command-list identity is required by this backend. The recorder's + // interposed list must not be submitted there; report unsupported rather + // than counting the offscreen control as a successful capture. + assert!(!requires_native_lists(&device), "record/replay unsupported on this backend: requires native command-list identity"); + let (dir, folder, expected) = capture_frame(&device); let plain = Options { loops: 3,