diff --git a/d3d12/scripts/play-nvidia.ps1 b/d3d12/scripts/play-nvidia.ps1 index 26862777f5..71f1db8fd6 100644 --- a/d3d12/scripts/play-nvidia.ps1 +++ b/d3d12/scripts/play-nvidia.ps1 @@ -119,13 +119,26 @@ if ($wantDlss -and -not $DlssDir) { Write-Host "repository's folder) fetches them from NVIDIA once, about 70 MB, with frame generation's." } -# The build: made here if there is none, and made again with DLSS once its SDK is there (the diag build only). +# The build: made here if there is none, and made again with DLSS once its SDK is there (the diag build only), +# whatever this start's switches ask for: the F1 menu's saved settings are read further down, and a DLSS choice saved +# there stands behind a replayed -Resolution too. Asked for only when the switches wanted DLSS, that build was never +# made for such a start, which fell back from DLSS every time (D3D12-F1-DLSS-REBUILD). -NoDlss: not for this start. $leonida = Join-Path $root "target\$Build\leonida.exe" $built = Join-Path $root "target\$Build\built-with.txt" $hasDlss = (Test-Path $built) -and ((Get-Content $built -Raw) -match 'dlss') -$canDlss = $wantDlss -and (Test-Path $sdkDlssLib) -if (-not $DryRun -and $Build -eq 'diag' -and (-not (Test-Path $leonida) -or ($canDlss -and -not $hasDlss -and (Test-Path $built)))) { - if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) { Write-Host 'No build and no cargo: install Rust (README.md), then start this again.'; return } +$canDlss = -not $NoDlss -and (Test-Path $sdkDlssLib) +# A build noted as made without DLSS, and the SDK here: it is made again. +$stale = $Build -eq 'diag' -and $canDlss -and -not $hasDlss -and (Test-Path $built) +$noCargo = -not (Get-Command cargo -ErrorAction SilentlyContinue) +if ($stale -and $noCargo -and (Test-Path $leonida)) { + # The build that is here still runs: only DLSS waits for cargo. + Write-Host "NVIDIA's SDK is here, but there is no cargo to build the layer again with DLSS (README.md): the build that is here runs." +} elseif ($stale -and $DryRun -and -not $noCargo) { + # Nothing is built in a dry run: it says what a start does first, and prints the settings of the start after it. + Write-Host "NVIDIA's SDK is here: a start builds the layer again with DLSS first." + $hasDlss = $true +} elseif (-not $DryRun -and $Build -eq 'diag' -and (-not (Test-Path $leonida) -or $stale)) { + if ($noCargo) { Write-Host 'No build and no cargo: install Rust (README.md), then start this again.'; return } Write-Host 'Building the layer (a few minutes the first time) ...' & (Join-Path $PSScriptRoot 'build-nvidia.ps1') $hasDlss = (Test-Path $built) -and ((Get-Content $built -Raw) -match 'dlss') diff --git a/docs/game_gate.md b/docs/game_gate.md index 7aed4339c3..4849a85f68 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -8,7 +8,7 @@ The script is `scripts/game-gate.ps1` (Windows, PowerShell 7). The parser is `to It needs PowerShell 7 (`pwsh`). Windows PowerShell 5.1 (`powershell.exe`) refuses the script with a message before anything runs, from its `#Requires -Version 7.0` line. -Build the runtime first (`d3d12\scripts\build-nvidia.ps1`). The gate refuses to start without `d3d12\target\diag\leonida.exe`, because the play script would build it inside the timed run. +Build the runtime first (`d3d12\scripts\build-nvidia.ps1`). The gate refuses to start without `d3d12\target\diag\leonida.exe`, because the play script would build it inside the timed run. For the same reason it refuses a build noted as made without DLSS (`built-with.txt`) once NVIDIA's SDK is in `d3d12\nvidia-sdk`: the play script makes that build again with DLSS at its next start (not with `-NoDlss` in `-PlayArgs`, and not without cargo). Make a data template once: 1. Play to the place the runs should start from. diff --git a/scripts/game-gate.ps1 b/scripts/game-gate.ps1 index 7d38505cea..6ab0c11a91 100644 --- a/scripts/game-gate.ps1 +++ b/scripts/game-gate.ps1 @@ -56,6 +56,32 @@ $RunRoot = (Resolve-Path $RunRoot).Path # A run writes gigabytes of logs and a copy of the saves: never into a checkout. if (($RunRoot + '\').StartsWith($repo + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "-RunRoot is inside the checkout: $RunRoot" } if (-not (Test-Path $exe)) { throw "no ${exe}: build it first (d3d12\scripts\build-nvidia.ps1), the play script would build it inside the run" } +# The play script also makes a build noted as made without DLSS again once NVIDIA's SDK is there, whatever the start's +# switches ask for (d3d12\scripts\play-nvidia.ps1; not with -NoDlss, and not without cargo): that build too would be +# made inside the run, after the exe's hash and what it was built with were written down below. +# Whether -PlayArgs say -NoDlss is asked of PowerShell itself: the play script's own param block binds the arguments +# the launch line below gives it, and nothing of the script runs. (A pattern over the text took `-NoDlss: $true` for +# not said, and `-Adapter 'a -NoDlss b'` for said.) It gives $true, $false, or the error's text when PowerShell cannot +# bind the arguments (the start fails on those too). A variable in -PlayArgs is read here as the gate has it, not as +# launch.ps1 will: only literal arguments are sure to bind the same way in both. +function Test-NoDlssBound([string]$PlayScript, [string]$Arguments) { + try { + $params = [System.Management.Automation.Language.Parser]::ParseFile($PlayScript, [ref]$null, [ref]$null).ParamBlock.Extent.Text + $probe = [scriptblock]::Create("$params`n[bool]`$NoDlss") + # The first thing written is the probe's answer, whatever the pasted text writes behind a `;`. + [bool]@(& ([scriptblock]::Create("& `$args[0] -Game x -Data x -More @{} $Arguments")) $probe)[0] + } catch { "$_" } +} +$builtWith = Join-Path $repo 'd3d12\target\diag\built-with.txt' +$dlssSdk = Join-Path $repo 'd3d12\nvidia-sdk\DLSS\lib\Windows_x86_64\x64\nvsdk_ngx_d.lib' +if ((Test-Path $builtWith) -and (Get-Content $builtWith -Raw) -notmatch 'dlss' -and (Test-Path $dlssSdk) -and + (Get-Command cargo -ErrorAction SilentlyContinue)) { + $noDlss = Test-NoDlssBound $play $PlayArgs + if ($noDlss -ne $true) { + $why = if ($noDlss -is [string]) { " (-PlayArgs do not bind to the play script, so -NoDlss is not read from them: $noDlss)" } else { '' } + throw "$exe was built without DLSS and NVIDIA's SDK is here: build it again first (d3d12\scripts\build-nvidia.ps1), the play script would do it inside the run$why" + } +} if (-not $RunDir) { $RunDir = Join-Path $RunRoot ('{0}-{1}' -f (Get-Date -Format 'yyyyMMdd-HHmmss'), ($Name -replace '[^\w.-]', '_')) } function Get-RunningGame { @@ -115,7 +141,6 @@ $moreText "@ $gpu = Get-CimInstance Win32_VideoController | Sort-Object { [uint64]$_.AdapterRAM } -Descending | Select-Object -First 1 -$builtWith = Join-Path $repo 'd3d12\target\diag\built-with.txt' [ordered]@{ name = $Name started_utc = (Get-Date).ToUniversalTime().ToString('o') diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index 6062b29c69..9873a95bfe 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -4,6 +4,8 @@ import json import os import re +import shutil +import subprocess import sys import tempfile import unittest @@ -327,6 +329,62 @@ def test_no_variable_takes_a_parameters_name_in_another_case(self): others = {m for m in re.findall(r"\$(\w+)\b", text) if m.lower() == name.lower() and m != name} self.assertFalse(others, f"${name} is also written {sorted(others)}") + # -PlayArgs, and whether they switch DLSS off for scripts/play-d3d12.ps1 as PowerShell binds them. The gate refuses + # a build made without DLSS once NVIDIA's SDK is there, unless the start says -NoDlss. + NO_DLSS = { + "": False, + "-SeriesS -NoFrameGen": False, + "-NoDlss": True, + "-NoD": True, + "-nodlss": True, + "-SeriesS -NoDlss -NoFrameGen": True, + "-NoDlss:$true": True, + "-NoDlss: $true": True, + "-SeriesS -NoDlss: $true -NoFrameGen": True, + "-NoDlss:$false": False, + "-NoDlss: $false": False, + "-SeriesS -NoDlss: $false -NoFrameGen": False, + "-Adapter 'Fixture -NoDlss Adapter'": False, + "-Adapter 'Fixture -NoDlss Adapter' -NoDlss:$false": False, + "-Adapter 'Fixture -NoDlss Adapter' -NoDlss": True, + "-No": False, # several switches begin so: the play script refuses it as well + "-NoDlssX": False, # no such switch + "-NoDlss -Bogus": False, # does not bind at all: the start fails on it, and the gate says so + "-SeriesS; $true": False, # what the text writes behind a `;` is not the answer + } + + def test_the_dlss_preflight_asks_powershell_not_a_pattern(self): + with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f: + text = f.read() + self.assertNotRegex(text, r"\$PlayArgs\s+-(not)?match") + self.assertIn("$noDlss = Test-NoDlssBound $play $PlayArgs", text) + + def test_the_dlss_preflight_follows_the_switch_powershell_binds(self): + # A pattern over the text took `-NoDlss: $true` (a space after the colon) for a start that wants DLSS, and a + # quoted adapter name with -NoDlss in it for one that does not. The gate's own function is taken out of the + # script and put to PowerShell 7 with each line of the table, against the real play script's parameters. + pwsh = shutil.which("pwsh") + if not pwsh: + self.skipTest("no PowerShell 7 here") + script = ("$ErrorActionPreference = 'Stop'; " + "$language = 'System.Management.Automation.Language'; " + "$ast = ($language + '.Parser' -as [type])::ParseFile($env:GATE_SCRIPT, [ref]$null, [ref]$null); " + "$fn = $ast.Find({ $args[0].GetType().Name -eq 'FunctionDefinitionAst' -and " + "$args[0].Name -eq 'Test-NoDlssBound' }, $true); " + "if (-not $fn) { throw 'the gate has no Test-NoDlssBound' }; " + ". ([scriptblock]::Create($fn.Extent.Text)); " + "foreach ($line in ($env:GATE_PLAY_ARGS | ConvertFrom-Json)) " + "{ [string]((Test-NoDlssBound $env:GATE_PLAY $line) -eq $true) }") + forms = list(self.NO_DLSS) + env = dict(os.environ, GATE_SCRIPT=os.path.join(ROOT, "scripts", "game-gate.ps1"), + GATE_PLAY=os.path.join(ROOT, "scripts", "play-d3d12.ps1"), GATE_PLAY_ARGS=json.dumps(forms)) + done = subprocess.run([pwsh, "-NoProfile", "-NonInteractive", "-Command", script], capture_output=True, + text=True, timeout=120, env=env) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual(len(done.stdout.split()), len(forms), done.stdout) + self.assertEqual(dict(zip(forms, done.stdout.split())), + {form: str(said) for form, said in self.NO_DLSS.items()}) + class Contract(unittest.TestCase): def test_the_runtime_still_writes_what_the_parser_reads(self): diff --git a/tests/test_play_nvidia_menu_choice.py b/tests/test_play_nvidia_menu_choice.py index ef07200d5a..06f9196243 100644 --- a/tests/test_play_nvidia_menu_choice.py +++ b/tests/test_play_nvidia_menu_choice.py @@ -220,6 +220,94 @@ def test_series_s_saved_dlss_replaces_the_upscaler_implied_by_resolution(self): self.assertEqual(settings.get("LEONIDA_UPSCALE"), upscaler) self.assertEqual(settings.get("LEONIDA_OWN_UPSCALER"), own) + def test_the_dlss_build_is_asked_for_once_its_sdk_is_here_whatever_the_switches(self): + """D3D12-F1-DLSS-REBUILD: the launcher asked for the build with DLSS only when the start's switches wanted + DLSS, before it read the menu's settings: a build noted as made without DLSS was never made again for a DLSS + choice the menu saved behind a replayed -Resolution, and that start fell back from DLSS with NVIDIA's SDK + installed. The SDK asks for the build now. A dry run builds nothing: it says what a start does first and + prints the settings of the start after it.""" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + scripts = root / "scripts" + scripts.mkdir() + script = scripts / SCRIPT.name + script.write_bytes(SCRIPT.read_bytes()) + exe = root / "placeholder.exe" + exe.touch() + lib = root / "nvidia-sdk" / "DLSS" / "lib" / "Windows_x86_64" + (lib / "rel").mkdir(parents=True) + (lib / "x64").mkdir() + dll, sdk = lib / "rel" / "nvngx_dlss.dll", lib / "x64" / "nvsdk_ngx_d.lib" + for build in ("diag", "release"): + (root / "target" / build).mkdir(parents=True) + (root / "target" / build / "leonida.exe").touch() + menu = root / "leonida-settings.txt" + # The launcher looks for cargo: a stand-in on a PATH that holds no other, so this PC's does not decide. + tools = root / "tools" + tools.mkdir() + (tools / "cargo.cmd").write_text("@exit /b 0\r\n", encoding="ascii") + found_as = {".ps1", *(e.lower() for e in os.environ.get("PATHEXT", ".COM;.EXE;.BAT;.CMD").split(os.pathsep) if e)} + no_cargo = os.pathsep.join( + d for d in os.environ.get("PATH", "").split(os.pathsep) + if d and not any((Path(d) / f"cargo{ext}").exists() for ext in found_as)) + env = {k: v for k, v in os.environ.items() if not k.startswith("LEONIDA_")} + env.update(TEST_SCRIPT=str(script), TEST_EXE=str(exe)) + command = ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command"] + launch = "& $env:TEST_SCRIPT -Exe $env:TEST_EXE -NoFrameGen -DryRun" + without, with_dlss = "diagnostics,mimalloc", "diagnostics,dlss,mimalloc" + here = {"sdk", "dll", "cargo", "menu"} + # (the build's note, what is here, switches) -> (a build is asked for, LEONIDA_UPSCALE, the own upscaler) + cases = ( + # The reported start: the menu's DLSS behind a replayed -Resolution. + (without, here, "-Resolution 720 -MenuRestart", True, "dlss", None), + # A -Resolution typed for this start wins over the menu's choice, and the build is asked for all the same. + (without, here, "-Resolution 720", True, None, "1"), + # Series X drops a DLSS choice that -Dlss did not make; the SDK still asks for the build. + (without, here, "-SeriesX -MenuRestart", True, None, "1"), + # No menu file: Series S asks for DLSS by itself, and the dry run shows it after the build too. + (without, here - {"menu"}, "", True, "dlss", None), + (with_dlss, here, "-Resolution 720 -MenuRestart", False, "dlss", None), + (without, here - {"sdk"}, "-Resolution 720 -MenuRestart", False, "stretch", "1"), + (without, here, "-Resolution 720 -NoDlss -MenuRestart", False, "stretch", "1"), + # Only the diag build is made here. + (without, here, "-Resolution 720 -MenuRestart -Build release", False, "stretch", "1"), + # The build alone is not DLSS: without NVIDIA's own file the start still falls back. + (without, here - {"dll"}, "-Resolution 720 -MenuRestart", True, "stretch", "1"), + # Without cargo nothing can be built: the launcher says so and the build that is here runs. + (without, here - {"cargo"}, "-Resolution 720 -MenuRestart", False, "stretch", "1"), + ) + for built, there, args, asked, upscaler, own in cases: + with self.subTest(built=built, missing=sorted(here - there), args=args): + for build in ("diag", "release"): + (root / "target" / build / "built-with.txt").write_text(built, encoding="ascii") + for name, file in (("sdk", sdk), ("dll", dll)): + if name in there: + file.touch() + elif file.exists(): + file.unlink() + if "menu" in there: + menu.write_text("LEONIDA_UPSCALE=dlss\n", encoding="utf-8") + elif menu.exists(): + menu.unlink() + env["PATH"] = (str(tools) + os.pathsep if "cargo" in there else "") + no_cargo + res = subprocess.run([*command, f"{launch} {args}"], env=env, capture_output=True, text=True, + encoding="utf-8", errors="replace", timeout=60) + self.assertEqual(res.returncode, 0, res.stderr) + self.assertEqual("builds the layer again with DLSS" in res.stdout, asked, res.stdout) + self.assertEqual("there is no cargo" in res.stdout, "cargo" not in there, res.stdout) + settings = dict(line.split("=", 1) for line in res.stdout.splitlines() + if line.startswith("LEONIDA_") and "=" in line) + self.assertEqual(settings.get("LEONIDA_UPSCALE"), upscaler) + self.assertEqual(settings.get("LEONIDA_OWN_UPSCALER"), own) + # The note of a build whose exe is gone, and no cargo: nothing here "runs", so the dry run says neither. + (root / "target" / "diag" / "leonida.exe").unlink() + env["PATH"] = no_cargo + res = subprocess.run([*command, f"{launch} -Resolution 720 -MenuRestart"], env=env, capture_output=True, + text=True, encoding="utf-8", errors="replace", timeout=60) + self.assertEqual(res.returncode, 0, res.stderr) + self.assertNotIn("there is no cargo", res.stdout) + self.assertNotIn("builds the layer again with DLSS", res.stdout) + def test_the_restart_replays_every_frame_generation_switch(self): """The menu's SAVE AND RESTART starts the launcher again with LEONIDA_MENU_ARGS: a switch left out of it is lost on that start (-NoFrameGen was, and the restart turned frame generation on)."""