Save sharing in the F1 menu, restarts keep their options, DLSS fixes, monitor's card

- F1 EXPORT SAVE writes the save as one zip into the game folder's Saves
  folder; IMPORT SAVE lists the zips there to pick from. An import is put
  in place at the next start, and the save there before is zipped first
  ("backup before import ..."). Zips made by hand are taken too: with a
  folder around the save, or starting inside the saves folder. The game's
  own settings (SettingsProfileSettings) are never exported or imported:
  the player keeps theirs.
- A restart from the F1 menu keeps the options the game was started with
  (#197).
- DLSS picked in the F1 menu fetches NVIDIA's files at the next start,
  even after an earlier "no", and the menu says so (#514).
- When the driver refuses nearly every DLSS upscaling, DLSS and frame
  generation are turned off for the run.
- FSR 3 frame generation is made ready only with DLSS upscaling on: the
  title's own FidelityFX check stopped the game otherwise (#331, #459).
- RTX Ada, Blackwell and RTX PRO workstation cards count as cards with
  DLSS frame generation.
- On a PC with two cards the game plays on the card the monitor is on, and
  the preload's pipelines are kept per card.
- The warm-up restart comes after 10 seconds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-authored-by: DueTonight <[email protected]>
Co-authored-by: mikan123pro <[email protected]>
This commit is contained in:
committed 2026-11-27 16:58:02 -08:00
1 parent 64d4931b3d
commit c1cbdc9d11
10 files changed
+1191 -61

No files matched your search

+106 -21
View File
@@ -316,7 +316,10 @@ fn settings(o: &Play, menu: &[(String, String)], streamline: Option<&Path>) -> (
// AMD FSR 3 frame generation, made ready as DLSS frame generation is: auto, the layer uses
// it only where DLSS frame generation does not run; fsr, DLSS frame generation is not asked.
// The layer checks the files and the card and says at the start what runs and why not.
if fg_type != "dlss" && (framegen || !o.no_framegen_ready) {
// Only with DLSS on: it never runs without DLSS's upscaling, and made ready without it (the
// title's FidelityFX then left with AMD's files) the title stopped during the boot screens
// (0x80000003 at +0x2219650, or exit code 3; #331, #459: --no-framegen-ready avoided it).
if dlss_on && fg_type != "dlss" && (framegen || !o.no_framegen_ready) {
set("VICTORY_FSR_FRAMEGEN", "1");
if fg_type == "fsr" {
s.remove("VICTORY_FRAMEGEN");
@@ -420,8 +423,21 @@ pub(crate) fn get_dlss() -> Result<()> {
}
/// Asks once, at a start without NVIDIA's files, whether to fetch them.
fn offer_dlss() {
/// `picked`: DLSS was turned on in the F1 menu, which says they are fetched at
/// the next start: they are, without asking, also after an earlier "no"
/// (players who said no and later picked DLSS in F1 saw it turn off again at
/// every start, #514).
fn offer_dlss(picked: bool) {
let Ok(to) = nvidia_home() else { return };
if picked {
println!("DLSS was picked in the F1 menu: fetching NVIDIA's DLSS and frame generation files from");
println!("github.com/NVIDIA-RTX/Streamline (NVIDIA's own, under NVIDIA's licences; about 70 MB, once).");
let _ = std::fs::remove_file(to.join("declined"));
if let Err(e) = fetch(&to) {
println!("{e:#}");
}
return;
}
let declined = to.join("declined");
if declined.exists() || !std::io::stdin().is_terminal() {
println!("No NVIDIA files: running without DLSS and frame generation (`victory get-dlss` fetches them).");
@@ -752,8 +768,9 @@ fn mod_dlls(here: &Path) -> Vec<String> {
NAMES.iter().filter(|n| here.join(n).is_file()).map(|n| (*n).to_owned()).collect()
}
/// How long the first start of a new victory.exe plays before it restarts.
const WARMUP_SECONDS: u32 = 30;
/// How long the first start of a new victory.exe plays before it restarts,
/// counted from the first frame of the game's world (100 draws or more).
const WARMUP_SECONDS: u32 = 10;
/// The file that says this victory.exe (its bytes) had its warm-up start:
/// `%LOCALAPPDATA%\victory\warmed\<hash>`. `None`: the exe could not be read.
@@ -796,14 +813,9 @@ pub(crate) fn prepare(o: &Play) -> Result<Ready> {
std::fs::create_dir_all(&home).with_context(|| format!("creating {}", home.display()))?;
let menu_file = home.join("victory-settings.txt");
let menu = parse_menu(&std::fs::read_to_string(&menu_file).unwrap_or_default());
let wants_dlss = menu
.iter()
.rev()
.find(|(k, _)| k == "VICTORY_MENU_DLSS")
.map_or(o.dlss.as_str(), |(_, v)| v.as_str())
!= "off";
if wants_dlss && streamline_dir(&here).is_none() {
offer_dlss();
let picked = menu.iter().rev().find(|(k, _)| k == "VICTORY_MENU_DLSS").map(|(_, v)| v.as_str());
if picked.unwrap_or(o.dlss.as_str()) != "off" && streamline_dir(&here).is_none() {
offer_dlss(picked.is_some_and(|d| DLSS_MODES.contains(&d)));
}
let streamline = streamline_dir(&here);
let (mut s, series_s) = settings(o, &menu, streamline.as_deref());
@@ -850,14 +862,10 @@ pub(crate) fn prepare(o: &Play) -> Result<Ready> {
s.insert("VICTORY_WARMUP_RESTART".to_owned(), WARMUP_SECONDS.to_string());
s.insert("VICTORY_WARMUP_MARK".to_owned(), mark.to_string_lossy().into_owned());
}
// Where the menu saves, and how it starts the title again (`--set` is not carried over).
let quoted = |p: &Path| format!("'{}'", p.to_string_lossy().replace('\'', "''"));
// Where the menu saves, and how it starts the title again: with this start's options.
s.insert("VICTORY_MENU_FILE".to_owned(), menu_file.to_string_lossy().into_owned());
s.insert("VICTORY_MENU_PLAY".to_owned(), program.to_string_lossy().into_owned());
s.insert(
"VICTORY_MENU_ARGS".to_owned(),
format!("play {}{}", quoted(&exe), if o.no_framegen_ready { " --no-framegen-ready" } else { "" }),
);
s.insert("VICTORY_MENU_ARGS".to_owned(), restart_args(o, &exe));
let log = log_file(&home.join("logs"))?;
let console = if series_s { "series-s" } else { "series-x" };
let line: Vec<String> = s.iter().map(|(k, v)| format!("{k}={v}")).collect();
@@ -888,6 +896,35 @@ pub(crate) fn prepare(o: &Play) -> Result<Ready> {
Ok(Ready { exe, series_s })
}
/// A PowerShell word holding `text` as it is.
fn quoted(text: &str) -> String {
format!("'{}'", text.replace('\'', "''"))
}
/// The arguments the warm-up and the F1 menu's restarts start the title
/// again with (`VICTORY_MENU_ARGS`, after `& '<victory.exe>'` in PowerShell):
/// this start's own options, so those given on the command line (`--series-s`,
/// `--dlss`, `--framegen`, `--set` ...) are kept. Values saved in the F1 menu
/// still win over them, as at every start. A preload is not asked again.
fn restart_args(o: &Play, exe: &Path) -> String {
let mut args = vec!["play".to_owned(), quoted(&exe.to_string_lossy())];
if o.series_s {
args.push("--series-s".to_owned());
}
args.extend(["--res".to_owned(), quoted(&o.res), "--dlss".to_owned(), quoted(&o.dlss)]);
if let Some(x) = o.framegen {
args.extend(["--framegen".to_owned(), x.to_string()]);
}
if o.no_framegen_ready {
args.push("--no-framegen-ready".to_owned());
}
args.extend(["--fg-type".to_owned(), quoted(&o.fg_type), "--fps".to_owned(), o.fps.to_string()]);
for more in &o.more {
args.extend(["--set".to_owned(), quoted(more)]);
}
args.join(" ")
}
/// After a start that went wrong in a window of its own (a double click):
/// the text stays until a key is pressed.
pub(crate) fn hold_window() {
@@ -917,6 +954,51 @@ mod tests {
}
}
#[test]
fn a_restart_keeps_the_options_of_the_command_line() {
use clap::Parser;
#[derive(clap::Parser)]
struct Line {
#[command(flatten)]
play: Play,
}
let exe = Path::new(r"C:\Games\GTA VI's\game_scarlett_master.exe");
let first = [
"x", "--series-s", "--dlss", "performance", "--framegen", "2", "--fg-type", "dlss", "--set", "VICTORY_MFG_UNLOCKER=1", "--set",
"VICTORY_X=a b", "--preload",
];
let o = Line::try_parse_from(first).unwrap().play;
let args = restart_args(&o, exe);
assert_eq!(
args,
r"play 'C:\Games\GTA VI''s\game_scarlett_master.exe' --series-s --res '1440' --dlss 'performance' --framegen 2 --fg-type 'dlss' --fps 1000 --set 'VICTORY_MFG_UNLOCKER=1' --set 'VICTORY_X=a b'"
);
// Read back as PowerShell reads it: the same options again, and no preload.
let mut words: Vec<String> = Vec::new();
let (mut word, mut open, mut chars) = (String::new(), false, args.chars().peekable());
while let Some(c) = chars.next() {
match c {
'\'' if open && chars.peek() == Some(&'\'') => {
word.push('\'');
chars.next();
}
'\'' => open = !open,
' ' if !open => words.push(std::mem::take(&mut word)),
_ => word.push(c),
}
}
words.push(word);
assert_eq!(words[1], exe.to_string_lossy());
let again = Line::try_parse_from(std::iter::once("x".to_owned()).chain(words.into_iter().skip(2))).unwrap().play;
assert_eq!(restart_args(&again, exe), args);
assert!(o.preload && !again.preload);
let plain = Line::try_parse_from(["x"]).unwrap().play;
assert_eq!(
restart_args(&plain, exe),
r"play 'C:\Games\GTA VI''s\game_scarlett_master.exe' --res '1440' --dlss 'quality' --fg-type 'auto' --fps 1000"
);
}
#[test]
fn a_plain_start_is_the_launchers() {
let dir = Path::new(r"C:\nvidia");
@@ -943,9 +1025,9 @@ mod tests {
let get = |k: &str| s.get(k).map(String::as_str);
assert!(!s.contains_key("VICTORY_DLSS") && !s.contains_key("VICTORY_FRAMEGEN"));
assert_eq!(get("VICTORY_MENU_DLSS"), Some("off"));
// FSR 3 frame generation is made ready instead (the layer says whether it can run)
assert_eq!((get("VICTORY_FSR_FRAMEGEN"), get("VICTORY_FRAMEGEN_X")), (Some("1"), Some("0")));
assert_eq!(get("VICTORY_TEXTURE_ROOM_PERCENT"), Some("86"));
// nor FSR 3 frame generation: made ready without DLSS, the title's own FidelityFX
// check stopped the game (#331, #459)
assert!(!s.contains_key("VICTORY_FSR_FRAMEGEN") && !s.contains_key("VICTORY_FRAMEGEN_X"));
assert_eq!(get("VICTORY_MENU_FG_TYPE"), Some("auto"));
}
@@ -1007,6 +1089,9 @@ mod tests {
assert!(fg("NVIDIA GeForce RTX 5070") && fg("NVIDIA GeForce RTX 4070 SUPER") && fg("NVIDIA GeForce RTX 5090 Laptop GPU"));
assert!(!fg("NVIDIA GeForce RTX 3080 Ti") && !fg("NVIDIA GeForce RTX 2060") && !fg("NVIDIA GeForce GTX 1080"));
assert!(!fg("AMD Radeon RX 7900 XTX") && !fg("Intel(R) Arc(TM) A770 Graphics") && !fg(""));
// Workstation cards (#312): Ada and Blackwell have it, Turing and Ampere not.
assert!(fg("NVIDIA RTX PRO 4000 Blackwell SFF Edition") && fg("NVIDIA RTX 2000 Ada Generation") && fg("NVIDIA RTX 6000 Ada Generation"));
assert!(!fg("Quadro RTX 5000") && !fg("NVIDIA Quadro RTX 4000") && !fg("NVIDIA RTX A4500") && !fg("NVIDIA RTX A2000 12GB"));
}
/// MFG Unlocker is offered only to RTX 20 and 30 cards.
+6
View File
@@ -249,6 +249,12 @@ pub fn run(
victory_hle::modules::files::mount_at('G', title_dir);
let temp = cfg.data_subdir(&format!("{:08X}/temp", title.id))?;
victory_hle::modules::files::mount_at('T', &temp);
// The F1 menu's save sharing, and an import it staged put in place before the title runs.
if let Some(data) = storage.parent()
&& let Some(line) = victory_hle::save_share::start(data, title_dir)
{
println!("saves {line}");
}
victory_hle::runtime::set_title(victory_hle::runtime::Title { storage, ..title });
victory_hle::console::set(match console {
Console::SeriesX => victory_hle::console::Console::SeriesX,
+10 -4
View File
@@ -35,15 +35,21 @@ pub fn run(jobs: Option<usize>, limit: Option<usize>, again: bool, used: bool, t
// (A first preload on a PC no run has written pipelines down on yet: none known.)
std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
victory_hle::known_pipelines::use_translations(dir.with_file_name("shaders"));
// The driver keeps what is made here by program path: made by another copy of
// this program, a pipeline is not made for this one.
// The driver keeps what is made here by program path and card: made by
// another copy of this program, or on the other card of a PC with two, a
// pipeline is not made for this one (v2026.11.27.8 made them all on an RTX
// 5060 Ti while the runs played on the RTX 5070 beside it: black parts in
// the picture where the 5070 had not made a pipeline yet).
let fingerprint = {
let program = std::env::current_exe().map(|p| p.to_string_lossy().to_lowercase()).unwrap_or_default();
let card = victory_shader::emit::host::hardware_adapter().map(|(_, name, _)| name).unwrap_or_default();
let mut h = blake3::Hasher::new();
h.update(known::fingerprint().as_bytes());
h.update(program.as_bytes());
h.finalize().to_hex()[..16].to_owned()
h.update(card.as_bytes());
(h.finalize().to_hex()[..16].to_owned(), card)
};
let (fingerprint, card) = fingerprint;
let done_file = dir.join("warm-done.txt");
let bad_file = dir.join("warm-bad.txt");
let keys = known::keys(&dir);
@@ -72,7 +78,7 @@ pub fn run(jobs: Option<usize>, limit: Option<usize>, again: bool, used: bool, t
let cores = std::thread::available_parallelism().map_or(4, |n| n.get());
let jobs = jobs.unwrap_or(cores * 2 / 3).max(1);
println!(
"{} pipelines known, {} made before ({fingerprint}), {} bad; {} to make, {jobs} processes",
"{} pipelines known, {} made before ({fingerprint}, on {card}), {} bad; {} to make, {jobs} processes",
keys.len(),
done.len(),
bad.len(),
+2 -2
View File
@@ -932,13 +932,13 @@ fn create() -> windows::core::Result<Host> {
D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
tracing::info!("host device on the software adapter (WARP)");
} else {
// The card with the most memory of its own (or the one
// The card the monitor is on, else the one with the most memory (or the one
// VICTORY_ADAPTER names), not Windows' first adapter, which is
// often an integrated GPU.
if let Some((adapter, name, own)) = victory_shader::emit::host::hardware_adapter()
&& D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).is_ok()
{
tracing::info!(adapter = %name, own_memory_mb = own >> 20, "host device on the card with the most memory of its own (VICTORY_ADAPTER names another)");
tracing::info!(adapter = %name, own_memory_mb = own >> 20, "host device on the card the monitor is on, else the one with the most memory of its own (VICTORY_ADAPTER names another)");
}
if device.is_none() {
D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
+253 -9
View File
@@ -50,6 +50,44 @@ const ABOUT_PRELOAD: [&str; 3] = [
"TAKES A WHILE: MAYBE A LONG TIME, DEPENDING ON HARDWARE.",
"A LATER UPDATE OF THIS BUILD MAY NEED A NEW PRELOAD.",
];
/// The actions that export and import the game's save (`crate::save_share`), and what is said
/// of them while they are picked.
const EXPORT: usize = 4;
const IMPORT: usize = 5;
const ABOUT_EXPORT: [&str; 3] = [
"MAKES A ZIP OF YOUR SAVE IN SAVES, IN THE FOLDER OF",
"GAME_SCARLETT_MASTER.EXE. SEND THAT ZIP TO SHARE IT.",
"YOUR SAVE STAYS AS IT IS. GAME SETTINGS ARE LEFT OUT.",
];
const ABOUT_IMPORT: [&str; 3] = [
"PUT A SAVE ZIP INTO SAVES, IN THE FOLDER OF",
"GAME_SCARLETT_MASTER.EXE, THEN PRESS ENTER HERE AND",
"PICK IT FROM THE LIST. YOUR GAME SETTINGS ARE KEPT.",
];
/// The list IMPORT SAVE opens: the saves in `Saves`, then a line back to the settings.
const PICK_TITLE: &str = "IMPORT SAVE ESC GOES BACK";
const PICK_HELP: &str = "UP/DOWN PICK ENTER TWICE IMPORTS IT";
const PICK_NONE: &str = " NONE YET: PUT A SAVE ZIP INTO SAVES IN THE GAME FOLDER";
const PICK_BACK: &str = "BACK TO THE SETTINGS";
const ABOUT_PICK: [&str; 3] = [
"THE SAVE ZIPS IN SAVES, IN THE GAME FOLDER, NEWEST FIRST.",
"ENTER TWICE: THE GAME RESTARTS WITH THE SAVE PICKED.",
"YOUR OLD SAVE IS ZIPPED INTO SAVES FIRST, SO IT IS KEPT.",
];
/// The note after the first Enter on a save in the list: the second one imports it.
const CONFIRM_IMPORT: &str = "ENTER AGAIN: IMPORT IT AND RESTART THE GAME";
/// The longest save name shown in the list.
const IMPORT_NAME: usize = 56;
/// A save's file name as the menu's letters can show it.
fn shown_name(name: &str) -> String {
name.chars()
.map(|c| c.to_ascii_uppercase())
.map(|c| if c.is_ascii() && glyph(c as u8) != glyph(b'#') { c } else { '-' })
.take(IMPORT_NAME)
.collect()
}
/// The setting that turns MFG Unlocker on, and what is said of it while it is picked.
const MFG: &str = "VICTORY_MFG_UNLOCKER";
const ABOUT_MFG: [&str; 3] = [
@@ -57,6 +95,13 @@ const ABOUT_MFG: [&str; 3] = [
"ON: DOWNLOADED FROM ITS GITHUB AT THE NEXT START, THEN RUN.",
"NVIDIA DOES NOT SUPPORT IT. IF THE GAME FAILS, TURN IT OFF.",
];
/// The DLSS setting, and what is said while it is picked on in a start without NVIDIA's files.
const DLSS: &str = "VICTORY_MENU_DLSS";
const ABOUT_NO_DLSS: [&str; 3] = [
"THE NVIDIA DLSS FILES ARE NOT ON THIS PC YET: THEY ARE",
"DOWNLOADED FROM NVIDIA ON GITHUB AT THE NEXT START",
"(ABOUT 70 MB, ONCE). SAVE AND RESTART NOW DOES IT.",
];
/// 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.
@@ -116,8 +161,15 @@ 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; 5] =
["SAVE AND RESTART NOW", "SAVE FOR NEXT START", "PRELOAD SHADERS (RESTARTS THE GAME)", "RESET ALL TO PLAY DEFAULTS", "CLOSE"];
const ACTIONS: [&str; 7] = [
"SAVE AND RESTART NOW",
"SAVE FOR NEXT START",
"PRELOAD SHADERS (RESTARTS THE GAME)",
"RESET ALL TO PLAY DEFAULTS",
"EXPORT SAVE (TO SAVES IN THE GAME FOLDER)",
"IMPORT SAVE (PICK FROM SAVES)",
"CLOSE",
];
fn get(var: &str) -> String {
std::env::var(var).unwrap_or_default()
@@ -382,6 +434,11 @@ pub(super) struct Menu {
painted: Option<String>,
buffers: Option<Buffers>,
failed: bool,
/// The saves in `Saves` that can be imported (read when the menu opens), and the line
/// picked in their list (`imports.len()`: the line back), shown while `picking`.
imports: Vec<String>,
import_at: usize,
picking: bool,
}
impl Menu {
@@ -393,7 +450,7 @@ impl Menu {
crate::SETTINGS_MENU_OPEN.store(true, Ordering::Relaxed);
}
let values: Vec<String> = ITEMS.iter().map(|i| get(i.var)).collect();
Menu { started: values.clone(), values, at: 0, note: String::new(), changed: true, painted: None, buffers: None, failed: false }
Menu { started: values.clone(), values, at: 0, note: String::new(), changed: true, painted: None, buffers: None, failed: false, imports: Vec::new(), import_at: 0, picking: false }
}
fn open() -> bool {
@@ -401,6 +458,9 @@ impl Menu {
}
fn lines(&self) -> Vec<String> {
if self.picking {
return self.pick_lines();
}
let total = ITEMS.len() + ACTIONS.len();
let first = self.at.saturating_sub(ROWS / 2).min(total.saturating_sub(ROWS));
let mut out = vec![
@@ -426,8 +486,17 @@ impl Menu {
out.push(String::new());
let about = if self.at == ITEMS.len() + PRELOAD {
ABOUT_PRELOAD
} else if self.at == ITEMS.len() + EXPORT {
ABOUT_EXPORT
} else if self.at == ITEMS.len() + IMPORT {
ABOUT_IMPORT
} else if ITEMS.get(self.at).is_some_and(|i| i.var == MFG) {
ABOUT_MFG
} else if ITEMS.get(self.at).is_some_and(|i| i.var == DLSS)
&& !matches!(self.values[self.at].as_str(), "" | "off")
&& std::env::var_os("VICTORY_STREAMLINE_DIR").is_none()
{
ABOUT_NO_DLSS
} else {
[""; 3]
};
@@ -437,6 +506,30 @@ impl Menu {
out
}
/// The list IMPORT SAVE opens, in the box's lines.
fn pick_lines(&self) -> Vec<String> {
let mut out = vec![PICK_TITLE.to_owned(), PICK_HELP.to_owned(), String::new()];
if self.imports.is_empty() {
out.push(PICK_NONE.to_owned());
}
let rows = ROWS - (out.len() - 3);
let total = self.imports.len() + 1;
let first = self.import_at.saturating_sub(rows / 2).min(total.saturating_sub(rows));
for row in first..(first + rows).min(total) {
let cursor = if row == self.import_at { '>' } else { ' ' };
let name = self.imports.get(row).map_or_else(|| PICK_BACK.to_owned(), |n| shown_name(n));
out.push(format!("{cursor} {name}").chars().take(COLUMNS as usize).collect());
}
while out.len() < 3 + ROWS {
out.push(String::new());
}
out.push(String::new());
out.extend(ABOUT_PICK.iter().map(|l| (*l).to_owned()));
out.push(if self.note.is_empty() { format!("{} IN SAVES", self.imports.len()) } else { self.note.clone() });
out.push(REPO.to_owned());
out
}
/// Changes item `i` by `step` (+1 / -1) through its values.
fn change(&mut self, i: usize, step: isize) {
let item = &ITEMS[i];
@@ -591,6 +684,66 @@ impl Menu {
self.restart(false);
}
/// Reads which saves `Saves` holds, keeping the one picked if it is still there.
fn read_imports(&mut self) {
let picked = self.imports.get(self.import_at).cloned();
self.imports = crate::save_share::share().map(|s| crate::save_share::exports(&s)).unwrap_or_default();
self.import_at = picked.and_then(|p| self.imports.iter().position(|n| *n == p)).unwrap_or(0);
}
/// Writes the game's save into a new zip in `Saves`.
fn export_save(&mut self) {
let (Some(data), Some(share)) = (crate::save_share::data(), crate::save_share::share()) else {
self.note = "SAVE FOLDERS NOT KNOWN IN THIS START".to_owned();
return;
};
let name = format!("save {}", crate::save_share::stamp());
match crate::save_share::export(&data, &share, &name) {
Ok(to) => {
tracing::info!(to = %to.display(), "settings menu: save exported");
self.note = format!("EXPORTED TO SAVES: {}.ZIP", shown_name(&name));
self.read_imports();
}
Err(e) => {
tracing::warn!(error = %e, share = %share.display(), "settings menu: save not exported");
self.note = if e.kind() == std::io::ErrorKind::NotFound {
"NOTHING TO EXPORT: THE GAME HAS NOT SAVED YET"
} else {
"EXPORT FAILED: THE GAME FOLDER CANNOT BE WRITTEN"
}
.to_owned();
}
}
}
/// Stages the save picked to be put in place at the next start, and starts the game again.
fn import_save(&mut self) {
let (Some(data), Some(share)) = (crate::save_share::data(), crate::save_share::share()) else {
self.note = "SAVE FOLDERS NOT KNOWN IN THIS START".to_owned();
return;
};
let Some(name) = self.imports.get(self.import_at).cloned() else {
self.note = "NO SAVE TO IMPORT: PUT ONE IN SAVES FIRST".to_owned();
return;
};
if let Err(e) = crate::save_share::stage(&data, &share, &name) {
tracing::warn!(error = %e, name, "settings menu: save import not staged");
self.note = if e.kind() == std::io::ErrorKind::NotFound {
"IMPORT FAILED: NO SAVE IN THAT ZIP"
} else {
"IMPORT FAILED: THAT ZIP IS DAMAGED OR NOT A SAVE"
}
.to_owned();
return;
}
tracing::info!(name, "settings menu: save import staged; put in place at the next start");
if std::env::var_os("VICTORY_MENU_PLAY").is_some() {
self.restart(false);
} else {
self.note = "IMPORTED: CLOSE THE GAME AND START IT AGAIN".to_owned();
}
}
/// Removes the settings file: the launcher's own settings at the next start.
fn reset(&mut self) {
if let Some(path) = settings_file() {
@@ -618,20 +771,44 @@ impl Menu {
let total = ITEMS.len() + ACTIONS.len();
for vk in pressed {
let open = Self::open();
// Esc in the list of saves goes back to the settings.
if open && self.picking && vk == VK_ESCAPE {
self.picking = false;
self.note.clear();
self.changed = true;
continue;
}
if vk == VK_F1 || (open && vk == VK_ESCAPE) {
crate::SETTINGS_MENU_OPEN.store(!open && vk == VK_F1, Ordering::Relaxed);
self.note.clear();
self.picking = false;
if !open {
self.read_imports();
}
self.changed = true;
continue;
}
if !open {
continue;
}
// Only an Enter right after the first one starts a preload.
let confirmed = self.note == CONFIRM_PRELOAD;
// Only an Enter right after the first one starts a preload or an import.
let confirmed = self.note == CONFIRM_PRELOAD || self.note == CONFIRM_IMPORT;
if confirmed {
self.note.clear();
}
if self.picking {
let (n, back) = (self.imports.len() + 1, self.import_at >= self.imports.len());
match vk {
VK_UP => self.import_at = (self.import_at + n - 1) % n,
VK_DOWN => self.import_at = (self.import_at + 1) % n,
VK_RETURN if back => self.picking = false,
VK_RETURN if !confirmed => self.note = CONFIRM_IMPORT.to_owned(),
VK_RETURN => self.import_save(),
_ => {}
}
self.changed = true;
continue;
}
match vk {
VK_UP => self.at = (self.at + total - 1) % total,
VK_DOWN => self.at = (self.at + 1) % total,
@@ -654,6 +831,12 @@ impl Menu {
}
}
3 => self.reset(),
EXPORT => self.export_save(),
IMPORT => {
self.read_imports();
self.import_at = 0;
self.picking = true;
}
_ => crate::SETTINGS_MENU_OPEN.store(false, Ordering::Relaxed),
},
_ => {}
@@ -744,7 +927,7 @@ mod tests {
std::env::remove_var("VICTORY_MENU_FILE");
std::env::set_var("VICTORY_HOME", &home);
}
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 };
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, imports: Vec::new(), import_at: 0, picking: false };
menu.started = menu.values.clone();
let dlss = ITEMS.iter().position(|i| i.var == "VICTORY_MENU_DLSS").expect("in the menu");
menu.change_and_save(dlss, 1);
@@ -761,7 +944,7 @@ mod tests {
#[test]
fn every_line_fits_and_every_character_has_a_picture() {
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 };
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, imports: Vec::new(), import_at: 0, picking: false };
menu.started = menu.values.clone();
for at in 0..ITEMS.len() + ACTIONS.len() {
menu.at = at;
@@ -776,7 +959,7 @@ 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 };
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, imports: Vec::new(), import_at: 0, picking: false };
menu.started = menu.values.clone();
for note in ["", "SAVED"] {
menu.note = note.to_owned();
@@ -791,6 +974,10 @@ mod tests {
let about = &lines[n - 5..n - 2];
if at == ITEMS.len() + PRELOAD {
assert_eq!(about, ABOUT_PRELOAD);
} else if at == ITEMS.len() + EXPORT {
assert_eq!(about, ABOUT_EXPORT);
} else if at == ITEMS.len() + IMPORT {
assert_eq!(about, ABOUT_IMPORT);
} else if at < ITEMS.len() && ITEMS[at].var == MFG {
assert_eq!(about, ABOUT_MFG);
} else {
@@ -800,13 +987,32 @@ mod tests {
}
assert_eq!(ACTIONS[PRELOAD], "PRELOAD SHADERS (RESTARTS THE GAME)");
assert!(CONFIRM_PRELOAD.len() <= COLUMNS as usize);
assert_eq!(ACTIONS[EXPORT], "EXPORT SAVE (TO SAVES IN THE GAME FOLDER)");
assert_eq!(ACTIONS[IMPORT], "IMPORT SAVE (PICK FROM SAVES)");
let pick = [PICK_TITLE, PICK_HELP, PICK_NONE, PICK_BACK, CONFIRM_IMPORT, "IMPORT FAILED: THAT ZIP IS DAMAGED OR NOT A SAVE"];
for line in ABOUT_EXPORT.iter().chain(&ABOUT_IMPORT).chain(&ABOUT_PICK).chain(&pick) {
assert!(line.len() <= COLUMNS as usize, "{line}");
assert!(line.bytes().all(|c| glyph(c) != glyph(b'#')), "{line}");
}
assert!(ABOUT_MFG.iter().all(|l| l.len() <= COLUMNS as usize));
for line in ABOUT_NO_DLSS {
assert!(line.len() <= COLUMNS as usize && line.bytes().all(|c| glyph(c) != glyph(b'#')), "{line}");
}
// DLSS picked on where NVIDIA's files are missing (no VICTORY_STREAMLINE_DIR in tests): said so.
let dlss = ITEMS.iter().position(|i| i.var == DLSS).expect("in the menu");
menu.at = dlss;
menu.values[dlss] = "quality".to_owned();
let lines = menu.lines();
assert_eq!(&lines[lines.len() - 5..lines.len() - 2], ABOUT_NO_DLSS);
menu.values[dlss] = "off".to_owned();
let lines = menu.lines();
assert!(lines[lines.len() - 5..lines.len() - 2].iter().all(String::is_empty));
assert_eq!(ITEMS.iter().filter(|i| i.var == MFG).count(), 1);
}
#[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 };
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, imports: Vec::new(), import_at: 0, picking: false };
menu.started = menu.values.clone();
let n = ITEMS[0].values.len();
for _ in 0..n {
@@ -816,4 +1022,42 @@ mod tests {
menu.change(0, -1);
assert_eq!(menu.values[0], ITEMS[0].values[n - 1].0);
}
#[test]
fn a_shared_save_name_is_shown_in_letters_the_menu_has() {
let names = vec!["save 2026-11-27 23-45-10.zip".to_owned(), "Jason's boat ~ 100% [\u{e9}] and a very long name that goes on and on.zip".to_owned()];
let mut menu = Menu { values: ITEMS.iter().map(|_| String::new()).collect(), started: Vec::new(), at: ITEMS.len() + IMPORT, note: String::new(), changed: false, painted: None, buffers: None, failed: false, imports: names, import_at: 0, picking: true };
menu.started = menu.values.clone();
let check = |menu: &Menu| {
let lines = menu.lines();
assert_eq!(lines.len(), LINES as usize);
assert_eq!(lines[lines.len() - 1], REPO);
assert_eq!(&lines[lines.len() - 5..lines.len() - 2], ABOUT_PICK);
for line in &lines {
assert!(line.len() <= COLUMNS as usize, "{line}");
assert!(line.bytes().all(|c| glyph(c.to_ascii_uppercase()) != glyph(b'#')), "{line}");
}
lines
};
let lines = check(&menu);
assert!(lines.iter().any(|l| l == "> SAVE 2026-11-27 23-45-10.ZIP"), "{lines:?}");
assert!(lines.iter().any(|l| l == &format!(" {PICK_BACK}")), "{lines:?}");
menu.import_at = 1;
check(&menu);
menu.import_at = 2;
assert!(check(&menu).iter().any(|l| l == &format!("> {PICK_BACK}")));
// Many saves: the list scrolls and the box keeps its size.
menu.imports = (0..50).map(|i| format!("save {i}.zip")).collect();
for at in [0, 25, 49, 50] {
menu.import_at = at;
let lines = check(&menu);
let picked = if at == 50 { format!("> {PICK_BACK}") } else { format!("> SAVE {at}.ZIP") };
assert!(lines.contains(&picked), "{at}: {lines:?}");
}
menu.imports.clear();
menu.import_at = 0;
let lines = check(&menu);
assert!(lines.iter().any(|l| l == PICK_NONE));
assert!(lines.iter().any(|l| l == &format!("> {PICK_BACK}")));
}
}
+1
View File
@@ -73,6 +73,7 @@ pub mod replay;
#[cfg(windows)]
mod residency;
pub mod resource;
pub mod save_share;
pub mod root;
#[cfg(windows)]
mod safecopy;
+672
View File
@@ -0,0 +1,672 @@
//! Sharing game saves through the F1 menu (EXPORT SAVE, IMPORT SAVE).
//!
//! A save is the title's data folder's `saves` (the game's save containers)
//! and `storage` (its persistent local storage), under `<data>\<title id>`.
//! Export writes them into one zip file in `Saves` beside the game's
//! executable, to send as it is; another player puts that zip into their own
//! `Saves` and picks it in the menu's list. An import is staged
//! (`import-pending` in the data folder) and put in place at the next start,
//! before the title runs: the running game holds its saves and would write
//! over an import with its next autosave. The save it replaces is zipped into
//! `Saves` first ("backup before import ..."), so nothing is lost.
//!
//! A zip zipped again by hand (Windows' "Compress to ZIP file", with the
//! export's folder around it) imports too, and so does a save folder put in
//! `Saves` as it is (as the first test build exported them).
use std::io;
use std::path::{Path, PathBuf};
/// The folders of `<data>\<title id>` that make a save.
pub const PARTS: [&str; 2] = ["saves", "storage"];
/// An import must have this part.
const NEEDED: &str = "saves";
/// Where an import waits for the next start, in `<data>\<title id>`.
const PENDING: &str = "import-pending";
/// Backups go here when the game folder cannot be written.
const BACKUPS: &str = "save-backups";
/// The game keeps its own settings (picture, controls, sound) in a save container of this name
/// (`SettingsProfileSettings~<id>`): never exported nor imported, and the player's own is kept
/// when an import replaces the save (an import overwrote the player's settings, 2026-11-28).
const SETTINGS: &str = "SettingsProfileSettings";
fn is_settings(name: &str) -> bool {
name.starts_with(SETTINGS)
}
/// Inside `saves`: the folder of the one player (`{:016X}` of the HLE's XUID), then the
/// title's (`<scid>`), then the save containers (`<name>~<16 hex digits>`). Zips shared by
/// hand often start at one of these instead of at `saves` (one did, 2026-11-28).
const USER: &str = "0009000000000001";
const SCID: &str = "00000000-0000-0000-0000-00007952987a";
fn is_container(name: &str) -> bool {
name.split_once('~').is_some_and(|(kind, id)| {
!kind.is_empty() && id.len() == 16 && id.bytes().all(|b| b.is_ascii_hexdigit())
})
}
/// Where a zip that starts inside `saves` puts the entry `parts`, if it does.
fn inside_saves(parts: &[&str]) -> Option<PathBuf> {
let found = |is: &dyn Fn(&str) -> bool| parts.iter().take(3).position(|p| is(p));
let mut to = PathBuf::from(NEEDED);
let at = if let Some(at) = found(&|p| p.eq_ignore_ascii_case(USER)) {
at
} else if let Some(at) = found(&|p| p.eq_ignore_ascii_case(SCID)) {
to.push(USER);
at
} else {
let at = found(&is_container)?;
to.push(USER);
to.push(SCID);
at
};
Some(to.join(parts[at..].iter().collect::<PathBuf>()))
}
fn env(name: &str) -> Option<PathBuf> {
std::env::var_os(name).filter(|v| !v.is_empty()).map(PathBuf::from)
}
/// `<data>\<title id>`: where the running title's saves are (`VICTORY_SAVE_DATA`, set by [`start`]).
pub fn data() -> Option<PathBuf> {
env("VICTORY_SAVE_DATA")
}
/// `Saves` beside the game's executable (`VICTORY_SAVE_SHARE`, set by [`start`]).
pub fn share() -> Option<PathBuf> {
env("VICTORY_SAVE_SHARE")
}
fn now() -> windows_sys::Win32::Foundation::SYSTEMTIME {
let mut t: windows_sys::Win32::Foundation::SYSTEMTIME = unsafe { std::mem::zeroed() };
// SAFETY: fills a plain structure of ours.
unsafe { windows_sys::Win32::System::SystemInformation::GetLocalTime(&mut t) };
t
}
/// The local time as a file name can hold it: `2026-11-27 23-45-10`.
pub fn stamp() -> String {
let t = now();
format!("{:04}-{:02}-{:02} {:02}-{:02}-{:02}", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond)
}
fn bad(text: impl Into<String>) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, text.into())
}
/// Zip files: written with deflate (stored where that is no smaller), read
/// stored or deflated. No zip64, no encryption: a save is a few megabytes.
mod zip {
use super::bad;
use std::io;
/// The most a zip may unpack to (all its files together).
pub const MOST: u64 = 1 << 30;
const LOCAL: u32 = 0x0403_4b50;
const CENTRAL: u32 = 0x0201_4b50;
const END: u32 = 0x0605_4b50;
/// `(name, bytes)`; a name ending in `/` is a folder.
pub type Entry = (String, Vec<u8>);
fn deflate(data: &[u8]) -> Option<Vec<u8>> {
let mut buf = vec![0u8; zlib_rs::compress_bound(data.len())];
let config = zlib_rs::DeflateConfig { window_bits: -15, ..zlib_rs::DeflateConfig::new(6) };
let (packed, rc) = zlib_rs::compress_slice(&mut buf, data, config);
(rc == zlib_rs::ReturnCode::Ok && packed.len() < data.len()).then(|| packed.to_vec())
}
fn inflate(packed: &[u8], size: usize) -> Option<Vec<u8>> {
if size == 0 {
return Some(Vec::new());
}
let mut out = vec![0u8; size];
let (got, rc) = zlib_rs::decompress_slice(&mut out, packed, zlib_rs::InflateConfig { window_bits: -15 });
let n = got.len();
(rc == zlib_rs::ReturnCode::Ok && n == size).then_some(out)
}
/// The zip of `entries`, dated `(time, date)` (MS-DOS form).
pub fn write(entries: &[Entry], (time, date): (u16, u16)) -> io::Result<Vec<u8>> {
if entries.len() >= 0xffff {
return Err(bad("too many files for a zip"));
}
let (mut out, mut central) = (Vec::new(), Vec::new());
for (name, data) in entries {
let packed = if name.ends_with('/') { None } else { deflate(data) };
let (method, body): (u16, &[u8]) = match &packed {
Some(p) => (8, p),
None => (0, data),
};
let offset = u32::try_from(out.len()).map_err(|_| bad("zip over 4 GB"))?;
let crc = zlib_rs::crc32::crc32(0, data);
let head = |sig: u32| {
let mut h = Vec::with_capacity(46 + name.len());
h.extend_from_slice(&sig.to_le_bytes());
if sig == CENTRAL {
h.extend_from_slice(&20u16.to_le_bytes()); // made by: MS-DOS, 2.0
}
for v in [20u16, 0x0800, method, time, date] {
h.extend_from_slice(&v.to_le_bytes()); // 0x0800: the name is UTF-8
}
for v in [crc, body.len() as u32, data.len() as u32] {
h.extend_from_slice(&v.to_le_bytes());
}
h.extend_from_slice(&(name.len() as u16).to_le_bytes());
h.extend_from_slice(&0u16.to_le_bytes()); // extra
if sig == CENTRAL {
let attributes: u32 = if name.ends_with('/') { 0x10 } else { 0x20 };
for v in [0u16, 0, 0] {
h.extend_from_slice(&v.to_le_bytes()); // comment, disk, internal
}
h.extend_from_slice(&attributes.to_le_bytes());
h.extend_from_slice(&offset.to_le_bytes());
}
h.extend_from_slice(name.as_bytes());
h
};
out.extend_from_slice(&head(LOCAL));
out.extend_from_slice(body);
central.extend_from_slice(&head(CENTRAL));
}
let at = u32::try_from(out.len()).map_err(|_| bad("zip over 4 GB"))?;
out.extend_from_slice(&central);
out.extend_from_slice(&END.to_le_bytes());
for v in [0u16, 0, entries.len() as u16, entries.len() as u16] {
out.extend_from_slice(&v.to_le_bytes());
}
out.extend_from_slice(&(central.len() as u32).to_le_bytes());
out.extend_from_slice(&at.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
Ok(out)
}
fn u16_at(b: &[u8], at: usize) -> io::Result<u16> {
b.get(at..at + 2).map(|s| u16::from_le_bytes([s[0], s[1]])).ok_or_else(|| bad("the zip is cut short"))
}
fn u32_at(b: &[u8], at: usize) -> io::Result<u32> {
b.get(at..at + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])).ok_or_else(|| bad("the zip is cut short"))
}
/// The entries of the zip `b`, unpacked and checked.
pub fn read(b: &[u8]) -> io::Result<Vec<Entry>> {
let lowest = b.len().saturating_sub(22 + 0xffff);
let end = (lowest..=b.len().saturating_sub(22))
.rev()
.find(|&i| u32_at(b, i).is_ok_and(|s| s == END))
.ok_or_else(|| bad("not a zip file"))?;
let count = u16_at(b, end + 10)? as usize;
let mut at = u32_at(b, end + 16)? as usize;
let (mut out, mut total) = (Vec::with_capacity(count), 0u64);
for _ in 0..count {
if u32_at(b, at)? != CENTRAL {
return Err(bad("the zip's list of files is damaged"));
}
let (flags, method) = (u16_at(b, at + 8)?, u16_at(b, at + 10)?);
let crc = u32_at(b, at + 16)?;
let (packed, size) = (u32_at(b, at + 20)? as usize, u32_at(b, at + 24)? as usize);
let (name_len, extra, comment) = (u16_at(b, at + 28)? as usize, u16_at(b, at + 30)? as usize, u16_at(b, at + 32)? as usize);
let local = u32_at(b, at + 42)? as usize;
let name = b.get(at + 46..at + 46 + name_len).ok_or_else(|| bad("the zip is cut short"))?;
let name = String::from_utf8_lossy(name).replace('\\', "/");
at += 46 + name_len + extra + comment;
if flags & 1 != 0 {
return Err(bad("the zip has a password"));
}
if packed == 0xffff_ffff || size == 0xffff_ffff {
return Err(bad("zip64 files are not read"));
}
total += size as u64;
if total > MOST {
return Err(bad("the zip unpacks to more than a save can be"));
}
if u32_at(b, local)? != LOCAL {
return Err(bad("the zip is damaged"));
}
let start = local + 30 + u16_at(b, local + 26)? as usize + u16_at(b, local + 28)? as usize;
let body = b.get(start..start + packed).ok_or_else(|| bad("the zip is cut short"))?;
let data = match method {
0 if packed == size => body.to_vec(),
8 => inflate(body, size).ok_or_else(|| bad(format!("{name}: damaged in the zip")))?,
_ => return Err(bad(format!("{name}: packed in a way that is not read (method {method})"))),
};
if zlib_rs::crc32::crc32(0, &data) != crc {
return Err(bad(format!("{name}: damaged in the zip")));
}
out.push((name, data));
}
Ok(out)
}
}
/// `(time, date)` now, as a zip holds them.
fn dos_now() -> (u16, u16) {
let t = now();
let time = (t.wHour << 11) | (t.wMinute << 5) | (t.wSecond / 2);
let date = (t.wYear.saturating_sub(1980) << 9) | (t.wMonth << 5) | t.wDay;
(time, date)
}
/// Every folder and file in `dir`, named `prefix/...` with `/` between parts.
fn gather(dir: &Path, prefix: &str, out: &mut Vec<zip::Entry>) -> io::Result<()> {
out.push((format!("{prefix}/"), Vec::new()));
let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<io::Result<_>>()?;
entries.sort_by_key(std::fs::DirEntry::file_name);
for entry in entries {
let name = format!("{prefix}/{}", entry.file_name().to_string_lossy());
if entry.file_type()?.is_dir() && is_settings(&entry.file_name().to_string_lossy()) {
continue;
}
if entry.file_type()?.is_dir() {
gather(&entry.path(), &name, out)?;
} else {
out.push((name, std::fs::read(entry.path())?));
}
}
Ok(())
}
/// Where an entry of a zip goes in `<data>\<title id>`: `saves/...` or
/// `storage/...`, with at most one folder around them. `None`: not part of
/// a save (a readme, say). A name that could reach out of the folder is refused.
fn place(name: &str) -> io::Result<Option<PathBuf>> {
let parts: Vec<&str> = name.split('/').filter(|p| !p.is_empty() && *p != ".").collect();
for p in &parts {
if *p == ".." || p.chars().any(|c| c.is_control() || r#"<>:"|?*"#.contains(c)) || p.ends_with([' ', '.']) {
return Err(bad(format!("{name}: not a name a save has")));
}
}
// (The game's settings, in zips made before they were left out: the player keeps theirs.)
if parts.iter().any(|p| is_settings(p)) {
return Ok(None);
}
match parts.iter().take(2).position(|p| PARTS.iter().any(|k| p.eq_ignore_ascii_case(k))) {
Some(at) => Ok(Some(parts[at..].iter().collect::<PathBuf>())),
None => Ok(inside_saves(&parts)),
}
}
/// Writes the save in `data` into a new zip `<name>.zip` in `share`. The zip.
pub fn export(data: &Path, share: &Path, name: &str) -> io::Result<PathBuf> {
if !data.join(NEEDED).is_dir() {
return Err(io::Error::new(io::ErrorKind::NotFound, "no save yet"));
}
let to = share.join(format!("{name}.zip"));
if to.exists() {
return Err(io::Error::new(io::ErrorKind::AlreadyExists, format!("{} exists", to.display())));
}
let mut entries = Vec::new();
for part in PARTS {
let from = data.join(part);
if from.is_dir() {
gather(&from, part, &mut entries)?;
}
}
let bytes = zip::write(&entries, dos_now())?;
std::fs::create_dir_all(share)?;
// Written whole under another name first: a zip is never seen half written.
let part = share.join(format!("{name}.zip.part"));
std::fs::write(&part, bytes)?;
std::fs::rename(&part, &to).inspect_err(|_| drop(std::fs::remove_file(&part)))?;
Ok(to)
}
/// What `share` holds to import, newest first: its zip files, and save
/// folders (with a `saves` folder) put there as they are.
pub fn exports(share: &Path) -> Vec<String> {
let Ok(entries) = std::fs::read_dir(share) else { return Vec::new() };
let mut found: Vec<(std::time::SystemTime, String)> = entries
.flatten()
.filter(|e| {
let path = e.path();
if path.is_dir() {
path.join(NEEDED).is_dir()
} else {
path.extension().is_some_and(|x| x.eq_ignore_ascii_case("zip"))
}
})
.filter_map(|e| {
let when = e.metadata().and_then(|m| m.modified()).unwrap_or(std::time::UNIX_EPOCH);
Some((when, e.file_name().into_string().ok()?))
})
.collect();
found.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
found.into_iter().map(|(_, name)| name).collect()
}
/// Copies the folder `from` into `to` (made), with everything in it (`settings`: also the
/// game's settings containers).
fn copy_dir(from: &Path, to: &Path, settings: bool) -> io::Result<()> {
std::fs::create_dir_all(to)?;
for entry in std::fs::read_dir(from)? {
let entry = entry?;
let target = to.join(entry.file_name());
if entry.file_type()?.is_dir() {
if !settings && is_settings(&entry.file_name().to_string_lossy()) {
continue;
}
copy_dir(&entry.path(), &target, settings)?;
} else {
std::fs::copy(entry.path(), &target)?;
}
}
Ok(())
}
/// Unpacks the save in the zip `bytes` into `to`. Nothing is written unless the whole zip reads.
fn unzip(bytes: &[u8], to: &Path) -> io::Result<()> {
let mut placed = Vec::new();
for (name, data) in zip::read(bytes)? {
if let Some(at) = place(&name)? {
placed.push((name.ends_with('/'), at, data));
}
}
if !placed.iter().any(|(_, at, _)| at.starts_with(NEEDED)) {
return Err(io::Error::new(io::ErrorKind::NotFound, "no save in that zip (no saves folder)"));
}
for (folder, at, data) in placed {
let path = to.join(at);
if folder {
std::fs::create_dir_all(&path)?;
} else {
if let Some(up) = path.parent() {
std::fs::create_dir_all(up)?;
}
std::fs::write(&path, data)?;
}
}
Ok(())
}
/// Stages the save `name` of `share` (a zip, or a save folder) to be put in
/// place at the next start ([`start`]).
pub fn stage(data: &Path, share: &Path, name: &str) -> io::Result<()> {
let from = share.join(name);
let pending = data.join(PENDING);
if pending.exists() {
std::fs::remove_dir_all(&pending)?;
}
let done = if from.is_file() {
std::fs::read(&from).and_then(|bytes| unzip(&bytes, &pending))
} else if from.join(NEEDED).is_dir() {
PARTS.iter().filter(|p| from.join(p).is_dir()).try_for_each(|p| copy_dir(&from.join(p), &pending.join(p), false))
} else {
Err(io::Error::new(io::ErrorKind::NotFound, format!("{} has no save", from.display())))
};
if done.is_err() {
let _ = std::fs::remove_dir_all(&pending);
}
done
}
/// Moves the game's settings containers in `old` (the save being replaced) to the same places
/// in `new` (the import, which has none), so the player's settings outlast the import.
fn keep_settings(old: &Path, new: &Path) -> io::Result<()> {
for entry in std::fs::read_dir(old)? {
let entry = entry?;
if !entry.file_type()?.is_dir() {
continue;
}
let target = new.join(entry.file_name());
if is_settings(&entry.file_name().to_string_lossy()) {
if !target.exists() {
std::fs::create_dir_all(new)?;
if std::fs::rename(entry.path(), &target).is_err() {
copy_dir(&entry.path(), &target, true)?;
}
}
} else {
keep_settings(&entry.path(), &target)?;
}
}
Ok(())
}
/// Whether an import waits for the next start.
pub fn staged(data: &Path) -> bool {
data.join(PENDING).join(NEEDED).is_dir()
}
/// Puts a staged import in place: the save there now is zipped first (into
/// `share`, else `<data>\save-backups`), then each part of the import takes
/// the place of the one it replaces (a part the import lacks is kept). The
/// backup, or `None` when nothing was staged.
pub fn apply(data: &Path, share: &Path, stamp: &str) -> io::Result<Option<PathBuf>> {
let pending = data.join(PENDING);
if !staged(data) {
return Ok(None);
}
let name = format!("backup before import {stamp}");
let backup = if data.join(NEEDED).is_dir() {
match export(data, share, &name) {
Ok(to) => Some(to),
// (A game folder that cannot be written, such as one under Program Files.)
Err(_) => Some(export(data, &data.join(BACKUPS), &name)?),
}
} else {
None
};
for part in PARTS {
let new = pending.join(part);
if !new.is_dir() {
continue;
}
let old = data.join(part);
if old.is_dir() {
keep_settings(&old, &new)?;
}
if old.exists() {
std::fs::remove_dir_all(&old)?;
}
if std::fs::rename(&new, &old).is_err() {
copy_dir(&new, &old, true)?;
}
}
std::fs::remove_dir_all(&pending)?;
Ok(Some(backup.unwrap_or_else(|| data.join(PARTS[0]))))
}
/// At start, before the title runs: the folders the menu uses (`data`,
/// `<data>\<title id>`; `Saves` in `game`, the executable's folder), and a
/// staged import put in place. A line for the console, if one was.
pub fn start(data: &Path, game: &Path) -> Option<String> {
let share = game.join("Saves");
// SAFETY: set once at start, before the title's and our threads read them.
unsafe {
std::env::set_var("VICTORY_SAVE_DATA", data);
std::env::set_var("VICTORY_SAVE_SHARE", &share);
}
match apply(data, &share, &stamp()) {
Ok(None) => None,
Ok(Some(backup)) => {
tracing::info!(backup = %backup.display(), "save import: put in place; the save it replaced was zipped first");
Some(format!("save imported (the save it replaced was zipped to {})", backup.display()))
}
Err(e) => {
tracing::warn!(error = %e, "save import: not put in place; the save is as it was");
Some(format!("the save import failed ({e}); the save is as it was"))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn folder(name: &str) -> PathBuf {
let p = std::env::temp_dir().join(format!("victory-save-share-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&p);
std::fs::create_dir_all(&p).unwrap();
p
}
fn put(path: &Path, text: &str) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
fn read(path: &Path) -> String {
std::fs::read_to_string(path).unwrap_or_default()
}
const SLOT: &str = "saves/0009000000000001/00000000-0000-0000-0000-00007952987a/Player~333dc56ddffd8ea0/v34/0";
#[test]
fn an_exported_zip_imports_on_another_pc_and_the_old_save_is_kept() {
let (mine, theirs, share, third) = (folder("mine"), folder("theirs"), folder("share"), folder("third"));
let big = "progress ".repeat(10_000); // packs small: deflated
put(&mine.join(SLOT), &big);
put(&mine.join("storage/settings/a"), "my storage");
std::fs::create_dir_all(mine.join("saves/empty folder")).unwrap();
put(&theirs.join(SLOT), "their progress");
// Export: one zip, the save left as it was.
let out = export(&mine, &share, "save 1").unwrap();
assert_eq!(out, share.join("save 1.zip"));
assert!(std::fs::metadata(&out).unwrap().len() < 10_000, "deflated");
assert_eq!(read(&mine.join(SLOT)), big);
assert!(export(&mine, &share, "save 1").is_err(), "an export never writes over another");
assert_eq!(exports(&share), ["save 1.zip"]);
// Import on the other PC: staged, put in place at the next start.
stage(&theirs, &share, "save 1.zip").unwrap();
assert!(staged(&theirs));
assert_eq!(read(&theirs.join(SLOT)), "their progress", "nothing changes while the game runs");
let backup = apply(&theirs, &share, "t1").unwrap().unwrap();
assert_eq!(read(&theirs.join(SLOT)), big);
assert_eq!(read(&theirs.join("storage/settings/a")), "my storage");
assert!(theirs.join("saves/empty folder").is_dir());
assert!(!staged(&theirs));
assert_eq!(apply(&theirs, &share, "t2").unwrap(), None, "applied once");
// The backup is a zip of the save it replaced.
assert_eq!(backup, share.join("backup before import t1.zip"));
stage(&third, &share, "backup before import t1.zip").unwrap();
apply(&third, &share, "t3").unwrap();
assert_eq!(read(&third.join(SLOT)), "their progress");
for f in [mine, theirs, share, third] {
let _ = std::fs::remove_dir_all(f);
}
}
#[test]
fn a_zip_zipped_again_by_hand_imports_and_one_reaching_out_is_refused() {
let (data, share) = (folder("byhand"), folder("share-byhand"));
let t = (0, 0);
// As Windows' "Compress to ZIP file" makes it: the export's folder around it.
let wrapped = zip::write(
&[
("save 1/".to_owned(), Vec::new()),
(format!("save 1\\{}", SLOT.replace('/', "\\")), b"progress".to_vec()),
("save 1/readme.txt".to_owned(), b"hi".to_vec()),
],
t,
)
.unwrap();
std::fs::write(share.join("wrapped.zip"), wrapped).unwrap();
stage(&data, &share, "wrapped.zip").unwrap();
apply(&data, &share, "t").unwrap();
assert_eq!(read(&data.join(SLOT)), "progress");
assert!(!data.join("readme.txt").exists());
// Names that would land outside the save are refused, and nothing is staged.
for name in ["saves/../../evil.dll", "saves/C:/evil", "../saves/x"] {
let zipped = zip::write(&[("saves/ok".to_owned(), b"1".to_vec()), (name.to_owned(), b"x".to_vec())], t).unwrap();
std::fs::write(share.join("evil.zip"), zipped).unwrap();
assert!(stage(&data, &share, "evil.zip").is_err(), "{name}");
assert!(!staged(&data), "{name}");
}
// A damaged zip, and one with no save in it.
let mut damaged = zip::write(&[("saves/a".to_owned(), b"some bytes here".to_vec())], t).unwrap();
damaged[30 + "saves/a".len() + 2] ^= 0xff; // in the file's bytes, after its local header
std::fs::write(share.join("damaged.zip"), damaged).unwrap();
assert!(stage(&data, &share, "damaged.zip").is_err());
std::fs::write(share.join("other.zip"), zip::write(&[("photo.png".to_owned(), vec![1])], t).unwrap()).unwrap();
assert_eq!(stage(&data, &share, "other.zip").unwrap_err().kind(), io::ErrorKind::NotFound);
std::fs::write(share.join("not a zip.zip"), b"hello").unwrap();
assert!(stage(&data, &share, "not a zip.zip").is_err());
assert!(!staged(&data));
for f in [data, share] {
let _ = std::fs::remove_dir_all(f);
}
}
#[test]
fn a_zip_of_what_is_inside_the_saves_folder_imports() {
let (data, share) = (folder("inside"), folder("share-inside"));
let t = (0, 0);
let slot = SLOT.strip_prefix("saves/").unwrap();
let from_scid = slot.strip_prefix("0009000000000001/").unwrap();
let from_container = from_scid.strip_prefix("00000000-0000-0000-0000-00007952987a/").unwrap();
// Zipped from the player's folder (as one shared save was), from the title's, from the
// containers themselves, and inside another folder of the zip's own.
for (n, name) in [slot.to_owned(), from_scid.to_owned(), from_container.to_owned(), format!("mine/{slot}")].iter().enumerate() {
let text = format!("progress {n}");
let mut dirs: Vec<(String, Vec<u8>)> = Vec::new();
let mut at = 0;
while let Some(i) = name[at..].find('/') {
at += i + 1;
dirs.push((name[..at].to_owned(), Vec::new()));
}
dirs.push((name.clone(), text.clone().into_bytes()));
dirs.push(("readme.txt".to_owned(), b"hi".to_vec()));
std::fs::write(share.join("inside.zip"), zip::write(&dirs, t).unwrap()).unwrap();
stage(&data, &share, "inside.zip").unwrap();
apply(&data, &share, &format!("t{n}")).unwrap();
assert_eq!(read(&data.join(SLOT)), text, "{name}");
assert!(!data.join("readme.txt").exists() && !data.join("saves").join("readme.txt").exists());
}
for f in [data, share] {
let _ = std::fs::remove_dir_all(f);
}
}
#[test]
fn the_game_settings_are_never_shared_and_the_players_own_are_kept() {
let (mine, theirs, share) = (folder("set-mine"), folder("set-theirs"), folder("set-share"));
let user = "saves/0009000000000001/00000000-0000-0000-0000-00007952987a";
let settings = format!("{user}/SettingsProfileSettings~0b4e25fca06268d0/v5/0");
put(&mine.join(SLOT), "my progress");
put(&mine.join(&settings), "my settings");
put(&theirs.join(SLOT), "their progress");
put(&theirs.join(&settings), "their settings");
// Export: no settings in the zip.
let out = export(&mine, &share, "save").unwrap();
let names: Vec<String> = zip::read(&std::fs::read(&out).unwrap()).unwrap().into_iter().map(|e| e.0).collect();
assert!(names.iter().any(|n| n == SLOT), "{names:?}");
assert!(!names.iter().any(|n| n.contains("SettingsProfileSettings")), "{names:?}");
// Import: their progress replaced, their settings kept.
stage(&theirs, &share, "save.zip").unwrap();
apply(&theirs, &share, "t").unwrap();
assert_eq!(read(&theirs.join(SLOT)), "my progress");
assert_eq!(read(&theirs.join(&settings)), "their settings");
// A zip made before settings were left out: they are passed over on import.
let older = zip::write(&[(SLOT.to_owned(), b"old progress".to_vec()), (settings.clone(), b"old settings".to_vec())], (0, 0)).unwrap();
std::fs::write(share.join("older.zip"), older).unwrap();
stage(&theirs, &share, "older.zip").unwrap();
apply(&theirs, &share, "t2").unwrap();
assert_eq!(read(&theirs.join(SLOT)), "old progress");
assert_eq!(read(&theirs.join(&settings)), "their settings");
for f in [mine, theirs, share] {
let _ = std::fs::remove_dir_all(f);
}
}
#[test]
fn nothing_to_export_or_import_is_refused() {
let (data, share) = (folder("empty"), folder("share-empty"));
assert!(export(&data, &share, "x").is_err());
std::fs::create_dir_all(share.join("not a save")).unwrap();
std::fs::write(share.join("notes.txt"), "x").unwrap();
assert!(exports(&share).is_empty());
assert!(stage(&data, &share, "not a save").is_err());
assert!(!staged(&data));
// A save folder put in Saves as it is (the first test build's exports) still imports.
put(&share.join("old export").join(SLOT), "old");
assert_eq!(exports(&share), ["old export"]);
stage(&data, &share, "old export").unwrap();
apply(&data, &share, "t").unwrap();
assert_eq!(read(&data.join(SLOT)), "old");
for f in [data, share] {
let _ = std::fs::remove_dir_all(f);
}
}
}
+76 -2
View File
@@ -307,6 +307,44 @@ static FG_ON: AtomicU64 = AtomicU64::new(0);
static FG_OFF: AtomicU64 = AtomicU64::new(0);
static FG_SHOWN: AtomicU64 = AtomicU64::new(0);
static EVALUATED_ALL: AtomicU64 = AtomicU64::new(0);
/// The driver's DLSS refused the evaluations Streamline gave it ("NGX
/// evaluate feature failed", reported through [`log_message`]), and how
/// many. Once nearly every one fails ([`dlss_failing`]), DLSS is left alone
/// for the run and the title's own FidelityFX upscales again: a refused
/// evaluation leaves the output as it was, so the screen stayed black with
/// the sound and subtitles running (#449: an RTX 5060 Ti with the NVIDIA
/// App's DLSS override, which loads its own Streamline plugins and asked
/// every DLSS mode for a 2560x1440 render while the title rendered
/// 1280x720; 599 of about 600 evaluations failed with 0xbad00005).
static NGX_FAILED: AtomicU64 = AtomicU64::new(0);
static DLSS_GIVEN_UP: AtomicBool = AtomicBool::new(false);
/// Failed evaluations from which DLSS is given up, if they are nine in
/// ten of the evaluations recorded.
const NGX_FAILED_ENOUGH: u64 = 90;
/// Whether DLSS is given up for the run (see [`NGX_FAILED`]).
fn dlss_failing(failed: u64, evaluated: u64) -> bool {
failed >= NGX_FAILED_ENOUGH && failed * 10 >= evaluated * 9
}
fn ngx_evaluate_failed(text: &str) {
let failed = NGX_FAILED.fetch_add(1, Relaxed) + 1;
if !DLSS_GIVEN_UP.load(Relaxed)
&& dlss_failing(failed, EVALUATED_ALL.load(Relaxed))
&& !DLSS_GIVEN_UP.swap(true, Relaxed)
{
tracing::error!(
failed,
evaluated = EVALUATED_ALL.load(Relaxed),
last = text,
"DLSS: the driver refused nearly every upscaling, which leaves the picture black; DLSS and frame generation are off for this run and the game's own FSR upscales. If the NVIDIA App has a DLSS override on for this game (Graphics > the program > DLSS Override), turn it off"
);
// Frame generation stops too (see `upscale`): with nothing noted it would show stale frames.
FG_WANTED.store(0, Relaxed);
}
}
static FG_STATUS: AtomicU32 = AtomicU32::new(0);
/// Presents with frame generation on, and frames it showed, in all.
static FG_ON_ALL: AtomicU64 = AtomicU64::new(0);
@@ -610,7 +648,12 @@ unsafe extern "C" fn log_message(kind: u32, message: *const c_char) {
// (Every plugin in the folder that was not asked for says so.)
let noise = text.contains("since it is was not requested by the host");
match kind {
abi::LOG_ERROR => tracing::error!(target: "streamline", "{text}"),
abi::LOG_ERROR => {
tracing::error!(target: "streamline", "{text}");
if text.contains("NGX evaluate feature failed") {
ngx_evaluate_failed(text);
}
}
abi::LOG_WARN if !noise => tracing::warn!(target: "streamline", "{text}"),
_ => tracing::debug!(target: "streamline", "{text}"),
}
@@ -628,9 +671,18 @@ pub fn adapter_name() -> Option<String> {
}
/// Whether a card of this name runs DLSS Frame Generation: a GeForce RTX of
/// the 40 or 50 series ("NVIDIA GeForce RTX 4070 SUPER", "... RTX 5090 Laptop GPU").
/// the 40 or 50 series ("NVIDIA GeForce RTX 4070 SUPER", "... RTX 5090 Laptop GPU"),
/// or a workstation card of those generations ("NVIDIA RTX 2000 Ada Generation",
/// "NVIDIA RTX PRO 4000 Blackwell SFF Edition", #312). Not the older Quadro RTX
/// 4000 to 8000 (Turing) or RTX A2000 to A6000 (Ampere).
pub fn dlss_framegen_card(name: &str) -> bool {
let name = name.to_ascii_uppercase();
if name.contains("QUADRO") {
return false;
}
if name.contains(" ADA") || name.contains("BLACKWELL") || name.contains("RTX PRO") {
return true;
}
let Some(at) = name.find("RTX") else { return false };
let model: String = name[at + 3..].trim_start().chars().take_while(char::is_ascii_digit).collect();
model.len() == 4 && (model.starts_with("40") || model.starts_with("50"))
@@ -1031,6 +1083,12 @@ 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 {
// DLSS given up: the title's own upscaling alone, as in a start without NVIDIA's files.
// Nothing is noted for frame generation (turned off with it, `ngx_evaluate_failed`): the
// title's FidelityFX beside our frame generation stops the title on a check (+0x2219650).
if DLSS_GIVEN_UP.load(Relaxed) {
return Taken::No("the driver refused DLSS's upscalings (DLSS and frame generation are off for the run)");
}
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.)
@@ -2273,3 +2331,19 @@ pub(crate) fn line(frames: f64) {
}
}
}
#[cfg(test)]
mod failing_tests {
use super::dlss_failing;
#[test]
fn dlss_is_given_up_only_when_nearly_every_upscaling_fails() {
// #449: 599 failed of about 600.
assert!(dlss_failing(599, 600));
assert!(dlss_failing(90, 100));
// Too few to tell yet, or a few refusals among working upscalings.
assert!(!dlss_failing(89, 89));
assert!(!dlss_failing(120, 1000));
assert!(!dlss_failing(500, 600));
}
}
+1
View File
@@ -27,6 +27,7 @@ pub use victory_gpu::console;
/// DLSS and frame generation (`VICTORY_DLSS`, `VICTORY_FRAMEGEN`).
#[cfg(windows)]
pub use victory_gpu::streamline;
pub use victory_gpu::save_share;
#[cfg(windows)]
pub use victory_gpu::reserve_upload_space;
#[cfg(all(windows, feature = "diagnostics"))]
+64 -23
View File
@@ -63,11 +63,17 @@ fn err(e: windows::core::Error) -> String {
}
/// The graphics card runs use: the first hardware adapter whose name holds
/// `VICTORY_ADAPTER` (any case), else the hardware adapter with the most
/// memory of its own. Windows' first adapter is often an integrated GPU (a
/// monitor on the board's outputs, a laptop), and a device made with no
/// adapter named runs there. The warm-up, the game's device and DLSS take the
/// same card, so the driver's saved pipelines are the card's that plays.
/// `VICTORY_ADAPTER` (any case); else, of the cards with memory of their own
/// (2 GB or more), the first in Windows' order that a monitor is plugged into;
/// else the hardware adapter with the most memory of its own. Windows' first
/// adapter is often an integrated GPU (a monitor on the board's outputs, a
/// laptop), and a device made with no adapter named runs there. A PC with two
/// cards plays on the one its monitor is on (v2026.11.27.8 took the one with
/// the most memory: an RTX 5060 Ti 16 GB beside the RTX 5070 the monitor was
/// on, every frame then sent across to the 5070). A laptop's card without
/// outputs of its own is still taken over the integrated GPU. The warm-up,
/// the game's device and DLSS take the same card, so the driver's saved
/// pipelines are the card's that plays.
/// None: no hardware adapter (the default device is made then).
pub fn hardware_adapter() -> Option<(IDXGIAdapter1, String, u64)> {
// SAFETY: plain DXGI queries.
@@ -81,49 +87,84 @@ pub fn hardware_adapter() -> Option<(IDXGIAdapter1, String, u64)> {
continue;
}
let len = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len());
all.push((adapter, String::from_utf16_lossy(&desc.Description[..len]), desc.DedicatedVideoMemory as u64));
let monitor = adapter.EnumOutputs(0).is_ok();
all.push((adapter, String::from_utf16_lossy(&desc.Description[..len]), desc.DedicatedVideoMemory as u64, monitor));
}
pick_adapter(all, std::env::var("VICTORY_ADAPTER").ok().as_deref())
}
}
/// The adapter `hardware_adapter` takes from (adapter, name, own memory).
fn pick_adapter<A>(all: Vec<(A, String, u64)>, named: Option<&str>) -> Option<(A, String, u64)> {
/// Own memory from which a card counts as one of its own, not an integrated GPU.
const CARD_MEMORY: u64 = 2 << 30;
/// The adapter `hardware_adapter` takes from (adapter, name, own memory,
/// whether a monitor is plugged into it).
fn pick_adapter<A>(all: Vec<(A, String, u64, bool)>, named: Option<&str>) -> Option<(A, String, u64)> {
let named = named.map(str::trim).filter(|n| !n.is_empty()).map(str::to_lowercase);
let mut shown: Option<(A, String, u64)> = None;
let mut best: Option<(A, String, u64)> = None;
for a in all {
for (adapter, name, own, monitor) in all {
if let Some(n) = &named
&& a.1.to_lowercase().contains(n.as_str())
&& name.to_lowercase().contains(n.as_str())
{
return Some(a);
return Some((adapter, name, own));
}
if best.as_ref().is_none_or(|b| a.2 > b.2) {
best = Some(a);
if monitor && own >= CARD_MEMORY && shown.is_none() {
shown = Some((adapter, name, own));
} else if best.as_ref().is_none_or(|b| own > b.2) {
best = Some((adapter, name, own));
}
}
best
shown.or(best)
}
#[cfg(test)]
mod adapter_tests {
use super::pick_adapter;
fn cards() -> Vec<((), String, u64)> {
type Card = ((), String, u64, bool);
fn cards() -> Vec<Card> {
vec![
((), "Intel(R) Graphics".to_owned(), 128 << 20),
((), "NVIDIA GeForce RTX 4070 Ti".to_owned(), 12 << 30),
((), "AMD Radeon(TM) Graphics".to_owned(), 512 << 20),
((), "Intel(R) Graphics".to_owned(), 128 << 20, true),
((), "NVIDIA GeForce RTX 4070 Ti".to_owned(), 12 << 30, false),
((), "AMD Radeon(TM) Graphics".to_owned(), 512 << 20, false),
]
}
fn name(all: Vec<Card>, named: Option<&str>) -> String {
pick_adapter(all, named).unwrap().1
}
#[test]
fn the_card_with_the_most_own_memory_unless_one_is_named() {
assert_eq!(pick_adapter(cards(), None).unwrap().1, "NVIDIA GeForce RTX 4070 Ti");
assert_eq!(pick_adapter(cards(), Some(" ")).unwrap().1, "NVIDIA GeForce RTX 4070 Ti");
assert_eq!(pick_adapter(cards(), Some("intel")).unwrap().1, "Intel(R) Graphics");
// A laptop: the monitor on the integrated GPU, the card without outputs.
assert_eq!(name(cards(), None), "NVIDIA GeForce RTX 4070 Ti");
assert_eq!(name(cards(), Some(" ")), "NVIDIA GeForce RTX 4070 Ti");
assert_eq!(name(cards(), Some("intel")), "Intel(R) Graphics");
// A name no card has: the rule as without one.
assert_eq!(pick_adapter(cards(), Some("arc b580")).unwrap().1, "NVIDIA GeForce RTX 4070 Ti");
assert!(pick_adapter(Vec::<((), String, u64)>::new(), None).is_none());
assert_eq!(name(cards(), Some("arc b580")), "NVIDIA GeForce RTX 4070 Ti");
assert!(pick_adapter(Vec::<Card>::new(), None).is_none());
}
#[test]
fn of_two_cards_the_one_the_monitor_is_on() {
let two = || {
vec![
((), "NVIDIA GeForce RTX 5070".to_owned(), 12 << 30, true),
((), "NVIDIA GeForce RTX 5060 Ti".to_owned(), 16 << 30, false),
]
};
assert_eq!(name(two(), None), "NVIDIA GeForce RTX 5070");
assert_eq!(name(two(), Some("5060")), "NVIDIA GeForce RTX 5060 Ti");
// Monitors on both: Windows' first.
let mut both = two();
both[1].3 = true;
assert_eq!(name(both, None), "NVIDIA GeForce RTX 5070");
// No monitor on either (a remote session): the most memory.
let mut none = two();
none[0].3 = false;
assert_eq!(name(none, None), "NVIDIA GeForce RTX 5060 Ti");
}
}