@gameslate/sdk 0.3.10 → 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.10",
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",
@@ -165,6 +165,12 @@ first). Commit the spec and the generated table; the decomp and ROM stay local.
165
165
  blank save reads as zeros anywhere, so a zero read proves nothing.
166
166
  7. **Sizes and signs come from declarations and probes, never from guesses:** a 14-byte struct
167
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.
168
174
 
169
175
  **Leads, from LiveSplit or RetroAchievements:**
170
176
 
@@ -285,6 +291,16 @@ the plugin repos) in the same change as the fix. The next game should not have t
285
291
  more after the finish line, a retire or a quit, until the results (0x29-0x2D): reading only the
286
292
  named race state dropped the final place as it was decided. Find the function that dispatches
287
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).
288
304
  - **Player arrays hold more than players.** Mario Kart 64's time-trial ghosts are human-flagged
289
305
  karts with one extra bit (`PLAYER_INVISIBLE_OR_BOMB`), and a replay puts a ghost in slot 0.
290
306
  Read every function that spawns into the array before deciding which slots are rivals, ghosts
@@ -322,8 +338,19 @@ the plugin repos) in the same change as the fix. The next game should not have t
322
338
  directly, and let a route's `expect` check what the daemon actually sends.
323
339
  - **Unnamed values and globals:** a decomp with few names (Kirby 64) still gives addresses: a
324
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.
325
347
  - **Menus may read only the d-pad.** Gopher64's d-pad is `w` `a` `s` `d` and its arrows are the
326
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.
327
354
  - **Menus remember:** many games save the last menu choices, so a route that only presses Start
328
355
  lands somewhere else next time. Pin each choice with the game's own menu variables.
329
356
  - **Prove it on real data before writing to a player's files.** Back up what's there before the
@@ -46,9 +46,15 @@ The steps:
46
46
  `network_remote_enable_user_p1 = "true"` and `pause_nonactive = "false"`, and write the
47
47
  route's `press` steps as `pad:` keys. With mupen64plus-next, RetroPad **B is the N64's A**
48
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.
50
- 5. **Wait on state, not time:** after each input, read until the game state you expect appears
51
- (for example "game state = racing"), with a timeout.
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.
52
58
 
53
59
  Script the route per game as inputs plus checks, such as "Start until game state 4, hold A for
54
60
  9 s, expect place and lap". Prefer moments a route reaches from boot.
@@ -58,6 +64,36 @@ Script the route per game as inputs plus checks, such as "Start until game state
58
64
  (`.eep`/`.sra`) work across emulators. A save state is the last resort: tied to one emulator
59
65
  version, and it needs a person to make it. Keep saves and states out of the repo: they're game
60
66
  data.
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.
61
97
  - **RetroArch** can load a state at start (`-e <slot>`), answers network commands and takes the
62
98
  network RetroPad. Its mupen64plus-next core crashed on one dev machine with one build and ran
63
99
  for an hour with another (`stable-cores`): check that it boots a game first. Under it,
@@ -119,6 +155,9 @@ map), because the game saves the last choices.
119
155
  whose address moves.
120
156
  - `"times": 3` needs that many matching reads in a row. Transitions can pass through a state
121
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.
122
161
 
123
162
  The first step that can't do what it says stops the run and names itself.
124
163
  - **Pin every menu choice.** A route that presses Start until "racing" goes wherever the saved
@@ -156,6 +195,10 @@ puts their terminal in front and stalls the run.
156
195
  1. Build the plugin: `yarn check`.
157
196
  2. Start a local GameSlate daemon with your build:
158
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.
159
202
  3. `yarn dlx -p @gameslate/sdk gameslate-plugin verify verify/<moment>.json`
160
203
 
161
204
  It starts the emulator (`emulator.command`, with `${NAME}` taken from the environment, so specs
@@ -202,3 +245,8 @@ the start straight, so holding A long enough fetches an item to check the held-i
202
245
  `supportedBuildIds`? The daemon reports an unsupported build to the page.
203
246
  - **The game never starts** (the emulator idles at about 0% CPU): the display or GPU stack is
204
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.