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:
Diffstat (limited to 'scripts')
-rw-r--r--scripts/play.ps12
-rw-r--r--scripts/port_ctl.py320
-rw-r--r--scripts/sync_victory.py94
3 files changed, 1 insertions, 415 deletions
diff --git a/scripts/play.ps1 b/scripts/play.ps1
index 76b9f5139..70a990685 100644
--- a/scripts/play.ps1
+++ b/scripts/play.ps1
@@ -41,7 +41,7 @@ Set-Default "LEONIDA_KEYBOARD_PAD" "1" # keyboard and mouse as a pad wh
41# The title's soft asserts (an int3 the console build carries on from) are stepped over and logged; the one known 41# The title's soft asserts (an int3 the console build carries on from) are stepped over and logged; the one known
42# site is game+0x4ffd879 after the start screen (docs/port_status.md, open items). 42# site is game+0x4ffd879 after the start screen (docs/port_status.md, open items).
43Set-Default "LEONIDA_SKIP_INT3" "1" 43Set-Default "LEONIDA_SKIP_INT3" "1"
44$tables = Join-Path $repo "victory\crates\victory-formats\src\bcpack-tables.bin" 44$tables = Join-Path $repo "d3d12\crates\leonida-formats\src\bcpack-tables.bin"
45if (Test-Path $tables) { Set-Default "LEONIDA_BCPACK_TABLES" $tables } 45if (Test-Path $tables) { Set-Default "LEONIDA_BCPACK_TABLES" $tables }
46 46
47$logs = Join-Path $Work "logs" 47$logs = Join-Path $Work "logs"
diff --git a/scripts/port_ctl.py b/scripts/port_ctl.py
deleted file mode 100644
index 9a7e595d0..000000000
--- a/scripts/port_ctl.py
+++ /dev/null
@@ -1,320 +0,0 @@
1#!/usr/bin/env python3
2"""Drive a VIctory run of the title for testing: start, press, shot, fps, stop.
3
4Everything the run writes (logs, frame captures, saves, caches) goes under a
5work folder outside the repository (``--work``, default ``G:\\gta6port`` or
6``LEONIDA_PORT_WORK``). Nothing from the game is read or written here beyond
7what the runtime itself does.
8
9 python -I scripts/port_ctl.py start --name run1 # launch the title
10 python -I scripts/port_ctl.py press Enter # tap A on the stand-in pad
11 python -I scripts/port_ctl.py press W 3000 # hold left stick up for 3 s
12 python -I scripts/port_ctl.py shot # save the next presented frame
13 python -I scripts/port_ctl.py fps # latest frame-rate lines
14 python -I scripts/port_ctl.py status # running?, fps, last warnings
15 python -I scripts/port_ctl.py stop # end the run
16
17Keys (the stand-in pad's table): sticks W A S D / I J K L, triggers Z C,
18buttons X Y Q E F H, Enter (A), Back (B), Esc (Menu), Tab (View),
19Up Down Left Right (D-pad). The runtime reads the pad file only while no real
20controller is connected.
21"""
22
23import argparse
24import json
25import os
26import re
27import subprocess
28import sys
29import time
30
31REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
32VICTORY = os.path.join(REPO, "victory")
33DEFAULT_WORK = os.environ.get("LEONIDA_PORT_WORK", r"G:\gta6port")
34DEFAULT_GAME = os.environ.get("LEONIDA_GAME_DIR", os.path.expanduser(r"~\Documents\GTA6"))
35TITLE_EXE = "game_scarlett_master.exe"
36
37FPS_RE = re.compile(r"(\d+(?:\.\d+)?) fps, (\d+(?:\.\d+)?) ms/frame")
38ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
39
40
41def read_log(log):
42 try:
43 with open(log, encoding="utf-8", errors="replace") as f:
44 return [ANSI_RE.sub("", ln) for ln in f]
45 except OSError:
46 return []
47
48
49def paths(work):
50 ctl = os.path.join(work, "ctl")
51 return {
52 "work": work,
53 "ctl": ctl,
54 "state": os.path.join(ctl, "state.json"),
55 "pad": os.path.join(ctl, "pad.txt"),
56 "shot": os.path.join(ctl, "shot.txt"),
57 "logs": os.path.join(work, "logs"),
58 "captures": os.path.join(work, "captures"),
59 "cache": os.path.join(work, "cache"),
60 "data": os.path.join(work, "data"),
61 }
62
63
64def load_state(p):
65 try:
66 with open(p["state"], encoding="utf-8") as f:
67 return json.load(f)
68 except (OSError, ValueError):
69 return {}
70
71
72def save_state(p, state):
73 os.makedirs(p["ctl"], exist_ok=True)
74 with open(p["state"], "w", encoding="utf-8", newline="\n") as f:
75 json.dump(state, f, indent=1)
76
77
78def alive(pid):
79 if not pid:
80 return False
81 out = subprocess.run(
82 ["tasklist", "/FI", f"PID eq {pid}", "/NH", "/FO", "CSV"],
83 stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
84 ).stdout
85 return f'"{pid}"' in out
86
87
88def write_atomic(path, text):
89 tmp = path + ".tmp"
90 with open(tmp, "w", encoding="utf-8", newline="\n") as f:
91 f.write(text)
92 os.replace(tmp, path)
93
94
95def cmd_start(args, p):
96 state = load_state(p)
97 if alive(state.get("pid")):
98 print(f"a run is already going: pid {state['pid']} ({state.get('name')}); stop it first")
99 return 1
100 exe = args.exe or os.path.join(VICTORY, "target", args.profile, "victory.exe")
101 if not os.path.isfile(exe):
102 print(f"no runtime at {exe}; build it first (cargo build --release -p victory --features diagnostics --bins)")
103 return 1
104 title = os.path.join(args.game, TITLE_EXE)
105 if not os.path.isfile(title):
106 print(f"no title executable at {title}")
107 return 1
108 name = args.name or time.strftime("run-%Y%m%d-%H%M%S")
109 for key in ("ctl", "logs", "captures", "cache", "data"):
110 os.makedirs(p[key], exist_ok=True)
111 captures = os.path.join(p["captures"], name)
112 os.makedirs(captures, exist_ok=True)
113 data = args.data or p["data"]
114 os.makedirs(data, exist_ok=True)
115 # Fresh command files: the runtime only acts on increasing numbers.
116 for f in (p["pad"], p["shot"]):
117 if os.path.exists(f):
118 os.remove(f)
119 env = dict(os.environ)
120 env.update({
121 "VICTORY_GAME_DIR": args.game,
122 "VICTORY_CACHE_DIR": p["cache"],
123 "VICTORY_DATA_DIR": data,
124 "VICTORY_LOG": args.log,
125 "VICTORY_CAPTURE": captures,
126 "VICTORY_CAPTURE_REQUEST": p["shot"],
127 "VICTORY_MOVEMENT_FILE": p["pad"],
128 })
129 if args.world:
130 env["VICTORY_CAPTURE_WORLD"] = "1"
131 for item in args.env or []:
132 k, _, v = item.partition("=")
133 env[k] = v
134 log = os.path.join(p["logs"], f"{name}.log")
135 cmd = [exe, "run", title, "--execute", "--console", args.console]
136 flags = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
137 # The runtime writes its own bytes here; newline only keeps the repository's line-ending rule.
138 with open(log, "w", encoding="utf-8", newline="\n") as out:
139 proc = subprocess.Popen(cmd, cwd=args.game, env=env, stdout=out, stderr=subprocess.STDOUT,
140 stdin=subprocess.DEVNULL, creationflags=flags)
141 state = {
142 "pid": proc.pid, "name": name, "log": log, "captures": captures, "started": time.time(),
143 "pad_seq": 0, "shot_seq": 0, "cmd": cmd,
144 "env": {k: v for k, v in env.items() if k.startswith("VICTORY_")},
145 }
146 save_state(p, state)
147 print(f"started pid {proc.pid} as {name}\n log {log}\n captures {captures}")
148 return 0
149
150
151def cmd_press(args, p):
152 state = load_state(p)
153 seq = int(time.time() * 1000)
154 seq = max(seq, state.get("pad_seq", 0) + 1)
155 write_atomic(p["pad"], f"{seq} {args.key} {args.ms}")
156 state["pad_seq"] = seq
157 save_state(p, state)
158 print(f"pressed {args.key} for {args.ms} ms (sequence {seq})")
159 if args.wait:
160 time.sleep(args.ms / 1000.0 + 0.4)
161 return 0
162
163
164def newest_png(folder, since):
165 best = None
166 try:
167 for entry in os.scandir(folder):
168 if entry.name.endswith(".png") and entry.stat().st_mtime >= since:
169 if best is None or entry.stat().st_mtime > best.stat().st_mtime:
170 best = entry
171 except OSError:
172 return None
173 return best.path if best else None
174
175
176def shrink(path, width):
177 """A copy of the capture `width` pixels wide beside it (needs Pillow); the capture itself otherwise."""
178 try:
179 from PIL import Image
180 except ImportError:
181 return path
182 with Image.open(path) as im:
183 height = max(1, round(im.height * width / im.width))
184 small = im.resize((width, height), Image.LANCZOS)
185 out = path[:-4] + f"-w{width}.png"
186 small.save(out)
187 return out
188
189
190def cmd_shot(args, p):
191 state = load_state(p)
192 seq = state.get("shot_seq", 0) + 1
193 since = time.time() - 0.5
194 write_atomic(p["shot"], str(seq))
195 state["shot_seq"] = seq
196 save_state(p, state)
197 folder = state.get("captures")
198 deadline = time.time() + args.timeout
199 while time.time() < deadline:
200 found = newest_png(folder, since)
201 if found:
202 time.sleep(0.5) # let the writer finish
203 if args.small:
204 found = shrink(found, args.small)
205 print(found)
206 return 0
207 time.sleep(0.25)
208 print(f"no new frame in {folder} after {args.timeout} s (the title may not be presenting)")
209 return 1
210
211
212def fps_lines(log, count):
213 hits = [ln.rstrip() for ln in read_log(log) if FPS_RE.search(ln)]
214 return hits[-count:]
215
216
217def summarize(line):
218 m = FPS_RE.search(line)
219 if not m:
220 return line
221 tail = line[m.start():]
222 keep = []
223 for pattern in (r"\d+(?:\.\d+)? fps, \d+(?:\.\d+)? ms/frame", r"\(\S+ preparing", r"[\d.]+ on the GPU",
224 r"\d+ draws/frame", r"dropped \d+ without a host pipeline \(\d+ being made\)",
225 r"cpu [\d.]+% gpu \d+% busy ram \d+ MB"):
226 mm = re.search(pattern, tail)
227 if mm:
228 keep.append(mm.group(0))
229 stamp = line[:m.start()].split(" ")[0]
230 return f"{stamp} " + " | ".join(keep)
231
232
233def cmd_fps(args, p):
234 state = load_state(p)
235 log = args.log or state.get("log")
236 if not log:
237 print("no run recorded")
238 return 1
239 for line in fps_lines(log, args.count):
240 print(line if args.full else summarize(line))
241 return 0
242
243
244def cmd_status(args, p):
245 state = load_state(p)
246 if not state:
247 print("no run recorded")
248 return 1
249 up = time.time() - state.get("started", time.time())
250 print(f"{state.get('name')}: pid {state.get('pid')} {'running' if alive(state.get('pid')) else 'NOT running'}, "
251 f"up {int(up // 60)}:{int(up % 60):02d}")
252 for line in fps_lines(state["log"], 3):
253 print(" " + summarize(line))
254 lines = read_log(state["log"])
255 bad = [ln.rstrip() for ln in lines if re.search(r"\b(ERROR|WARN)\b|panicked|crash|DEVICE_HUNG|DEVICE_REMOVED", ln)]
256 for line in bad[-args.warnings:]:
257 print(" ! " + line[:300])
258 return 0
259
260
261def cmd_stop(args, p):
262 state = load_state(p)
263 pid = state.get("pid")
264 if not alive(pid):
265 print("no run is going")
266 return 0
267 subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
268 for _ in range(40):
269 if not alive(pid):
270 break
271 time.sleep(0.25)
272 print(f"stopped pid {pid} ({state.get('name')})")
273 return 0
274
275
276def main():
277 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
278 ap.add_argument("--work", default=DEFAULT_WORK, help="work folder outside the repository")
279 sub = ap.add_subparsers(dest="command", required=True)
280
281 s = sub.add_parser("start", help="launch the title under VIctory")
282 s.add_argument("--name")
283 s.add_argument("--game", default=DEFAULT_GAME)
284 s.add_argument("--exe", help="runtime executable (default: victory/target/<profile>/victory.exe)")
285 s.add_argument("--profile", default="release")
286 s.add_argument("--console", default="series-x", choices=["series-x", "series-s"])
287 s.add_argument("--log", default="info", help="VICTORY_LOG filter")
288 s.add_argument("--data", help="data folder (saves); default <work>/data")
289 s.add_argument("--world", action="store_true", help="also capture world frames (VICTORY_CAPTURE_WORLD)")
290 s.add_argument("--env", action="append", help="extra K=V for the run (repeatable)")
291
292 s = sub.add_parser("press", help="press a stand-in pad key")
293 s.add_argument("key")
294 s.add_argument("ms", nargs="?", type=int, default=200)
295 s.add_argument("--wait", action="store_true", help="return after the hold ends")
296
297 s = sub.add_parser("shot", help="save the next presented frame and print its path")
298 s.add_argument("--timeout", type=float, default=30.0)
299 s.add_argument("--small", type=int, default=0, metavar="WIDTH",
300 help="also write a copy this many pixels wide and print its path (needs Pillow)")
301
302 s = sub.add_parser("fps", help="latest frame-rate lines of the run's log")
303 s.add_argument("--count", type=int, default=5)
304 s.add_argument("--log")
305 s.add_argument("--full", action="store_true")
306
307 s = sub.add_parser("status", help="whether the run is going, its fps and last warnings")
308 s.add_argument("--warnings", type=int, default=5)
309
310 sub.add_parser("stop", help="end the run")
311
312 args = ap.parse_args()
313 p = paths(args.work)
314 return {"start": cmd_start, "press": cmd_press, "shot": cmd_shot, "fps": cmd_fps,
315 "status": cmd_status, "stop": cmd_stop}[args.command](args, p)
316
317
318if __name__ == "__main__":
319 sys.stdout.reconfigure(errors="replace")
320 sys.exit(main())
diff --git a/scripts/sync_victory.py b/scripts/sync_victory.py
deleted file mode 100644
index ccae2c459..000000000
--- a/scripts/sync_victory.py
+++ /dev/null
@@ -1,94 +0,0 @@
1#!/usr/bin/env python3
2"""Check DexNom/VIctory for new commits and optionally merge them into victory/.
3
4VIctory lives in this repository as a git subtree under ``victory/`` (added with
5``git subtree add --prefix=victory victory main``). This tool fetches the
6``victory`` remote, reports the commits that are not merged yet and, with
7``--merge``, pulls them in with ``git subtree pull`` so upstream history is kept
8and local changes under ``victory/`` are merged, not overwritten.
9
10Run from anywhere inside the repository:
11
12 python -I scripts/sync_victory.py # report only
13 python -I scripts/sync_victory.py --merge # report, then merge if clean
14
15Exit codes: 0 up to date or merged, 10 updates waiting (report only),
162 git failure, 3 working tree not clean (merge refused), 4 merge conflict.
17"""
18
19import argparse
20import datetime
21import os
22import subprocess
23import sys
24
25REMOTE = "victory"
26BRANCH = "main"
27PREFIX = "victory"
28
29
30def git(*args, check=True):
31 proc = subprocess.run(
32 ["git", *args],
33 stdout=subprocess.PIPE,
34 stderr=subprocess.STDOUT,
35 text=True,
36 encoding="utf-8",
37 errors="replace",
38 )
39 if check and proc.returncode != 0:
40 print(f"git {' '.join(args)} failed ({proc.returncode}):\n{proc.stdout}")
41 sys.exit(2)
42 return proc
43
44
45def main():
46 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
47 ap.add_argument("--merge", action="store_true", help="merge new commits with git subtree pull")
48 args = ap.parse_args()
49
50 top = git("rev-parse", "--show-toplevel").stdout.strip()
51 os.chdir(top)
52 stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
53
54 git("fetch", "--quiet", REMOTE, BRANCH)
55 upstream = git("rev-parse", f"{REMOTE}/{BRANCH}").stdout.strip()
56 merged = git("merge-base", "--is-ancestor", upstream, "HEAD", check=False).returncode == 0
57 if merged:
58 print(f"[{stamp}] {REMOTE}/{BRANCH} {upstream[:9]} is already merged; nothing to do.")
59 return 0
60
61 new = git("log", "--oneline", "--no-decorate", f"HEAD..{upstream}").stdout.strip().splitlines()
62 print(f"[{stamp}] {len(new)} new {REMOTE}/{BRANCH} commit(s) up to {upstream[:9]}:")
63 for line in new:
64 print(f" {line}")
65 if not args.merge:
66 return 10
67
68 dirty = git("status", "--porcelain", "--untracked-files=no").stdout.strip()
69 if dirty:
70 print("Working tree has uncommitted changes; commit or stash them, then run --merge again.")
71 print(dirty)
72 return 3
73
74 msg = (
75 f"Merge {REMOTE}/{BRANCH} {upstream[:9]} into {PREFIX}/ ({len(new)} commit(s))\n\n"
76 "Pulled with scripts/sync_victory.py --merge (git subtree pull).\n"
77 )
78 pull = git("subtree", "pull", f"--prefix={PREFIX}", REMOTE, BRANCH, "-m", msg, check=False)
79 print(pull.stdout.strip())
80 if pull.returncode != 0:
81 conflicts = git("diff", "--name-only", "--diff-filter=U", check=False).stdout.strip()
82 if conflicts:
83 print("Merge stopped on conflicts in:")
84 print(conflicts)
85 return 4
86 print("git subtree pull failed.")
87 return 2
88 print(f"Merged {REMOTE}/{BRANCH} {upstream[:9]} into {PREFIX}/.")
89 return 0
90
91
92if __name__ == "__main__":
93 sys.stdout.reconfigure(errors="replace")
94 sys.exit(main())