Initial
Rust validation / Formatting (push) Failing after 27s
EonaCat/ci-workflows: SonarQube / sonar (push) Successful in 47s
Rust validation / Windows x64 build and tests (push) Canceled after 0s

This commit is contained in:
EonaCat committed 2026-12-04 21:03:25 +01:00
1 parent 2cff35f215
commit 1b0d534e6c
358 files changed
+253978 -74

No files matched your search

+392
View File
@@ -0,0 +1,392 @@
#![allow(non_snake_case)]
#![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 eonacat_xsbox_gpu::object::Object;
use eonacat_xsbox_gpu::streamline::{self, Taken, Upscale, plan::Camera};
use eonacat_xsbox_gpu::loader::{ImportResolver, Provenance, Resolution};
use eonacat_xsbox_gpu::pe::ImportSymbol;
pub const LOADER_DLL: &str = "amd_fidelityfx_loader_xbox.dll";
const OK: u32 = 0;
const PARAMETER: u32 = 6;
const CREATE_UPSCALE: u64 = 0x1_0000;
const DISPATCH_UPSCALE: u64 = 0x1_0001;
pub fn init_pc(dir: &std::path::Path) -> bool {
match pc::init(dir) {
Ok(()) => true,
Err(error) => {
tracing::warn!(%error, "PC FidelityFX is unavailable; retaining the title renderer");
false
}
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
struct Header {
kind: u64,
next: *mut Header,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
struct CreateUpscale {
header: Header,
flags: u32,
max_render: [u32; 2],
max_output: [u32; 2],
message: usize,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
struct Resource {
resource: *mut c_void,
description: [u32; 8],
state: u32,
}
#[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::<CreateUpscale>() == 0x30);
const _: () = assert!(size_of::<Resource>() == 0x30);
const _: () = assert!(size_of::<DispatchUpscale>() == 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;
type Call = unsafe extern "C" fn(*mut *mut c_void, *mut Header) -> u32;
static ORIGINALS: [AtomicUsize; 5] = [const { AtomicUsize::new(0) }; 5];
const NAMES: [&str; 5] = ["ffxCreateContext", "ffxDestroyContext", "ffxConfigure", "ffxQuery", "ffxDispatch"];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Created {
flags: u32,
max_render: [u32; 2],
max_output: [u32; 2],
clamped: bool,
}
static CONTEXTS: Mutex<Option<HashMap<usize, Created>>> = 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)*));
}};
}
mod pc;
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() || pc::active()) {
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,
}
}
}
pub fn wrap(dll: &str, name: &str, address: usize) -> usize {
if address == 0 || !dll.eq_ignore_ascii_case(LOADER_DLL) || !streamline::serving() {
return address;
}
interpose(name, address).unwrap_or(address)
}
fn interpose(name: &str, original: usize) -> Option<usize> {
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<T>(f: impl FnOnce(&mut HashMap<usize, Created>) -> T) -> T {
let mut contexts = CONTEXTS.lock().unwrap_or_else(|e| e.into_inner());
f(contexts.get_or_insert_with(HashMap::new))
}
const SHIPPING_MAX_OUTPUT: [u32; 2] = [1920, 1080];
const SHIPPING_MAX_RENDER: [u32; 2] = [1280, 720];
fn shipping_sizes(render: [u32; 2], output: [u32; 2]) -> Option<([u32; 2], [u32; 2])> {
((render, output) != (SHIPPING_MAX_RENDER, SHIPPING_MAX_OUTPUT)).then_some((SHIPPING_MAX_RENDER, SHIPPING_MAX_OUTPUT))
}
fn find(desc: *mut Header, kind: u64) -> Option<*mut Header> {
let mut at = desc;
for _ in 0..16 {
if at.is_null() {
return None;
}
let header = unsafe { at.read() };
if header.kind == kind {
return Some(at);
}
at = header.next;
}
None
}
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 };
let call = |desc: *mut Header| unsafe { std::mem::transmute::<*const (), Create>(create)(context, desc, memory) };
let Some(upscale) = find(desc, CREATE_UPSCALE) else {
return call(desc);
};
let asked = unsafe { upscale.cast::<CreateUpscale>().read() };
if pc::active() && !streamline::upscaling() {
return pc::create(context, asked, memory);
}
let shipping = streamline::upscaling().then(|| shipping_sizes(asked.max_render, asked.max_output)).flatten();
let clamped = shipping.is_some();
let code = if let Some((render, output)) = shipping {
let mut fitted = asked;
fitted.max_render = render;
fitted.max_output = output;
unsafe { upscale.cast::<CreateUpscale>().write(fitted) };
let code = call(desc);
unsafe { upscale.cast::<CreateUpscale>().write(asked) };
tracing::info!(
asked_render = ?asked.max_render,
asked_output = ?asked.max_output,
made_render = ?fitted.max_render,
made_output = ?fitted.max_output,
code,
"FidelityFX: the title's upscaler made at a size its shipping FSR4 accepts; DLSS upscales to the size asked"
);
code
} else {
call(desc)
};
if code != OK || context.is_null() {
if code != OK && !streamline::upscaling() {
tracing::error!(
code,
max_render = ?asked.max_render,
max_output = ?asked.max_output,
"FidelityFX: the title's own upscaler was not made at these sizes (its shipping FSR4 takes 1280x720 or 1920x1080 in, 1920x1080 out): with frame generation at another output size, set EONACAT_XS_DLSS=1 as well; the title fails at its first upscaling without an upscaler"
);
}
return code;
}
let handle = unsafe { *context } as usize;
let created = Created { flags: asked.flags, max_render: asked.max_render, max_output: asked.max_output, clamped };
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 {
if let Some(code) = pc::destroy(context) {
return code;
}
let Some(destroy) = original(1) else { return PARAMETER };
if !context.is_null() {
let handle = unsafe { *context } as usize;
if contexts(|c| c.remove(&handle)).is_some() {
streamline::upscaler_destroyed(handle);
}
}
unsafe { std::mem::transmute::<*const (), Destroy>(destroy)(context, memory) }
}
extern "C" fn ffxConfigure(context: *mut *mut c_void, desc: *mut Header) -> u32 {
if let Some(code) = pc::call(context, desc, false) {
return code;
}
let Some(configure) = original(2) else { return PARAMETER };
unsafe { std::mem::transmute::<*const (), Call>(configure)(context, desc) }
}
extern "C" fn ffxQuery(context: *mut *mut c_void, desc: *mut Header) -> u32 {
if let Some(code) = pc::call(context, desc, true) {
return code;
}
let Some(query) = original(3) else { return PARAMETER };
if !desc.is_null() {
let kind = unsafe { (*desc).kind };
static SEEN: Mutex<Vec<u64>> = 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)");
}
}
unsafe { std::mem::transmute::<*const (), Call>(query)(context, desc) }
}
extern "C" fn ffxDispatch(context: *mut *mut c_void, desc: *mut Header) -> u32 {
if let Some(code) = pc::dispatch(context, desc) {
return code;
}
let Some(dispatch) = original(4) else { return PARAMETER };
let own = || unsafe { std::mem::transmute::<*const (), Call>(dispatch)(context, desc) };
if context.is_null() || desc.is_null() {
return own();
}
let handle = unsafe { *context as usize };
let Some(asked) = find(desc, DISPATCH_UPSCALE) else {
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();
};
let d = unsafe { asked.cast::<DispatchUpscale>().read() };
first_dispatch(&d, &created);
let up = upscale(&d, &created, handle);
match streamline::upscale(&up) {
Taken::Dlss => OK,
Taken::Noted => own(),
Taken::No(why) if created.clamped => {
refused(why);
if eonacat_xsbox_gpu::upscale_fallback::upscale(&up) {
once!(warn, "FidelityFX: DLSS did not take an upscaling on a context made smaller than asked; a plain (bilinear) one ran");
} else {
once!(warn, "FidelityFX: DLSS did not take an upscaling on a context made smaller than asked; none ran");
}
OK
}
Taken::No(why) => {
streamline::forwarded();
refused(why);
own()
}
}
}
fn refused(why: &'static str) {
static SEEN: Mutex<Vec<&'static str>> = 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}");
}
}
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::<Vec<_>>(),
"FidelityFX: the title's first upscale dispatch (resources: present, format, width, height, state)"
);
}
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::<Object>().cast_const(),
resources: d.resources.map(|r| (r.resource.cast::<Object>().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,
view_space_to_meters: d.view_space_to_meters_factor,
}
}