diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index 659a65b..9707d12 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -153,6 +153,24 @@ enum Command { Replay(replay::Replay), /// Show the resolved configuration and check it. Config, + /// Check NVIDIA Streamline, DLSS and DLSS Frame Generation on this PC + /// without the title (`VICTORY_STREAMLINE_DIR`, `VICTORY_DLSS_MODE`, + /// `VICTORY_DLSS_PRESET`): what loads and what this GPU supports; with + /// --device, the host device handed over and DLSS run three times on + /// stand-in textures; with --present too, three seconds of presents with + /// frame generation in a window of ours. + #[cfg(windows)] + UpscalerCheck { + /// The output size, `x`. + #[arg(long, default_value = "2560x1440")] + output: String, + /// Make the host device and run DLSS on it. + #[arg(long)] + device: bool, + /// Present for three seconds with frame generation (with --device). + #[arg(long)] + present: bool, + }, } #[derive(Clone, Copy, ValueEnum)] @@ -230,6 +248,17 @@ fn main() -> Result<()> { #[cfg(all(windows, feature = "diagnostics"))] Command::Replay(options) => replay::run(options), Command::Config => show_config(), + #[cfg(windows)] + Command::UpscalerCheck { output, device, present } => { + let size = output + .split_once(['x', 'X']) + .and_then(|(w, h)| Some([w.trim().parse().ok()?, h.trim().parse().ok()?])) + .ok_or_else(|| anyhow::anyhow!("--output {output}: not x"))?; + for line in victory_hle::streamline::check(size, device || present, present) { + println!("{line}"); + } + Ok(()) + } } } diff --git a/apps/victory/src/native_1440p.rs b/apps/victory/src/native_1440p.rs index a70e3b2..499f83b 100644 --- a/apps/victory/src/native_1440p.rs +++ b/apps/victory/src/native_1440p.rs @@ -13,6 +13,7 @@ use anyhow::{Context, Result, ensure}; use victory_formats::texture::{Dimension, Swizzle, Texture, TextureDesc}; +use victory_hle::streamline::Mode; use victory_loader::PreparedImage; const RETAIL_BUILD: &str = "b99f876b74d4a77f03af5f878223b27bd647b5c35a79d5decd9f716504239e93"; @@ -74,6 +75,69 @@ pub(super) fn prepare(image: &mut PreparedImage, render_1080p: bool) -> Result<( Ok((render_width, render_height)) } +/// The title's renderer selection: `mov eax, 6; cmovne eax, ecx` (the +/// title's own temporal pass, or on Series S with the upscaler there the +/// FidelityFX path, 7). +const RENDERER_SELECTION: u32 = 0x007e_9421; +const STOCK_RENDERER_SELECTION: [u8; 8] = [0xb8, 6, 0, 0, 0, 0x0f, 0x45, 0xc1]; +/// The FidelityFX path's render size: the console check's result (Series S) +/// is noted as the FidelityFX quality mode and picks the scaled branch +/// (`movzx eax, al; mov [r14+0x90], eax; test al, al; jne`), whose scale +/// multiplies the output size. +const UPSCALER_SIZING: u32 = 0x028e_f69a; +const STOCK_UPSCALER_SIZING: [u8; 14] = [0x0f, 0xb6, 0xc0, 0x41, 0x89, 0x86, 0x90, 0, 0, 0, 0x84, 0xc0, 0x75, 0x0a]; +/// The native branch's load of 1.0, and the scaled branch's of the scale. +const NATIVE_LOAD: u32 = 0x028e_f6a8; +const STOCK_NATIVE_LOAD: [u8; 10] = [0xc5, 0xfa, 0x10, 0x05, 0x28, 0x78, 0x6d, 0x03, 0xeb, 0x08]; +const SCALED_LOAD: u32 = 0x028e_f6b2; +const STOCK_SCALED_LOAD: [u8; 8] = [0xc5, 0xfa, 0x10, 0x05, 0xa2, 0xe2, 0x86, 0x03]; +/// The scale the scaled branch loads (shared with other code: not written). +const UPSCALER_SCALE: u32 = 0x0615_d95c; + +/// Makes the title render through its FidelityFX upscaler path (renderer 7, +/// as Series S does) with the scene at `mode`'s scale of the output, so that +/// DLSS can take its upscale dispatches over (`victory_hle::modules::fidelityfx`). +/// On Series X the stock title uses its own temporal pass instead and never +/// loads its upscaler. The FidelityFX quality mode the title notes is +/// `mode`'s; the temporal scene scale (the title's own pass, and +/// `prepare`'s 1440p patch) is set to the same scale, as the stock Series X +/// image pairs them (2/3 each). Every patched instruction is checked against +/// the stock bytes first; nothing is written if one differs. +/// +/// From DexNom's fork (DexNom/VIctory, `apps/victory/src/native_1440p.rs`, +/// `prepare_fsr_4k`, GPL-3.0-or-later), there for a 4K output; kept here +/// with the 1440p one. +pub(super) fn prepare_upscaler(image: &mut PreparedImage, mode: Mode) -> Result<()> { + ensure!( + image.original_hash.to_hex().as_str() == RETAIL_BUILD, + "the upscaler path is only known for the retail build {RETAIL_BUILD}" + ); + ensure!(*field::<8>(image, RENDERER_SELECTION)? == STOCK_RENDERER_SELECTION, "unexpected renderer selection"); + ensure!(*field::<14>(image, UPSCALER_SIZING)? == STOCK_UPSCALER_SIZING, "unexpected upscaler render size selection"); + ensure!(*field::<10>(image, NATIVE_LOAD)? == STOCK_NATIVE_LOAD, "unexpected upscaler native scale load"); + ensure!(*field::<8>(image, SCALED_LOAD)? == STOCK_SCALED_LOAD, "unexpected upscaler scaled load"); + ensure!(*field::<4>(image, UPSCALER_SCALE)? == (2.0f32 / 3.0).to_le_bytes(), "unexpected upscaler scale"); + let temporal = f32::from_le_bytes(*field::<4>(image, TEMPORAL_SCALE)?); + ensure!( + temporal == 2.0 / 3.0 || temporal == 1.0, + "unexpected temporal scene scale {temporal} (stock 2/3, or 1 with the 1440p output)" + ); + // Renderer 7 every time it is asked (the console check has run). + *field::<8>(image, RENDERER_SELECTION)? = [0xb8, 7, 0, 0, 0, 0x90, 0x90, 0x90]; + // `mov eax, mode; mov [r14+0x90], eax; jmp scaled`. + *field::<14>(image, UPSCALER_SIZING)? = [0xb8, mode.ffx_mode(), 0, 0, 0, 0x41, 0x89, 0x86, 0x90, 0, 0, 0, 0xeb, 0x0a]; + if mode != Mode::Quality { + // The jump leaves the native branch unreached: its load's operand + // becomes a literal of ours, which the scaled branch loads. + let literal = NATIVE_LOAD + 4; + *field::<4>(image, literal)? = mode.scale().to_le_bytes(); + let displacement = literal as i32 - (SCALED_LOAD as i32 + 8); + *field::<4>(image, SCALED_LOAD + 4)? = displacement.to_le_bytes(); + } + *field::<4>(image, TEMPORAL_SCALE)? = mode.scale().to_le_bytes(); + Ok(()) +} + fn field(image: &mut PreparedImage, rva: u32) -> Result<&mut [u8; N]> { let offset = image.info.rva_to_file_offset(rva).context("display profile field missing")? as usize; image @@ -112,4 +176,39 @@ mod tests { assert!(prepare(&mut image, render_1080p).is_err()); } } + + /// With the retail executable (as above): the upscaler path at each + /// scale, alone (4K output) and after the 1440p patch; the scaled + /// branch then loads the mode's scale and the noted mode is its + /// FidelityFX mode. + #[test] + fn patches_the_upscaler_path() { + let Some(path) = std::env::var_os("VICTORY_DISPLAY_PROFILE_TEST_IMAGE") else { + return; + }; + let bytes = std::fs::read(path).unwrap(); + for native in [false, true] { + for mode in [Mode::Dlaa, Mode::Quality, Mode::Balanced, Mode::Performance, Mode::UltraPerformance] { + let mut image = victory_loader::prepare(&bytes).unwrap(); + if native { + prepare(&mut image, false).unwrap(); + } + prepare_upscaler(&mut image, mode).unwrap(); + assert_eq!(*field::<8>(&mut image, RENDERER_SELECTION).unwrap(), [0xb8, 7, 0, 0, 0, 0x90, 0x90, 0x90]); + let sizing = *field::<14>(&mut image, UPSCALER_SIZING).unwrap(); + assert_eq!(sizing[1], mode.ffx_mode()); + assert_eq!(sizing[12..], [0xeb, 0x0a]); + // The jump lands on the scaled load. + assert_eq!(UPSCALER_SIZING + 14 + 0x0a, SCALED_LOAD); + let disp = i32::from_le_bytes(*field::<4>(&mut image, SCALED_LOAD + 4).unwrap()); + let loaded = (SCALED_LOAD + 8).wrapping_add_signed(disp); + assert_eq!(f32::from_le_bytes(*field::<4>(&mut image, loaded).unwrap()), mode.scale()); + assert_eq!(f32::from_le_bytes(*field::<4>(&mut image, TEMPORAL_SCALE).unwrap()), mode.scale()); + // The shared constant stays as it was. + assert_eq!(*field::<4>(&mut image, UPSCALER_SCALE).unwrap(), (2.0f32 / 3.0).to_le_bytes()); + // Patched once, refused. + assert!(prepare_upscaler(&mut image, mode).is_err()); + } + } + } } diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 82bd30d..0c3c589 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -56,6 +56,21 @@ pub fn run( // A title that relaunched itself: the old process must be gone first. victory_hle::modules::lifecycle::wait_for_previous(); let cfg = victory_core::Config::load()?; + // DLSS and frame generation (`VICTORY_DLSS`, `VICTORY_FRAMEGEN`): Streamline + // is loaded before anything of the title or the host GPU, and fails soft; + // only if it offers one of them does the title render through its + // FidelityFX path, which DLSS takes over (`native_1440p::prepare_upscaler`). + let asked = victory_hle::streamline::Asked::from_env().map_err(anyhow::Error::msg)?; + let available = victory_hle::streamline::init(&asked); + let upscaler = (available.dlss || available.framegen).then_some(asked.mode); + if asked.any() { + println!( + "upscaling DLSS {}, frame generation {}{}", + if available.dlss { "on" } else if asked.dlss { "asked, not available" } else { "off" }, + if available.framegen { "on" } else if asked.framegen { "asked, not available" } else { "off" }, + upscaler.map(|m| format!(", scene at the {} scale ({})", m.name(), m.scale())).unwrap_or_default() + ); + } let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?; let mut prepared = victory_loader::prepare(&original)?; let hash = prepared.original_hash.to_hex(); @@ -70,15 +85,46 @@ pub fn run( let native_1440p = render_1080p || std::env::var("VICTORY_NATIVE_1440P").as_deref() == Ok("1"); let images = if native_1440p { anyhow::ensure!(matches!(console, Console::SeriesX), "1440p output needs the Series X profile"); - let (w, h) = native_1440p::prepare(&mut prepared, render_1080p)?; + if upscaler.is_some() && render_1080p { + println!("display VICTORY_RENDER_1080P is left out: VICTORY_DLSS_MODE sets the scene's size"); + } + let (w, h) = native_1440p::prepare(&mut prepared, render_1080p && upscaler.is_none())?; // SAFETY: nothing else runs yet; the title and the display mode list // read these later. unsafe { std::env::set_var("VICTORY_DISPLAY_MODE", format!("{}x{}", native_1440p::WIDTH, native_1440p::HEIGHT)); std::env::set_var("VICTORY_NATIVE_1440P", "1"); } - println!("display {}x{} SDR, scene {w}x{h}", native_1440p::WIDTH, native_1440p::HEIGHT); - cfg.cache_subdir(if render_1080p { "images/1080p-to-1440p-sdr" } else { "images/native-1440p-sdr" })? + match upscaler.map(|mode| (mode, native_1440p::prepare_upscaler(&mut prepared, mode))) { + Some((mode, Ok(()))) => { + let [rw, rh] = mode.render_size([native_1440p::WIDTH, native_1440p::HEIGHT]); + println!( + "display {}x{} SDR, scene {rw}x{rh} through the title's FidelityFX path ({})", + native_1440p::WIDTH, + native_1440p::HEIGHT, + mode.name() + ); + cfg.cache_subdir(&format!("images/native-1440p-upscaler-{}-sdr", mode.name()))? + } + other => { + if let Some((_, Err(e))) = other { + println!("upscaling the title's FidelityFX path was not patched in: {e:#}"); + } + println!("display {}x{} SDR, scene {w}x{h}", native_1440p::WIDTH, native_1440p::HEIGHT); + cfg.cache_subdir(if render_1080p { "images/1080p-to-1440p-sdr" } else { "images/native-1440p-sdr" })? + } + } + } else if let Some(mode) = upscaler { + match native_1440p::prepare_upscaler(&mut prepared, mode) { + Ok(()) => { + println!("display the title's output, scene at {} of it through its FidelityFX path ({})", mode.scale(), mode.name()); + cfg.cache_subdir(&format!("images/upscaler-{}", mode.name()))? + } + Err(e) => { + println!("upscaling the title's FidelityFX path was not patched in: {e:#}"); + cfg.cache_subdir("images")? + } + } } else { cfg.cache_subdir("images")? }; @@ -182,7 +228,10 @@ pub fn run( show(name, dll.bind_imports(&with_dlls, policy)?); } let exe_name = exe.file_name().unwrap_or_default().to_string_lossy(); - show(&exe_name, image.bind_imports(&with_dlls, policy)?); + // The title's FidelityFX calls go through ours when DLSS or frame + // generation is on (bound as before otherwise). + let interposed = victory_hle::modules::fidelityfx::Interpose { inner: &with_dlls }; + show(&exe_name, image.bind_imports(&interposed, policy)?); if execute { let size = image.info().size_of_image as usize; // SAFETY: the image stays mapped, and nothing of it has run yet. diff --git a/crates/victory-hle/src/lib.rs b/crates/victory-hle/src/lib.rs index ab8ea45..0ab8244 100644 --- a/crates/victory-hle/src/lib.rs +++ b/crates/victory-hle/src/lib.rs @@ -23,6 +23,9 @@ pub mod runtime; pub use host::HostPolicy; pub use registry::{HleExport, HleModule, registry}; pub use victory_gpu::console; +/// DLSS and frame generation (`VICTORY_DLSS`, `VICTORY_FRAMEGEN`). +#[cfg(windows)] +pub use victory_gpu::streamline; #[cfg(all(windows, feature = "diagnostics"))] pub use victory_gpu::replay; diff --git a/crates/victory-hle/src/modules/fidelityfx.rs b/crates/victory-hle/src/modules/fidelityfx.rs new file mode 100644 index 0000000..9f13081 --- /dev/null +++ b/crates/victory-hle/src/modules/fidelityfx.rs @@ -0,0 +1,433 @@ +//! `amd_fidelityfx_loader_xbox.dll`: the title's FidelityFX API, five +//! functions over chains of descriptions, each starting with a type id and +//! the next one's address. With DLSS or frame generation on +//! (`victory_gpu::streamline`, `VICTORY_DLSS=1`, `VICTORY_FRAMEGEN=1`), the +//! title's imports of it are bound to the functions here ([`Interpose`]), +//! which call the title's own DLL for everything except an upscale dispatch +//! DLSS takes: DLSS then records the upscaling at that place of the title's +//! command list instead, from the same textures into the same output. With +//! frame generation alone the title's own upscaling runs and its depth and +//! motion vectors are noted for the present. Without either switch, or +//! without Streamline, the imports are bound as before. +//! +//! The title's upscaler context stays the title's own (its FidelityFX makes +//! it), so the title's upscaling runs again on any frame DLSS does not take. +//! +//! The description layouts are the FidelityFX SDK's API (MIT) as DexNom's fork +//! reads them (DexNom/VIctory, `crates/victory-hle/src/modules/fidelityfx.rs`, +//! GPL-3.0-or-later), from which they are ported. +#![allow(non_snake_case)] +// Title code calls these through its import table. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; + +use victory_gpu::object::Object; +use victory_gpu::streamline::{self, Taken, Upscale, plan::Camera}; +use victory_loader::{ImportResolver, Provenance, Resolution}; +use victory_pe::ImportSymbol; + +/// The DLL the title imports the API from (it loads the upscaler itself). +pub const LOADER_DLL: &str = "amd_fidelityfx_loader_xbox.dll"; + +// Return codes. +const OK: u32 = 0; +const PARAMETER: u32 = 6; + +// Description types. +const CREATE_UPSCALE: u64 = 0x1_0000; +const DISPATCH_UPSCALE: u64 = 0x1_0001; + +#[repr(C)] +#[derive(Clone, Copy, Debug)] +struct Header { + kind: u64, + next: *mut Header, +} + +/// An upscaler context: flags, largest render and output sizes, a message +/// callback. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +struct CreateUpscale { + header: Header, + flags: u32, + max_render: [u32; 2], + max_output: [u32; 2], + message: usize, +} + +/// A resource, its description (type, format, sizes, mips, flags, usage) +/// and the state it is in. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +struct Resource { + resource: *mut c_void, + description: [u32; 8], + state: u32, +} + +/// One upscaling: the command list, then colour, depth, motion vectors, +/// exposure, reactive mask, transparency mask and output; jitter, +/// motion-vector scale, sizes, sharpening, frame time (ms), pre-exposure, +/// reset, camera and flags. (The C `bool`s are read as bytes.) +#[repr(C)] +#[derive(Clone, Copy, Debug)] +struct DispatchUpscale { + header: Header, + list: *mut c_void, + resources: [Resource; 7], + jitter: [f32; 2], + motion_scale: [f32; 2], + render_size: [u32; 2], + upscale_size: [u32; 2], + enable_sharpening: u8, + sharpness: f32, + frame_time_delta: f32, + pre_exposure: f32, + reset: u8, + camera_near: f32, + camera_far: f32, + camera_fov_angle_vertical: f32, + view_space_to_meters_factor: f32, + flags: u32, +} + +const _: () = assert!(size_of::() == 0x30); +const _: () = assert!(size_of::() == 0x30); +const _: () = assert!(size_of::() == 0x1b0); + +type Create = unsafe extern "C" fn(*mut *mut c_void, *mut Header, *const c_void) -> u32; +type Destroy = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> u32; +/// Configure, query and dispatch. +type Call = unsafe extern "C" fn(*mut *mut c_void, *mut Header) -> u32; + +/// The title's own functions, by [`NAMES`]. +static ORIGINALS: [AtomicUsize; 5] = [const { AtomicUsize::new(0) }; 5]; +const NAMES: [&str; 5] = ["ffxCreateContext", "ffxDestroyContext", "ffxConfigure", "ffxQuery", "ffxDispatch"]; + +/// An upscaler context the title made: its creation flags and largest +/// sizes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Created { + flags: u32, + max_render: [u32; 2], + max_output: [u32; 2], +} + +static CONTEXTS: Mutex>> = Mutex::new(None); + +macro_rules! once { + ($level:ident, $($arg:tt)*) => {{ + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::$level!($($arg)*)); + }}; +} + +/// Binds the title's imports of [`LOADER_DLL`] to the functions here when +/// DLSS or frame generation is on, keeping what `inner` binds them to (the +/// title's own DLL) for them to call; otherwise binds as `inner` does. +pub struct Interpose<'a> { + pub inner: &'a dyn ImportResolver, +} + +impl ImportResolver for Interpose<'_> { + fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution { + let found = self.inner.resolve(dll, symbol); + if !dll.eq_ignore_ascii_case(LOADER_DLL) || !streamline::serving() { + return found; + } + match (&found, symbol) { + (&Resolution::Found { address, .. }, ImportSymbol::Name { name, .. }) => match interpose(name, address) { + Some(ours) => Resolution::Found { address: ours, provenance: Provenance::Hle }, + None => found, + }, + _ => found, + } + } +} + +/// Keeps `original` as the title's `name` and gives ours, if we have one. +fn interpose(name: &str, original: usize) -> Option { + let i = NAMES.iter().position(|n| *n == name)?; + ORIGINALS[i].store(original, Relaxed); + let ours = [ + ffxCreateContext as *const () as usize, + ffxDestroyContext as *const () as usize, + ffxConfigure as *const () as usize, + ffxQuery as *const () as usize, + ffxDispatch as *const () as usize, + ][i]; + tracing::info!(name, original = format_args!("{original:#x}"), "FidelityFX: the title's import goes through ours (DLSS / frame generation)"); + Some(ours) +} + +fn original(i: usize) -> Option<*const ()> { + let address = ORIGINALS[i].load(Relaxed); + (address != 0).then_some(address as *const ()) +} + +fn contexts(f: impl FnOnce(&mut HashMap) -> T) -> T { + let mut contexts = CONTEXTS.lock().unwrap_or_else(|e| e.into_inner()); + f(contexts.get_or_insert_with(HashMap::new)) +} + +extern "C" fn ffxCreateContext(context: *mut *mut c_void, desc: *mut Header, memory: *const c_void) -> u32 { + let Some(create) = original(0) else { return PARAMETER }; + // SAFETY: the title's own function, with its arguments. + let code = unsafe { std::mem::transmute::<*const (), Create>(create)(context, desc, memory) }; + if code != OK || context.is_null() || desc.is_null() { + return code; + } + // SAFETY: the title passes a chain of descriptions. + if unsafe { (*desc).kind } != CREATE_UPSCALE { + return code; + } + // SAFETY: an upscaler description, by its type; the context was made. + let (created, handle) = unsafe { + let d = desc.cast::().read(); + (Created { flags: d.flags, max_render: d.max_render, max_output: d.max_output }, *context as usize) + }; + tracing::info!( + context = format_args!("{handle:#x}"), + flags = format_args!("{:#x}", created.flags), + max_render = ?created.max_render, + max_output = ?created.max_output, + "FidelityFX: the title made its upscaler" + ); + contexts(|c| c.insert(handle, created)); + code +} + +extern "C" fn ffxDestroyContext(context: *mut *mut c_void, memory: *const c_void) -> u32 { + let Some(destroy) = original(1) else { return PARAMETER }; + if !context.is_null() { + // SAFETY: the title passes its context. + let handle = unsafe { *context } as usize; + if contexts(|c| c.remove(&handle)).is_some() { + streamline::upscaler_destroyed(handle); + } + } + // SAFETY: the title's own function, with its arguments. + unsafe { std::mem::transmute::<*const (), Destroy>(destroy)(context, memory) } +} + +extern "C" fn ffxConfigure(context: *mut *mut c_void, desc: *mut Header) -> u32 { + let Some(configure) = original(2) else { return PARAMETER }; + // SAFETY: the title's own function, with its arguments. + unsafe { std::mem::transmute::<*const (), Call>(configure)(context, desc) } +} + +extern "C" fn ffxQuery(context: *mut *mut c_void, desc: *mut Header) -> u32 { + let Some(query) = original(3) else { return PARAMETER }; + if !desc.is_null() { + // SAFETY: the title passes a description. + let kind = unsafe { (*desc).kind }; + static SEEN: Mutex> = Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if !seen.contains(&kind) && seen.len() < 32 { + seen.push(kind); + tracing::info!(kind = format_args!("{kind:#x}"), "FidelityFX: the title asks a query of this kind (answered by its own DLL)"); + } + } + // SAFETY: the title's own function, with its arguments. + unsafe { std::mem::transmute::<*const (), Call>(query)(context, desc) } +} + +extern "C" fn ffxDispatch(context: *mut *mut c_void, desc: *mut Header) -> u32 { + let Some(dispatch) = original(4) else { return PARAMETER }; + // SAFETY: the title's own function, with its arguments. + let own = || unsafe { std::mem::transmute::<*const (), Call>(dispatch)(context, desc) }; + if context.is_null() || desc.is_null() { + return own(); + } + // SAFETY: the title passes a description and its context. + let (kind, handle) = unsafe { ((*desc).kind, *context as usize) }; + if kind != DISPATCH_UPSCALE { + return own(); + } + let Some(created) = contexts(|c| c.get(&handle).copied()) else { + once!(warn, "FidelityFX: an upscale dispatch on a context we did not see made; the title's own runs"); + return own(); + }; + // SAFETY: an upscaling, by its type. + let d = unsafe { desc.cast::().read() }; + first_dispatch(&d, &created); + let up = upscale(&d, &created, handle); + match streamline::upscale(&up) { + Taken::Dlss => OK, + Taken::Noted => own(), + Taken::No(why) => { + streamline::forwarded(); + refused(why); + own() + } + } +} + +/// Each reason the title's own upscaling ran instead, once. +fn refused(why: &'static str) { + static SEEN: Mutex> = Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if !seen.contains(&why) { + seen.push(why); + tracing::warn!("FidelityFX: the title's own upscaling runs: {why}"); + } +} + +/// The first upscale dispatch, all of it. +fn first_dispatch(d: &DispatchUpscale, created: &Created) { + once!( + info, + render = ?d.render_size, + output = ?d.upscale_size, + max_render = ?created.max_render, + max_output = ?created.max_output, + create_flags = format_args!("{:#x}", created.flags), + flags = format_args!("{:#x}", d.flags), + jitter = ?d.jitter, + motion_vector_scale = ?d.motion_scale, + near = d.camera_near, + far = d.camera_far, + fov = d.camera_fov_angle_vertical, + frame_ms = d.frame_time_delta, + pre_exposure = d.pre_exposure, + reset = d.reset != 0, + sharpening = d.enable_sharpening != 0, + resources = ?d.resources.iter().map(|r| (r.resource as usize != 0, r.description[1], r.description[2], r.description[3], r.state)).collect::>(), + "FidelityFX: the title's first upscale dispatch (resources: present, format, width, height, state)" + ); +} + +/// An upscaling in `victory_gpu::streamline`'s terms. The output size is the +/// context's largest when the dispatch names none (as FidelityFX reads it). +fn upscale(d: &DispatchUpscale, created: &Created, context: usize) -> Upscale { + let output = if d.upscale_size == [0, 0] { created.max_output } else { d.upscale_size }; + Upscale { + context, + list: d.list.cast::().cast_const(), + resources: d.resources.map(|r| (r.resource.cast::().cast_const(), r.state)), + camera: Camera { + jitter: d.jitter, + motion_scale: d.motion_scale, + render: d.render_size, + output, + near: d.camera_near, + far: d.camera_far, + fov_y: d.camera_fov_angle_vertical, + reset: d.reset != 0, + flags: created.flags, + }, + pre_exposure: d.pre_exposure, + frame_ms: d.frame_time_delta, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::mem::offset_of; + use std::ptr::null_mut; + + #[test] + fn descriptions_lay_out_as_the_sdk() { + assert_eq!(offset_of!(CreateUpscale, flags), 0x10); + assert_eq!(offset_of!(CreateUpscale, max_output), 0x1c); + assert_eq!(offset_of!(Resource, state), 0x28); + assert_eq!(offset_of!(DispatchUpscale, list), 0x10); + assert_eq!(offset_of!(DispatchUpscale, resources), 0x18); + assert_eq!(offset_of!(DispatchUpscale, jitter), 0x168); + assert_eq!(offset_of!(DispatchUpscale, render_size), 0x178); + assert_eq!(offset_of!(DispatchUpscale, upscale_size), 0x180); + assert_eq!(offset_of!(DispatchUpscale, enable_sharpening), 0x188); + assert_eq!(offset_of!(DispatchUpscale, frame_time_delta), 0x190); + assert_eq!(offset_of!(DispatchUpscale, reset), 0x198); + assert_eq!(offset_of!(DispatchUpscale, camera_near), 0x19c); + assert_eq!(offset_of!(DispatchUpscale, flags), 0x1ac); + } + + fn resource(at: usize, state: u32) -> Resource { + Resource { resource: at as *mut c_void, description: [1, 10, 2560, 1440, 1, 1, 0, 0], state } + } + + fn dispatch(output: [u32; 2]) -> DispatchUpscale { + DispatchUpscale { + header: Header { kind: DISPATCH_UPSCALE, next: null_mut() }, + list: 0x1000 as *mut c_void, + resources: [ + resource(0x10, 0xc), + resource(0x20, 0xc), + resource(0x30, 0xc), + resource(0, 0), + resource(0x50, 0xc), + resource(0, 0), + resource(0x70, 0x2), + ], + jitter: [0.25, -0.125], + motion_scale: [1706.0, 960.0], + render_size: [1706, 960], + upscale_size: output, + enable_sharpening: 0, + sharpness: 0.0, + frame_time_delta: 33.3, + pre_exposure: 1.5, + reset: 1, + camera_near: 0.1, + camera_far: 5000.0, + camera_fov_angle_vertical: 0.9, + view_space_to_meters_factor: 1.0, + flags: 0, + } + } + + /// A dispatch reads as the upscaling it names; without an output size + /// the context's largest is the output. + #[test] + fn a_dispatch_reads_as_its_upscaling() { + let created = Created { flags: 0x29, max_render: [2560, 1440], max_output: [2560, 1440] }; + let up = upscale(&dispatch([2560, 1440]), &created, 0xabc); + assert_eq!(up.context, 0xabc); + assert_eq!(up.list as usize, 0x1000); + assert_eq!(up.resources[streamline::COLOUR], (0x10 as *const Object, 0xc)); + assert_eq!(up.resources[streamline::EXPOSURE].0 as usize, 0); + assert_eq!(up.resources[streamline::OUTPUT], (0x70 as *const Object, 0x2)); + assert_eq!(up.camera.render, [1706, 960]); + assert_eq!(up.camera.output, [2560, 1440]); + assert_eq!(up.camera.flags, 0x29); + assert!(up.camera.reset && up.camera.depth_inverted()); + assert_eq!((up.pre_exposure, up.frame_ms), (1.5, 33.3)); + let up = upscale(&dispatch([0, 0]), &Created { max_output: [1920, 1080], ..created }, 0); + assert_eq!(up.camera.output, [1920, 1080]); + } + + struct Fixed; + impl ImportResolver for Fixed { + fn resolve(&self, dll: &str, _: &ImportSymbol) -> Resolution { + if dll.eq_ignore_ascii_case(LOADER_DLL) { + Resolution::Found { address: 0x1234, provenance: Provenance::Title } + } else { + Resolution::Missing + } + } + } + + /// Without Streamline the title's imports bind as before; the names we + /// serve are the API's five. + #[test] + fn without_streamline_the_titles_own_binds() { + let name = |n: &str| ImportSymbol::Name { hint: 0, name: n.into() }; + let interposed = Interpose { inner: &Fixed }; + assert_eq!( + interposed.resolve("AMD_FIDELITYFX_LOADER_XBOX.DLL", &name("ffxDispatch")), + Resolution::Found { address: 0x1234, provenance: Provenance::Title } + ); + assert_eq!(interposed.resolve("other.dll", &name("ffxDispatch")), Resolution::Missing); + assert_eq!(interpose("ffxGetVersion", 1), None); + assert!(interpose("ffxQuery", 0x5678).is_some()); + assert_eq!(original(3), Some(0x5678 as *const ())); + ORIGINALS[3].store(0, Relaxed); + } +} diff --git a/crates/victory-hle/src/modules/mod.rs b/crates/victory-hle/src/modules/mod.rs index 7f8a931..5c09fb2 100644 --- a/crates/victory-hle/src/modules/mod.rs +++ b/crates/victory-hle/src/modules/mod.rs @@ -17,6 +17,8 @@ pub mod dsp; #[cfg(windows)] pub mod dstorage; #[cfg(windows)] +pub mod fidelityfx; +#[cfg(windows)] pub mod files; pub mod gameinput; pub mod kernel;