@gameslate/sdk 0.3.9 → 0.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,6 +19,8 @@ import { initPlugin } from '../build/init-plugin.mjs';
19
19
  * gameslate-plugin addresses <spec.json> [--out <file.ts>]
20
20
  * A game's address table from its decompilation: symbols from its maps, struct offsets,
21
21
  * sizes and constants from a clang probe against its headers (src/host/addresses.ts).
22
+ * gameslate-plugin names <map or symbol file> …
23
+ * Triage before writing a reader: how many symbols name the game, and its named globals.
22
24
  */
23
25
  const { values, positionals } = parseArgs({
24
26
  options: {
@@ -37,6 +39,7 @@ const USAGE = [
37
39
  ' gameslate-plugin validate <builtDir> [--core-version <version>]',
38
40
  ' gameslate-plugin verify <verify.json>',
39
41
  ' gameslate-plugin addresses <spec.json> [--out <file.ts>]',
42
+ ' gameslate-plugin names <map or symbol file> … does the decomp name the game? (triage)',
40
43
  ].join('\n');
41
44
 
42
45
  async function validate(builtDir) {
@@ -151,6 +154,19 @@ if (command === 'build' && dir && values.out) {
151
154
  const text = addressModule(table, provenance);
152
155
  if (values.out) fs.writeFileSync(path.resolve(values.out), text);
153
156
  else process.stdout.write(text);
157
+ } else if (command === 'names' && dir) {
158
+ const { parseSymbolFile, triageNames } = await import('../lib/host/index.js');
159
+ const symbols = new Map(
160
+ positionals.slice(1).flatMap(f => [...parseSymbolFile(fs.readFileSync(f, 'utf8'))]),
161
+ );
162
+ const { placeholders, library, game } = triageNames(symbols);
163
+ console.log(
164
+ `${symbols.size} symbols: ${game.length} name the game, ${placeholders} placeholders (func_/D_), ${library} library`,
165
+ );
166
+ const globals = game.filter(n => /^g[A-Z_]/.test(n));
167
+ console.log(`globals (g…): ${globals.length ? globals.slice(0, 60).join(' ') : 'none'}`);
168
+ if (globals.length === 0)
169
+ console.log("No named globals: read the skill's first pitfall before writing a reader.");
154
170
  } else {
155
171
  console.error(USAGE);
156
172
  process.exit(1);
@@ -2,6 +2,7 @@ import { execFile, spawn } from 'node:child_process';
2
2
  import dgram from 'node:dgram';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
+ import { firstBusyUdpPort, RETROARCH_UDP_PORTS } from '../lib/host/index.js';
5
6
 
6
7
  /*
7
8
  * The real effects of `gameslate-plugin verify` (src/host/verify.ts has the steps and their
@@ -17,8 +18,10 @@ const COMMAND_TIMEOUT_MS = 2000;
17
18
  export function verifyEffects(specDir, log = line => console.error(line)) {
18
19
  const at = p => path.resolve(specDir, p);
19
20
  return {
20
- launch: spec =>
21
- spec.emulator ? launchEmulator(spec, at, log) : launchRetroArch(spec, at, log),
21
+ launch: async spec => {
22
+ await refuseBusyRetroArchPorts(spec);
23
+ return spec.emulator ? launchEmulator(spec, at, log) : launchRetroArch(spec, at, log);
24
+ },
22
25
  drive: (spec, args) => drive(spec, at, args),
23
26
  wait: ms => new Promise(resolve => setTimeout(resolve, ms)),
24
27
  state: spec => nextState(spec),
@@ -27,6 +30,19 @@ export function verifyEffects(specDir, log = line => console.error(line)) {
27
30
  };
28
31
  }
29
32
 
33
+ /* A RetroArch run needs its UDP ports to itself: another RetroArch still holding them would take
34
+ * the route's presses and commands (udp-ports.ts). */
35
+ async function refuseBusyRetroArchPorts(spec) {
36
+ const usesRetroArch = !spec.emulator || /retroarch/i.test(spec.emulator.command.join(' '));
37
+ if (!usesRetroArch) return;
38
+ const busy = await firstBusyUdpPort(RETROARCH_UDP_PORTS);
39
+ if (busy !== null) {
40
+ throw new Error(
41
+ `UDP port ${busy} is in use (another RetroArch running?): close it before verifying`,
42
+ );
43
+ }
44
+ }
45
+
30
46
  /* a started process, once it has run STARTUP_MS without exiting */
31
47
  function started(child, stop) {
32
48
  return new Promise((resolve, reject) => {
@@ -68,6 +68,13 @@ export declare const AddressSpecSchema: z.ZodObject<{
68
68
  export type AddressSpec = z.infer<typeof AddressSpecSchema>;
69
69
  /** Symbols from an ld map (` 0x800dc50c gGamestate`) or a splat file (`gGameState = 0x80177834;`). */
70
70
  export declare function parseSymbolFile(text: string): Map<string, number>;
71
+ /** How much of a decomp's symbol map names the game itself: the triage before writing a reader
72
+ * (a byte-identical decomp can still name nothing past boot code, like Yoshi's Story's). */
73
+ export declare function triageNames(symbols: ReadonlyMap<string, number>): {
74
+ placeholders: number;
75
+ library: number;
76
+ game: string[];
77
+ };
71
78
  /** `struct CourseTable.vertexStart` → the type and the member path. */
72
79
  export declare function splitMember(spec: string): {
73
80
  type: string;
@@ -58,6 +58,26 @@ export function parseSymbolFile(text) {
58
58
  }
59
59
  return out;
60
60
  }
61
+ /* splat's and m2c's placeholders for unnamed code and data */
62
+ const PLACEHOLDER = /^(func|D|B|jtbl|L|lbl|sub|unk|RO|dlabel|jlabel)_[0-9A-Fa-f]+/;
63
+ /* libultra, the audio library and the compiler runtime: named, but not the game */
64
+ const LIBRARY = /^(_|os|gu|gsp|gdsp|al|n_al|rsp|sp|__|bcopy|bzero|memcpy|strlen|sprintf|ld|ll)/;
65
+ /** How much of a decomp's symbol map names the game itself: the triage before writing a reader
66
+ * (a byte-identical decomp can still name nothing past boot code, like Yoshi's Story's). */
67
+ export function triageNames(symbols) {
68
+ let placeholders = 0;
69
+ let library = 0;
70
+ const game = [];
71
+ for (const name of symbols.keys()) {
72
+ if (PLACEHOLDER.test(name))
73
+ placeholders++;
74
+ else if (LIBRARY.test(name))
75
+ library++;
76
+ else
77
+ game.push(name);
78
+ }
79
+ return { placeholders, library, game: game.sort() };
80
+ }
61
81
  /** `struct CourseTable.vertexStart` → the type and the member path. */
62
82
  export function splitMember(spec) {
63
83
  const m = /^((?:struct |union )?[A-Za-z_][A-Za-z0-9_]*)\.(.+)$/.exec(spec);
@@ -4,3 +4,4 @@ export * from './asset-sandbox.js';
4
4
  export * from './inspect.js';
5
5
  export * from './verify.js';
6
6
  export * from './addresses.js';
7
+ export * from './udp-ports.js';
package/lib/host/index.js CHANGED
@@ -8,3 +8,4 @@ export * from './asset-sandbox.js';
8
8
  export * from './inspect.js';
9
9
  export * from './verify.js';
10
10
  export * from './addresses.js';
11
+ export * from './udp-ports.js';
@@ -0,0 +1,4 @@
1
+ /** RetroArch's default command port and player 1's network-pad port. */
2
+ export declare const RETROARCH_UDP_PORTS: readonly [55355, 55400];
3
+ /** The first of these UDP ports something else holds, or null when all are free. */
4
+ export declare function firstBusyUdpPort(ports: readonly number[]): Promise<number | null>;
@@ -0,0 +1,26 @@
1
+ import dgram from 'node:dgram';
2
+ /*
3
+ * RetroArch's network commands (55355) and network pad (55400 + player) are UDP ports on
4
+ * localhost. A second RetroArch still holding them takes the route's presses and commands for
5
+ * itself, and the run fails for no visible reason (GoldenEye's route, 2026-12-01).
6
+ */
7
+ /** RetroArch's default command port and player 1's network-pad port. */
8
+ export const RETROARCH_UDP_PORTS = [55355, 55400];
9
+ /* whether a UDP port on localhost can be bound now */
10
+ function udpPortFree(port) {
11
+ return new Promise(resolve => {
12
+ const socket = dgram.createSocket('udp4');
13
+ socket.once('error', () => {
14
+ socket.close();
15
+ resolve(false);
16
+ });
17
+ socket.bind(port, '127.0.0.1', () => socket.close(() => resolve(true)));
18
+ });
19
+ }
20
+ /** The first of these UDP ports something else holds, or null when all are free. */
21
+ export async function firstBusyUdpPort(ports) {
22
+ for (const port of ports)
23
+ if (!(await udpPortFree(port)))
24
+ return port;
25
+ return null;
26
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gameslate/sdk",
3
- "version": "0.3.9",
3
+ "version": "0.3.11",
4
4
  "description": "Build plugins for GameSlate, the second-screen companion for PC games: the plugin contract, game-state and catalogue schemas, and the plugin builder.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -124,6 +124,11 @@ Mario Kart 64's verified addresses):
124
124
  }
125
125
  ```
126
126
 
127
+ It prints the table unless given `--out`, and it fails on any `${VAR}` in the spec that isn't
128
+ set (`CLANG_INCLUDE` is `$(clang-18 -print-resource-dir)/include`). Some decomps keep a symbol
129
+ only in the linker script, which the `.map` reader skips (F-Zero X's `gRacers`): find it in the
130
+ splat `symbol_addrs*.txt`, and confirm its size against the struct times the count.
131
+
127
132
  A decomp that generates headers at build time (Paper Mario's `item_enum.h`) needn't be built:
128
133
  list them in `"stubHeaders"` and the probe gets empty ones (a layout that really needs one still
129
134
  fails to compile). Constants come back signed.
@@ -160,6 +165,12 @@ first). Commit the spec and the generated table; the decomp and ROM stay local.
160
165
  blank save reads as zeros anywhere, so a zero read proves nothing.
161
166
  7. **Sizes and signs come from declarations and probes, never from guesses:** a 14-byte struct
162
167
  isn't 16 (`CourseVtx` has 2-byte alignment); a `u8` read as `getInt8` turns 0xFD into -3.
168
+ 8. **Check each offset in the compiled code as well.** A matching decomp's objects are the
169
+ truth the probe models: `mips-linux-gnu-objdump -dr build/<region>/src/<file>.o` on a
170
+ one-line accessor gives the offset and the array stride (GoldenEye's
171
+ `getCurrentPlayerWeaponId` is a shift-add chain making ×0x3A8, then `lw v0,2160(t8)`:
172
+ `struct hand` is 0x3A8 bytes and `weaponnum` sits at 0x870). Every GoldenEye read was checked
173
+ this way; it costs minutes and catches a probe compiled with the wrong defines.
163
174
 
164
175
  **Leads, from LiveSplit or RetroAchievements:**
165
176
 
@@ -272,6 +283,32 @@ plugin exactly as the core will before running it. Then bump `version`, tag `vX.
272
283
 
273
284
  ## Pitfalls seen in real plugins
274
285
 
286
+ **Add to this list as you go.** When a review, a route or a live run catches something a future
287
+ game could repeat, add it here (in `@gameslate/sdk`'s `template/claude/skills`, then copy it into
288
+ the plugin repos) in the same change as the fix. The next game should not have to find it again.
289
+
290
+ - **"Racing" is more than one state.** Wave Race 64 runs the race in its race state, then in five
291
+ more after the finish line, a retire or a quit, until the results (0x29-0x2D): reading only the
292
+ named race state dropped the final place as it was decided. Find the function that dispatches
293
+ on the game state and list every state it runs as the race.
294
+ A stage's phase can live in another variable than its mode: GoldenEye keeps `current_menu` at
295
+ RUN_STAGE for the whole stage, and `g_CameraMode` says what the player sees (intro, fade,
296
+ swirl, first person, the AI's cuts and exit cinemas, two death cameras that alternate, a
297
+ one-frame return to Bond). Map every value the stage runs under, and keep the mission as the
298
+ location through the debrief that follows it.
299
+ - **The probe can need what IDO forgives.** GoldenEye's headers declare `extern` arrays of
300
+ incomplete struct types and a prototype with an undeclared type: IDO builds them, clang
301
+ refuses. Use the decomp's own switch that skips the header (`-DAIPARSE` skips
302
+ `chrobjdata.h`) or `-D` the missing type, only when it touches no layout you read, say so in
303
+ the source, and confirm the offsets in the compiled code (§ 4, step 8).
304
+ - **Player arrays hold more than players.** Mario Kart 64's time-trial ghosts are human-flagged
305
+ karts with one extra bit (`PLAYER_INVISIBLE_OR_BOMB`), and a replay puts a ghost in slot 0.
306
+ Read every function that spawns into the array before deciding which slots are rivals, ghosts
307
+ or people.
308
+ - **CI must run the real check.** On a runner without the `packageManager` pin, `yarn` is Yarn 1
309
+ and plain `yarn check` is its built-in lockfile check: CI stayed green while running no tests.
310
+ Pin `packageManager` and run `yarn run check`.
311
+
275
312
  - **Texture packs:** a port's HD packs (`mods/*.o2r`) replace textures. Read them the way the game
276
313
  does: packs first, in name order, each preferring its `alt/` asset, then the base archive.
277
314
  Otherwise you overwrite HD output with vanilla.
@@ -301,8 +338,19 @@ plugin exactly as the core will before running it. Then bump `version`, tag `vX.
301
338
  directly, and let a route's `expect` check what the daemon actually sends.
302
339
  - **Unnamed values and globals:** a decomp with few names (Kirby 64) still gives addresses: a
303
340
  splat `D_<address>` is its address. Cite the function that reads it, and confirm each live.
341
+ - **Check the decomp names the game before writing anything** (`gameslate-plugin names <map>`
342
+ counts the game's own names against `func_`/`D_` placeholders and lists its `g…` globals). List the map's names that aren't
343
+ `func_`/`D_`/libultra, and look for an unsplit `bin` segment in the splat yaml. Yoshi's Story's
344
+ matching decomp names only boot, threads, fault, EEPROM, DMA and pad code, and everything past
345
+ ROM 0xB58B0 is one `unkbin` blob: no game state, level or player at all, so there was nothing
346
+ to read without guessing. Stop there and say so; matching isn't the same as named.
304
347
  - **Menus may read only the d-pad.** Gopher64's d-pad is `w` `a` `s` `d` and its arrows are the
305
348
  stick (`~/.config/gopher64/config.json`); Kirby 64's menus ignore the stick.
349
+ - **Steer by the highlight, not the selection.** A menu's "selected" variable is often set only
350
+ when the choice is confirmed (GoldenEye's `selected_difficulty`), while the stick moves a cursor
351
+ and a separate "highlighted" one (`mission_difficulty_highlighted`). A route pushes the stick
352
+ until the highlight reads the choice, on the menu that shows it (`current_menu` 8 there, not
353
+ the briefing after it), then confirms and checks the selection.
306
354
  - **Menus remember:** many games save the last menu choices, so a route that only presses Start
307
355
  lands somewhere else next time. Pin each choice with the game's own menu variables.
308
356
  - **Prove it on real data before writing to a player's files.** Back up what's there before the
@@ -39,9 +39,22 @@ The steps:
39
39
  two contexts 0x30 bytes apart that sit just before them, each holding a framebuffer pointer.
40
40
  Grabbing an emulator's window can come back black (WSLg, GPU surfaces).
41
41
  4. **Press buttons:** XTEST key events into the emulator's window (Gopher64 maps Start to Return,
42
- A to Left Shift, B to Left Ctrl, Z to `z`, the stick to the arrows).
43
- 5. **Wait on state, not time:** after each input, read until the game state you expect appears
44
- (for example "game state = racing"), with a timeout.
42
+ A to Left Shift, B to Left Ctrl, Z to `z`, the stick to the arrows). Those need the window to
43
+ have the keyboard, which an unattended WSLg run never gets. **RetroArch needs no focus:** its
44
+ network RetroPad takes `pad:` keys (`gameslate drive press pad:START 120 pad:B 6000`). Start it
45
+ with an appended config holding `network_remote_enable = "true"`,
46
+ `network_remote_enable_user_p1 = "true"` and `pause_nonactive = "false"`, and write the
47
+ route's `press` steps as `pad:` keys. With mupen64plus-next, RetroPad **B is the N64's A**
48
+ (confirms menus in Mario Kart 64 and F-Zero X, accelerates in F-Zero X) and RetroPad A is the
49
+ N64's B. gameslate-n64's `verify/mk64-gp-start-retroarch.json` (with
50
+ `verify/retroarch-pad.cfg`) is the worked example: it passed `gameslate-plugin verify` from
51
+ boot to a Grand Prix race with nobody at the machine.
52
+ The network RetroPad takes the **analog sticks** too: `pad:LSTICK:<x>,<y>` (and `RSTICK`,
53
+ the C buttons under mupen64plus-next), each -1..1 with +x right and +y down, held for the
54
+ hold time and then recentred. It moved Mario Kart 64's menu cursor live. Menus with an
55
+ analog cursor (GoldenEye's folders, missions and difficulties) can now be steered; a route
56
+ written before this, like `verify/ge-dam-start-retroarch.json`, may still pin whatever the
57
+ cursor rested on.
45
58
 
46
59
  Script the route per game as inputs plus checks, such as "Start until game state 4, hold A for
47
60
  9 s, expect place and lap". Prefer moments a route reaches from boot.
@@ -51,8 +64,41 @@ Script the route per game as inputs plus checks, such as "Start until game state
51
64
  (`.eep`/`.sra`) work across emulators. A save state is the last resort: tied to one emulator
52
65
  version, and it needs a person to make it. Keep saves and states out of the repo: they're game
53
66
  data.
54
- - **RetroArch** can load a state at start (`-e <slot>`) and answers network commands, but its
55
- N64 core crashed on one dev machine. Check that it boots a game before relying on it.
67
+ - **Replaying a TAS (N64, BizHawk `.bk2`)**: `gameslate drive tas <movie.bk2> <rom> <frame>,…
68
+ --retroarch <AppImage> --core <…_libretro.so>` replays it in RetroArch, unattended, and
69
+ leaves a snapshot per frame in `~/.cache/gameslate/snapshots/` (state, EEPROM, `rdram.bin`,
70
+ `screen.png`); later runs start from the nearest one. Diff `rdram.bin` before and after an
71
+ event the screen shows (a fruit eaten, a hit) for candidate addresses, then confirm each in the
72
+ decomp. Before trusting a frame, prove the replay is in sync: check moments the run must hit
73
+ (a menu choice, a random roll it stops on, a count) in memory and on the screen, and compare
74
+ the game's own frame counter between cores. Limits: it stops before the movie's first reset;
75
+ `mupen64plus_next` (resumable, screens via angrylion) clamps sticks past ±119, which the game
76
+ can tell; `parallel_n64` sends −128..127 exactly (`--options <file>` sets its RSP/video) but
77
+ only plays from power-on, and booted slower than the movie expects. Neither kept Yoshi's
78
+ Story's 100% movie in sync (`docs/emulator-driving.md`), so use the snapshots for diffing real
79
+ events, not "frame N is event X". Fetch the movie on demand and keep it, and the snapshots,
80
+ out of every repo.
81
+ - **Replay a TAS in BizHawk** when you can: `drive tas … --emulator bizhawk` runs the movie in its
82
+ own emulator (Windows BizHawk from WSL, version from the movie's header; an older movie needs
83
+ the nearest release that runs: 2.2.1's N64 plugins heap-crash on Windows 11 24H2), so it
84
+ should stay in sync where RetroArch's cores drift. Star Fox 64's glitchless 7190 played in
85
+ sync on 2.9.1. From WSL, start Windows
86
+ programs through `/init <exe>` (Mono's binfmt handler intercepts `.exe`s otherwise), never
87
+ through a shell-built command line (a lost apostrophe in a ROM name gave an empty window),
88
+ and tell the user before a window opens. A modal box stalls an unattended run: find one with
89
+ UI Automation or EnumWindows on the PID, and check the Application event log for APPCRASH.
90
+ Prove sync as above before using a frame. Pick the movie in this order: glitchless/100%/standard
91
+ categories that play the game as intended, the newest BizHawk, the default core and plugin;
92
+ avoid ACE, wrong-warp and game-end-glitch runs, and read the submission (`tasvideos.org/<n>S`)
93
+ for sync steps. On Windows 11 24H2 old Mupen64Plus code fails (the dynarec,
94
+ Glide64mk2): a movie that sits at frame 0 or crashes may run with `Core` 1 (interpreter) in a
95
+ copy of its `SyncSettings.json`, but such a copy is a deviation: prove sync (menu picks, counts
96
+ rising steadily, no lost health, level clears) before trusting any frame of it.
97
+ - **RetroArch** can load a state at start (`-e <slot>`), answers network commands and takes the
98
+ network RetroPad. Its mupen64plus-next core crashed on one dev machine with one build and ran
99
+ for an hour with another (`stable-cores`): check that it boots a game first. Under it,
100
+ `drive frame` comes back black (the renderer doesn't write the frame to RDRAM) and so do its own
101
+ screenshots under WSL: take frames from Gopher64, or check values with `peek` instead.
56
102
  - **PC games:** a save file at that moment, loaded by hand. Then the tool only reads; leave
57
103
  `retroarch` out of the spec.
58
104
 
@@ -109,6 +155,9 @@ map), because the game saves the last choices.
109
155
  whose address moves.
110
156
  - `"times": 3` needs that many matching reads in a row. Transitions can pass through a state
111
157
  for an instant: MM's opening reads as gameplay between its shots.
158
+ - `press` with `until` presses again before every read, so `"times": 2` there means two
159
+ presses. On a toggle (a pause menu, GoldenEye's watch) the second press undoes the first:
160
+ use `"times": 1`, or press once and `waitFor` the state, with a `waitMs` while it animates.
112
161
 
113
162
  The first step that can't do what it says stops the run and names itself.
114
163
  - **Pin every menu choice.** A route that presses Start until "racing" goes wherever the saved
@@ -146,6 +195,10 @@ puts their terminal in front and stalls the run.
146
195
  1. Build the plugin: `yarn check`.
147
196
  2. Start a local GameSlate daemon with your build:
148
197
  `GAMESLATE_PLUGINS_DIR=$PWD/dist node <gameslate>/dist/gameslate.mjs`.
198
+ Beside a daemon that's already running, give yours its own `GAMESLATE_PORT`, a `HOME` holding
199
+ `.config/gameslate/config.json` (a `pairingToken`), and a short `GAMESLATE_SOCK`: a UNIX
200
+ socket path over 107 bytes fails with `EINVAL`, and a scratch folder's often is. Then set the
201
+ spec's `"daemon": { "url": "ws://localhost:<port>/ws" }`; `verify` reads 4310 otherwise.
149
202
  3. `yarn dlx -p @gameslate/sdk gameslate-plugin verify verify/<moment>.json`
150
203
 
151
204
  It starts the emulator (`emulator.command`, with `${NAME}` taken from the environment, so specs
@@ -192,3 +245,8 @@ the start straight, so holding A long enough fetches an item to check the held-i
192
245
  `supportedBuildIds`? The daemon reports an unsupported build to the page.
193
246
  - **The game never starts** (the emulator idles at about 0% CPU): the display or GPU stack is
194
247
  broken (seen in WSL). Restart it; that's not the plugin.
248
+ - **"the game's RAM is in 2 places"**: two copies of the game's code both looked like live RAM.
249
+ The emulator's cartridge copy is rejected (the core checks for the ROM header in front of the
250
+ code first). Under RetroArch, Yoshi's Story also shows two full RAM copies, one in the heap and
251
+ one in a large mapping, both with a valid RAM size (2026-12-01, not yet resolved; MK64, F-Zero X,
252
+ Dr. Mario and GoldenEye don't). Verify such a game in Gopher64, and report the two addresses.