upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMoonEyes <ducoinbenjamin@yahoo.fr>2026-11-29 20:00:10 +0100
committerGitHub <noreply@github.com>2026-11-29 20:00:10 +0100
commitf7a4e75bf8cdb0db8fae0a0bc89e8b854f3f463b (patch)
tree060e3dd3efe39cd3253f3443b1e43afc8b14b807
parenta09d1627e307734a2fbca31a989723ff04ff40f9 (diff)
parent865f6c24e33bd7d1f442433d07d52c00187242fb (diff)
Merge pull request #2615 from alpfilho/d3d12/fsr3-framegen
d3d12: FSR 3 frame generation for cards without DLSS frame generation (D3D12-FSR3-FRAMEGEN)
-rw-r--r--d3d12/README.md1
-rw-r--r--d3d12/crates/leonida-gpu/Cargo.toml2
-rw-r--r--d3d12/crates/leonida-gpu/src/dlss.rs2
-rw-r--r--d3d12/crates/leonida-gpu/src/draw.rs2
-rw-r--r--d3d12/crates/leonida-gpu/src/fg.rs66
-rw-r--r--d3d12/crates/leonida-gpu/src/fsr.rs928
-rw-r--r--d3d12/crates/leonida-gpu/src/host.rs27
-rw-r--r--d3d12/crates/leonida-gpu/src/host/menu.rs7
-rw-r--r--d3d12/crates/leonida-gpu/src/lib.rs3
-rw-r--r--d3d12/crates/leonida-gpu/src/list.rs2
-rw-r--r--d3d12/scripts/play-nvidia.ps138
-rw-r--r--scripts/play-d3d12.ps15
12 files changed, 1067 insertions, 16 deletions
diff --git a/d3d12/README.md b/d3d12/README.md
index ef00cc428..136d3a730 100644
--- a/d3d12/README.md
+++ b/d3d12/README.md
@@ -50,6 +50,7 @@ measurements and what is still wrong in the picture are in the [top-level README
50| Draws of programs kept unpacked in their container dropped (three of the title's text programs) | Always: a container's raw FSSM record (XDAT kind 0x0c) is read beside the zlib-packed one (0x0d); before, such a container had no program and its draws were dropped | `crates/leonida-shader/src/native.rs` | fuzeofficial (Marvisak/VIctory#3116 ef15cada), through Androtim/MiniVI 96e788c7 and trustno1-coder/VIctory-NVIDIA 87d73cb2 | 50| Draws of programs kept unpacked in their container dropped (three of the title's text programs) | Always: a container's raw FSSM record (XDAT kind 0x0c) is read beside the zlib-packed one (0x0d); before, such a container had no program and its draws were dropped | `crates/leonida-shader/src/native.rs` | fuzeofficial (Marvisak/VIctory#3116 ef15cada), through Androtim/MiniVI 96e788c7 and trustno1-coder/VIctory-NVIDIA 87d73cb2 |
51| No trainer menu | `LEONIDA_MENU` (on; 0 off): F4 (or RB + d-pad Left) opens an in-game menu beside the F1 settings and the F3 panel; arrows or numpad 8/2/4/6 move, Enter or 5 selects, Backspace or 0 goes back; `LEONIDA_MENU_OPEN=1` starts it open. DLSS sharpness, the frame-rate cap and the FPS panel (the renderer's own settings, shared with the F1 menu), screenshots, frame recording and the title's clock rate work; script features (god mode, vehicles, weather, ...) wait for the title's natives. Built and unit-tested, not yet tried in the running title (`docs/mod-menu.md`) | `crates/leonida-menu`, `crates/leonida-gpu/src/host/trainer.rs` | Leonida's own; the classic single-player trainer layout, no code or art from one | 51| No trainer menu | `LEONIDA_MENU` (on; 0 off): F4 (or RB + d-pad Left) opens an in-game menu beside the F1 settings and the F3 panel; arrows or numpad 8/2/4/6 move, Enter or 5 selects, Backspace or 0 goes back; `LEONIDA_MENU_OPEN=1` starts it open. DLSS sharpness, the frame-rate cap and the FPS panel (the renderer's own settings, shared with the F1 menu), screenshots, frame recording and the title's clock rate work; script features (god mode, vehicles, weather, ...) wait for the title's natives. Built and unit-tested, not yet tried in the running title (`docs/mod-menu.md`) | `crates/leonida-menu`, `crates/leonida-gpu/src/host/trainer.rs` | Leonida's own; the classic single-player trainer layout, no code or art from one |
52| No Lua mods | `LEONIDA_LUA` (on; 0 off, no thread): Lua 5.4 mods in `mods\<name>\` (`mod.json` with `"script": "main.lua"`, `LEONIDA_MODS` names the folder) run in a sandbox on a thread of their own, with the `leonida` API (version 1): frame, key and menu events, an overlay, the live settings (frame cap, DLSS sharpness, panel), pages in the F4 menu under Mods (and Reload Lua mods), keys held for the title, and checked reads, writes and pattern scans of the title's memory; a failing mod is switched off alone. `mods\example_lua` ships disabled. Not the title's own script functions (god mode, vehicles, weather: none can be called). Built and unit-tested, not yet tried in the running title (`docs/lua-modding.md`) | `crates/leonida-lua`, `crates/leonida-menu/src/{overlay,mods}.rs`, `crates/leonida-gpu/src/host/trainer.rs` | Leonida's own; Lua 5.4 through the `mlua` crate (MIT) | 52| No Lua mods | `LEONIDA_LUA` (on; 0 off, no thread): Lua 5.4 mods in `mods\<name>\` (`mod.json` with `"script": "main.lua"`, `LEONIDA_MODS` names the folder) run in a sandbox on a thread of their own, with the `leonida` API (version 1): frame, key and menu events, an overlay, the live settings (frame cap, DLSS sharpness, panel), pages in the F4 menu under Mods (and Reload Lua mods), keys held for the title, and checked reads, writes and pattern scans of the title's memory; a failing mod is switched off alone. `mods\example_lua` ships disabled. Not the title's own script functions (god mode, vehicles, weather: none can be called). Built and unit-tested, not yet tried in the running title (`docs/lua-modding.md`) | `crates/leonida-lua`, `crates/leonida-menu/src/{overlay,mods}.rs`, `crates/leonida-gpu/src/host/trainer.rs` | Leonida's own; Lua 5.4 through the `mlua` crate (MIT) |
53| No frame generation on RTX 20 and 30 cards (DLSS's runs on RTX 40 and 50 only) | `LEONIDA_FSR_FRAMEGEN=1` (off; `-FsrFrameGen`, or FSR 3 FRAME GEN in the F1 menu from the next start, off and on again while it runs) with AMD's signed `amd_fidelityfx_loader_dx12.dll` and `amd_fidelityfx_framegeneration_dx12.dll` in `amd-sdk\FidelityFX\bin` (`LEONIDA_FIDELITYFX_DIR`): the swap chain is FidelityFX's frame interpolation swap chain, given the depth and motion vectors DLSS frame generation is given, and one frame is generated between each two rendered; on Series S the base plane is the colour without the interface. Never with DLSS frame generation or ray tracing | `crates/leonida-gpu/src/fsr.rs`, `crates/leonida-gpu/src/fg.rs`, `scripts/play-nvidia.ps1` | trustno1-coder/VIctory-NVIDIA `29d8dbf` (`crates/victory-gpu/src/streamline/fsr.rs`, GPL-3.0) |
53 54
54 55
55## Shaders and pipelines are made before the title starts 56## Shaders and pipelines are made before the title starts
diff --git a/d3d12/crates/leonida-gpu/Cargo.toml b/d3d12/crates/leonida-gpu/Cargo.toml
index b7806fe00..617a774c2 100644
--- a/d3d12/crates/leonida-gpu/Cargo.toml
+++ b/d3d12/crates/leonida-gpu/Cargo.toml
@@ -38,7 +38,7 @@ mimalloc = ["dep:mimalloc"]
38workspace = true 38workspace = true
39 39
40[target.'cfg(windows)'.dependencies] 40[target.'cfg(windows)'.dependencies]
41windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] } 41windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Cryptography", "Win32_Security_WinTrust", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }
42windows = { workspace = true, features = [ 42windows = { workspace = true, features = [
43 "Win32_Graphics_Direct3D", 43 "Win32_Graphics_Direct3D",
44 "Win32_Graphics_Direct3D_Fxc", 44 "Win32_Graphics_Direct3D_Fxc",
diff --git a/d3d12/crates/leonida-gpu/src/dlss.rs b/d3d12/crates/leonida-gpu/src/dlss.rs
index eb466b1da..c7e2b9ece 100644
--- a/d3d12/crates/leonida-gpu/src/dlss.rs
+++ b/d3d12/crates/leonida-gpu/src/dlss.rs
@@ -337,7 +337,7 @@ pub(crate) fn record(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, in
337 } 337 }
338 // LOCAL (11/26): DLSS Frame Generation's inputs (`LEONIDA_FRAME_GEN`), in the state the 338 // LOCAL (11/26): DLSS Frame Generation's inputs (`LEONIDA_FRAME_GEN`), in the state the
339 // upscale read them in. 339 // upscale read them in.
340 if crate::fg::active() { 340 if crate::fg::collecting() {
341 crate::fg::tag( 341 crate::fg::tag(
342 [render[0].min(in_w), render[1].min(in_h)], 342 [render[0].min(in_w), render[1].min(in_h)],
343 [jit * inputs.jitter[0], jit * inputs.jitter[1]], 343 [jit * inputs.jitter[0], jit * inputs.jitter[1]],
diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs
index da2a36af3..c2bd6d2e4 100644
--- a/d3d12/crates/leonida-gpu/src/draw.rs
+++ b/d3d12/crates/leonida-gpu/src/draw.rs
@@ -2393,7 +2393,7 @@ impl State {
2393 // (`crate::fg::gbuffer`). The pass is the one with four or more targets, one of them two 16-bit floats 2393 // (`crate::fg::gbuffer`). The pass is the one with four or more targets, one of them two 16-bit floats
2394 // (DXGI format 34), and a depth target of that size. 2394 // (DXGI format 34), and a depth target of that size.
2395 const VELOCITY: u32 = 34; 2395 const VELOCITY: u32 = 34;
2396 if crate::fg::active() && views.len() >= 4 && self.depth != 0 { 2396 if crate::fg::collecting() && views.len() >= 4 && self.depth != 0 {
2397 let velocity = (0..views.len().min(8)).find(|&i| formats[i] == VELOCITY && titles[i] != 0); 2397 let velocity = (0..views.len().min(8)).find(|&i| formats[i] == VELOCITY && titles[i] != 0);
2398 if let (Some(i), Some((depth, _))) = (velocity, dsv.as_ref()) 2398 if let (Some(i), Some((depth, _))) = (velocity, dsv.as_ref())
2399 && let Some(motion) = views[i].0 2399 && let Some(motion) = views[i].0
diff --git a/d3d12/crates/leonida-gpu/src/fg.rs b/d3d12/crates/leonida-gpu/src/fg.rs
index 482064de1..9ebc7e3bf 100644
--- a/d3d12/crates/leonida-gpu/src/fg.rs
+++ b/d3d12/crates/leonida-gpu/src/fg.rs
@@ -712,7 +712,7 @@ static LATEST: Mutex<Option<Latest>> = Mutex::new(None);
712/// one the constants and tags carry. 712/// one the constants and tags carry.
713#[allow(clippy::too_many_arguments)] 713#[allow(clippy::too_many_arguments)]
714pub(crate) fn tag(render: [u32; 2], jitter: [f32; 2], mv_pixels: [f32; 2], near: f32, far: f32, reset: bool) { 714pub(crate) fn tag(render: [u32; 2], jitter: [f32; 2], mv_pixels: [f32; 2], near: f32, far: f32, reset: bool) {
715 if state().is_none() { 715 if !collecting() {
716 return; 716 return;
717 } 717 }
718 let mut latest = LATEST.lock().unwrap_or_else(|e| e.into_inner()); 718 let mut latest = LATEST.lock().unwrap_or_else(|e| e.into_inner());
@@ -744,7 +744,7 @@ pub(crate) fn tag_plain(up: &crate::list::Upscale, colour: [u32; 2]) {
744 744
745/// The title's depth and motion vectors the DLSS upscale read (`crate::list::upscale_now`). 745/// The title's depth and motion vectors the DLSS upscale read (`crate::list::upscale_now`).
746pub(crate) fn note_titles(depth: u64, motion: u64) { 746pub(crate) fn note_titles(depth: u64, motion: u64) {
747 if state().is_none() { 747 if !collecting() {
748 return; 748 return;
749 } 749 }
750 let mut latest = LATEST.lock().unwrap_or_else(|e| e.into_inner()); 750 let mut latest = LATEST.lock().unwrap_or_else(|e| e.into_inner());
@@ -776,7 +776,7 @@ fn gbuffer_on() -> bool {
776/// presents are served later in the line, so the pass recorded last can be the next frame's, whose 776/// presents are served later in the line, so the pass recorded last can be the next frame's, whose
777/// targets the card has not drawn yet when it runs the present being tagged. 777/// targets the card has not drawn yet when it runs the present being tagged.
778pub(crate) fn gbuffer(list: &crate::host::HostList, depth: u64, motion: u64, size: [u32; 2]) { 778pub(crate) fn gbuffer(list: &crate::host::HostList, depth: u64, motion: u64, size: [u32; 2]) {
779 if state().is_none() || !gbuffer_on() || UPSCALE_TAGS.load(Ordering::Relaxed) { 779 if !collecting() || !gbuffer_on() || UPSCALE_TAGS.load(Ordering::Relaxed) {
780 return; 780 return;
781 } 781 }
782 // (the list's last bind of such a pass stands for it) 782 // (the list's last bind of such a pass stands for it)
@@ -801,7 +801,7 @@ static GBUFFER_PASSED_OVER: AtomicU64 = AtomicU64::new(0);
801/// probe's), and taking whichever came last gave a generated frame that pass's depth and motion vectors 801/// probe's), and taking whichever came last gave a generated frame that pass's depth and motion vectors
802/// now and then (four times in four seconds standing, 2026-11-29: a one-frame picture of garbage). 802/// now and then (four times in four seconds standing, 2026-11-29: a one-frame picture of garbage).
803pub(crate) fn gbuffer_submitted(depth: u64, motion: u64, size: [u32; 2]) { 803pub(crate) fn gbuffer_submitted(depth: u64, motion: u64, size: [u32; 2]) {
804 if state().is_none() || !gbuffer_on() || UPSCALE_TAGS.load(Ordering::Relaxed) { 804 if !collecting() || !gbuffer_on() || UPSCALE_TAGS.load(Ordering::Relaxed) {
805 return; 805 return;
806 } 806 }
807 let area = u64::from(size[0]) * u64::from(size[1]); 807 let area = u64::from(size[0]) * u64::from(size[1]);
@@ -1155,6 +1155,9 @@ static SHOWN: AtomicU32 = AtomicU32::new(1);
1155 1155
1156/// For the frame-rate texts: frames shown per frame rendered; 1 when generation is off or failing. 1156/// For the frame-rate texts: frames shown per frame rendered; 1 when generation is off or failing.
1157pub(crate) fn shown_per_frame() -> u32 { 1157pub(crate) fn shown_per_frame() -> u32 {
1158 if let Some(per) = crate::fsr::shown_per_frame() {
1159 return per;
1160 }
1158 if state().is_some() { SHOWN.load(Ordering::Relaxed).max(1) } else { 1 } 1161 if state().is_some() { SHOWN.load(Ordering::Relaxed).max(1) } else { 1 }
1159} 1162}
1160 1163
@@ -1710,3 +1713,58 @@ mod hudless_tests {
1710 } 1713 }
1711} 1714}
1712 1715
1716/// Leonida: whether upscales and the G-buffer pass hand their depth, motion vectors and numbers over: Streamline
1717/// presents ([`active`]), or FidelityFX's frame interpolation swap chain does (`crate::fsr`).
1718pub(crate) fn collecting() -> bool {
1719 state().is_some() || crate::fsr::live_swap_chain()
1720}
1721
1722/// Leonida: what the last upscale (or G-buffer pass) handed over, for FSR 3 frame generation (`crate::fsr`): its
1723/// numbers, and the host copies of its depth and motion vectors with the states they are in at the present.
1724pub(crate) struct Inputs {
1725 pub(crate) render: [u32; 2],
1726 pub(crate) jitter: [f32; 2],
1727 pub(crate) mv_pixels: [f32; 2],
1728 pub(crate) near: f32,
1729 pub(crate) far: f32,
1730 pub(crate) reset: bool,
1731 pub(crate) depth: (ID3D12Resource, u32),
1732 pub(crate) motion: (ID3D12Resource, u32),
1733 /// An upscale ran since the last present.
1734 pub(crate) fresh: bool,
1735}
1736
1737/// Leonida: at a present without Streamline ([`present_start`] takes them with it): [`Inputs`], if anything was
1738/// handed over and its title resources are still there.
1739pub(crate) fn inputs_for_present() -> Option<Inputs> {
1740 if state().is_some() {
1741 return None;
1742 }
1743 // The G-buffer pass of the frame this present shows (submitted before it), as in `present_start`.
1744 gbuffer_at_present();
1745 let fresh = TAGGED.swap(false, Ordering::Relaxed);
1746 let latest = LATEST.lock().unwrap_or_else(|e| e.into_inner());
1747 let l = latest.as_ref()?;
1748 // As in `present_start`: only a title resource that is still one, and its host copy as it is.
1749 let look = |title: usize| {
1750 let this = title as crate::object::This;
1751 if this.is_null() || !crate::resource::is_resource(this) {
1752 return None;
1753 }
1754 let copy = crate::resource::made_copy(this)?;
1755 let state = crate::host::legal_state(&copy.texture, copy.state.load(Ordering::Relaxed));
1756 Some((copy.texture.clone(), state))
1757 };
1758 Some(Inputs {
1759 render: l.render,
1760 jitter: l.jitter,
1761 mv_pixels: l.mv_pixels,
1762 near: l.near,
1763 far: l.far,
1764 reset: l.reset,
1765 depth: look(l.depth)?,
1766 motion: look(l.motion)?,
1767 fresh,
1768 })
1769}
1770
diff --git a/d3d12/crates/leonida-gpu/src/fsr.rs b/d3d12/crates/leonida-gpu/src/fsr.rs
new file mode 100644
index 000000000..5e5061134
--- /dev/null
+++ b/d3d12/crates/leonida-gpu/src/fsr.rs
@@ -0,0 +1,928 @@
1//! Leonida: AMD FSR 3 frame generation, for cards DLSS Frame Generation does not run on (RTX 20 and 30, and
2//! others with Direct3D 12). Ported from trustno1-coder/VIctory-NVIDIA (`crates/victory-gpu/src/streamline/fsr.rs`,
3//! `29d8dbf` and later, GPL-3.0), fitted to this tree's presenter and to the inputs [`crate::fg`] keeps.
4//!
5//! - `LEONIDA_FSR_FRAMEGEN=1` at the start: the presenter's swap chain is FidelityFX's frame interpolation swap
6//! chain, and each present is told the depth and motion vectors of the last upscale (the same inputs DLSS Frame
7//! Generation is handed, [`crate::fg::inputs_for_present`]), so one frame is generated between each two the title
8//! renders. Not with Streamline's swap chain: where DLSS Frame Generation started, this stays off.
9//! While running, the F1 menu turns generation off and on again (`LEONIDA_FSR_FRAMEGEN` unset or `1`); the swap
10//! chain stays FidelityFX's until the next start.
11//! - `LEONIDA_FIDELITYFX_DIR`: the folder of AMD's signed `amd_fidelityfx_loader_dx12.dll` and
12//! `amd_fidelityfx_framegeneration_dx12.dll` (the FidelityFX SDK's `bin`; default: a `fidelityfx` folder beside
13//! our exe). Their signatures are checked before they are loaded.
14//! - `LEONIDA_FSR_FRAMEGEN_DEBUG=1`: FidelityFX draws its tear and pacing lines.
15//!
16//! Anything missing (the folder, a signature, the swap chain, the context) leaves the plain present as it was, with
17//! a warning in the log. The title gives no camera: as for DLSS Frame Generation, a 60 degree field of view, the
18//! upscale's near and far and its render size. On Series S the base plane is the colour without the interface (the
19//! interface is the overlay plane composed over it), which FidelityFX uses to keep the interface from moving with
20//! the scene; elsewhere no such colour is handed over.
21
22use std::ffi::{CStr, c_void};
23use std::path::{Path, PathBuf};
24use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering::*};
25use std::sync::{Mutex, OnceLock};
26use std::time::Instant;
27
28use windows::Win32::Foundation::HWND;
29use windows::Win32::Graphics::Direct3D12::*;
30use windows::Win32::Graphics::Dxgi::Common::*;
31use windows::Win32::Graphics::Dxgi::*;
32use windows::core::Interface;
33
34const LOADER: &str = "amd_fidelityfx_loader_dx12.dll";
35const FRAMEGEN: &str = "amd_fidelityfx_framegeneration_dx12.dll";
36
37// Structure types (ffx_api.h, ffx_framegeneration.h, ffx_api_dx12.h and ffx_api_framegeneration_dx12.h of the
38// FidelityFX SDK 2.x).
39const CREATE_BACKEND_DX12: u64 = 0x0000_0002;
40const CREATE_FRAMEGENERATION: u64 = 0x0002_0001;
41const CONFIGURE_FRAMEGENERATION: u64 = 0x0002_0002;
42const CREATE_FRAMEGENERATION_HUDLESS: u64 = 0x0002_0009;
43const DISPATCH_PREPARE_V2: u64 = 0x0002_000c;
44const CREATE_FRAMEGENERATION_VERSION: u64 = 0x0002_000e;
45const CREATE_SWAPCHAIN_FOR_HWND_DX12: u64 = 0x0003_0006;
46const DISPATCH_WAIT_FOR_PRESENTS_DX12: u64 = 0x0003_0007;
47const CREATE_SWAPCHAIN_VERSION_DX12: u64 = 0x0003_000b;
48/// The versions our structures are those of.
49const FRAMEGENERATION_VERSION: u32 = (4 << 22) | 2;
50const SWAPCHAIN_VERSION: u32 = 4 << 22;
51
52// Context creation flags.
53const FG_DEPTH_INVERTED: u32 = 1 << 3;
54const FG_HIGH_DYNAMIC_RANGE: u32 = 1 << 5;
55// Dispatch flags (`LEONIDA_FSR_FRAMEGEN_DEBUG=1`).
56const FG_DRAW_DEBUG_TEAR_LINES: u32 = 1 << 0;
57const FG_DRAW_DEBUG_PACING_LINES: u32 = 1 << 4;
58
59// Resource states, types and usages as FidelityFX names them.
60const STATE_COMMON: u32 = 1 << 0;
61const STATE_UNORDERED_ACCESS: u32 = 1 << 1;
62const STATE_COMPUTE_READ: u32 = 1 << 2;
63const STATE_PIXEL_READ: u32 = 1 << 3;
64const STATE_COPY_SRC: u32 = 1 << 4;
65const STATE_COPY_DEST: u32 = 1 << 5;
66const STATE_RENDER_TARGET: u32 = 1 << 8;
67const STATE_DEPTH_ATTACHMENT: u32 = 1 << 9;
68const TYPE_TEXTURE2D: u32 = 2;
69const USAGE_UAV: u32 = 1 << 1;
70const USAGE_DEPTHTARGET: u32 = 1 << 2;
71const USAGE_STENCILTARGET: u32 = 1 << 5;
72
73const OK: u32 = 0;
74/// The field of view the title's camera is taken to have (as [`crate::fg`]'s constants).
75const FOV_Y_DEGREES: f32 = 60.0;
76
77#[repr(C)]
78struct Header {
79 kind: u64,
80 next: *mut Header,
81}
82
83impl Header {
84 fn new(kind: u64) -> Self {
85 Header { kind, next: std::ptr::null_mut() }
86 }
87}
88
89#[repr(C)]
90#[derive(Clone, Copy, Default)]
91struct Dims {
92 width: u32,
93 height: u32,
94}
95
96impl From<[u32; 2]> for Dims {
97 fn from([width, height]: [u32; 2]) -> Self {
98 Dims { width, height }
99 }
100}
101
102#[repr(C)]
103#[derive(Clone, Copy, Default)]
104struct Floats {
105 x: f32,
106 y: f32,
107}
108
109#[repr(C)]
110#[derive(Clone, Copy, Default)]
111struct Rect {
112 left: i32,
113 top: i32,
114 width: i32,
115 height: i32,
116}
117
118#[repr(C)]
119#[derive(Clone, Copy, Default)]
120struct ResourceDescription {
121 kind: u32,
122 format: u32,
123 width: u32,
124 height: u32,
125 depth: u32,
126 mip_count: u32,
127 flags: u32,
128 usage: u32,
129}
130
131#[repr(C)]
132#[derive(Clone, Copy)]
133struct Resource {
134 resource: *mut c_void,
135 description: ResourceDescription,
136 state: u32,
137}
138
139impl Resource {
140 const NONE: Resource = Resource {
141 resource: std::ptr::null_mut(),
142 description: ResourceDescription { kind: 0, format: 0, width: 0, height: 0, depth: 0, mip_count: 0, flags: 0, usage: 0 },
143 state: STATE_COMMON,
144 };
145
146 /// `ffxApiGetResourceDX12` of a 2D texture in the D3D12 state `state`.
147 fn texture(texture: &ID3D12Resource, state: u32) -> Resource {
148 // SAFETY: a live resource.
149 let desc = unsafe { texture.GetDesc() };
150 let depth = match desc.Format {
151 DXGI_FORMAT_D16_UNORM | DXGI_FORMAT_D32_FLOAT => USAGE_DEPTHTARGET,
152 DXGI_FORMAT_D24_UNORM_S8_UINT | DXGI_FORMAT_D32_FLOAT_S8X24_UINT => USAGE_DEPTHTARGET | USAGE_STENCILTARGET,
153 _ => 0,
154 };
155 let uav = if desc.Flags.contains(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) { USAGE_UAV } else { 0 };
156 Resource {
157 resource: texture.as_raw(),
158 description: ResourceDescription {
159 kind: TYPE_TEXTURE2D,
160 format: surface_format(desc.Format),
161 width: desc.Width as u32,
162 height: desc.Height,
163 depth: u32::from(desc.DepthOrArraySize),
164 mip_count: u32::from(desc.MipLevels),
165 flags: 0,
166 usage: depth | uav,
167 },
168 state: ffx_state(state),
169 }
170 }
171}
172
173#[repr(C)]
174struct CreateSwapChainForHwnd {
175 header: Header,
176 swap_chain: *mut *mut c_void,
177 hwnd: HWND,
178 desc: *const DXGI_SWAP_CHAIN_DESC1,
179 fullscreen: *const c_void,
180 factory: *mut c_void,
181 queue: *mut c_void,
182}
183
184/// A header and one 32-bit word (a version, or the format of the colour without the interface).
185#[repr(C)]
186struct Version {
187 header: Header,
188 version: u32,
189}
190
191#[repr(C)]
192struct CreateFrameGeneration {
193 header: Header,
194 flags: u32,
195 display_size: Dims,
196 max_render_size: Dims,
197 back_buffer_format: u32,
198}
199
200#[repr(C)]
201struct CreateBackend {
202 header: Header,
203 device: *mut c_void,
204}
205
206type FrameGenerationCallback = unsafe extern "C" fn(params: *mut Header, user: *mut c_void) -> u32;
207
208#[repr(C)]
209struct ConfigureFrameGeneration {
210 header: Header,
211 swap_chain: *mut c_void,
212 present_callback: *const c_void,
213 present_callback_user: *mut c_void,
214 frame_generation_callback: Option<FrameGenerationCallback>,
215 frame_generation_callback_user: *mut c_void,
216 frame_generation_enabled: bool,
217 allow_async_workloads: bool,
218 hudless_color: Resource,
219 flags: u32,
220 only_present_generated: bool,
221 generation_rect: Rect,
222 frame_id: u64,
223}
224
225#[repr(C)]
226struct PrepareV2 {
227 header: Header,
228 frame_id: u64,
229 flags: u32,
230 command_list: *mut c_void,
231 render_size: Dims,
232 jitter_offset: Floats,
233 motion_vector_scale: Floats,
234 frame_time_delta: f32,
235 reset: bool,
236 camera_near: f32,
237 camera_far: f32,
238 camera_fov_angle_vertical: f32,
239 view_space_to_meters_factor: f32,
240 depth: Resource,
241 motion_vectors: Resource,
242 camera_position: [f32; 3],
243 camera_up: [f32; 3],
244 camera_right: [f32; 3],
245 camera_forward: [f32; 3],
246}
247
248type Context = *mut c_void;
249type Create = unsafe extern "C" fn(context: *mut Context, desc: *mut Header, memory: *const c_void) -> u32;
250type Destroy = unsafe extern "C" fn(context: *mut Context, memory: *const c_void) -> u32;
251type Configure = unsafe extern "C" fn(context: *mut Context, desc: *const Header) -> u32;
252type Dispatch = unsafe extern "C" fn(context: *mut Context, desc: *const Header) -> u32;
253
254/// A loaded DLL, let go with its owner.
255struct Library(windows_sys::Win32::Foundation::HMODULE);
256
257impl Drop for Library {
258 fn drop(&mut self) {
259 // SAFETY: this owns the reference `LoadLibraryExW` took.
260 unsafe { windows_sys::Win32::Foundation::FreeLibrary(self.0) };
261 }
262}
263
264// SAFETY: a module handle, valid on every thread.
265unsafe impl Send for Library {}
266// SAFETY: as above; nothing is changed through it.
267unsafe impl Sync for Library {}
268
269/// The loader's exports, with the two DLLs held for the run.
270struct Ffx {
271 _framegen: Library,
272 _loader: Library,
273 create: Create,
274 destroy: Destroy,
275 configure: Configure,
276 dispatch: Dispatch,
277}
278
279static FFX: OnceLock<Ffx> = OnceLock::new();
280/// The presenter's swap chain is FidelityFX's.
281static SWAP_CHAIN: AtomicBool = AtomicBool::new(false);
282/// Generation ran at the last present.
283static ON: AtomicBool = AtomicBool::new(false);
284/// Presents so far (for how often the switch is read).
285static PRESENTS: AtomicU32 = AtomicU32::new(0);
286/// `LEONIDA_FSR_FRAMEGEN` as last read ([`wanted_now`]).
287static WANTED: AtomicBool = AtomicBool::new(true);
288// Since the last line of counts: presents with generation on and off, prepare dispatches that failed, and presents
289// given the colour without the interface.
290static PRESENTS_ON: AtomicU64 = AtomicU64::new(0);
291static PRESENTS_OFF: AtomicU64 = AtomicU64::new(0);
292static FAILED: AtomicU64 = AtomicU64::new(0);
293static HUDLESS_GIVEN: AtomicU64 = AtomicU64::new(0);
294
295/// What a context was made for: display size, largest render size, back buffer format, flags, and the format of
296/// the colour without the interface (unknown: none).
297type MadeFor = ([u32; 2], [u32; 2], DXGI_FORMAT, u32, DXGI_FORMAT);
298
299/// What is kept from present to present: the contexts (boxed: their addresses are handed out, the frame generation
300/// one to the swap chain's callback), what the frame generation context was made for, and the frame ids.
301struct Live {
302 swap_chain_context: Box<Context>,
303 /// The swap chain (not a reference of ours: the presenter holds it).
304 swap_chain: *mut c_void,
305 framegen: Option<(Box<Context>, MadeFor)>,
306 frame_id: u64,
307 /// The frame generation context could not be made for these sizes.
308 refused: Option<([u32; 2], [u32; 2])>,
309 /// When the last fresh inputs were handed over (for the frame time FidelityFX is told).
310 last_fresh: Option<Instant>,
311}
312
313// SAFETY: FidelityFX contexts, used under the lock by one thread at a time.
314unsafe impl Send for Live {}
315
316static LIVE: Mutex<Option<Live>> = Mutex::new(None);
317
318fn live() -> std::sync::MutexGuard<'static, Option<Live>> {
319 LIVE.lock().unwrap_or_else(|e| e.into_inner())
320}
321
322macro_rules! once {
323 ($level:ident, $($arg:tt)*) => {{
324 static ONCE: std::sync::Once = std::sync::Once::new();
325 ONCE.call_once(|| tracing::$level!($($arg)*));
326 }};
327}
328
329/// `LEONIDA_FSR_FRAMEGEN=1` at the start.
330fn asked() -> bool {
331 static ASKED: OnceLock<bool> = OnceLock::new();
332 *ASKED.get_or_init(|| std::env::var("LEONIDA_FSR_FRAMEGEN").is_ok_and(|v| v.trim() == "1"))
333}
334
335/// Whether generation is wanted now: the F1 menu unsets `LEONIDA_FSR_FRAMEGEN` to turn it off while running. Read
336/// at the first present and every eighth after it.
337fn wanted_now() -> bool {
338 let n = PRESENTS.fetch_add(1, Relaxed);
339 if n.is_multiple_of(8) {
340 WANTED.store(std::env::var("LEONIDA_FSR_FRAMEGEN").is_ok_and(|v| v.trim() == "1"), Relaxed);
341 }
342 WANTED.load(Relaxed)
343}
344
345/// `LEONIDA_FIDELITYFX_DIR`, or a `fidelityfx` folder beside our exe.
346fn dir() -> PathBuf {
347 match std::env::var_os("LEONIDA_FIDELITYFX_DIR").filter(|v| !v.is_empty()) {
348 Some(dir) => PathBuf::from(dir),
349 None => std::env::current_exe()
350 .ok()
351 .and_then(|exe| exe.parent().map(|d| d.join("fidelityfx")))
352 .unwrap_or_else(|| PathBuf::from("fidelityfx")),
353 }
354}
355
356fn wide(path: &Path) -> Vec<u16> {
357 use std::os::windows::ffi::OsStrExt;
358 path.as_os_str().encode_wide().chain([0]).collect()
359}
360
361/// Whether the file at `path` carries a valid Authenticode signature (Windows' own check, no network).
362fn verify_signature(path: &Path) -> Result<(), String> {
363 use windows_sys::Win32::Security::WinTrust::*;
364 let file = wide(path);
365 let mut info = WINTRUST_FILE_INFO {
366 cbStruct: size_of::<WINTRUST_FILE_INFO>() as u32,
367 pcwszFilePath: file.as_ptr(),
368 hFile: std::ptr::null_mut(),
369 pgKnownSubject: std::ptr::null_mut(),
370 };
371 let mut data = WINTRUST_DATA {
372 cbStruct: size_of::<WINTRUST_DATA>() as u32,
373 dwUIChoice: WTD_UI_NONE,
374 fdwRevocationChecks: WTD_REVOKE_NONE,
375 dwUnionChoice: WTD_CHOICE_FILE,
376 Anonymous: WINTRUST_DATA_0 { pFile: &mut info },
377 dwStateAction: WTD_STATEACTION_VERIFY,
378 dwProvFlags: WTD_CACHE_ONLY_URL_RETRIEVAL | WTD_REVOCATION_CHECK_NONE,
379 ..Default::default()
380 };
381 let mut action = WINTRUST_ACTION_GENERIC_VERIFY_V2;
382 // SAFETY: filled structures that live through both calls.
383 let code = unsafe { WinVerifyTrust(std::ptr::null_mut(), &mut action, (&raw mut data).cast()) };
384 data.dwStateAction = WTD_STATEACTION_CLOSE;
385 // SAFETY: as above; closes the state the first call opened.
386 unsafe { WinVerifyTrust(std::ptr::null_mut(), &mut action, (&raw mut data).cast()) };
387 if code == 0 { Ok(()) } else { Err(format!("{} is not validly signed ({:#x})", path.display(), code as u32)) }
388}
389
390/// Loads AMD's DLLs from `dir`, signatures checked first.
391fn load(dir: &Path) -> Result<Ffx, String> {
392 use windows_sys::Win32::System::LibraryLoader::{
393 GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
394 };
395 let open = |name: &str| -> Result<Library, String> {
396 let path = dir.join(name);
397 if !path.is_file() {
398 return Err(format!("{} is missing", path.display()));
399 }
400 verify_signature(&path)?;
401 let file = wide(&path);
402 // Its own folder and System32 only, never the current folder.
403 // SAFETY: a NUL-terminated full path.
404 let module = unsafe {
405 LoadLibraryExW(file.as_ptr(), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32)
406 };
407 if module.is_null() {
408 return Err(format!("{name} did not load ({})", std::io::Error::last_os_error()));
409 }
410 Ok(Library(module))
411 };
412 // The effect first, by its full path: the loader then finds it loaded.
413 let framegen = open(FRAMEGEN)?;
414 let loader = open(LOADER)?;
415 let module = loader.0;
416 let find = |name: &CStr| {
417 // SAFETY: a loaded module and a NUL-terminated name.
418 unsafe { GetProcAddress(module, name.as_ptr().cast()) }
419 .map(|f| f as *const c_void)
420 .ok_or_else(|| format!("{LOADER} has no {}", name.to_string_lossy()))
421 };
422 macro_rules! get {
423 ($name:literal, $t:ty) => {
424 // SAFETY: the export of that name has the header's signature.
425 unsafe { std::mem::transmute::<*const c_void, $t>(find($name)?) }
426 };
427 }
428 Ok(Ffx {
429 create: get!(c"ffxCreateContext", Create),
430 destroy: get!(c"ffxDestroyContext", Destroy),
431 configure: get!(c"ffxConfigure", Configure),
432 dispatch: get!(c"ffxDispatch", Dispatch),
433 _loader: loader,
434 _framegen: framegen,
435 })
436}
437
438/// Whether the presents go through FidelityFX's swap chain (upscales then hand their inputs over, and the F1 menu's
439/// switch applies at once).
440pub(crate) fn live_swap_chain() -> bool {
441 SWAP_CHAIN.load(Acquire)
442}
443
444/// Frames shown for each one rendered while generation runs (2), else `None`.
445pub(crate) fn shown_per_frame() -> Option<u32> {
446 (SWAP_CHAIN.load(Relaxed) && ON.load(Relaxed)).then_some(2)
447}
448
449/// The presenter's swap chain made by FidelityFX for `hwnd` on `queue` (its frame interpolation swap chain), or
450/// `None` to make it as before: not asked for, Streamline's swap chain has the presents, or something failed (then
451/// logged).
452pub(crate) fn swap_chain(
453 factory: &IDXGIFactory2,
454 queue: &ID3D12CommandQueue,
455 hwnd: HWND,
456 desc: &DXGI_SWAP_CHAIN_DESC1,
457) -> Option<IDXGISwapChain3> {
458 if !asked() {
459 return None;
460 }
461 if crate::fg::active() {
462 tracing::info!("FSR 3 frame generation stays off: DLSS Frame Generation has the presents");
463 return None;
464 }
465 let ffx = match FFX.get() {
466 Some(ffx) => ffx,
467 None => {
468 let folder = dir();
469 match load(&folder) {
470 Ok(ffx) => {
471 tracing::info!(folder = %folder.display(), "FSR 3 frame generation: AMD's FidelityFX DLLs loaded (signatures valid)");
472 FFX.get_or_init(|| ffx)
473 }
474 Err(why) => {
475 tracing::warn!(folder = %folder.display(), "FSR 3 frame generation: {why}; it stays off (LEONIDA_FIDELITYFX_DIR)");
476 return None;
477 }
478 }
479 }
480 };
481 let mut made: *mut c_void = std::ptr::null_mut();
482 let mut version = Version { header: Header::new(CREATE_SWAPCHAIN_VERSION_DX12), version: SWAPCHAIN_VERSION };
483 let mut create = CreateSwapChainForHwnd {
484 header: Header::new(CREATE_SWAPCHAIN_FOR_HWND_DX12),
485 swap_chain: &mut made,
486 hwnd,
487 desc,
488 fullscreen: std::ptr::null(),
489 factory: factory.as_raw(),
490 queue: queue.as_raw(),
491 };
492 create.header.next = (&raw mut version).cast();
493 let mut context: Box<Context> = Box::new(std::ptr::null_mut());
494 // SAFETY: filled descriptions that live through the call.
495 let code = unsafe { (ffx.create)(&mut *context, (&raw mut create).cast(), std::ptr::null()) };
496 if code != OK || made.is_null() {
497 tracing::warn!(code, "FSR 3 frame generation: FidelityFX did not make the swap chain; made as before, generation off");
498 return None;
499 }
500 // SAFETY: the swap chain FidelityFX made, with the reference it gave us.
501 let swap_chain = unsafe { IDXGISwapChain4::from_raw(made) };
502 let swap_chain = match swap_chain.cast::<IDXGISwapChain3>() {
503 Ok(s) => s,
504 Err(e) => {
505 tracing::warn!(error = %e, "FSR 3 frame generation: the swap chain has no IDXGISwapChain3");
506 return None;
507 }
508 };
509 *live() = Some(Live {
510 swap_chain_context: context,
511 swap_chain: swap_chain.as_raw(),
512 framegen: None,
513 frame_id: 0,
514 refused: None,
515 last_fresh: None,
516 });
517 SWAP_CHAIN.store(true, Release);
518 tracing::info!(
519 width = desc.Width,
520 height = desc.Height,
521 format = desc.Format.0,
522 "FSR 3 frame generation: the swap chain is FidelityFX's frame interpolation swap chain"
523 );
524 Some(swap_chain)
525}
526
527/// The swap chain's buffers are about to be made again (everything sent has run): the frame generation context
528/// goes, and is made again for the new size at the next present with an upscale.
529pub(crate) fn resizing() {
530 let Some(ffx) = FFX.get() else { return };
531 let mut live = live();
532 if let Some(live) = live.as_mut()
533 && retire(ffx, live)
534 {
535 tracing::info!("FSR 3 frame generation: its context goes with the swap chain's buffers");
536 }
537}
538
539/// The frame generation context goes: the swap chain is told to stop calling it and its presents in flight are
540/// waited for first. Whether there was one.
541fn retire(ffx: &Ffx, live: &mut Live) -> bool {
542 let Some((mut context, _)) = live.framegen.take() else { return false };
543 live.frame_id += 1;
544 let mut off = ConfigureFrameGeneration {
545 header: Header::new(CONFIGURE_FRAMEGENERATION),
546 swap_chain: live.swap_chain,
547 present_callback: std::ptr::null(),
548 present_callback_user: std::ptr::null_mut(),
549 frame_generation_callback: None,
550 frame_generation_callback_user: std::ptr::null_mut(),
551 frame_generation_enabled: false,
552 allow_async_workloads: false,
553 hudless_color: Resource::NONE,
554 flags: 0,
555 only_present_generated: false,
556 generation_rect: Rect::default(),
557 frame_id: live.frame_id,
558 };
559 let mut wait = Header::new(DISPATCH_WAIT_FOR_PRESENTS_DX12);
560 // SAFETY: our contexts and filled descriptions; nothing of ours uses the frame generation context after this.
561 unsafe {
562 (ffx.configure)(&mut *context, (&raw mut off).cast());
563 (ffx.dispatch)(&mut *live.swap_chain_context, &raw mut wait);
564 (ffx.destroy)(&mut *context, std::ptr::null());
565 }
566 live.refused = None;
567 ON.store(false, Relaxed);
568 true
569}
570
571/// The swap chain's call to generate a frame: the dispatch goes to the frame generation context it was configured
572/// with.
573unsafe extern "C" fn generate(params: *mut Header, user: *mut c_void) -> u32 {
574 let Some(ffx) = FFX.get() else { return 1 };
575 // SAFETY: `user` is the boxed frame generation context the configuration named; `params` the swap chain's
576 // dispatch description.
577 unsafe { (ffx.dispatch)(user.cast(), params) }
578}
579
580/// Into `list` (the presenter's last list before `Present`, on the swap chain's queue): with a fresh upscale, the
581/// frame's prepare dispatch from its depth and motion vectors, then the frame's configuration (generation on or
582/// off) for the back buffer of `size` and `format`. `hudless` is the colour without the interface and its state
583/// (Series S's base plane), if there is one. `keep` holds a texture until `list` has run.
584pub(crate) fn before_present(
585 device: &ID3D12Device,
586 swap_chain: &IDXGISwapChain3,
587 list: &ID3D12GraphicsCommandList,
588 size: [u32; 2],
589 format: DXGI_FORMAT,
590 hudless: Option<(&ID3D12Resource, u32)>,
591 keep: &dyn Fn(&ID3D12Resource),
592) {
593 if !SWAP_CHAIN.load(Acquire) {
594 return;
595 }
596 let Some(ffx) = FFX.get() else { return };
597 let wanted = wanted_now();
598 // Of the back buffer's size only (FidelityFX compares the two pixel by pixel).
599 let hudless = hudless.filter(|(t, _)| {
600 // SAFETY: a live texture.
601 let desc = unsafe { t.GetDesc() };
602 let same = [desc.Width as u32, desc.Height] == size;
603 if !same {
604 once!(info, 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");
605 }
606 same
607 });
608 let hudless_format = hudless.map_or(DXGI_FORMAT_UNKNOWN, |(t, _)| {
609 // SAFETY: a live texture.
610 unsafe { t.GetDesc() }.Format
611 });
612 // Taken at every present, even with generation off: left waiting, the first present after it is turned on
613 // again would generate from old inputs.
614 let fresh = crate::fg::inputs_for_present().filter(|i| i.fresh && wanted);
615 let mut guard = live();
616 let Some(live) = guard.as_mut() else { return };
617 if let Some(inputs) = &fresh {
618 let render = inputs.render;
619 let flags = create_flags(inputs.near > inputs.far, format);
620 // A context made for other sizes or formats goes first (a frame without its colour without the
621 // interface keeps the context as it is).
622 let stale = live.framegen.as_ref().is_some_and(|(_, (s, r, f, fl, h))| {
623 *s != size || r[0] < render[0] || r[1] < render[1] || *f != format || *fl != flags || (hudless_format != DXGI_FORMAT_UNKNOWN && *h != hudless_format)
624 });
625 if stale {
626 // Everything sent so far is waited for: what was recorded with the old context has run.
627 crate::host::settle_now(crate::host::WHY_SYNC);
628 retire(ffx, live);
629 tracing::info!(display = ?size, max_render = ?render, "FSR 3 frame generation: its context is made again for other sizes");
630 }
631 if live.framegen.is_none() && live.refused != Some((size, render)) {
632 match create_context(ffx, device, size, render, format, flags, hudless_format) {
633 Some(context) => {
634 tracing::info!(
635 display = ?size,
636 max_render = ?render,
637 format = format.0,
638 hudless_format = hudless_format.0,
639 flags = format_args!("{flags:#x}"),
640 "FSR 3 frame generation: its context was made"
641 );
642 live.framegen = Some((context, (size, render, format, flags, hudless_format)));
643 live.refused = None;
644 }
645 None => live.refused = Some((size, render)),
646 }
647 }
648 }
649 let Some((context, _)) = live.framegen.as_mut() else {
650 PRESENTS_OFF.fetch_add(1, Relaxed);
651 return;
652 };
653 live.frame_id += 1;
654 let frame_id = live.frame_id;
655 let debug = debug_flags();
656 let mut prepared = false;
657 if let Some(inputs) = &fresh {
658 let now = Instant::now();
659 let frame_ms = live.last_fresh.map_or(16.7, |t| (now - t).as_secs_f32() * 1000.0).clamp(1.0, 1000.0);
660 live.last_fresh = Some(now);
661 keep(&inputs.depth.0);
662 keep(&inputs.motion.0);
663 let mut prepare = PrepareV2 {
664 header: Header::new(DISPATCH_PREPARE_V2),
665 frame_id,
666 flags: debug,
667 command_list: list.as_raw(),
668 render_size: inputs.render.into(),
669 jitter_offset: Floats { x: inputs.jitter[0], y: inputs.jitter[1] },
670 motion_vector_scale: Floats { x: inputs.mv_pixels[0], y: inputs.mv_pixels[1] },
671 frame_time_delta: frame_ms,
672 reset: inputs.reset,
673 // As the title gives them to its upscaler (FidelityFX's terms: near and far swapped with inverted depth).
674 camera_near: inputs.near,
675 camera_far: inputs.far,
676 camera_fov_angle_vertical: FOV_Y_DEGREES.to_radians(),
677 view_space_to_meters_factor: 1.0,
678 depth: Resource::texture(&inputs.depth.0, inputs.depth.1),
679 motion_vectors: Resource::texture(&inputs.motion.0, inputs.motion.1),
680 camera_position: [0.0; 3],
681 camera_up: [0.0, 1.0, 0.0],
682 camera_right: [1.0, 0.0, 0.0],
683 camera_forward: [0.0, 0.0, 1.0],
684 };
685 // SAFETY: our context and a filled description of live textures in the states they are in when `list` runs.
686 let code = unsafe { (ffx.dispatch)(&mut **context, (&raw mut prepare).cast()) };
687 if code == OK {
688 prepared = true;
689 once!(
690 info,
691 render = ?inputs.render,
692 back_buffer = ?size,
693 depth_state = format_args!("{:#x}", inputs.depth.1),
694 motion_state = format_args!("{:#x}", inputs.motion.1),
695 near = inputs.near,
696 far = inputs.far,
697 jitter = ?inputs.jitter,
698 mv_scale = ?inputs.mv_pixels,
699 frame_ms,
700 "FSR 3 frame generation: first frame prepared from depth and motion vectors"
701 );
702 } else {
703 FAILED.fetch_add(1, Relaxed);
704 once!(warn, code, "FSR 3 frame generation: the prepare dispatch failed");
705 }
706 }
707 let on = prepared && wanted;
708 if let Some((texture, _)) = hudless.filter(|_| on) {
709 keep(texture);
710 }
711 let mut configure = ConfigureFrameGeneration {
712 header: Header::new(CONFIGURE_FRAMEGENERATION),
713 swap_chain: swap_chain.as_raw(),
714 present_callback: std::ptr::null(),
715 present_callback_user: std::ptr::null_mut(),
716 frame_generation_callback: Some(generate),
717 frame_generation_callback_user: (&raw mut **context).cast(),
718 frame_generation_enabled: on,
719 allow_async_workloads: false,
720 hudless_color: match hudless {
721 Some((texture, state)) if on => Resource::texture(texture, state),
722 _ => Resource::NONE,
723 },
724 flags: debug,
725 only_present_generated: false,
726 generation_rect: Rect { left: 0, top: 0, width: size[0] as i32, height: size[1] as i32 },
727 frame_id,
728 };
729 // SAFETY: our context and a filled description.
730 let code = unsafe { (ffx.configure)(&mut **context, (&raw mut configure).cast()) };
731 if code != OK {
732 once!(warn, code, "FSR 3 frame generation: the configuration failed");
733 }
734 let on = on && code == OK;
735 if ON.swap(on, Relaxed) != on {
736 tracing::info!(on, frame_id, "FSR 3 frame generation switched");
737 }
738 if on {
739 PRESENTS_ON.fetch_add(1, Relaxed);
740 if hudless.is_some() {
741 HUDLESS_GIVEN.fetch_add(1, Relaxed);
742 once!(info, "FSR 3 frame generation: first frame with the colour without the interface");
743 }
744 } else {
745 PRESENTS_OFF.fetch_add(1, Relaxed);
746 }
747 let presents = PRESENTS.load(Relaxed);
748 if presents.is_multiple_of(600) {
749 tracing::info!(
750 on = PRESENTS_ON.swap(0, Relaxed),
751 off = PRESENTS_OFF.swap(0, Relaxed),
752 failed = FAILED.swap(0, Relaxed),
753 hudless = HUDLESS_GIVEN.swap(0, Relaxed),
754 "FSR 3 frame generation: presents with it on and off, failed prepares and presents given the colour without the interface, since the last line"
755 );
756 }
757}
758
759fn create_context(
760 ffx: &Ffx,
761 device: &ID3D12Device,
762 size: [u32; 2],
763 render: [u32; 2],
764 format: DXGI_FORMAT,
765 flags: u32,
766 hudless_format: DXGI_FORMAT,
767) -> Option<Box<Context>> {
768 let mut backend = CreateBackend { header: Header::new(CREATE_BACKEND_DX12), device: device.as_raw() };
769 // The colour without the interface in a format of its own (else the back buffer's is assumed).
770 let own_hudless = hudless_format != DXGI_FORMAT_UNKNOWN && hudless_format != format;
771 let mut hudless = Version { header: Header::new(CREATE_FRAMEGENERATION_HUDLESS), version: surface_format(hudless_format) };
772 hudless.header.next = (&raw mut backend).cast();
773 let after_version: *mut Header = if own_hudless { (&raw mut hudless).cast() } else { (&raw mut backend).cast() };
774 let mut version = Version { header: Header::new(CREATE_FRAMEGENERATION_VERSION), version: FRAMEGENERATION_VERSION };
775 version.header.next = after_version;
776 let mut create = CreateFrameGeneration {
777 header: Header::new(CREATE_FRAMEGENERATION),
778 flags,
779 display_size: size.into(),
780 max_render_size: render.into(),
781 back_buffer_format: surface_format(format),
782 };
783 create.header.next = (&raw mut version).cast();
784 let mut context: Box<Context> = Box::new(std::ptr::null_mut());
785 // SAFETY: filled descriptions that live through the call.
786 let code = unsafe { (ffx.create)(&mut *context, (&raw mut create).cast(), std::ptr::null()) };
787 if code != OK || context.is_null() {
788 tracing::warn!(code, display = ?size, max_render = ?render, format = format.0, "FSR 3 frame generation: its context was not made; presents stay plain");
789 return None;
790 }
791 Some(context)
792}
793
794/// The context's flags: inverted depth (the upscale's near beyond its far, as [`crate::fg`] reads it), and high
795/// dynamic range for a float back buffer only (what is presented is after the title's tone mapping).
796fn create_flags(depth_inverted: bool, format: DXGI_FORMAT) -> u32 {
797 let mut flags = 0;
798 if depth_inverted {
799 flags |= FG_DEPTH_INVERTED;
800 }
801 if format == DXGI_FORMAT_R16G16B16A16_FLOAT {
802 flags |= FG_HIGH_DYNAMIC_RANGE;
803 }
804 flags
805}
806
807/// `LEONIDA_FSR_FRAMEGEN_DEBUG=1`: tear and pacing lines drawn.
808fn debug_flags() -> u32 {
809 static FLAGS: OnceLock<u32> = OnceLock::new();
810 *FLAGS.get_or_init(|| {
811 if std::env::var("LEONIDA_FSR_FRAMEGEN_DEBUG").is_ok_and(|v| v.trim() == "1") {
812 FG_DRAW_DEBUG_TEAR_LINES | FG_DRAW_DEBUG_PACING_LINES
813 } else {
814 0
815 }
816 })
817}
818
819/// A D3D12 state as FidelityFX names it.
820fn ffx_state(state: u32) -> u32 {
821 let s = D3D12_RESOURCE_STATES(state as i32);
822 if s == D3D12_RESOURCE_STATE_COMMON {
823 return STATE_COMMON;
824 }
825 let pairs = [
826 (D3D12_RESOURCE_STATE_UNORDERED_ACCESS, STATE_UNORDERED_ACCESS),
827 (D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, STATE_COMPUTE_READ),
828 (D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, STATE_PIXEL_READ),
829 (D3D12_RESOURCE_STATE_COPY_SOURCE, STATE_COPY_SRC),
830 (D3D12_RESOURCE_STATE_COPY_DEST, STATE_COPY_DEST),
831 (D3D12_RESOURCE_STATE_RENDER_TARGET, STATE_RENDER_TARGET),
832 (D3D12_RESOURCE_STATE_DEPTH_WRITE, STATE_DEPTH_ATTACHMENT),
833 (D3D12_RESOURCE_STATE_DEPTH_READ, STATE_DEPTH_ATTACHMENT),
834 ];
835 let out = pairs.iter().filter(|(d3d, _)| s.contains(*d3d)).fold(0, |out, (_, ffx)| out | ffx);
836 if out == 0 { STATE_COMMON } else { out }
837}
838
839/// `ffxApiGetSurfaceFormatDX12`.
840fn surface_format(format: DXGI_FORMAT) -> u32 {
841 match format {
842 DXGI_FORMAT_R32G32B32A32_TYPELESS => 1,
843 DXGI_FORMAT_R32G32B32A32_UINT => 2,
844 DXGI_FORMAT_R32G32B32A32_FLOAT => 3,
845 DXGI_FORMAT_R16G16B16A16_FLOAT => 4,
846 DXGI_FORMAT_R32G32_FLOAT => 6,
847 DXGI_FORMAT_R8_UINT | DXGI_FORMAT_X32_TYPELESS_G8X24_UINT | DXGI_FORMAT_X24_TYPELESS_G8_UINT => 7,
848 DXGI_FORMAT_R32_UINT | DXGI_FORMAT_R24G8_TYPELESS | DXGI_FORMAT_D24_UNORM_S8_UINT | DXGI_FORMAT_R24_UNORM_X8_TYPELESS => 8,
849 DXGI_FORMAT_R8G8B8A8_TYPELESS => 9,
850 DXGI_FORMAT_R8G8B8A8_UNORM => 10,
851 DXGI_FORMAT_R8G8B8A8_SNORM => 11,
852 DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => 12,
853 DXGI_FORMAT_B8G8R8A8_TYPELESS => 13,
854 DXGI_FORMAT_B8G8R8A8_UNORM => 14,
855 DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => 15,
856 DXGI_FORMAT_R11G11B10_FLOAT => 16,
857 DXGI_FORMAT_R10G10B10A2_UNORM => 17,
858 DXGI_FORMAT_R16G16_FLOAT => 18,
859 DXGI_FORMAT_R16G16_UINT => 19,
860 DXGI_FORMAT_R16_FLOAT => 21,
861 DXGI_FORMAT_R16_UINT => 22,
862 DXGI_FORMAT_R16_UNORM | DXGI_FORMAT_D16_UNORM => 23,
863 DXGI_FORMAT_R16_SNORM => 24,
864 DXGI_FORMAT_R8_UNORM | DXGI_FORMAT_A8_UNORM => 25,
865 DXGI_FORMAT_R8G8_UNORM => 26,
866 DXGI_FORMAT_R8G8_UINT => 27,
867 DXGI_FORMAT_R32_FLOAT
868 | DXGI_FORMAT_D32_FLOAT
869 | DXGI_FORMAT_R32G8X24_TYPELESS
870 | DXGI_FORMAT_D32_FLOAT_S8X24_UINT
871 | DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS => 28,
872 DXGI_FORMAT_R9G9B9E5_SHAREDEXP => 29,
873 DXGI_FORMAT_R16G16B16A16_TYPELESS => 30,
874 DXGI_FORMAT_R32G32_TYPELESS => 31,
875 DXGI_FORMAT_R10G10B10A2_TYPELESS => 32,
876 DXGI_FORMAT_R16G16_TYPELESS => 33,
877 DXGI_FORMAT_R16_TYPELESS => 34,
878 DXGI_FORMAT_R8_TYPELESS => 35,
879 DXGI_FORMAT_R8G8_TYPELESS => 36,
880 DXGI_FORMAT_R32_TYPELESS => 37,
881 DXGI_FORMAT_R8_SNORM => 39,
882 _ => 0,
883 }
884}
885
886#[cfg(test)]
887mod tests {
888 use super::*;
889
890 #[test]
891 fn layouts_match_the_headers() {
892 // x64 sizes and offsets of the C structures (FidelityFX SDK 2.x headers).
893 assert_eq!(size_of::<Header>(), 16);
894 assert_eq!(size_of::<ResourceDescription>(), 32);
895 assert_eq!(size_of::<Resource>(), 48);
896 assert_eq!(size_of::<CreateFrameGeneration>(), 40);
897 assert_eq!(size_of::<CreateSwapChainForHwnd>(), 64);
898 assert_eq!(std::mem::offset_of!(ConfigureFrameGeneration, hudless_color), 64);
899 assert_eq!(std::mem::offset_of!(ConfigureFrameGeneration, generation_rect), 120);
900 assert_eq!(std::mem::offset_of!(ConfigureFrameGeneration, frame_id), 136);
901 assert_eq!(size_of::<ConfigureFrameGeneration>(), 144);
902 assert_eq!(std::mem::offset_of!(PrepareV2, command_list), 32);
903 assert_eq!(std::mem::offset_of!(PrepareV2, frame_time_delta), 64);
904 assert_eq!(std::mem::offset_of!(PrepareV2, camera_near), 72);
905 assert_eq!(std::mem::offset_of!(PrepareV2, depth), 88);
906 assert_eq!(std::mem::offset_of!(PrepareV2, camera_position), 184);
907 assert_eq!(size_of::<PrepareV2>(), 232);
908 }
909
910 #[test]
911 fn states_and_formats() {
912 assert_eq!(ffx_state(0), STATE_COMMON);
913 assert_eq!(ffx_state(0x8), STATE_UNORDERED_ACCESS);
914 assert_eq!(ffx_state(0xC0), STATE_COMPUTE_READ | STATE_PIXEL_READ);
915 assert_eq!(ffx_state(0x20), STATE_DEPTH_ATTACHMENT);
916 assert_eq!(ffx_state(0x10), STATE_DEPTH_ATTACHMENT);
917 assert_eq!(surface_format(DXGI_FORMAT_R8G8B8A8_UNORM), 10);
918 assert_eq!(surface_format(DXGI_FORMAT_R10G10B10A2_UNORM), 17);
919 assert_eq!(surface_format(DXGI_FORMAT_R32_TYPELESS), 37);
920 }
921
922 #[test]
923 fn flags_from_depth_and_back_buffer() {
924 assert_eq!(create_flags(false, DXGI_FORMAT_R8G8B8A8_UNORM), 0);
925 assert_eq!(create_flags(true, DXGI_FORMAT_R10G10B10A2_UNORM), FG_DEPTH_INVERTED);
926 assert_eq!(create_flags(true, DXGI_FORMAT_R16G16B16A16_FLOAT), FG_DEPTH_INVERTED | FG_HIGH_DYNAMIC_RANGE);
927 }
928}
diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs
index c71bbe670..e3c420267 100644
--- a/d3d12/crates/leonida-gpu/src/host.rs
+++ b/d3d12/crates/leonida-gpu/src/host.rs
@@ -3904,7 +3904,7 @@ mod sync_callers {
3904} 3904}
3905 3905
3906/// Why flights were settled ([`LATE_STATS`]' places from 2 on). 3906/// Why flights were settled ([`LATE_STATS`]' places from 2 on).
3907const WHY_SYNC: usize = 2; 3907pub(crate) const WHY_SYNC: usize = 2;
3908const WHY_CARD_DONE: usize = 3; 3908const WHY_CARD_DONE: usize = 3;
3909const WHY_VALUE: usize = 4; 3909const WHY_VALUE: usize = 4;
3910const WHY_STALE: usize = 5; 3910const WHY_STALE: usize = 5;
@@ -12675,6 +12675,8 @@ impl Host {
12675 if (p.width, p.height, p.format) != (placed.width, placed.height, format) { 12675 if (p.width, p.height, p.format) != (placed.width, placed.height, format) {
12676 // Presents sent ahead hold back buffers until they have run. 12676 // Presents sent ahead hold back buffers until they have run.
12677 settle_now(WHY_SYNC); 12677 settle_now(WHY_SYNC);
12678 // Leonida: FSR 3 frame generation's context goes with the buffers (made again at the next upscale).
12679 crate::fsr::resizing();
12678 // SAFETY: no back buffer is held; every submission was waited for. 12680 // SAFETY: no back buffer is held; every submission was waited for.
12679 let resized = unsafe { 12681 let resized = unsafe {
12680 p.swap_chain 12682 p.swap_chain
@@ -12932,6 +12934,18 @@ impl Host {
12932 )); 12934 ));
12933 list.ResourceBarrier(&post); 12935 list.ResourceBarrier(&post);
12934 } 12936 }
12937 // Leonida: FSR 3 frame generation's prepare dispatch and configuration for this present (crate::fsr),
12938 // last on the list before `Present`. Series S's base plane is the colour without the interface.
12939 let hudless = (composed && whole).then_some((texture, state_u32));
12940 crate::fsr::before_present(
12941 &self.device,
12942 &p.swap_chain,
12943 list,
12944 [placed.width, placed.height],
12945 format,
12946 hudless,
12947 &|t: &ID3D12Resource| copy.keep(t),
12948 );
12935 copy.close(); 12949 copy.close();
12936 let flown = match slot { 12950 let flown = match slot {
12937 Some(i) => { 12951 Some(i) => {
@@ -13039,9 +13053,14 @@ impl Host {
13039 Flags: chain_flags(tearing).0 as u32, 13053 Flags: chain_flags(tearing).0 as u32,
13040 ..Default::default() 13054 ..Default::default()
13041 }; 13055 };
13042 let swap_chain = factory 13056 // Leonida: with `LEONIDA_FSR_FRAMEGEN=1` (and no Streamline swap chain), FidelityFX's frame interpolation
13043 .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)? 13057 // swap chain (crate::fsr); as before if it cannot be made.
13044 .cast::<IDXGISwapChain3>()?; 13058 let swap_chain = match crate::fsr::swap_chain(&factory, &self.queue, hwnd, &desc) {
13059 Some(swap_chain) => swap_chain,
13060 None => factory
13061 .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
13062 .cast::<IDXGISwapChain3>()?,
13063 };
13045 let copy = self.new_list()?; 13064 let copy = self.new_list()?;
13046 copy.close(); 13065 copy.close();
13047 tracing::info!(width, height, format = format.0, "presenting to a window"); 13066 tracing::info!(width, height, format = format.0, "presenting to a window");
diff --git a/d3d12/crates/leonida-gpu/src/host/menu.rs b/d3d12/crates/leonida-gpu/src/host/menu.rs
index e24d504cd..0abafbb91 100644
--- a/d3d12/crates/leonida-gpu/src/host/menu.rs
+++ b/d3d12/crates/leonida-gpu/src/host/menu.rs
@@ -60,6 +60,9 @@ const ITEMS: &[Item] = &[
60 Item { var: "LEONIDA_RENDER_SCALE", label: "RENDER SCALE (DLSS MODE)", values: &[("", "GAME"), ("0.6667", "0.667 QUALITY"), ("0.6", "0.6 BALANCED"), ("0.5", "0.5 PERFORMANCE"), ("0.3333", "0.333 ULTRA PERF."), ("0.75", "0.75")], live: false }, 60 Item { var: "LEONIDA_RENDER_SCALE", label: "RENDER SCALE (DLSS MODE)", values: &[("", "GAME"), ("0.6667", "0.667 QUALITY"), ("0.6", "0.6 BALANCED"), ("0.5", "0.5 PERFORMANCE"), ("0.3333", "0.333 ULTRA PERF."), ("0.75", "0.75")], live: false },
61 // On Series X the launcher turns DLSS on with it: the generator's depth and motion vectors come from that upscale. 61 // On Series X the launcher turns DLSS on with it: the generator's depth and motion vectors come from that upscale.
62 Item { var: "LEONIDA_FRAME_GEN", label: "FRAME GEN (NOT WITH RAY TR.)", values: &[("", "OFF"), ("2", "2X"), ("3", "3X"), ("4", "4X"), ("5", "5X"), ("6", "6X (MOST)")], live: false }, 62 Item { var: "LEONIDA_FRAME_GEN", label: "FRAME GEN (NOT WITH RAY TR.)", values: &[("", "OFF"), ("2", "2X"), ("3", "3X"), ("4", "4X"), ("5", "5X"), ("6", "6X (MOST)")], live: false },
63 // Leonida: AMD's FSR 3 frame generation (crate::fsr), 2X, for cards without DLSS frame generation (RTX 20 and 30).
64 // Turned on, it applies at the next start (the swap chain is FidelityFX's); off and on again while it runs.
65 Item { var: "LEONIDA_FSR_FRAMEGEN", label: "FSR 3 FRAME GEN 2X (RTX 20/30)", values: UNSET_ON, live: false },
63 // The window's shape, and the game's 16:9 picture in a window of another shape (`crate::aspect`). 66 // The window's shape, and the game's 16:9 picture in a window of another shape (`crate::aspect`).
64 Item { var: "LEONIDA_ASPECT", label: "WINDOW SHAPE", values: &[("", "16:9 (GAME)"), ("21:9", "21:9"), ("32:9", "32:9"), ("auto", "AS THE SCREEN")], live: false }, 67 Item { var: "LEONIDA_ASPECT", label: "WINDOW SHAPE", values: &[("", "16:9 (GAME)"), ("21:9", "21:9"), ("32:9", "32:9"), ("auto", "AS THE SCREEN")], live: false },
65 Item { var: "LEONIDA_PRESENT_SCALE", label: "PICTURE IN ANOTHER SHAPE", values: &[("", "BY WINDOW SHAPE"), ("fit", "BARS"), ("stretch", "STRETCH")], live: true }, 68 Item { var: "LEONIDA_PRESENT_SCALE", label: "PICTURE IN ANOTHER SHAPE", values: &[("", "BY WINDOW SHAPE"), ("fit", "BARS"), ("stretch", "STRETCH")], live: true },
@@ -149,7 +152,9 @@ fn fps_line() -> Option<String> {
149 152
150/// Whether a change of `item` shows at once. 153/// Whether a change of `item` shows at once.
151fn live(item: &Item) -> bool { 154fn live(item: &Item) -> bool {
152 item.live || (item.var == "LEONIDA_FRAME_GEN" && crate::fg::active()) 155 item.live
156 || (item.var == "LEONIDA_FRAME_GEN" && crate::fg::active())
157 || (item.var == "LEONIDA_FSR_FRAMEGEN" && crate::fsr::live_swap_chain())
153} 158}
154 159
155/// The index of `value` among the item's values (an unknown value: shown as 160/// The index of `value` among the item's values (an unknown value: shown as
diff --git a/d3d12/crates/leonida-gpu/src/lib.rs b/d3d12/crates/leonida-gpu/src/lib.rs
index de3036fdc..e3730f8a0 100644
--- a/d3d12/crates/leonida-gpu/src/lib.rs
+++ b/d3d12/crates/leonida-gpu/src/lib.rs
@@ -62,6 +62,9 @@ pub mod aspect;
62pub mod streamline; 62pub mod streamline;
63#[cfg(windows)] 63#[cfg(windows)]
64mod fg; 64mod fg;
65/// Leonida: AMD FSR 3 frame generation where DLSS Frame Generation does not run (`LEONIDA_FSR_FRAMEGEN`).
66#[cfg(windows)]
67mod fsr;
65#[cfg_attr(not(windows), allow(dead_code))] 68#[cfg_attr(not(windows), allow(dead_code))]
66mod smooth; 69mod smooth;
67#[cfg(windows)] 70#[cfg(windows)]
diff --git a/d3d12/crates/leonida-gpu/src/list.rs b/d3d12/crates/leonida-gpu/src/list.rs
index 74c9bc4e9..d640f5cd3 100644
--- a/d3d12/crates/leonida-gpu/src/list.rs
+++ b/d3d12/crates/leonida-gpu/src/list.rs
@@ -1032,7 +1032,7 @@ pub(super) fn upscale_now(this: This, up: &Upscale) -> bool {
1032 done = crate::stretch::record_stretch(&host.device, &list.list, to, from, up.render); 1032 done = crate::stretch::record_stretch(&host.device, &list.list, to, from, up.render);
1033 // Frame generation's inputs from a stretched upscale as well (a DLSS one notes them itself): the 1033 // Frame generation's inputs from a stretched upscale as well (a DLSS one notes them itself): the
1034 // title's depth, motion vectors and jitter are the same whoever makes the output. 1034 // title's depth, motion vectors and jitter are the same whoever makes the output.
1035 if done && crate::fg::active() { 1035 if done && crate::fg::collecting() {
1036 // SAFETY: a live resource. 1036 // SAFETY: a live resource.
1037 let colour = unsafe { from.GetDesc() }; 1037 let colour = unsafe { from.GetDesc() };
1038 crate::fg::tag_plain(up, [colour.Width as u32, colour.Height]); 1038 crate::fg::tag_plain(up, [colour.Width as u32, colour.Height]);
diff --git a/d3d12/scripts/play-nvidia.ps1 b/d3d12/scripts/play-nvidia.ps1
index 33521e530..643f7ea2c 100644
--- a/d3d12/scripts/play-nvidia.ps1
+++ b/d3d12/scripts/play-nvidia.ps1
@@ -23,6 +23,11 @@
23# -NoFrameGen no DLSS frame generation (Smooth Motion instead, if the NVIDIA App has it on for leonida_sm.exe) 23# -NoFrameGen no DLSS frame generation (Smooth Motion instead, if the NVIDIA App has it on for leonida_sm.exe)
24# -MotionBlur the title's own motion blur, left out by default: it blurs by the movement of one frame, so at 24# -MotionBlur the title's own motion blur, left out by default: it blurs by the movement of one frame, so at
25# this port's frame rate its smears are twice as long as at 30 and break into blocks on camera turns 25# this port's frame rate its smears are twice as long as at 30 and break into blocks on camera turns
26# -FsrFrameGen AMD's FSR 3 frame generation instead (twice the frames shown), for cards without DLSS frame
27# generation (RTX 20 and 30). It takes the same depth and motion vectors, and needs AMD's signed
28# amd_fidelityfx_loader_dx12.dll and amd_fidelityfx_framegeneration_dx12.dll in amd-sdk\FidelityFX\bin
29# (or -FidelityFxDir). Also in the F1 menu (FSR 3 FRAME GEN), from the next start.
30# -FidelityFxDir the folder with AMD's two DLLs, if not amd-sdk\FidelityFX\bin
26# -Aspect the window's shape: 21:9, 32:9, 16:9, W:H or auto (the screen's). The game still draws 16:9. 31# -Aspect the window's shape: 21:9, 32:9, 16:9, W:H or auto (the screen's). The game still draws 16:9.
27# -PresentScale fit (the 16:9 picture centred, black bars beside it: the default with -Aspect) or stretch 32# -PresentScale fit (the 16:9 picture centred, black bars beside it: the default with -Aspect) or stretch
28# -Quality fewer stretched/jumping bodies, slower (relay stage 1, no card steps) 33# -Quality fewer stretched/jumping bodies, slower (relay stage 1, no card steps)
@@ -65,6 +70,8 @@ param(
65 [ValidateRange(2, 6)][int]$FrameGen, 70 [ValidateRange(2, 6)][int]$FrameGen,
66 [switch]$NoFrameGen, 71 [switch]$NoFrameGen,
67 [switch]$MotionBlur, 72 [switch]$MotionBlur,
73 [switch]$FsrFrameGen,
74 [string]$FidelityFxDir,
68 [ValidatePattern('^(auto|\d+(\.\d+)?([:x/]\d+(\.\d+)?)?)$')][string]$Aspect, 75 [ValidatePattern('^(auto|\d+(\.\d+)?([:x/]\d+(\.\d+)?)?)$')][string]$Aspect,
69 [ValidateSet('fit', 'stretch')][string]$PresentScale, 76 [ValidateSet('fit', 'stretch')][string]$PresentScale,
70 [string]$Adapter, 77 [string]$Adapter,
@@ -334,6 +341,7 @@ if ($Resolution -or $Lowest) {
334} 341}
335if ($Dlss -and -not $dlssOn) { Write-Host "-Dlss ${Dlss}: no DLSS here (its files, or a build with it): the title's picture is not made by DLSS." } 342if ($Dlss -and -not $dlssOn) { Write-Host "-Dlss ${Dlss}: no DLSS here (its files, or a build with it): the title's picture is not made by DLSS." }
336if ($FrameGen) { $settings.LEONIDA_FRAME_GEN = "$FrameGen" } 343if ($FrameGen) { $settings.LEONIDA_FRAME_GEN = "$FrameGen" }
344if ($FsrFrameGen) { $settings.LEONIDA_FSR_FRAMEGEN = '1' }
337# Leonida: DLSS frame generation twice the frames shown by default on cards that make it (RTX 40 and 50) when its 345# Leonida: DLSS frame generation twice the frames shown by default on cards that make it (RTX 40 and 50) when its
338# Streamline files are here and the title upscales by itself (-Resolution: its depth and motion vectors are the 346# Streamline files are here and the title upscales by itself (-Resolution: its depth and motion vectors are the
339# G-buffer pass's, fg.rs). Series X at -Resolution 1080 on an RTX 4060 Ti (2026-11-28): 15 frames rendered, 29 347# G-buffer pass's, fg.rs). Series X at -Resolution 1080 on an RTX 4060 Ti (2026-11-28): 15 frames rendered, 29
@@ -463,6 +471,30 @@ if ($settings.LEONIDA_FRAME_GEN -and -not $StreamlineDir) {
463 Write-Host 'Frame generation needs the Streamline files (Get-NVIDIA-DLSS.cmd): left off.' 471 Write-Host 'Frame generation needs the Streamline files (Get-NVIDIA-DLSS.cmd): left off.'
464 $settings.Remove('LEONIDA_FRAME_GEN') 472 $settings.Remove('LEONIDA_FRAME_GEN')
465} 473}
474# Leonida: AMD's FSR 3 frame generation (-FsrFrameGen, or the F1 menu's FSR 3 FRAME GEN), in place of DLSS's: never
475# both, and not with ray tracing (as DLSS's). Its DLLs are checked for here; the layer checks their signatures.
476if ($settings.LEONIDA_FSR_FRAMEGEN -eq '1') {
477 if (-not $FidelityFxDir) { $FidelityFxDir = $env:LEONIDA_FIDELITYFX_DIR }
478 if (-not $FidelityFxDir) { $FidelityFxDir = Join-Path $root 'amd-sdk\FidelityFX\bin' }
479 $fsrFiles = 'amd_fidelityfx_loader_dx12.dll', 'amd_fidelityfx_framegeneration_dx12.dll' | ForEach-Object { Join-Path $FidelityFxDir $_ }
480 if ($fsrFiles | Where-Object { -not (Test-Path $_) }) {
481 Write-Host "FSR 3 frame generation needs AMD's amd_fidelityfx_loader_dx12.dll and amd_fidelityfx_framegeneration_dx12.dll"
482 Write-Host "in $FidelityFxDir (the FidelityFX SDK's bin folder, from AMD's GitHub): left off."
483 $settings.Remove('LEONIDA_FSR_FRAMEGEN')
484 } elseif ($settings.LEONIDA_BVH_BUILDER -eq '1' -and $settings.LEONIDA_FG_WITH_RT -ne '1') {
485 Write-Host 'Ray tracing is on: FSR 3 frame generation is left off (as DLSS frame generation is).'
486 $settings.Remove('LEONIDA_FSR_FRAMEGEN')
487 } else {
488 $settings.LEONIDA_FIDELITYFX_DIR = $FidelityFxDir
489 if ($settings.LEONIDA_FRAME_GEN) {
490 Write-Host 'FSR 3 frame generation asked for: DLSS frame generation is left off (one or the other).'
491 $settings.Remove('LEONIDA_FRAME_GEN')
492 }
493 # Generation's own buffers take 1.5 to 2 GB of the card, which the layer otherwise fills with textures: they
494 # are left a fifth of its budget (VIctory-NVIDIA's play.rs does the same for it), unless a share is set.
495 if (-not $settings.LEONIDA_TEXTURE_ROOM_PERCENT) { $settings.LEONIDA_TEXTURE_ROOM_PERCENT = '80' }
496 }
497}
466# Series X: the title upscales with its own upscaler, as passes that hand nothing over. DLSS (or the stretch) 498# Series X: the title upscales with its own upscaler, as passes that hand nothing over. DLSS (or the stretch)
467# can stand in for its FidelityFX upscale instead, which the title is then made to use (LEONIDA_FSR_UPSCALER, the 499# can stand in for its FidelityFX upscale instead, which the title is then made to use (LEONIDA_FSR_UPSCALER, the
468# loader's hooks.rs): only when -Dlss asks for it, because that path lights nothing yet (the world is black with 500# loader's hooks.rs): only when -Dlss asks for it, because that path lights nothing yet (the world is black with
@@ -486,16 +518,17 @@ if ($console -eq 'series-x') {
486} 518}
487# Smooth Motion is a second frame generator: off while DLSS frame generation is on. 519# Smooth Motion is a second frame generator: off while DLSS frame generation is on.
488if ($settings.LEONIDA_FRAME_GEN -and $settings.LEONIDA_FRAME_GEN -ne '1') { $smooth = $false } 520if ($settings.LEONIDA_FRAME_GEN -and $settings.LEONIDA_FRAME_GEN -ne '1') { $smooth = $false }
521if ($settings.LEONIDA_FSR_FRAMEGEN -eq '1') { $smooth = $false }
489# For the menu: what it shows as the current values, where it saves, and how it starts the game again. 522# For the menu: what it shows as the current values, where it saves, and how it starts the game again.
490$settings.LEONIDA_MENU_SMOOTH_MOTION = if ($smooth) { '1' } else { '0' } 523$settings.LEONIDA_MENU_SMOOTH_MOTION = if ($smooth) { '1' } else { '0' }
491$settings.LEONIDA_MENU_CONSOLE = $console 524$settings.LEONIDA_MENU_CONSOLE = $console
492$settings.LEONIDA_MENU_FILE = $menuFile 525$settings.LEONIDA_MENU_FILE = $menuFile
493$settings.LEONIDA_MENU_PLAY = $MyInvocation.MyCommand.Path 526$settings.LEONIDA_MENU_PLAY = $MyInvocation.MyCommand.Path
494$again = @("-Exe '$($Exe -replace "'", "''")'", "-Build $Build") 527$again = @("-Exe '$($Exe -replace "'", "''")'", "-Build $Build")
495foreach ($s in 'NoSmoothMotion', 'NoDlss', 'SeriesX', 'Quality', 'RayTracing', 'NoPrecompile', 'Log', 'Capture') { 528foreach ($s in 'NoSmoothMotion', 'NoDlss', 'SeriesX', 'Quality', 'RayTracing', 'FsrFrameGen', 'NoPrecompile', 'Log', 'Capture') {
496 if ($PSBoundParameters[$s]) { $again += "-$s" } 529 if ($PSBoundParameters[$s]) { $again += "-$s" }
497} 530}
498foreach ($s in 'Resolution', 'Lowest', 'Dlss', 'FrameGen', 'Aspect', 'PresentScale', 'Adapter', 'DlssDir', 'StreamlineDir') { 531foreach ($s in 'Resolution', 'Lowest', 'Dlss', 'FrameGen', 'Aspect', 'PresentScale', 'Adapter', 'DlssDir', 'StreamlineDir', 'FidelityFxDir') {
499 if ($PSBoundParameters[$s]) { $again += "-$s '$($PSBoundParameters[$s] -replace "'", "''")'" } 532 if ($PSBoundParameters[$s]) { $again += "-$s '$($PSBoundParameters[$s] -replace "'", "''")'" }
500} 533}
501if ($PSBoundParameters.ContainsKey('WindowsBarMB')) { $again += "-WindowsBarMB $WindowsBarMB" } 534if ($PSBoundParameters.ContainsKey('WindowsBarMB')) { $again += "-WindowsBarMB $WindowsBarMB" }
@@ -514,6 +547,7 @@ $picture = if ($own -and $settings.LEONIDA_RENDER_SCALE) { "render scale $($sett
514$extras = '' 547$extras = ''
515if ($settings.LEONIDA_ASPECT) { $extras += ", window $($settings.LEONIDA_ASPECT)" } 548if ($settings.LEONIDA_ASPECT) { $extras += ", window $($settings.LEONIDA_ASPECT)" }
516if ($settings.LEONIDA_FRAME_GEN) { $extras += ", frame generation $($settings.LEONIDA_FRAME_GEN)x" } 549if ($settings.LEONIDA_FRAME_GEN) { $extras += ", frame generation $($settings.LEONIDA_FRAME_GEN)x" }
550if ($settings.LEONIDA_FSR_FRAMEGEN -eq '1') { $extras += ', FSR 3 frame generation 2x' }
517if ($settings.LEONIDA_BVH_BUILDER -eq '1') { $extras += ', ray tracing' } 551if ($settings.LEONIDA_BVH_BUILDER -eq '1') { $extras += ', ray tracing' }
518Write-Host "Series $(if ($console -eq 'series-x') { 'X' } else { 'S' }), $picture$extras. F1 in the game: settings." 552Write-Host "Series $(if ($console -eq 'series-x') { 'X' } else { 'S' }), $picture$extras. F1 in the game: settings."
519if ($DryRun) { 553if ($DryRun) {
diff --git a/scripts/play-d3d12.ps1 b/scripts/play-d3d12.ps1
index aed36ce25..4bcaad50c 100644
--- a/scripts/play-d3d12.ps1
+++ b/scripts/play-d3d12.ps1
@@ -24,6 +24,8 @@
24# on the title's own upscaler, held to 28 shown frames a second. 24# on the title's own upscaler, held to 28 shown frames a second.
25# -NoFrameGen no DLSS frame generation at all, the frames the game renders only 25# -NoFrameGen no DLSS frame generation at all, the frames the game renders only
26# -MotionBlur the game's own motion blur (left out by default: at this frame rate it smears in blocks on turns) 26# -MotionBlur the game's own motion blur (left out by default: at this frame rate it smears in blocks on turns)
27# -FsrFrameGen AMD's FSR 3 frame generation instead (2x), for cards without DLSS frame generation (RTX 20 and 30):
28# needs AMD's two signed FidelityFX DLLs in d3d12\amd-sdk\FidelityFX\bin
27# -Aspect the window's shape: 21:9, 32:9, 16:9, W:H or auto (the screen's). The game still draws 16:9, shown 29# -Aspect the window's shape: 21:9, 32:9, 16:9, W:H or auto (the screen's). The game still draws 16:9, shown
28# centred with black bars (-PresentScale fit, the default with -Aspect) or stretched (stretch). 30# centred with black bars (-PresentScale fit, the default with -Aspect) or stretched (stretch).
29# -Resolution the older path: the game renders at this height and the title's own upscaler does the rest 31# -Resolution the older path: the game renders at this height and the title's own upscaler does the rest
@@ -52,6 +54,7 @@ param(
52 [ValidateSet(0, 2, 3, 4, 5, 6)][int]$FrameGen = 0, 54 [ValidateSet(0, 2, 3, 4, 5, 6)][int]$FrameGen = 0,
53 [switch]$NoFrameGen, 55 [switch]$NoFrameGen,
54 [switch]$MotionBlur, 56 [switch]$MotionBlur,
57 [switch]$FsrFrameGen,
55 [string]$Aspect = '', 58 [string]$Aspect = '',
56 [ValidateSet('', 'fit', 'stretch')][string]$PresentScale = '', 59 [ValidateSet('', 'fit', 'stretch')][string]$PresentScale = '',
57 [string]$Adapter = '', 60 [string]$Adapter = '',
@@ -97,7 +100,7 @@ if ($Dlss) { $launch.Dlss = $Dlss }
97if ($FrameGen) { $launch.FrameGen = $FrameGen } 100if ($FrameGen) { $launch.FrameGen = $FrameGen }
98if ($Aspect) { $launch.Aspect = $Aspect } 101if ($Aspect) { $launch.Aspect = $Aspect }
99if ($PresentScale) { $launch.PresentScale = $PresentScale } 102if ($PresentScale) { $launch.PresentScale = $PresentScale }
100foreach ($switch in 'Quality', 'NoDlss', 'NoFrameGen', 'MotionBlur', 'RayTracing', 'Capture', 'NoPrecompile', 'Log', 'DryRun') { 103foreach ($switch in 'Quality', 'NoDlss', 'NoFrameGen', 'MotionBlur', 'RayTracing', 'Capture', 'NoPrecompile', 'Log', 'DryRun', 'FsrFrameGen') {
101 if ($PSBoundParameters[$switch]) { $launch[$switch] = $true } 104 if ($PSBoundParameters[$switch]) { $launch[$switch] = $true }
102} 105}
103if ($Resolution) { $launch.Resolution = $Resolution } 106if ($Resolution) { $launch.Resolution = $Resolution }