diff --git a/Play-MyRig.cmd b/Play-MyRig.cmd new file mode 100644 index 000000000..2d572cef3 --- /dev/null +++ b/Play-MyRig.cmd @@ -0,0 +1,17 @@ +@echo off +rem Double click: checks this PC, then starts the game with settings worked out for it (scripts\play-rig.ps1, +rem docs\rig-launcher.md). ASCII only. +rem Play-MyRig.cmd check, then play (asks once for game_scarlett_master.exe) +rem Play-MyRig.cmd -Check only the checks, the settings and the command +rem Play-MyRig.cmd -Summary what the newest run's log says +rem Play-MyRig.cmd -Cores pcores the title's threads on the fast cores as well (compare with -Summary) +setlocal +set "PS1=%~dp0scripts\play-rig.ps1" +if not exist "%PS1%" ( + echo Not found: %PS1% + pause + exit /b 1 +) +powershell -NoProfile -ExecutionPolicy Bypass -File "%PS1%" %* +echo. +pause diff --git a/README.md b/README.md index 29f9b109a..bbbc610dd 100644 --- a/README.md +++ b/README.md @@ -346,6 +346,12 @@ delete that file to go back to them. Full screen: start the game, then run `.\scripts\fullscreen.ps1` in another window. Logs go to `%LOCALAPPDATA%\victory\logs`, saves to `%LOCALAPPDATA%\victory\data`. +`Play-MyRig.cmd` (`scripts\play-rig.ps1`) is a wrapper around `victory.exe play` +that checks the PC first (commit room, a game process left behind, fast and slow +cores, the card's memory) and picks the settings for it. Its `-Summary` turns a +run's log into frame rate, stalls and memory numbers, so settings can be compared. +See [docs/rig-launcher.md](docs/rig-launcher.md). + If the menu works but loading a scene closes the game, see the [Windows memory troubleshooting guide](docs/windows-memory.md). It shows how to check memory on systems with 32 GB of RAM or GPUs with 8 GB of VRAM. diff --git a/docs/rig-launcher.md b/docs/rig-launcher.md new file mode 100644 index 000000000..1f6ae613e --- /dev/null +++ b/docs/rig-launcher.md @@ -0,0 +1,95 @@ +# The rig launcher (`Play-MyRig.cmd`, `scripts\play-rig.ps1`) + +A wrapper around `victory.exe play` that looks at the PC first and starts the game with settings +worked out for it. It changes nothing in the layer or in the title's files: it picks options and +`--set` switches, checks what made earlier runs fail, and watches the game's process while it runs. + +```powershell +.\Play-MyRig.cmd # double click: checks, then plays +.\scripts\play-rig.ps1 -Exe 'D:\MyDump\game_scarlett_master.exe' # once; the path is remembered +.\scripts\play-rig.ps1 -Check # the checks, the settings and the command only +.\scripts\play-rig.ps1 -Summary # the newest run's log: fps, stalls, memory, crash +``` + +It was built on, and for, this PC: + +| | | +|---|---| +| CPU | Intel Core i5-13600K: 6 fast cores (12 threads) and 8 slow cores | +| GPU | GeForce RTX 4080 16 GB, driver 621.40 | +| RAM | 32 GB DDR5 (at 4800 MT/s; the sticks are rated 5600) | +| Windows | Windows 10 22H2 (build 19045), D3D12 Agility runtime 1.614 beside victory.exe | +| Disk | the dump on an NVMe drive | +| Display | 2560x1440 at 240 Hz, hardware-accelerated GPU scheduling on | + +Everything it decides is read from the PC at each start, so it also picks sensible settings +elsewhere, but the measured basis below is from this one. + +## What two runs on this PC showed + +Both runs used `victory.exe` on its own (Series X, native 1440p, DLSS Quality, no frame generation). + +1. **It ran out of memory to commit.** Six seconds in, the layer warned of host memory pressure with + 3.9 GB of commit left (Windows' commit limit is RAM plus page file: 47.8 GB here, with a fixed + 16 GB page file, and about 20 GB already taken by other programs). Two minutes later, 89 + `no shared buffer ... 0x8007000E` warnings ended in `a host command list did not close`, and + the run was over. This is the failure in [windows-memory.md](windows-memory.md). +2. **It sat at 2-3 frames a second after loading into the world** for about 30 s, with the card + about 9 % busy. The driver was building the world's pipelines for the first time (the log's + pipeline library: 662 made at the end). A shader preload builds them ahead. + +## What it does about it + +| On this PC | Why | +|---|---| +| Stops before starting if a `victory.exe` is still running, and offers to end it | the F1 menu's SAVE AND RESTART can leave one behind without a window, holding its memory | +| Checks free commit: wants about 32 GB, lists what holds the most if there is less | the crash above | +| `VICTORY_PIPELINE_WORKERS=4` under 32 GB free, `2` under 26 GB (the layer's own choice here: 8) | the 32 GB reports in windows-memory.md ran out while pipelines were being made; fxceless #777 throttles the same workers. A preload leaves few to make in play | +| Recommends a page file that puts the commit limit at RAM + 32 GB (here: 32,768 MB or "System managed") | a change only you make: sysdm.cpl, then a restart | +| Preloads shaders (`play --preload`) once for each victory.exe and graphics driver, asked first | the 2-3 fps stretch above; both change what the pipelines are | +| DLSS frame generation 2x | an RTX 40 with GPU scheduling on; the layer renders near 30 fps, so this is where smoothness comes from | +| `VICTORY_TEXTURE_ROOM_PERCENT=84` | the launcher's 80 keeps a fifth of the card's budget for frame generation, sized for a 12 GB card; it needs about 2 GB, so a 16 GB card keeps 2.4 GB and gives the rest to textures | +| Series X at native 1440p, DLSS Quality, no frame cap | the monitor is 2560x1440 at 240 Hz | +| Makes the window borderless full screen once it is up, and again after an F1 restart | the layer fits its window inside the screen (2488x1400 here), which scales a 2560x1440 picture down; full screen shows it pixel for pixel. Frame generation also needs the window in focus | +| Writes a summary after each run and a line in `%LOCALAPPDATA%\victory\rig-runs.csv` | so a change of settings can be measured, not guessed | + +The settings go to `victory.exe play` as options and `--set` switches, so the F1 menu's SAVE AND +RESTART keeps them. What the F1 menu saved still wins over the options, as at every start. + +It also notes what only you can change: XMP/EXPO off in the BIOS (memory speed matters to this +CPU-bound layer), a power-saving plan, the game on a hard disk or SATA drive. + +## The fast and slow cores (`-Cores pcores`) + +The layer already keeps its own threads that a frame waits for on the fast cores +(`VICTORY_FAST_CORES`, `crates\victory-gpu\src\cores.rs`; the log says `fast=12 of=20` here). +The title's own threads are left to Windows, and Windows 10 has no Thread Director to steer them. + +`-Cores pcores` sets the game process's default CPU sets to the fast cores, so that every thread that +picks none of its own prefers them: the title's, and also the layer's pipeline, streaming and +list-translating workers. It is a preference, not a hard affinity mask. It is off by default because +`cores.rs` measured the opposite for the list-translating threads (more threads than the fast cores +run at once, with the slow cores idle), and it is not measured on this PC yet. Compare it: + +```powershell +.\scripts\play-rig.ps1 # play the same stretch, then +.\scripts\play-rig.ps1 -Cores pcores # the same stretch again +Import-Csv $env:LOCALAPPDATA\victory\rig-runs.csv | Format-Table +``` + +The summary's numbers come from the layer's own once-a-second frame-time lines. Seconds drawn faster +than 125 frames a second (menus, loading screens) are left out; "under 10 fps" counts the stalls. + +## Options + +| Option | What | +|---|---| +| `-Exe`, `-Victory` | the title's exe and victory.exe; remembered in `%LOCALAPPDATA%\victory\rig-launcher.json` | +| `-Check` | checks, settings and the command, nothing started | +| `-Summary [-Log ]` | a run's summary only | +| `-Cores layer` / `pcores` | see above | +| `-Dlss`, `-Res`, `-FrameGen 0..6`, `-NoFrameGen`, `-SeriesS`, `-Fps` | override what it picked | +| `-Preload auto` / `yes` / `no` | the shader preload | +| `-NoFullscreen` | leave the window as the layer makes it | +| `-Set VICTORY_X=1` | add or override any switch (`-Set "VICTORY_A=1,VICTORY_B=2"` from cmd) | +| `-Yes` | take the default answer to every question | diff --git a/scripts/play-rig.ps1 b/scripts/play-rig.ps1 new file mode 100644 index 000000000..28a3225c6 --- /dev/null +++ b/scripts/play-rig.ps1 @@ -0,0 +1,717 @@ +# Starts the title on VIctory-NVIDIA with settings worked out for THIS PC: the processor's fast and slow cores, +# the card and its memory, how much memory Windows can still commit, the disk, the monitor. A wrapper around +# `victory.exe play`; the layer and the title's files are not changed. +# +# .\Play-MyRig.cmd double click: checks this PC, then plays +# .\scripts\play-rig.ps1 -Exe 'D:\MyDump\game_scarlett_master.exe' (remembered after the first time) +# .\scripts\play-rig.ps1 -Check only the checks, the settings and the command it would run +# .\scripts\play-rig.ps1 -Summary what the newest run's log says (fps, stalls, memory, crash) +# .\scripts\play-rig.ps1 -Cores pcores also keep the title's threads on the fast cores (try A/B) +# .\scripts\play-rig.ps1 -NoFrameGen -Dlss dlaa override what it picked +# .\scripts\play-rig.ps1 -Set VICTORY_X=1 add or override any switch (as often as needed) +# +# What it does, in order (docs/rig-launcher.md has the why of each): +# 1. Looks at the PC: CPU fast/slow cores, GPU, VRAM, driver, RAM, commit room, page file, the game's disk, +# Windows build and its Direct3D 12 runtime, GPU scheduling, power plan, monitor. +# 2. Checks what stopped earlier runs: a game process left behind without a window, and too little room +# to commit memory (the E_OUTOFMEMORY "no shared buffer" crash). +# 3. Picks the options and switches for this PC and starts `victory.exe play` with them (`--set`, so the F1 +# menu's SAVE AND RESTART keeps them). Preloads shaders the first time for this victory.exe and driver. +# 4. While the game runs: makes its window borderless full screen at the monitor's size (one game pixel per +# screen pixel) and, with -Cores pcores, keeps the title's threads on the fast cores; again after a +# restart from the F1 menu. +# 5. After it closes: a summary of the run's log, and a line in %LOCALAPPDATA%\victory\rig-runs.csv so runs +# with different settings can be compared. +# +# Windows PowerShell 5.1 or PowerShell 7. ASCII only (5.1 reads files without a BOM as ANSI). +[CmdletBinding()] +param( + # The title's game_scarlett_master.exe. Not given: VICTORY_GAME_DIR, the last one used, victory.toml's + # game_dir, else asked. + [string]$Exe, + # victory.exe. Not given: the last one used, the one beside the title, else target\release here. + [string]$Victory, + # Only the checks, the settings and the command; nothing is started. + [switch]$Check, + # Only the summary of the newest run's log (or of -Log). + [switch]$Summary, + [string]$Log, + # layer: the layer's own placement (its threads a frame waits for on the fast cores; the default). + # pcores: the title's threads too, through the process's default CPU sets (a preference, not a hard mask). + [ValidateSet('layer', 'pcores')][string]$Cores = 'layer', + [ValidateSet('auto', 'off', 'dlaa', 'quality', 'balanced', 'performance')][string]$Dlss = 'auto', + [ValidateSet('auto', '1440', '1080to1440', '4k')][string]$Res = 'auto', + # Frames shown for each one rendered, 2 to 6 (0: off). Not given: 2 on an RTX 40 or 50 with GPU scheduling on. + [ValidateRange(-1, 6)][int]$FrameGen = -1, + [switch]$NoFrameGen, + [switch]$SeriesS, + # Frames a second at most (0: no cap, 1000 to the layer). + [ValidateRange(0, 1000)][int]$Fps = 0, + # auto: once for each victory.exe and graphics driver (asked); yes: now; no: not. + [ValidateSet('auto', 'yes', 'no')][string]$Preload = 'auto', + [switch]$NoFullscreen, + # Add or override a switch: -Set VICTORY_X=1,VICTORY_Y=2 + [string[]]$Set = @(), + # Take the default answer to every question. + [switch]$Yes +) +$ErrorActionPreference = 'Continue' +$repo = Split-Path $PSScriptRoot -Parent +$vhome = if ($env:VICTORY_HOME) { $env:VICTORY_HOME } else { Join-Path $env:LOCALAPPDATA 'victory' } +New-Item -ItemType Directory -Force $vhome | Out-Null +$stateFile = Join-Path $vhome 'rig-launcher.json' +$runsFile = Join-Path $vhome 'rig-runs.csv' +$interactive = [Environment]::UserInteractive -and -not [Console]::IsInputRedirected -and -not $Yes + +# Commit room the title and the layer need. Measured on an i5-13600K / RTX 4080 / 32 GB PC (2026-11-28, Series X +# 1440p, DLSS Quality): the run that ended in E_OUTOFMEMORY ("no shared buffer", then "a host command list did not +# close") had 3.9 GB of commit left six seconds in, with about 20 GB already taken by other programs; the title +# and the layer held about 24 GB by then, and more while the world loads. +$CommitComfortGB = 32 +$CommitTightGB = 26 +# What DLSS frame generation takes of the card's memory (play.rs: "1.5 to 2 GB"), plus a margin. +$FrameGenVramMB = 2300 + +Add-Type -TypeDefinition @' +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +public static class RigNative { + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool GetSystemCpuSetInformation(IntPtr information, uint bufferLength, out uint returnedLength, IntPtr process, uint flags); + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool SetProcessDefaultCpuSets(IntPtr process, uint[] cpuSetIds, uint cpuSetIdCount); + [DllImport("kernel32.dll", SetLastError = true)] + static extern IntPtr OpenProcess(uint access, bool inherit, int pid); + [DllImport("kernel32.dll")] + static extern bool CloseHandle(IntPtr handle); + + // The system's CPU sets: { id, group, logical processor index, core index, efficiency class (higher: faster) }. + public static List CpuSets() { + List sets = new List(); + uint length = 0; + GetSystemCpuSetInformation(IntPtr.Zero, 0, out length, IntPtr.Zero, 0); + if (length == 0) return sets; + IntPtr buffer = Marshal.AllocHGlobal((int)length); + try { + if (!GetSystemCpuSetInformation(buffer, length, out length, IntPtr.Zero, 0)) return sets; + int at = 0; + while (at + 20 <= (int)length) { + int size = Marshal.ReadInt32(buffer, at); + if (size <= 0) break; + if (Marshal.ReadInt32(buffer, at + 4) == 0) { // CpuSetInformation + sets.Add(new uint[] { + (uint)Marshal.ReadInt32(buffer, at + 8), + (uint)(ushort)Marshal.ReadInt16(buffer, at + 12), + Marshal.ReadByte(buffer, at + 14), + Marshal.ReadByte(buffer, at + 15), + Marshal.ReadByte(buffer, at + 18) }); + } + at += size; + } + } finally { Marshal.FreeHGlobal(buffer); } + return sets; + } + + // The process's threads that choose no CPU sets of their own run on these (a preference the scheduler keeps + // while any of them is free; the layer's own frame threads keep the sets they chose). + public static string PreferCpuSets(int pid, uint[] ids) { + IntPtr process = OpenProcess(0x2000 | 0x1000, false, pid); // SET_LIMITED_INFORMATION | QUERY_LIMITED_INFORMATION + if (process == IntPtr.Zero) return "could not open it (error " + Marshal.GetLastWin32Error() + ")"; + try { + if (SetProcessDefaultCpuSets(process, ids, (uint)ids.Length)) return "ok"; + return "refused (error " + Marshal.GetLastWin32Error() + ")"; + } finally { CloseHandle(process); } + } + + [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; } + [StructLayout(LayoutKind.Sequential)] public struct MONITORINFO { public int cbSize; public RECT rcMonitor, rcWork; public uint dwFlags; } + [DllImport("user32.dll")] public static extern bool SetProcessDPIAware(); + [DllImport("user32.dll")] static extern IntPtr MonitorFromWindow(IntPtr window, uint flags); + [DllImport("user32.dll")] static extern bool GetMonitorInfo(IntPtr monitor, ref MONITORINFO info); + [DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW")] static extern IntPtr SetWindowLongPtr(IntPtr window, int index, IntPtr value); + [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr window, IntPtr after, int x, int y, int cx, int cy, uint flags); + [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window); + + // The window borderless and the size of its monitor (scripts\fullscreen.ps1 does the same once). + public static string Borderless(IntPtr window) { + IntPtr monitor = MonitorFromWindow(window, 2); + MONITORINFO info = new MONITORINFO(); + info.cbSize = Marshal.SizeOf(info); + if (!GetMonitorInfo(monitor, ref info)) return "no monitor"; + RECT r = info.rcMonitor; + SetWindowLongPtr(window, -16, new IntPtr(0x90000000L)); // WS_POPUP | WS_VISIBLE + SetWindowPos(window, IntPtr.Zero, r.Left, r.Top, r.Right - r.Left, r.Bottom - r.Top, 0x0060); // FRAMECHANGED | SHOWWINDOW + SetForegroundWindow(window); + return (r.Right - r.Left) + "x" + (r.Bottom - r.Top); + } +} +'@ +[void][RigNative]::SetProcessDPIAware() + +function Write-Line([string]$tag, [string]$text) { + $color = switch ($tag) { 'OK' { 'Green' } 'WARN' { 'Yellow' } 'FIX' { 'Red' } default { 'Gray' } } + Write-Host (' [{0,-4}] ' -f $tag) -ForegroundColor $color -NoNewline + Write-Host $text +} + +function Read-YesNo([string]$question, [bool]$default) { + if (-not $interactive) { return $default } + $hint = if ($default) { '[Y/n]' } else { '[y/N]' } + $answer = Read-Host "$question $hint" + if ([string]::IsNullOrWhiteSpace($answer)) { return $default } + return $answer.Trim().ToLowerInvariant().StartsWith('y') +} + +function Read-State { + if (Test-Path -LiteralPath $stateFile) { + try { return Get-Content -LiteralPath $stateFile -Raw | ConvertFrom-Json } catch { } + } + return [pscustomobject]@{} +} + +function Save-State($state) { + $state | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $stateFile -Encoding UTF8 +} + +function Set-StateValue($state, [string]$name, $value) { + if ($state.PSObject.Properties[$name]) { $state.$name = $value } else { $state | Add-Member -NotePropertyName $name -NotePropertyValue $value } +} + +# --------------------------------------------------------------------------------------------------------------- +# The PC +# --------------------------------------------------------------------------------------------------------------- +function Get-Rig([string]$gameExe, [string]$victoryExe) { + $os = Get-CimInstance Win32_OperatingSystem + $cpu = Get-CimInstance Win32_Processor | Select-Object -First 1 + $build = [Environment]::OSVersion.Version.Build + + # Fast and slow cores, as the layer sees them (crates\victory-gpu\src\cores.rs reads the same efficiency classes). + $sets = @([RigNative]::CpuSets() | Where-Object { $_[1] -eq 0 }) + $best = ($sets | ForEach-Object { $_[4] } | Measure-Object -Maximum).Maximum + $fast = @($sets | Where-Object { $_[4] -eq $best }) + $slow = @($sets | Where-Object { $_[4] -ne $best }) + $hybrid = $slow.Count -gt 0 + + # The card: nvidia-smi where there is one, else what Windows says. + $gpu = [pscustomobject]@{ Name = ''; VramMB = 0; Driver = ''; Nvidia = $false; Refresh = 0; Width = 0; Height = 0 } + $smi = Get-Command nvidia-smi -ErrorAction SilentlyContinue + if ($smi) { + $row = & $smi.Source --query-gpu=name,memory.total,driver_version --format=csv,noheader,nounits 2>$null | Select-Object -First 1 + if ($row -match '^\s*(.+?),\s*(\d+),\s*([\d.]+)\s*$') { + $gpu.Name = $Matches[1]; $gpu.VramMB = [int]$Matches[2]; $gpu.Driver = $Matches[3]; $gpu.Nvidia = $true + } + } + $controllers = @(Get-CimInstance Win32_VideoController) + $shown = $controllers | Where-Object { $_.CurrentVerticalResolution } | Sort-Object CurrentVerticalResolution -Descending | Select-Object -First 1 + if ($shown) { $gpu.Width = [int]$shown.CurrentHorizontalResolution; $gpu.Height = [int]$shown.CurrentVerticalResolution; $gpu.Refresh = [int]$shown.CurrentRefreshRate } + if (-not $gpu.Name) { + $card = $controllers | Where-Object { $_.Name -match 'NVIDIA|AMD|Radeon|Arc' } | Select-Object -First 1 + if (-not $card) { $card = $controllers | Select-Object -First 1 } + if ($card) { + $gpu.Name = $card.Name; $gpu.Driver = $card.DriverVersion; $gpu.Nvidia = $card.Name -match 'NVIDIA' + # Win32_VideoController stops at 4 GB; the driver's own key does not. + $key = 'HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}' + Get-ChildItem $key -ErrorAction SilentlyContinue | ForEach-Object { + $p = Get-ItemProperty $_.PSPath -ErrorAction SilentlyContinue + if ($p.DriverDesc -eq $card.Name -and $p.'HardwareInformation.qwMemorySize') { $gpu.VramMB = [int]([int64]$p.'HardwareInformation.qwMemorySize' / 1MB) } + } + } + } + $generation = if ($gpu.Name -match 'RTX\s*(\d{2})\d{2}') { [int]$Matches[1] } else { 0 } + + $hags = (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\GraphicsDrivers' -Name HwSchMode -ErrorAction SilentlyContinue).HwSchMode -eq 2 + + $sticks = @(Get-CimInstance Win32_PhysicalMemory) + $ramSpeed = ($sticks | ForEach-Object { if ($_.ConfiguredClockSpeed) { $_.ConfiguredClockSpeed } else { $_.Speed } } | Measure-Object -Minimum).Minimum + # The speed the sticks are sold at, where the part number says it (CMK32GX5M2B5600C36: 5600). + $rated = 0 + foreach ($s in $sticks) { + foreach ($m in [regex]::Matches([string]$s.PartNumber, '\d{4}')) { $v = [int]$m.Value; if ($v -ge 2133 -and $v -le 9600 -and $v -gt $rated) { $rated = $v } } + } + + $pagefiles = @(Get-CimInstance Win32_PageFileUsage -ErrorAction SilentlyContinue) + $autoPage = (Get-CimInstance Win32_ComputerSystem).AutomaticManagedPagefile + + $plan = '' + $planLine = powercfg /getactivescheme 2>$null + if ($planLine -match '\(([^)]+)\)\s*$') { $plan = $Matches[1] } + + $disk = $null + if ($gameExe) { + try { + $letter = (Split-Path -Qualifier $gameExe).TrimEnd(':') + $part = Get-Partition -DriveLetter $letter -ErrorAction Stop + $d = Get-Disk -Number $part.DiskNumber -ErrorAction Stop + $pd = Get-PhysicalDisk -ErrorAction SilentlyContinue | Where-Object { $_.DeviceId -eq [string]$d.Number } | Select-Object -First 1 + $disk = [pscustomobject]@{ Letter = $letter; Bus = [string]$d.BusType; Media = if ($pd) { [string]$pd.MediaType } else { '' }; Name = $d.FriendlyName } + } catch { } + } + + $agility = $null + if ($victoryExe) { + $core = Join-Path (Split-Path $victoryExe -Parent) 'D3D12\D3D12Core.dll' + if (Test-Path -LiteralPath $core) { $agility = (Get-Item -LiteralPath $core).VersionInfo.FileVersion } + } + + [pscustomobject]@{ + CpuName = ($cpu.Name -replace '\s+', ' ').Trim() + Logical = $sets.Count + FastIds = [uint32[]]@($fast | ForEach-Object { $_[0] }) + FastLogical = $fast.Count + FastCores = @($fast | ForEach-Object { $_[3] } | Sort-Object -Unique).Count + SlowLogical = $slow.Count + SlowCores = @($slow | ForEach-Object { $_[3] } | Sort-Object -Unique).Count + Hybrid = $hybrid + Gpu = $gpu + RtxGeneration = $generation + Hags = $hags + RamGB = [math]::Round($os.TotalVisibleMemorySize / 1MB, 1) + RamSpeed = $ramSpeed + RamRated = $rated + CommitLimitGB = [math]::Round($os.TotalVirtualMemorySize / 1MB, 1) + CommitFreeGB = [math]::Round($os.FreeVirtualMemory / 1MB, 1) + PageFiles = $pagefiles + PageAuto = $autoPage + Build = $build + Windows10 = $build -lt 22000 + Agility = $agility + Plan = $plan + Disk = $disk + } +} + +function Show-Rig($rig) { + Write-Host '' + Write-Host 'This PC' -ForegroundColor Cyan + $cores = if ($rig.Hybrid) { + "{0} fast cores ({1} threads) + {2} slow cores ({3} threads)" -f $rig.FastCores, $rig.FastLogical, $rig.SlowCores, $rig.SlowLogical + } else { "{0} threads, all alike" -f $rig.Logical } + Write-Host (" CPU {0}: {1}" -f $rig.CpuName, $cores) + $vram = if ($rig.Gpu.VramMB) { '{0:N0} GB' -f ($rig.Gpu.VramMB / 1024) } else { 'memory unknown' } + Write-Host (" GPU {0}, {1}, driver {2}" -f $rig.Gpu.Name, $vram, $rig.Gpu.Driver) + $rated = if ($rig.RamRated -gt $rig.RamSpeed) { " (sticks rated {0})" -f $rig.RamRated } else { '' } + Write-Host (" RAM {0} GB at {1} MT/s{2}" -f [math]::Round($rig.RamGB), $rig.RamSpeed, $rated) + $pf = if ($rig.PageAuto) { 'page file managed by Windows' } elseif ($rig.PageFiles.Count) { 'page file ' + (($rig.PageFiles | ForEach-Object { '{0} {1:N0} GB' -f $_.Name, ($_.AllocatedBaseSize / 1024) }) -join ', ') } else { 'no page file' } + Write-Host (" Commit {0:N1} GB free of {1:N1} GB ({2})" -f $rig.CommitFreeGB, $rig.CommitLimitGB, $pf) + if ($rig.Disk) { Write-Host (" Disk game on {0}: {1} {2} ({3})" -f $rig.Disk.Letter, $rig.Disk.Bus, $rig.Disk.Media, $rig.Disk.Name) } + $win = if ($rig.Windows10) { "Windows 10 build $($rig.Build)" } else { "Windows 11 build $($rig.Build)" } + if ($rig.Windows10) { $win += if ($rig.Agility) { ", D3D12 Agility runtime beside victory.exe ($($rig.Agility))" } else { ', no D3D12 Agility runtime beside victory.exe yet' } } + Write-Host (" Windows {0}" -f $win) + Write-Host (" Display {0}x{1} at {2} Hz; GPU scheduling {3}; power plan {4}" -f $rig.Gpu.Width, $rig.Gpu.Height, $rig.Gpu.Refresh, $(if ($rig.Hags) { 'on' } else { 'off' }), $rig.Plan) +} + +# --------------------------------------------------------------------------------------------------------------- +# Checks +# --------------------------------------------------------------------------------------------------------------- +function Test-Rig($rig, [string]$victoryExe) { + Write-Host '' + Write-Host 'Checks' -ForegroundColor Cyan + + # A game process left behind (the F1 menu's SAVE AND RESTART can leave one without a window) holds its memory. + $left = @(Get-Process victory -ErrorAction SilentlyContinue) + if ($left.Count) { + foreach ($p in $left) { + Write-Line 'FIX' ("victory.exe already running: pid {0}, {1:N1} GB committed, {2}" -f $p.Id, ($p.PrivateMemorySize64 / 1GB), $(if ($p.MainWindowHandle -ne 0) { 'with a window' } else { 'no window (left behind)' })) + } + if (Read-YesNo ' End these victory.exe processes first? Their memory counts against this run.' $false) { + $left | ForEach-Object { Stop-Process -Id $_.Id -ErrorAction SilentlyContinue } + Start-Sleep -Seconds 2 + $os = Get-CimInstance Win32_OperatingSystem + $rig.CommitFreeGB = [math]::Round($os.FreeVirtualMemory / 1MB, 1) + Write-Line 'OK' ("ended; commit free now {0:N1} GB" -f $rig.CommitFreeGB) + } + } else { + Write-Line 'OK' 'no victory.exe left running' + } + + # Room to commit memory: what ended a run on this PC (E_OUTOFMEMORY, "no shared buffer"). + if ($rig.CommitFreeGB -ge $CommitComfortGB) { + Write-Line 'OK' ("{0:N1} GB of commit free (the game wants about {1} GB)" -f $rig.CommitFreeGB, $CommitComfortGB) + } else { + $tag = if ($rig.CommitFreeGB -lt $CommitTightGB) { 'FIX' } else { 'WARN' } + Write-Line $tag ("only {0:N1} GB of commit free of {1:N1} GB; the game wants about {2} GB. Runs ended with E_OUTOFMEMORY" -f $rig.CommitFreeGB, $rig.CommitLimitGB, $CommitComfortGB) + Write-Host ' ("no shared buffer") when it ran out. What holds the most now:' + Get-Process | Group-Object Name | ForEach-Object { + [pscustomobject]@{ Name = $_.Name; GB = ($_.Group | Measure-Object PrivateMemorySize64 -Sum).Sum / 1GB; Count = $_.Count } + } | Sort-Object GB -Descending | Select-Object -First 6 | ForEach-Object { + Write-Host (" {0,-22} {1,5:N1} GB{2}" -f $_.Name, $_.GB, $(if ($_.Count -gt 1) { " ($($_.Count) processes)" } else { '' })) + } + Write-Host ' Closing browsers and chat apps before playing gives it back. This launcher also' + Write-Host ' makes fewer pipelines at a time (VICTORY_PIPELINE_WORKERS) while room is short.' + } + $wantLimit = $rig.RamGB + 32 + if ($rig.CommitLimitGB -lt $wantLimit) { + Write-Line 'WARN' ("the commit limit is {0:N1} GB (RAM + page file). A page file that lets it reach {1:N0} GB or more" -f $rig.CommitLimitGB, $wantLimit) + Write-Host ' keeps the game from running out (docs/windows-memory.md): sysdm.cpl > Advanced > Performance' + Write-Host ' Settings > Advanced > Virtual memory > Change: "System managed size" on the NVMe drive, or a' + Write-Host (" custom size of at least {0:N0} MB, then restart Windows." -f (($wantLimit - $rig.RamGB) * 1024)) + } + + # The card. + if (-not $rig.Gpu.Nvidia) { + Write-Line 'WARN' "$($rig.Gpu.Name): not an NVIDIA card; DLSS is left off (README: FSR 3 on the Series S profile)" + } elseif ($rig.RtxGeneration -ge 40) { + if ($rig.Hags) { Write-Line 'OK' ("RTX {0}: DLSS and DLSS frame generation; GPU scheduling is on, as frame generation needs" -f $rig.RtxGeneration) } + else { Write-Line 'FIX' 'GPU scheduling is off: DLSS frame generation needs it (Settings > Display > Graphics settings > Hardware-accelerated GPU scheduling, then restart)' } + } elseif ($rig.RtxGeneration -ge 20) { + Write-Line 'OK' ("RTX {0}: DLSS; frame generation only through FSR 3 or the MFG Unlocker mod (README)" -f $rig.RtxGeneration) + } + + # Windows 10's own Direct3D 12 stops at shader model 6.5; victory.exe offers Microsoft's newer one when it is missing. + if ($rig.Windows10) { + if ($rig.Agility) { Write-Line 'OK' "Windows 10: Microsoft's D3D12 Agility runtime is beside victory.exe ($($rig.Agility)), for shader model 6.6" } + else { Write-Line 'WARN' "Windows 10 without D3D12\D3D12Core.dll beside victory.exe: victory.exe will offer to fetch it (victory.exe get-d3d12)" } + } + + # The disk: the title streams from it all the time. + if ($rig.Disk) { + if ($rig.Disk.Bus -eq 'NVMe') { Write-Line 'OK' ("the game is on an NVMe drive ({0}:)" -f $rig.Disk.Letter) } + elseif ($rig.Disk.Media -eq 'HDD') { Write-Line 'FIX' ("the game is on a hard disk ({0}:): streaming will stall; move it to an SSD, NVMe best" -f $rig.Disk.Letter) } + else { Write-Line 'WARN' ("the game is on a {0} drive ({1}:); an NVMe drive streams faster" -f $rig.Disk.Bus, $rig.Disk.Letter) } + } + + # Memory speed: the layer leans on the CPU and its memory more than on the card. + if ($rig.RamRated -gt $rig.RamSpeed + 200) { + Write-Line 'WARN' ("RAM runs at {0} MT/s, the sticks are rated {1}: turning on XMP/EXPO in the BIOS speeds up the CPU-bound layer" -f $rig.RamSpeed, $rig.RamRated) + } + if ($rig.Plan -and $rig.Plan -match 'saver|Energiebesparing|Economie') { + Write-Line 'WARN' "power plan '$($rig.Plan)': the CPU is held back; High performance or Balanced is better" + } + if ($rig.Hybrid -and $rig.Windows10) { + Write-Line 'INFO' ("Windows 10 places threads on fast and slow cores without Intel's Thread Director. The layer keeps its own frame threads on the {0} fast" -f $rig.FastLogical) + Write-Host ' threads already; -Cores pcores asks the same for the title''s threads (compare runs with -Summary).' + } +} + +# --------------------------------------------------------------------------------------------------------------- +# Settings for this PC +# --------------------------------------------------------------------------------------------------------------- +function Get-RigSettings($rig) { + $o = [ordered]@{ Console = 'series-x'; Res = '1440'; Dlss = 'quality'; FrameGen = 0; Fps = 1000 } + $switchSet = [ordered]@{} # (not $set: names are not case-sensitive, and -Set is the script's parameter) + $why = New-Object System.Collections.Generic.List[string] + + if ($SeriesS) { $o.Console = 'series-s' } + # The picture: native 1440p where the monitor has the lines for it. + if ($Res -ne 'auto') { $o.Res = $Res } + elseif ($rig.Gpu.Height -ge 1440 -or $rig.Gpu.Height -eq 0) { $o.Res = '1440' } + else { $o.Res = '1080to1440'; $why.Add("res 1080to1440: the monitor has $($rig.Gpu.Height) lines") } + if ($o.Console -eq 'series-x' -and $o.Res -eq '1440') { $why.Add("Series X at a native 2560x1440: the monitor is $($rig.Gpu.Width)x$($rig.Gpu.Height)") } + + # DLSS: on any RTX card; Quality, as tested. The card is rarely the limit on this layer (the run's log: about + # 9 % busy while the CPU side worked), so -Dlss dlaa is the picture to try next. + if ($Dlss -ne 'auto') { $o.Dlss = $Dlss } + elseif ($rig.Gpu.Nvidia -and $rig.RtxGeneration -ge 20) { $o.Dlss = 'quality' } + else { $o.Dlss = 'off'; $why.Add('DLSS off: no RTX card') } + + # Frame generation: DLSS's on an RTX 40/50 with GPU scheduling on. 2x: what an RTX 40 does, and the least + # latency on an RTX 50. The layer is CPU-bound near 30 frames a second, so this is where smoothness comes from. + if ($NoFrameGen) { $o.FrameGen = 0 } + elseif ($FrameGen -ge 0) { $o.FrameGen = if ($FrameGen -eq 1) { 2 } else { $FrameGen } } + elseif ($o.Dlss -ne 'off' -and $rig.RtxGeneration -ge 40 -and $rig.Hags) { $o.FrameGen = 2 } + if ($o.FrameGen -ge 2) { + $why.Add(("DLSS frame generation {0}x: RTX {1} with GPU scheduling on; the layer renders near 30 fps, shown {2}" -f $o.FrameGen, $rig.RtxGeneration, $(if ($o.FrameGen -eq 2) { 'near 60' } else { 'more' }))) + # The launcher keeps a fifth of the card's budget out of the texture pool for frame generation, sized for a + # 12 GB card. Frame generation itself takes about 2 GB; on a bigger card the rest can hold textures. + if ($rig.Gpu.VramMB -gt 0) { + $budget = $rig.Gpu.VramMB * 0.933 # what Windows gives as the budget (16376 MB card: 15280 MB) + $percent = [math]::Floor(100 * ($budget - $FrameGenVramMB) / $budget) + $percent = [math]::Max(80, [math]::Min(90, $percent)) + if ($percent -gt 80) { + $switchSet.VICTORY_TEXTURE_ROOM_PERCENT = [string]$percent + $why.Add(("VICTORY_TEXTURE_ROOM_PERCENT=$percent : {0:N0} GB card, about {1:N1} GB kept for frame generation instead of the 12 GB card's fifth" -f ($rig.Gpu.VramMB / 1024), ((100 - $percent) * $budget / 100 / 1024))) + } + } + } + + if ($Fps -gt 0) { $o.Fps = $Fps; $why.Add("frame cap $Fps") } + elseif ($rig.Gpu.Refresh -ge 100) { $why.Add("no frame cap: a $($rig.Gpu.Refresh) Hz monitor is above anything the layer renders") } + + # Commit room: fewer pipelines made at a time while it is short (docs/windows-memory.md: the 32 GB reports that + # ran out did so while pipelines were being made; fxceless #777 throttles the same workers). The layer's own + # choice on a 32 GB PC is 8. A preload makes most of them before the game, so few are left to make in play. + if ($rig.CommitFreeGB -lt $CommitTightGB) { + $switchSet.VICTORY_PIPELINE_WORKERS = '2' + $why.Add(("VICTORY_PIPELINE_WORKERS=2 : only {0:N1} GB of commit free" -f $rig.CommitFreeGB)) + } elseif ($rig.CommitFreeGB -lt $CommitComfortGB) { + $switchSet.VICTORY_PIPELINE_WORKERS = '4' + $why.Add(("VICTORY_PIPELINE_WORKERS=4 : {0:N1} GB of commit free, under the {1} GB the game wants" -f $rig.CommitFreeGB, $CommitComfortGB)) + } + + if ($Cores -eq 'pcores' -and $rig.Hybrid) { + $why.Add("-Cores pcores: the title's threads prefer the $($rig.FastLogical) fast threads too") + } + + foreach ($pair in $Set) { + # Split before each further VICTORY_ name only: a value can hold commas (VICTORY_LEAVE_OUT). + foreach ($item in ($pair -split ',(?=\s*VICTORY_)')) { + if ($item -match '^\s*(VICTORY_[A-Z0-9_]+)\s*=(.*)$') { $switchSet[$Matches[1]] = $Matches[2].Trim(); $why.Add("$($Matches[1])=$($Matches[2].Trim()) : given with -Set") } + elseif ($item.Trim()) { Write-Line 'WARN' "-Set '$item' is not VICTORY_NAME=value; left out" } + } + } + [pscustomobject]@{ Options = $o; Set = $switchSet; Why = $why } +} + +function Get-PlayArgs([string]$gameExe, $settings, [bool]$preload) { + $o = $settings.Options + $list = New-Object System.Collections.Generic.List[string] + foreach ($a in @('play', $gameExe, '--res', $o.Res, '--dlss', $o.Dlss, '--fg-type', 'auto', '--fps', [string]$o.Fps)) { $list.Add($a) } + if ($o.Console -eq 'series-s') { $list.Add('--series-s') } + if ($o.FrameGen -ge 2) { $list.Add('--framegen'); $list.Add([string]$o.FrameGen) } + if ($preload) { $list.Add('--preload') } + foreach ($k in $settings.Set.Keys) { $list.Add('--set'); $list.Add("$k=$($settings.Set[$k])") } + return , $list.ToArray() +} + +# --------------------------------------------------------------------------------------------------------------- +# A run's log +# --------------------------------------------------------------------------------------------------------------- +function Get-RunSummary([string]$path) { + $lines = [IO.File]::ReadAllLines($path) + $header = $lines | Select-Object -First 1 + $switches = @{} + foreach ($m in [regex]::Matches([string]$header, '(VICTORY_[A-Z0-9_]+)=(\S*)')) { $switches[$m.Groups[1].Value] = $m.Groups[2].Value } + $windows = New-Object System.Collections.Generic.List[double] + $first = $null; $last = $null; $minCommit = $null; $pressure = 0; $oom = 0; $errors = 0; $firstError = $null; $ended = $false + foreach ($line in $lines) { + if ($line -match '^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)') { + $t = [datetime]::ParseExact($Matches[1], "yyyy-MM-dd'T'HH:mm:ss", [Globalization.CultureInfo]::InvariantCulture) + if (-not $first) { $first = $t } + $last = $t + } + if ($line -match 'frame times: (\d+) frames, median ([\d.]+) ms') { + $ms = [double]::Parse($Matches[2], [Globalization.CultureInfo]::InvariantCulture) + # Menus and loading screens draw at hundreds a second; the game's world and its cutscenes do not. + if ($ms -ge 8.0) { $windows.Add(1000.0 / $ms) } + } + if ($line -match 'available_commit_mib=(\d+)') { $v = [int]$Matches[1]; if ($null -eq $minCommit -or $v -lt $minCommit) { $minCommit = $v } } + if ($line -match 'host memory pressure') { $pressure++ } + if ($line -match '0x8007000E') { $oom++ } + if ($line -match '^\S+\s+ERROR\s') { $errors++; if (-not $firstError) { $firstError = $line } } + if ($line -match 'title suspended; ending the title|window closed: suspending the title') { $ended = $true } + } + $sorted = @($windows | Sort-Object) + $pick = { param($q) if ($sorted.Count) { $sorted[[math]::Min($sorted.Count - 1, [math]::Floor($q * $sorted.Count))] } else { $null } } + $crash = $null + if ($path -match '-(\d+)\.log$') { + $procId = $Matches[1] + foreach ($file in Get-ChildItem (Join-Path $vhome 'data\*\crashes.log') -ErrorAction SilentlyContinue) { + $text = Get-Content -LiteralPath $file.FullName + for ($i = 0; $i -lt $text.Count; $i++) { + if ($text[$i] -match "^unix time \d+, process $procId\s*$" -and $i + 1 -lt $text.Count) { $crash = $text[$i + 1] } + } + } + } + [pscustomobject]@{ + Log = Split-Path $path -Leaf + Seconds = if ($first -and $last) { [int]($last - $first).TotalSeconds } else { 0 } + Console = $switches['VICTORY_MENU_CONSOLE'] + Res = $switches['VICTORY_MENU_RES'] + Dlss = $switches['VICTORY_MENU_DLSS'] + FrameGen = $switches['VICTORY_MENU_FRAMEGEN'] + Workers = $switches['VICTORY_PIPELINE_WORKERS'] + Room = $switches['VICTORY_TEXTURE_ROOM_PERCENT'] + GameSeconds = $sorted.Count + FpsMedian = & $pick 0.5 + FpsLow = & $pick 0.05 + Stalls = @($sorted | Where-Object { $_ -lt 10 }).Count + MinCommitMB = $minCommit + Pressure = $pressure + OutOfMemory = $oom + Errors = $errors + FirstError = $firstError + Ended = if ($crash -or ($oom -gt 0 -and -not $ended)) { 'crashed' } elseif ($ended) { 'closed' } else { 'unknown' } + Crash = $crash + } +} + +function Show-RunSummary($s) { + Write-Host '' + Write-Host "Run: $($s.Log)" -ForegroundColor Cyan + Write-Host (" settings {0} {1}, DLSS {2}, frame generation {3}, pipeline workers {4}, texture room {5}" -f $s.Console, $s.Res, $s.Dlss, $(if ($s.FrameGen -and $s.FrameGen -ne '0') { "$($s.FrameGen)x" } else { 'off' }), $(if ($s.Workers) { $s.Workers } else { "layer's" }), $(if ($s.Room) { "$($s.Room) %" } else { "layer's" })) + Write-Host (" length {0}:{1:00}, of it {2} s in the game (not menus or loading screens)" -f [math]::Floor($s.Seconds / 60), ($s.Seconds % 60), $s.GameSeconds) + if ($s.GameSeconds) { + Write-Host (" rendered median {0:N1} fps, slowest 5 % {1:N1} fps, {2} s under 10 fps (pipelines being made or streaming)" -f $s.FpsMedian, $s.FpsLow, $s.Stalls) + } + $commit = if ($null -ne $s.MinCommitMB) { ', lowest commit free {0:N1} GB' -f ($s.MinCommitMB / 1024) } else { '' } + Write-Host (" memory {0} memory-pressure warnings, {1} out-of-memory errors{2}" -f $s.Pressure, $s.OutOfMemory, $commit) + $tag = if ($s.Ended -eq 'crashed') { 'FIX' } elseif ($s.Ended -eq 'closed') { 'OK' } else { 'WARN' } + $end = switch ($s.Ended) { 'crashed' { 'it crashed' } 'closed' { 'it was closed' } default { 'its end is not in the log' } } + Write-Line $tag $end + if ($s.Crash) { Write-Host " $($s.Crash)" } + elseif ($s.FirstError) { Write-Host (" first error: " + $s.FirstError.Substring(0, [math]::Min(200, $s.FirstError.Length))) } + if ($s.OutOfMemory -gt 0) { Write-Host ' Out of memory: close other programs and give Windows a bigger page file (the checks say how).' } + if ($s.Stalls -gt 5) { Write-Host ' Many seconds under 10 fps: a shader preload (-Preload yes) makes those pipelines ahead.' } +} + +function Add-RunRow($s, [string]$cores) { + $new = -not (Test-Path -LiteralPath $runsFile) + $row = [pscustomobject]@{ + When = (Get-Date).ToString('yyyy-MM-dd HH:mm'); Log = $s.Log; Console = $s.Console; Res = $s.Res; Dlss = $s.Dlss + FrameGen = $s.FrameGen; Cores = $cores; Workers = $s.Workers; Room = $s.Room; GameSeconds = $s.GameSeconds + FpsMedian = if ($null -ne $s.FpsMedian) { [math]::Round($s.FpsMedian, 1) } else { '' } + FpsLow = if ($null -ne $s.FpsLow) { [math]::Round($s.FpsLow, 1) } else { '' } + Stalls = $s.Stalls; MinCommitMB = $s.MinCommitMB; OutOfMemory = $s.OutOfMemory; Ended = $s.Ended + } + $csv = $row | ConvertTo-Csv -NoTypeInformation + if ($new) { $csv | Set-Content -LiteralPath $runsFile -Encoding UTF8 } else { $csv | Select-Object -Skip 1 | Add-Content -LiteralPath $runsFile -Encoding UTF8 } +} + +# --------------------------------------------------------------------------------------------------------------- +# -Summary: no start +# --------------------------------------------------------------------------------------------------------------- +if ($Summary) { + $path = if ($Log) { $Log } else { Get-ChildItem (Join-Path $vhome 'logs') -Filter 'victory-nvidia*.log' -ErrorAction SilentlyContinue | Sort-Object LastWriteTime | Select-Object -Last 1 -ExpandProperty FullName } + if (-not $path) { Write-Host "No run logs in $(Join-Path $vhome 'logs')."; return } + Show-RunSummary (Get-RunSummary $path) + if (Test-Path -LiteralPath $runsFile) { Write-Host ''; Write-Host "Earlier runs: $runsFile" } + return +} + +# --------------------------------------------------------------------------------------------------------------- +# The title and victory.exe +# --------------------------------------------------------------------------------------------------------------- +$state = Read-State +$game = $null +$candidates = @() +if ($Exe) { $candidates += $Exe } +if ($env:VICTORY_GAME_DIR) { $candidates += (Join-Path $env:VICTORY_GAME_DIR 'game_scarlett_master.exe') } +if ($state.PSObject.Properties['exe']) { $candidates += $state.exe } +$toml = Join-Path $repo 'victory.toml' +if ((Test-Path -LiteralPath $toml) -and ((Get-Content -LiteralPath $toml -Raw) -match "(?m)^\s*game_dir\s*=\s*['""]([^'""]+)['""]")) { $candidates += (Join-Path $Matches[1] 'game_scarlett_master.exe') } +foreach ($c in $candidates) { + if ($c -and (Test-Path -LiteralPath $c -PathType Container)) { $c = Join-Path $c 'game_scarlett_master.exe' } + if ($c -and (Test-Path -LiteralPath $c -PathType Leaf)) { $game = (Resolve-Path -LiteralPath $c).Path; break } +} +if (-not $game -and $interactive) { + $typed = (Read-Host 'Path to your own dump''s game_scarlett_master.exe (or its folder)').Trim('"', ' ') + if ($typed -and (Test-Path -LiteralPath $typed -PathType Container)) { $typed = Join-Path $typed 'game_scarlett_master.exe' } + if ($typed -and (Test-Path -LiteralPath $typed -PathType Leaf)) { $game = (Resolve-Path -LiteralPath $typed).Path } +} +if (-not $game) { Write-Host 'No game_scarlett_master.exe: give it with -Exe (it is remembered), or set VICTORY_GAME_DIR.'; exit 2 } + +$runner = $null +foreach ($c in @($Victory, $(if ($state.PSObject.Properties['victory']) { $state.victory }), (Join-Path (Split-Path $game -Parent) 'victory.exe'), (Join-Path $repo 'target\release\victory.exe'))) { + if ($c -and (Test-Path -LiteralPath $c -PathType Leaf)) { $runner = (Resolve-Path -LiteralPath $c).Path; break } +} +if (-not $runner) { Write-Host "No victory.exe: put the release's victory.exe beside $game, or build it (cargo build --release --locked -p victory)."; exit 2 } +Set-StateValue $state 'exe' $game +Set-StateValue $state 'victory' $runner + +$rig = Get-Rig $game $runner +Show-Rig $rig +Write-Host '' +Write-Host " Game $game" +Write-Host " Runner $runner" +Test-Rig $rig $runner +$settings = Get-RigSettings $rig + +# A preload for each victory.exe (its bytes) and graphics driver: both change what the pipelines are. +$hash = (Get-FileHash -LiteralPath $runner -Algorithm SHA256).Hash.Substring(0, 16) +$preloadKey = "$hash|$($rig.Gpu.Driver)" +$done = $state.PSObject.Properties['preloaded'] -and $state.preloaded -eq $preloadKey +$doPreload = switch ($Preload) { 'yes' { $true } 'no' { $false } default { -not $done } } + +Write-Host '' +Write-Host 'Settings for this PC' -ForegroundColor Cyan +foreach ($w in $settings.Why) { Write-Host " - $w" } +if ($Preload -eq 'auto') { + if ($done) { Write-Host ' - shaders already preloaded for this victory.exe and driver' } + else { Write-Host " - shader preload: not done yet for this victory.exe and driver $($rig.Gpu.Driver) (the last run sat at 2-3 fps while the world's pipelines were made)" } +} +if (-not $NoFullscreen) { Write-Host ' - borderless full screen at the monitor''s size once the window is up (the layer fits a window inside the screen, scaling the picture)' } + +$playArgs = Get-PlayArgs $game $settings $doPreload +Write-Host '' +Write-Host 'Command' -ForegroundColor Cyan +Write-Host (" & '{0}' {1}" -f $runner, (($playArgs | ForEach-Object { if ($_ -match '[\s'']') { "'" + ($_ -replace "'", "''") + "'" } else { $_ } }) -join ' ')) +Write-Host ' (What the F1 menu saved in victory-settings.txt still goes over these options, as at every start.)' + +if ($Check) { Save-State $state; return } + +if ($Preload -eq 'auto' -and $doPreload) { + $doPreload = Read-YesNo 'Preload shaders before the game starts? A while (more on a first time); what is done is kept.' $true + if (-not $doPreload) { $playArgs = Get-PlayArgs $game $settings $false } +} +if ($rig.CommitFreeGB -lt $CommitTightGB -and -not (Read-YesNo 'Commit room is short and the game may run out of memory. Start anyway?' $true)) { Save-State $state; return } +Save-State $state + +# --------------------------------------------------------------------------------------------------------------- +# While it runs: the window, and the title's threads on the fast cores +# --------------------------------------------------------------------------------------------------------------- +$sync = [hashtable]::Synchronized(@{ Stop = $false; Notes = [System.Collections.ArrayList]::Synchronized((New-Object System.Collections.ArrayList)) }) +$pin = if ($Cores -eq 'pcores' -and $rig.Hybrid) { $rig.FastIds } else { $null } +$watch = { + param($RunnerPath, $PinIds, $MakeBorderless, $Sync) + $seen = @{} + while (-not $Sync.Stop) { + foreach ($p in @(Get-Process victory -ErrorAction SilentlyContinue)) { + $path = $null + try { $path = $p.Path } catch { } + if ($path -ne $RunnerPath) { continue } + $st = $seen[$p.Id] + if (-not $st) { + $cmd = (Get-CimInstance Win32_Process -Filter "ProcessId=$($p.Id)" -ErrorAction SilentlyContinue).CommandLine + $st = @{ Preload = [string]$cmd -match '\spreload\s'; Pinned = $false; Window = [IntPtr]::Zero; WindowAt = $null; Done = $false } + $seen[$p.Id] = $st + } + if ($st.Preload) { continue } # the shader preload: every core is welcome + if ($PinIds -and -not $st.Pinned) { + $r = [RigNative]::PreferCpuSets($p.Id, [uint32[]]$PinIds) + $st.Pinned = $true + [void]$Sync.Notes.Add("pid $($p.Id): the title's threads prefer the fast cores: $r") + } + if ($MakeBorderless -and -not $st.Done) { + $h = $p.MainWindowHandle + if ($h -ne [IntPtr]::Zero) { + if ($st.Window -ne $h) { $st.Window = $h; $st.WindowAt = Get-Date } + elseif (((Get-Date) - $st.WindowAt).TotalSeconds -ge 3) { + $size = [RigNative]::Borderless($h) + $st.Done = $true + [void]$Sync.Notes.Add("pid $($p.Id): window made borderless full screen ($size)") + } + } + } + } + Start-Sleep -Milliseconds 1000 + } +} +$ps = [powershell]::Create() +[void]$ps.AddScript($watch).AddArgument($runner).AddArgument($pin).AddArgument(-not $NoFullscreen).AddArgument($sync) +$handle = $ps.BeginInvoke() + +# --------------------------------------------------------------------------------------------------------------- +# The run +# --------------------------------------------------------------------------------------------------------------- +$began = Get-Date +$preloadOk = $false +Write-Host '' +Write-Host 'Starting. F1 in the game: settings; F3: the stats panel.' -ForegroundColor Cyan +& $runner @playArgs 2>&1 | ForEach-Object { + $line = "$_" + if ($line -match '^Shaders preloaded in') { $preloadOk = $true } + $line +} +$code = $LASTEXITCODE +# A restart from the F1 menu (or the first start's warm-up) is a new victory.exe: wait for it as well. +while (@(Get-Process victory -ErrorAction SilentlyContinue | Where-Object { try { $_.Path -eq $runner } catch { $false } }).Count) { Start-Sleep -Seconds 2 } +$sync.Stop = $true +[void]$ps.EndInvoke($handle) +$ps.Dispose() +foreach ($n in $sync.Notes) { Write-Host " $n" } + +if ($preloadOk) { + $state = Read-State + Set-StateValue $state 'preloaded' $preloadKey + Save-State $state +} + +$logs = @(Get-ChildItem (Join-Path $vhome 'logs') -Filter 'victory-nvidia-play-*.log' -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -ge $began } | Sort-Object LastWriteTime) +foreach ($l in $logs) { + $s = Get-RunSummary $l.FullName + Show-RunSummary $s + Add-RunRow $s $Cores +} +if ($logs.Count) { Write-Host ''; Write-Host "Runs so far, to compare settings: $runsFile" } +else { Write-Host "victory.exe ended (code $code) without a new log in $(Join-Path $vhome 'logs')." }