upleb.uk

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

summaryrefslogtreecommitdiff
path: root/scripts
diff options
context:
space:
mode:
authorTheGeogeo <57634077+TheGeogeo@users.noreply.github.com>2026-11-30 20:39:48 +0100
committerTheGeogeo <57634077+TheGeogeo@users.noreply.github.com>2026-11-30 20:39:48 +0100
commitb535fb0dc32d896b88a57c3425dbfadadfef6cb6 (patch)
tree6b7caa7417b7c38c1f8c1784671bf89293a83d19 /scripts
parent8f41d7d019e6b7006a68682de065ae176a56f2ec (diff)
d3d12: an in-game gate: one command, one run folder, one summary.json (D3D12-GAME-GATE)
Testers ran in-game gates and A/Bs by hand on five machines, each with their own launcher wrapper and log parsers, and lost runs to consoles and key files. scripts/game-gate.ps1 runs leonida.exe through the checkout's play-d3d12.ps1 and writes one folder per run: run.json, launch.ps1, the -DryRun settings, the F1 settings file, the launcher's output (the precompile lines nobody kept), the runtime's log, events.jsonl and a copy of the tester's data template (their own saves are never touched). It stops the game with WM_SYSCOMMAND/SC_CLOSE (the runtime's own end: suspend, pipeline cache saved) once -WorldSeconds were spent in the world, on a STOP file or after -MaxMinutes, and kills it only 60 s later; it keeps the game's exit code. `start` runs the same detached (created through CIM, so an agent's or console's end does not end it); `stop` asks a run to end. tools/game_gate.py (standard library) reads the folder into summary.json (leonida-gate-summary/1): build, card, settings (the run's settings line, no paths), precompile counts, time to the world (two frame lines with 500 draws or more, cutscenes included), when the pipeline cache went warm (60 s with nothing being made), fps from the presents (median, p5, frame p95, end median, the first second under 2 frames, the longest gap with no frame), crashes by kind (device lost, panic, fault by module kind), exit, stop and a verdict: PASS needs 300 s in the world, no device loss, panic or fault, no gap over 10 s, alive at the stop. The testers' answers to a draft on the bridge are folded in. Its tests use synthetic logs and check that the runtime still writes what it reads.
Diffstat (limited to 'scripts')
-rw-r--r--scripts/game-gate.ps1214
1 files changed, 214 insertions, 0 deletions
diff --git a/scripts/game-gate.ps1 b/scripts/game-gate.ps1
new file mode 100644
index 000000000..5d1020186
--- /dev/null
+++ b/scripts/game-gate.ps1
@@ -0,0 +1,214 @@
1# The in-game gate for the D3D12 runtime (leonida.exe): one run, measured the same way on every machine.
2#
3# pwsh -NoProfile -File scripts\game-gate.ps1 run -Game <dir> -Data <dir> -DataTemplate <dir> -Name <label> [options]
4# pwsh -NoProfile -File scripts\game-gate.ps1 start <same options> # the same, detached: returns at once, prints the run folder
5# pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir <run folder> # asks a run to stop (a STOP file)
6#
7# It starts the game through this checkout's scripts\play-d3d12.ps1, so a run is what players run, and writes one
8# folder per run under -RunRoot (default: <Data>\gate-runs): run.json, launch.ps1, settings.txt (the play script's
9# -DryRun), leonida-settings.txt (the F1 menu file, when there is one), launcher.txt (the precompile lines),
10# leonida.log (the runtime's log), events.jsonl (what this script did and saw), data\ (a copy of -DataTemplate, so
11# the tester's own saves are never touched) and summary.json (tools\game_gate.py, schema in docs\game_gate.md).
12#
13# It stops the game with WM_SYSCOMMAND/SC_CLOSE (the runtime's own end: the title suspended, the pipeline cache
14# saved) when -WorldSeconds were spent in the world, when a STOP file appears in the run folder, or after
15# -MaxMinutes; it kills the game only if it has not ended 60 s later. Exit code: 0 PASS, 1 FAIL, 2 ERROR.
16# Options: -WorldSeconds (300), -MaxMinutes (45), -More 'LEONIDA_X=1;LEONIDA_Y=2', -PlayArgs '-SeriesS -NoFrameGen'.
17param(
18 [Parameter(Mandatory, Position = 0)][ValidateSet('run', 'start', 'stop')][string]$Verb,
19 [string]$Game = '',
20 [string]$Data = '',
21 [string]$DataTemplate = '',
22 [string]$Name = '',
23 [string]$RunRoot = '',
24 [string]$RunDir = '',
25 [int]$WorldSeconds = 300,
26 [int]$MaxMinutes = 45,
27 [string]$More = '',
28 [string]$PlayArgs = '',
29 [string]$Python = ''
30)
31$ErrorActionPreference = 'Stop'
32$repo = Split-Path -Parent $PSScriptRoot
33$tool = Join-Path $repo 'tools\game_gate.py'
34$play = Join-Path $repo 'scripts\play-d3d12.ps1'
35$exe = Join-Path $repo 'd3d12\target\diag\leonida.exe'
36$menuFile = Join-Path $repo 'd3d12\leonida-settings.txt'
37if (-not $Python) { $Python = (Get-Command python -ErrorAction Stop).Source }
38
39if ($Verb -eq 'stop') {
40 if (-not $RunDir -or -not (Test-Path (Join-Path $RunDir 'run.json'))) { throw "not a run folder: '$RunDir'" }
41 Set-Content (Join-Path $RunDir 'STOP') 'stop' -NoNewline
42 "asked $RunDir to stop"
43 exit 0
44}
45
46foreach ($p in 'Game', 'Data', 'DataTemplate', 'Name') {
47 if (-not (Get-Variable $p -ValueOnly)) { throw "-$p is needed" }
48}
49$Game = (Resolve-Path $Game).Path
50$Data = (Resolve-Path $Data).Path
51$DataTemplate = (Resolve-Path $DataTemplate).Path
52if (-not $RunRoot) { $RunRoot = Join-Path $Data 'gate-runs' }
53New-Item -ItemType Directory -Force $RunRoot | Out-Null
54$RunRoot = (Resolve-Path $RunRoot).Path
55# A run writes gigabytes of logs and a copy of the saves: never into a checkout.
56if (($RunRoot + '\').StartsWith($repo + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "-RunRoot is inside the checkout: $RunRoot" }
57if (-not (Test-Path $exe)) { throw "no ${exe}: build it first (d3d12\scripts\build-nvidia.ps1), the play script would build it inside the run" }
58if (-not $RunDir) { $RunDir = Join-Path $RunRoot ('{0}-{1}' -f (Get-Date -Format 'yyyyMMdd-HHmmss'), ($Name -replace '[^\w.-]', '_')) }
59
60function Get-RunningGame {
61 Get-CimInstance Win32_Process -Filter "Name='leonida.exe' OR Name='leonida_sm.exe'" |
62 Where-Object { $_.CommandLine -match '\srun\s' } | Select-Object -First 1
63}
64
65if ($Verb -eq 'start') {
66 if (Get-RunningGame) { throw 'a leonida run is already running' }
67 $pwsh = (Get-Process -Id $PID).Path
68 $quote = { param($s) '"' + ($s -replace '"', '\"') + '"' }
69 $line = @(& $quote $pwsh; '-NoProfile'; '-ExecutionPolicy'; 'Bypass'; '-File'; & $quote $PSCommandPath; 'run'
70 '-Game'; & $quote $Game; '-Data'; & $quote $Data; '-DataTemplate'; & $quote $DataTemplate; '-Name'; & $quote $Name
71 '-RunRoot'; & $quote $RunRoot; '-RunDir'; & $quote $RunDir; '-WorldSeconds'; $WorldSeconds; '-MaxMinutes'; $MaxMinutes
72 '-More'; & $quote $More; '-PlayArgs'; & $quote $PlayArgs; '-Python'; & $quote $Python) -join ' '
73 # Created by Windows, not as a child of this shell: an agent's or a console's end does not end the run.
74 $startup = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]0 }
75 $made = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{
76 CommandLine = $line; CurrentDirectory = $repo; ProcessStartupInformation = $startup }
77 if ($made.ReturnValue -ne 0) { throw "starting the run failed ($($made.ReturnValue))" }
78 $RunDir
79 exit 0
80}
81
82# ---- run: the supervisor, in the foreground.
83if (Get-RunningGame) { throw 'a leonida run is already running' }
84New-Item -ItemType Directory -Force $RunDir | Out-Null
85# A detached run has no console: what this script says, and any error, goes to supervisor.log.
86Start-Transcript -Path (Join-Path $RunDir 'supervisor.log') -Append | Out-Null
87$events = Join-Path $RunDir 'events.jsonl'
88function Add-Event([string]$event, [hashtable]$fields = @{}) {
89 $e = [ordered]@{ t = (Get-Date).ToUniversalTime().ToString('o'); event = $event }
90 foreach ($k in $fields.Keys) { $e[$k] = $fields[$k] }
91 Add-Content $events ($e | ConvertTo-Json -Compress)
92}
93
94# The tester's saves, copied: the run plays from its own data folder (-More wins over the play script's own).
95Copy-Item -Path (Join-Path $DataTemplate '*') -Destination (New-Item -ItemType Directory -Force (Join-Path $RunDir 'data')).FullName -Recurse
96$hadMenuFile = Test-Path $menuFile
97if ($hadMenuFile) { Copy-Item $menuFile (Join-Path $RunDir 'leonida-settings.txt') }
98
99$settings = [ordered]@{
100 LEONIDA_DATA_DIR = (Join-Path $RunDir 'data')
101 LEONIDA_LOG = 'info,leonida_gpu::frame=debug'
102}
103foreach ($s in ($More -split ';' | Where-Object { $_ -match '=' })) { $k, $v = $s -split '=', 2; $settings[$k.Trim()] = $v.Trim() }
104$moreText = ($settings.GetEnumerator() | ForEach-Object { " {0} = '{1}'" -f $_.Key, ($_.Value -replace "'", "''") }) -join "`n"
105$launch = Join-Path $RunDir 'launch.ps1'
106Set-Content $launch @"
107# Written by scripts\game-gate.ps1: how this run started the game.
108`$env:NO_COLOR = '1'
109Set-Location '$repo'
110`$settings = @{
111$moreText
112}
113& '$play' -Game '$Game' -Data '$Data' -More `$settings $PlayArgs @args
114"@
115
116$gpu = Get-CimInstance Win32_VideoController | Sort-Object { [uint64]$_.AdapterRAM } -Descending | Select-Object -First 1
117$builtWith = Join-Path $repo 'd3d12\target\diag\built-with.txt'
118[ordered]@{
119 name = $Name
120 started_utc = (Get-Date).ToUniversalTime().ToString('o')
121 commit = (git -C $repo rev-parse --short HEAD)
122 dirty = [bool](git -C $repo status --porcelain --untracked-files=no)
123 exe_sha16 = (Get-FileHash $exe -Algorithm SHA256).Hash.Substring(0, 16).ToLower()
124 built_with = if (Test-Path $builtWith) { (Get-Content $builtWith -Raw).Trim() } else { $null }
125 gpu = $gpu.Name
126 driver = $gpu.DriverVersion
127 play_args = $PlayArgs
128 world_seconds = $WorldSeconds
129 max_minutes = $MaxMinutes
130 f1_settings_file = $hadMenuFile
131} | ConvertTo-Json | Set-Content (Join-Path $RunDir 'run.json')
132
133& pwsh -NoProfile -ExecutionPolicy Bypass -File $launch -DryRun *> (Join-Path $RunDir 'settings.txt')
134$launcher = Start-Process pwsh -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $launch) -WindowStyle Hidden -PassThru `
135 -RedirectStandardOutput (Join-Path $RunDir 'launcher.txt') -RedirectStandardError (Join-Path $RunDir 'leonida.log')
136Add-Event 'started' @{ launcher = $launcher.Id }
137
138if (-not ('GateWindow' -as [type])) {
139 Add-Type -TypeDefinition @'
140using System;
141using System.Runtime.InteropServices;
142public static class GateWindow {
143 delegate bool EnumProc(IntPtr h, IntPtr l);
144 [StructLayout(LayoutKind.Sequential)] public struct RECT { public int L, T, R, B; }
145 [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc cb, IntPtr l);
146 [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
147 [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h);
148 [DllImport("user32.dll")] static extern bool GetClientRect(IntPtr h, out RECT r);
149 [DllImport("user32.dll")] static extern bool PostMessage(IntPtr h, uint msg, IntPtr w, IntPtr l);
150 // WM_SYSCOMMAND/SC_CLOSE to the process's largest visible window: the runtime's end_title path. (A plain
151 // WM_CLOSE goes to the title's own window procedure, which does not end the run.)
152 public static bool Close(int pid) {
153 IntPtr best = IntPtr.Zero; long area = 0;
154 EnumWindows((h, l) => {
155 uint p; GetWindowThreadProcessId(h, out p);
156 RECT r;
157 if (p == (uint)pid && IsWindowVisible(h) && GetClientRect(h, out r)) {
158 long a = (long)(r.R - r.L) * (r.B - r.T);
159 if (a > area) { area = a; best = h; }
160 }
161 return true;
162 }, IntPtr.Zero);
163 return best != IntPtr.Zero && PostMessage(best, 0x0112, new IntPtr(0xF060), IntPtr.Zero);
164 }
165}
166'@
167}
168
169$began = Get-Date
170$title = $null # the game process ($Game, the same name in any case, is its folder)
171$stopReason = $null
172try {
173while ($true) {
174 Start-Sleep -Seconds 5
175 if (-not $title) {
176 $found = Get-RunningGame
177 if ($found) {
178 $title = Get-Process -Id $found.ProcessId
179 $null = $title.Handle # held now, so that the exit code can be read after the process ends
180 Add-Event 'game' @{ pid = $found.ProcessId; image = $found.Name }
181 }
182 }
183 if ($title -and $title.HasExited) { break }
184 if (-not $title -and $launcher.HasExited) { break }
185 $state = & $Python -I $tool state $RunDir | ConvertFrom-Json
186 if ($state.relaunched) { $stopReason = 'relaunched' }
187 elseif (Test-Path (Join-Path $RunDir 'STOP')) { $stopReason = 'stop_file' }
188 elseif ($state.world_s -ge $WorldSeconds) { $stopReason = 'target' }
189 elseif (((Get-Date) - $began).TotalMinutes -ge $MaxMinutes) { $stopReason = 'timeout' }
190 if ($stopReason) { break }
191}
192
193if ($stopReason -and $title -and -not $title.HasExited) {
194 Add-Event 'stop_requested' @{ reason = $stopReason }
195 if ([GateWindow]::Close($title.Id)) { Add-Event 'close_sent' }
196 if (-not $title.WaitForExit(60000)) {
197 Stop-Process -Id $title.Id -Force
198 Add-Event 'killed'
199 $title.WaitForExit()
200 }
201} elseif ($stopReason) {
202 Add-Event 'stop_requested' @{ reason = $stopReason }
203}
204if ($title) { Add-Event 'game_exited' @{ exit_code = $title.ExitCode } }
205if (-not $launcher.WaitForExit(30000)) { Stop-Process -Id $launcher.Id -Force }
206} catch {
207 Add-Event 'error' @{ message = $_.Exception.Message; line = $_.InvocationInfo.ScriptLineNumber }
208 Write-Host "gate error: $($_.Exception.Message) (line $($_.InvocationInfo.ScriptLineNumber))"
209} finally {
210 & $Python -I $tool summary $RunDir
211 $code = $LASTEXITCODE
212 Stop-Transcript | Out-Null
213}
214exit $code