AMD FSR 3 frame generation for cards without DLSS frame generation; start notice; F1 preload

- FSR 3 frame generation (AMD FidelityFX 2.x DLLs, never in the repository:
  VICTORY_FIDELITYFX_DIR or a fidelityfx folder beside victory.exe), 2x at most,
  with the HUD-less picture so the HUD is not doubled. Series X needs DLSS upscaling.
- F1 menu: FRAME GEN TYPE (auto, DLSS, FSR 3); PRELOAD SHADERS; unset rows read NOT SET;
  save and restart opens its own console window.
- A notice at the start (30 s on the picture, and in the console): the GPU, which
  frame generation runs, and why not (DLSS off, NVIDIA files missing, or the card).
- victory preload / --preload; warm keys its work to the program's path.
- Logs are named victory-nvidia-...; README: what each card supports, first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
trustno1-coderandClaude Opus 5.5 committed 2026-11-27 09:06:36 -08:00
1 parent d12eb1b23d
commit 29d8dbf7d9
12 files changed
+1712 -118

No files matched your search

+25 -6
View File
@@ -2828,7 +2828,7 @@ fn line() -> std::sync::MutexGuard<'static, Line> {
}
/// Why flights were settled ([`LATE_STATS`]' places from 2 on).
const WHY_SYNC: usize = 2;
pub(crate) const WHY_SYNC: usize = 2;
const WHY_CARD_DONE: usize = 3;
const WHY_VALUE: usize = 4;
const WHY_STALE: usize = 5;
@@ -9234,6 +9234,8 @@ struct Presenter {
composer: Option<crate::compose::Composer>,
/// The numbers panel (F3), in every build.
panel: panel::Panel,
/// What the card does for frame generation, for the first seconds.
notice: panel::Notice,
/// The F1 settings menu.
menu: menu::Menu,
}
@@ -9703,8 +9705,8 @@ impl Meter {
let Some(caption) = &self.caption else { return };
// With frame generation showing more frames than are rendered, both rates.
let text = match crate::streamline::shown_per_frame() {
1 => format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame"),
per => format!(" | VIctory {fps:.0} fps (frame gen {:.0} fps) {ms:.1} ms/frame {draws:.0} draws/frame", fps * f64::from(per)),
1 => format!(" | VIctory-NVIDIA {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame"),
per => format!(" | VIctory-NVIDIA {fps:.0} fps (frame gen {:.0} fps) {ms:.1} ms/frame {draws:.0} draws/frame", fps * f64::from(per)),
};
let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
text.push(0);
@@ -9799,6 +9801,7 @@ impl Host {
// Presents sent ahead hold back buffers until they have run.
settle_now(WHY_SYNC);
crate::streamline::resizing();
crate::streamline::fsr::resizing();
// SAFETY: no back buffer is held; every submission was waited for.
let resized = unsafe {
p.swap_chain
@@ -9972,6 +9975,7 @@ impl Host {
crate::popwatch::take(&self.device, list, texture)
};
p.panel.draw(self, copy, &back, (width, height), format);
p.notice.draw(self, copy, &back, (width, height), format);
p.menu.draw(self, copy, &back, (width, height), format);
#[cfg(not(feature = "diagnostics"))]
let _ = frame;
@@ -9993,6 +9997,17 @@ impl Host {
));
list.ResourceBarrier(&post);
}
// FSR 3 frame generation: this frame's prepare dispatch, last in
// the list before the Present (its own descriptor heaps).
crate::streamline::fsr::before_present(
&self.device,
&p.swap_chain,
list,
[width, height],
format,
(texture, state_u32),
composed && overlay.is_some(),
);
copy.close();
let flown = match slot {
Some(i) => {
@@ -10078,14 +10093,17 @@ impl Host {
SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
..Default::default()
};
// FSR 3 frame generation (where DLSS Frame Generation does not
// run): FidelityFX's frame interpolation swap chain.
let fsr = crate::streamline::fsr::swap_chain(&factory, &self.queue, hwnd, &desc);
// With frame generation, through Streamline's factory proxy and
// on its queue proxy: the swap chain is its proxy.
let proxied = crate::streamline::swap_chain_factory(&factory).map(|(proxy, queue)| {
let proxied = if fsr.is_some() { None } else { crate::streamline::swap_chain_factory(&factory) }.map(|(proxy, queue)| {
proxy
.CreateSwapChainForHwnd(&queue, hwnd, &desc, None, None)
.and_then(|s| s.cast::<IDXGISwapChain3>())
});
let swap_chain = match proxied {
let swap_chain = if let Some(swap_chain) = fsr { swap_chain } else { match proxied {
Some(Ok(swap_chain)) => {
crate::streamline::swap_chain_made(true, None);
// Frame generation must be off across a change between
@@ -10105,7 +10123,7 @@ impl Host {
None => crate::streamline::present_hooked(
factory.CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?.cast::<IDXGISwapChain3>()?,
),
};
} };
let copy = self.new_list()?;
copy.close();
tracing::info!(width, height, format = format.0, "presenting to a window");
@@ -10121,6 +10139,7 @@ impl Host {
meter: Meter::new(),
composer: None,
panel: panel::Panel::new(),
notice: panel::Notice::new(),
menu: menu::Menu::new(),
})
}
+121 -18
View File
@@ -1,6 +1,9 @@
//! The F1 settings menu. F1 shows and hides it while our window has the
//! focus; Up/Down pick a setting, Left/Right change it, Enter runs the line
//! picked (save, save and restart, reset, close), Esc closes. While it is
//! picked (save, save and restart, preload shaders, reset, close), Esc
//! closes. Preloading saves, ends this run and has the launcher make every
//! shader before the title starts again (`VICTORY_PRELOAD=1`, `victory
//! preload`); it asks for a second Enter first. While it is
//! shown the title sees no keyboard (`crate::SETTINGS_MENU_OPEN`, read by the
//! input module); a pad still works.
//!
@@ -35,9 +38,21 @@ const GLYPH: (u32, u32) = (5, 7);
const CELL: (u32, u32) = (6, 9);
const COLUMNS: u32 = 60;
/// Lines of the box: a title, a help line, a blank, the settings shown, a
/// blank and a note.
/// blank, what the line picked does (`ABOUT`, else blank), a note and the
/// repository's link.
const ROWS: usize = 20;
const LINES: u32 = ROWS as u32 + 5;
const LINES: u32 = ROWS as u32 + 9;
/// The action that preloads shaders, and what is said of it while it is picked.
const PRELOAD: usize = 2;
const ABOUT_PRELOAD: [&str; 3] = [
"MAKES EVERY SHADER AHEAD, THEN STARTS THE GAME AGAIN.",
"TAKES A WHILE: MAYBE A LONG TIME, DEPENDING ON HARDWARE.",
"A LATER UPDATE OF THIS BUILD MAY NEED A NEW PRELOAD.",
];
/// The note after the first Enter on it: the second one does it.
const CONFIRM_PRELOAD: &str = "ENTER AGAIN: SAVE, CLOSE THE GAME AND PRELOAD";
/// The last line of the box: where this build comes from.
const REPO: &str = "GITHUB.COM/TRUSTNO1-CODER/VICTORY-NVIDIA";
const RIM: u32 = 4;
const UPLOADS: usize = 4;
@@ -60,6 +75,8 @@ const ITEMS: &[Item] = &[
// The launcher's own choices.
Item { var: "VICTORY_MENU_DLSS", label: "DLSS", values: &[("quality", "QUALITY"), ("balanced", "BALANCED"), ("performance", "PERFORMANCE"), ("dlaa", "DLAA (NATIVE)"), ("off", "OFF")], live: false },
Item { var: "VICTORY_MENU_FRAMEGEN", label: "FRAME GENERATION", values: &[("0", "OFF"), ("2", "2X"), ("3", "3X"), ("4", "4X"), ("5", "5X"), ("6", "6X (MOST)")], live: false },
// DLSS Frame Generation where it runs (RTX 40 and later), else AMD's FSR 3 (2X only).
Item { var: "VICTORY_MENU_FG_TYPE", label: "FRAME GEN TYPE", values: &[("auto", "AUTO"), ("dlss", "DLSS"), ("fsr", "FSR 3 (OLDER CARDS)")], live: false },
Item { var: "VICTORY_MENU_FPS", label: "FRAME RATE CAP", values: &[("1000", "NONE"), ("120", "120"), ("60", "60"), ("30", "30 (THE GAME)")], live: false },
Item { var: "VICTORY_FPS_LINE", label: "FPS AT THE TOP", values: &[("1", "ON"), ("0", "OFF")], live: true },
Item { var: "VICTORY_PANEL", label: "STATS PANEL (F3)", values: &[("0", "OFF"), ("1", "ON")], live: true },
@@ -87,12 +104,52 @@ const ITEMS: &[Item] = &[
Item { var: "VICTORY_PORT_CONSTANTS", label: "CONSTANTS HEAP IN PLACE", values: UNSET_ON, live: false },
];
/// The lines after the settings.
const ACTIONS: [&str; 4] = ["SAVE AND RESTART NOW", "SAVE FOR NEXT START", "RESET ALL TO PLAY DEFAULTS", "CLOSE"];
const ACTIONS: [&str; 5] =
["SAVE AND RESTART NOW", "SAVE FOR NEXT START", "PRELOAD SHADERS (RESTARTS THE GAME)", "RESET ALL TO PLAY DEFAULTS", "CLOSE"];
fn get(var: &str) -> String {
std::env::var(var).unwrap_or_default()
}
/// Starts `command_line` in a console window of its own, with that console's input and output.
/// (`std::process::Command` always hands its child this process's standard handles: the restarted
/// launcher then wrote into the old launcher's pipe and log, not its own window, and kept the old
/// launcher waiting on that pipe.)
fn new_console(command_line: &str) -> std::io::Result<()> {
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Threading::{CREATE_NEW_CONSOLE, CreateProcessW, PROCESS_INFORMATION, STARTUPINFOW};
let mut line: Vec<u16> = command_line.encode_utf16().chain(Some(0)).collect();
// SAFETY: plain structs, zero is their empty value.
let mut startup: STARTUPINFOW = unsafe { std::mem::zeroed() };
startup.cb = std::mem::size_of::<STARTUPINFOW>() as u32;
let mut process: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: `line` is a writable, terminated UTF-16 string; no handles inherited; this
// process's environment and folder.
let made = unsafe {
CreateProcessW(
std::ptr::null(),
line.as_mut_ptr(),
std::ptr::null(),
std::ptr::null(),
0,
CREATE_NEW_CONSOLE,
std::ptr::null(),
std::ptr::null(),
&startup,
&mut process,
)
};
if made == 0 {
return Err(std::io::Error::last_os_error());
}
// SAFETY: the two handles CreateProcessW gave, closed once.
unsafe {
CloseHandle(process.hThread);
CloseHandle(process.hProcess);
}
Ok(())
}
/// Whether a change of `item` shows at once. Frame generation does when this run started with
/// it ready (the launcher asks for that whenever Streamline is there).
fn live(item: &Item) -> bool {
@@ -131,6 +188,17 @@ fn index_of(item: &Item, value: &str) -> Option<usize> {
item.values.iter().position(|(v, _)| *v == value)
}
/// What the menu shows for `value`: its label, an unknown value as itself,
/// and a value the launcher did not set (a start without play.ps1) as
/// "NOT SET" rather than a blank.
fn shown_value(item: &Item, value: &str) -> String {
match index_of(item, value) {
Some(i) => item.values[i].1.to_owned(),
None if value.is_empty() => "NOT SET".to_owned(),
None => value.to_ascii_uppercase(),
}
}
/// Keys pressed, gathered on a thread of their own every 10 ms: a frame
/// lasts 50 ms and more, and a short press would fall between two frames.
fn keys() -> &'static Mutex<Vec<u16>> {
@@ -294,7 +362,7 @@ impl Menu {
let cursor = if row == self.at { '>' } else { ' ' };
let line = if let Some(item) = ITEMS.get(row) {
let value = &self.values[row];
let shown = index_of(item, value).map_or(value.to_ascii_uppercase(), |i| item.values[i].1.to_owned());
let shown = shown_value(item, value);
let mark = if *value != self.started[row] { if live(item) { " *LIVE" } else { " *" } } else if live(item) { " LIVE" } else { "" };
format!("{cursor} {:<27} < {shown} >{mark}", item.label)
} else {
@@ -306,7 +374,10 @@ impl Menu {
out.push(String::new());
}
out.push(String::new());
let about = if self.at == ITEMS.len() + PRELOAD { ABOUT_PRELOAD } else { [""; 3] };
out.extend(about.iter().map(|l| (*l).to_owned()));
out.push(if self.note.is_empty() { "* = CHANGED: APPLIES AT THE NEXT START UNLESS LIVE".to_owned() } else { self.note.clone() });
out.push(REPO.to_owned());
out
}
@@ -384,23 +455,18 @@ impl Menu {
}
/// Starts the launcher again in a new console, a few seconds on, and ends this run.
fn restart(&mut self) {
use std::os::windows::process::CommandExt;
/// `preload`: the launcher makes every shader first (its `-Preload`, for that start alone).
fn restart(&mut self, preload: bool) {
let Some(play) = std::env::var_os("VICTORY_MENU_PLAY") else {
self.note = "SAVED. START THE LAUNCHER AGAIN YOURSELF".to_owned();
return;
};
let play = play.to_string_lossy().replace('\'', "''");
let args = get("VICTORY_MENU_ARGS");
let command = format!("Start-Sleep 3; & '{play}' {args}");
const CREATE_NEW_CONSOLE: u32 = 0x10;
match std::process::Command::new("powershell.exe")
.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", &command])
.creation_flags(CREATE_NEW_CONSOLE)
.spawn()
{
Ok(_) => {
tracing::info!(command, "settings menu: restarting");
let command = format!("Start-Sleep 3; & '{play}' {args}{}", if preload { " -Preload" } else { "" });
match new_console(&format!("powershell.exe -NoProfile -ExecutionPolicy Bypass -Command \"{}\"", command.replace('"', "\\\""))) {
Ok(()) => {
tracing::info!(command, preload, "settings menu: restarting");
// Ended at once: std::process::exit runs the DLLs' unloading, which with
// Streamline loaded did not come back (a windowless leftover process).
// SAFETY: this process, with nothing of its own left to save.
@@ -443,6 +509,11 @@ impl Menu {
if !open {
continue;
}
// Only an Enter right after the first one starts a preload.
let confirmed = self.note == CONFIRM_PRELOAD;
if confirmed {
self.note.clear();
}
match vk {
VK_UP => self.at = (self.at + total - 1) % total,
VK_DOWN => self.at = (self.at + 1) % total,
@@ -452,13 +523,19 @@ impl Menu {
VK_RETURN => match self.at - ITEMS.len() {
0 => {
if self.save() {
self.restart();
self.restart(false);
}
}
1 => {
self.save();
}
2 => self.reset(),
PRELOAD if !confirmed => self.note = CONFIRM_PRELOAD.to_owned(),
PRELOAD => {
if self.save() {
self.restart(true);
}
}
3 => self.reset(),
_ => crate::SETTINGS_MENU_OPEN.store(false, Ordering::Relaxed),
},
_ => {}
@@ -555,6 +632,32 @@ mod tests {
}
}
#[test]
fn the_link_is_always_right_under_the_note() {
let mut menu = Menu { values: ITEMS.iter().map(|_| String::new()).collect(), started: Vec::new(), at: 0, note: String::new(), changed: false, painted: None, buffers: None, failed: false };
menu.started = menu.values.clone();
for note in ["", "SAVED"] {
menu.note = note.to_owned();
for at in 0..ITEMS.len() + ACTIONS.len() {
menu.at = at;
let lines = menu.lines();
assert_eq!(lines.len(), LINES as usize);
let n = lines.len();
assert!(lines[n - 2].starts_with("* = CHANGED") || lines[n - 2] == note, "{}", lines[n - 2]);
assert_eq!(lines[n - 1], REPO);
// What a preload costs is said while it is picked, and only then.
let about = &lines[n - 5..n - 2];
if at == ITEMS.len() + PRELOAD {
assert_eq!(about, ABOUT_PRELOAD);
} else {
assert!(about.iter().all(String::is_empty), "{about:?}");
}
}
}
assert_eq!(ACTIONS[PRELOAD], "PRELOAD SHADERS (RESTARTS THE GAME)");
assert!(CONFIRM_PRELOAD.len() <= COLUMNS as usize);
}
#[test]
fn values_cycle_both_ways() {
let mut menu = Menu { values: ITEMS.iter().map(|i| i.values[0].0.to_owned()).collect(), started: Vec::new(), at: 0, note: String::new(), changed: false, painted: None, buffers: None, failed: false };
+125 -57
View File
@@ -62,9 +62,19 @@ fn pressed() -> bool {
process == std::process::id()
}
/// A box's characters in a line, and lines.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) struct Shape {
columns: u32,
lines: u32,
}
/// The numbers panel's box.
const PANEL: Shape = Shape { columns: COLUMNS, lines: LINES };
/// The box's size in pixels, a dot being `scale` of them each way.
const fn size(scale: u32) -> (u32, u32) {
((COLUMNS * CELL.0 + 2 * RIM) * scale, (LINES * CELL.1 + 2 * RIM) * scale)
const fn size(shape: Shape, scale: u32) -> (u32, u32) {
((shape.columns * CELL.0 + 2 * RIM) * scale, (shape.lines * CELL.1 + 2 * RIM) * scale)
}
/// Pixels to a dot for a picture that high: a 720-line screenshot of it
@@ -74,11 +84,11 @@ fn scale(height: u32) -> u32 {
}
/// Whether a dot of the picture of `lines` is white.
fn lit(lines: &[String], x: u32, y: u32) -> bool {
fn lit(lines: &[String], shape: Shape, x: u32, y: u32) -> bool {
let (Some(x), Some(y)) = (x.checked_sub(RIM), y.checked_sub(RIM)) else {
return false;
};
if x % CELL.0 >= GLYPH.0 || y % CELL.1 >= GLYPH.1 || x / CELL.0 >= COLUMNS {
if x % CELL.0 >= GLYPH.0 || y % CELL.1 >= GLYPH.1 || x / CELL.0 >= shape.columns {
return false;
}
let Some(&c) = lines.get((y / CELL.1) as usize).and_then(|l| l.as_bytes().get((x / CELL.0) as usize)) else {
@@ -88,14 +98,14 @@ fn lit(lines: &[String], x: u32, y: u32) -> bool {
}
/// The box as rows of `pitch` bytes.
fn painted(lines: &[String], scale: u32, colours: [&[u8]; 2], pitch: usize) -> Vec<u8> {
let (width, height) = size(scale);
fn painted(lines: &[String], shape: Shape, scale: u32, colours: [&[u8]; 2], pitch: usize) -> Vec<u8> {
let (width, height) = size(shape, scale);
let bytes = colours[0].len();
let mut out = vec![0; pitch * height as usize];
for y in 0..height / scale {
let top = pitch * (y * scale) as usize;
for x in 0..width / scale {
let colour = colours[usize::from(lit(lines, x, y))];
let colour = colours[usize::from(lit(lines, shape, x, y))];
for i in 0..scale {
let at = top + (x * scale + i) as usize * bytes;
out[at..at + bytes].copy_from_slice(colour);
@@ -199,6 +209,7 @@ fn text(c: &[f64; COUNTERS], ms: f64, worst: f64, cost: f64, host: &Host) -> Vec
/// The buffers of a box that size and format.
struct Buffers {
shape: Shape,
format: DXGI_FORMAT,
scale: u32,
pitch: u32,
@@ -214,8 +225,8 @@ struct Buffers {
unsafe impl Send for Buffers {}
impl Buffers {
fn new(host: &Host, format: DXGI_FORMAT, scale: u32) -> Option<Buffers> {
let (width, height) = size(scale);
fn new(host: &Host, shape: Shape, format: DXGI_FORMAT, scale: u32) -> Option<Buffers> {
let (width, height) = size(shape, scale);
let pitch = (width * colours(format)?[0].len() as u32).next_multiple_of(256);
let bytes = u64::from(pitch) * u64::from(height);
let uploads = (0..UPLOADS).map(|_| host.upload_buffer(bytes)).collect::<Option<Vec<_>>>()?;
@@ -240,17 +251,56 @@ impl Buffers {
.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut card)
.ok()?;
}
Some(Buffers { format, scale, pitch, uploads, card: card?, turn: 0, fresh: false })
Some(Buffers { shape, format, scale, pitch, uploads, card: card?, turn: 0, fresh: false })
}
fn write(&mut self, lines: &[String]) {
let Some(colours) = colours(self.format) else { return };
let picture = painted(lines, self.scale, colours, self.pitch as usize);
let picture = painted(lines, self.shape, self.scale, colours, self.pitch as usize);
self.turn = (self.turn + 1) % UPLOADS;
// SAFETY: a mapped upload buffer of the picture's size, which the card read a second or more ago.
unsafe { std::ptr::copy_nonoverlapping(picture.as_ptr(), self.uploads[self.turn].1, picture.len()) };
self.fresh = true;
}
/// Records the copy of the box onto `back` (of `width` x `height`, in the
/// state to be copied into), its upper left corner at `at`.
fn copy(&mut self, list: &ID3D12GraphicsCommandList, back: &ID3D12Resource, at: (u32, u32), (width, height): (u32, u32)) {
let (w, h) = size(self.shape, self.scale);
if at.0 >= width || at.1 >= height {
return;
}
// SAFETY: an open list and live resources; the box lies within both.
unsafe {
if std::mem::take(&mut self.fresh) {
list.CopyResource(&self.card, &self.uploads[self.turn].0);
list.ResourceBarrier(&[transition(&self.card, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
}
let from = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(&self.card),
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
Offset: 0,
Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
Format: self.format,
Width: w,
Height: h,
Depth: 1,
RowPitch: self.pitch,
},
},
},
};
let to = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(back),
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
};
let part = D3D12_BOX { left: 0, top: 0, front: 0, right: w.min(width - at.0), bottom: h.min(height - at.1), back: 1 };
list.CopyTextureRegion(&to, at.0, at.1, 0, &from, Some(&part));
}
}
}
/// The panel of a presenter.
@@ -341,7 +391,7 @@ impl Panel {
if self.buffers.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) {
// (What the card may still read stays: a picture's size changes once or twice in a run.)
std::mem::forget(self.buffers.take());
self.buffers = Buffers::new(host, format, scale);
self.buffers = Buffers::new(host, PANEL, format, scale);
self.failed = self.buffers.is_none();
self.changed = true;
}
@@ -349,53 +399,71 @@ impl Panel {
if std::mem::take(&mut self.changed) {
buffers.write(&self.lines);
}
let (w, h) = size(scale);
let list = &list.list;
// SAFETY: an open list and live resources; the box lies within both.
unsafe {
if std::mem::take(&mut buffers.fresh) {
list.CopyResource(&buffers.card, &buffers.uploads[buffers.turn].0);
list.ResourceBarrier(&[transition(
&buffers.card,
D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_COPY_SOURCE,
)]);
}
let from = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(&buffers.card),
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
Offset: 0,
Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
Format: format,
Width: w,
Height: h,
Depth: 1,
RowPitch: buffers.pitch,
},
},
},
};
let to = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(back),
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
};
let part = D3D12_BOX {
left: 0,
top: 0,
front: 0,
right: w.min(width),
bottom: h.min(height),
back: 1,
};
list.CopyTextureRegion(&to, 0, 0, 0, &from, Some(&part));
}
buffers.copy(&list.list, back, (0, 0), (width, height));
self.cost += began.elapsed();
}
}
/// How long the start's notice stays.
const NOTICE_FOR: Duration = Duration::from_secs(30);
/// The longest notice line, in characters.
const NOTICE_COLUMNS: u32 = 52;
/// What this card does for frame generation, said at the top of the picture
/// for the first [`NOTICE_FOR`] of a run (`crate::streamline::notice`); in
/// every build, nothing without a notice.
pub(super) struct Notice {
lines: Vec<String>,
shape: Shape,
since: Option<Instant>,
buffers: Option<Buffers>,
written: bool,
done: bool,
}
impl Notice {
pub(super) fn new() -> Notice {
let lines: Vec<String> = crate::streamline::notice().into_iter().map(|l| l.to_ascii_uppercase()).collect();
let columns = lines.iter().map(|l| l.len() as u32).max().unwrap_or(0).min(NOTICE_COLUMNS);
let shape = Shape { columns, lines: lines.len() as u32 };
Notice { done: lines.is_empty(), lines, shape, since: None, buffers: None, written: false }
}
/// Records the copy of the notice onto `back` (as [`Panel::draw`]), at
/// the top in the middle, while it is due.
pub(super) fn draw(&mut self, host: &Host, list: &HostList, back: &ID3D12Resource, (width, height): (u32, u32), format: DXGI_FORMAT) {
if self.done {
return;
}
let since = *self.since.get_or_insert_with(Instant::now);
if since.elapsed() > NOTICE_FOR {
// (Its buffers stay: the card may still read them.)
std::mem::forget(self.buffers.take());
self.done = true;
return;
}
#[cfg(feature = "diagnostics")]
let _ours = crate::replay::record::unrecorded();
let scale = scale(height);
if self.buffers.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) {
std::mem::forget(self.buffers.take());
self.buffers = Buffers::new(host, self.shape, format, scale);
self.written = false;
if self.buffers.is_none() {
self.done = true;
return;
}
}
let Some(buffers) = &mut self.buffers else { return };
if !std::mem::replace(&mut self.written, true) {
buffers.write(&self.lines);
}
let (w, _) = size(self.shape, scale);
let at = (width.saturating_sub(w) / 2, 24 * scale);
buffers.copy(&list.list, back, at, (width, height));
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -426,10 +494,10 @@ mod tests {
fn a_box_is_painted() {
let lines = vec!["I".to_owned(), " i".to_owned()];
for scale in [1, 2, 4] {
let (width, height) = size(scale);
let (width, height) = size(PANEL, scale);
let pitch = (width * 4).next_multiple_of(256) as usize;
let colours = colours(DXGI_FORMAT_R10G10B10A2_UNORM).unwrap();
let picture = painted(&lines, scale, colours, pitch);
let picture = painted(&lines, PANEL, scale, colours, pitch);
assert_eq!(picture.len(), pitch * height as usize);
let at = |x: u32, y: u32| &picture[y as usize * pitch + x as usize * 4..][..4];
// The rim is black, the first letter's top row lit in its middle.
+13
View File
@@ -214,6 +214,19 @@ pub fn use_translations(dir: PathBuf) {
crate::shader_cache::use_shader_cache(dir);
}
/// The translations and the host pipeline library of a run are in the cache
/// folder `shaders`'s neighbours: what [`make`] makes from now on is stored in
/// that library (`victory preload`), which the runs load at their start.
pub fn use_library(shaders: PathBuf) {
super::library::use_pipeline_cache(shaders.with_file_name("pipelines"));
crate::shader_cache::use_shader_cache(shaders);
}
/// Writes the library [`use_library`] filled.
pub fn keep_library() {
super::library::save(true);
}
/// Makes the host pipelines of those of `which` (numbers in the file) and
/// lets each go again: the driver's cache on disk keeps them. `each` is told
/// the number before, and what came of it after: milliseconds and whether
+230 -26
View File
@@ -79,6 +79,16 @@ pub struct Asked {
/// our swap chain is Streamline's proxy of it, so that Streamline sees
/// the presents (its bookkeeping per frame).
pub present_hook: bool,
/// `VICTORY_FSR_FRAMEGEN=1`: AMD FSR 3 frame generation where DLSS Frame
/// Generation does not run ([`fsr`]), from `fidelityfx_dir`
/// (`VICTORY_FIDELITYFX_DIR`).
pub fsr_framegen: bool,
pub fidelityfx_dir: PathBuf,
/// The Series S profile (the caller sets it; from the environment,
/// `VICTORY_MENU_CONSOLE=series-s`). Without DLSS the title's own
/// FidelityFX upscales, made for the Series S sizes only: FSR 3 frame
/// generation, which needs that upscaling, runs on Series X with DLSS only.
pub series_s: bool,
}
impl Asked {
@@ -87,12 +97,13 @@ impl Asked {
let var = |name: &str| std::env::var(name).ok();
let on = |name: &str| var(name).is_some_and(|v| v.trim() == "1");
let framegen = on("VICTORY_FRAMEGEN");
let fsr_framegen = fsr::asked_from_env();
let mode = match var("VICTORY_DLSS_MODE") {
Some(name) => Mode::from_name(&name).ok_or_else(|| {
format!("VICTORY_DLSS_MODE={name}: not one of dlaa, quality, balanced, performance, ultraperformance")
})?,
// Frame generation alone keeps the scene at the output's size.
None if framegen && !on("VICTORY_DLSS") => Mode::Dlaa,
None if (framegen || fsr_framegen) && !on("VICTORY_DLSS") => Mode::Dlaa,
None => Mode::Quality,
};
let preset = match var("VICTORY_DLSS_PRESET") {
@@ -112,6 +123,9 @@ impl Asked {
log_dir: var("VICTORY_STREAMLINE_LOG").filter(|v| !v.trim().is_empty() && v.trim() != "0").map(PathBuf::from),
hudless: var("VICTORY_FRAMEGEN_HUDLESS").is_none_or(|v| v.trim() != "0"),
present_hook: on("VICTORY_STREAMLINE_PRESENT"),
fsr_framegen,
fidelityfx_dir: fsr::dir_from_env(),
series_s: var("VICTORY_MENU_CONSOLE").is_some_and(|c| c.trim() == "series-s"),
})
}
@@ -126,6 +140,9 @@ impl Asked {
pub struct Available {
pub dlss: bool,
pub framegen: bool,
/// AMD's DLLs for FSR 3 frame generation are in (it runs if DLSS Frame
/// Generation does not).
pub fsr_framegen: bool,
}
/// One upscaling the title asked for: a FidelityFX `ffxDispatch` of an
@@ -174,6 +191,8 @@ macro_rules! once {
}};
}
pub(crate) mod fsr;
struct Library(windows_sys::Win32::Foundation::HMODULE);
impl Drop for Library {
@@ -302,19 +321,156 @@ static CHECKING: AtomicBool = AtomicBool::new(false);
/// title's imports are bound. Fails soft: what is not there is logged and
/// left off.
pub fn init(asked: &Asked) -> Available {
if !asked.any() {
return Available::default();
}
match load_and_init(asked, true) {
Ok(available) => available,
Err(why) => {
tracing::warn!(
folder = %asked.dir.display(),
"Streamline: {why}; DLSS and frame generation stay off, the title's own upscaling and our present run"
);
Available::default()
let mut files_missing = false;
let available = if !asked.any() {
Available::default()
} else {
match load_and_init(asked, true) {
Ok(available) => available,
Err(why) => {
tracing::warn!(
folder = %asked.dir.display(),
"Streamline: {why}; DLSS and frame generation stay off, the title's own upscaling and our present run"
);
files_missing = true;
Available::default()
}
}
};
let no_dlss = if available.dlss {
None
} else if !asked.dlss {
Some(NoDlss::TurnedOff)
} else if files_missing {
Some(NoDlss::FilesMissing)
} else {
Some(NoDlss::Card)
};
// FSR 3 frame generation needs the title's upscaling to run: on Series X that is DLSS's
// (the title's own FidelityFX takes the Series S sizes only, and the title fails without it).
let fsr_needs_series_s = asked.fsr_framegen && !asked.series_s && !available.dlss;
if fsr_needs_series_s {
tracing::warn!(
"FSR 3 frame generation stays off: on Series X it needs DLSS for the upscaling, which this card or these files do not give; the Series S profile runs it"
);
}
let fsr_framegen = asked.fsr_framegen && !fsr_needs_series_s && fsr::init(&asked.fidelityfx_dir);
let _ = FACTS.set(Facts {
adapter: default_adapter().map(|a| a.0).unwrap_or_default(),
series_s: asked.series_s,
no_dlss,
files_missing,
dlss_fg_asked: asked.framegen,
dlss_fg_supported: available.framegen,
fsr_asked: asked.fsr_framegen,
fsr_loaded: fsr_framegen,
fsr_needs_series_s,
});
Available { fsr_framegen, ..available }
}
/// What the start found out about frame generation on this card ([`notice`]).
struct Facts {
adapter: String,
series_s: bool,
/// Why DLSS upscaling is not running (`None`: it runs).
no_dlss: Option<NoDlss>,
/// Streamline's files did not load (nothing is known of the card).
files_missing: bool,
dlss_fg_asked: bool,
dlss_fg_supported: bool,
fsr_asked: bool,
fsr_loaded: bool,
fsr_needs_series_s: bool,
}
/// Why DLSS upscaling is not running: the notice must not blame a card that
/// has DLSS when it was only turned off or its files were not found.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum NoDlss {
/// Not asked (F1 > DLSS > OFF, or VICTORY_DLSS unset).
TurnedOff,
/// Asked, but Streamline's files did not load.
FilesMissing,
/// Asked and loaded, and the card does not support it.
Card,
}
static FACTS: OnceLock<Facts> = OnceLock::new();
/// What this card does for frame generation, in a few lines of at most 52
/// characters: printed at the start and shown on the picture for its first
/// seconds. Nothing if no frame generation was asked or made ready.
pub fn notice() -> Vec<String> {
let Some(f) = FACTS.get() else { return Vec::new() };
notice_of(f, FG_READY.load(Acquire) && SWAP_CHAIN_PROXIED.load(Acquire), fsr::live_swap_chain())
}
/// [`notice`] as it is expected at the start, before the swap chain is made
/// (DLSS Frame Generation where it is supported, else FSR 3 if loaded).
pub fn notice_at_start() -> Vec<String> {
let Some(f) = FACTS.get() else { return Vec::new() };
notice_of(f, f.dlss_fg_supported, f.fsr_loaded && !f.dlss_fg_supported)
}
fn notice_of(f: &Facts, dlss_live: bool, fsr_live: bool) -> Vec<String> {
if !f.dlss_fg_asked && !f.fsr_asked {
return Vec::new();
}
let mut lines = Vec::new();
if !f.adapter.is_empty() {
// (Only what the picture's font draws: "Intel(R) Arc(TM)" and the like keep their letters.)
let name: String = f.adapter.trim().chars().filter(|c| c.is_ascii_alphanumeric() || " .,:()/-+".contains(*c)).collect();
let mut gpu = format!("GPU: {}", name.to_ascii_uppercase());
gpu.truncate(52);
lines.push(gpu);
}
// A card DLSS Frame Generation was asked of and did not run on.
let no_dlss_fg = f.dlss_fg_asked && !f.dlss_fg_supported;
if no_dlss_fg {
lines.push(if f.files_missing {
"DLSS FRAME GEN: NVIDIA DLSS FILES NOT FOUND"
} else {
"DLSS FRAME GEN: NOT ON THIS CARD (RTX 40 AND UP)"
}.into());
}
if dlss_live {
lines.push("FRAME GEN: DLSS, SUPPORTED HERE (F1 MENU: 2X-6X)".into());
lines.push("MORE THAN 2X NEEDS AN RTX 50 CARD".into());
} else if fsr_live {
lines.push(if no_dlss_fg {
"USING AMD FSR 3 FRAME GEN INSTEAD: 2X AT MOST".into()
} else {
"FRAME GEN: AMD FSR 3 (CHOSEN IN F1), 2X AT MOST".into()
});
if !f.series_s {
lines.push("SERIES X WITH FSR 3 NEEDS DLSS UPSCALING (ON)".into());
} else if f.no_dlss.is_some() {
lines.push("SERIES S MODE: FSR 3 RUNS WITHOUT DLSS".into());
}
} else if f.fsr_needs_series_s {
lines.push("FRAME GEN OFF: FSR 3 ON SERIES X NEEDS DLSS ON".into());
lines.push(match f.no_dlss {
Some(NoDlss::FilesMissing) => "NVIDIA DLSS FILES NOT FOUND (VICTORY_STREAMLINE_DIR)",
Some(NoDlss::Card) => "THIS CARD HAS NO DLSS UPSCALING",
_ => "DLSS UPSCALING IS OFF: TURN IT ON IN F1 > DLSS",
}.into());
lines.push(if f.no_dlss == Some(NoDlss::Card) {
"USE F1 > CONSOLE > SERIES S (THE GAME RESTARTS)"
} else {
"OR F1 > CONSOLE > SERIES S (THE GAME RESTARTS)"
}.into());
} else if f.fsr_asked && !f.fsr_loaded {
lines.push("FRAME GEN OFF: AMD FSR 3 FILES NOT FOUND".into());
lines.push("(AMD FIDELITYFX DLLS, VICTORY_FIDELITYFX_DIR)".into());
} else if no_dlss_fg {
lines.push("F1 > FRAME GEN TYPE > FSR 3 GIVES 2X ON THIS CARD".into());
} else if f.dlss_fg_supported {
lines.push("FRAME GEN: DLSS DID NOT START (SEE THE LOG)".into());
} else {
return Vec::new();
}
lines
}
fn load_and_init(asked: &Asked, require_line: bool) -> Result<Available, String> {
@@ -401,7 +557,7 @@ fn load_and_init(asked: &Asked, require_line: bool) -> Result<Available, String>
"Streamline loaded (manual hooking, no downloads)"
);
let _ = PLAN.set(Plan { asked: asked.clone(), dlss, framegen });
Ok(Available { dlss, framegen })
Ok(Available { dlss, framegen, fsr_framegen: false })
}
/// Logs whether a feature is supported, with its requirements; whether it is.
@@ -561,7 +717,7 @@ fn load(path: &Path) -> Result<Sl, String> {
/// Whether the title's FidelityFX calls are to be served (DLSS or frame
/// generation is on): `victory_hle` then puts its own in front of them.
pub fn serving() -> bool {
PLAN.get().is_some_and(|p| p.dlss || p.framegen)
PLAN.get().is_some_and(|p| p.dlss || p.framegen) || fsr::noting()
}
/// Whether DLSS is to take the title's upscale dispatches (`VICTORY_DLSS=1`
@@ -782,13 +938,16 @@ fn frame_token(sl: &Sl, index: u32) -> Option<*mut abi::FrameToken> {
/// its inputs are noted there for the present); the title's own runs
/// otherwise.
pub fn upscale(up: &Upscale) -> Taken {
let Some(plan) = PLAN.get() else {
return Taken::No("Streamline is not loaded");
};
let dlss = plan.dlss && DLSS_READY.load(Acquire);
let framegen = plan.framegen && FG_READY.load(Acquire);
let plan = PLAN.get();
let dlss = plan.is_some_and(|p| p.dlss) && DLSS_READY.load(Acquire);
// (FSR 3 frame generation reads the same inputs at the present.)
let framegen = plan.is_some_and(|p| p.framegen) && FG_READY.load(Acquire) || fsr::noting();
if !dlss && !framegen {
return Taken::No("Streamline has no device yet, or its features did not start");
return Taken::No(if plan.is_none() {
"Streamline is not loaded"
} else {
"Streamline has no device yet, or its features did not start"
});
}
if [COLOUR, DEPTH, MOTION, OUTPUT].iter().any(|&i| up.resources[i].0.is_null()) {
return Taken::No("a required texture (colour, depth, motion vectors, output) is missing");
@@ -857,7 +1016,7 @@ fn note(host: &crate::host::HostList, up: &Upscale, id: u64) {
};
let mut pending = pending();
pending.retain(|n| id.saturating_sub(n.id) < 16);
pending.push(Noted { id, depth: Source::Host(depth), motion: Source::Host(motion), camera: up.camera });
pending.push(Noted { id, depth: Source::Host(depth), motion: Source::Host(motion), camera: up.camera, frame_ms: up.frame_ms });
drop(pending);
host.mark_upscale(id);
}
@@ -868,6 +1027,34 @@ struct Noted {
depth: Source,
motion: Source,
camera: plan::Camera,
frame_ms: f32,
}
/// What FSR 3 frame generation reads at a present ([`fresh_inputs`]): depth
/// and motion vectors with the D3D12 states they are in then.
pub(crate) struct Inputs {
pub(crate) depth: (ID3D12Resource, u32),
pub(crate) motion: (ID3D12Resource, u32),
pub(crate) camera: plan::Camera,
pub(crate) frame_ms: f32,
}
impl Source {
fn current(&self) -> (ID3D12Resource, u32) {
match self {
Source::Host(t) => (t.texture.clone(), t.state.load(Relaxed)),
Source::Fixed(t, state) => (t.clone(), *state),
}
}
}
/// The latest upscaling submitted since the last present that took one, if
/// any (and from now on the last taken).
pub(crate) fn fresh_inputs() -> Option<Inputs> {
let latest = SUBMITTED.lock().unwrap_or_else(|e| e.into_inner());
let n = latest.as_ref().filter(|n| n.id > PRESENTED_ID.load(Relaxed))?;
PRESENTED_ID.store(n.id, Relaxed);
Some(Inputs { depth: n.depth.current(), motion: n.motion.current(), camera: n.camera, frame_ms: n.frame_ms })
}
/// A texture frame generation reads at the present, and the state it is in
@@ -1605,19 +1792,30 @@ fn framegen_wanted() -> u32 {
/// Whether frame generation can be switched and changed while the title runs: it was planned
/// at the start, so our swap chain is Streamline's proxy (the F1 menu asks).
pub(crate) fn framegen_live() -> bool {
FG_READY.load(Acquire) && SWAP_CHAIN_PROXIED.load(Acquire)
FG_READY.load(Acquire) && SWAP_CHAIN_PROXIED.load(Acquire) || fsr::live_swap_chain()
}
/// Asks frame generation off (0) or for `times` frames shown for each one rendered (2..6),
/// from the next present on.
/// Which frame generation the presents have: DLSS's, AMD's FSR 3, or none.
pub(crate) fn framegen_kind() -> Option<&'static str> {
if FG_READY.load(Acquire) && SWAP_CHAIN_PROXIED.load(Acquire) {
Some("DLSS")
} else if fsr::live_swap_chain() {
Some("FSR 3")
} else {
None
}
}
/// Asks frame generation off (0) or for `times` frames shown for each one rendered (2..6;
/// FSR 3 frame generation shows 2 for any of them), from the next present on.
pub(crate) fn set_framegen(times: u32) {
FG_WANTED.store(if times == 0 { 0 } else { times.clamp(2, 6) }, Relaxed);
tracing::info!(times, "DLSS Frame Generation: asked from the settings menu");
tracing::info!(times, kind = framegen_kind().unwrap_or("none"), "frame generation: asked from the settings menu");
}
/// For the frame-rate texts: frames shown for each one rendered (1 without frame generation).
pub(crate) fn shown_per_frame() -> u32 {
FG_PER.load(Relaxed).max(1)
fsr::shown_per_frame().unwrap_or_else(|| FG_PER.load(Relaxed).max(1))
}
/// After our swap chain's Present: the frame's last marker, the next
@@ -1869,6 +2067,7 @@ fn check_run(output: [u32; 2], device: bool, present: bool) -> Vec<String> {
depth: Source::Fixed(depth.clone(), SHADER_READ),
motion: Source::Fixed(motion.clone(), SHADER_READ),
camera,
frame_ms: 16.7,
});
if let Some(copy) = &copy {
lock(&HUD_SUBMITTED).push(Copied { id: frame, target: base.as_raw() as usize, texture: copy.clone() });
@@ -1930,6 +2129,11 @@ fn texture(
/// For the frame-rate line.
pub(crate) fn line(frames: f64) {
if let Some((on, off, failed, hudless)) = fsr::line_counts() {
tracing::info!(
"FSR 3 frame generation: {on} presents with it on ({hudless} with the colour without the interface), {off} off, {failed} prepare dispatches failed"
);
}
let Some(plan) = PLAN.get() else { return };
let [done, failed, forwarded, on, off, shown] =
[&EVALUATED, &FAILED, &FORWARDED, &FG_ON, &FG_OFF, &FG_SHOWN].map(|c| c.swap(0, Relaxed));
+944
View File
@@ -0,0 +1,944 @@
//! AMD FSR 3 frame generation (the FidelityFX API's frame generation and its
//! frame interpolation swap chain), for cards DLSS Frame Generation does not
//! run on. Off by default; loaded at run time from a folder of the user's.
//!
//! - `VICTORY_FSR_FRAMEGEN=1`: our swap chain is FidelityFX's frame
//! interpolation swap chain, and every present is told the depth and motion
//! vectors of the last upscaling submitted before it (the same inputs DLSS
//! Frame Generation is given), so that one frame is generated between each
//! two the title renders. With `VICTORY_FRAMEGEN=1` as well, DLSS Frame
//! Generation is used where it runs, this where it does not; never both.
//! - `VICTORY_FIDELITYFX_DIR`: the folder of `amd_fidelityfx_loader_dx12.dll`
//! and `amd_fidelityfx_framegeneration_dx12.dll` (AMD's signed DLLs of the
//! FidelityFX SDK's `bin`; default: a `fidelityfx` folder beside our exe).
//!
//! Anything missing (the folder, a signature, the swap chain) leaves our plain
//! present as it was, with a warning in the log. Like DLSS Frame Generation,
//! it needs the line of submissions (`VICTORY_THIN=1` or
//! `VICTORY_ASYNC_SUBMIT=1`), and the title's upscaling has to run (its own
//! FidelityFX at the Series S sizes, or DLSS).
use std::ffi::{CStr, c_void};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::*};
use std::sync::{Mutex, OnceLock};
use windows::Win32::Foundation::HWND;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows::Win32::Graphics::Dxgi::*;
use windows::core::Interface;
use super::{Library, plan};
const LOADER: &str = "amd_fidelityfx_loader_dx12.dll";
const FRAMEGEN: &str = "amd_fidelityfx_framegeneration_dx12.dll";
// Structure types (ffx_api.h, ffx_framegeneration.h, ffx_api_dx12.h,
// ffx_api_framegeneration_dx12.h of FidelityFX SDK 2.x).
const CREATE_BACKEND_DX12: u64 = 0x0000_0002;
const CREATE_FRAMEGENERATION: u64 = 0x0002_0001;
const CONFIGURE_FRAMEGENERATION: u64 = 0x0002_0002;
const DISPATCH_PREPARE_V2: u64 = 0x0002_000c;
const CREATE_FRAMEGENERATION_VERSION: u64 = 0x0002_000e;
/// `ffxCreateContextDescFrameGenerationHudless` (a header and one format, laid
/// out as [`Version`]).
const CREATE_FRAMEGENERATION_HUDLESS: u64 = 0x0002_0009;
const CREATE_SWAPCHAIN_FOR_HWND_DX12: u64 = 0x0003_0006;
const CREATE_SWAPCHAIN_VERSION_DX12: u64 = 0x0003_000b;
const DISPATCH_WAIT_FOR_PRESENTS_DX12: u64 = 0x0003_0007;
/// The versions our structures are those of.
const FRAMEGENERATION_VERSION: u32 = (4 << 22) | 2;
const SWAPCHAIN_VERSION: u32 = 4 << 22;
// Frame generation context creation flags.
const FG_DISPLAY_RESOLUTION_MV: u32 = 1 << 1;
const FG_MV_JITTER_CANCELLATION: u32 = 1 << 2;
const FG_DEPTH_INVERTED: u32 = 1 << 3;
const FG_DEPTH_INFINITE: u32 = 1 << 4;
const FG_HIGH_DYNAMIC_RANGE: u32 = 1 << 5;
/// Dispatch flag: draws the tear and pacing lines (`VICTORY_FSR_FRAMEGEN_DEBUG=1`).
const FG_DRAW_DEBUG_TEAR_LINES: u32 = 1 << 0;
const FG_DRAW_DEBUG_PACING_LINES: u32 = 1 << 4;
// Resource states and types.
const STATE_COMMON: u32 = 1 << 0;
const STATE_UNORDERED_ACCESS: u32 = 1 << 1;
const STATE_COMPUTE_READ: u32 = 1 << 2;
const STATE_PIXEL_READ: u32 = 1 << 3;
const STATE_COPY_SRC: u32 = 1 << 4;
const STATE_COPY_DEST: u32 = 1 << 5;
const STATE_RENDER_TARGET: u32 = 1 << 8;
const STATE_DEPTH_ATTACHMENT: u32 = 1 << 9;
const TYPE_TEXTURE2D: u32 = 2;
const USAGE_UAV: u32 = 1 << 1;
const USAGE_DEPTHTARGET: u32 = 1 << 2;
const USAGE_STENCILTARGET: u32 = 1 << 5;
const OK: u32 = 0;
#[repr(C)]
struct Header {
kind: u64,
next: *mut Header,
}
impl Header {
fn new(kind: u64) -> Self {
Header { kind, next: std::ptr::null_mut() }
}
}
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct Dims {
width: u32,
height: u32,
}
impl From<[u32; 2]> for Dims {
fn from([width, height]: [u32; 2]) -> Self {
Dims { width, height }
}
}
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct Floats {
x: f32,
y: f32,
}
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct Rect {
left: i32,
top: i32,
width: i32,
height: i32,
}
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct ResourceDescription {
kind: u32,
format: u32,
width: u32,
height: u32,
depth: u32,
mip_count: u32,
flags: u32,
usage: u32,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct Resource {
resource: *mut c_void,
description: ResourceDescription,
state: u32,
}
impl Resource {
const NONE: Resource =
Resource { resource: std::ptr::null_mut(), description: ResourceDescription { kind: 0, format: 0, width: 0, height: 0, depth: 0, mip_count: 0, flags: 0, usage: 0 }, state: STATE_COMMON };
/// `ffxApiGetResourceDX12` of a 2D texture in D3D12 state `state`.
fn texture(texture: &ID3D12Resource, state: u32) -> Resource {
// SAFETY: a live resource.
let desc = unsafe { texture.GetDesc() };
let usage = match desc.Format {
DXGI_FORMAT_D16_UNORM | DXGI_FORMAT_D32_FLOAT => USAGE_DEPTHTARGET,
DXGI_FORMAT_D24_UNORM_S8_UINT | DXGI_FORMAT_D32_FLOAT_S8X24_UINT => USAGE_DEPTHTARGET | USAGE_STENCILTARGET,
_ => 0,
} | if desc.Flags.contains(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) { USAGE_UAV } else { 0 };
Resource {
resource: texture.as_raw(),
description: ResourceDescription {
kind: TYPE_TEXTURE2D,
format: surface_format(desc.Format),
width: desc.Width as u32,
height: desc.Height,
depth: u32::from(desc.DepthOrArraySize),
mip_count: u32::from(desc.MipLevels),
flags: 0,
usage,
},
state: ffx_state(state),
}
}
}
#[repr(C)]
struct CreateSwapChainForHwnd {
header: Header,
swap_chain: *mut *mut c_void,
hwnd: HWND,
desc: *const DXGI_SWAP_CHAIN_DESC1,
fullscreen: *const c_void,
factory: *mut c_void,
queue: *mut c_void,
}
#[repr(C)]
struct Version {
header: Header,
version: u32,
}
#[repr(C)]
struct CreateFrameGeneration {
header: Header,
flags: u32,
display_size: Dims,
max_render_size: Dims,
back_buffer_format: u32,
}
#[repr(C)]
struct CreateBackend {
header: Header,
device: *mut c_void,
}
type FrameGenerationCallback = unsafe extern "C" fn(params: *mut Header, user: *mut c_void) -> u32;
#[repr(C)]
struct ConfigureFrameGeneration {
header: Header,
swap_chain: *mut c_void,
present_callback: *const c_void,
present_callback_user: *mut c_void,
frame_generation_callback: Option<FrameGenerationCallback>,
frame_generation_callback_user: *mut c_void,
frame_generation_enabled: bool,
allow_async_workloads: bool,
hudless_color: Resource,
flags: u32,
only_present_generated: bool,
generation_rect: Rect,
frame_id: u64,
}
#[repr(C)]
struct PrepareV2 {
header: Header,
frame_id: u64,
flags: u32,
command_list: *mut c_void,
render_size: Dims,
jitter_offset: Floats,
motion_vector_scale: Floats,
frame_time_delta: f32,
reset: bool,
camera_near: f32,
camera_far: f32,
camera_fov_angle_vertical: f32,
view_space_to_meters_factor: f32,
depth: Resource,
motion_vectors: Resource,
camera_position: [f32; 3],
camera_up: [f32; 3],
camera_right: [f32; 3],
camera_forward: [f32; 3],
}
type Context = *mut c_void;
type Create = unsafe extern "C" fn(context: *mut Context, desc: *mut Header, memory: *const c_void) -> u32;
type Destroy = unsafe extern "C" fn(context: *mut Context, memory: *const c_void) -> u32;
type Configure = unsafe extern "C" fn(context: *mut Context, desc: *const Header) -> u32;
type Dispatch = unsafe extern "C" fn(context: *mut Context, desc: *const Header) -> u32;
/// The loader's exports.
struct Ffx {
_framegen: Library,
_loader: Library,
create: Create,
destroy: Destroy,
configure: Configure,
dispatch: Dispatch,
}
static FFX: OnceLock<Ffx> = OnceLock::new();
/// Our swap chain is FidelityFX's frame interpolation swap chain.
static SWAP_CHAIN: AtomicBool = AtomicBool::new(false);
/// Frame generation ran on the last present.
static ON: AtomicBool = AtomicBool::new(false);
// Since the last frame-rate line: presents with frame generation on, off,
// and prepare dispatches that failed.
static PRESENTS_ON: AtomicU64 = AtomicU64::new(0);
static PRESENTS_OFF: AtomicU64 = AtomicU64::new(0);
static FAILED: AtomicU64 = AtomicU64::new(0);
/// Presents with frame generation on given the colour without the interface.
static HUDLESS_GIVEN: AtomicU64 = AtomicU64::new(0);
/// What is kept from present to present: the contexts (boxed, for their
/// addresses are handed out: the frame generation one to the swap chain's
/// callback), the sizes the frame generation context was made for, and the
/// frame ids.
struct Live {
swap_chain_context: Box<Context>,
/// The swap chain (not a reference of ours: the presenter holds it).
swap_chain: *mut c_void,
/// The context and what it was made for: display and largest render size,
/// back buffer format, flags, and the format of the colour without the
/// interface (unknown: none was known).
framegen: Option<(Box<Context>, [u32; 2], [u32; 2], DXGI_FORMAT, u32, DXGI_FORMAT)>,
frame_id: u64,
/// The frame generation context could not be made for these sizes.
refused: Option<([u32; 2], [u32; 2])>,
}
// SAFETY: FidelityFX contexts, used under the lock by one thread at a time.
unsafe impl Send for Live {}
static LIVE: Mutex<Option<Live>> = Mutex::new(None);
fn live() -> std::sync::MutexGuard<'static, Option<Live>> {
LIVE.lock().unwrap_or_else(|e| e.into_inner())
}
/// `VICTORY_FSR_FRAMEGEN=1`.
pub(crate) fn asked_from_env() -> bool {
std::env::var("VICTORY_FSR_FRAMEGEN").is_ok_and(|v| v.trim() == "1")
}
/// `VICTORY_FIDELITYFX_DIR`, or a `fidelityfx` folder beside our exe.
pub(crate) fn dir_from_env() -> PathBuf {
match std::env::var_os("VICTORY_FIDELITYFX_DIR").filter(|v| !v.is_empty()) {
Some(dir) => PathBuf::from(dir),
None => std::env::current_exe()
.ok()
.and_then(|exe| exe.parent().map(|d| d.join("fidelityfx")))
.unwrap_or_else(|| PathBuf::from("fidelityfx")),
}
}
/// Loads AMD's DLLs from `dir` (signatures checked first); whether they are in.
pub(crate) fn init(dir: &Path) -> bool {
match load(dir) {
Ok(ffx) => {
let _ = FFX.set(ffx);
tracing::info!(folder = %dir.display(), "FSR 3 frame generation: AMD's FidelityFX DLLs loaded (signatures valid)");
true
}
Err(why) => {
tracing::warn!(folder = %dir.display(), "FSR 3 frame generation: {why}; it stays off");
false
}
}
}
fn load(dir: &Path) -> Result<Ffx, String> {
use windows_sys::Win32::System::LibraryLoader::{
GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
};
let open = |name: &str| -> Result<Library, String> {
let path = dir.join(name);
if !path.is_file() {
return Err(format!("{} is missing", path.display()));
}
super::verify_signature(&path)?;
let file = super::wide(&path);
// Its own folder and System32 only, never the current folder.
// SAFETY: a NUL-terminated full path.
let module = unsafe {
LoadLibraryExW(file.as_ptr(), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32)
};
if module.is_null() {
return Err(format!("{name} did not load ({})", std::io::Error::last_os_error()));
}
Ok(Library(module))
};
// The effect first, by its full path: the loader then finds it in.
let framegen = open(FRAMEGEN)?;
let loader = open(LOADER)?;
let module = loader.0;
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!("{LOADER} has no {}", name.to_string_lossy()))
};
macro_rules! get {
($name:literal, $t:ty) => {
// SAFETY: the export of that name has the header's signature.
unsafe { std::mem::transmute::<*const c_void, $t>(find($name)?) }
};
}
Ok(Ffx {
create: get!(c"ffxCreateContext", Create),
destroy: get!(c"ffxDestroyContext", Destroy),
configure: get!(c"ffxConfigure", Configure),
dispatch: get!(c"ffxDispatch", Dispatch),
_loader: loader,
_framegen: framegen,
})
}
/// Whether the title's upscalings are to be noted for us: the DLLs are in and
/// DLSS Frame Generation does not have the presents.
pub(crate) fn noting() -> bool {
FFX.get().is_some() && !super::FG_READY.load(Acquire)
}
/// Whether the presents go through FidelityFX's swap chain (frame generation
/// can be switched while the title runs).
pub(crate) fn live_swap_chain() -> bool {
SWAP_CHAIN.load(Acquire)
}
/// Frames shown for each one rendered: 2 while frame generation runs.
pub(crate) fn shown_per_frame() -> Option<u32> {
(SWAP_CHAIN.load(Relaxed) && ON.load(Relaxed)).then_some(2)
}
/// Our swap chain, made by FidelityFX for `hwnd` on `queue` (the frame
/// interpolation swap chain); `None` to make it as before (FSR 3 frame
/// generation not asked or not loaded, DLSS Frame Generation has it, or it
/// failed: then logged).
pub(crate) fn swap_chain(
factory: &IDXGIFactory2,
queue: &ID3D12CommandQueue,
hwnd: HWND,
desc: &DXGI_SWAP_CHAIN_DESC1,
) -> Option<IDXGISwapChain3> {
let ffx = FFX.get()?;
if super::FG_READY.load(Acquire) {
tracing::info!("FSR 3 frame generation stays off: DLSS Frame Generation runs on this card");
return None;
}
let mut made: *mut c_void = std::ptr::null_mut();
let mut version = Version { header: Header::new(CREATE_SWAPCHAIN_VERSION_DX12), version: SWAPCHAIN_VERSION };
let mut create = CreateSwapChainForHwnd {
header: Header::new(CREATE_SWAPCHAIN_FOR_HWND_DX12),
swap_chain: &mut made,
hwnd,
desc,
fullscreen: std::ptr::null(),
factory: factory.as_raw(),
queue: queue.as_raw(),
};
create.header.next = (&raw mut version).cast();
let mut context: Box<Context> = Box::new(std::ptr::null_mut());
// SAFETY: filled descriptions that live through the call.
let code = unsafe { (ffx.create)(&mut *context, (&raw mut create).cast(), std::ptr::null()) };
if code != OK || made.is_null() {
tracing::warn!(code, "FSR 3 frame generation: FidelityFX did not make the swap chain; made as before, frame generation off");
return None;
}
// SAFETY: the swap chain FidelityFX made, with the reference it gave us.
let swap_chain = unsafe { IDXGISwapChain4::from_raw(made) };
let swap_chain = match swap_chain.cast::<IDXGISwapChain3>() {
Ok(s) => s,
Err(e) => {
tracing::warn!(error = %e, "FSR 3 frame generation: the swap chain has no IDXGISwapChain3");
return None;
}
};
*live() = Some(Live { swap_chain_context: context, swap_chain: swap_chain.as_raw(), framegen: None, frame_id: 0, refused: None });
SWAP_CHAIN.store(true, Release);
// The colour without the interface is copied in front of the title's interface composite, as for DLSS
// Frame Generation (`VICTORY_FRAMEGEN_HUDLESS=0`: not).
let hudless = std::env::var("VICTORY_FRAMEGEN_HUDLESS").map_or(true, |v| v.trim() != "0");
super::HUDLESS_WANTED.store(hudless, Release);
tracing::info!(
width = desc.Width,
height = desc.Height,
format = desc.Format.0,
"FSR 3 frame generation: our swap chain is FidelityFX's frame interpolation swap chain"
);
Some(swap_chain)
}
/// The swap chain's buffers are about to be made again (everything sent has
/// run): the frame generation context goes, and is made again for the new
/// size at the next present with an upscaling.
pub(crate) fn resizing() {
let Some(ffx) = FFX.get() else { return };
let mut live = live();
if let Some(live) = live.as_mut()
&& retire(ffx, live)
{
tracing::info!("FSR 3 frame generation: its context goes with the swap chain's buffers");
}
}
/// The frame generation context goes: the swap chain is told to stop calling
/// it and its presents in flight are waited for first. Whether there was one.
fn retire(ffx: &Ffx, live: &mut Live) -> bool {
let Some((mut context, ..)) = live.framegen.take() else { return false };
live.frame_id += 1;
let mut off = ConfigureFrameGeneration {
header: Header::new(CONFIGURE_FRAMEGENERATION),
swap_chain: live.swap_chain,
present_callback: std::ptr::null(),
present_callback_user: std::ptr::null_mut(),
frame_generation_callback: None,
frame_generation_callback_user: std::ptr::null_mut(),
frame_generation_enabled: false,
allow_async_workloads: false,
hudless_color: Resource::NONE,
flags: 0,
only_present_generated: false,
generation_rect: Rect::default(),
frame_id: live.frame_id,
};
let mut wait = Header::new(DISPATCH_WAIT_FOR_PRESENTS_DX12);
// SAFETY: our contexts and filled descriptions; nothing of ours uses the
// frame generation context after this.
unsafe {
(ffx.configure)(&mut *context, (&raw mut off).cast());
(ffx.dispatch)(&mut *live.swap_chain_context, &raw mut wait);
(ffx.destroy)(&mut *context, std::ptr::null());
}
live.refused = None;
ON.store(false, Relaxed);
true
}
unsafe extern "C" fn generate(params: *mut Header, user: *mut c_void) -> u32 {
let Some(ffx) = FFX.get() else { return 1 };
// SAFETY: `user` is the boxed frame generation context the configuration
// named; `params` the swap chain's dispatch description.
unsafe { (ffx.dispatch)(user.cast(), params) }
}
/// Into `list` (the last list before our Present, on the same queue): with a
/// fresh upscaling, the frame's prepare dispatch from its depth and motion
/// vectors, and the frame's configuration (frame generation on or off), for
/// the back buffer of `size` and `format`.
///
/// `base` is the texture presented and its state; `two_planes`: the interface
/// is a plane of its own composed over it (Series S), so `base` is the colour
/// without the interface. Otherwise (Series X) that is the copy taken in front
/// of the title's interface composite. FidelityFX tells the interface (and our
/// panel and menu, drawn after) from the scene by it and does not move it with
/// the scene.
pub(crate) fn before_present(
device: &ID3D12Device,
swap_chain: &IDXGISwapChain3,
list: &ID3D12GraphicsCommandList,
size: [u32; 2],
format: DXGI_FORMAT,
base: (&ID3D12Resource, u32),
two_planes: bool,
) {
if !SWAP_CHAIN.load(Acquire) {
return;
}
let Some(ffx) = FFX.get() else { return };
// (Taken at every present: the copies of a texture not presented go.)
let hudless: Option<(ID3D12Resource, u32)> = if two_planes {
Some((base.0.clone(), base.1))
} else if super::hudless_wanted() {
super::hudless_for(base.0).map(|copy| (copy, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32))
} else {
None
};
// Of the back buffer's size only (FidelityFX compares the two pixel by pixel).
let hudless = hudless.filter(|(t, _)| {
// SAFETY: a live texture.
let desc = unsafe { t.GetDesc() };
let same = [desc.Width as u32, desc.Height] == size;
if !same {
once!(warn, hudless = ?[desc.Width as u32, desc.Height], back_buffer = ?size, "FSR 3 frame generation: the colour without the interface is not the back buffer's size; the interface moves with the scene");
}
same
});
let hudless_format = hudless.as_ref().map_or(DXGI_FORMAT_UNKNOWN, |(t, _)| {
// SAFETY: a live texture.
unsafe { t.GetDesc() }.Format
});
let mut guard = live();
let Some(live) = guard.as_mut() else { return };
// The textures' states are those the submissions before this present
// left: only the line of submissions orders the two.
let line = crate::queue::line_on();
if !line {
once!(warn, "FSR 3 frame generation: the line of submissions did not start; frame generation stays off");
}
let wanted = super::framegen_wanted() != 0 && line;
let fresh = if wanted { super::fresh_inputs() } else { None };
// The context, made at the first upscaling (its sizes are the title's)
// and again when they change.
if let Some(inputs) = &fresh {
let render = inputs.camera.render;
let made_for = live.framegen.as_ref().map(|(_, s, r, f, flags, h)| (*s, *r, *f, *flags, *h));
let flags = create_flags(&inputs.camera, format);
// (A frame without its copy keeps the context as it is.)
let stale = made_for.is_some_and(|(s, r, f, fl, h)| {
s != size || r[0] < render[0] || r[1] < render[1] || f != format || fl != flags || (hudless_format != DXGI_FORMAT_UNKNOWN && h != hudless_format)
});
if stale {
// (Everything sent so far is waited for: what was recorded with
// the old context has run.)
crate::host::settle_now(crate::host::WHY_SYNC);
retire(ffx, live);
tracing::info!(display = ?size, max_render = ?render, "FSR 3 frame generation: its context is made again for other sizes");
}
if live.framegen.is_none() && live.refused != Some((size, render)) {
match create_context(ffx, device, size, render, format, flags, hudless_format) {
Some(context) => {
tracing::info!(
display = ?size,
max_render = ?render,
format = format.0,
hudless_format = hudless_format.0,
flags = format_args!("{flags:#x}"),
"FSR 3 frame generation: its context was made"
);
live.framegen = Some((context, size, render, format, flags, hudless_format));
live.refused = None;
}
None => live.refused = Some((size, render)),
}
}
}
let Some((context, ..)) = live.framegen.as_mut() else {
PRESENTS_OFF.fetch_add(1, Relaxed);
return;
};
live.frame_id += 1;
let frame_id = live.frame_id;
let debug = debug_flags();
let mut prepared = false;
if let Some(inputs) = &fresh {
let camera = inputs.camera;
let depth = Resource::texture(&inputs.depth.0, inputs.depth.1);
let motion = Resource::texture(&inputs.motion.0, inputs.motion.1);
let mut prepare = PrepareV2 {
header: Header::new(DISPATCH_PREPARE_V2),
frame_id,
flags: debug,
command_list: list.as_raw(),
render_size: camera.render.into(),
jitter_offset: Floats { x: camera.jitter[0], y: camera.jitter[1] },
motion_vector_scale: Floats { x: camera.motion_scale[0], y: camera.motion_scale[1] },
frame_time_delta: inputs.frame_ms,
reset: camera.reset,
// As the title gives them to its upscaler (FidelityFX's terms).
camera_near: camera.near,
camera_far: camera.far,
camera_fov_angle_vertical: camera.fov_y,
view_space_to_meters_factor: 1.0,
depth,
motion_vectors: motion,
camera_position: [0.0; 3],
camera_up: [0.0, 1.0, 0.0],
camera_right: [1.0, 0.0, 0.0],
camera_forward: [0.0, 0.0, 1.0],
};
// SAFETY: our context and a filled description of live textures in
// the states they are in when `list` runs.
let code = unsafe { (ffx.dispatch)(&mut **context, (&raw mut prepare).cast()) };
if code == OK {
prepared = true;
once!(
info,
render = ?camera.render,
output = ?camera.output,
back_buffer = ?size,
depth_state = format_args!("{:#x}", inputs.depth.1),
motion_state = format_args!("{:#x}", inputs.motion.1),
near = camera.near,
far = camera.far,
fov = camera.fov_y,
jitter = ?camera.jitter,
mvec_scale = ?camera.motion_scale,
frame_ms = inputs.frame_ms,
"FSR 3 frame generation: first frame prepared from depth and motion vectors"
);
} else {
FAILED.fetch_add(1, Relaxed);
once!(warn, code, "FSR 3 frame generation: the prepare dispatch failed");
}
}
let on = prepared && wanted;
let mut configure = ConfigureFrameGeneration {
header: Header::new(CONFIGURE_FRAMEGENERATION),
swap_chain: swap_chain.as_raw(),
present_callback: std::ptr::null(),
present_callback_user: std::ptr::null_mut(),
frame_generation_callback: Some(generate),
frame_generation_callback_user: (&raw mut **context).cast(),
frame_generation_enabled: on,
allow_async_workloads: false,
hudless_color: match (&hudless, on) {
(Some((texture, state)), true) => Resource::texture(texture, *state),
_ => Resource::NONE,
},
flags: debug,
only_present_generated: false,
generation_rect: Rect { left: 0, top: 0, width: size[0] as i32, height: size[1] as i32 },
frame_id,
};
// SAFETY: our context and a filled description.
let code = unsafe { (ffx.configure)(&mut **context, (&raw mut configure).cast()) };
if code != OK {
once!(warn, code, "FSR 3 frame generation: the configuration failed");
}
let on = on && code == OK;
if ON.swap(on, Relaxed) != on {
tracing::info!(on, frame_id, "FSR 3 frame generation switched");
}
if on {
PRESENTS_ON.fetch_add(1, Relaxed);
if hudless.is_some() {
HUDLESS_GIVEN.fetch_add(1, Relaxed);
once!(info, two_planes, "FSR 3 frame generation: first frame with the colour without the interface");
}
} else {
PRESENTS_OFF.fetch_add(1, Relaxed);
}
}
fn create_context(
ffx: &Ffx,
device: &ID3D12Device,
size: [u32; 2],
render: [u32; 2],
format: DXGI_FORMAT,
flags: u32,
hudless_format: DXGI_FORMAT,
) -> Option<Box<Context>> {
let mut backend = CreateBackend { header: Header::new(CREATE_BACKEND_DX12), device: device.as_raw() };
// The colour without the interface in a format of its own (else the back buffer's is assumed).
let mut hudless = Version { header: Header::new(CREATE_FRAMEGENERATION_HUDLESS), version: surface_format(hudless_format) };
if hudless_format != DXGI_FORMAT_UNKNOWN && hudless_format != format {
hudless.header.next = (&raw mut backend).cast();
}
let first_after_version: *mut Header =
if hudless_format != DXGI_FORMAT_UNKNOWN && hudless_format != format { (&raw mut hudless).cast() } else { (&raw mut backend).cast() };
let mut version = Version { header: Header::new(CREATE_FRAMEGENERATION_VERSION), version: FRAMEGENERATION_VERSION };
let mut create = CreateFrameGeneration {
header: Header::new(CREATE_FRAMEGENERATION),
flags,
display_size: size.into(),
max_render_size: render.into(),
back_buffer_format: surface_format(format),
};
version.header.next = first_after_version;
create.header.next = (&raw mut version).cast();
let mut context: Box<Context> = Box::new(std::ptr::null_mut());
// SAFETY: filled descriptions that live through the call.
let code = unsafe { (ffx.create)(&mut *context, (&raw mut create).cast(), std::ptr::null()) };
if code != OK || context.is_null() {
tracing::warn!(code, display = ?size, max_render = ?render, format = format.0, "FSR 3 frame generation: its context was not made; presents stay plain");
return None;
}
Some(context)
}
/// The frame generation context's flags from the title's upscaler's (the
/// same meanings, other bits) and our back buffer.
fn create_flags(camera: &plan::Camera, format: DXGI_FORMAT) -> u32 {
let mut flags = 0;
if camera.flags & plan::FFX_DISPLAY_RESOLUTION_MOTION_VECTORS != 0 {
flags |= FG_DISPLAY_RESOLUTION_MV;
}
if camera.flags & plan::FFX_MOTION_VECTORS_JITTER_CANCELLATION != 0 {
flags |= FG_MV_JITTER_CANCELLATION;
}
if camera.flags & plan::FFX_DEPTH_INVERTED != 0 {
flags |= FG_DEPTH_INVERTED;
}
if camera.flags & plan::FFX_DEPTH_INFINITE != 0 {
flags |= FG_DEPTH_INFINITE;
}
// (The title's upscaler takes the scene before its tone mapping; what we
// present is after it: high dynamic range only for a float back buffer.)
if format == DXGI_FORMAT_R16G16B16A16_FLOAT {
flags |= FG_HIGH_DYNAMIC_RANGE;
}
flags
}
/// `VICTORY_FSR_FRAMEGEN_DEBUG=1`: tear and pacing lines drawn.
fn debug_flags() -> u32 {
static FLAGS: OnceLock<u32> = OnceLock::new();
*FLAGS.get_or_init(|| {
if std::env::var("VICTORY_FSR_FRAMEGEN_DEBUG").is_ok_and(|v| v.trim() == "1") {
FG_DRAW_DEBUG_TEAR_LINES | FG_DRAW_DEBUG_PACING_LINES
} else {
0
}
})
}
/// A D3D12 state as FidelityFX names it.
fn ffx_state(state: u32) -> u32 {
let s = D3D12_RESOURCE_STATES(state as i32);
if s == D3D12_RESOURCE_STATE_COMMON {
return STATE_COMMON;
}
let mut out = 0;
if s.contains(D3D12_RESOURCE_STATE_UNORDERED_ACCESS) {
out |= STATE_UNORDERED_ACCESS;
}
if s.contains(D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE) {
out |= STATE_COMPUTE_READ;
}
if s.contains(D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE) {
out |= STATE_PIXEL_READ;
}
if s.contains(D3D12_RESOURCE_STATE_COPY_SOURCE) {
out |= STATE_COPY_SRC;
}
if s.contains(D3D12_RESOURCE_STATE_COPY_DEST) {
out |= STATE_COPY_DEST;
}
if s.contains(D3D12_RESOURCE_STATE_RENDER_TARGET) {
out |= STATE_RENDER_TARGET;
}
if s.contains(D3D12_RESOURCE_STATE_DEPTH_WRITE) || s.contains(D3D12_RESOURCE_STATE_DEPTH_READ) {
out |= STATE_DEPTH_ATTACHMENT;
}
if out == 0 { STATE_COMMON } else { out }
}
/// `ffxApiGetSurfaceFormatDX12`.
fn surface_format(format: DXGI_FORMAT) -> u32 {
match format {
DXGI_FORMAT_R32G32B32A32_TYPELESS => 1,
DXGI_FORMAT_R32G32B32A32_UINT => 2,
DXGI_FORMAT_R32G32B32A32_FLOAT => 3,
DXGI_FORMAT_R16G16B16A16_FLOAT => 4,
DXGI_FORMAT_R32G32_FLOAT => 6,
DXGI_FORMAT_R8_UINT | DXGI_FORMAT_X32_TYPELESS_G8X24_UINT | DXGI_FORMAT_X24_TYPELESS_G8_UINT => 7,
DXGI_FORMAT_R32_UINT | DXGI_FORMAT_R24G8_TYPELESS | DXGI_FORMAT_D24_UNORM_S8_UINT | DXGI_FORMAT_R24_UNORM_X8_TYPELESS => 8,
DXGI_FORMAT_R8G8B8A8_TYPELESS => 9,
DXGI_FORMAT_R8G8B8A8_UNORM => 10,
DXGI_FORMAT_R8G8B8A8_SNORM => 11,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => 12,
DXGI_FORMAT_B8G8R8A8_TYPELESS => 13,
DXGI_FORMAT_B8G8R8A8_UNORM => 14,
DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => 15,
DXGI_FORMAT_R11G11B10_FLOAT => 16,
DXGI_FORMAT_R10G10B10A2_UNORM => 17,
DXGI_FORMAT_R16G16_FLOAT => 18,
DXGI_FORMAT_R16G16_UINT => 19,
DXGI_FORMAT_R16_FLOAT => 21,
DXGI_FORMAT_R16_UINT => 22,
DXGI_FORMAT_R16_UNORM | DXGI_FORMAT_D16_UNORM => 23,
DXGI_FORMAT_R16_SNORM => 24,
DXGI_FORMAT_R8_UNORM | DXGI_FORMAT_A8_UNORM => 25,
DXGI_FORMAT_R8G8_UNORM => 26,
DXGI_FORMAT_R8G8_UINT => 27,
DXGI_FORMAT_R32_FLOAT | DXGI_FORMAT_D32_FLOAT | DXGI_FORMAT_R32G8X24_TYPELESS | DXGI_FORMAT_D32_FLOAT_S8X24_UINT | DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS => 28,
DXGI_FORMAT_R9G9B9E5_SHAREDEXP => 29,
DXGI_FORMAT_R16G16B16A16_TYPELESS => 30,
DXGI_FORMAT_R32G32_TYPELESS => 31,
DXGI_FORMAT_R10G10B10A2_TYPELESS => 32,
DXGI_FORMAT_R16G16_TYPELESS => 33,
DXGI_FORMAT_R16_TYPELESS => 34,
DXGI_FORMAT_R8_TYPELESS => 35,
DXGI_FORMAT_R8G8_TYPELESS => 36,
DXGI_FORMAT_R32_TYPELESS => 37,
DXGI_FORMAT_R8_SNORM => 39,
_ => 0,
}
}
/// For the frame-rate line: presents with FSR 3 frame generation on and off
/// since the last one, and prepare dispatches that failed; `None` if it is
/// not in use.
pub(crate) fn line_counts() -> Option<(u64, u64, u64, u64)> {
// (Every tenth frame-rate line: about every ten seconds.)
static LINES: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let due = LINES.fetch_add(1, Relaxed) % 10 == 9;
(SWAP_CHAIN.load(Relaxed) && due).then(|| {
(PRESENTS_ON.swap(0, Relaxed), PRESENTS_OFF.swap(0, Relaxed), FAILED.swap(0, Relaxed), HUDLESS_GIVEN.swap(0, Relaxed))
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn layouts_match_the_headers() {
// x64 sizes of the C structures (FidelityFX SDK 2.x headers).
assert_eq!(size_of::<Header>(), 16);
assert_eq!(size_of::<ResourceDescription>(), 32);
assert_eq!(size_of::<Resource>(), 48);
assert_eq!(size_of::<CreateFrameGeneration>(), 40);
assert_eq!(size_of::<CreateSwapChainForHwnd>(), 64);
assert_eq!(std::mem::offset_of!(ConfigureFrameGeneration, hudless_color), 64);
assert_eq!(std::mem::offset_of!(ConfigureFrameGeneration, generation_rect), 120);
assert_eq!(std::mem::offset_of!(ConfigureFrameGeneration, frame_id), 136);
assert_eq!(size_of::<ConfigureFrameGeneration>(), 144);
assert_eq!(std::mem::offset_of!(PrepareV2, command_list), 32);
assert_eq!(std::mem::offset_of!(PrepareV2, frame_time_delta), 64);
assert_eq!(std::mem::offset_of!(PrepareV2, camera_near), 72);
assert_eq!(std::mem::offset_of!(PrepareV2, depth), 88);
assert_eq!(std::mem::offset_of!(PrepareV2, camera_position), 184);
assert_eq!(size_of::<PrepareV2>(), 232);
}
fn facts(dlss: bool, dlss_fg_supported: bool, fsr_loaded: bool, series_s: bool) -> super::super::Facts {
super::super::Facts {
adapter: "NVIDIA GeForce RTX 3080".into(),
series_s,
no_dlss: if dlss { None } else { Some(super::super::NoDlss::Card) },
files_missing: false,
dlss_fg_asked: true,
dlss_fg_supported,
fsr_asked: true,
fsr_loaded,
fsr_needs_series_s: !series_s && !dlss,
}
}
/// The start's notice: what runs and why, in lines the picture's box and font show.
#[test]
fn the_notice_says_what_the_card_does() {
use super::super::notice_of;
let shown = |lines: &[String]| {
for l in lines {
assert!(l.len() <= 52, "{l}");
assert!(l.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || b" .,:()/->+!?_=*".contains(&c)), "{l}");
}
};
let lines = |f, dlss_live, fsr_live| {
let l = notice_of(&f, dlss_live, fsr_live).into_iter().map(|l| l.to_ascii_uppercase()).collect::<Vec<_>>();
shown(&l);
l.join("|")
};
// RTX 40/50: DLSS frame generation.
assert!(lines(facts(true, true, true, false), true, false).contains("FRAME GEN: DLSS"));
// RTX 20/30 on Series X with DLSS: FSR 3 instead, 2X.
let rtx30 = lines(facts(true, false, true, false), false, true);
assert!(rtx30.contains("NOT ON THIS CARD") && rtx30.contains("FSR 3") && rtx30.contains("2X"));
// No DLSS at all, Series X: FSR 3 needs Series S.
let amd_x = lines(facts(false, false, false, false), false, false);
assert!(amd_x.contains("HAS NO DLSS") && amd_x.contains("SERIES S"), "{amd_x}");
// A card with DLSS, only turned off: say so, not "this card".
let mut off = facts(false, true, false, false);
off.no_dlss = Some(super::super::NoDlss::TurnedOff);
let off = lines(off, false, false);
assert!(off.contains("DLSS UPSCALING IS OFF") && !off.contains("THIS CARD"), "{off}");
let mut missing = facts(false, false, false, false);
missing.no_dlss = Some(super::super::NoDlss::FilesMissing);
missing.files_missing = true;
let missing = lines(missing, false, false);
assert!(missing.contains("FILES NOT FOUND") && !missing.contains("THIS CARD"), "{missing}");
// No DLSS, Series S: FSR 3 runs.
assert!(lines(facts(false, false, true, true), false, true).contains("RUNS WITHOUT DLSS"));
// Nothing asked: nothing said.
let mut quiet = facts(true, true, true, false);
(quiet.dlss_fg_asked, quiet.fsr_asked) = (false, false);
assert!(notice_of(&quiet, false, false).is_empty());
}
#[test]
fn states_and_formats() {
assert_eq!(ffx_state(0), STATE_COMMON);
assert_eq!(ffx_state(0x8), STATE_UNORDERED_ACCESS);
assert_eq!(ffx_state(0xC0), STATE_COMPUTE_READ | STATE_PIXEL_READ);
assert_eq!(ffx_state(0x20), STATE_DEPTH_ATTACHMENT);
assert_eq!(surface_format(DXGI_FORMAT_R8G8B8A8_UNORM), 10);
assert_eq!(surface_format(DXGI_FORMAT_R10G10B10A2_UNORM), 17);
assert_eq!(surface_format(DXGI_FORMAT_R32_TYPELESS), 37);
}
}