From daefadd7d714e46fbdb865fc60eedc20e3059b1c Mon Sep 17 00:00:00 2001 From: AwkGrep256 Date: Fri, 27 Nov 2026 16:22:20 +0300 Subject: [PATCH] FidelityFX: add opt-in AMD frame generation to the FSR preset Port AwkGrep256's AMD Frame Generation 3 and 4.0.2 integration from Marvisak/VIctory#1917 and #2751. Adapt tightfall's use of the DexNom FidelityFX recording path from Belobug/VIctory-Belobug-AMD#361 and feed the matched title camera to mode 4. Co-authored-by: tightfall --- README.md | 6 + crates/victory-gpu/src/draw.rs | 32 + crates/victory-gpu/src/external.rs | 75 +- crates/victory-gpu/src/framegen.rs | 916 +++++++++++++++++++ crates/victory-gpu/src/framegen/camera.rs | 238 +++++ crates/victory-gpu/src/host.rs | 84 +- crates/victory-gpu/src/lib.rs | 2 + crates/victory-hle/src/modules/fidelityfx.rs | 52 +- 8 files changed, 1386 insertions(+), 19 deletions(-) create mode 100644 crates/victory-gpu/src/framegen.rs create mode 100644 crates/victory-gpu/src/framegen/camera.rs diff --git a/README.md b/README.md index c6fb6fce224..cf95ceb65a8 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,12 @@ Open **DexNom RayTime (FSR Quality 4K)** to use the tested Series X profile. It The baseline was tested with a PC FidelityFX 4.1.2 provider. Put the provider and its dependencies in the installed runtime's `fidelityfx` subfolder or set `VICTORY_FIDELITYFX_DIR` to the folder containing `amd_fidelityfx_upscaler_dx12.dll`. The provider is supplied separately. +### Experimental AMD Frame Generation + +Frame generation is off by default. In a diagnostics build, set `VICTORY_FIDELITYFX_FRAMEGEN=4` before launching the FSR Quality preset to request Frame Generation 4.0.2. Set it to `1` to try the analytical 3.x provider. Both modes use `amd_fidelityfx_framegeneration_dx12.dll` from the same SDK folder as the upscaler. + +Frame generation requires an RGBA8 swap chain. Mode 4 also requires a supported GPU and a camera sample matching the current upscale. If the proxy or the requested provider is unavailable, the runtime logs the reason and continues with ordinary presentation. + For a manual launch, use the same flags as the Quality shortcut. ```powershell diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 2900faa5d2f..59809d0628e 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3150,6 +3150,34 @@ impl State { out } + #[cfg(feature = "diagnostics")] + fn record_framegen_camera(&self, list: &HostList) { + if !crate::framegen::ml_enabled() { + return; + } + let Some(pipeline) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return; + }; + // The 1.0.2.1 velocity pass is identified by its shader pair. + if !pipeline.stages.iter().any(|stage| stage.shader.hash == "4adcfeaa24ae6450") + || !pipeline.stages.iter().any(|stage| stage.shader.hash == "9ab96b7a002d6ac8") + { + return; + } + let Some(Root::Table(table)) = self.roots_ref(false).get(1) else { + return; + }; + let Some(handle) = table.checked_add(8 * 4) else { + return; + }; + let Some(View::Constant(address, size)) = crate::descriptor::view(handle) else { + return; + }; + if let Some(viewport) = self.viewports.first() { + crate::framegen::camera::record(list, address, size, [viewport.Width, viewport.Height]); + } + } + pub(crate) fn draw( &mut self, list: &HostList, @@ -3176,6 +3204,10 @@ impl State { }; #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false)); + #[cfg(feature = "diagnostics")] + if count == 3 && instances == 1 { + self.record_framegen_camera(list); + } let frontend = if count == 3 && instances == 1 { self.native_frontend_viewport() } else { diff --git a/crates/victory-gpu/src/external.rs b/crates/victory-gpu/src/external.rs index 6c1236f15df..14ba6f276b8 100644 --- a/crates/victory-gpu/src/external.rs +++ b/crates/victory-gpu/src/external.rs @@ -45,6 +45,73 @@ pub fn prepare_input(list: *const Object, resource: *const Object) -> Option<()> Some(()) } +/// The host list while a title command list is being recorded. +pub struct Recording<'a>(&'a crate::host::HostList); + +impl Recording<'_> { + /// The open D3D12 list for the provider to record into. + pub fn list(&self) -> &ID3D12GraphicsCommandList { + &self.0.list + } + + /// At a host upscale recorded here: its depth and motion textures + /// (title resources) and constants feed frame generation for the next + /// present, once this list has run. Nothing when it is off. + #[cfg(feature = "diagnostics")] + pub fn frame_generation_inputs( + &self, + depth: *const Object, + motion: *const Object, + frame: FrameInputs, + ) { + if !crate::framegen::enabled() { + return; + } + let (Some(depth), Some(motion)) = ( + crate::resource::host_copy(depth), + crate::resource::host_copy(motion), + ) else { + return; + }; + crate::framegen::record( + self.0, + crate::framegen::Inputs { + depth, + motion, + frame, + pose: None, + }, + ); + } +} + +/// What frame generation needs of an upscaled frame besides its depth and +/// motion vectors: the upscale's constants (as its description has them) +/// and the motion and depth bits of its creation flags. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[cfg(feature = "diagnostics")] +pub struct FrameInputs { + pub render: [u32; 2], + pub jitter: [f32; 2], + pub motion_scale: [f32; 2], + pub frame_time_ms: f32, + pub reset: bool, + /// Near, far, vertical field of view, metres per view-space unit. + pub camera: [f32; 4], + pub flags: u32, + /// The FidelityFX descriptions of the depth and motion textures. + pub depth_desc: [u32; 8], + pub motion_desc: [u32; 8], +} + +/// Turns on AMD frame generation for upscaled frames (diagnostics) with +/// `amd_fidelityfx_framegeneration_dx12.dll` from `dir`: the presenter's +/// swap chain becomes its proxy. The DLL's path, or why not. +#[cfg(feature = "diagnostics")] +pub fn use_frame_generation(dir: &std::path::Path, ml: bool) -> Result { + crate::framegen::load(dir, ml) +} + /// The producer recorded its output on the host's command list. pub fn output_written(resource: *const Object) { crate::texture::host_written(resource); @@ -63,9 +130,15 @@ pub fn record( list: *const Object, f: impl FnOnce(&ID3D12GraphicsCommandList) -> R, ) -> Option { + record_upscale(list, |recording| f(recording.list())) +} + +/// As [`record`], with access to the frame generation inputs for a +/// successfully recorded upscale. +pub fn record_upscale(list: *const Object, f: impl FnOnce(Recording<'_>) -> R) -> Option { let mut out = None; crate::list::with_state(list, |host, state| { - out = Some(f(&host.list)); + out = Some(f(Recording(host))); state.host_state_lost(); }); out diff --git a/crates/victory-gpu/src/framegen.rs b/crates/victory-gpu/src/framegen.rs new file mode 100644 index 00000000000..537d6f3b87a --- /dev/null +++ b/crates/victory-gpu/src/framegen.rs @@ -0,0 +1,916 @@ +//! AMD FidelityFX frame generation for frames the title upscales +//! (diagnostics, `VICTORY_FIDELITYFX_FRAMEGEN=1` beside +//! `VICTORY_FIDELITYFX_DIR`). The title asks for no frame generation; the +//! inputs are its upscale's: at each host upscale (`external::record` +//! through the HLE FidelityFX module) the depth and motion vectors and the +//! frame's constants are kept, and those of the last submitted list feed +//! the next present. The presenter's swap chain is then AMD's frame +//! generation proxy (`amd_fidelityfx_framegeneration_dx12.dll`), which +//! inserts the generated frames. +//! +//! Mode 1 uses the analytical provider. Experimental mode 4 supplies the +//! title's world-space camera from its velocity pass when it matches the +//! current upscale. +//! +//! shortcut: an RGBA8 swap chain only; no HUD-less colour, so the UI is +//! interpolated with the scene. + +use std::ffi::{CStr, c_void}; +use std::path::Path; +use std::ptr::{null, null_mut}; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +use windows::Win32::Foundation::HWND; +use windows::Win32::Graphics::Direct3D12::{ + D3D12_RESOURCE_BARRIER, ID3D12CommandQueue, ID3D12Device, +}; +use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM; +use windows::Win32::Graphics::Dxgi::{ + DXGI_SWAP_CHAIN_DESC1, IDXGIFactory2, IDXGISwapChain3, IDXGISwapChain4, +}; +use windows::core::Interface; + +use crate::host::HostList; +use crate::resource::HostTexture; + +pub(crate) mod camera; + +const DLL: &str = "amd_fidelityfx_framegeneration_dx12.dll"; +const OK: u32 = 0; + +// FidelityFX SDK v2.4.0: ffx_api.h, ffx_framegeneration.h, +// ffx_api_dx12.h, and dx12/ffx_api_framegeneration_dx12.h. +const BACKEND_DX12: u64 = 2; +const GET_VERSIONS: u64 = 4; +const OVERRIDE_VERSION: u64 = 5; +const PROVIDER_VERSION: u64 = 6; +const CREATE: u64 = 0x20001; +const CONFIGURE: u64 = 0x20002; +const PREPARE: u64 = 0x2000c; +const VERSION: u64 = 0x2000e; +const SWAPCHAIN_CREATE: u64 = 0x30006; +const SWAPCHAIN_WAIT: u64 = 0x30007; +const SWAPCHAIN_VERSION: u64 = 0x3000b; +const RGBA8_UNORM: u32 = 10; +/// Display-resolution motion vectors, motion-vector jitter cancellation, +/// inverted depth, and infinite depth. The upscale HDR flag is separate. +const MOTION_DEPTH_FLAGS: u32 = 0b11110; +/// The FidelityFX resource state of compute reads, and the host's. +const FFX_COMPUTE_READ: u32 = 1 << 2; +const HOST_NON_PIXEL_SHADER_RESOURCE: u32 = 0x40; + +#[repr(C)] +struct Header { + kind: u64, + next: *mut Header, +} + +fn header(kind: u64) -> Header { + Header { + kind, + next: null_mut(), + } +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct Resource { + resource: *mut c_void, + description: [u32; 8], + state: u32, +} + +#[repr(C)] +struct BackendDx12 { + header: Header, + device: *mut c_void, +} + +#[repr(C)] +struct Version { + header: Header, + version: u32, +} + +#[repr(C)] +struct Versions { + header: Header, + effect: u64, + device: *mut c_void, + count: *mut u64, + ids: *mut u64, + names: *mut *const std::ffi::c_char, +} + +#[repr(C)] +struct ProviderOverride { + header: Header, + id: u64, +} + +#[repr(C)] +struct SwapchainDesc { + header: Header, + output: *mut *mut c_void, + hwnd: HWND, + desc: *const DXGI_SWAP_CHAIN_DESC1, + fullscreen_desc: *const c_void, + factory: *mut c_void, + queue: *mut c_void, +} + +#[repr(C)] +struct Create { + header: Header, + flags: u32, + display: [u32; 2], + max_render: [u32; 2], + format: u32, +} + +type Callback = unsafe extern "C" fn(*mut Generate, *mut c_void) -> u32; + +#[repr(C)] +struct Configure { + header: Header, + swapchain: *mut c_void, + present_callback: *const c_void, + present_user: *mut c_void, + generate_callback: Option, + generate_user: *mut c_void, + enabled: bool, + allow_async: bool, + hudless: Resource, + flags: u32, + only_generated: bool, + rect: [i32; 4], + id: u64, +} + +#[repr(C)] +struct Prepare { + header: Header, + id: u64, + flags: u32, + list: *mut c_void, + render: [u32; 2], + jitter: [f32; 2], + scale: [f32; 2], + time_ms: f32, + reset: bool, + camera: [f32; 4], + depth: Resource, + motion: Resource, + camera_position: [f32; 3], + camera_up: [f32; 3], + camera_right: [f32; 3], + camera_forward: [f32; 3], +} + +#[repr(C)] +struct Generate { + header: Header, + list: *mut c_void, + color: Resource, + output: [Resource; 4], + count: u32, +} + +#[repr(C)] +struct ProviderVersion { + header: Header, + id: u64, + name: *const std::ffi::c_char, +} + +const _: () = { + use std::mem::offset_of; + + // These x64 offsets catch reordered fields even when the size is unchanged. + assert!(size_of::() == 48); + assert!(offset_of!(Resource, description) == 8); + assert!(offset_of!(Resource, state) == 40); + assert!(size_of::() == 56); + assert!(offset_of!(Versions, count) == 32); + assert!(offset_of!(Versions, ids) == 40); + assert!(offset_of!(Versions, names) == 48); + assert!(size_of::() == 24); + assert!(offset_of!(ProviderOverride, id) == 16); + assert!(size_of::() == 64); + assert!(offset_of!(SwapchainDesc, output) == 16); + assert!(offset_of!(SwapchainDesc, desc) == 32); + assert!(offset_of!(SwapchainDesc, queue) == 56); + assert!(size_of::() == 40); + assert!(offset_of!(Create, display) == 20); + assert!(offset_of!(Create, max_render) == 28); + assert!(size_of::() == 144); + assert!(offset_of!(Configure, generate_callback) == 40); + assert!(offset_of!(Configure, generate_user) == 48); + assert!(offset_of!(Configure, enabled) == 56); + assert!(offset_of!(Configure, id) == 136); + assert!(size_of::() == 232); + assert!(offset_of!(Prepare, render) == 40); + assert!(offset_of!(Prepare, jitter) == 48); + assert!(offset_of!(Prepare, scale) == 56); + assert!(offset_of!(Prepare, depth) == 88); + assert!(offset_of!(Prepare, motion) == 136); + assert!(offset_of!(Generate, color) == 24); + assert!(offset_of!(Generate, output) == 72); + assert!(offset_of!(Generate, count) == 264); +}; + +type CreateFn = unsafe extern "C" fn(*mut *mut c_void, *mut Header, *const c_void) -> u32; +type DestroyFn = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> u32; +type CallFn = unsafe extern "C" fn(*mut *mut c_void, *mut Header) -> u32; + +struct Api { + create: CreateFn, + destroy: DestroyFn, + configure: CallFn, + query: CallFn, + dispatch: CallFn, + legacy_providers: Option, +} + +#[derive(Clone, Copy)] +struct Providers { + generator: u64, + swapchain: u64, +} + +static API: OnceLock = OnceLock::new(); + +/// A provider for an effect. A null device enumerates the SDK's built-in +/// providers. The actual DX12 device also exposes its driver providers. +fn find_provider(query: CallFn, effect: u64, device: *mut c_void, version: &[u8]) -> Option { + let mut count = 0; + let mut versions = Versions { + header: header(GET_VERSIONS), + effect, + device, + count: &mut count, + ids: null_mut(), + names: null_mut(), + }; + // SAFETY: a null context requests version enumeration. The descriptor + // and its count remain live for both calls. + if unsafe { query(null_mut(), &mut versions.header) } != OK || !(1..=64).contains(&count) { + return None; + } + let mut ids = vec![0; count as usize]; + let mut names = vec![null(); count as usize]; + versions.ids = ids.as_mut_ptr(); + versions.names = names.as_mut_ptr(); + // SAFETY: both arrays have the capacity in the count slot. + if unsafe { query(null_mut(), &mut versions.header) } != OK { + return None; + } + ids.into_iter() + .zip(names) + .take(count as usize) + .find_map(|(id, name)| { + if id == 0 || name.is_null() { + return None; + } + // SAFETY: the API returns static NUL-terminated version names. + let name = unsafe { CStr::from_ptr(name) }.to_bytes(); + let matches = if version.ends_with(b".") { + name.starts_with(version) + } else { + name == version + }; + matches.then_some(id) + }) +} + +/// Loads AMD's frame generation from `dir` (the FidelityFX SDK's +/// `signedbin`, as for the upscaler); its presence turns frame generation +/// on. The DLL's version, or why it did not load. +pub(crate) fn load(dir: &Path, ml: bool) -> Result { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::System::LibraryLoader::{ + GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, + LoadLibraryExW, + }; + let path = std::path::absolute(dir.join(DLL)).map_err(|e| e.to_string())?; + if !path.is_file() { + return Err(format!("no {DLL} there")); + } + let wide: Vec = path.as_os_str().encode_wide().chain([0]).collect(); + // SAFETY: a NUL-terminated path; its own folder and System32 only. + let module = unsafe { + LoadLibraryExW( + wide.as_ptr(), + null_mut(), + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32, + ) + }; + if module.is_null() { + return Err(format!( + "{DLL} did not load ({})", + std::io::Error::last_os_error() + )); + } + let find = |name: &CStr| { + // SAFETY: a loaded module and a NUL-terminated name. + unsafe { GetProcAddress(module, name.as_ptr().cast()) } + .map(|f| f as *const c_void) + .ok_or_else(|| format!("{DLL} has no {}", name.to_string_lossy())) + }; + // SAFETY: the API's query export, with its signature. + let query = unsafe { std::mem::transmute::<*const c_void, CallFn>(find(c"ffxQuery")?) }; + let legacy_providers = if ml { + None + } else { + Some(Providers { + generator: find_provider(query, CREATE, null_mut(), b"3.") + .ok_or("no built-in Frame Generation 3 provider")?, + swapchain: find_provider(query, SWAPCHAIN_CREATE, null_mut(), b"3.") + .ok_or("no built-in Frame Generation 3 swap chain provider")?, + }) + }; + // SAFETY: the API's exports, with their signatures. + let api = unsafe { + Api { + create: std::mem::transmute::<*const c_void, CreateFn>(find(c"ffxCreateContext")?), + destroy: std::mem::transmute::<*const c_void, DestroyFn>(find(c"ffxDestroyContext")?), + configure: std::mem::transmute::<*const c_void, CallFn>(find(c"ffxConfigure")?), + query, + dispatch: std::mem::transmute::<*const c_void, CallFn>(find(c"ffxDispatch")?), + legacy_providers, + } + }; + let _ = API.set(api); + Ok(path.display().to_string()) +} + +fn api() -> Option<&'static Api> { + API.get() +} + +/// Whether frame generation is on (its DLL loaded). +pub(crate) fn enabled() -> bool { + API.get().is_some() +} + +pub(crate) fn ml_enabled() -> bool { + api().is_some_and(|api| api.legacy_providers.is_none()) +} + +/// What frame generation needs of an upscaled frame (see +/// `external::FrameInputs`), with the host copies of its depth and motion +/// vectors, which it holds. +#[derive(Clone)] +pub(crate) struct Inputs { + pub(crate) depth: Arc, + pub(crate) motion: Arc, + pub(crate) frame: crate::external::FrameInputs, + pub(crate) pose: Option, +} + +// SAFETY: D3D12 resources are free-threaded; the rest is plain data. +unsafe impl Send for Inputs {} +// SAFETY: as above. +unsafe impl Sync for Inputs {} + +static SUBMITTED: Mutex> = Mutex::new(None); + +/// At an upscale recorded into `list`: its inputs feed the next present +/// once the list is submitted (the present runs after it on the queue). +pub(crate) fn record(list: &HostList, inputs: Inputs) { + list.defer_host(move || { + let mut submitted = inputs.clone(); + if ml_enabled() { + submitted.pose = camera::take_matching(submitted.frame.render, submitted.frame.jitter); + } + *SUBMITTED.lock().unwrap_or_else(|e| e.into_inner()) = Some(submitted); + }); +} + +fn take_inputs() -> Option { + SUBMITTED.lock().unwrap_or_else(|e| e.into_inner()).take() +} + +struct Context { + api: &'static Api, + handle: *mut c_void, +} + +// SAFETY: the presenter's mutex serializes every use, including the +// callbacks the proxy makes during Present. +unsafe impl Send for Context {} + +impl Context { + fn create(api: &'static Api, desc: &mut Header) -> Result { + let mut ctx = Self { + api, + handle: null_mut(), + }; + // SAFETY: the typed chain and the handle slot live through the call. + let code = unsafe { (api.create)(&mut ctx.handle, desc, null()) }; + if code == OK && !ctx.handle.is_null() { + Ok(ctx) + } else { + Err(code) + } + } + + fn configure(&self, desc: &mut Configure) -> u32 { + // SAFETY: our context and the matching description. + unsafe { (self.api.configure)(&mut { self.handle }, &mut desc.header) } + } + + fn dispatch(&self, desc: &mut Header) -> u32 { + // SAFETY: our context and the matching description. + unsafe { (self.api.dispatch)(&mut { self.handle }, desc) } + } + + fn provider(&self) -> String { + let mut q = ProviderVersion { + header: header(PROVIDER_VERSION), + id: 0, + name: null(), + }; + // SAFETY: a provider query on our context. + let code = unsafe { (self.api.query)(&mut { self.handle }, &mut q.header) }; + if code != OK || q.name.is_null() { + return String::new(); + } + // SAFETY: a NUL-terminated name the DLL keeps. + unsafe { CStr::from_ptr(q.name) } + .to_string_lossy() + .into_owned() + } +} + +impl Drop for Context { + fn drop(&mut self) { + // SAFETY: owned, and no present is in flight when it is released. + unsafe { (self.api.destroy)(&mut self.handle, null()) }; + } +} + +struct Generator { + context: Context, + generated: AtomicU64, + error: AtomicU32, +} + +/// The proxy's call during Present: generate the frames. +unsafe extern "C" fn generate(desc: *mut Generate, user: *mut c_void) -> u32 { + // SAFETY: the configured callback gets our boxed generator and a live + // dispatch description the SDK owns. + let g = unsafe { &*user.cast::() }; + // SAFETY: as above. + let code = unsafe { (g.context.api.dispatch)(&mut { g.context.handle }, desc.cast()) }; + if code == OK { + // SAFETY: the description is live for this call; the SDK may update + // the generated-frame count in it. + let count = unsafe { std::ptr::addr_of!((*desc).count).read() }; + g.generated.fetch_add(u64::from(count), Ordering::Relaxed); + } else { + g.error.store(code, Ordering::Relaxed); + } + code +} + +/// Frame generation for one presenter: the proxy swap chain's context and +/// the generator for the current sizes. +pub(crate) struct Presentation { + api: &'static Api, + generator_provider: u64, + proxy: Context, + generator: Option>, + key: Option<([u32; 2], [u32; 2], u32)>, + armed: bool, + next_id: u64, + continuous: u64, + last_frame: u64, + base_presents: u32, + logged: bool, + missing_camera_warning: camera::MissingCameraWarning, +} + +impl Presentation { + /// The proxy swap chain for `hwnd` and its frame generation, in place + /// of the plain one; `None` when off, for another format, or if the + /// proxy is refused (the presenter makes a plain one). + pub(crate) fn create( + factory: &IDXGIFactory2, + device: &ID3D12Device, + queue: &ID3D12CommandQueue, + hwnd: HWND, + desc: &DXGI_SWAP_CHAIN_DESC1, + ) -> Option<(IDXGISwapChain3, Self)> { + let api = api()?; + if desc.Format != DXGI_FORMAT_R8G8B8A8_UNORM { + tracing::warn!( + format = desc.Format.0, + "FidelityFX frame generation: only an RGBA8 swap chain; presenting without it" + ); + return None; + } + let providers = if let Some(legacy) = api.legacy_providers { + legacy + } else { + let (Some(generator), Some(swapchain)) = ( + find_provider(api.query, CREATE, device.as_raw(), b"4.0.2"), + find_provider(api.query, SWAPCHAIN_CREATE, device.as_raw(), b"4.0.0"), + ) else { + tracing::warn!( + "FidelityFX frame generation: the GPU did not offer the 4.0.2 generator and 4.0.0 proxy; off" + ); + return None; + }; + Providers { + generator, + swapchain, + } + }; + let mut version = Version { + header: header(SWAPCHAIN_VERSION), + version: 4 << 22, + }; + let mut provider = ProviderOverride { + header: Header { + kind: OVERRIDE_VERSION, + next: &mut version.header, + }, + id: providers.swapchain, + }; + let mut output = null_mut(); + let mut args = SwapchainDesc { + header: Header { + kind: SWAPCHAIN_CREATE, + next: &mut provider.header, + }, + output: &mut output, + hwnd, + desc, + fullscreen_desc: null(), + factory: factory.as_raw(), + queue: queue.as_raw(), + }; + let proxy = Context::create(api, &mut args.header) + .inspect_err(|code| { + tracing::warn!( + code, + "FidelityFX frame generation: no proxy swap chain; presenting without it" + ) + }) + .ok()?; + if output.is_null() { + return None; + } + // SAFETY: the SDK returned an owned IDXGISwapChain4 reference. + let swap_chain = unsafe { IDXGISwapChain4::from_raw(output) }.cast().ok()?; + let proxy_provider = proxy.provider(); + if api.legacy_providers.is_none() && proxy_provider != "4.0.0" { + tracing::warn!( + provider = proxy_provider, + "FidelityFX frame generation: unexpected ML proxy provider; off" + ); + return None; + } + tracing::info!( + provider = proxy_provider, + "FidelityFX frame generation: proxy swap chain" + ); + Some(( + swap_chain, + Self { + api, + generator_provider: providers.generator, + proxy, + generator: None, + key: None, + armed: false, + next_id: 0, + continuous: 0, + last_frame: 0, + base_presents: 0, + logged: false, + missing_camera_warning: camera::MissingCameraWarning::default(), + }, + )) + } + + /// Frame generation off for the coming presents (another size, or no + /// upscaled frame): waits for the proxy's queued frames. + pub(crate) fn disable(&mut self, chain: &IDXGISwapChain3) { + if !self.armed { + return; + } + if let Some(g) = &self.generator { + let code = g.context.configure(&mut self.config(chain, false, [0; 2])); + if code != OK { + tracing::warn!(code, "FidelityFX frame generation: not switched off"); + } + } + let _ = self.proxy.dispatch(&mut header(SWAPCHAIN_WAIT)); + self.armed = false; + } + + fn config(&self, chain: &IDXGISwapChain3, armed: bool, display: [u32; 2]) -> Configure { + let generator = self.generator.as_deref().filter(|_| armed); + Configure { + header: header(CONFIGURE), + swapchain: chain.as_raw(), + present_callback: null(), + present_user: null_mut(), + generate_callback: generator.map(|_| generate as Callback), + generate_user: generator + .map_or(null_mut(), |g| std::ptr::from_ref(g).cast_mut().cast()), + enabled: armed, + allow_async: false, + hudless: Resource { + resource: null_mut(), + description: [0; 8], + state: 0, + }, + flags: 0, + only_generated: false, + rect: [0, 0, display[0] as i32, display[1] as i32], + id: self.next_id, + } + } + + /// Before presenting frame `frame` at `display` size: the generator + /// configured and given the last submitted upscale's depth and motion + /// (recorded into `list`, which runs before the present). True if + /// frames will be generated for this present. + pub(crate) fn prepare( + &mut self, + chain: &IDXGISwapChain3, + device: &ID3D12Device, + list: &HostList, + display: [u32; 2], + frame: u64, + ) -> bool { + if ml_enabled() { + camera::clear(); + } + let Some(input) = take_inputs().filter(|i| { + i.frame + .render + .into_iter() + .zip(display) + .all(|(r, d)| r > 0 && r <= d) + }) else { + self.disable(chain); + return false; + }; + let pose = if ml_enabled() { + if self.missing_camera_warning.observe(input.pose.is_some()) { + tracing::warn!( + upscales = camera::WARNING_AFTER_UPSCALES, + "FidelityFX Frame Generation 4.0.2: no matching velocity-pass camera; presenting ordinary frames. The shader pair was verified on title 1.0.2.1. Set VICTORY_LOG=info,victory_gpu::framegen=debug for matching details" + ); + } + let Some(pose) = input.pose else { + tracing::debug!( + frame, + "FidelityFX frame generation: no camera matching this upscale" + ); + self.disable(chain); + return false; + }; + pose + } else { + camera::Pose::LEGACY + }; + let flags = input.frame.flags & MOTION_DEPTH_FLAGS; + let key = (display, input.frame.render, flags); + if self.key != Some(key) { + self.renew(chain, device, key); + } + let Some(g) = &self.generator else { + return false; + }; + let code = g.context.configure(&mut self.config(chain, true, display)); + if code != OK { + tracing::warn!(code, "FidelityFX frame generation: configure failed"); + self.disable(chain); + return false; + } + let reset = input.frame.reset || !self.armed || self.last_frame + 1 != frame; + let mut barriers = Vec::new(); + let depth = read(list, &input.depth, input.frame.depth_desc, &mut barriers); + let motion = read(list, &input.motion, input.frame.motion_desc, &mut barriers); + if !barriers.is_empty() { + // SAFETY: an open list and textures the inputs hold. + unsafe { list.list.ResourceBarrier(&barriers) }; + } + list.keep(&input.depth.texture); + list.keep(&input.motion.texture); + let mut prepare = Prepare { + header: header(PREPARE), + id: self.next_id, + flags: 0, + list: list.list.as_raw(), + render: input.frame.render, + jitter: input.frame.jitter, + scale: input.frame.motion_scale, + time_ms: input.frame.frame_time_ms, + reset, + camera: input.frame.camera, + depth, + motion, + camera_position: pose.position, + camera_up: pose.up, + camera_right: pose.right, + camera_forward: pose.forward, + }; + self.armed = true; + let code = g.context.dispatch(&mut prepare.header); + if code != OK { + tracing::warn!(code, "FidelityFX frame generation: prepare failed"); + self.disable(chain); + return false; + } + self.last_frame = frame; + self.next_id += 1; + self.continuous += u64::from(!reset); + if self.next_id == 1 { + let screen = display; + tracing::info!(frame, render = ?input.frame.render, ?screen, camera_pose = ml_enabled(), "FidelityFX frame generation: first upscaled frame's depth and motion given to it"); + } + true + } + + /// A new generator for (display, render, flags). + fn renew( + &mut self, + chain: &IDXGISwapChain3, + device: &ID3D12Device, + key: ([u32; 2], [u32; 2], u32), + ) { + self.disable(chain); + self.generator = None; + self.key = Some(key); + self.next_id = 0; + self.continuous = 0; + let _ = self.proxy.dispatch(&mut header(SWAPCHAIN_WAIT)); + // SAFETY: the proxy swap chain is live; the presenter serializes us. + self.base_presents = unsafe { chain.GetLastPresentCount() }.unwrap_or(0); + let (screen, render, flags) = key; + let mut backend = BackendDx12 { + header: header(BACKEND_DX12), + device: device.as_raw(), + }; + let mut version = Version { + header: Header { + kind: VERSION, + next: &mut backend.header, + }, + version: (4 << 22) | 2, + }; + let mut provider = ProviderOverride { + header: Header { + kind: OVERRIDE_VERSION, + next: &mut version.header, + }, + id: self.generator_provider, + }; + let mut args = Create { + header: Header { + kind: CREATE, + next: &mut provider.header, + }, + flags, + display: screen, + max_render: render, + format: RGBA8_UNORM, + }; + match Context::create(self.api, &mut args.header) { + Ok(context) => { + let provider = context.provider(); + let expected = if ml_enabled() { + provider == "4.0.2" + } else { + provider.starts_with("3.") + }; + if expected { + tracing::info!( + provider, + ?screen, + ?render, + "FidelityFX frame generation: generator for the upscaled frames" + ); + self.generator = Some(Box::new(Generator { + context, + generated: AtomicU64::new(0), + error: AtomicU32::new(0), + })); + } else { + tracing::warn!( + provider, + "FidelityFX frame generation: unexpected generator provider; off" + ); + } + } + Err(code) => tracing::warn!( + code, + ?screen, + ?render, + "FidelityFX frame generation: no generator" + ), + } + } + + /// After presenting frame `frame`: a failed generation switches it off; + /// the first steady stretch is logged with the presents it made. + pub(crate) fn presented(&mut self, chain: &IDXGISwapChain3, frame: u64) { + let Some(g) = &self.generator else { return }; + let error = g.error.load(Ordering::Relaxed); + if error != OK { + tracing::warn!(error, "FidelityFX frame generation: generating failed; off"); + self.disable(chain); + } else if !self.logged && self.continuous >= 2 && g.generated.load(Ordering::Relaxed) >= 3 { + let waited = self.proxy.dispatch(&mut header(SWAPCHAIN_WAIT)); + // SAFETY: a live proxy swap chain with completed presents. + let presents = unsafe { chain.GetLastPresentCount() } + .unwrap_or(0) + .saturating_sub(self.base_presents); + tracing::info!( + frame, + rendered = self.next_id, + continuous = self.continuous, + generated = g.generated.load(Ordering::Relaxed), + presents, + waited, + "FidelityFX frame generation: generated frames" + ); + self.logged = true; + } + } +} + +/// `copy` as frame generation reads it (compute read), moved there in +/// `list` (`barriers` gets the transition, if any). +fn read( + list: &HostList, + copy: &Arc, + description: [u32; 8], + barriers: &mut Vec, +) -> Resource { + barriers.extend(list.move_texture(copy, HOST_NON_PIXEL_SHADER_RESOURCE)); + Resource { + resource: copy.texture.as_raw(), + description, + state: FFX_COMPUTE_READ, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn without_the_dll_frame_generation_stays_off() { + let dir = std::env::temp_dir().join("victory-no-framegen"); + let _ = std::fs::create_dir_all(&dir); + assert!(load(&dir, false).unwrap_err().contains(DLL)); + } + + #[test] + fn selects_the_builtin_three_provider_for_each_effect() { + unsafe extern "C" fn query(ctx: *mut *mut c_void, desc: *mut Header) -> u32 { + // SAFETY: find_provider passes its live Versions descriptor. + let versions = unsafe { &mut *desc.cast::() }; + if !ctx.is_null() || versions.header.kind != GET_VERSIONS || !versions.device.is_null() + { + return 1; + } + let provider_id = match versions.effect { + CREATE => 31, + SWAPCHAIN_CREATE => 32, + _ => return 1, + }; + // SAFETY: count is live. On the second call both arrays have two entries. + unsafe { + if versions.ids.is_null() && versions.names.is_null() { + *versions.count = 2; + } else if *versions.count == 2 + && !versions.ids.is_null() + && !versions.names.is_null() + { + *versions.ids = 40; + *versions.ids.add(1) = provider_id; + *versions.names = c"4.0.2".as_ptr(); + *versions.names.add(1) = c"3.1.6".as_ptr(); + } else { + return 1; + } + } + OK + } + + assert_eq!(find_provider(query, CREATE, null_mut(), b"3."), Some(31)); + assert_eq!( + find_provider(query, SWAPCHAIN_CREATE, null_mut(), b"3."), + Some(32) + ); + } +} diff --git a/crates/victory-gpu/src/framegen/camera.rs b/crates/victory-gpu/src/framegen/camera.rs new file mode 100644 index 00000000000..6f2b62da3f4 --- /dev/null +++ b/crates/victory-gpu/src/framegen/camera.rs @@ -0,0 +1,238 @@ +//! Camera inputs from the title's fullscreen velocity pass. Take the +//! camera sample at draw recording, then associate it with an upscale in +//! command-list submission order. + +use std::sync::Mutex; + +use crate::host::HostList; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Pose { + pub(crate) position: [f32; 3], + pub(crate) right: [f32; 3], + pub(crate) up: [f32; 3], + pub(crate) forward: [f32; 3], +} + +impl Pose { + /// The analytical provider does not use the pose. + pub(crate) const LEGACY: Self = Self { + position: [0.0; 3], + right: [1.0, 0.0, 0.0], + up: [0.0, 1.0, 0.0], + forward: [0.0, 0.0, 1.0], + }; +} + +#[derive(Clone, Copy, PartialEq)] +struct Sample { + pose: Pose, + viewport: [f32; 2], + projection_offset: [f32; 2], +} + +const BUFFER_SIZE: u32 = 480; +const MAX_CANDIDATES: usize = 16; +static CANDIDATES: Mutex> = Mutex::new(Vec::new()); + +pub(crate) const WARNING_AFTER_UPSCALES: u8 = 60; + +#[derive(Default)] +pub(crate) struct MissingCameraWarning { + misses: u8, + warned: bool, +} + +impl MissingCameraWarning { + /// Call only when an upscale supplies otherwise usable frame inputs. + pub(crate) fn observe(&mut self, matched: bool) -> bool { + if self.warned { + return false; + } + if matched { + self.misses = 0; + return false; + } + self.misses += 1; + self.warned = self.misses == WARNING_AFTER_UPSCALES; + self.warned + } +} + +fn dot(a: [f32; 3], b: [f32; 3]) -> f32 { + a.into_iter().zip(b).map(|(x, y)| x * y).sum() +} + +fn vec3(words: &[f32; 52], at: usize) -> [f32; 3] { + [words[at], words[at + 1], words[at + 2]] +} + +impl Sample { + fn decode(words: &[f32; 52], viewport: [f32; 2]) -> Option { + if !words.iter().all(|x| x.is_finite()) + || !viewport.iter().all(|&x| x.is_finite() && x > 0.0) + || words[16] <= 0.0 + || words[21] <= 0.0 + || words[27] != -1.0 + || words[31] != 0.0 + || words[51] != 1.0 + { + return None; + } + // The buffer contains view rotation and its inverse. World-space + // camera axes are the rows of the inverse, with backward negated. + let axes = [vec3(words, 32), vec3(words, 36), vec3(words, 40)]; + for (i, axis) in axes.iter().enumerate() { + for (j, other) in axes.iter().enumerate() { + let expected = if i == j { 1.0 } else { 0.0 }; + if (dot(*axis, *other) - expected).abs() > 0.001 + || (axis[j] - words[j * 4 + i]).abs() > 0.001 + { + return None; + } + } + } + Some(Self { + pose: Pose { + position: vec3(words, 48), + right: axes[0], + up: axes[1], + forward: axes[2].map(|value| -value), + }, + viewport, + projection_offset: [words[24], words[25]], + }) + } + + fn matches(self, render: [u32; 2], jitter: [f32; 2]) -> bool { + // The velocity shader's projection is in clip space. FidelityFX + // takes offsets in pixels. The two paths can use different signs. + (0..2).all(|axis| { + let extent = render[axis] as f32; + let projected = self.projection_offset[axis].abs() * extent * 0.5; + (self.viewport[axis] - extent).abs() < 0.5 + && (projected - jitter[axis].abs()).abs() < 0.015 + }) + } +} + +pub(crate) fn record(list: &HostList, address: u64, size: u32, viewport: [f32; 2]) { + if size != BUFFER_SIZE { + return; + } + let mut bytes = [0; 52 * 4]; + if !crate::host::read_into(address as *const u8, &mut bytes) { + return; + } + let chunks = bytes.as_chunks::<4>().0; + let words = std::array::from_fn(|i| f32::from_le_bytes(chunks[i])); + let Some(sample) = Sample::decode(&words, viewport) else { + return; + }; + list.defer_host(move || { + let mut candidates = CANDIDATES.lock().unwrap_or_else(|e| e.into_inner()); + // Keep one extra entry to mark overflow. Overflow and ambiguity + // both leave the current upscale without a usable camera. + if candidates.len() <= MAX_CANDIDATES && !candidates.contains(&sample) { + candidates.push(sample); + } + }); +} + +pub(crate) fn take_matching(render: [u32; 2], jitter: [f32; 2]) -> Option { + let mut candidates = CANDIDATES.lock().unwrap_or_else(|e| e.into_inner()); + let result = unique_match(&candidates, render, jitter); + if result.is_none() && !candidates.is_empty() { + let observed = candidates + .first() + .map(|s| (s.viewport, s.projection_offset)); + tracing::debug!( + ?render, + ?jitter, + ?observed, + candidates = candidates.len(), + "no unique camera for the host upscale" + ); + } + candidates.clear(); + result +} + +pub(crate) fn clear() { + CANDIDATES.lock().unwrap_or_else(|e| e.into_inner()).clear(); +} + +fn unique_match(candidates: &[Sample], render: [u32; 2], jitter: [f32; 2]) -> Option { + if candidates.len() > MAX_CANDIDATES { + return None; + } + let mut fits = candidates + .iter() + .filter(|candidate| candidate.matches(render, jitter)); + let pose = fits.next()?.pose; + fits.all(|candidate| candidate.pose == pose).then_some(pose) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn words() -> [f32; 52] { + let mut words = [0.0; 52]; + words[..16].copy_from_slice(&[ + 0.0, -1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, + ]); + words[16] = 1.2; + words[21] = 2.0; + words[24] = -0.5 / 1920.0; + words[25] = 0.75 / 1080.0; + words[27] = -1.0; + words[32..48].copy_from_slice(&[ + 0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, + ]); + words[48..].copy_from_slice(&[20.0, 40.0, -10.0, 1.0]); + words + } + + #[test] + fn decodes_world_axes_and_rejects_non_inverse_matrices() { + let mut words = words(); + let sample = Sample::decode(&words, [1920.0, 1080.0]).unwrap(); + assert_eq!(sample.pose.position, [20.0, 40.0, -10.0]); + assert_eq!(sample.pose.right, [0.0, 1.0, 0.0]); + assert_eq!(sample.pose.up, [-1.0, 0.0, 0.0]); + assert_eq!(sample.pose.forward, [0.0, 0.0, -1.0]); + words[4] = -1.0; + assert!(Sample::decode(&words, [1920.0, 1080.0]).is_none()); + } + + #[test] + fn partners_a_pose_only_with_a_matching_unambiguous_upscale() { + let size = [1920, 1080]; + let jitter = [0.25, -0.375]; + let sample = Sample::decode(&words(), [1920.0, 1080.0]).unwrap(); + assert_eq!(unique_match(&[sample], size, jitter), Some(sample.pose)); + assert_eq!(unique_match(&[sample], [2560, 1440], jitter), None); + assert_eq!(unique_match(&[sample], size, [0.0; 2]), None); + let mut other = sample; + other.pose.position[0] += 5.0; + assert_eq!(unique_match(&[sample, other], size, jitter), None); + } + + #[test] + fn warns_once_only_after_a_sustained_stretch_without_a_camera() { + let mut warning = MissingCameraWarning::default(); + for _ in 1..WARNING_AFTER_UPSCALES { + assert!(!warning.observe(false)); + } + assert!(!warning.observe(true)); + for _ in 1..WARNING_AFTER_UPSCALES { + assert!(!warning.observe(false)); + } + assert!(warning.observe(false)); + assert!(!warning.observe(true)); + for _ in 0..WARNING_AFTER_UPSCALES { + assert!(!warning.observe(false)); + } + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index f859688e102..6c8de29984d 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -6121,11 +6121,13 @@ impl HostList { result } - /// Moves host texture `copy` to `wanted` (a host state) in this list, - /// as [`HostList::transition`] does a title resource's host copy, and - /// records the barrier: for textures that are not a title resource's - /// host copy (colour twins) and for the copies between the two. - fn settle(&self, copy: &std::sync::Arc, wanted: u32) { + /// As [`HostList::settle`], returning the barrier to record instead of + /// recording it (frame generation batches its own). + pub(crate) fn move_texture( + &self, + copy: &std::sync::Arc, + wanted: u32, + ) -> Option { let wanted = legal_state(©.texture, wanted); let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) { @@ -6137,14 +6139,20 @@ impl HostList { let before = std::mem::replace(&mut o.get_mut().1, wanted); (before != wanted).then_some(before) } - }; - drop(states); - if let Some(before) = before { - let barrier = transition( - ©.texture, - D3D12_RESOURCE_STATES(before as i32), - D3D12_RESOURCE_STATES(wanted as i32), - ); + }?; + Some(transition( + ©.texture, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATES(wanted as i32), + )) + } + + /// Moves host texture `copy` to `wanted` (a host state) in this list, + /// as [`HostList::transition`] does a title resource's host copy, and + /// records the barrier: for textures that are not a title resource's + /// host copy (colour twins) and for the copies between the two. + fn settle(&self, copy: &std::sync::Arc, wanted: u32) { + if let Some(barrier) = self.move_texture(copy, wanted) { // SAFETY: an open list and a live texture. unsafe { self.list.ResourceBarrier(&[barrier]) }; } @@ -7632,6 +7640,9 @@ struct Presenter { ahead: Vec<(HostList, u64)>, hwnd: HWND, meter: Meter, + /// The AMD proxy and generator, if the opt-in path could be created. + #[cfg(feature = "diagnostics")] + framegen: Option, } /// The process's CPU time in microseconds, kernel and user. @@ -8088,6 +8099,10 @@ impl Host { } let p = presenter.as_mut()?; if (p.width, p.height, p.format) != (width, height, format) { + #[cfg(feature = "diagnostics")] + if let Some(fg) = &mut p.framegen { + fg.disable(&p.swap_chain); + } // Presents sent ahead hold back buffers until they have run. settle_now(WHY_SYNC); // SAFETY: no back buffer is held; every submission was waited for. @@ -8127,6 +8142,11 @@ impl Host { let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame); #[cfg(not(feature = "diagnostics"))] let read_now = false; + // Frame generation presents through its proxy from the one list + // upstream runs it with, not one sent ahead: in a sent-ahead + // list it crashed a run freeing objects (`bury`) after 4 minutes. + #[cfg(feature = "diagnostics")] + let read_now = read_now || p.framegen.is_some(); let slot = if late_free_present() && !read_now { let finished = FINISHED.load(Ordering::Acquire); p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| { @@ -8169,6 +8189,14 @@ impl Host { D3D12_RESOURCE_STATE_PRESENT, ), ]); + // Frame generation reads the last submitted upscale's depth and + // motion in this list, before the present inserts its frames. + #[cfg(feature = "diagnostics")] + let generated = p.framegen.as_mut().is_some_and(|fg| { + fg.prepare(&p.swap_chain, &self.device, copy, [width, height], frame) + }); + #[cfg(not(feature = "diagnostics"))] + let generated = false; copy.close(); match slot { Some(i) => { @@ -8181,7 +8209,19 @@ impl Host { if let Some((buffer, footprint)) = capture { crate::capture::save_read_back(frame, &buffer, &footprint); } - let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); + // The proxy paces generated frames against the display. + let status = p.swap_chain.Present(u32::from(generated), DXGI_PRESENT(0)); + #[cfg(not(feature = "diagnostics"))] + let _ = status; + #[cfg(feature = "diagnostics")] + if generated && let Some(fg) = &mut p.framegen { + if status == windows::Win32::Foundation::S_OK { + fg.presented(&p.swap_chain, frame); + } else if status.is_err() { + tracing::warn!(?status, frame, "FidelityFX frame generation: present failed; off"); + fg.disable(&p.swap_chain); + } + } p.meter.frame(p.hwnd); #[cfg(feature = "diagnostics")] return Some(probe.is_some_and(|b| crate::capture::black(&b))); @@ -8217,6 +8257,20 @@ impl Host { SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, ..Default::default() }; + #[cfg(feature = "diagnostics")] + let (swap_chain, framegen) = match crate::framegen::enabled() + .then(|| crate::framegen::Presentation::create(&factory, &self.device, &self.queue, hwnd, &desc)) + .flatten() + { + Some((swap_chain, fg)) => (swap_chain, Some(fg)), + None => ( + factory + .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None) + .and_then(|chain| chain.cast::())?, + None, + ), + }; + #[cfg(not(feature = "diagnostics"))] let swap_chain = factory .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)? .cast::()?; @@ -8233,6 +8287,8 @@ impl Host { ahead: Vec::new(), hwnd, meter: Meter::new(), + #[cfg(feature = "diagnostics")] + framegen, }) } } diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index f4e10ab4786..d36ec39e088 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -31,6 +31,8 @@ pub mod dxgi; pub mod external; pub mod fence; pub mod frame; +#[cfg(all(windows, feature = "diagnostics"))] +mod framegen; #[cfg(windows)] mod host; #[cfg(windows)] diff --git a/crates/victory-hle/src/modules/fidelityfx.rs b/crates/victory-hle/src/modules/fidelityfx.rs index f8ffa92461e..74c02d5175c 100644 --- a/crates/victory-hle/src/modules/fidelityfx.rs +++ b/crates/victory-hle/src/modules/fidelityfx.rs @@ -233,7 +233,19 @@ pub fn use_host_dir(dir: Option<&Path>) { match load(dir) { Ok((host, versions)) => { tracing::info!(folder = %dir.display(), versions, "FidelityFX: the host's upscaler serves the title's"); - let _ = HOST.set(host); + let installed = HOST.set(host).is_ok(); + #[cfg(not(feature = "diagnostics"))] + let _ = installed; + #[cfg(feature = "diagnostics")] + if installed + && let Ok(mode) = std::env::var("VICTORY_FIDELITYFX_FRAMEGEN") + && matches!(mode.as_str(), "1" | "4") + { + match victory_gpu::external::use_frame_generation(dir, mode == "4") { + Ok(dll) => tracing::info!(dll, mode, "FidelityFX: frame generation on the title's upscaled frames"), + Err(why) => tracing::warn!("FidelityFX frame generation: {why}; off"), + } + } } Err(why) => tracing::warn!( folder = %dir.display(), @@ -597,6 +609,9 @@ extern "C" fn ffxDispatch(context: *mut *mut c_void, desc: *mut Header) -> u32 { }; let list = dispatch.list.cast::().cast_const(); let output = dispatch.resources[6].resource.cast::(); + // Depth and motion as the title names them, for frame generation. + #[cfg(feature = "diagnostics")] + let title = dispatch; // Alive for the call (the list holds them too). let mut textures = Vec::new(); let mut backing_extents = [None; 7]; @@ -649,10 +664,19 @@ extern "C" fn ffxDispatch(context: *mut *mut c_void, desc: *mut Header) -> u32 { // SAFETY: a live texture. unsafe { t.GetDesc() }.Format.0 }).collect::>(), "FidelityFX: first upscaling, host formats of its textures"); - let Some(code) = victory_gpu::external::record(list, |host_list| { - dispatch.list = host_list.as_raw(); + let Some(code) = victory_gpu::external::record_upscale(list, |recording| { + dispatch.list = recording.list().as_raw(); // SAFETY: the PC dispatch on host objects; the context is the host's. - unsafe { (host.dispatch)(context, &raw mut dispatch.header) } + let code = unsafe { (host.dispatch)(context, &raw mut dispatch.header) }; + #[cfg(feature = "diagnostics")] + if code == OK { + recording.frame_generation_inputs( + title.resources[1].resource.cast::().cast_const(), + title.resources[2].resource.cast::().cast_const(), + frame_inputs(&title, create.flags), + ); + } + code }) else { once!( warn, @@ -677,6 +701,26 @@ extern "C" fn ffxDispatch(context: *mut *mut c_void, desc: *mut Header) -> u32 { code } +/// What frame generation needs of an upscaling: `settings` in the order of +/// `ffxDispatchDescUpscale` after the sizes (sharpening, sharpness, frame +/// time, pre-exposure, reset, camera near/far/fov/scale, flags) and its +/// context's creation `flags`. +#[cfg(feature = "diagnostics")] +fn frame_inputs(d: &DispatchUpscale, flags: u32) -> victory_gpu::external::FrameInputs { + let f = |i: usize| f32::from_bits(d.settings[i]); + victory_gpu::external::FrameInputs { + render: d.render_size, + jitter: d.jitter, + motion_scale: d.motion_scale, + frame_time_ms: f(2), + reset: d.settings[4] & 0xff != 0, + camera: [f(5), f(6), f(7), f(8)], + flags, + depth_desc: d.resources[1].description, + motion_desc: d.resources[2].description, + } +} + pub(crate) fn module() -> HleModule { HleModule { name: "fidelityfx",