Make F8 write a bug capture and add a test run that starts from one.

F8 now always writes a folder under logs/captures: the area, Link's position and rotation, the camera of the frame on screen and the game's own, the presented frame as a PNG, frame times around the press, the machine, the settings that differ from the defaults, the end of the log, the save, and the game's flags and texts. A note on screen names the capture. The flight recorder's F8 dump goes into the capture's folder.

NX2NAVI_CAPTURE_REPLAY starts a run on a capture's settings, teleports to its area, walks Link to where he stood and puts the free camera where the camera was; tools/capture_run.py prepares the profile from the capture's save, runs it and compares the two captures. docs/bug-capture.md has the files and the steps.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
epicmeme546
2026-11-13 06:22:18 -05:00
parent a01910d905
commit 4fd70e398f
21 changed files with 1687 additions and 49 deletions

View File

@@ -223,8 +223,9 @@ keeps per-core data without locks and relies on that, so the host models it (`ru
whose size it uses, is made whole (`gfx_shader.c` `reflect_exact`). `auto` picks by the device-local budget.
- Occlusion queries never block the CPU; a result that is not ready counts as visible.
- Allocation: Vulkan Memory Allocator. Debugging: Vulkan validation layers, per-pass frame dumps (`NX2NAVI_DUMP`,
`vk_dump.c`), a sampling profiler (`NX2NAVI_PROFILE`, `tools/prof_report.py`) and a flight recorder
(`NX2NAVI_FLIGHT`). RenderDoc cannot capture, because it hides `VK_EXT_external_memory_host` from the application.
`vk_dump.c`), a sampling profiler (`NX2NAVI_PROFILE`, `tools/prof_report.py`), a flight recorder
(`NX2NAVI_FLIGHT`) and bug captures, which a player's F8 writes and a test run starts from (`bugcap.c`,
[bug-capture.md](bug-capture.md)). RenderDoc cannot capture, because it hides `VK_EXT_external_memory_host` from the application.
Maxwell behaviour the back end has to match: [maxwell.md](maxwell.md).

120
docs/bug-capture.md Normal file
View File

@@ -0,0 +1,120 @@
# Bug captures
A bug capture records where and how the game was when a player saw something wrong, so that the bug can be looked for
again at that place instead of somewhere else. The player presses **F8**; a test run then starts from what the press
wrote. Code: `runtime/bugcap.c`, `tools/capture_run.py`. Ocarina of Time 1.1.1 (the place and the camera come from the
debug tools, `runtime/debug_tools.c`); on other game versions a capture still has the picture, the timing, the
settings and the save.
## For the player
When you see a bug, press **F8** while the game window is in front. About a second later a note at the top of the
screen says *Bug capture 3 saved* with the folder's name. Tell whoever looks into the bug the number ("capture 3") and
what you saw; nothing else is needed. Press it as often as you like: each press is its own capture, and a press while
the one before is still being written is skipped.
The captures are in the game folder under `logs\captures`, one folder each, named by number and time
(`003-20261113-141502`). *Menu > Open log folder* shows `logs`. A capture is between one and a few megabytes; delete
old ones whenever you like. Nothing leaves your PC: a capture is files on your disk.
## What a capture holds
| File | What |
|---|---|
| `capture.txt` | Written last: a folder that has it is complete. `key = value` lines under `[sections]`, see below |
| `frame.png` | The frame on screen as the window got it, the overlay included, without the capture's own note (an HDR picture converted to sRGB) |
| `frames.tsv` | The last 600 presents before the press and the 30 after: frame, interval and replay time in ms |
| `log-tail.txt` | The last 256 KB of the run's log |
| `settings.ini` | Every setting that had a value (from `nx2navi.ini`, the menu or the environment) as `nx2navi.ini` lines, without the private ones (`runtime/cfg_private.h`) |
| `NX2navi-save-<time>.zip` | The save the game would load next, as *Menu > Export save* writes it |
| `flags.tsv`, `texts.tsv` | The game's on/off flags and its 64-character texts, by the hash of their names |
| `flight/` | With `flight = 1`: the flight recorder's dump of the same moment (`tools/flight_view.py` reads it) |
`capture.txt`:
- `[capture]`: `number`, `name`, `time`, `time_utc`, `trigger` (`F8`, `NX2NAVI_CAPTURE_AT`, `replay`), the NX2navi and
game versions, the presented `frame`, `run_seconds`, `menu_open`.
- `[place]`: `area` (the game's own name, which says child or adult for the outdoor areas: `HyruleField_Adult`),
`player_pos` in metres (`none` at the title screen and while loading), `player_rot` (Link's 3x3 rotation by rows) and
`player_yaw`, and `nearest_start`, the area's start position nearest to him, when the list of start positions was
read (the debug menu or a test reads it).
- `[camera]`: `camera_pos`, `camera_dir`, `camera_yaw` and `camera_pitch` (radians; the camera looks along
`(cos pitch sin yaw, sin pitch, cos pitch cos yaw)`, the free camera's convention) with `camera_source`: the frame on
screen when DLSS, DLAA or FSR runs (then also `camera_fov_y_degrees`, `camera_aspect`, the near and far planes),
else the free camera when it is on, else the game's own camera. `game_camera_pos` / `game_camera_target` and
`event_camera_pos` / `event_camera_target` are the game's two scene cameras as its camera update chose them in the
frames after the press, whatever was drawn.
- `[picture]`: the window's size, the game image's size, HDR, the scaler, the present mode, the display's rate.
- `[timing]`: over the presents before the press: the average frame rate, the median, 95th and 99th percentile and
the longest frame time, how many frames took over 33 and 50 ms, the last 30 intervals before and the first after,
and the performance overlay's numbers when it was on.
- `[system]`: OS, CPU, RAM, GPU, driver.
- `[settings that differ from the defaults]`: the settings whose value is not the default; a private one shows only
that it is set.
Position, rotation, area and the camera of the frame on screen are read on the render thread at the press, so they
belong to the frame the timing ends with; the picture is the next present.
## Starting a test run from a capture
```
python tools/capture_run.py 3
python tools/capture_run.py "C:\...\game\logs\captures\003-20261113-141502" --set FSR4=0 --hold 30
```
The argument is a capture's folder or its number under the installed game's `logs\captures` (`--game` names another
game folder). The script
1. refuses to start while a game is running (one game at a time);
2. makes a throwaway profile: the game's own profile without its saves, with the capture's save as a waiting import,
which the game makes the save when it starts;
3. starts the game with `NX2NAVI_CAPTURE_REPLAY=<the capture's folder>`, in a window of the capture's size that takes
neither the focus nor your input (`--foreground` and `--fullscreen` change that), co-op and Discord off;
4. waits while the game presses A through the title screen and the file menu, teleports to the capture's area,
walks Link to where he stood, puts the free camera where the camera was and takes a capture of its own;
5. closes the game and prints both captures side by side: area, positions, the distance between them, cameras, and
the mean difference of the two pictures.
The run's log and its capture are in `<capture>/replays` (`--out` names another folder). `--set KEY=VALUE` puts one
setting on top of the capture's for this run, which is how a suspected setting is tried: run once as captured and
once with `--set`. `--hold <seconds>` keeps the game open after its capture; `--no-camera` leaves the camera to the
game, for a bug that is about the camera itself. Any other test setting can ride along with `--set` (`DUMP`, `SHOT_DIR`
and `SHOT_EVERY`, `DBG_TEST`, `TRACE`).
What the game does in such a run (`NX2NAVI_CAPTURE_REPLAY`, environment only):
- The capture's `settings.ini` stands in for `nx2navi.ini`, which is neither read nor written; the environment still
wins over it. The log's first lines say so and list the settings.
- Until Link appears the pad presses A (four reads in every hundred).
- Three seconds later the game changes area as its own doors do (`dbg_warp`), to the start position of the capture's
area that is nearest to the captured place; when the save already starts within 60 m of it, there is no teleport.
A refused teleport (an event still running after the load) is asked again, up to six times.
- Link runs to the captured `x z` (`dbg_route_to`), walking the last three metres, steered by the game's own camera, and counts as there within half a
metre. He is walked, not put: his position cannot be written (`debug_tools.c`). When something is in the way he
sidesteps, and after ten tries the walk is given up where he is.
- The free camera is turned on standing (the pad still plays the game) and put at `camera_pos`, `camera_yaw`,
`camera_pitch`. `NX2NAVI_CAPTURE_REPLAY_CAMERA=0` leaves the game's camera.
- Three seconds later the log says `capture: replay of <name> ready: ...` with how far Link is from the captured
place, and the run takes its own capture (`trigger = replay`), whose `capture.txt` adds `replay_of`,
`replay_player_off_metres`, `replay_walk` and `replay_camera`.
What a replay does not bring back: the time of day, enemies and other actors, Link's pose and what he holds, an event
or cutscene that was running, and progress made since the last save (the save is the one on disk at the press; the
flags that differed are in `flags.tsv`). A capture taken at the title screen or while loading has no area: its replay
applies the settings and stops.
Without the script: set `NX2NAVI_CAPTURE_REPLAY` to the folder and start the game with `--profile <a copy of a
profile>`; `NX2NAVI_CAPTURE_DIR` says where the run's own capture goes (default `<capture>/replays`).
## Test settings
Environment or `nx2navi.ini`, for runs without a keyboard:
- `NX2NAVI_CAPTURE_AT=<frame>[,<frame>...]`: a capture at each of those presented frames (up to 16).
- `NX2NAVI_CAPTURE_DIR=<folder>`: the folder captures go to, in place of `logs/captures`.
## The flight recorder
`flight = 1` keeps a ring of the last frames with a small picture each (`runtime/flight.c`). Its dump on F8 now
belongs to the capture: it goes to the capture's `flight` folder. Its other dumps (a frame over `flight_spike_ms`,
`NX2NAVI_FLIGHT_AT`, `NX2NAVI_FLIGHT_EVERY`) go to the `flight` folder beside the game folder as before.

View File

@@ -89,6 +89,7 @@ The game's *Swap Jump Controls* option trades B and X (jump on B, put away on X)
| Key | Gamepad | Action |
|---|---|---|
| F1 or Esc | Minus and Plus together | open or close the settings menu; the game gets no input while it is open |
| F8 | | bug capture: saves where you are, the camera, the picture, the settings, the log's end and your save into `logs\captures`, and a note on screen names it ([bug-capture.md](bug-capture.md)) |
| F10 | L3 + R3 (both stick clicks) | performance overlay: off, frame rate, full panel |
| F11 | | borderless fullscreen on or off, saved to `nx2navi.ini`; not with Ctrl, Shift or Alt held, which overlays and capture tools use |
@@ -102,7 +103,7 @@ The sound plays on the system default device, and follows it when the Windows de
## Remapping
The *Controls* tab of the settings menu lists, under the button layout, every Switch button and the eight stick directions the keys drive (movement and camera), each with two key cells and a controller cell. Each row's description says what the button does in the game. Select a cell, press A or Enter, then press the new key, mouse button or controller button; Esc or five seconds without a press cancel, and a controller button cancels a key cell. Delete, Backspace or X clears the selected cell. A key another action has moves to the new one (the description names the action it left); a controller button swaps with the one it replaces. A remapped controller button is physical: from then on the face buttons (A B X Y) stay where they are in both layouts, until the buttons are put back as the layout in use has them or *Reset all buttons* is chosen. F1, F8, F10, F11 and Esc cannot be bound (the menu, the flight recorder and the window keep them). Punctuation keys are named by their place on a US keyboard; the menu shows the character the keyboard layout in use puts there.
The *Controls* tab of the settings menu lists, under the button layout, every Switch button and the eight stick directions the keys drive (movement and camera), each with two key cells and a controller cell. Each row's description says what the button does in the game. Select a cell, press A or Enter, then press the new key, mouse button or controller button; Esc or five seconds without a press cancel, and a controller button cancels a key cell. Delete, Backspace or X clears the selected cell. A key another action has moves to the new one (the description names the action it left); a controller button swaps with the one it replaces. A remapped controller button is physical: from then on the face buttons (A B X Y) stay where they are in both layouts, until the buttons are put back as the layout in use has them or *Reset all buttons* is chosen. F1, F8, F10, F11 and Esc cannot be bound (the menu, the bug capture and the window keep them). Punctuation keys are named by their place on a US keyboard; the menu shows the character the keyboard layout in use puts there.
The tab writes `nx2navi.ini` lines, one per Switch button or stick direction: `bind_<button> = <entry>, <entry>, ...`. The button is `A B X Y L R ZL ZR PLUS MINUS LEFT UP RIGHT DOWN LCLICK RCLICK`, or a stick direction `LSTICK_LEFT LSTICK_UP LSTICK_RIGHT LSTICK_DOWN` (movement, W A S D by default) and `RSTICK_...` (camera, the arrow keys). An entry is `pad:<name>` or `key:<name>`:

View File

@@ -34,6 +34,13 @@
yet: the other players as a Link model, shared enemies, and invites that start the game for a friend who has it
closed. Everyone needs the same NX2navi version. `docs/coop.md` has the details and how to go back to a save.
- **F8 saves a bug capture.** When you see something wrong, press F8: the game writes where Link stands, the area,
the camera, the picture on screen, your settings, the frame times around the press, the end of the log and your
save into one folder under `logs\captures`, and a note on screen gives the capture its number. Telling us "capture
3" is then enough: a test run starts at that place with that camera and those settings
(`python tools/capture_run.py 3`, `docs/bug-capture.md`) instead of somewhere else on another save. Until now F8
did something only with the flight recorder on (`flight = 1`); its F8 dump now goes into the capture's folder.
## Changed
- **The draw replay on several CPU cores is off by default again** (`replay_workers = 0`). With three workers on by

802
runtime/bugcap.c Normal file
View File

@@ -0,0 +1,802 @@
// Bug captures (bugcap.h): what a player's F8 writes, and the run that starts from it. docs/bug-capture.md.
//
// A capture is one folder, <log folder>/captures/<number>-<YYYYMMDD-HHMMSS>/ (NX2NAVI_CAPTURE_DIR names another base):
//
// capture.txt written last, so a folder that has it is complete. "key = value" lines under [sections]: when,
// versions, the area, Link's position and rotation, the camera of the frame on screen and the
// game's own, the window and picture, frame times around the press, the machine, and the settings
// that differ from the defaults
// frame.png the presented frame as the window got it, overlay included, without this capture's own note
// frames.tsv the last RING presents before the press and the POST after it: frame, interval, replay time
// log-tail.txt the end of this run's log
// settings.ini every setting with a value, as nx2navi.ini lines, without the private ones (cfg_private.h): what a
// replay runs with
// NX2navi-save-*.zip the save the game would load next (save_share.c), which a replay starts from
// flags.tsv, texts.tsv the game's on/off flags and its 64-character texts, by the hash of their names
// flight/ the flight recorder's dump of the same moment, when flight = 1 (flight.c)
//
// The press is taken on the render thread (bugcap_frame), which reads what cannot wait: the position, the camera of
// the frame being shown, the frame times. It asks the present path for the next frame's pixels (vk_present_grab) and
// the game's camera update for its own choice (dbg_camera_watch), and a thread of its own waits for both, writes the
// files and then lets the note show. One capture at a time: a press while one is being written is logged and dropped.
//
// A replay (NX2NAVI_CAPTURE_REPLAY=<folder>) is a test run: cfg.c takes the folder's settings.ini in place of
// nx2navi.ini, the environment still on top, and writes no settings file. On the game's thread bugcap_replay_pad
// presses A until the save is loaded and bugcap_replay_tick then goes where the capture was taken with the debug
// menu's own tools (debug_tools.c): the game's change of area to the start position nearest to the place, Link's
// walk to it, the free camera at the captured camera. Link is walked, not put: his position cannot be written
// (debug_tools.c). At the end the replay takes a capture of its own, into <folder>/replays unless NX2NAVI_CAPTURE_DIR
// says otherwise, whose capture.txt names the original and how far from it Link ended.
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "bugcap.h"
#include "cfg.h"
#include "cfg_private.h"
#include "debug_tools.h"
#include "flight.h"
#include "host.h"
#include "input.h"
#include "input_map.h"
#include "perfmon.h"
#include "platform/platform.h"
#include "save_share.h"
#include "sysinfo.h"
#include "ui/menu.h"
#include "vk.h"
#include "vk_dlaa.h"
#define RING 600 // presents kept before a press: ten seconds at 60 a second
#define POST 30 // presents recorded after it
#define NOTE_NS 6000000000ull
#define LOG_TAIL (256u << 10)
typedef struct { uint64_t frame; uint32_t interval_us, replay_us; } FrameRec;
// The capture being taken. Filled by the render thread at the press, then read by the writer; grab comes from the
// present path and post from the render thread meanwhile, each behind its own count.
static struct {
int number;
char name[64], dir[PLAT_PATH_MAX], why[160];
struct tm local;
uint64_t unix_ns, frame, start_ns;
int have_pos, have_rot, have_area, have_cam, menu_open;
float pos[3], rot[9], speed;
char area[64];
VkDlaaCamera cam;
int fc_on, fc_sticks;
float fc_speed, fc_yaw, fc_pitch;
double fc_pos[3];
uint64_t seen0[2]; // the game's camera updates seen before this capture watched them
PerfStats perf;
FrameRec pre[RING];
int pre_n, flight;
FrameRec post[POST];
volatile int post_n;
VkGrab *grab;
volatile int grab_done;
char replay_note[400]; // a replay's capture: what it was a replay of and how close it came
} job;
static volatile int32_t busy; // a capture is being taken or written
static FrameRec ring[RING]; // the render thread's
static uint64_t ring_n;
static volatile uint64_t note_until; // the note shows until then (plat_now_ns); the three below are set before it
static int note_number, note_ok;
static char note_name[64];
// ---- where captures go
static struct {
int state; // 0 not looked at, 1 a replay, -1 none
char dir[PLAT_PATH_MAX], name[64];
char text[16384]; // the replayed capture.txt
} rp_src;
static void replay_source(void) {
if (rp_src.state) return;
const char *e = getenv("NX2NAVI_CAPTURE_REPLAY"); // the environment only: a replay is one run, never a saved setting
if (!e || !*e) {
rp_src.state = -1;
return;
}
char path[PLAT_PATH_MAX + 16];
snprintf(rp_src.dir, sizeof rp_src.dir, "%s", e);
size_t n = strlen(rp_src.dir);
if (n > 12 && !strcmp(rp_src.dir + n - 12, "/capture.txt")) rp_src.dir[n - 12] = 0;
else if (n > 12 && !strcmp(rp_src.dir + n - 12, "\\capture.txt")) rp_src.dir[n - 12] = 0;
for (n = strlen(rp_src.dir); n && (rp_src.dir[n - 1] == '/' || rp_src.dir[n - 1] == '\\'); n--) rp_src.dir[n - 1] = 0;
const char *base = rp_src.dir;
for (const char *p = rp_src.dir; *p; p++)
if (*p == '/' || *p == '\\') base = p + 1;
snprintf(rp_src.name, sizeof rp_src.name, "%s", base);
snprintf(path, sizeof path, "%s/capture.txt", rp_src.dir);
uint64_t size = 0;
uint8_t *data = plat_file_read(path, &size);
if (data) snprintf(rp_src.text, sizeof rp_src.text, "%.*s", (int)(size < sizeof rp_src.text - 1 ? size : sizeof rp_src.text - 1), (const char *)data);
free(data);
rp_src.state = 1;
}
const char *bugcap_replay_dir(void) {
replay_source();
return rp_src.state > 0 ? rp_src.dir : NULL;
}
static void base_dir(char *out, size_t cap) {
const char *e = cfg_get("NX2NAVI_CAPTURE_DIR");
char logs[PLAT_PATH_MAX];
if (e && *e) snprintf(out, cap, "%s", e);
else if (bugcap_replay_dir()) snprintf(out, cap, "%s/replays", rp_src.dir);
else if (sysinfo_log_folder(logs, sizeof logs)) snprintf(out, cap, "%s/captures", logs);
else snprintf(out, cap, "captures");
}
static int highest(const char *name, int kind, uint64_t size, void *ctx) {
(void)size;
int n = 0, digits = 0;
while (name[digits] >= '0' && name[digits] <= '9' && digits < 6) n = n * 10 + (name[digits++] - '0');
if (kind == PLAT_FS_DIR && digits && name[digits] == '-' && n > *(int *)ctx) *(int *)ctx = n;
return 1;
}
// ---- the writer
typedef struct { FILE *f; } Txt;
static void put(Txt *t, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
static void put(Txt *t, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(t->f, fmt, ap);
va_end(ap);
}
static FILE *open_in(const char *name, const char *mode) {
char path[PLAT_PATH_MAX + 64];
snprintf(path, sizeof path, "%s/%s", job.dir, name);
FILE *f = fopen(path, mode);
if (!f) rt_log("capture: cannot write %s", path);
return f;
}
static int by_interval(const void *a, const void *b) {
uint32_t x = *(const uint32_t *)a, y = *(const uint32_t *)b;
return x < y ? -1 : x > y;
}
static void put_timing(Txt *t) {
static uint32_t sorted[RING];
int n = 0, over33 = 0, over50 = 0;
uint64_t sum = 0, rep = 0;
for (int i = 0; i < job.pre_n; i++) {
uint32_t us = job.pre[i].interval_us;
if (!us) continue;
sorted[n++] = us, sum += us, rep += job.pre[i].replay_us;
over33 += us > 33400, over50 += us > 50000;
}
put(t, "\n[timing]\n");
if (!n) {
put(t, "frames = 0\n");
return;
}
qsort(sorted, (size_t)n, sizeof *sorted, by_interval);
put(t, "frames = %d\nseconds = %.2f\nfps_average = %.1f\n", n, sum / 1e6, n * 1e6 / (double)sum);
put(t, "frame_ms_median = %.2f\nframe_ms_95 = %.2f\nframe_ms_99 = %.2f\nframe_ms_longest = %.2f\n", sorted[n / 2] / 1e3,
sorted[n * 95 / 100] / 1e3, sorted[n * 99 / 100] / 1e3, sorted[n - 1] / 1e3);
put(t, "frames_over_33ms = %d\nframes_over_50ms = %d\nreplay_ms_average = %.2f\n", over33, over50, rep / 1e3 / n);
put(t, "last_30_before_ms =");
for (int i = job.pre_n > 30 ? job.pre_n - 30 : 0; i < job.pre_n; i++) put(t, " %.1f", job.pre[i].interval_us / 1e3);
int post_n = __atomic_load_n(&job.post_n, __ATOMIC_ACQUIRE);
put(t, "\nfirst_%d_after_ms =", post_n);
for (int i = 0; i < post_n; i++) put(t, " %.1f", job.post[i].interval_us / 1e3);
put(t, "\n");
const PerfStats *p = &job.perf;
if (p->fps > 0) { // the performance overlay was on: its numbers of the last second
put(t, "overlay_fps = %.1f\noverlay_1pct_low_fps = %.1f\noverlay_frame_ms_max = %.2f\n", p->fps, p->low1_fps, p->frame_ms_max);
put(t, "overlay_cpu_pct = %.0f (the game %.0f)\noverlay_gpu_pct = %.0f\noverlay_vram_mb = %.0f of %.0f (the game %.0f)\n",
p->cpu_total_pct, p->cpu_game_pct, p->gpu_pct, p->vram_used_mb, p->vram_total_mb, p->vram_game_mb);
put(t, "overlay_replay_ms = %.2f\noverlay_gpu_ms = %.2f\noverlay_pipeline_wait_ms = %.2f\noverlay_texture_ms = %.2f\n",
p->replay_ms, p->gpu_ms, p->pipe_wait_ms, p->tex_ms);
}
}
static void write_frames(void) {
FILE *f = open_in("frames.tsv", "w");
if (!f) return;
fprintf(f, "# presents around bug capture %d, taken at frame %llu\nframe\tinterval_ms\treplay_ms\twhen\n", job.number,
(unsigned long long)job.frame);
for (int i = 0; i < job.pre_n; i++)
fprintf(f, "%llu\t%.2f\t%.2f\t%s\n", (unsigned long long)job.pre[i].frame, job.pre[i].interval_us / 1e3,
job.pre[i].replay_us / 1e3, job.pre[i].frame == job.frame ? "press" : "before");
int post_n = __atomic_load_n(&job.post_n, __ATOMIC_ACQUIRE);
for (int i = 0; i < post_n; i++)
fprintf(f, "%llu\t%.2f\t%.2f\tafter\n", (unsigned long long)job.post[i].frame, job.post[i].interval_us / 1e3,
job.post[i].replay_us / 1e3);
fclose(f);
}
// The end of the log: the last LOG_TAIL bytes from the first whole line on.
static void write_log_tail(void) {
char path[PLAT_PATH_MAX];
const char *log = rt_log_path();
if (log) snprintf(path, sizeof path, "%s", log);
else if (!plat_stderr_path(path, sizeof path)) return;
rt_log_sync();
// the game holds the log open for writing: the C library's open shares it, where plat_file_open is refused
FILE *in = fopen(path, "rb");
if (!in) return;
plat_fseek64(in, 0, SEEK_END);
int64_t size = plat_ftell64(in);
int64_t from = size > (int64_t)LOG_TAIL ? size - (int64_t)LOG_TAIL : 0;
size_t n = (size_t)(size - from);
char *buf = n ? malloc(n) : NULL;
int64_t got = buf && !plat_fseek64(in, from, SEEK_SET) ? (int64_t)fread(buf, 1, n, in) : -1;
fclose(in);
FILE *f = got > 0 ? open_in("log-tail.txt", "wb") : NULL;
if (f) {
const char *p = buf;
if (from) {
const char *line = memchr(buf, '\n', (size_t)got);
if (line) p = line + 1;
}
fprintf(f, "# the last %lld of %lld bytes of %s\n", (long long)(got - (p - buf)), (long long)size, path);
fwrite(p, 1, (size_t)(got - (p - buf)), f);
fclose(f);
}
free(buf);
}
// Keys that are of one run and not of the game's settings: what a test run's harness sets (scripted input, shots,
// dumps, the window kept in the background). capture.txt lists them; settings.ini, which a replay runs with, leaves
// them out.
static int run_key(const char *key) {
static const char *const starts[] = {"MENU_TEST", "SHOT_", "SHOTS", "DUMP", "PROFILE", "DBG_TEST"};
static const char *const whole[] = {"INPUT", "INPUT_SCRIPT", "INPUT_RECORD", "ASSUME_FOCUS", "BACKGROUND_WINDOW",
"FLIGHT_AT", "FLIGHT_EVERY", "FLIGHT_DIR", "TRACE"};
for (size_t i = 0; i < sizeof starts / sizeof *starts; i++)
if (!strncmp(key, starts[i], strlen(starts[i]))) return 1;
for (size_t i = 0; i < sizeof whole / sizeof *whole; i++)
if (!strcmp(key, whole[i])) return 1;
return 0;
}
typedef struct { FILE *ini; Txt *txt; int differ; } Settings;
static void setting_cb(const char *key, const char *value, int from_env, void *ctx) {
Settings *s = ctx;
if (!strncmp(key, "CAPTURE_", 8)) return; // a replay's own keys
char lower[80], var[96];
snprintf(lower, sizeof lower, "%s", key);
for (char *p = lower; *p; p++) *p = *p >= 'A' && *p <= 'Z' ? (char)(*p + 32) : *p;
snprintf(var, sizeof var, "NX2NAVI_%s", key);
if (!from_env && cfg_from_env(var)) return; // the file's line of a key the environment sets too: that one counts
int private = cfg_private_key(key);
if (s->ini && !private && *value && !run_key(key)) fprintf(s->ini, "%s = %s\n", lower, value);
if (!s->txt || !*value) return;
const char *def = cfg_default(key);
if (def && *def && !strcmp(def, value)) return; // set, to what it would be anyway
put(s->txt, "%s = %s%s\n", lower, private ? CFG_PRIVATE_SHOWN : value,
from_env ? " # from the environment" : def && *def ? "" : " # no fixed default");
s->differ++;
}
static void text_cb(uint32_t hash, const char *text, void *ctx) {
static const char *const names[] = {"Sequence_CurrentBanc", "Sequence_ReservedNextBanc", "Sequence_ReservedNextStartPosName",
"Sequence_ReservedBootEventName", "Sequence_ReservedEventStarterName"};
const char *name = "";
for (size_t i = 0; i < sizeof names / sizeof *names; i++)
if (dbg_name_hash(names[i]) == hash) name = names[i];
if (*text || *name) fprintf(ctx, "%08x\t%s\t%s\n", hash, text, name);
}
static void write_game_data(void) {
FILE *f = open_in("texts.tsv", "w");
if (f) {
fprintf(f, "# the game's 64-character texts that are not empty, by the hash of their names\nhash\ttext\tname\n");
dbg_texts(text_cb, f);
fclose(f);
}
int n = dbg_flags_refresh();
if (n && (f = open_in("flags.tsv", "w"))) {
fprintf(f, "# the game's on/off flags, by the hash of their names (a name: when the debug menu had read them)\nhash\tvalue\tname\n");
for (int i = 0; i < n; i++) {
const char *name = dbg_flag_name(i);
fprintf(f, "%08x\t%d\t%s\n", dbg_flag_hash(i), dbg_flag_value(i), name ? name : "");
}
fclose(f);
}
}
static void put_vec(Txt *t, const char *key, const double v[3]) { put(t, "%s = %.4f %.4f %.4f\n", key, v[0], v[1], v[2]); }
// A direction as the free camera's angles (debug_tools.c): it looks along (cos p sin y, sin p, cos p cos y).
static void angles_of(const double d[3], double *yaw, double *pitch) {
double len = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
*yaw = atan2(d[0], d[2]);
*pitch = len > 1e-9 ? asin(d[1] / len) : 0;
}
static void put_camera(Txt *t) {
put(t, "\n[camera]\n");
// the game's own cameras, as its update chose them in the frames after the press
static const char *const which[2] = {"game_camera", "event_camera"};
double gpos[2][3], gat[2][3];
int fresh[2] = {0, 0};
for (int i = 0; i < 2; i++) {
float up[3];
fresh[i] = dbg_camera_seen(i, gpos[i], gat[i], up) > job.seen0[i];
}
double pos[3], dir[3], yaw = 0, pitch = 0;
const char *source = "none";
if (job.have_cam) { // what the frame on screen was drawn with
for (int i = 0; i < 3; i++) pos[i] = job.cam.pos[i], dir[i] = job.cam.fwd[i];
source = "the frame on screen (the upscaler's camera)";
} else if (job.fc_on) {
memcpy(pos, job.fc_pos, sizeof pos);
yaw = job.fc_yaw, pitch = job.fc_pitch;
dir[0] = cos(pitch) * sin(yaw), dir[1] = sin(pitch), dir[2] = cos(pitch) * cos(yaw);
source = "the free camera";
} else if (fresh[0] || fresh[1]) {
int k = fresh[0] ? 0 : 1;
for (int i = 0; i < 3; i++) pos[i] = gpos[k][i], dir[i] = gat[k][i] - gpos[k][i];
source = k ? "the game's camera for events" : "the game's camera that follows Link";
}
put(t, "camera_source = %s\n", source);
if (strcmp(source, "none")) {
angles_of(dir, &yaw, &pitch);
double len = sqrt(dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]);
for (int i = 0; i < 3; i++) dir[i] = len > 1e-9 ? dir[i] / len : 0;
put_vec(t, "camera_pos", pos);
put_vec(t, "camera_dir", dir);
put(t, "camera_yaw = %.5f\ncamera_pitch = %.5f\n", yaw, pitch);
}
if (job.have_cam) {
put(t, "camera_up = %.4f %.4f %.4f\n", job.cam.up[0], job.cam.up[1], job.cam.up[2]);
put(t, "camera_fov_y_degrees = %.2f\ncamera_aspect = %.4f\ncamera_near = %.4f\n", job.cam.fov_y * 57.29578f,
job.cam.aspect, job.cam.znear);
if (job.cam.infinite) put(t, "camera_far = none\n");
else put(t, "camera_far = %.1f\n", job.cam.zfar);
}
for (int i = 0; i < 2; i++) {
if (!fresh[i]) continue;
char key[40];
snprintf(key, sizeof key, "%s_pos", which[i]);
put_vec(t, key, gpos[i]);
snprintf(key, sizeof key, "%s_target", which[i]);
put_vec(t, key, gat[i]);
}
put(t, "free_camera = %s\n", job.fc_on ? job.fc_sticks ? "on, flown with the sticks" : "on, standing" : "off");
if (job.fc_on) {
put_vec(t, "free_camera_pos", job.fc_pos);
put(t, "free_camera_yaw = %.5f\nfree_camera_pitch = %.5f\n", job.fc_yaw, job.fc_pitch);
}
}
static void grab_cb(VkGrab *g, void *ctx) {
(void)ctx;
job.grab = g;
__atomic_store_n(&job.grab_done, 1, __ATOMIC_RELEASE);
}
static void writer(void *arg) {
(void)arg;
plat_thread_priority(PLAT_PRIO_BELOW_NORMAL);
plat_file_mkdir_p(job.dir);
int ok = plat_dir_exists(job.dir);
if (!ok) rt_log("capture: cannot create %s", job.dir);
// the frame's pixels come with the next present, the game's camera with its next update, the frames after the
// press as they are shown: a second at most for all three
while (plat_now_ns() - job.start_ns < 2000000000ull && !__atomic_load_n(&job.grab_done, __ATOMIC_ACQUIRE)) plat_sleep_ms(2);
if (!__atomic_load_n(&job.grab_done, __ATOMIC_ACQUIRE)) vk_present_grab_cancel();
while (plat_now_ns() - job.start_ns < 700000000ull && __atomic_load_n(&job.post_n, __ATOMIC_ACQUIRE) < POST) plat_sleep_ms(5);
char shot[160] = "none: the frame could not be read back";
VkGrab *g = job.grab;
if (ok && g) {
uint8_t *rgba = malloc((size_t)g->w * (size_t)g->h * 4);
if (rgba) {
char path[PLAT_PATH_MAX + 16];
vk_present_grab_rgba(g, rgba);
snprintf(path, sizeof path, "%s/frame.png", job.dir);
if (flight_write_png(path, rgba, (uint32_t)g->w, (uint32_t)g->h))
snprintf(shot, sizeof shot, "frame.png (%dx%d%s)", g->w, g->h, g->hdr ? ", HDR10 converted to sRGB" : "");
else snprintf(shot, sizeof shot, "none: frame.png could not be written");
free(rgba);
}
}
FILE *f = ok ? open_in("capture.txt.part", "w") : NULL;
if (f) {
Txt t = {f};
struct tm u;
plat_gmtime((int64_t)(job.unix_ns / 1000000000u), &u);
put(&t, "# NX2navi bug capture %d. docs/bug-capture.md says how to start a run from it.\n[capture]\n", job.number);
put(&t, "number = %d\nname = %s\n", job.number, job.name);
put(&t, "time = %04d-%02d-%02d %02d:%02d:%02d\ntime_utc = %04d-%02d-%02dT%02d:%02d:%02dZ\n", job.local.tm_year + 1900,
job.local.tm_mon + 1, job.local.tm_mday, job.local.tm_hour, job.local.tm_min, job.local.tm_sec, u.tm_year + 1900,
u.tm_mon + 1, u.tm_mday, u.tm_hour, u.tm_min, u.tm_sec);
put(&t, "trigger = %s\nnx2navi = %s\ngame = Ocarina of Time %d.%d.%d\n", job.why, rt_port_version, rt_game_version / 100,
rt_game_version / 10 % 10, rt_game_version % 10);
put(&t, "frame = %llu\nrun_seconds = %.1f\nmenu_open = %d\n", (unsigned long long)job.frame,
plat_process_uptime_ns() / 1e9, job.menu_open);
if (job.replay_note[0]) put(&t, "%s", job.replay_note);
put(&t, "\n[place]\n");
if (job.have_area) put(&t, "area = %s\n", job.area);
else put(&t, "area = unknown\n");
if (job.have_pos) {
put(&t, "player_pos = %.4f %.4f %.4f\n", job.pos[0], job.pos[1], job.pos[2]);
char start[64];
float dist = 0;
if (job.have_area && dbg_place_nearest(job.area, job.pos, start, &dist))
put(&t, "nearest_start = %s\nnearest_start_metres = %.1f\n", start, dist);
} else {
put(&t, "player_pos = none\n# no player: the title screen, a loading screen, or a moment without Link\n");
}
if (job.have_rot) {
put(&t, "player_rot =");
for (int i = 0; i < 9; i++) put(&t, " %.5f", job.rot[i]);
// the matrix's third column is the way he faces, as the free camera's yaw counts it
put(&t, "\nplayer_yaw = %.5f\n", atan2(job.rot[2], job.rot[8]));
}
if (job.speed != 1.0f) put(&t, "game_speed = %.3f\n", job.speed);
put_camera(&t);
put(&t, "\n[picture]\nshot = %s\n", shot);
if (g) {
put(&t, "window = %dx%d\ngame_image = %dx%d\nhdr = %d\n", g->w, g->h, g->image_w, g->image_h, g->hdr);
static const char *const scalers[] = {"none", "bilinear", "FSR 1", "bilinear and sharpening"};
put(&t, "scaled_by = %s\n", scalers[g->scaler & 3]);
put(&t, "picture_rect = %.4f %.4f %.4f %.4f\n", g->pic[0], g->pic[1], g->pic[2], g->pic[3]);
}
put(&t, "present_mode = %s\ndisplay_hz = %.1f\n", gfx_window_present_mode(), gfx_window_refresh_hz());
if (gfx_output_fps() > 0) put(&t, "frame_generation_output_fps = %.1f\n", gfx_output_fps());
put(&t, "flight_recorder = %s\n", job.flight ? "flight/ (frames.tsv, events.tsv, thumbnails)" : flight_on ? "on, busy with another dump" : "off");
put_timing(&t);
put(&t, "\n[system]\n");
static char sys[16384];
sysinfo_text(sys, sizeof sys);
char *cut = strstr(sys, "Settings with a value:");
if (cut) *cut = 0;
for (char *line = sys, *end; line && *line; line = end ? end + 1 : NULL) { // "OS: ..." as "os = ..."
if ((end = strchr(line, '\n'))) *end = 0;
char *colon = strstr(line, ": ");
if (!colon) continue;
*colon = 0;
for (char *p = line; *p; p++) *p = *p >= 'A' && *p <= 'Z' ? (char)(*p + 32) : *p;
put(&t, "%s = %s\n", line, colon + 2);
}
put(&t, "\n[settings that differ from the defaults]\n");
Settings s = {open_in("settings.ini", "w"), &t, 0};
if (s.ini)
fprintf(s.ini, "# The settings bug capture %d ran with, as nx2navi.ini lines: every setting that had a value, from the\n"
"# file, the menu or the environment, without the private ones. NX2NAVI_CAPTURE_REPLAY reads it.\n", job.number);
cfg_each_active(setting_cb, &s);
if (s.ini) fclose(s.ini);
if (!s.differ) put(&t, "# none\n");
fclose(f);
}
if (ok) {
write_frames();
write_log_tail();
write_game_data();
char zip[PLAT_PATH_MAX];
save_share_export(job.dir, 0, zip, sizeof zip);
// capture.txt appears last and whole
char part[PLAT_PATH_MAX + 32], done[PLAT_PATH_MAX + 32];
snprintf(part, sizeof part, "%s/capture.txt.part", job.dir);
snprintf(done, sizeof done, "%s/capture.txt", job.dir);
ok = f && plat_file_replace(part, done, 0);
}
vk_present_grab_free(g);
job.grab = NULL;
if (ok) rt_log("capture: %d saved to %s (%s; %s; %.0f ms)", job.number, job.dir, job.why, shot, (plat_now_ns() - job.start_ns) / 1e6);
else rt_log("capture: %d could not be written to %s", job.number, job.dir);
note_number = job.number, note_ok = ok;
snprintf(note_name, sizeof note_name, "%s", job.name);
__atomic_store_n(&note_until, plat_now_ns() + NOTE_NS, __ATOMIC_RELEASE);
__atomic_store_n(&busy, 0, __ATOMIC_RELEASE);
}
int bugcap_note(int *number, int *ok, char name[64]) {
uint64_t until = __atomic_load_n(&note_until, __ATOMIC_ACQUIRE);
if (!until || plat_now_ns() >= until) return 0;
*number = note_number, *ok = note_ok;
snprintf(name, 64, "%s", note_name);
return 1;
}
// ---- the press (render thread)
static volatile int32_t replay_wants; // the replay's own capture, asked for by the game's thread
static char replay_note[400]; // ... with these lines for its capture.txt, written before replay_wants
static void start(uint64_t frame, uint64_t interval_ns, const char *why) {
int32_t idle = 0;
if (!__atomic_compare_exchange_n(&busy, &idle, 1, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) {
rt_log("capture: %s at frame %llu while capture %d is being written: not taken", why, (unsigned long long)frame, job.number);
return;
}
job.start_ns = plat_now_ns();
job.frame = frame;
job.unix_ns = plat_unix_time_ns();
plat_local_time(&job.local);
snprintf(job.why, sizeof job.why, "%s", why);
char base[PLAT_PATH_MAX];
base_dir(base, sizeof base);
int top = 0;
plat_fs_list(base, highest, &top);
job.number = top + 1;
snprintf(job.name, sizeof job.name, "%03d-%04d%02d%02d-%02d%02d%02d", job.number, job.local.tm_year + 1900,
job.local.tm_mon + 1, job.local.tm_mday, job.local.tm_hour, job.local.tm_min, job.local.tm_sec);
snprintf(job.dir, sizeof job.dir, "%s/%s", base, job.name);
// what the game holds now: the writer comes later
job.have_pos = dbg_player_pos(job.pos);
job.have_rot = dbg_player_rot(job.rot);
job.have_area = dbg_area(job.area);
job.speed = dbg_speed_factor();
job.have_cam = vk_dlaa_fg_camera(&job.cam);
job.fc_on = dbg_freecam(&job.fc_sticks, &job.fc_speed, job.fc_pos);
dbg_freecam_angles(&job.fc_yaw, &job.fc_pitch);
job.menu_open = menu_is_open();
perfmon_snapshot(&job.perf);
job.pre_n = ring_n < RING ? (int)ring_n : RING;
for (int i = 0; i < job.pre_n; i++) job.pre[i] = ring[(ring_n - (uint64_t)job.pre_n + (uint64_t)i) % RING];
__atomic_store_n(&job.post_n, 0, __ATOMIC_RELEASE);
job.replay_note[0] = 0;
if (!strncmp(why, "replay", 6)) snprintf(job.replay_note, sizeof job.replay_note, "%s", replay_note);
for (int i = 0; i < 2; i++) {
double p[3], a[3];
float up[3];
job.seen0[i] = dbg_camera_seen(i, p, a, up);
}
dbg_camera_watch(1);
job.grab = NULL;
__atomic_store_n(&job.grab_done, 0, __ATOMIC_RELEASE);
if (!vk_present_grab(grab_cb, NULL)) __atomic_store_n(&job.grab_done, 1, __ATOMIC_RELEASE);
char fdir[PLAT_PATH_MAX + 16];
snprintf(fdir, sizeof fdir, "%s/flight", job.dir);
job.flight = flight_capture(frame, interval_ns, fdir);
rt_log("capture: %d at frame %llu (%s): %s, Link at %.2f %.2f %.2f%s", job.number, (unsigned long long)frame, why,
job.have_area ? job.area : "no area", job.pos[0], job.pos[1], job.pos[2], job.have_pos ? "" : " (no player)");
if (!plat_thread_spawn(writer, NULL, "bug capture", 0)) {
rt_log("capture: cannot start the thread that writes it");
vk_present_grab_cancel();
dbg_camera_watch(0);
__atomic_store_n(&busy, 0, __ATOMIC_RELEASE);
}
}
void bugcap_frame(uint64_t frame, uint64_t now_ns, uint64_t interval_ns, uint64_t replay_ns) {
(void)now_ns;
FrameRec r = {frame, (uint32_t)(interval_ns / 1000), (uint32_t)(replay_ns / 1000)};
ring[ring_n++ % RING] = r;
static int watch_frames;
if (__atomic_load_n(&busy, __ATOMIC_ACQUIRE)) {
int n = job.post_n;
if (n < POST && frame > job.frame) job.post[n] = r, __atomic_store_n(&job.post_n, n + 1, __ATOMIC_RELEASE);
// the game's camera update has had its frames: the patch site goes quiet again
if (watch_frames >= 0 && ++watch_frames > 8) dbg_camera_watch(0), watch_frames = -1;
} else {
if (watch_frames > 0) dbg_camera_watch(0);
watch_frames = 0;
}
static uint64_t at[16];
static int n_at = -1;
if (n_at < 0) { // NX2NAVI_CAPTURE_AT=<frame>[,<frame>...]: captures without a key, for test runs
n_at = 0;
for (const char *p = cfg_get("NX2NAVI_CAPTURE_AT"); p && *p && n_at < 16;) {
char *end;
unsigned long long f = strtoull(p, &end, 10);
if (end == p) break;
at[n_at++] = f;
p = *end == ',' ? end + 1 : end;
}
}
static int key_was;
int key = input_flight_key();
const char *why = key && !key_was ? "F8" : NULL;
key_was = key;
for (int i = 0; i < n_at; i++)
if (at[i] == frame) why = "NX2NAVI_CAPTURE_AT";
if (__atomic_exchange_n(&replay_wants, 0, __ATOMIC_ACQ_REL)) why = "replay";
if (why) start(frame, interval_ns, why);
}
// ---- the replay (the game's thread)
// The value of key in the replayed capture.txt ("key = value" at a line's start); 0 without it.
static int src_get(const char *key, char *out, size_t cap) {
size_t kl = strlen(key);
for (const char *p = rp_src.text; p && *p; p = strchr(p, '\n'), p = p ? p + 1 : NULL) {
if (strncmp(p, key, kl) || strncmp(p + kl, " = ", 3)) continue;
const char *v = p + kl + 3, *e = v;
while (*e && *e != '\n' && *e != '\r') e++;
snprintf(out, cap, "%.*s", (int)(e - v), v);
return 1;
}
return 0;
}
enum { R_NEW, R_WAIT, R_LIST, R_WARP, R_ROUTE, R_ROUTING, R_CAMERA, R_CAMERA_PUT, R_SETTLE, R_DONE };
static struct {
int state, tries, have_pos, have_cam, cam_on, routed, walks, held_seen;
char area[64];
float pos[3], yaw, pitch;
double cam[3];
uint64_t t_ns, tick;
float still_at[3]; // R_ROUTING: where Link was when he last moved, and when
uint64_t still_ns;
} rp;
static volatile int32_t rp_loaded; // Link has appeared: bugcap_replay_pad stops pressing A
static volatile int32_t rp_held; // Link stands still on his walk (a conversation holds him): it presses A again
void bugcap_replay_pad(uint64_t *buttons) {
static uint64_t reads;
if (!bugcap_replay_dir()) return;
reads++;
if (__atomic_load_n(&rp_loaded, __ATOMIC_RELAXED)) {
// a conversation that began where the teleport arrived (the game's own, on a save that had not been there):
// A takes it to its end
if (__atomic_load_n(&rp_held, __ATOMIC_RELAXED) && reads % 60 < 4) *buttons |= 1ull << B_A;
return;
}
// through the title screen and the file menu: A for four reads, every hundred, from the fifth second on
if (reads > 300 && reads % 100 < 4) *buttons |= 1ull << B_A;
}
static void rp_go(int state) { rp.state = state, rp.t_ns = plat_now_ns(); }
static void rp_fail(const char *what) {
rt_log("capture: replay of %s stopped: %s", rp_src.name, what);
rp_go(R_DONE);
}
void bugcap_replay_tick(uint64_t tick) {
if (rp.state == R_DONE || !bugcap_replay_dir()) return;
uint64_t now = plat_now_ns();
double in_state = (double)(now - rp.t_ns) / 1e9;
char text[256], area[64] = "";
float p[3] = {0, 0, 0};
switch (rp.state) {
case R_NEW:
__atomic_store_n(&rp_loaded, 1, __ATOMIC_RELAXED);
if (!rp_src.text[0]) {
rp_fail("its capture.txt cannot be read");
return;
}
if (src_get("area", rp.area, sizeof rp.area) && !strcmp(rp.area, "unknown")) rp.area[0] = 0;
rp.have_pos = src_get("player_pos", text, sizeof text) && sscanf(text, "%f %f %f", &rp.pos[0], &rp.pos[1], &rp.pos[2]) == 3;
rp.have_cam = src_get("camera_pos", text, sizeof text) && sscanf(text, "%lf %lf %lf", &rp.cam[0], &rp.cam[1], &rp.cam[2]) == 3 &&
src_get("camera_yaw", text, sizeof text) && sscanf(text, "%f", &rp.yaw) == 1 &&
src_get("camera_pitch", text, sizeof text) && sscanf(text, "%f", &rp.pitch) == 1;
const char *cam = getenv("NX2NAVI_CAPTURE_REPLAY_CAMERA"); // 0: the game's own camera stays
rp.cam_on = !(cam && !strcmp(cam, "0"));
rt_log("capture: replay of %s: %s, Link at %.2f %.2f %.2f%s, camera %s", rp_src.name, rp.area[0] ? rp.area : "no area",
rp.pos[0], rp.pos[1], rp.pos[2], rp.have_pos ? "" : " (not in the capture)",
!rp.have_cam ? "not in the capture" : rp.cam_on ? "to be placed" : "left to the game");
if (!rp.area[0]) {
rp_fail("the capture names no area (taken at the title screen or while loading): only its settings apply");
return;
}
rp_go(R_WAIT);
break;
case R_WAIT: // the save has just loaded: the game takes no change of area in its first moments
if (in_state < 3) break;
dbg_flags_refresh(), dbg_names(NULL); // the start positions, read with the flag names
rp_go(R_LIST);
break;
case R_LIST:
if (dbg_names(NULL) != 2) {
dbg_flags_refresh();
if (in_state > 60) rp_fail("the game's list of start positions was not read in a minute");
break;
}
if (dbg_area(area) && !strcmp(area, rp.area) && rp.have_pos && dbg_player_pos(p) &&
fabsf(p[0] - rp.pos[0]) + fabsf(p[1] - rp.pos[1]) + fabsf(p[2] - rp.pos[2]) < 60) {
rt_log("capture: replay: the save starts in %s, %.1f %.1f %.1f: no teleport", area, p[0], p[1], p[2]);
rp_go(R_ROUTE);
break;
}
// fall through
case R_WARP:
if (rp.state == R_WARP) {
if (dbg_busy() || in_state < 1) {
if (in_state > 180) rp_fail("the teleport did not end in three minutes");
break;
}
if (dbg_area(area) && !strcmp(area, rp.area)) {
rp_go(R_ROUTE);
break;
}
if (in_state < 4) break; // a refusal (an event still runs after the load): asked again in a moment
dbg_status(text);
if (++rp.tries >= 6) {
rt_log("capture: replay: the game's last word on the teleport: %s", text);
rp_fail("the area could not be reached");
break;
}
}
{
char start[64] = "";
float dist = 0;
if (rp.have_pos) dbg_place_nearest(rp.area, rp.pos, start, &dist);
rt_log("capture: replay: teleport to %s, %s%s", rp.area, start[0] ? start : "its first start position",
rp.tries ? " (again)" : "");
dbg_warp(rp.area, start);
rp_go(R_WARP);
}
break;
case R_ROUTE:
if (in_state < 1) break;
if (rp.have_pos && dbg_player_pos(p) && hypotf(p[0] - rp.pos[0], p[2] - rp.pos[2]) > 0.5f) {
dbg_route_to(rp.pos[0], rp.pos[2], 0.5f);
rp.routed = 1, rp.walks = 1;
memcpy(rp.still_at, p, sizeof rp.still_at), rp.still_ns = now;
rp_go(R_ROUTING);
} else {
rp_go(R_CAMERA);
}
break;
case R_ROUTING:
// Link not moving at all for two seconds is no wall (he would slide along it or sidestep): the game holds him,
// for a conversation or an event. A is pressed until he moves again, and the walk is asked for once more
// should the route have given up meanwhile.
if (dbg_player_pos(p) && fabsf(p[0] - rp.still_at[0]) + fabsf(p[1] - rp.still_at[1]) + fabsf(p[2] - rp.still_at[2]) > 0.05f) {
memcpy(rp.still_at, p, sizeof rp.still_at), rp.still_ns = now;
__atomic_store_n(&rp_held, 0, __ATOMIC_RELAXED);
} else if (now - rp.still_ns > 2000000000ull && !__atomic_load_n(&rp_held, __ATOMIC_RELAXED)) {
__atomic_store_n(&rp_held, 1, __ATOMIC_RELAXED);
if (!rp.held_seen++) rt_log("capture: replay: Link does not move (a conversation or an event holds him): pressing A until he does");
}
if (dbg_route_state() == 1 && in_state < 120) break;
if (dbg_route_state() == 2 && rp.held_seen && rp.walks < 3 && in_state < 120) { // given up while he was held
dbg_route_to(rp.pos[0], rp.pos[2], 0.5f);
rp.walks++;
break;
}
if (dbg_route_state() == 1) dbg_route_stop();
__atomic_store_n(&rp_held, 0, __ATOMIC_RELAXED);
rp_go(R_CAMERA);
break;
case R_CAMERA:
if (in_state < 1) break; // Link has stopped
if (rp.have_cam && rp.cam_on && dbg_freecam_available()) {
dbg_freecam_set(1, 0, 8.0f); // standing: the pad still plays the game
rp.tick = tick;
rp_go(R_CAMERA_PUT);
} else {
rp.cam_on = 0;
rp_go(R_SETTLE);
}
break;
case R_CAMERA_PUT:
if (tick < rp.tick + 3) break; // its first update took the game's view: now the captured one
dbg_freecam_place(rp.cam, rp.yaw, rp.pitch);
rp_go(R_SETTLE);
break;
case R_SETTLE: {
if (in_state < 3) break; // the picture's history and the area's detail settle
int have = dbg_player_pos(p);
float off = have && rp.have_pos ? sqrtf((p[0] - rp.pos[0]) * (p[0] - rp.pos[0]) + (p[1] - rp.pos[1]) * (p[1] - rp.pos[1]) +
(p[2] - rp.pos[2]) * (p[2] - rp.pos[2])) : -1;
dbg_area(area);
snprintf(replay_note, sizeof replay_note,
"replay_of = %s\nreplay_area = %s\nreplay_player_off_metres = %.2f\nreplay_walk = %s\nreplay_camera = %s\n",
rp_src.name, !strcmp(area, rp.area) ? "the capture's" : "another", off,
!rp.routed ? "none needed" : dbg_route_state() == 2 ? "given up: something was in the way" : "arrived",
rp.cam_on ? "the free camera at the captured camera" : "the game's own");
rt_log("capture: replay of %s ready: %s, Link at %.2f %.2f %.2f, %.2f m from the captured place (%s); camera: %s",
rp_src.name, area, p[0], p[1], p[2], off,
!rp.routed ? "no walk needed" : dbg_route_state() == 2 ? "the walk was given up" : "walked there",
rp.cam_on ? "the free camera at the captured camera" : "the game's own");
__atomic_store_n(&replay_wants, 1, __ATOMIC_RELEASE);
rp_go(R_DONE);
break;
}
}
}

31
runtime/bugcap.h Normal file
View File

@@ -0,0 +1,31 @@
// Bug captures (bugcap.c): F8 writes what is needed to find a bug again where the player saw it, as one folder under
// the log folder, and NX2NAVI_CAPTURE_REPLAY starts a run at a capture's place with its camera and its settings.
// docs/bug-capture.md has the folder's files and the steps.
#pragma once
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
// perf_present, every present on the render thread: one record into the ring of frame times, and the triggers (F8 while
// the game window is in front, NX2NAVI_CAPTURE_AT=<frame>[,<frame>...], a replay's own capture).
void bugcap_frame(uint64_t frame, uint64_t now_ns, uint64_t interval_ns, uint64_t replay_ns);
// The note on screen after a capture (ui/menu.cpp, the present path): 1 while it shows, with the capture's number,
// whether it was written, and its folder's name ("003-20261113-141502").
int bugcap_note(int *number, int *ok, char name[64]);
// A replay (NX2NAVI_CAPTURE_REPLAY=<a capture's folder>). bugcap_replay_dir: the folder, or NULL without one; cfg.c
// reads the capture's settings.ini in place of nx2navi.ini then and writes neither. The game's thread at its pad read
// (debug_tools.c): bugcap_replay_pad presses A until the save is loaded, bugcap_replay_tick then teleports to the
// capture's area, walks Link to where he stood, puts the free camera where the camera was and takes a capture of its
// own for the comparison.
const char *bugcap_replay_dir(void);
void bugcap_replay_pad(uint64_t *buttons);
void bugcap_replay_tick(uint64_t tick);
#ifdef __cplusplus
}
#endif

View File

@@ -11,6 +11,7 @@
#include <stdlib.h>
#include <string.h>
#include "bugcap.h"
#include "cfg.h"
#include "cfg_private.h"
#include "discord_app.h"
@@ -36,6 +37,7 @@ static const char *const known[] = {
"CORES", "TM_DISPATCH", "NVN2_CS_TABLE", "SKIP_SHADERS", "MOVIE_DEBAND", "MOVIE_FPS", "MOVIE_SKIP", "MOVIE_OVERLAY", "MOVIES", "NPLN", "NVN2_PROGRAMS", "NVN_TRAP", "OCARINA_REALTIME", "ONESHOT_BUDGET", "ONESHOT_WAIT_MS", "OCARINA_STEP", "PHYSICS_STEPS", "PICKUP_COUNT", "STEP_STEADY", "VI_HZ", "VI_VRR", "TIME_DUMP", "SHADER_DUMP", "SHOT_AFTER", "SHOT_DIR", "SHOT_EVERY", // Switch 2 port: movie skip (romfs.c), NVN2 proc traps (nvn_procs.c)
"AA", "AA_LOG", "AB", "AMIIBO_DIR", "ANISO", "APP_POOL", "ASPECT", "ASPECT_PATCH", "ASSUME_FOCUS", "ASTC", "ASTC_BC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_CHANNELS", "AUDIO_DEVICE", "AUDIO_GAME_PRIO", "AUDIO_OFF", "AUDIO_PREFILL_MS", "AUDIO_STATS",
"BARRIER_GAME", "MESH_AHEAD", "MESH_FALLBACK", "MESH_FALLBACK_MB", "MESH_FALLBACK_WORKERS", "PROBE_MESHFB_DIR",
"CAPTURE_AT", "CAPTURE_DIR", "CAPTURE_REPLAY", "CAPTURE_REPLAY_CAMERA", // bug captures and their replays (bugcap.c)
"BACKGROUND_WINDOW", "BIND_A", "BIND_B", "BIND_DOWN", "BIND_L", "BIND_LCLICK", "BIND_LEFT", "BIND_LSTICK_DOWN", "BIND_LSTICK_LEFT",
"BIND_LSTICK_RIGHT", "BIND_LSTICK_UP", "BIND_MINUS",
"BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_RSTICK_DOWN", "BIND_RSTICK_LEFT", "BIND_RSTICK_RIGHT", "BIND_RSTICK_UP",
@@ -1078,7 +1080,10 @@ static int find_ini(void) {
return 1;
}
// A replay of a bug capture (bugcap.c) runs on the capture's settings and leaves the player's nx2navi.ini as it is:
// nothing is saved, whatever the run sets.
int cfg_save(void) {
if (bugcap_replay_dir()) return 1;
if (find_ini()) return cfg_save_to(ini_path);
__atomic_store_n(&save_ok, 0, __ATOMIC_RELEASE);
return 0;
@@ -1088,7 +1093,7 @@ int cfg_save(void) {
// about 900 characters, and then the keys that are no settings of this version, which do nothing. A report's log then
// shows which settings its run had and which of the file's lines had no effect; before, it held only the count of
// keys, and a player who had added a line this version does not read could take it for the cause of what changed.
static void log_file_settings(void) {
static void log_file_settings(const char *file) {
char line[1024];
size_t k = 0;
for (int i = 0; i < n_entries; i++) {
@@ -1101,26 +1106,40 @@ static void log_file_settings(void) {
size_t vl = strlen(value);
if (vl > 200) vl = 200; // a long value (a list of mods) is cut: the line shows that the key is set
if (k && k + strlen(key) + vl + 5 > 900) {
rt_log("cfg: nx2navi.ini sets: %s", line);
rt_log("cfg: %s sets: %s", file, line);
k = 0;
}
k += (size_t)snprintf(line + k, sizeof line - k, "%s%s = %.*s", k ? ", " : "", key, (int)vl, value);
}
if (k) rt_log("cfg: nx2navi.ini sets: %s", line);
if (k) rt_log("cfg: %s sets: %s", file, line);
if (n_unknown)
rt_log("cfg: nx2navi.ini has %d key%s that %s no setting of this version and %s nothing: %s%s", n_unknown,
rt_log("cfg: %s has %d key%s that %s no setting of this version and %s nothing: %s%s", file, n_unknown,
n_unknown == 1 ? "" : "s", n_unknown == 1 ? "is" : "are", n_unknown == 1 ? "does" : "do", unknown_keys,
unknown_cut ? ", ..." : "");
}
static void load_ini(void) {
// NX2NAVI_CAPTURE_REPLAY=<a bug capture's folder>: the settings that capture was taken with (its settings.ini) stand
// in for nx2navi.ini, which is neither read nor written in such a run; the environment still wins over them
const char *replay = bugcap_replay_dir();
if (replay) {
char path[1100];
snprintf(path, sizeof path, "%s/settings.ini", replay);
int ok = cfg_load(path);
rt_log(ok ? "cfg: replay of the bug capture in %s: its settings.ini (%d keys) in place of nx2navi.ini, which this run does not write"
: "cfg: replay of the bug capture in %s: no settings.ini there, so every setting has its default (%d keys); "
"nx2navi.ini is not read or written",
replay, n_entries);
if (ok) log_file_settings("the capture's settings.ini");
return;
}
if (!find_ini()) return;
if (!cfg_load(ini_path)) {
rt_log("cfg: no settings file at %s", ini_path);
return;
}
rt_log("cfg: read %s: %d keys", ini_path, n_entries);
log_file_settings();
log_file_settings("nx2navi.ini");
for (int i = 0; i < n_entries; i++) {
char var[128];
snprintf(var, sizeof var, PREFIX "%s", entries[i].key);

View File

@@ -39,6 +39,7 @@
#include <string.h>
#include <zstd.h>
#include "bugcap.h"
#include "cfg.h"
#include "cpu.h"
#include "debug_tools.h"
@@ -76,6 +77,15 @@ int dbg_player_pos(float xyz[3]) {
return a && rd(a + 0x31c, xyz, 12) && isfinite(xyz[0]) && isfinite(xyz[1]) && isfinite(xyz[2]);
}
// The actor's rotation beside its position: nine floats, a 3x3 matrix by rows (bugcap.c writes them as they are).
int dbg_player_rot(float m[9]) {
uint64_t a = dbg_supported() ? player() : 0;
if (!a || !rd(a + 0x328, m, 36)) return 0;
for (int i = 0; i < 9; i++)
if (!isfinite(m[i])) return 0;
return 1;
}
static float speed_factor = 1.0f;
float dbg_speed_factor(void) { return speed_factor; }
void dbg_speed_set(float factor) { speed_factor = factor >= 0.05f && factor <= 8.0f ? factor : 1.0f; }
@@ -182,16 +192,24 @@ static int flags_list(void) {
return 1;
}
// Under flags_lock: the menu's thread, the game's thread (test_script, warp_tick) and a bug capture's writer
// (bugcap.c) all ask, and the list is made by whichever asks first.
static PlatMutex flags_lock = PLAT_MUTEX_INIT;
int dbg_flags_refresh(void) {
if (!dbg_supported() || !flags_list()) return 0;
if (!dbg_supported()) return 0;
plat_mutex_lock(&flags_lock);
if (!flags_list()) {
plat_mutex_unlock(&flags_lock);
return 0;
}
uint64_t m = gmd(), entries = m ? rd_ptr(m + 0x18) : 0;
uint32_t count = 0;
if (!entries || !rd(m + 0x10, &count, 4) || !count || count > 200000) return flag_n;
uint8_t *raw = malloc((size_t)count * 0x18);
uint8_t *raw = entries && rd(m + 0x10, &count, 4) && count && count <= 200000 ? malloc((size_t)count * 0x18) : NULL;
if (raw && rd(entries, raw, (size_t)count * 0x18))
for (int i = 0; i < flag_n; i++)
if (flag_pairs[i].index < count) flag_value[i] = raw[(size_t)flag_pairs[i].index * 0x18 + 0x16] & 1;
free(raw);
plat_mutex_unlock(&flags_lock);
return flag_n;
}
@@ -458,6 +476,23 @@ static const char *place_after(const char *area, const char *pos) {
return first;
}
// The start position of area nearest to xyz among those the game's file gives coordinates for (a bug capture names
// it, and a replay of the capture arrives there, bugcap.c). 0 while the list is not read or the area has none.
int dbg_place_nearest(const char *area, const float xyz[3], char name[64], float *dist) {
int n = dbg_places(), best = -1;
float best_d = 0;
for (int i = 0; i < n; i++) {
if (strcmp(places[i].area, area) || !places[i].has_xyz) continue;
float dx = places[i].xyz[0] - xyz[0], dy = places[i].xyz[1] - xyz[1], dz = places[i].xyz[2] - xyz[2];
float d = sqrtf(dx * dx + dy * dy + dz * dz);
if (best < 0 || d < best_d) best = i, best_d = d;
}
if (best < 0) return 0;
snprintf(name, 64, "%s", places[best].pos);
if (dist) *dist = best_d;
return 1;
}
static int place_listed(const char *area, const char *pos) {
int n = dbg_places();
for (int i = 0; i < n; i++)
@@ -494,6 +529,28 @@ static int text_get(const char *name, char out[64]) {
return 1;
}
// Every 64-character text of the game data with its name's hash (a bug capture lists them, bugcap.c): the area, the
// reserved next area and start position among them. Returns how many it visited.
int dbg_texts(void (*cb)(uint32_t hash, const char *text, void *ctx), void *ctx) {
uint64_t m = dbg_supported() ? gmd() : 0, sec = m + (uint64_t)GD_TEXT64 * 0x60;
uint64_t table = m ? rd_ptr(sec + 0x20) : 0, entries = m ? rd_ptr(sec + 0x18) : 0;
uint32_t count = 0, size = 0;
if (!table || !entries || !rd(sec + 0x10, &count, 4) || !rd(sec + 0x2c, &size, 4) || !size || size > 100000) return 0;
int n = 0;
for (uint32_t i = 0; i < size; i++) {
Pair pr;
char text[64];
if (!rd(table + (uint64_t)i * 8, &pr, 8) || !pr.hash || pr.index >= count) continue;
uint64_t tp = rd_ptr(entries + (uint64_t)pr.index * 0x108 + 0x68);
if (!tp || !rd(tp, text, 63)) continue;
text[63] = 0;
cb(pr.hash, text, ctx);
n++;
}
return n;
}
uint32_t dbg_name_hash(const char *name) { return hash_of(name); }
// A text written into the entry's own buffers (game thread). 0: the game has no such text.
int dbg_area(char out[64]) { return dbg_supported() && text_get("Sequence_CurrentBanc", out) && out[0]; }
@@ -777,6 +834,13 @@ static struct {
} fc = {.sticks = 1, .speed = 8.0f, .reach = 5.0};
static PlatMutex ground_lock = PLAT_MUTEX_INIT;
// The game's own camera as its update chose it, before the free camera stands in: kept per scene camera (0 the one
// that follows Link, 1 the one events direct) while a bug capture watches (dbg_camera_watch) or the free camera is on,
// which is when the patch site calls dbg_freecam_host at all.
static struct { double pos[3], at[3]; float up[3]; uint64_t n; } cam_seen[2];
static PlatMutex cam_lock = PLAT_MUTEX_INIT;
static volatile int32_t cam_watch; // how many watch it: a bug capture, and Link's walk to a captured place
int dbg_freecam_flying(void) { return fc.on && fc.sticks && !fc.capture && fc.avoid; }
void dbg_freecam_avoid_set(int on) {
if ((on != 0) != fc.avoid) rt_log("debug: free camera ground avoidance %s", on ? "on" : "off");
@@ -845,18 +909,31 @@ static void set_s(Cpu *c, int r, float v) {
// The update runs for each of the game's cameras, every frame: the one that follows Link and the one its events
// direct are the scene's, and the free camera stands in for both; the camera of the interface's 3D models and the
// one the sound follows stay the game's. A camera's state (x19) has its actor at +0x10, the actor its name at +0x20.
// 1 the camera that follows Link, 2 the events' camera, 0 another.
static int scene_camera(uint64_t state) {
char name[16] = "";
uint64_t actor = rd_ptr(state + 0x10), np = actor ? rd_ptr(actor + 0x20) : 0;
if (!np || !rd(np, name, 13)) return 0;
return !memcmp(name, "PlayerCamera", 13) || !memcmp(name, "EventCamera", 12);
return !memcmp(name, "PlayerCamera", 13) ? 1 : !memcmp(name, "EventCamera", 12) ? 2 : 0;
}
// The patch site's host function, on the patch page at +0xf70. patches.c registers it: that file is compiled with
// the game version's patches.h, which has the page's address.
void dbg_freecam_host(Cpu *c) {
fc.updates++;
if (fc.on && scene_camera(c->x[19])) {
int scene = scene_camera(c->x[19]);
if (scene) { // what the game chose, for a bug capture (dbg_camera_seen)
static const int up_reg[3] = {7, 16, 6};
plat_mutex_lock(&cam_lock);
for (int i = 0; i < 3; i++) cam_seen[scene - 1].pos[i] = reg_d(c, i), cam_seen[scene - 1].at[i] = reg_d(c, 3 + i);
for (int i = 0; i < 3; i++) {
uint32_t b = (uint32_t)c->v[up_reg[i]];
memcpy(&cam_seen[scene - 1].up[i], &b, 4);
}
cam_seen[scene - 1].n++;
plat_mutex_unlock(&cam_lock);
}
if (fc.on && scene) {
if (fc.capture) { // start where the game's camera is, looking where it looks
double d[3] = {reg_d(c, 3) - reg_d(c, 0), reg_d(c, 4) - reg_d(c, 1), reg_d(c, 5) - reg_d(c, 2)};
double len = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
@@ -878,6 +955,35 @@ void dbg_freecam_host(Cpu *c) {
int dbg_freecam_available(void) { return dbg_supported() && rt_patch_set("freecam") >= 0; }
// The patch site calls dbg_freecam_host while the free camera is on or a bug capture watches the game's camera.
static void cam_patch_sync(void) { rt_patch_switch(rt_patch_set("freecam"), fc.on || cam_watch); }
void dbg_camera_watch(int on) {
if (!dbg_freecam_available()) return;
if (__atomic_add_fetch(&cam_watch, on ? 1 : -1, __ATOMIC_ACQ_REL) < 0) __atomic_store_n(&cam_watch, 0, __ATOMIC_RELEASE);
cam_patch_sync();
}
uint64_t dbg_camera_seen(int which, double pos[3], double at[3], float up[3]) {
if (which < 0 || which > 1) return 0;
plat_mutex_lock(&cam_lock);
memcpy(pos, cam_seen[which].pos, sizeof cam_seen[which].pos);
memcpy(at, cam_seen[which].at, sizeof cam_seen[which].at);
memcpy(up, cam_seen[which].up, sizeof cam_seen[which].up);
uint64_t n = cam_seen[which].n;
plat_mutex_unlock(&cam_lock);
return n;
}
// The game's thread: the free camera, which must be on, at a place and direction given outright (a replay of a bug
// capture, bugcap.c), instead of where the game's camera is.
void dbg_freecam_place(const double pos[3], float yaw, float pitch) {
memcpy(fc.pos, pos, sizeof fc.pos);
fc.yaw = yaw, fc.pitch = pitch > 1.5f ? 1.5f : pitch < -1.5f ? -1.5f : pitch;
fc.reach = 5.0;
fc.capture = 0;
}
void dbg_freecam_set(int on, int sticks, float speed) {
if (!dbg_freecam_available()) return;
fc.sticks = sticks != 0;
@@ -885,7 +991,7 @@ void dbg_freecam_set(int on, int sticks, float speed) {
if (on && !fc.on) fc.capture = 1;
if ((on != 0) != fc.on) rt_log("debug: free camera %s", on ? "on" : "off"); // what a tester changed, for the log
fc.on = on != 0;
rt_patch_switch(rt_patch_set("freecam"), on != 0);
cam_patch_sync();
}
void dbg_freecam_reset(void) { fc.capture = 1; } // back to the game's view, and free from there
@@ -896,6 +1002,7 @@ int dbg_freecam(int *sticks, float *speed, double pos[3]) {
if (pos) memcpy(pos, fc.pos, sizeof fc.pos);
return fc.on;
}
void dbg_freecam_angles(float *yaw, float *pitch) { *yaw = fc.yaw, *pitch = fc.pitch; }
// Whether s holds the len characters at part, in any case.
static int contains_nocase(const char *s, const char *part, size_t len) {
@@ -912,12 +1019,20 @@ static int contains_nocase(const char *s, const char *part, size_t len) {
// he moves towards the next point (the game's camera follows behind him, so a stick to the side turns him), with an
// integral that takes out the camera's own angle; a point counts as reached within ROUTE_NEAR metres. When he gains
// less than a metre on it in 2.5 seconds he is stuck (a wall, a fence, a steep slope): he sidesteps for two seconds,
// three times to one side and then to the other, and after ROUTE_STUCK such tries the route ends.
// three times to one side and then to the other, and after ROUTE_STUCK such tries the route ends. A route asked for
// with a smaller distance (dbg_route_to, a replay of a bug capture) walks the last three metres, so that Link stops on
// the point instead of running rings round it, and is steered by the game's own camera (dbg_camera_seen): the stick
// moves Link along the camera's view and across it, so the stick's angle is the angle between the view and the way to
// the point, with nothing to estimate. In a room that matters: the estimate starts with a run straight ahead, which
// in Link's house put him on the furniture beside the door, three metres from the point, for good.
#define ROUTE_MAX 16
#define ROUTE_NEAR 4.0
#define ROUTE_STUCK 10
static struct {
volatile int on;
volatile int on, gave_up;
int by_camera; // steered by the game's camera, which is watched meanwhile (dbg_route_to)
uint64_t cam_n, cam_ns; // the camera updates seen at the last look, and when their number last grew
float within; // metres: a point counts as reached within them
int n, at, have_last, have_heading, side, stuck;
float pt[ROUTE_MAX][2]; // x, z in metres
char name[ROUTE_MAX][48];
@@ -926,9 +1041,18 @@ static struct {
uint64_t prev_ns, prog_ns, side_until;
} route;
static void route_start(void) {
static void route_end(void) {
route.on = 0;
if (route.by_camera) dbg_camera_watch(0);
route.by_camera = 0;
}
static void route_start(float within) {
route.within = within, route.gave_up = 0;
route.at = 0, route.have_last = route.have_heading = 0, route.stuck = 0, route.side = 1, route.integ = 0;
route.best = 1e9f, route.prog_ns = plat_now_ns(), route.side_until = 0, route.prev_ns = 0;
if (route.by_camera) dbg_camera_watch(0); // of a walk that this route replaces
route.by_camera = 0;
route.on = route.n > 0;
if (route.on) rt_log("debug: route of %d points, first %s at %.1f %.1f", route.n, route.name[0], route.pt[0][0], route.pt[0][1]);
}
@@ -943,10 +1067,10 @@ static void route_pad(int32_t *lx, int32_t *ly) {
route.prev_ns = now;
if (dt > 0.1) dt = 0.1;
double dx = route.pt[route.at][0] - p[0], dz = route.pt[route.at][1] - p[2], d = sqrt(dx * dx + dz * dz);
if (d < ROUTE_NEAR) {
if (d < route.within) {
rt_log("debug: route: reached %s (%d of %d) at %.1f %.1f %.1f", route.name[route.at], route.at + 1, route.n, p[0], p[1], p[2]);
if (++route.at == route.n) {
route.on = 0;
route_end();
rt_log("debug: route done");
return;
}
@@ -964,11 +1088,21 @@ static void route_pad(int32_t *lx, int32_t *ly) {
route.integ += err * dt * 0.4;
route.integ = route.integ > 1.0 ? 1.0 : route.integ < -1.0 ? -1.0 : route.integ;
double a = -(1.2 * err + route.integ); // the stick's angle from straight ahead, right positive
if (route.by_camera) {
double cp[3], ct[3];
float up[3];
uint64_t seen = dbg_camera_seen(0, cp, ct, up);
if (seen != route.cam_n) route.cam_n = seen, route.cam_ns = now;
double fx = ct[0] - cp[0], fz = ct[2] - cp[2], fl = sqrt(fx * fx + fz * fz);
// the view, level: ahead (fx, fz), right (-fz, fx), as the free camera's frame below has them
if (route.cam_ns && now - route.cam_ns < 250000000ull && fl > 1e-6 && d > 1e-6)
a = atan2((-dx * fz + dz * fx) / fl, (dx * fx + dz * fz) / fl);
}
a = a > 1.4 ? 1.4 : a < -1.4 ? -1.4 : a;
if (d < route.best - 1.0f) route.best = (float)d, route.prog_ns = now;
if (d < route.best - (route.within < ROUTE_NEAR ? 0.25f : 1.0f)) route.best = (float)d, route.prog_ns = now;
else if (now - route.prog_ns > 2500000000ull && now >= route.side_until) {
if (++route.stuck > ROUTE_STUCK) {
route.on = 0;
route_end(), route.gave_up = 1;
rt_log("debug: route given up before %s: stuck %d times at %.1f %.1f %.1f", route.name[route.at], ROUTE_STUCK, p[0], p[1], p[2]);
return;
}
@@ -980,15 +1114,30 @@ static void route_pad(int32_t *lx, int32_t *ly) {
route.name[route.at], route.side > 0 ? "right" : "left");
}
if (now < route.side_until) a = route.side * 1.5;
*lx = (int32_t)(sin(a) * 30000), *ly = (int32_t)(cos(a) * 30000);
double tilt = route.within < ROUTE_NEAR && d < 3.0 && now >= route.side_until ? (d / 3.0 < 0.4 ? 0.4 : d / 3.0) : 1.0;
*lx = (int32_t)(sin(a) * 30000 * tilt), *ly = (int32_t)(cos(a) * 30000 * tilt);
}
// The game's thread: Link runs to one point of the area, reached within near_m metres. dbg_route_state: 1 on his way,
// 0 there (or no route), 2 given up (stuck).
void dbg_route_to(float x, float z, float near_m) {
route.n = 1;
route.pt[0][0] = x, route.pt[0][1] = z;
snprintf(route.name[0], sizeof route.name[0], "the captured place");
route_start(near_m > 0.3f && near_m < ROUTE_NEAR ? near_m : (float)ROUTE_NEAR);
route.by_camera = 1, route.cam_n = 0, route.cam_ns = 0;
dbg_camera_watch(1);
}
int dbg_route_state(void) { return route.on ? 1 : route.gave_up ? 2 : 0; }
void dbg_route_stop(void) { route_end(); }
// The game's thread, with the pad's state before the game gets it: while the free camera has the sticks, the left one
// moves it where it looks and sideways, the right one turns it, ZR and ZL raise and lower it, R makes it four times as
// fast and L four times as slow, and the game is told that none of those is touched, so Link stays where he is.
// Nothing stops it: it goes through walls, objects and the ground, below which the picture shows the void under the
// map. Ground avoidance (the menu's switch, off unless asked for) keeps it a metre above ground-like surfaces instead.
void dbg_pad(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry) {
bugcap_replay_pad(buttons); // a replay of a bug capture presses A until the save is loaded
route_pad(lx, ly);
if (!fc.on || !fc.sticks || fc.capture) {
fc.last_ns = 0;
@@ -1085,7 +1234,7 @@ static void test_script(uint64_t tick) {
snprintf(route.name[route.n], sizeof route.name[0], "point %d", route.n + 1);
route.n++, q += used;
}
route_start();
route_start((float)ROUTE_NEAR);
} else if (!strncmp(colon + 1, "routeto ", 8)) {
// routeto <part of a start position's name>[/<another part>] ...: the area's own start positions, in order
char area[64] = "", item[128];
@@ -1113,7 +1262,7 @@ static void test_script(uint64_t tick) {
snprintf(route.name[route.n], sizeof route.name[0], "%s", places[found].pos);
route.n++;
}
route_start();
route_start((float)ROUTE_NEAR);
} else if (!strncmp(colon + 1, "warp ", 5)) {
char area[64] = "", pos[64] = "";
if (sscanf(colon + 6, "%63[^ ;] %63[^ ;]", area, pos) >= 1) dbg_warp(area, pos);
@@ -1169,6 +1318,7 @@ void dbg_tick(Cpu *c) {
if (!dbg_supported() || (!tick && !player())) return;
tick++;
test_script(tick);
bugcap_replay_tick(tick); // a replay of a bug capture: the teleport, the walk and the camera (bugcap.c)
warp_tick(c, tick);
static Req todo[Q_MAX];
int n;

View File

@@ -16,7 +16,11 @@ extern "C" {
int dbg_supported(void); // this game build's structures are known (Ocarina of Time 1.1.1)
int dbg_player_pos(float xyz[3]); // Link's position in metres; 0 while there is no player
int dbg_player_rot(float m[9]); // Link's rotation, a 3x3 matrix by rows; 0 while there is no player
int dbg_area(char out[64]); // the area the game is in, by its name in the game's files; 0 unknown
// Every 64-character text of the game data (the area among them) with the hash of its name; returns their number.
int dbg_texts(void (*cb)(uint32_t hash, const char *text, void *ctx), void *ctx);
uint32_t dbg_name_hash(const char *name); // the hash the game knows a flag or a text by
float dbg_speed_factor(void); // the game's speed: 1 normal, 0.05 to 8 (frame_rate.c multiplies the game's step)
void dbg_speed_set(float factor);
@@ -37,6 +41,8 @@ int dbg_places(void);
const char *dbg_place_area(int i);
const char *dbg_place_pos(int i); // never "": a teleport without a listed position takes the area's first
void dbg_warp(const char *area, const char *pos);
// The start position of area nearest to xyz (metres) among those with coordinates: its name and distance; 0 none.
int dbg_place_nearest(const char *area, const float xyz[3], char name[64], float *dist);
int dbg_events(void);
const char *dbg_event_name(int i);
void dbg_event_start(const char *name);
@@ -49,6 +55,19 @@ int dbg_freecam_available(void); // the build has the camera's patch set
void dbg_freecam_set(int on, int sticks, float speed);
void dbg_freecam_reset(void); // back to the game's view, free again from there
int dbg_freecam(int *sticks, float *speed, double pos[3]); // on or off
void dbg_freecam_angles(float *yaw, float *pitch); // radians: it looks along (cos p sin y, sin p, cos p cos y)
// The game's thread: the free camera, which is on, put at a place and direction outright.
void dbg_freecam_place(const double pos[3], float yaw, float pitch);
// The game's own camera, before the free camera stands in for it: dbg_camera_watch(1) has the game's camera update
// report it (it does anyway while the free camera is on), dbg_camera_seen gives the last position, target and up vector
// of the camera that follows Link (which 0) or of the events' camera (1) and how many updates were seen so far.
void dbg_camera_watch(int on);
uint64_t dbg_camera_seen(int which, double pos[3], double at[3], float up[3]);
// The game's thread: Link runs to a point of the area (x, z in metres), reached within near_m. dbg_route_state: 1 on
// his way, 0 there or no route, 2 given up.
void dbg_route_to(float x, float z, float near_m);
int dbg_route_state(void);
void dbg_route_stop(void); // the game's thread: the route ends where Link is
int dbg_freecam_flying(void); // on, with the sticks and ground avoidance: vk_dlaa.c reads the ground's distances back
void dbg_freecam_avoid_set(int on); // ground avoidance (off by default): the camera stays a metre above ground-like surfaces
int dbg_freecam_avoid(void);

View File

@@ -1,7 +1,8 @@
// NX2NAVI_FLIGHT=1 flight recorder: a ring of the last NX2NAVI_FLIGHT_FRAMES (600) presents, one record each (interval,
// render-thread blocked time per perf kind, event counts, the game's time step) and a 640x360 thumbnail each (gfx_present.c, blitted on the
// GPU by the present thread). A dump goes to <dir>/<YYYYMMDD-HHMMSS>-f<frame>/: events.tsv (the texture events of its
// frames, flight_tex), f<frame>.png per thumbnail and frames.tsv, written in that order by a background thread. Triggers: F8 while the game window has focus, a frame interval over
// frames, flight_tex), f<frame>.png per thumbnail and frames.tsv, written in that order by a background thread. Triggers: a bug
// capture (F8 while the game window has focus, bugcap.c: its dump goes into the capture's own folder, as flight/), a frame interval over
// NX2NAVI_FLIGHT_SPIKE_MS (100; 0 off; at most one dump per 10 s), NX2NAVI_FLIGHT_AT=<frame>[,<frame>...] and
// NX2NAVI_FLIGHT_EVERY=<n> (every n-th frame: with n under the ring's length the dumps of a run hold every frame of it
// but the last n). A dump holds the frames up to FLIGHT_POST presents after the trigger, so the aftermath is in it
@@ -68,6 +69,7 @@ static uint64_t recorded; // records written so far
static uint64_t spike_ns, t0_ns;
static uint64_t dump_at, trig_frame, trig_interval_us, last_spike_ns;
static const char *trig_why;
static char trig_dir[PLAT_PATH_MAX]; // the pending dump's folder when its trigger names one (flight_capture), else ""
static uint64_t at_frames[16], every;
static int n_at;
static char base_dir[PLAT_PATH_MAX];
@@ -110,7 +112,7 @@ void flight_init(void) {
if (thumbs_on) vk_thumbs_enable(ring_n);
if (!(tex_ring = calloc(TEX_RING, sizeof *tex_ring))) rt_log("flight: no memory for the texture events, none kept");
flight_on = 1;
rt_log("flight: on: last %d frames, %s; dump on F8, on a frame over %llu ms (one per 10 s)%s, to %s", ring_n,
rt_log("flight: on: last %d frames, %s; dump with a bug capture (F8, into the capture's folder), on a frame over %llu ms (one per 10 s)%s, to %s", ring_n,
thumbs_on ? "thumbnails 640x360" : "no thumbnails", (unsigned long long)(spike_ns / 1000000),
spike_ns ? "" : " (spike trigger off)", base_dir);
if (thumbs_on)
@@ -311,10 +313,19 @@ static uint8_t paeth(int a, int b, int c) {
return (uint8_t)(pa <= pb && pa <= pc ? a : pb <= pc ? b : c);
}
typedef struct { uint8_t *raw, *z; int32_t *head; } PngBufs;
typedef struct { uint8_t *raw, *z; int32_t *head; } PngBufs; // for a w x h picture: (1 + 3w)h bytes, 9/8 of that + 64, 1 << HBITS entries
static int write_png(const char *path, const uint8_t *rgba, PngBufs *pb) {
const uint32_t w = FLIGHT_THUMB_W, h = FLIGHT_THUMB_H, row = 1 + 3 * w;
static void crc_init(void) {
if (crc_table[1]) return;
for (uint32_t i = 0; i < 256; i++) {
uint32_t c = i;
for (int k = 0; k < 8; k++) c = c & 1 ? 0xEDB88320u ^ (c >> 1) : c >> 1;
crc_table[i] = c;
}
}
static int write_png(const char *path, const uint8_t *rgba, uint32_t w, uint32_t h, PngBufs *pb) {
const uint32_t row = 1 + 3 * w;
for (uint32_t y = 0; y < h; y++) {
uint8_t *o = pb->raw + (size_t)y * row;
o[0] = 4; // Paeth
@@ -328,6 +339,7 @@ static int write_png(const char *path, const uint8_t *rgba, PngBufs *pb) {
}
}
size_t zn = deflate_fixed(pb->raw, (size_t)row * h, pb->z, pb->head);
if (zn > UINT32_MAX) return 0; // one IDAT chunk
FILE *f = fopen(path, "wb");
if (!f) return 0;
static const uint8_t sig[8] = {0x89, 'P', 'N', 'G', 13, 10, 26, 10};
@@ -339,6 +351,17 @@ static int write_png(const char *path, const uint8_t *rgba, PngBufs *pb) {
return fclose(f) == 0;
}
// A picture of any size as a compressed PNG, with buffers of its own (a bug capture's frame, bugcap.c; any thread, with
// the recorder on or off). 0 when memory runs out or the file cannot be written.
int flight_write_png(const char *path, const uint8_t *rgba, uint32_t w, uint32_t h) {
size_t raw_n = (size_t)(1 + 3 * (size_t)w) * h;
PngBufs pb = {malloc(raw_n), malloc(raw_n * 9 / 8 + 64), malloc(sizeof(int32_t) << HBITS)};
crc_init();
int ok = w && h && raw_n < INT32_MAX && pb.raw && pb.z && pb.head && write_png(path, rgba, w, h, &pb);
free(pb.raw), free(pb.z), free(pb.head);
return ok;
}
// ---------------------------------------------------------------- dump thread
static void dump_main(void *arg) {
DumpJob *j = arg;
@@ -354,12 +377,7 @@ static void dump_main(void *arg) {
uint8_t *have = calloc((size_t)j->n, 1);
int n_thumbs = 0;
if (thumbs_on && have) {
if (!crc_table[1])
for (uint32_t i = 0; i < 256; i++) {
uint32_t c = i;
for (int k = 0; k < 8; k++) c = c & 1 ? 0xEDB88320u ^ (c >> 1) : c >> 1;
crc_table[i] = c;
}
crc_init();
size_t raw_n = (size_t)(1 + 3 * FLIGHT_THUMB_W) * FLIGHT_THUMB_H;
PngBufs pb = {malloc(raw_n), malloc(raw_n * 9 / 8 + 64), malloc(sizeof(int32_t) << HBITS)};
uint8_t *px = malloc((size_t)FLIGHT_THUMB_W * FLIGHT_THUMB_H * 4);
@@ -371,7 +389,7 @@ static void dump_main(void *arg) {
if (have[i] || !vk_thumbs_read(j->r[i].frame, px)) continue;
char path[PLAT_PATH_MAX + 32];
snprintf(path, sizeof path, "%s/f%06llu.png", j->dir, (unsigned long long)j->r[i].frame);
if (write_png(path, px, &pb)) have[i] = 1, n_thumbs++;
if (write_png(path, px, FLIGHT_THUMB_W, FLIGHT_THUMB_H, &pb)) have[i] = 1, n_thumbs++;
}
}
free(px), free(pb.raw), free(pb.z), free(pb.head);
@@ -422,19 +440,31 @@ static void start_dump(void) {
copy_events(j, j->r[0].frame);
struct tm st;
plat_local_time(&st);
snprintf(j->dir, sizeof j->dir, "%s/%04d%02d%02d-%02d%02d%02d-f%llu", base_dir, st.tm_year + 1900, st.tm_mon + 1,
st.tm_mday, st.tm_hour, st.tm_min, st.tm_sec, (unsigned long long)trig_frame);
if (trig_dir[0]) snprintf(j->dir, sizeof j->dir, "%s", trig_dir);
else
snprintf(j->dir, sizeof j->dir, "%s/%04d%02d%02d-%02d%02d%02d-f%llu", base_dir, st.tm_year + 1900, st.tm_mon + 1,
st.tm_mday, st.tm_hour, st.tm_min, st.tm_sec, (unsigned long long)trig_frame);
if (!plat_thread_spawn(dump_main, j, "flight dump", 0)) rt_log("flight: cannot start the dump thread"), free(j->ev), free(j);
}
static void trigger(uint64_t frame, uint64_t interval_ns, const char *why) {
if (dump_at) return; // one dump pending at a time; its window covers this frame
trig_dir[0] = 0;
trig_frame = frame;
trig_interval_us = interval_ns / 1000;
trig_why = why;
dump_at = frame + (FLIGHT_POST < ring_n / 4 ? FLIGHT_POST : (uint64_t)ring_n / 4);
}
// A bug capture (bugcap.c, the render thread): the dump of the frames around it goes to dir. 0 when the recorder is off
// or a dump is pending already, whose window covers this frame and which goes where its own trigger said.
int flight_capture(uint64_t frame, uint64_t interval_ns, const char *dir) {
if (!flight_on || dump_at) return 0;
trigger(frame, interval_ns, "F8");
snprintf(trig_dir, sizeof trig_dir, "%s", dir);
return 1;
}
// ---------------------------------------------------------------- per frame (render thread)
void flight_frame(uint64_t frame, uint64_t now_ns, uint64_t interval_ns, const uint64_t blocked_ns[],
const volatile int64_t counts[]) {
@@ -468,10 +498,6 @@ void flight_frame(uint64_t frame, uint64_t now_ns, uint64_t interval_ns, const u
frame_step_flight(&r->step_page, &r->step_game, &r->guest_presents);
recorded++;
static int key_was;
int key = input_flight_key();
if (key && !key_was) trigger(frame, interval_ns, "F8");
key_was = key;
for (int i = 0; i < n_at; i++)
if (at_frames[i] == frame) trigger(frame, interval_ns, "NX2NAVI_FLIGHT_AT");
if (every && frame && frame % every == 0) trigger(frame, interval_ns, "NX2NAVI_FLIGHT_EVERY");

View File

@@ -1,5 +1,5 @@
// NX2NAVI_FLIGHT=1 flight recorder (flight.c): the last frames' timing and event counts plus a thumbnail each, written to
// disk on F8 or after a slow frame, so a glitch or stutter seen in play can be read after the fact.
// disk with a bug capture (F8, bugcap.c) or after a slow frame, so a glitch or stutter seen in play can be read after the fact.
#pragma once
#include <stdint.h>
@@ -14,6 +14,9 @@ void flight_init(void); // prof_start calls it
// blocked time per PERF_* kind in this frame, and the running PERF_CNT_* totals.
void flight_frame(uint64_t frame, uint64_t now_ns, uint64_t interval_ns, const uint64_t blocked_ns[],
const volatile int64_t counts[]);
// A bug capture at this frame (the render thread, before or after flight_frame): the recorder dumps the frames around
// it into dir. 0 when the recorder is off or busy with another dump.
int flight_capture(uint64_t frame, uint64_t interval_ns, const char *dir);
// Texture events of the recorded frames (vk_texture.c), written with each dump as events.tsv: a texture made (with how
// its content started), uploaded, uploaded again, released by the game, taken back after a release, or destroyed. Each
@@ -45,6 +48,9 @@ void flight_tex(int kind, uint64_t addr, uint32_t format, uint32_t w, uint32_t h
const char *vk_texture_start_name(int start); // vk_texture.c: the names of Tex.og_start and of drop_tex's reasons
const char *vk_texture_drop_name(int why);
// A w x h RGBA picture as a compressed RGB PNG (Paeth rows, fixed-Huffman deflate); any thread, recorder on or off.
int flight_write_png(const char *path, const uint8_t *rgba, uint32_t w, uint32_t h);
// gfx_present.c: the present thread blits every presented frame into a host-visible ring of n thumbnails.
void vk_thumbs_enable(int n); // before the first present; n slots of FLIGHT_THUMB_W x FLIGHT_THUMB_H
void vk_thumbs_frame(uint64_t frame); // the present thread names the frame of the vk_present_image call that follows

View File

@@ -675,6 +675,65 @@ int vk_present_captured(const uint8_t **px, int *w, int *h, VkFormat *fmt) {
static float g_pic[4]; // gfx_picture_rect
static volatile int32_t g_pic_ok;
// ---- vk_present_grab (vk.h): one presented frame's pixels for a bug capture. The request is taken by the next
// present (g_pl held), which copies the read-back buffer and calls back; the PNG is made by the caller's own thread.
static void (*volatile g_grab_cb)(VkGrab *g, void *ctx);
static void *g_grab_ctx;
int vk_present_grab(void (*cb)(VkGrab *g, void *ctx), void *ctx) {
plat_rmutex_lock(&g_pl);
int ok = !g_grab_cb;
if (ok) g_grab_ctx = ctx, g_grab_cb = cb;
plat_rmutex_unlock(&g_pl);
return ok;
}
void vk_present_grab_cancel(void) {
plat_rmutex_lock(&g_pl);
g_grab_cb = NULL;
plat_rmutex_unlock(&g_pl);
}
void vk_present_grab_rgba(const VkGrab *g, uint8_t *out) {
size_t n = (size_t)g->w * (size_t)g->h * 4;
if (g->hdr) {
vk_hdr_to_srgb8(g->px, out, n / 4, g->a2r);
return;
}
for (size_t i = 0; i < n; i += 4) {
out[i] = g->px[i + (g->bgra ? 2 : 0)];
out[i + 1] = g->px[i + 1];
out[i + 2] = g->px[i + (g->bgra ? 0 : 2)];
out[i + 3] = 255;
}
}
void vk_present_grab_free(VkGrab *g) {
if (g) free(g->px);
free(g);
}
// The present that took the request: the read-back buffer holds this frame (g_cap_ptr, the fence waited for).
static void grab_deliver(int image_w, int image_h) {
void (*cb)(VkGrab *g, void *ctx) = g_grab_cb;
void *ctx = g_grab_ctx;
g_grab_cb = NULL;
size_t n = (size_t)g_cap_w * (size_t)g_cap_h * 4;
VkGrab *g = calloc(1, sizeof *g);
if (g && (g->px = malloc(n))) {
memcpy(g->px, g_cap_ptr, n);
g->w = g_cap_w, g->h = g_cap_h;
g->bgra = g_sc_fmt == VK_FORMAT_B8G8R8A8_UNORM || g_sc_fmt == VK_FORMAT_B8G8R8A8_SRGB;
g->hdr = g_sc_hdr != 0, g->a2r = g_sc_fmt == VK_FORMAT_A2R10G10B10_UNORM_PACK32;
g->image_w = image_w, g->image_h = image_h, g->scaler = g_scaler;
if (__atomic_load_n(&g_pic_ok, __ATOMIC_ACQUIRE)) memcpy(g->pic, g_pic, sizeof g->pic);
} else {
free(g);
g = NULL;
}
cb(g, ctx); // NULL: no memory for the copy
}
// The captured swapchain image as a PNG (the menu's test hook), RGBA with opaque alpha. From an HDR10 swapchain the
// log also gets the luminance in nits of the picture's rectangle (vk_hdr_luminance_stats: the black floor of a dark
// scene, for one), and <path>.pq10 keeps the raw pixels: "PQ10", width, height, 1 when A2R10G10B10 (u32 each), then
@@ -1495,7 +1554,8 @@ static void present_image(VkImage src, VkImageLayout layout, VkFormat fmt, int w
next_ns = plat_now_ns() + (uint64_t)(every * 1e9);
}
}
int cap = (g_capture || menu_shot) && ensure_capture_buffer();
int grab = src && g_grab_cb; // a bug capture asked for this frame (vk_present_grab)
int cap = (g_capture || menu_shot || grab) && ensure_capture_buffer();
int thumb = src && g_th_n && ensure_thumbs();
VkCommandBuffer cb = g_cb[slot];
@@ -1654,6 +1714,11 @@ static void present_image(VkImage src, VkImageLayout layout, VkFormat fmt, int w
g_cap_h = (int)g_sc_ext.height;
g_cap_valid = 1;
if (menu_shot) save_capture(menu_shot);
if (grab) grab_deliver(cw, ch);
} else if (grab) { // no read-back buffer: the request ends without pixels
void (*cb)(VkGrab *g, void *ctx) = g_grab_cb;
g_grab_cb = NULL;
cb(NULL, g_grab_ctx);
}
out:
plat_rmutex_unlock(&g_pl);

View File

@@ -69,7 +69,7 @@ void input_map_snapshot(struct InputMap *m);
int input_capture(int reset, int *id);
// The character on a punctuation key (KEY_MINUS..KEY_GRAVE) in the keyboard layout in use, 0 for another key.
uint32_t input_key_char(int key);
// F8, the flight recorder's key (no KEY_ id), held while the game window is in front.
// F8, the bug capture's key (bugcap.c; no KEY_ id), held while the game window is in front.
int input_flight_key(void);
// Insert, the frame dump's key (vk_dump.c, NX2NAVI_DUMP=key), held. On Windows also while another window is in front:
// a player on a gamepad often leaves the focus elsewhere. Unbound in the game's default layout.

View File

@@ -16,7 +16,7 @@ enum {
ACTION_COUNT = 25
};
// Keys and mouse buttons. F1, F10, F11 and Esc belong to the menu and the window, F8 to the flight recorder: no ids.
// Keys and mouse buttons. F1, F10, F11 and Esc belong to the menu and the window, F8 to the bug capture (bugcap.c): no ids.
enum {
KEY_NONE = 0,
KEY_A, KEY_B, KEY_C, KEY_D, KEY_E, KEY_F, KEY_G, KEY_H, KEY_I, KEY_J, KEY_K, KEY_L, KEY_M, // letters and digits are

View File

@@ -6,6 +6,7 @@
#include <string.h>
#include "cfg.h"
#include "bugcap.h"
#include "flight.h"
#include "gfx.h"
#include "host.h"
@@ -821,6 +822,7 @@ void perf_present(uint64_t frame) {
perfmon_frame(now, d, frame_ns, rep, __atomic_load_n(&counts[PERF_CNT_TEX_UP], __ATOMIC_RELAXED));
kern_core_diag_frame(frame, d);
if (flight_on) flight_frame(frame, now, d, frame_ns, counts);
bugcap_frame(frame, now, d, rep); // F8: a bug capture (bugcap.c); otherwise one record into its ring
if (!(rt_trace & RT_TRACE_PERF)) {
memset(frame_ns, 0, sizeof frame_ns);
last = now;

View File

@@ -43,6 +43,7 @@ static int g_font_bad;
extern "C" {
#include "amiibo.h"
#include "bugcap.h"
#include "cheats.h"
#include "debug_tools.h"
#include "cfg.h"
@@ -2051,6 +2052,24 @@ static void perf_draw(const MenuTarget *t, float scale) {
dl->AddText(ImVec2(p.x + padx, p.y + pady), SKIN_TEXT, g_perf_text);
}
// The note after F8 (bugcap.c): the capture's number and its folder's name for a few seconds, top centre, in the
// menu's look. It shows once the capture is written, so the capture's own picture is without it.
static void capture_note(const MenuTarget *t, float scale, bool below_coop) {
int number = 0, ok = 0;
char name[64], line1[160], line2[160] = "";
if (!bugcap_note(&number, &ok, name)) return;
snprintf(line1, sizeof line1, menu_text(ok ? UI_MENU_CAPTURE_SAVED : UI_MENU_CAPTURE_FAILED), number);
if (ok) snprintf(line2, sizeof line2, menu_text(UI_MENU_CAPTURE_FOLDER), name);
ImDrawList *dl = ImGui::GetForegroundDrawList();
ImVec2 s1 = ImGui::CalcTextSize(line1), s2 = ImGui::CalcTextSize(line2);
float padx = 16 * scale, pady = 10 * scale, gap = line2[0] ? 4 * scale : 0;
float w = (s1.x > s2.x ? s1.x : s2.x) + padx * 2, h = s1.y + (line2[0] ? s2.y : 0) + gap + pady * 2;
ImVec2 p(((float)t->width - w) * 0.5f, (below_coop ? 96 : 12) * scale); // co-op puts its lines at the top centre
skin_panel(dl, p, ImVec2(p.x + w, p.y + h), scale * 0.6f, 0.92f);
dl->AddText(ImVec2(p.x + (w - s1.x) * 0.5f, p.y + pady), SKIN_TEXT, line1);
if (line2[0]) dl->AddText(ImVec2(p.x + (w - s2.x) * 0.5f, p.y + pady + s1.y + gap), SKIN_TEXT_DIM, line2);
}
static int overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot) {
*shot = NULL;
if (t->phys && t->phys != g_gpu_vendor_of) { // the GPU's vendor for the rows that depend on it (dlss_offered)
@@ -2067,6 +2086,9 @@ static int overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot)
perf_tick(plat_now_ns(), t);
amiibo_tick();
const bool coop_draws = coop_overlay_tick(); // names of the other players, chat lines, an invite: over the game
int cap_number, cap_ok;
char cap_name[64];
const bool capture_shows = bugcap_note(&cap_number, &cap_ok, cap_name) != 0; // the note after F8
if (g_booting.load(std::memory_order_relaxed)) g_booting.store(0, std::memory_order_release); // the game runs
bool open = g_open.load(std::memory_order_relaxed);
// the frame the menu is first laid out after opening: also when its g_reset went to an earlier frame of the overlay
@@ -2084,7 +2106,7 @@ static int overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot)
if (g_debug.load()) debug_menu_tab(0);
set_open(1);
open = true;
} else if (!g_perf_mode && !coop_draws) {
} else if (!g_perf_mode && !coop_draws && !capture_shows) {
return 0;
}
}
@@ -2151,6 +2173,7 @@ static int overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot)
}
perf_draw(t, scale);
if (coop_draws) coop_overlay_draw((float)t->width, (float)t->height, scale, open);
capture_note(t, scale, coop_draws);
ImGui::Render();
if (open) g_save_pending = opt_save_tick(0);
g_cost_ns += plat_now_ns() - t0;

View File

@@ -734,6 +734,9 @@ static const char *const text_en[UI_TEXT_COUNT] = {
[UI_MENU_COOP_N_LEFT] = "You left the room.",
[UI_MENU_COOP_LOCAL] = "Test mode: a stand-in for Steam on this PC.",
[UI_MENU_COOP_TOAST_INVITE] = "%s invites you to a room: open the menu's Co-op tab.",
[UI_MENU_CAPTURE_SAVED] = "Bug capture %d saved",
[UI_MENU_CAPTURE_FOLDER] = "Folder: %s",
[UI_MENU_CAPTURE_FAILED] = "Bug capture %d could not be saved",
[UI_BOOT_TITLE] = "Preparing shaders",
[UI_BOOT_STARTING] = "Starting", [UI_BOOT_SHADERS] = "Shaders: %lld of %lld", [UI_BOOT_PIPELINES] = "Pipelines: %lld of %lld",
[UI_MENU_UPSCALING] = "Upscaling",
@@ -1382,6 +1385,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
[UI_MENU_COOP_N_LEFT] = "Вы вышли из комнаты.",
[UI_MENU_COOP_LOCAL] = "Тестовый режим: замена Steam на этом ПК.",
[UI_MENU_COOP_TOAST_INVITE] = "%s приглашает вас в комнату: откройте вкладку «Кооператив» в меню.",
[UI_MENU_CAPTURE_SAVED] = "Снимок ошибки %d сохранён",
[UI_MENU_CAPTURE_FOLDER] = "Папка: %s",
[UI_MENU_CAPTURE_FAILED] = "Снимок ошибки %d не удалось сохранить",
[UI_BOOT_TITLE] = "Подготовка шейдеров",
[UI_BOOT_STARTING] = "Запуск", [UI_BOOT_SHADERS] = "Шейдеры: %lld из %lld", [UI_BOOT_PIPELINES] = "Конвейеры: %lld из %lld",
[UI_MENU_CHEATS_REBUILD] = "Пересобрать игру сейчас",
@@ -2013,6 +2019,9 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
[UI_MENU_COOP_N_LEFT] = "Você saiu da sala.",
[UI_MENU_COOP_LOCAL] = "Modo de teste: um substituto da Steam neste PC.",
[UI_MENU_COOP_TOAST_INVITE] = "%s convida você para uma sala: abra a aba Co-op do menu.",
[UI_MENU_CAPTURE_SAVED] = "Captura de bug %d salva",
[UI_MENU_CAPTURE_FOLDER] = "Pasta: %s",
[UI_MENU_CAPTURE_FAILED] = "Não foi possível salvar a captura de bug %d",
[UI_BOOT_TITLE] = "Preparando shaders",
[UI_BOOT_STARTING] = "Iniciando", [UI_BOOT_SHADERS] = "Shaders: %lld de %lld", [UI_BOOT_PIPELINES] = "Pipelines: %lld de %lld",
[UI_MENU_CHEATS_REBUILD] = "Recompilar o jogo agora",
@@ -2724,6 +2733,9 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
[UI_MENU_COOP_N_LEFT] = "你已离开房间。",
[UI_MENU_COOP_LOCAL] = "测试模式:在本机上代替 Steam。",
[UI_MENU_COOP_TOAST_INVITE] = "%s 邀请你加入房间:请打开菜单的“合作”页。",
[UI_MENU_CAPTURE_SAVED] = "错误快照 %d 已保存",
[UI_MENU_CAPTURE_FOLDER] = "文件夹:%s",
[UI_MENU_CAPTURE_FAILED] = "错误快照 %d 无法保存",
[UI_BOOT_TITLE] = "正在准备着色器",
[UI_BOOT_STARTING] = "正在启动", [UI_BOOT_SHADERS] = "着色器:%lld / %lld", [UI_BOOT_PIPELINES] = "管线:%lld / %lld",
[UI_MENU_CHEATS_REBUILD] = "立即重新构建游戏",

View File

@@ -287,7 +287,9 @@ typedef enum {
UI_MENU_COOP_N_FULL, UI_MENU_COOP_N_REFUSED, UI_MENU_COOP_N_NOT_OURS, UI_MENU_COOP_N_OTHER_VERSION,
UI_MENU_COOP_N_REMOVED, UI_MENU_COOP_N_HOST_SILENT, UI_MENU_COOP_N_LOST, UI_MENU_COOP_N_LEFT,
UI_MENU_COOP_LOCAL, UI_MENU_COOP_TOAST_INVITE,
UI_MENU_LAST_ID = UI_MENU_COOP_TOAST_INVITE,
// the note after F8 (bugcap.c, ui/menu.cpp capture_note): "%d" the capture's number, "%s" its folder's name
UI_MENU_CAPTURE_SAVED, UI_MENU_CAPTURE_FOLDER, UI_MENU_CAPTURE_FAILED,
UI_MENU_LAST_ID = UI_MENU_CAPTURE_FAILED,
// the boot screen while the boot prewarm prepares shaders and pipelines (boot.c, ui/menu.cpp menu_boot_frame)
UI_BOOT_TITLE, UI_BOOT_STARTING,
UI_BOOT_SHADERS, UI_BOOT_PIPELINES, // printf: "%lld" done, "%lld" total

View File

@@ -253,6 +253,22 @@ void vk_sync_flush_held(void); // queue lock held: the held submissions go to
// NX2NAVI_ASPECT); the rest is black.
void gfx_fit_rect(int cw, int ch, int dw, int dh, int out[4]);
void vk_present_capture(int on);
// The next presented frame, as the window gets it with the overlay on it, for a bug capture (bugcap.c): its pixels
// are copied (px, malloc'd, as the swapchain holds them) and cb gets them on the presenting thread right after that
// present; cb owns g and frees it with vk_present_grab_free. vk_present_grab_rgba: the pixels as RGBA bytes, an HDR10
// picture converted to sRGB, into out (w * h * 4). One request at a time: 0 while one waits.
typedef struct {
uint8_t *px;
int w, h; // the swapchain image
int bgra, hdr, a2r; // its bytes' order; an HDR10 swapchain, and whether it is A2R10G10B10
int image_w, image_h; // the game image this present showed
int scaler; // how it was scaled to the window: 0 not, 1 bilinear, 2 FSR 1, 3 bilinear + sharpening
float pic[4]; // where the picture sits in the swapchain image, in fractions: x, y, w, h
} VkGrab;
int vk_present_grab(void (*cb)(VkGrab *g, void *ctx), void *ctx);
void vk_present_grab_cancel(void); // the request is dropped: once this returns, cb has run or never will
void vk_present_grab_rgba(const VkGrab *g, uint8_t *out);
void vk_present_grab_free(VkGrab *g);
int vk_present_captured(const uint8_t **px, int *w, int *h, VkFormat *fmt);
// The window system's part of device creation (gfx_window_win.c with Win32, gfx_window_sdl.c with SDL): the instance

View File

@@ -28,7 +28,7 @@
// NX2NAVI_DUMP_RAW=1: also save each copied image's native texel bytes as .bin, for numerical analysis.
// NX2NAVI_DUMP_KEY=<key> (Windows): each press of that key in the game window dumps the next frame to
// NX2NAVI_DUMP_DIR/f<frame>. Keys: pause (also 1), scrolllock, insert, home, end, pageup, pagedown, f2-f7, f9, f12 (F1, F8,
// F10 and F11 are the menu, the flight recorder, the overlay and fullscreen). The game still gets a key it has bound.
// F10 and F11 are the menu, the bug capture, the overlay and fullscreen). The game still gets a key it has bound.
#include <math.h>
#include <stdarg.h>
#include <stdio.h>

336
tools/capture_run.py Normal file
View File

@@ -0,0 +1,336 @@
"""Start a test run from a bug capture (runtime/bugcap.c, docs/bug-capture.md).
python tools/capture_run.py <capture folder or number> [--game DIR] [--set KEY=VALUE ...]
The game starts on a throwaway profile holding the capture's save, with the capture's settings in place of nx2navi.ini
(NX2NAVI_CAPTURE_REPLAY), in a window of the capture's size that does not take the focus. It loads the save, goes to
the capture's area, walks Link to where he stood, puts the camera where it was and takes a capture of its own; this
script then closes the game and prints both captures side by side: the positions, the distance between them, and how
much the two pictures differ. The player's nx2navi.ini and save are not written.
One game at a time: the script refuses to start while a game is running.
"""
import argparse
import hashlib
import os
import shutil
import struct
import subprocess
import sys
import time
import zipfile
import zlib
from pathlib import Path
WIN = os.name == 'nt'
SKIP_IN_PROFILE = {'save', 'save-backup', 'save-tx', 'save-import', 'save-import.part', 'coop-backup', 'instance.lock'}
def default_game():
if WIN:
return Path(os.environ.get('LOCALAPPDATA', '')) / 'Programs' / 'NX2navi' / 'game'
return Path.home() / '.local' / 'share' / 'NX2navi' / 'game'
def find_exe(game):
for name in ('ocarina.exe', 'nx2navi.exe', 'ocarina', 'nx2navi'):
if (game / name).is_file():
return game / name
return None
def read_capture(folder):
"""capture.txt as a dict of its "key = value" lines (the first of a key wins)."""
out = {}
for line in (folder / 'capture.txt').read_text(encoding='utf-8', errors='replace').splitlines():
key, sep, value = line.partition(' = ')
if sep and not key.startswith('#') and key not in out:
out[key] = value.split(' # ')[0].strip()
return out
def find_capture(arg, game):
p = Path(arg)
if p.name == 'capture.txt':
p = p.parent
if (p / 'capture.txt').is_file():
return p.resolve()
if arg.isdigit():
hits = sorted((game / 'logs' / 'captures').glob(f'{int(arg):03d}-*'))
hits = [h for h in hits if (h / 'capture.txt').is_file()]
if hits:
return hits[-1].resolve()
return None
def game_pids(exe):
"""The ids of the processes running the game's executable, by its file name."""
if WIN:
out = subprocess.run(['tasklist', '/FI', f'IMAGENAME eq {exe.name}', '/FO', 'CSV', '/NH'], capture_output=True, text=True).stdout
pids = []
for line in out.splitlines():
cells = [c.strip('"') for c in line.split('","')]
if len(cells) > 1 and cells[0].lower() == exe.name.lower() and cells[1].isdigit():
pids.append(int(cells[1]))
return pids
out = subprocess.run(['pgrep', '-x', exe.name], capture_output=True, text=True).stdout
return [int(x) for x in out.split() if x.isdigit()]
def game_running(exe):
return bool(game_pids(exe))
def make_profile(profile, game, capture):
"""A profile whose save is the capture's: the game's own profile without its saves, and the capture's save zip
as a waiting import (runtime/fs_host.c import_pending), which the game makes the save at its start."""
src = game / 'profile'
profile.mkdir(parents=True)
if src.is_dir():
for entry in src.iterdir():
if entry.name in SKIP_IN_PROFILE:
continue
if entry.is_dir():
shutil.copytree(entry, profile / entry.name)
else:
shutil.copy2(entry, profile / entry.name)
zips = sorted(capture.glob('NX2navi-save-*.zip'))
if not zips:
if (src / 'save').is_dir():
shutil.copytree(src / 'save', profile / 'save')
return 'the capture holds no save: a copy of the save the game has now'
staged = profile / 'save-import'
files = 0
with zipfile.ZipFile(zips[0]) as z:
for info in z.infolist():
name = info.filename
if info.is_dir() or not name.startswith('save/'):
continue
rel = Path(name[5:])
if rel.is_absolute() or '..' in rel.parts or name.lower().endswith(('.keys', '.keys.txt')):
continue
dst = staged / rel
dst.parent.mkdir(parents=True, exist_ok=True)
dst.write_bytes(z.read(info))
files += 1
return f'the capture\'s save ({files} files from {zips[0].name})'
def close_game(proc, exe, grace=30):
"""Ask the game's windows to close, as the window's own button does (it then writes its exit lines); by force when
that does not end it. The game may be a child of the process this script started: at its start it runs itself
again when Windows has put something where its memory must go (runtime/platform/win32.c plat_reexec), and the
first process only waits for the second. No other game ran when this one started (main checks), so every process
of the executable is this run's."""
if proc.poll() is not None and not game_pids(exe):
return 'had ended'
if WIN:
import ctypes
from ctypes import wintypes
user32 = ctypes.windll.user32
proto = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
pids = set(game_pids(exe)) | {proc.pid}
def each(hwnd, _):
pid = wintypes.DWORD()
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
if pid.value in pids and user32.IsWindowVisible(hwnd):
user32.PostMessageW(hwnd, 0x10, 0, 0) # WM_CLOSE
return True
user32.EnumWindows(proto(each), 0)
else:
proc.terminate()
end = time.time() + grace
while time.time() < end and (proc.poll() is None or game_pids(exe)):
time.sleep(0.5)
if proc.poll() is not None and not game_pids(exe):
return 'closed'
if WIN:
for pid in game_pids(exe):
subprocess.run(['taskkill', '/PID', str(pid), '/T', '/F'], capture_output=True)
if proc.poll() is None:
proc.kill()
proc.wait()
time.sleep(1)
return 'STILL RUNNING: close it by hand' if game_pids(exe) else 'closed by force'
def read_png(path):
"""(width, height, bytes per pixel, rows) of an 8-bit RGB or RGBA PNG without interlacing, as the game writes."""
data = path.read_bytes()
if data[:8] != b'\x89PNG\r\n\x1a\n':
raise ValueError('not a PNG')
at, idat, head = 8, [], None
while at + 8 <= len(data):
n, kind = struct.unpack('>I4s', data[at:at + 8])
body = data[at + 8:at + 8 + n]
if kind == b'IHDR':
head = struct.unpack('>IIBBBBB', body)
elif kind == b'IDAT':
idat.append(body)
at += 12 + n
w, h, depth, colour, _, _, interlace = head
if depth != 8 or colour not in (2, 6) or interlace:
raise ValueError('a PNG kind this does not read')
bpp = 3 if colour == 2 else 4
raw = zlib.decompress(b''.join(idat))
stride = w * bpp
rows, prev = [], bytearray(stride)
for y in range(h):
f = raw[y * (stride + 1)]
line = bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)])
if f == 1:
for i in range(bpp, stride):
line[i] = (line[i] + line[i - bpp]) & 255
elif f == 2:
for i in range(stride):
line[i] = (line[i] + prev[i]) & 255
elif f == 3:
for i in range(stride):
line[i] = (line[i] + ((line[i - bpp] if i >= bpp else 0) + prev[i]) // 2) & 255
elif f == 4:
for i in range(stride):
a = line[i - bpp] if i >= bpp else 0
b = prev[i]
c = prev[i - bpp] if i >= bpp else 0
p = a + b - c
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
line[i] = (line[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 255
rows.append(line)
prev = line
return w, h, bpp, rows
def picture_difference(a, b, step=4):
"""The mean difference of the colour channels (0 to 255) over every step-th pixel of two pictures of one size."""
wa, ha, bpa, ra = read_png(a)
wb, hb, bpb, rb = read_png(b)
if (wa, ha) != (wb, hb):
return None, f'{wa}x{ha} against {wb}x{hb}'
total = count = 0
for y in range(0, ha, step):
la, lb = ra[y], rb[y]
for x in range(0, wa, step):
for c in range(3):
total += abs(la[x * bpa + c] - lb[x * bpb + c])
count += 3
return total / count, f'{wa}x{ha}'
def sha(path):
return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else ''
def main():
ap = argparse.ArgumentParser(description='Start a test run at a bug capture\'s place, camera and settings.')
ap.add_argument('capture', help='a capture\'s folder, or its number in the game\'s logs/captures')
ap.add_argument('--game', type=Path, default=default_game(), help='the game folder (default: the installed game)')
ap.add_argument('--exe', type=Path, help='the game\'s executable (default: the one in the game folder)')
ap.add_argument('--out', type=Path, help='where the run\'s log and its own capture go (default: <capture>/replays)')
ap.add_argument('--seconds', type=int, default=300, help='give up after this long (default 300)')
ap.add_argument('--hold', type=int, default=0, help='seconds to keep the game open after its capture, to watch or test')
ap.add_argument('--set', action='append', default=[], metavar='KEY=VALUE',
help='a setting for this run on top of the capture\'s (NX2NAVI_ is added), e.g. --set FSR4=0')
ap.add_argument('--no-camera', action='store_true', help='leave the camera to the game instead of placing it')
ap.add_argument('--fullscreen', action='store_true', help='keep the capture\'s fullscreen and window settings')
ap.add_argument('--foreground', action='store_true', help='a normal window that takes the focus and your input')
args = ap.parse_args()
game = args.game.resolve()
exe = (args.exe or find_exe(game) or game / 'ocarina.exe').resolve()
if not exe.is_file():
sys.exit(f'no game executable in {game}')
capture = find_capture(args.capture, game)
if not capture:
sys.exit(f'no capture.txt found for "{args.capture}" (a folder, or a number under {game / "logs" / "captures"})')
if game_running(exe):
sys.exit(f'{exe.name} is running: one game at a time. Close it first.')
cap = read_capture(capture)
out = (args.out or capture / 'replays').resolve()
out.mkdir(parents=True, exist_ok=True)
stamp = time.strftime('%Y%m%d-%H%M%S')
profile = out / f'profile-{stamp}'
log = out / f'run-{stamp}.log'
print(f'capture {cap.get("number", "?")} ({capture.name}): {cap.get("area", "no area")}, Link at {cap.get("player_pos", "?")}, '
f'camera at {cap.get("camera_pos", "not captured")}; NX2navi {cap.get("nx2navi", "?")}')
print('profile:', make_profile(profile, game, capture))
env = {k: v for k, v in os.environ.items() if not k.upper().startswith('NX2NAVI_')}
pins = {'CAPTURE_REPLAY': str(capture), 'CAPTURE_DIR': str(out), 'COOP': '0', 'COOP_STEAM': '0', 'DISCORD_RPC': '0'}
if not args.fullscreen:
pins['FULLSCREEN'] = '0'
if 'x' in cap.get('window', ''):
pins['WINDOW_SIZE'] = cap['window']
if not args.foreground:
pins.update(BACKGROUND_WINDOW='1', ASSUME_FOCUS='1', INPUT='none')
if args.no_camera:
pins['CAPTURE_REPLAY_CAMERA'] = '0'
for pair in args.set:
key, sep, value = pair.partition('=')
if not sep:
sys.exit(f'--set takes KEY=VALUE, not "{pair}"')
key = key.strip().upper()
pins[key[8:] if key.startswith('NX2NAVI_') else key] = value
for key, value in pins.items():
env['NX2NAVI_' + key] = value
print('this run sets:', ', '.join(f'{k}={v}' for k, v in sorted(pins.items()) if k not in ('CAPTURE_REPLAY', 'CAPTURE_DIR')))
ini = game / 'nx2navi.ini'
ini_before = sha(ini)
before = {p.name for p in out.iterdir() if p.is_dir()}
result, state = None, 'timed out'
with open(log, 'wb') as err:
proc = subprocess.Popen([str(exe), '--profile', str(profile)], cwd=str(game), env=env, stderr=err,
stdout=subprocess.DEVNULL, stdin=subprocess.DEVNULL)
t0 = time.time()
ready = False
try:
while time.time() - t0 < args.seconds and proc.poll() is None:
time.sleep(1)
text = log.read_text(encoding='utf-8', errors='replace')
if 'capture: replay of' in text and ' stopped: ' in text:
state = 'the replay stopped'
break
if not ready and ' ready: ' in text and 'capture: replay of' in text:
ready = True
if ready and any(' saved to ' in line and '(replay' in line for line in text.splitlines()):
state = 'done'
break
if proc.poll() is not None:
state = f'the game ended by itself (exit {proc.returncode})'
elif state == 'done' and args.hold:
print(f'the game stays open for {args.hold} s')
time.sleep(args.hold)
finally:
print('game:', close_game(proc, exe), f'after {time.time() - t0:.0f} s; {state}')
shutil.rmtree(profile, ignore_errors=True)
print('nx2navi.ini', 'unchanged' if sha(ini) == ini_before else 'CHANGED by the run: put it back from your copy')
text = log.read_text(encoding='utf-8', errors='replace')
for line in text.splitlines():
if 'capture: ' in line or 'debug: route' in line or ('debug: ' in line and ('eleport' in line or 'Arrived' in line)):
print(' ' + line[:300])
new = sorted(p for p in out.iterdir() if p.is_dir() and p.name not in before and (p / 'capture.txt').is_file())
if new:
result = new[-1]
rep = read_capture(result)
print(f'\nthe run\'s own capture: {result}')
for key in ('area', 'player_pos', 'camera_pos', 'camera_yaw', 'camera_pitch', 'camera_fov_y_degrees', 'window', 'game_image'):
a, b = cap.get(key, '-'), rep.get(key, '-')
print(f' {key:22} {a:38} {b:38} {"same" if a == b else ""}')
print(f' Link ended {rep.get("replay_player_off_metres", "?")} m from the captured place; the walk: {rep.get("replay_walk", "?")}; '
f'camera: {rep.get("replay_camera", "?")}')
if (capture / 'frame.png').is_file() and (result / 'frame.png').is_file():
try:
diff, size = picture_difference(capture / 'frame.png', result / 'frame.png')
print(f' pictures ({size}):', 'of different sizes' if diff is None else
f'mean difference {diff:.1f} of 255 per channel (two frames of one standing view differ by 1 to 4)')
except (ValueError, zlib.error, struct.error) as e:
print(' pictures: not compared:', e)
else:
print('\nno capture came out of the run; the log:', log)
return 0 if result else 1
if __name__ == '__main__':
sys.exit(main())