Bring public main's bug capture on F8 and its removal of the Steam co-op into the 0.10.0 line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	docs/architecture.md
#	launcher/steamlib.py
#	launcher/ui/app.py
#	runtime/boot.c
#	runtime/cfg.c
#	runtime/flight.c
#	runtime/flight.h
#	runtime/gfx_present.c
#	tests/launcher_test.py
This commit is contained in:
chrg6
2026-11-13 09:52:43 -05:00
46 changed files with 1720 additions and 4147 deletions

View File

@@ -15,7 +15,6 @@
#include <string.h>
#include "cfg.h"
#include "coop.h"
#include "cheats.h"
#include "fs.h"
#include "kernel.h"
@@ -325,7 +324,6 @@ void rt_frame_presented(const tex_t *t, uint64_t n) {
stats_line();
fflush(stdout);
fflush(stderr);
coop_shutdown(); // leaves the room, before the process ends
input_rumble_hd_stop(); // a controller on HD rumble gets the neutral value before the exit
fs_save_flush();
vk_pipeline_prewarm_marker_clear(); // an orderly end, not a driver crash in the boot's builds (vk_pipeline.c pm_skipped)

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", "PHYSICS_STEPS_FULL", "PICKUP_COUNT", "WATER_STEPS", "SOUND_STEPS", "FLOOR_PROBE", "FLOOR_SCAN", "FLOOR_WATCH", "FLOOR_CARRY", "MOVIE_PTS", "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_CATCHUP", "AUDIO_CHANNELS", "AUDIO_DEVICE", "AUDIO_GAME_PRIO", "AUDIO_OFF", "AUDIO_PREFILL_MS", "AUDIO_RAMP", "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",
@@ -84,13 +86,14 @@ static const char *const known[] = {
"MEM_BUDGET_TEST_VRAM_MB", "MEM_BUDGET_TEST_RAM_MB",
"TEX_COMPACT", "TEX_COMPACT_MIN_MB", "TEX_COMPACT_FRAME_MB", // texture compaction (vk_texture.c); no menu row
"STANDIN_FILTER", // the filter of the scene upscaler's stand-in (vk_tonemap.c); no menu row
"COOP_STEAM", "COOP_SHARE", "COOP_NAMES", "COOP_CHAT", // co-op (coop.c, coop_game.c, ui/coop_page.cpp)
// retired: the settings of the co-op of versions up to 0.9.2; read by nothing, listed so that a file which still
// sets them logs no unknown key. COOP was that co-op's switch: the new one's is COOP_STEAM, so that a "coop = 1"
// left in a file from then turns nothing on
// sets them logs no unknown key
"COOP", "COOP_BETA", "COOP_NAME", "COOP_SERVER", "COOP_PORT", "COOP_ROOM", "COOP_AUTO", "COOP_DROP",
"COOP_PROGRESS", "COOP_ITEMS", "COOP_SONGS", "COOP_QUEST", "COOP_KEYS", "COOP_RUPEES", "COOP_AMMO",
"COOP_TEST_SET", "COOP_ACCEPT", "COOP_REMOVE", "COOP_RESET_POOLS",
// retired: the settings of the co-op through Steam that the main branch held for a while after 0.9.2 and no
// release shipped; listed like the ones above, for the file of someone who built from it then and turned it on
"COOP_STEAM", "COOP_SHARE", "COOP_NAMES", "COOP_CHAT",
};
// The nx2navi.ini section a key cfg_set may write goes to when the file lacks it (nx2navi.ini.example's sections).
@@ -120,7 +123,6 @@ static const struct { const char *key, *section; } sections[] = {
{"LOW_LATENCY", "display"},
{"DEVICE_PROFILE", "display"}, {"ASSUME_FOCUS", "display"},
{"DISCORD_RPC", "discord"}, {"DISCORD_APP_ID", "discord"}, {"DISCORD_IMAGE", "discord"},
{"COOP_STEAM", "coop"}, {"COOP_SHARE", "coop"}, {"COOP_NAMES", "coop"}, {"COOP_CHAT", "coop"},
{"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"CONTACT_SHADOWS", "display"},
{"PCSS", "display"},
{"SHADOW_PCF", "display"},
@@ -291,11 +293,6 @@ static const CfgMeta metas[] = {
{"DISCORD_RPC", "1", "0|1", LIVE},
{"DISCORD_APP_ID", NX2NAVI_DISCORD_APP_ID_DEFAULT, NULL, LIVE},
{"DISCORD_IMAGE", NX2NAVI_DISCORD_IMAGE_DEFAULT, NULL, LIVE},
// Co-op (coop.c): COOP_STEAM is its switch, off until the player turns it on; then the game signs in to Steam as its test app and can make
// or join a room. In a room: COOP_SHARE shares progress, items and songs with the other players (coop_game.c),
// COOP_NAMES shows the other players' names where they stand, COOP_CHAT shows the chat's lines over the game.
{"COOP_STEAM", "0", "0|1", LIVE}, {"COOP_SHARE", "1", "0|1", LIVE}, {"COOP_NAMES", "1", "0|1", LIVE},
{"COOP_CHAT", "1", "0|1", LIVE},
// Advanced: scheduling
{"ASYNC_PREEMPT", "1", "0|1|2", RESTART}, {"REPLAY_ASYNC", "0", "0|1", RESTART},
{"REPLAY_PIPE", "0", "0..4", RESTART},
@@ -1166,7 +1163,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;
@@ -1176,7 +1176,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++) {
@@ -1189,26 +1189,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

@@ -88,22 +88,6 @@ int probe_cfg(void) {
CHECK(EQ(cfg_unknown_keys(&n), "") && n == 0, "a missing file leaves no unknown keys either");
}
// A file from the co-op of versions up to 0.9.2: its lines are retired settings, not unknown keys, and its switch,
// coop = 1, does not turn the new co-op on, whose switch has a name of its own (coop_steam).
{
static const char old_coop[] = "[coop]\ncoop = 1\ncoop_beta = 1\ncoop_name = someone\ncoop_progress = shared\n";
cfg_setenv("NX2NAVI_COOP_STEAM", NULL);
CHECK(plat_file_write(path, old_coop, sizeof old_coop - 1) && cfg_load(path) == 1, "load a file of the old co-op");
int n = -1;
CHECK(EQ(cfg_unknown_keys(&n), "") && n == 0, "the old co-op's settings are no unknown keys");
CHECK(!cfg_bool("NX2NAVI_COOP_STEAM"), "the old co-op's coop = 1 does not turn the new co-op on");
static const char new_coop[] = "[coop]\ncoop = 0\ncoop_steam = 1\n";
CHECK(plat_file_write(path, new_coop, sizeof new_coop - 1) && cfg_load(path) == 1 && cfg_bool("NX2NAVI_COOP_STEAM"),
"coop_steam = 1 turns the new co-op on");
plat_file_delete(path);
CHECK(cfg_load(path) == 0, "the co-op file is gone again");
}
// A player's file as a report showed it: settings the menu wrote, and three lines added by hand that are no
// settings of this version (the player took the first for the fix of a crash). The three are named as such, a
// repeated one once, a key of other characters is counted without being listed, and the menu's save keeps every

View File

@@ -1,736 +0,0 @@
// Co-op, the room (coop.h): one host thread that owns Steam (steam.c) and the room and talks to the other games.
//
// A room is a Steam lobby that carries the note nx2navi = 1; a lobby without it is somebody else's (the app id is
// shared with every program that uses Steam's test app) and is left at once. The lobby's owner is the host. Being in
// the lobby is not yet being in the room: a game that came says HELLO to the host with its protocol number and game
// build, the host answers WELCOME or REFUSED and lists the players it let in (ROSTER, at each change and every two
// seconds), and every game takes poses, chat and the game layer's messages only from the players on the host's list.
// So a player the host removed, or a game of another version, is in nobody's room though Steam still shows it in the
// lobby for a moment. When the host leaves, Steam makes another member the owner; that game carries on with the list
// it had.
//
// Messages are one kind byte and a body, in the byte order of the PCs this runs on (little-endian):
// HELLO u16 protocol, u32 game build to the host, every second until it answers
// WELCOME u16 protocol the host's yes
// REFUSED u8 why (REFUSE_*) the host's no; the game leaves the lobby
// ROSTER u8 count, count x u64 id the host's list, the host first
// POSE u32 number, the pose (pose_put) unreliable, 20 a second while Link is in the world, 2 a second else
// CHAT text, UTF-8, at most COOP_CHAT_CAP to everyone on the list
// from COOP_GAME_KIND on: the game layer's (coop_game.c), passed through
// Steam vouches for the sender of every message (its id is the Steam account's) and encrypts them; nothing here adds
// to that. Every length is checked before a body is read, a float that is not finite ends the message, and a name or
// a chat line is shown with its control characters replaced.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cfg.h"
#include "coop.h"
#include "coop_net.h"
#include "host.h"
#include "platform/platform.h"
enum {
K_HELLO = 1, K_WELCOME, K_REFUSED, K_ROSTER, K_POSE, K_CHAT,
REFUSE_VERSION = 1, REFUSE_REMOVED, REFUSE_FULL,
GAME_BUILD = 0xe0f3ccfa, // the game build this runtime's co-op knows (1.1.1)
STEP_MS = 5,
HELLO_EVERY_MS = 1000, HOST_WAIT_MS = 15000, ROSTER_EVERY_MS = 2000,
POSE_EVERY_MS = 50, POSE_IDLE_MS = 500, POSE_STALE_MS = 3000,
STEAM_RETRY_MS = 5000,
COMMANDS = 16, OUTBOX = 256, REMOVED_MAX = 32,
POSE_BYTES = 4 + 12 + 12 + 4 + 1 + 1, // number, pos, vel, yaw, flags, scene length; then the scene
};
typedef enum { C_CREATE = 1, C_JOIN, C_JOIN_INVITE, C_DECLINE, C_LEAVE, C_RETRY, C_INVITE, C_INVITE_WINDOW, C_REMOVE, C_CHAT, C_FRIENDS } CmdKind;
typedef struct { CmdKind kind; uint64_t arg; char text[COOP_CHAT_CAP + 1]; } Cmd;
typedef struct { uint64_t to; uint16_t n; uint8_t reliable; uint8_t bytes[1 + COOP_MESSAGE_MAX]; } Out;
typedef struct {
uint64_t id;
char name[COOP_NAME_CAP];
int has_pose;
uint32_t pose_number;
uint64_t pose_at;
CoopPose pose;
} Player;
// The co-op thread's own state.
static struct {
const CoopNet *net;
int up;
uint64_t retry_at;
CoopState state;
CoopNote note;
char steam_says[160];
uint64_t room, owner;
int made; // this game made the room
int welcomed; // the host let this game in (always, for the host itself)
uint64_t entered_at, hello_at, roster_at, pose_sent_at;
uint32_t pose_number;
int n;
Player players[COOP_PLAYERS]; // the host's list as this game knows it; this game is among them once welcomed
int nremoved;
uint64_t removed[REMOVED_MAX];
uint64_t invite_room, invite_from;
int nchat;
CoopChatLine chat[COOP_CHAT_LINES];
uint32_t friends_serial;
int own_has; // this game's own pose, as last sent
CoopPose own_pose;
} G;
// What the other threads share with it.
static struct {
PlatMutex lock;
PlatEvent stopped;
volatile int32_t stop;
volatile uint32_t serial;
CoopView view;
int ncmd;
Cmd cmd[COMMANDS];
int nout;
Out *out;
int has_pose;
CoopPose pose;
int nfriends;
SteamFriend friends[COOP_FRIENDS];
int in_room; // for coop_post: only then is a message queued
} P;
// ---- text from outside: control characters and the characters that reorder a line are no part of a name or a chat line
static void clean_text(char *s) {
for (unsigned char *p = (unsigned char *)s; *p; p++) {
if (*p < 0x20 || *p == 0x7f) *p = ' ';
// U+202A..U+202E and U+2066..U+2069 (E2 80 AA..AE, E2 81 A6..A9): direction overrides and isolates
if (p[0] == 0xe2 && ((p[1] == 0x80 && p[2] >= 0xaa && p[2] <= 0xae) || (p[1] == 0x81 && p[2] >= 0xa6 && p[2] <= 0xa9)))
p[0] = p[1] = p[2] = ' ';
}
}
// ---- the players
static Player *player_of(uint64_t id) {
for (int i = 0; i < G.n; i++)
if (G.players[i].id == id) return &G.players[i];
return NULL;
}
static void name_player(Player *p) {
if (p->name[0]) return;
G.net->name_of(p->id, p->name, sizeof p->name);
clean_text(p->name);
}
static Player *player_add(uint64_t id) {
Player *p = player_of(id);
if (p || G.n >= COOP_PLAYERS) return p;
p = &G.players[G.n++];
memset(p, 0, sizeof *p);
p->id = id;
name_player(p);
return p;
}
static void chat_line(const char *name, const char *text, int notice, int joined) {
if (G.nchat == COOP_CHAT_LINES) memmove(G.chat, G.chat + 1, sizeof G.chat[0] * (size_t)--G.nchat);
CoopChatLine *l = &G.chat[G.nchat++];
memset(l, 0, sizeof *l);
snprintf(l->name, sizeof l->name, "%s", name);
snprintf(l->text, sizeof l->text, "%s", text);
l->at_ms = plat_now_ms(), l->notice = (uint8_t)notice, l->joined = (uint8_t)joined;
}
static void player_remove(uint64_t id) {
for (int i = 0; i < G.n; i++) {
if (G.players[i].id != id) continue;
if (G.welcomed && id != G.net->self()) {
rt_log("coop: %s left the room", G.players[i].name[0] ? G.players[i].name : "a player");
chat_line(G.players[i].name, "", 1, 0);
}
memmove(G.players + i, G.players + i + 1, sizeof G.players[0] * (size_t)(G.n - i - 1));
G.n--;
return;
}
}
static int is_removed(uint64_t id) {
for (int i = 0; i < G.nremoved; i++)
if (G.removed[i] == id) return 1;
return 0;
}
static int hosting(void) { return G.room && G.owner == G.net->self(); }
// ---- sending
static void send_kind(uint64_t to, uint8_t kind, const void *body, size_t n, int reliable) {
uint8_t d[1 + COOP_MESSAGE_MAX];
if (n > COOP_MESSAGE_MAX) return;
d[0] = kind;
if (n) memcpy(d + 1, body, n);
G.net->send(to, d, n + 1, reliable);
}
static void send_listed(uint8_t kind, const void *body, size_t n, int reliable) {
for (int i = 0; i < G.n; i++)
if (G.players[i].id != G.net->self()) send_kind(G.players[i].id, kind, body, n, reliable);
}
static void send_roster(void) {
uint8_t d[1 + 8 * COOP_PLAYERS];
d[0] = (uint8_t)G.n;
for (int i = 0; i < G.n; i++) memcpy(d + 1 + 8 * i, &G.players[i].id, 8);
send_listed(K_ROSTER, d, 1 + 8 * (size_t)G.n, 1);
G.roster_at = plat_now_ms();
}
static size_t pose_put(uint8_t *d, uint32_t number, const CoopPose *p) {
size_t sl = strnlen(p->scene, COOP_SCENE_CAP - 1);
memcpy(d, &number, 4), memcpy(d + 4, p->pos, 12), memcpy(d + 16, p->vel, 12), memcpy(d + 28, &p->yaw, 4);
d[32] = p->flags, d[33] = (uint8_t)sl;
memcpy(d + POSE_BYTES, p->scene, sl);
return POSE_BYTES + sl;
}
static int pose_get(const uint8_t *d, size_t n, uint32_t *number, CoopPose *p) {
if (n < POSE_BYTES || d[33] >= COOP_SCENE_CAP || n != POSE_BYTES + (size_t)d[33]) return 0;
memset(p, 0, sizeof *p);
memcpy(number, d, 4), memcpy(p->pos, d + 4, 12), memcpy(p->vel, d + 16, 12), memcpy(&p->yaw, d + 28, 4);
p->flags = d[32];
memcpy(p->scene, d + POSE_BYTES, d[33]);
for (int i = 0; i < 3; i++)
if (!isfinite(p->pos[i]) || !isfinite(p->vel[i]) || fabsf(p->pos[i]) > 1e6f) return 0;
if (!isfinite(p->yaw)) return 0;
clean_text(p->scene);
return 1;
}
// ---- the room
static void room_end(CoopNote note) {
if (G.room || G.state == COOP_ENTERING) {
G.net->room_leave();
if (G.welcomed) coop_game_room(0);
if (G.room) rt_log("coop: left the room");
}
G.room = G.owner = 0, G.made = G.welcomed = 0, G.n = 0, G.nremoved = 0;
G.state = COOP_READY;
G.note = note;
}
static void welcomed(void) {
G.welcomed = 1;
G.state = COOP_IN_ROOM;
G.note = COOP_NOTE_NONE;
player_add(G.net->self());
coop_game_room(1);
}
static void on_entered(uint64_t room) {
G.room = room;
G.owner = G.net->room_owner();
G.entered_at = plat_now_ms(), G.hello_at = 0;
G.n = 0, G.nremoved = 0, G.welcomed = 0;
if (G.made) {
G.net->room_set("nx2navi", "1");
welcomed();
char code[STEAM_CODE_CAP];
steam_code_make(room, code);
rt_log("coop: room made%s", code[0] || G.net == &coop_net_local ? "" : " (it has no room id: invite through Steam)");
return;
}
char ours[8];
G.net->room_get("nx2navi", ours, sizeof ours);
if (strcmp(ours, "1")) {
rt_log("coop: that Steam lobby is no NX2navi room; left it");
room_end(COOP_NOTE_NOT_OURS);
return;
}
rt_log("coop: in the lobby; asking the host");
}
static void on_message(uint64_t from, const uint8_t *d, size_t n) {
if (!G.room || n < 1) return;
uint8_t kind = d[0];
const uint8_t *b = d + 1;
n--;
int from_host = from == G.owner;
if (kind == K_HELLO) {
if (!hosting() || n != 6) return;
uint16_t proto;
uint32_t build;
memcpy(&proto, b, 2), memcpy(&build, b + 2, 4);
uint8_t why = proto != COOP_PROTOCOL || build != GAME_BUILD ? REFUSE_VERSION : is_removed(from) ? REFUSE_REMOVED
: !player_of(from) && G.n >= COOP_PLAYERS ? REFUSE_FULL : 0;
if (why) {
send_kind(from, K_REFUSED, &why, 1, 1);
return;
}
int fresh = !player_of(from);
Player *p = player_add(from);
if (!p) return;
uint16_t mine = COOP_PROTOCOL;
send_kind(from, K_WELCOME, &mine, 2, 1);
send_roster();
if (fresh) {
rt_log("coop: %s joined the room", p->name[0] ? p->name : "a player");
chat_line(p->name, "", 1, 1);
coop_game_joined(from);
}
} else if (kind == K_WELCOME) {
if (from_host && !G.welcomed && n == 2) {
player_add(from);
welcomed();
rt_log("coop: joined the room");
coop_game_joined(from);
}
} else if (kind == K_REFUSED) {
if (from_host && n == 1 && !hosting())
room_end(b[0] == REFUSE_VERSION ? COOP_NOTE_OTHER_VERSION : b[0] == REFUSE_REMOVED ? COOP_NOTE_REMOVED
: b[0] == REFUSE_FULL ? COOP_NOTE_FULL : COOP_NOTE_REFUSED);
} else if (kind == K_ROSTER) {
if (!from_host || hosting() || !G.welcomed || n < 1 || b[0] > COOP_PLAYERS || n != 1 + 8 * (size_t)b[0]) return;
uint64_t ids[COOP_PLAYERS];
memcpy(ids, b + 1, 8 * (size_t)b[0]);
int listed = 0;
for (int i = 0; i < b[0]; i++) listed |= ids[i] == G.net->self();
if (!listed) { // the host took this game off its list
room_end(COOP_NOTE_REMOVED);
return;
}
for (int i = G.n - 1; i >= 0; i--) {
int still = 0;
for (int k = 0; k < b[0]; k++) still |= ids[k] == G.players[i].id;
if (!still) player_remove(G.players[i].id);
}
for (int k = 0; k < b[0]; k++) {
if (player_of(ids[k])) continue;
Player *p = player_add(ids[k]);
if (p && ids[k] != G.owner) {
rt_log("coop: %s joined the room", p->name[0] ? p->name : "a player");
chat_line(p->name, "", 1, 1);
}
if (p) coop_game_joined(ids[k]);
}
} else if (!G.welcomed || !player_of(from)) {
return; // everything below: only from a player on the host's list
} else if (kind == K_POSE) {
Player *p = player_of(from);
uint32_t number;
CoopPose pose;
if (!pose_get(b, n, &number, &pose)) return;
if (p->has_pose && (int32_t)(number - p->pose_number) <= 0) return; // late or twice
p->pose = pose, p->pose_number = number, p->pose_at = plat_now_ms(), p->has_pose = 1;
} else if (kind == K_CHAT) {
if (n < 1 || n > COOP_CHAT_CAP) return;
char text[COOP_CHAT_CAP + 1];
memcpy(text, b, n), text[n] = 0;
clean_text(text);
Player *p = player_of(from);
name_player(p);
chat_line(p->name, text, 0, 0);
} else if (kind >= COOP_GAME_KIND) {
coop_game_message(from, kind, b, n);
}
}
static void on_event(const SteamEvent *e, void *user) {
(void)user;
switch (e->kind) {
case STEAM_EV_ROOM_ENTERED: on_entered(e->a); break;
case STEAM_EV_ROOM_FAILED:
G.state = COOP_READY, G.made = 0;
G.note = e->code == STEAM_FAIL_CREATE ? COOP_NOTE_CREATE_FAILED : e->code == STEAM_FAIL_NO_ROOM ? COOP_NOTE_NO_ROOM
: e->code == STEAM_FAIL_FULL ? COOP_NOTE_FULL : COOP_NOTE_REFUSED;
rt_log("coop: the room could not be %s (%d)", e->code == STEAM_FAIL_CREATE ? "made" : "joined", e->code);
break;
case STEAM_EV_MEMBER_JOINED: break; // it says HELLO when it is one of ours
case STEAM_EV_MEMBER_LEFT:
if (player_of(e->a)) {
player_remove(e->a);
if (hosting()) send_roster();
}
break;
case STEAM_EV_INVITED:
if (!G.room && G.state != COOP_ENTERING) G.invite_room = e->a, G.invite_from = e->b;
break;
case STEAM_EV_JOIN_ASKED:
// the player said yes in Steam itself: leave the room this game is in and go there
if (e->a != G.room) {
if (G.room || G.state == COOP_ENTERING) room_end(COOP_NOTE_NONE);
G.made = 0, G.invite_room = 0;
if (G.net->room_join(e->a)) G.state = COOP_ENTERING, G.entered_at = plat_now_ms();
}
break;
case STEAM_EV_MESSAGE: on_message(e->a, e->data, e->n); break;
case STEAM_EV_LOST:
rt_log("coop: Steam lost its connection; the room is gone");
if (G.welcomed) coop_game_room(0);
G.room = G.owner = 0, G.made = G.welcomed = 0, G.n = 0;
G.state = COOP_READY, G.note = COOP_NOTE_LOST;
break;
}
}
// ---- the thread's step
static void run_command(const Cmd *c) {
if (!G.up) {
if (c->kind == C_RETRY) G.retry_at = 0;
return;
}
switch (c->kind) {
case C_CREATE:
if (G.room || G.state == COOP_ENTERING) break;
if (G.net->room_create(COOP_PLAYERS)) G.state = COOP_ENTERING, G.made = 1, G.note = COOP_NOTE_NONE, G.entered_at = plat_now_ms();
else G.note = COOP_NOTE_CREATE_FAILED;
break;
case C_JOIN:
case C_JOIN_INVITE: {
uint64_t room = c->kind == C_JOIN ? c->arg : G.invite_room;
G.invite_room = 0;
if (!room || G.room || G.state == COOP_ENTERING) break;
if (G.net->room_join(room)) G.state = COOP_ENTERING, G.made = 0, G.note = COOP_NOTE_NONE, G.entered_at = plat_now_ms();
else G.note = COOP_NOTE_NO_ROOM;
break;
}
case C_DECLINE: G.invite_room = 0; break;
case C_LEAVE:
if (G.room || G.state == COOP_ENTERING) room_end(COOP_NOTE_LEFT);
break;
case C_RETRY: break;
case C_INVITE:
if (G.room && !coop_local_wanted()) steam_invite(c->arg);
break;
case C_INVITE_WINDOW:
if (G.room && !coop_local_wanted()) steam_invite_window();
break;
case C_REMOVE:
if (!hosting() || c->arg == G.net->self() || !player_of(c->arg)) break;
if (G.nremoved < REMOVED_MAX) G.removed[G.nremoved++] = c->arg;
send_kind(c->arg, K_REFUSED, (uint8_t[]){REFUSE_REMOVED}, 1, 1);
player_remove(c->arg);
send_roster();
break;
case C_CHAT: {
size_t n = strlen(c->text);
if (!G.welcomed || !n) break;
send_listed(K_CHAT, c->text, n, 1);
Player *me = player_of(G.net->self());
if (me) name_player(me), chat_line(me->name, c->text, 0, 0);
break;
}
case C_FRIENDS:
if (!coop_local_wanted()) {
static SteamFriend list[COOP_FRIENDS];
int n = steam_friends(list, COOP_FRIENDS);
plat_mutex_lock(&P.lock);
memcpy(P.friends, list, sizeof list[0] * (size_t)n);
P.nfriends = n;
plat_mutex_unlock(&P.lock);
G.friends_serial++;
}
break;
}
}
static void tick(uint64_t now) {
if (!G.room) {
if (G.state == COOP_ENTERING && now - G.entered_at > HOST_WAIT_MS) room_end(COOP_NOTE_NO_ROOM);
return;
}
// the owner changed: the host left and Steam picked another member
uint64_t owner = G.net->room_owner();
if (owner && owner != G.owner) {
G.owner = owner;
if (hosting() && G.welcomed) {
rt_log("coop: the host left; this game is the host now");
send_roster();
}
}
if (!G.welcomed) {
if (now - G.entered_at > HOST_WAIT_MS) {
rt_log("coop: the room's host did not answer");
room_end(COOP_NOTE_HOST_SILENT);
} else if (now - G.hello_at >= HELLO_EVERY_MS) {
uint8_t d[6];
uint16_t proto = COOP_PROTOCOL;
uint32_t build = GAME_BUILD;
memcpy(d, &proto, 2), memcpy(d + 2, &build, 4);
send_kind(G.owner, K_HELLO, d, sizeof d, 1);
G.hello_at = now;
}
return;
}
if (hosting() && now - G.roster_at >= ROSTER_EVERY_MS) send_roster();
// a member Steam no longer lists is gone, whatever message was missed
uint64_t ids[STEAM_ROOM_MAX];
int nm = G.net->room_members(ids, STEAM_ROOM_MAX);
for (int i = G.n - 1; i >= 0; i--) {
int there = G.players[i].id == G.net->self();
for (int k = 0; k < nm; k++) there |= ids[k] == G.players[i].id;
if (!there) {
player_remove(G.players[i].id);
if (hosting()) send_roster();
}
}
for (int i = 0; i < G.n; i++) name_player(&G.players[i]);
// this game's own pose
plat_mutex_lock(&P.lock);
int has = P.has_pose;
CoopPose pose = P.pose;
plat_mutex_unlock(&P.lock);
if (!has) memset(&pose, 0, sizeof pose);
G.own_has = has, G.own_pose = pose;
// NX2NAVI_COOP_TRACE=1 (tests, environment only): every two seconds where this game's Link is and where it has the others
static int trace = -1;
static uint64_t traced_at;
if (trace < 0) {
char v[8];
trace = plat_getenv("NX2NAVI_COOP_TRACE", v, sizeof v) && v[0] == '1';
}
if (trace && now - traced_at >= 2000) {
traced_at = now;
rt_log("coop: trace: own %s %.1f %.1f %.1f yaw %.2f; %d in the room", has ? pose.scene : "(not in the world)", pose.pos[0],
pose.pos[1], pose.pos[2], pose.yaw, G.n);
for (int i = 0; i < G.n; i++) {
const Player *p = &G.players[i];
if (p->id == G.net->self()) continue;
rt_log("coop: trace: %s %s %.1f %.1f %.1f, %llu ms ago", p->name, p->has_pose ? p->pose.scene : "(no pose)", p->pose.pos[0],
p->pose.pos[1], p->pose.pos[2], (unsigned long long)(p->has_pose ? now - p->pose_at : 0));
}
}
if (now - G.pose_sent_at >= (uint64_t)(has ? POSE_EVERY_MS : POSE_IDLE_MS)) {
uint8_t d[POSE_BYTES + COOP_SCENE_CAP];
size_t n = pose_put(d, ++G.pose_number, &pose);
send_listed(K_POSE, d, n, 0);
G.pose_sent_at = now;
}
}
static void drain_outbox(void) {
static Out batch[OUTBOX];
plat_mutex_lock(&P.lock);
int n = P.nout;
if (n) memcpy(batch, P.out, sizeof batch[0] * (size_t)n);
P.nout = 0;
plat_mutex_unlock(&P.lock);
for (int i = 0; i < n && G.welcomed; i++) {
if (!batch[i].to) {
for (int k = 0; k < G.n; k++)
if (G.players[k].id != G.net->self()) G.net->send(G.players[k].id, batch[i].bytes, batch[i].n, batch[i].reliable);
} else if (player_of(batch[i].to)) {
G.net->send(batch[i].to, batch[i].bytes, batch[i].n, batch[i].reliable);
}
}
}
static void publish(uint64_t now) {
static CoopView v;
memset(&v, 0, sizeof v);
v.state = G.state, v.note = G.note;
snprintf(v.steam_says, sizeof v.steam_says, "%s", G.steam_says);
v.local = G.net == &coop_net_local;
if (G.up && G.room && G.welcomed) {
if (v.local) snprintf(v.code, sizeof v.code, "%llu", (unsigned long long)G.room);
else steam_code_make(G.room, v.code);
v.host = (uint8_t)hosting();
v.overlay = (uint8_t)(!v.local && steam_overlay());
for (int i = 0; i < G.n; i++) {
CoopPlayer *o = &v.players[v.n++];
const Player *p = &G.players[i];
o->id = p->id;
snprintf(o->name, sizeof o->name, "%s", p->name);
o->self = p->id == G.net->self(), o->host = p->id == G.owner;
if (o->self) {
o->has_pose = (uint8_t)G.own_has, o->pose = G.own_pose;
} else {
o->has_pose = (uint8_t)(p->has_pose && now - p->pose_at < POSE_STALE_MS);
o->pose_ms = o->has_pose ? (uint32_t)(now - p->pose_at) : 0;
o->pose = p->pose;
}
}
}
if (G.invite_room) {
v.invite_room = G.invite_room;
G.net->name_of(G.invite_from, v.invite_from, sizeof v.invite_from);
clean_text(v.invite_from);
}
v.nchat = G.nchat;
memcpy(v.chat, G.chat, sizeof G.chat[0] * (size_t)G.nchat);
v.friends_serial = G.friends_serial;
plat_mutex_lock(&P.lock);
if (memcmp(&P.view, &v, sizeof v)) {
P.view = v;
__atomic_add_fetch(&P.serial, 1, __ATOMIC_RELEASE);
}
P.in_room = G.welcomed;
plat_mutex_unlock(&P.lock);
}
static const CoopNet net_steam = {steam_start, steam_stop, steam_self, steam_name_of, steam_room_create, steam_room_join,
steam_room_leave, steam_room, steam_room_owner, steam_room_members, steam_room_set,
steam_room_get, steam_send, steam_pump};
static void net_down(void) {
if (!G.up) return;
room_end(COOP_NOTE_NONE);
G.net->stop();
G.up = 0;
rt_log("coop: off");
}
static void coop_main(void *arg) {
(void)arg;
unsigned cfg_seen = ~0u;
int on = 0;
while (!__atomic_load_n(&P.stop, __ATOMIC_ACQUIRE)) {
uint64_t now = plat_now_ms();
unsigned v = cfg_version();
if (v != cfg_seen) cfg_seen = v, on = cfg_bool("NX2NAVI_COOP_STEAM") && RT_V111;
if (!on) {
net_down();
if (G.state != COOP_OFF) G.state = COOP_OFF, G.note = COOP_NOTE_NONE, publish(now);
plat_sleep_ms(200);
continue;
}
// commands, also while Steam is not up: Retry is one
Cmd cmds[COMMANDS];
plat_mutex_lock(&P.lock);
int nc = P.ncmd;
memcpy(cmds, P.cmd, sizeof cmds[0] * (size_t)nc);
P.ncmd = 0;
plat_mutex_unlock(&P.lock);
for (int i = 0; i < nc; i++) run_command(&cmds[i]);
if (!G.up) {
if (now >= G.retry_at) {
G.net = coop_local_wanted() ? &coop_net_local : &net_steam;
int which = 0;
char why[160] = "";
if (G.net->start(why, sizeof why, &which)) {
G.up = 1, G.state = COOP_READY, G.note = COOP_NOTE_NONE, G.steam_says[0] = 0;
rt_log("coop: on%s", G.net == &coop_net_local ? " (the test stand-in for Steam)" : ", signed in to Steam as app 480");
if (G.net == &coop_net_local) {
if (coop_local_join()) run_command(&(Cmd){.kind = C_JOIN, .arg = coop_local_join()});
else if (coop_local_makes()) run_command(&(Cmd){.kind = C_CREATE});
}
} else {
CoopNote note = which == STEAM_WHY_NO_LIBRARY ? COOP_NOTE_NO_LIBRARY : which == STEAM_WHY_OLD_LIBRARY ? COOP_NOTE_OLD_LIBRARY
: which == STEAM_WHY_OTHER_OS ? COOP_NOTE_OTHER_OS : COOP_NOTE_NO_CLIENT;
if (G.state != COOP_NO_STEAM || G.note != note) rt_log("coop: Steam is not available: %s", why);
G.state = COOP_NO_STEAM, G.note = note;
snprintf(G.steam_says, sizeof G.steam_says, "%s", why);
G.retry_at = now + STEAM_RETRY_MS;
}
}
publish(now);
plat_sleep_ms(G.up ? STEP_MS : 100);
continue;
}
G.net->pump(on_event, NULL);
tick(now);
drain_outbox();
publish(now);
plat_sleep_ms(STEP_MS);
}
net_down();
plat_event_set(&P.stopped);
}
// ---- for the other threads
static int started;
void coop_init(void) {
plat_mutex_init(&P.lock);
plat_event_init(&P.stopped, 1, 0);
P.out = calloc(OUTBOX, sizeof *P.out);
if (!P.out || !plat_thread_spawn(coop_main, NULL, "coop", 0)) {
rt_log("coop: cannot start the co-op thread");
return;
}
started = 1;
}
void coop_shutdown(void) {
if (!started) return;
started = 0;
__atomic_store_n(&P.stop, 1, __ATOMIC_RELEASE);
plat_event_wait_ns(&P.stopped, 1500ull * 1000000); // leaving a lobby is one call to Steam; do not hold the exit for it
}
uint32_t coop_serial(void) { return __atomic_load_n(&P.serial, __ATOMIC_ACQUIRE); }
void coop_view(CoopView *out) {
if (!started) {
memset(out, 0, sizeof *out);
return;
}
plat_mutex_lock(&P.lock);
*out = P.view;
plat_mutex_unlock(&P.lock);
}
static void command(CmdKind kind, uint64_t arg, const char *text) {
if (!started) return;
plat_mutex_lock(&P.lock);
if (P.ncmd < COMMANDS) {
Cmd *c = &P.cmd[P.ncmd++];
memset(c, 0, sizeof *c);
c->kind = kind, c->arg = arg;
if (text) snprintf(c->text, sizeof c->text, "%s", text);
}
plat_mutex_unlock(&P.lock);
}
void coop_create(void) { command(C_CREATE, 0, NULL); }
int coop_join(const char *code) {
uint64_t room = steam_code_parse(code);
if (!room) return 0;
command(C_JOIN, room, NULL);
return 1;
}
void coop_join_invite(void) { command(C_JOIN_INVITE, 0, NULL); }
void coop_decline_invite(void) { command(C_DECLINE, 0, NULL); }
void coop_leave(void) { command(C_LEAVE, 0, NULL); }
void coop_retry(void) { command(C_RETRY, 0, NULL); }
void coop_invite(uint64_t friend_id) { command(C_INVITE, friend_id, NULL); }
void coop_invite_window(void) { command(C_INVITE_WINDOW, 0, NULL); }
void coop_remove(uint64_t player_id) { command(C_REMOVE, player_id, NULL); }
void coop_chat(const char *text) { command(C_CHAT, 0, text); }
void coop_friends_refresh(void) { command(C_FRIENDS, 0, NULL); }
int coop_friends(SteamFriend *out, int max) {
if (!started) return 0;
plat_mutex_lock(&P.lock);
int n = P.nfriends < max ? P.nfriends : max;
memcpy(out, P.friends, sizeof out[0] * (size_t)n);
plat_mutex_unlock(&P.lock);
return n;
}
void coop_pose_set(const CoopPose *pose) {
if (!started) return;
plat_mutex_lock(&P.lock);
P.has_pose = pose != NULL;
if (pose) P.pose = *pose;
plat_mutex_unlock(&P.lock);
}
int coop_post(uint64_t to, uint8_t kind, const void *data, size_t n, int reliable) {
if (!started || kind < COOP_GAME_KIND || n > COOP_MESSAGE_MAX) return 0;
int ok = 0;
plat_mutex_lock(&P.lock);
if (P.in_room && P.nout < OUTBOX) {
Out *o = &P.out[P.nout++];
o->to = to, o->n = (uint16_t)(n + 1), o->reliable = (uint8_t)reliable;
o->bytes[0] = kind;
if (n) memcpy(o->bytes + 1, data, n);
ok = 1;
}
plat_mutex_unlock(&P.lock);
return ok;
}

View File

@@ -1,124 +0,0 @@
// Co-op (coop.c): each player runs their own game; a room connects up to four of them through Steam (steam.h). The
// room is a Steam lobby, its maker's game is the host, and the games send each other where their Link is, chat lines
// and what the game layer shares (coop_game.c). docs/coop.md is the players' and the reviewers' description.
//
// One host thread (the co-op thread) owns Steam and the room. The menu and the game's thread never wait for it: they
// read the view it publishes at each step and hand it commands it carries out at its next one.
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "steam.h"
#ifdef __cplusplus
extern "C" {
#endif
enum {
COOP_PROTOCOL = 1, // games of another number do not play together
COOP_PLAYERS = 4,
COOP_NAME_CAP = STEAM_NAME_CAP,
COOP_SCENE_CAP = 48,
COOP_CHAT_CAP = 200, // bytes of a chat line, UTF-8
COOP_CHAT_LINES = 8,
COOP_FRIENDS = 64,
COOP_GAME_KIND = 16, // message kinds from here on belong to the game layer (coop_game.c)
COOP_MESSAGE_MAX = STEAM_MESSAGE_MAX - 1, // bytes of a message after its kind
};
typedef enum {
COOP_OFF, // the setting is off: no thread work, Steam untouched
COOP_NO_STEAM, // on, but Steam is not there (note says why); tried again every few seconds and at coop_retry
COOP_READY, // Steam is up, in no room
COOP_ENTERING, // making or joining a room, or waiting for its host to answer
COOP_IN_ROOM,
} CoopState;
// Why the last attempt ended, for the menu's status line (ui/coop_page.cpp has the texts).
typedef enum {
COOP_NOTE_NONE,
COOP_NOTE_NO_LIBRARY, COOP_NOTE_OLD_LIBRARY, COOP_NOTE_NO_CLIENT, COOP_NOTE_OTHER_OS,
COOP_NOTE_CREATE_FAILED, COOP_NOTE_NO_ROOM, COOP_NOTE_FULL, COOP_NOTE_REFUSED, COOP_NOTE_NOT_OURS,
COOP_NOTE_OTHER_VERSION, COOP_NOTE_REMOVED, COOP_NOTE_HOST_SILENT, COOP_NOTE_LOST, COOP_NOTE_BAD_CODE,
COOP_NOTE_LEFT,
} CoopNote;
// Where a player's Link is, as their game last said.
enum { COOP_POSE_ADULT = 1, COOP_POSE_PAUSED = 2 };
typedef struct {
float pos[3]; // metres, the game's world
float vel[3]; // metres a second
float yaw; // radians about the up axis, the way Link faces
uint8_t flags; // COOP_POSE_*
char scene[COOP_SCENE_CAP]; // the area's name as the game has it; "": not in the world (title screen, loading)
} CoopPose;
typedef struct {
uint64_t id;
char name[COOP_NAME_CAP];
uint8_t self, host;
uint8_t has_pose;
uint32_t pose_ms; // how long ago the pose arrived
CoopPose pose;
} CoopPlayer;
typedef struct {
char name[COOP_NAME_CAP];
char text[COOP_CHAT_CAP + 1];
uint64_t at_ms; // plat_now_ms when it arrived
uint8_t notice; // a line of the room itself ("... joined"): name holds the player, text is empty
uint8_t joined; // for a notice: 1 joined, 0 left
} CoopChatLine;
typedef struct {
CoopState state;
CoopNote note;
char steam_says[160]; // with COOP_NO_STEAM: the Steam layer's own sentence, for the log's reader
char code[STEAM_CODE_CAP]; // the room's id, "" outside a room
uint8_t host; // this game is the room's host
uint8_t overlay; // Steam's own invite window can be shown
uint8_t local; // the test stand-in for Steam is in use (two games on one PC)
int n;
CoopPlayer players[COOP_PLAYERS];
uint64_t invite_room; // a friend invites this player to a room (0 none) ...
char invite_from[COOP_NAME_CAP];
int nchat;
CoopChatLine chat[COOP_CHAT_LINES]; // oldest first
uint32_t friends_serial; // changes when coop_friends has a new list
} CoopView;
void coop_init(void); // starts the co-op thread; it idles while the COOP setting is off
void coop_shutdown(void); // leaves the room and signs out of Steam, before the process ends
void coop_view(CoopView *out);
uint32_t coop_serial(void); // changes whenever the view does: a reader that keeps a copy compares this first
// Commands, from any thread; each is carried out at the co-op thread's next step and none waits.
void coop_create(void);
int coop_join(const char *code); // 0: the text is no room id (nothing is asked of Steam)
void coop_join_invite(void); // the room of the invite the view shows
void coop_decline_invite(void);
void coop_leave(void);
void coop_retry(void); // look for Steam again now
void coop_invite(uint64_t friend_id);
void coop_invite_window(void);
void coop_remove(uint64_t player_id); // the host's: that player is out of the room and stays out
void coop_chat(const char *text);
void coop_friends_refresh(void);
int coop_friends(SteamFriend *out, int max); // the list of the last refresh
// ---- for the game layer (coop_game.c)
void coop_pose_set(const CoopPose *pose); // this game's own Link, each frame he is in the world; NULL when he is not
// A message of the game layer to everyone in the room (to 0) or to one player; kind from COOP_GAME_KIND on, n at most
// COOP_MESSAGE_MAX. From any thread; it leaves at the co-op thread's next step. 0 outside a room.
int coop_post(uint64_t to, uint8_t kind, const void *data, size_t n, int reliable);
// coop_game.c's part, called on the co-op thread: a message of its kinds from a player of the room, and a player who
// came (the game layer sends that player what it shares) or went.
void coop_game_message(uint64_t from, uint8_t kind, const uint8_t *data, size_t n);
void coop_game_joined(uint64_t id);
void coop_game_room(int in_room);
#ifdef __cplusplus
}
#endif

View File

@@ -1,702 +0,0 @@
// Co-op, the game side (coop_game.h), for Ocarina 1.1.1: where this game's Link is, for the others, and the progress
// the players of a room share. It runs on the game's thread between two frames (coop_present, at the present) and
// talks to the room through coop.h; what the room sends arrives on the co-op thread and waits in an inbox.
//
// Link. The Player actor is [[main+0x4e371d0] + 0x480] while its name, [+0x20], reads "Player": its position in metres
// at +0x31c, its rotation as a 3x3 matrix at +0x328. The area is the game's text flag Sequence_CurrentBanc
// (debug_tools.c dbg_area). A pose goes out only while a save is being played (gate below): on the title screen and
// while an area loads the others see no Link of this game.
//
// The flag database. The game keeps its progress in one manager, *(u64 *)(main+0x4e842a8), as typed containers of 0x60
// bytes from +8: Bool at +0x008, Int at +0x0c8, UInt at +0x788. A container holds its entry count (+0x08), entries
// (+0x10), an open-addressing table of {u32 hash, u32 entry} slots probed from hash % capacity (+0x18, capacity +0x24) and a
// ring of pending sets (+0x28 capacity, +0x30 slots, +0x38 counter, its low 20 bits the count). A Bool entry is 0x18 bytes
// (+0x08 the reset kinds, +0x10 the save file, -1 none, +0x15 default, +0x16 current value), an Int or UInt entry 0x28
// (+0x08, +0x10 the same, +0x18 default, +0x1c current). Structs group flags: the struct table (+0xc10 count, +0xc18
// entries of 0x20, +0xc20 slots, +0xc2c capacity) maps a struct's hash to an entry whose member table (+0x08, capacity +0x14)
// holds {u32 member hash, u32 flag or struct hash} slots. Flags are named by MurmurHash3 of their names; the names stay out
// of this file, the hashes it needs are numbers below.
//
// Writes go through the game's own set routines, SetBool (main+0x682b20) and SetInt (main+0x163b70), with x0 the manager,
// x1 the value and x2 the hash: they queue the change on the ring and the game's per-frame drain writes the current and
// saved values and its own bookkeeping, as for a change the game made. Reads are of the entries' current values.
//
// What is shared (docs/coop.md has the reasons), each value only ever raised:
// - progress: every Bool that goes to progress.sav (save file 0) and is reset only by a new game or a load (reset kinds 8,
// 16 and 32; flags with kind 1 or 256 revert at scene changes, 2 at a new day, 4 are options), except the heart
// rewards below. A flag counts as 1 once it differs from its default (63 of them start true and count down), and a
// flag anyone has at 1 becomes 1 for everyone. Story, world and dungeon flags are one kind: the game's flags carry
// no mark of which is which.
// - items, songs and quest items: the songs' and the items' "got it once" markers, the item counts of the pouch struct
// (except the lists below), the capacity struct (wallet, bag and quiver sizes) and the magic meter's size; the
// highest count wins.
// - per player always: small keys, rupees and ammunition (counters the game spends: a highest-count merge would hand
// back what was spent), the trade sequence, rented masks, the knife that breaks and amiibo items (the game takes
// them away again), heart pieces, gold skulltula tokens and the 11 heart reward flags (their pickups are flags of
// single objects this layer does not write, so a shared count would pay a piece twice); life, magic, bottle
// contents, the equipment worn and the time of day.
//
// The messages (kinds from COOP_GAME_KIND, reliable): FLAGS is u32 schema and up to 140 pairs of u32 hash and u32
// value, sent to everyone when a value rises here and to one player as the parts of this game's whole state; ASK is
// u32 schema, "send me your whole state", sent when this game starts to share (a save is played in a room) and once
// more a few seconds later, since a player who joined a moment ago may not be on every game's list yet. The schema
// is a sum over this file's table (every shared hash with its type and limit): games whose tables differ do not
// merge. A value from the room is checked against the table before it is kept: the flag must be a shared one, a
// Bool's value 1, a count at most 999; anything else is dropped and counted in the log.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cfg.h"
#include "coop.h"
#include "coop_game.h"
#include "cpu.h"
#include "debug_tools.h"
#include "fs.h"
#include "host.h"
#include "layout.h"
#include "platform/platform.h"
#define MGR_PTR (MOD_MAIN_BASE + 0x4e842a8ull)
#define SET_BOOL_FN (MOD_MAIN_BASE + 0x682b20ull)
#define SET_INT_FN (MOD_MAIN_BASE + 0x163b70ull)
#define PLAYER_PTR (MOD_MAIN_BASE + 0x4e371d0ull)
enum {
C_BOOL = 0x008, C_INT = 0x0c8, C_UINT = 0x788,
CN_COUNT = 0x08, CN_ENTRIES = 0x10, CN_TABLE = 0x18, CN_CAP = 0x24,
BOOL_SIZE = 0x18, INT_SIZE = 0x28,
E_RESET = 0x08, E_FILE = 0x10, B_DEFAULT = 0x15, B_CURRENT = 0x16, I_CURRENT = 0x1c,
ST_COUNT = 0xc10, ST_ENTRIES = 0xc18, ST_TABLE = 0xc20, ST_CAP = 0xc2c, ST_SIZE = 0x20, STE_MEMBERS = 0x08, STE_MCAP = 0x14,
MGR_SIZE = 0xd80,
RESET_NEW_GAME = 8 | 16 | 32, RESET_TEMPORARY = 1 | 2 | 4 | 256,
SLICES = 4, // a quarter of the flags is read each frame: every flag every 4 frames
APPLY_PER_FRAME = 16,
INT_MAX_ITEM = 999, // the highest item count the room may set: the game's counters show three digits
CLOCK_MS = 2500, // the game clock advanced this recently: the game is being played
K_FLAGS = COOP_GAME_KIND, K_ASK,
PAIRS_PER_MESSAGE = 140,
INBOX = 16384, // pairs waiting for the game's thread
JOBS = 8,
PARTS_PER_FRAME = 4, // of a whole state on its way to one player
ASK_AGAIN_MS = 6000,
SAVE_COPIES = 12,
};
// Struct and member hashes (MurmurHash3 of the names the game uses).
#define S_POUCH 0x3da094e3u // item counts, one struct per item
#define M_STOCK 0x22344481u // an item's count
#define S_FIRST_GET 0xade0ef78u // "got it once" markers, one per item
#define S_DUNGEON 0xf5a32cdcu // one struct per dungeon: map, compass, boss key, small keys
#define M_SMALL_KEYS 0x1af87831u
#define S_CAPACITY 0xf80f8077u // wallet, bomb bag, quiver, seed bag, stick and nut capacities
#define F_RUPEES 0xa77921d7u
#define F_MAGIC_SIZE 0x12d63a97u
#define F_PLAY_CLOCK 0xe53eb6d1u // UInt: seconds played, advanced while the game runs (on the title screen too)
#define F_LOADING 0xf5deef0au // Bool: a save is being loaded
// Scene changes in progress (Bool, not saved): nothing is read or written while one is set.
static const uint32_t transition_flags[] = {0x9a9506e7, 0xf8633c7f, 0xf96989b6, 0xe19dfdd6};
static const uint32_t heart_reward_flags[] = {0x6b8fc751, 0x1d1793e9, 0xb5127e75, 0xe41e1597, 0x98ca7aab, 0xf1891f6e,
0x3f43245b, 0x1657d7d8, 0xa666baa8, 0x5ff7aa30, 0xf2fab510};
// Item counts that stay with each player: what the game takes away again, heart pieces and skulltula tokens.
static const uint32_t own_counts[] = {0x07f10aaf, 0x0165e7ca, 0x51d89ef0, 0x07de3e6f, 0x58c9bc78, 0xa862d276, 0x2815c82a,
0x897cf7eb, 0x919ea324, 0x5c41a6b1, 0xded8e8d3, 0x24596e8e, 0xb6ca6093, 0x6be5c3b0,
0x7e607033, 0x0e94a8df, 0xfc508da7, 0xb5c10899, 0x47b2d775, 0xf046629e, 0x96459cd3,
0x924e9a46, 0xf5e647da, 0x486c59a4, 0x49d1c374, 0x20820479, 0x396a5c02, 0x8d02f5ea,
0x600e29eb, 0x51ec97b3, 0x04735978};
// Ammunition counts: spent by the game, so per player.
static const uint32_t ammo_counts[] = {0xdb1bcd4f, 0xdf7c517a, 0x518ec74b, 0xf30d9f54, 0x5fadf7fc, 0xb9494411, 0xb003124d};
static int in_list(const uint32_t *list, size_t n, uint32_t h) {
for (size_t i = 0; i < n; i++)
if (list[i] == h) return 1;
return 0;
}
#define IN(list, h) in_list(list, sizeof list / sizeof list[0], h)
typedef struct {
uint32_t hash;
uint8_t is_int, inv;
uint8_t pending; // want is above the game's value: on the list of flags to set
uint32_t max; // the highest value the room may set: 1 for a Bool, INT_MAX_ITEM for a count
int32_t last; // the raw value last read
uint32_t sent; // the value the room last heard from this game
uint32_t want; // the highest value the room has sent
uint64_t addr; // the entry
} GFlag;
// A set of hashes (open addressing, 0 empty), for the struct memberships while the table is built.
typedef struct { uint32_t *h; unsigned cap; } HSet;
static void hset_add(HSet *s, uint32_t h) {
if (!h || !s->h) return;
unsigned i = h & (s->cap - 1);
while (s->h[i] && s->h[i] != h) i = (i + 1) & (s->cap - 1);
s->h[i] = h;
}
static int hset_has(const HSet *s, uint32_t h) {
if (!h || !s->h) return 0;
unsigned i = h & (s->cap - 1);
while (s->h[i]) {
if (s->h[i] == h) return 1;
i = (i + 1) & (s->cap - 1);
}
return 0;
}
typedef struct { uint32_t hash, value; } Pair;
typedef struct { uint64_t to; uint64_t at; int next; int live; } Job; // this game's whole state on its way to one player
// The game thread's state.
static struct {
unsigned cfg_seen;
int on, share, said_version;
// the table
uint64_t mgr, bool_entries, int_entries;
int bound;
GFlag *flags;
int nflags, cap;
int *by_hash;
uint32_t schema;
int slice;
int *todo; // indices of flags with pending set
int ntodo;
// the gate
uint64_t gate_mgr, clock_entry, loading_entry, transition_entry[4];
uint32_t clock;
uint64_t clock_at;
int titles, loaded, player, gate;
// the room
int sharing;
uint32_t room_epoch; // X.room_epoch when sharing started: another room since starts it again
int asks_left; // ASK messages still to send, the next at ask_at
uint64_t ask_at;
Job jobs[JOBS];
uint32_t refused, applied;
uint64_t log_at;
// the pose
float last_pos[3];
uint64_t last_pos_at;
int posed;
} G;
// What the co-op thread hands over.
static struct {
PlatMutex lock;
volatile int32_t room; // in a room (coop_game_room)
volatile uint32_t room_epoch; // counts the rooms entered
volatile int32_t on; // the COOP setting, for coop_game_rom_open on the game's file threads
volatile int32_t save_copied; // the save was copied for this room: values may be set
volatile int32_t titles; // the title screen's starts (coop_game_rom_open)
int n;
Pair *pairs; // INBOX of them
int overflow; // pairs were dropped: ask for the whole state again
int njoined, nasked;
uint64_t joined[JOBS], asked[JOBS];
uint32_t schema; // the table's, for the co-op thread's check of a message; 0 while there is none
uint32_t other_schema; // messages with another schema arrived (logged by the game thread)
} X;
static int rd_ok(uint64_t a, uint64_t n) { return a >= 0x1000 && mem_readable(a, n); }
// The entry of hash in the container at base (stride bytes per entry), 0 when absent.
static uint64_t entry_of(uint64_t mgr, unsigned base, unsigned stride, uint32_t hash) {
uint64_t c = mgr + base, table = LD64(c + CN_TABLE), entries = LD64(c + CN_ENTRIES);
uint32_t cap = LD32(c + CN_CAP), count = LD32(c + CN_COUNT);
if (!hash || !cap || !table || !entries) return 0;
for (uint32_t i = hash % cap, k = 0; k < cap; k++, i = i + 1 == cap ? 0 : i + 1) {
uint32_t h = LD32(table + 8ull * i);
if (h == hash) {
uint32_t idx = LD32(table + 8ull * i + 4);
return entries + (uint64_t)(idx < count ? idx : 0) * stride;
}
if (!h) return 0;
}
return 0;
}
static uint64_t struct_of(uint64_t mgr, uint32_t hash) {
uint64_t table = LD64(mgr + ST_TABLE), entries = LD64(mgr + ST_ENTRIES);
uint32_t cap = LD32(mgr + ST_CAP), count = LD32(mgr + ST_COUNT);
if (!cap || !table || !entries || !rd_ok(table, 8ull * cap)) return 0;
for (uint32_t i = hash % cap, k = 0; k < cap; k++, i = i + 1 == cap ? 0 : i + 1) {
uint32_t h = LD32(table + 8ull * i);
if (h == hash) {
uint32_t idx = LD32(table + 8ull * i + 4);
uint64_t e = entries + (uint64_t)(idx < count ? idx : 0) * ST_SIZE;
return rd_ok(e, ST_SIZE) ? e : 0;
}
if (!h) return 0;
}
return 0;
}
// fn(member hash, flag or struct hash, user) for each member of struct entry e.
static void members(uint64_t e, void (*fn)(uint32_t m, uint32_t v, void *u), void *u) {
uint64_t t = LD64(e + STE_MEMBERS);
uint32_t cap = LD32(e + STE_MCAP);
if (!t || !cap || cap > 65536 || !rd_ok(t, 8ull * cap)) return;
for (uint32_t i = 0; i < cap; i++) {
uint32_t m = LD32(t + 8ull * i);
if (m) fn(m, LD32(t + 8ull * i + 4), u);
}
}
typedef struct { uint64_t mgr; HSet *set; uint32_t want; } Walk;
static void add_member(uint32_t m, uint32_t v, void *u) { (void)m, hset_add(((Walk *)u)->set, v); }
static void pick(uint32_t m, uint32_t v, void *u) {
Walk *w = u;
if (m == w->want) hset_add(w->set, v);
}
// A struct of structs: the flag of member want in each.
static void add_nested(uint32_t m, uint32_t v, void *u) {
(void)m;
Walk *w = u;
uint64_t e = struct_of(w->mgr, v);
if (e) members(e, pick, w);
}
static GFlag *add_flag(void) {
if (G.nflags == G.cap) {
int nc = G.cap ? G.cap * 2 : 4096;
GFlag *nf = realloc(G.flags, (size_t)nc * sizeof *nf);
if (!nf) return NULL;
G.flags = nf, G.cap = nc;
}
GFlag *f = &G.flags[G.nflags++];
memset(f, 0, sizeof *f);
return f;
}
static int cmp_by_hash(const void *a, const void *b) {
uint32_t x = G.flags[*(const int *)a].hash, y = G.flags[*(const int *)b].hash;
return x < y ? -1 : x > y;
}
// The table of the manager's shared flags (the header comment's rules). 0 when the database is not readable.
static int build_table(uint64_t mgr) {
G.nflags = 0;
HSet first_get = {0}, pouch = {0}, keys = {0}, capacity = {0};
HSet *sets[] = {&first_get, &pouch, &keys, &capacity};
for (int i = 0; i < 4; i++) {
sets[i]->cap = 1024;
sets[i]->h = calloc(sets[i]->cap, sizeof *sets[i]->h);
}
uint64_t e;
Walk w = {mgr, &first_get, 0};
if ((e = struct_of(mgr, S_FIRST_GET))) members(e, add_member, &w);
w.set = &pouch, w.want = M_STOCK;
if ((e = struct_of(mgr, S_POUCH))) members(e, add_nested, &w);
w.set = &keys, w.want = M_SMALL_KEYS;
if ((e = struct_of(mgr, S_DUNGEON))) members(e, add_nested, &w);
w.set = &capacity;
if ((e = struct_of(mgr, S_CAPACITY))) members(e, add_member, &w);
for (int type = 0; type < 2; type++) {
unsigned base = type ? C_INT : C_BOOL, stride = type ? INT_SIZE : BOOL_SIZE;
uint64_t c = mgr + base, table = LD64(c + CN_TABLE), entries = LD64(c + CN_ENTRIES);
uint32_t cap = LD32(c + CN_CAP), count = LD32(c + CN_COUNT);
if (!cap || !count || count > 1000000 || !rd_ok(table, 8ull * cap) || !rd_ok(entries, (uint64_t)count * stride)) continue;
for (uint32_t i = 0; i < cap; i++) {
uint32_t h = LD32(table + 8ull * i), idx = LD32(table + 8ull * i + 4);
if (!h || idx >= count) continue;
uint64_t a = entries + (uint64_t)idx * stride;
uint32_t reset = LD32(a + E_RESET);
int32_t file = (int32_t)LD32(a + E_FILE);
uint8_t inv = 0;
if (!type) {
if (file != 0 || reset & RESET_TEMPORARY || !(reset & RESET_NEW_GAME) || IN(heart_reward_flags, h)) continue;
inv = LD8(a + B_DEFAULT) != 0;
} else if (h == F_RUPEES || hset_has(&keys, h)) {
continue;
} else if (hset_has(&pouch, h)) {
if (IN(own_counts, h) || IN(ammo_counts, h)) continue;
} else if (!hset_has(&capacity, h) && h != F_MAGIC_SIZE) {
continue;
}
GFlag *f = add_flag();
if (!f) break;
f->hash = h, f->is_int = (uint8_t)type, f->inv = inv, f->addr = a;
f->max = type ? INT_MAX_ITEM : 1;
}
}
for (int i = 0; i < 4; i++) free(sets[i]->h);
free(G.by_hash), free(G.todo);
G.by_hash = malloc((size_t)G.nflags * sizeof *G.by_hash);
G.todo = malloc((size_t)G.nflags * sizeof *G.todo);
G.ntodo = 0;
if (!G.by_hash || !G.todo) return 0;
for (int i = 0; i < G.nflags; i++) G.by_hash[i] = i;
qsort(G.by_hash, (size_t)G.nflags, sizeof *G.by_hash, cmp_by_hash);
// the schema: this layer's version, the game's, and the table (every hash with its type and limit), so that two
// builds that share or limit differently do not merge
uint64_t h = 0xcbf29ce484222325ull;
for (const char *p = "nx2navi-coop-share/1"; *p; p++) h = (h ^ (uint8_t)*p) * 0x100000001b3ull;
h = (h ^ (uint64_t)rt_game_version) * 0x100000001b3ull;
for (int i = 0; i < G.nflags; i++) {
const GFlag *f = &G.flags[G.by_hash[i]];
uint64_t row[2] = {f->hash | (uint64_t)f->is_int << 40, f->max};
for (int k = 0; k < 16; k++) h = (h ^ (uint8_t)(row[k / 8] >> 8 * (k % 8))) * 0x100000001b3ull;
}
G.schema = (uint32_t)(h ^ h >> 32);
if (!G.schema) G.schema = 1;
return G.nflags > 0;
}
static int32_t raw_of(const GFlag *f) { return f->is_int ? (int32_t)LD32(f->addr + I_CURRENT) : LD8(f->addr + B_CURRENT); }
static uint32_t value_of(const GFlag *f, int32_t raw) {
if (!f->is_int) return (raw != 0) != f->inv; // 1: differs from its default
return raw > 0 ? (uint32_t)raw : 0;
}
static int flag_index(uint32_t hash) {
int lo = 0, hi = G.nflags - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2, i = G.by_hash[mid];
if (G.flags[i].hash == hash) return i;
if (G.flags[i].hash < hash) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
// ---- the co-op thread's side
void coop_game_init(void) {
plat_mutex_init(&X.lock);
X.pairs = calloc(INBOX, sizeof *X.pairs);
}
void coop_game_rom_open(const char *path) {
// the title screen's event flow is opened each time the title screen starts: at boot and after the pause menu's
// Title Screen
if (__atomic_load_n(&X.on, __ATOMIC_RELAXED) && strstr(path, "/Event/EventFlow/TitleEvent.bfevfl")) plat_inc32(&X.titles);
}
// Before anything of a room reaches the save: a copy of it as it is, every slot. Slow (the whole save), so on a
// thread of its own, started when this game begins to share in a room (a save is played then: the game has its save
// storage open); values wait until the copy is there. arg: the room's count, so a copy that ends after the player
// went on to another room does not open that one.
static void copy_save(void *arg) {
uint32_t epoch = (uint32_t)(uintptr_t)arg;
char path[PLAT_PATH_MAX];
int ok = fs_save_snapshot("coop-backup", NULL, SAVE_COPIES, path, sizeof path);
if (ok && path[0]) rt_log("coop: the save as it was before this room is in %s", path);
else if (ok) rt_log("coop: nothing is saved yet, so there is no save to copy before this room");
else rt_log("coop: the save could not be copied; nothing of the room's progress is taken");
if (ok && epoch == __atomic_load_n(&X.room_epoch, __ATOMIC_ACQUIRE)) __atomic_store_n(&X.save_copied, 1, __ATOMIC_RELEASE);
}
void coop_game_room(int in_room) {
__atomic_store_n(&X.save_copied, 0, __ATOMIC_RELEASE);
plat_mutex_lock(&X.lock);
X.n = 0, X.overflow = 0, X.njoined = X.nasked = 0;
plat_mutex_unlock(&X.lock);
if (in_room) __atomic_add_fetch(&X.room_epoch, 1, __ATOMIC_RELEASE);
__atomic_store_n(&X.room, in_room, __ATOMIC_RELEASE);
}
void coop_game_joined(uint64_t id) {
plat_mutex_lock(&X.lock);
if (X.njoined < JOBS) X.joined[X.njoined++] = id;
plat_mutex_unlock(&X.lock);
}
void coop_game_message(uint64_t from, uint8_t kind, const uint8_t *data, size_t n) {
if (n < 4) return;
uint32_t schema;
memcpy(&schema, data, 4);
plat_mutex_lock(&X.lock);
if (X.schema && schema != X.schema) {
X.other_schema++;
} else if (kind == K_ASK && n == 4) {
if (X.nasked < JOBS) X.asked[X.nasked++] = from;
} else if (kind == K_FLAGS && (n - 4) % 8 == 0 && (n - 4) / 8 <= PAIRS_PER_MESSAGE) {
size_t count = (n - 4) / 8;
if (X.pairs && X.n + (int)count <= INBOX) {
memcpy(X.pairs + X.n, data + 4, count * 8);
X.n += (int)count;
} else {
X.overflow = 1;
}
}
plat_mutex_unlock(&X.lock);
}
// ---- the game's thread
// The table is the save's: another save, a load or the title screen ends it, and sharing with it.
static void unbind(void) {
G.bound = 0, G.sharing = 0, G.ntodo = 0; // the gate's own addresses stay: it reads through them this frame
memset(G.jobs, 0, sizeof G.jobs);
}
static void bind(uint64_t mgr) {
if (!build_table(mgr)) return;
G.mgr = mgr, G.bool_entries = LD64(mgr + C_BOOL + CN_ENTRIES), G.int_entries = LD64(mgr + C_INT + CN_ENTRIES);
for (int i = 0; i < G.nflags; i++) G.flags[i].last = raw_of(&G.flags[i]);
G.bound = 1, G.slice = 0;
plat_mutex_lock(&X.lock);
X.schema = G.schema;
plat_mutex_unlock(&X.lock);
rt_log("coop: a save is played: %d flags and counts can be shared", G.nflags);
}
static uint64_t player_actor(void) {
uint64_t m = rd_ok(PLAYER_PTR, 8) ? LD64(PLAYER_PTR) : 0, a = rd_ok(m + 0x480, 8) ? LD64(m + 0x480) : 0;
uint64_t name = rd_ok(a + 0x20, 8) ? LD64(a + 0x20) : 0;
if (!rd_ok(name, 7) || memcmp((const void *)(uintptr_t)name, "Player", 7) || !rd_ok(a + 0x31c, 12 + 36)) return 0;
return a;
}
// Link stands in the world: the Player actor exists away from the origin. There is none on the title screen at the
// start, so this holds everything back while the first load builds the world; after a return to the title screen the
// actor stays (the title count marks that).
static int player_in_world(float pos[3]) {
uint64_t a = player_actor();
if (!a) return 0;
memcpy(pos, (const void *)(uintptr_t)(a + 0x31c), 12);
return isfinite(pos[0]) && isfinite(pos[1]) && isfinite(pos[2]) && fabsf(pos[0]) + fabsf(pos[2]) >= 1.0f;
}
// The game is being played: a save was loaded since the title screen, Link stands in the world, the clock runs, no save
// is loading, no scene is changing. Notes a save change (unbind).
static int gate(uint64_t mgr, float pos[3]) {
if (mgr != G.gate_mgr || !G.clock_entry) { // the addresses of the few flags read every frame
G.gate_mgr = mgr;
G.clock_entry = entry_of(mgr, C_UINT, INT_SIZE, F_PLAY_CLOCK);
G.loading_entry = entry_of(mgr, C_BOOL, BOOL_SIZE, F_LOADING);
for (int i = 0; i < 4; i++) G.transition_entry[i] = entry_of(mgr, C_BOOL, BOOL_SIZE, transition_flags[i]);
}
if (!G.clock_entry || !rd_ok(G.clock_entry, INT_SIZE)) return 0;
uint64_t now = plat_now_ms();
int titles = __atomic_load_n(&X.titles, __ATOMIC_ACQUIRE);
if (titles != G.titles) {
G.titles = titles;
unbind();
G.loaded = 0;
}
uint32_t clock = LD32(G.clock_entry + I_CURRENT);
int loading = G.loading_entry && LD8(G.loading_entry + B_CURRENT);
unsigned moving = 0;
for (int i = 0; i < 4; i++) moving |= (unsigned)(G.transition_entry[i] && LD8(G.transition_entry[i] + B_CURRENT)) << i;
if (clock != G.clock) {
// the clock counts seconds one by one, on the title screen too; any other change is a save being loaded (a load,
// a new game, the same save again from where it was saved), which also sets the flags: play starts at the next
// tick after one
int tick = clock > G.clock && clock - G.clock <= 5;
if (!tick) unbind(), G.loaded = 1;
G.clock = clock;
G.clock_at = tick ? now : 0;
}
if (loading) unbind(), G.loaded = 1;
G.player = player_in_world(pos);
G.gate = G.loaded && G.player && !loading && !moving && G.clock_at && now - G.clock_at < CLOCK_MS;
return G.gate;
}
static void post_pose(const float pos[3], uint64_t now) {
CoopPose p;
memset(&p, 0, sizeof p);
memcpy(p.pos, pos, 12);
if (G.posed && now > G.last_pos_at && now - G.last_pos_at < 500) {
float dt = (float)(now - G.last_pos_at) / 1000.0f;
for (int i = 0; i < 3; i++) p.vel[i] = (pos[i] - G.last_pos[i]) / dt;
}
memcpy(G.last_pos, pos, 12), G.last_pos_at = now, G.posed = 1;
// the way Link faces, from his rotation's forward column; nothing draws by it yet
uint64_t a = player_actor();
float m[9];
if (a) {
memcpy(m, (const void *)(uintptr_t)(a + 0x328), sizeof m);
if (isfinite(m[2]) && isfinite(m[8])) p.yaw = atan2f(m[2], m[8]);
}
char area[64];
if (dbg_area(area)) snprintf(p.scene, sizeof p.scene, "%s", area);
coop_pose_set(&p);
}
static void set_flag(Cpu *c, uint64_t mgr, int is_int, uint32_t hash, int32_t value) {
rt_call(c, is_int ? SET_INT_FN : SET_BOOL_FN, 3, mgr, (uint64_t)(uint32_t)value, (uint64_t)hash);
}
static int post_pairs(uint64_t to, const Pair *pairs, int n) {
uint8_t d[4 + 8 * PAIRS_PER_MESSAGE];
memcpy(d, &G.schema, 4);
memcpy(d + 4, pairs, (size_t)n * 8);
return coop_post(to, K_FLAGS, d, 4 + (size_t)n * 8, 1);
}
// Reads a quarter of the flags; what changed and is above what the room last heard goes to everyone.
static void scan(void) {
int from = G.nflags * G.slice / SLICES, to = G.nflags * (G.slice + 1) / SLICES;
G.slice = (G.slice + 1) % SLICES;
Pair out[PAIRS_PER_MESSAGE];
int n = 0;
for (int i = from; i < to && n < PAIRS_PER_MESSAGE; i++) {
GFlag *f = &G.flags[i];
int32_t raw = raw_of(f);
if (raw == f->last) continue;
f->last = raw;
uint32_t v = value_of(f, raw);
if (v > f->max) v = f->max;
if (v > f->sent) out[n++] = (Pair){f->hash, v};
}
if (!n) return;
int sent = post_pairs(0, out, n);
for (int i = 0; i < n; i++) {
GFlag *f = &G.flags[flag_index(out[i].hash)];
if (sent) f->sent = out[i].value;
else f->last = INT32_MIN; // the room's queue is full: read as changed again at the next pass
}
}
// The inbox into the flags' wanted values.
static void take_inbox(void) {
static Pair batch[INBOX];
uint64_t joined[JOBS], asked[JOBS];
plat_mutex_lock(&X.lock);
int n = X.n, overflow = X.overflow, nj = X.njoined, na = X.nasked;
uint32_t other = X.other_schema;
memcpy(batch, X.pairs, (size_t)n * sizeof *batch);
memcpy(joined, X.joined, sizeof joined), memcpy(asked, X.asked, sizeof asked);
X.n = 0, X.overflow = 0, X.njoined = X.nasked = 0, X.other_schema = 0;
plat_mutex_unlock(&X.lock);
uint64_t now = plat_now_ms();
if (other) rt_log("coop: %u messages came from a game that shares other things than this one (another version); not taken", other);
for (int i = 0; i < n; i++) {
int k = flag_index(batch[i].hash);
GFlag *f = k >= 0 ? &G.flags[k] : NULL;
if (!f || !batch[i].value || batch[i].value > f->max) {
G.refused++;
continue;
}
if (batch[i].value > f->want) f->want = batch[i].value;
if (batch[i].value > f->sent) f->sent = batch[i].value; // the room has it: no need to say it again
if (!f->pending && f->want > value_of(f, raw_of(f))) f->pending = 1, G.todo[G.ntodo++] = k;
}
// a whole state for each player who asked, and (a little later, when it is on everyone's list) for each who came
for (int pass = 0; pass < 2; pass++) {
int count = pass ? nj : na;
const uint64_t *ids = pass ? joined : asked;
for (int i = 0; i < count; i++)
for (int j = 0; j < JOBS; j++)
if (!G.jobs[j].live) {
G.jobs[j] = (Job){.to = ids[i], .at = now + (pass ? 2000 : 0), .next = 0, .live = 1};
break;
}
}
if (overflow && !G.asks_left) G.asks_left = 1, G.ask_at = now; // pairs were dropped: the whole state once more
}
static void apply(Cpu *c, uint64_t mgr) {
if (!__atomic_load_n(&X.save_copied, __ATOMIC_ACQUIRE)) return; // no copy of the save yet: values wait
int done = 0;
while (G.ntodo && done < APPLY_PER_FRAME) {
int k = G.todo[--G.ntodo];
GFlag *f = &G.flags[k];
f->pending = 0;
if (f->want <= value_of(f, raw_of(f))) continue; // the game got there itself meanwhile
set_flag(c, mgr, f->is_int, f->hash, f->is_int ? (int32_t)f->want : !f->inv);
G.applied++, done++;
}
}
// This game's whole state to the players who wait for it, a few messages a frame.
static void run_jobs(uint64_t now) {
for (int j = 0; j < JOBS; j++) {
Job *job = &G.jobs[j];
if (!job->live || now < job->at) continue;
for (int part = 0; part < PARTS_PER_FRAME && job->live; part++) {
Pair out[PAIRS_PER_MESSAGE];
int n = 0, i = job->next;
for (; i < G.nflags && n < PAIRS_PER_MESSAGE; i++) {
const GFlag *f = &G.flags[i];
uint32_t v = value_of(f, raw_of(f));
if (v > f->max) v = f->max;
if (v) out[n++] = (Pair){f->hash, v};
}
if (n && !post_pairs(job->to, out, n)) return; // the room's queue is full: go on at the next frame
if (!job->to) // everyone has these now: a later rise is what scan sends
for (int k = 0; k < n; k++) {
GFlag *f = &G.flags[flag_index(out[k].hash)];
if (out[k].value > f->sent) f->sent = out[k].value;
}
job->next = i;
if (i >= G.nflags) job->live = 0;
}
}
}
void coop_present(Cpu *c) {
unsigned v = cfg_version();
if (v != G.cfg_seen) {
G.cfg_seen = v;
G.on = cfg_bool("NX2NAVI_COOP_STEAM");
__atomic_store_n(&X.on, G.on, __ATOMIC_RELAXED);
G.share = cfg_bool("NX2NAVI_COOP_SHARE");
}
if (!G.on) {
if (G.posed) coop_pose_set(NULL), G.posed = 0;
return;
}
if (!RT_V111) {
if (!G.said_version) rt_log("coop: co-op knows game 1.1.1 only; this is %d", rt_game_version);
G.said_version = 1;
return;
}
uint64_t mgr = LD64(MGR_PTR);
if (!rd_ok(mgr, MGR_SIZE)) {
unbind();
return;
}
if (G.bound && (mgr != G.mgr || LD64(mgr + C_BOOL + CN_ENTRIES) != G.bool_entries || LD64(mgr + C_INT + CN_ENTRIES) != G.int_entries))
unbind();
float pos[3];
uint64_t now = plat_now_ms();
if (!gate(mgr, pos)) {
if (G.posed) coop_pose_set(NULL), G.posed = 0;
return;
}
post_pose(pos, now);
int in_room = __atomic_load_n(&X.room, __ATOMIC_ACQUIRE);
if (!in_room || !G.share) {
if (G.sharing) { // left the room, or sharing was turned off: what the next room hears starts from nothing
G.sharing = 0, G.ntodo = 0;
memset(G.jobs, 0, sizeof G.jobs);
for (int i = 0; i < G.nflags; i++) G.flags[i].sent = G.flags[i].want = 0, G.flags[i].pending = 0;
}
return;
}
if (!G.bound) bind(mgr);
if (!G.bound) return;
Cpu keep = *c;
uint32_t epoch = __atomic_load_n(&X.room_epoch, __ATOMIC_ACQUIRE);
if (!G.sharing || epoch != G.room_epoch) {
// this game starts to share: the others send what they have, and get what this save has
G.sharing = 1, G.room_epoch = epoch;
if (!__atomic_load_n(&X.save_copied, __ATOMIC_ACQUIRE) &&
!plat_thread_spawn(copy_save, (void *)(uintptr_t)epoch, "coop-save", 0))
rt_log("coop: the save could not be copied; nothing of the room's progress is taken");
for (int i = 0; i < G.nflags; i++) G.flags[i].sent = G.flags[i].want = 0, G.flags[i].pending = 0;
G.ntodo = 0;
G.asks_left = 2, G.ask_at = now;
memset(G.jobs, 0, sizeof G.jobs);
G.jobs[0] = (Job){.to = 0, .at = now, .next = 0, .live = 1};
G.jobs[1] = (Job){.to = 0, .at = now + ASK_AGAIN_MS, .next = 0, .live = 1};
}
if (G.asks_left && now >= G.ask_at && coop_post(0, K_ASK, &G.schema, 4, 1)) G.asks_left--, G.ask_at = now + ASK_AGAIN_MS;
take_inbox();
scan();
apply(c, mgr);
run_jobs(now);
memcpy(c->x, keep.x, sizeof c->x);
memcpy(c->v, keep.v, sizeof c->v);
c->nzcv = keep.nzcv, c->fpsr = keep.fpsr;
if (now - G.log_at >= 5000 && (G.applied || G.refused)) {
if (G.applied) rt_log("coop: took %u values of progress from the room", G.applied);
if (G.refused) rt_log("coop: %u values from the room were not ones this game shares; dropped", G.refused);
G.applied = G.refused = 0, G.log_at = now;
}
}

View File

@@ -1,12 +0,0 @@
// Co-op, the game side (coop_game.c): where this game's Link is and the progress a room shares. coop.h declares the
// part the co-op thread calls (coop_game_message, coop_game_joined, coop_game_room).
#pragma once
#include "cpu.h"
void coop_game_init(void);
// At each present, on the game's thread, between two frames: reads Link and the game's flags and sets the flags the
// room has and this game lacks, through the game's own routines. Does nothing while the COOP setting is off.
void coop_present(Cpu *c);
// Each RomFS file the game opens (fs_host.c): the title screen's start is told by its event flow being opened.
void coop_game_rom_open(const char *path);

View File

@@ -1,192 +0,0 @@
// The stand-in for Steam in tests of two or more games on one PC (coop_net.h): datagrams between UDP ports on
// 127.0.0.1. A player's id is its port, a room's number its maker's port. The maker keeps the member list: a member
// says JOIN once a second, the maker answers everyone with MEMBERS and drops a member it has not heard for five
// seconds. Loopback loses and reorders nothing in practice, so "reliable" is a plain datagram here.
//
// Only the environment turns it on: a settings file cannot.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "coop_net.h"
#include "platform/platform.h"
enum { L_JOIN = 1, L_MEMBERS, L_DATA, L_LEAVE, L_MAX = 8, L_SILENT_MS = 5000, L_JOIN_EVERY_MS = 1000, L_JOIN_WAIT_MS = 4000 };
static struct {
PlatUdp *udp;
uint64_t self, room;
uint64_t joining; // the room asked for, until its maker answers
uint64_t join_since, join_sent, members_sent;
int n;
uint64_t ids[L_MAX];
uint64_t heard[L_MAX]; // the maker's: when each member last said JOIN
int pending_entered; // the maker's own room: entered at the next pump
} L;
static uint64_t env_number(const char *name) {
char v[32];
return plat_getenv(name, v, sizeof v) ? strtoull(v, NULL, 10) : 0;
}
int coop_local_wanted(void) { return env_number("NX2NAVI_COOP_LOCAL") != 0; }
uint64_t coop_local_join(void) { return env_number("NX2NAVI_COOP_LOCAL_JOIN"); }
int coop_local_makes(void) { return env_number("NX2NAVI_COOP_LOCAL_MAKE") == 1; }
static void to_port(uint64_t port, const void *p, size_t n) {
static const uint8_t loopback[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 127, 0, 0, 1};
PlatAddr a;
plat_addr_set(&a, loopback, (uint16_t)port, 0);
plat_udp_send(L.udp, &a, p, n);
}
static int l_start(char *why, size_t cap, int *which) {
if (L.udp) return 1;
uint64_t port = env_number("NX2NAVI_COOP_LOCAL");
L.udp = port && port < 65536 ? plat_udp_open((uint16_t)port, 0) : NULL;
if (!L.udp) {
snprintf(why, cap, "the test port %llu cannot be opened", (unsigned long long)port);
if (which) *which = STEAM_WHY_NO_CLIENT;
return 0;
}
L.self = port;
if (which) *which = STEAM_WHY_OK;
return 1;
}
static void l_room_leave(void) {
if (L.room && L.room != L.self) to_port(L.room, (uint8_t[]){L_LEAVE}, 1);
L.room = L.joining = 0, L.n = 0;
}
static void l_stop(void) {
l_room_leave();
if (L.udp) plat_udp_close(L.udp);
L.udp = NULL;
}
static uint64_t l_self(void) { return L.self; }
static void l_name_of(uint64_t id, char *out, size_t cap) { snprintf(out, cap, "Player %llu", (unsigned long long)id); }
static int l_room_create(int max_players) {
(void)max_players;
if (!L.udp || L.room) return 0;
L.room = L.self, L.n = 1, L.ids[0] = L.self, L.pending_entered = 1;
return 1;
}
static int l_room_join(uint64_t room) {
if (!L.udp || L.room || !room || room == L.self) return 0;
L.joining = room, L.join_since = plat_now_ms(), L.join_sent = 0;
return 1;
}
static uint64_t l_room(void) { return L.room; }
static uint64_t l_room_owner(void) { return L.room; }
static int l_room_members(uint64_t *out, int max) {
int n = L.room ? L.n : 0;
if (n > max) n = max;
memcpy(out, L.ids, (size_t)n * sizeof *out);
return n;
}
static int l_room_set(const char *key, const char *value) { (void)key, (void)value; return 1; }
static void l_room_get(const char *key, char *out, size_t cap) {
snprintf(out, cap, "%s", !strcmp(key, "nx2navi") ? "1" : ""); // every room of the stand-in is one of ours
}
static int member(uint64_t id) {
for (int i = 0; i < L.n; i++)
if (L.ids[i] == id) return i;
return -1;
}
static int l_send(uint64_t to, const void *data, size_t n, int reliable) {
(void)reliable;
if (!L.room || n > STEAM_MESSAGE_MAX || member(to) < 0) return 0;
uint8_t d[1 + STEAM_MESSAGE_MAX];
d[0] = L_DATA;
memcpy(d + 1, data, n);
to_port(to, d, n + 1);
return 1;
}
static void send_members(void) {
uint8_t d[1 + 8 * L_MAX];
d[0] = L_MEMBERS;
memcpy(d + 1, L.ids, (size_t)L.n * 8);
for (int i = 1; i < L.n; i++) to_port(L.ids[i], d, 1 + (size_t)L.n * 8);
L.members_sent = plat_now_ms();
}
static void drop(int i, void (*on)(const SteamEvent *, void *), void *user) {
uint64_t id = L.ids[i];
for (int k = i; k + 1 < L.n; k++) L.ids[k] = L.ids[k + 1], L.heard[k] = L.heard[k + 1];
L.n--;
on(&(SteamEvent){.kind = STEAM_EV_MEMBER_LEFT, .a = id}, user);
}
static void l_pump(void (*on)(const SteamEvent *e, void *user), void *user) {
if (!L.udp) return;
uint64_t now = plat_now_ms();
if (L.pending_entered) {
L.pending_entered = 0;
on(&(SteamEvent){.kind = STEAM_EV_ROOM_ENTERED, .a = L.room}, user);
}
uint64_t maker = L.joining ? L.joining : L.room != L.self ? L.room : 0;
if (maker && now - L.join_sent >= L_JOIN_EVERY_MS) to_port(maker, (uint8_t[]){L_JOIN}, 1), L.join_sent = now;
if (L.joining && now - L.join_since > L_JOIN_WAIT_MS) {
L.joining = 0;
on(&(SteamEvent){.kind = STEAM_EV_ROOM_FAILED, .code = STEAM_FAIL_NO_ROOM}, user);
}
for (;;) {
uint8_t d[1 + STEAM_MESSAGE_MAX + 8];
PlatAddr from;
int n = plat_udp_recv(L.udp, d, sizeof d, &from, 0);
if (n <= 0) break;
uint64_t who = plat_addr_port(&from);
if (d[0] == L_JOIN && L.room == L.self) {
int i = member(who);
if (i < 0 && L.n < L_MAX) {
i = L.n++;
L.ids[i] = who, L.heard[i] = now;
send_members();
on(&(SteamEvent){.kind = STEAM_EV_MEMBER_JOINED, .a = who}, user);
} else if (i >= 0) {
L.heard[i] = now;
}
} else if (d[0] == L_LEAVE && L.room == L.self) {
int i = member(who);
if (i > 0) drop(i, on, user), send_members();
} else if (d[0] == L_MEMBERS && (who == L.joining || (L.room && who == L.room && L.room != L.self))) {
uint64_t ids[L_MAX];
int count = (n - 1) / 8;
if (count > L_MAX) count = L_MAX;
memcpy(ids, d + 1, (size_t)count * 8);
int entering = L.joining != 0;
if (entering) L.room = L.joining, L.joining = 0, L.n = 0;
// who left, then who came, against the list held
for (int i = L.n - 1; i >= 0; i--) {
int still = 0;
for (int k = 0; k < count; k++) still |= ids[k] == L.ids[i];
if (!still) drop(i, on, user);
}
for (int k = 0; k < count; k++) {
if (member(ids[k]) >= 0 || L.n >= L_MAX) continue;
L.ids[L.n++] = ids[k];
if (!entering && ids[k] != L.self) on(&(SteamEvent){.kind = STEAM_EV_MEMBER_JOINED, .a = ids[k]}, user);
}
if (entering) on(&(SteamEvent){.kind = STEAM_EV_ROOM_ENTERED, .a = L.room}, user);
} else if (d[0] == L_DATA && L.room && member(who) >= 0 && n > 1) {
on(&(SteamEvent){.kind = STEAM_EV_MESSAGE, .a = who, .data = d + 1, .n = (size_t)n - 1}, user);
}
if (!L.udp) return; // a handler stopped the stand-in
}
if (L.room == L.self) {
for (int i = L.n - 1; i > 0; i--)
if (now - L.heard[i] > L_SILENT_MS) drop(i, on, user), send_members();
if (now - L.members_sent >= L_JOIN_EVERY_MS) send_members();
}
}
const CoopNet coop_net_local = {l_start, l_stop, l_self, l_name_of, l_room_create, l_room_join, l_room_leave, l_room,
l_room_owner, l_room_members, l_room_set, l_room_get, l_send, l_pump};

View File

@@ -1,30 +0,0 @@
// What co-op (coop.c) needs from the network under it: Steam (steam.c), or the stand-in for tests of two games on one
// PC (coop_local.c), which one Steam account cannot do. The functions are steam.h's, with its events.
#pragma once
#include "steam.h"
typedef struct {
int (*start)(char *why, size_t cap, int *which);
void (*stop)(void);
uint64_t (*self)(void);
void (*name_of)(uint64_t id, char *out, size_t cap);
int (*room_create)(int max_players);
int (*room_join)(uint64_t room);
void (*room_leave)(void);
uint64_t (*room)(void);
uint64_t (*room_owner)(void);
int (*room_members)(uint64_t *out, int max);
int (*room_set)(const char *key, const char *value);
void (*room_get)(const char *key, char *out, size_t cap);
int (*send)(uint64_t to, const void *data, size_t n, int reliable);
void (*pump)(void (*on)(const SteamEvent *e, void *user), void *user);
} CoopNet;
// The stand-in: NX2NAVI_COOP_LOCAL=<port> in the environment (never from nx2navi.ini) makes this game the player
// whose id is that UDP port on 127.0.0.1; the room it makes has that number, and another game joins it with
// NX2NAVI_COOP_LOCAL_JOIN=<that port>. No Steam, no room ids, no invites.
extern const CoopNet coop_net_local;
int coop_local_wanted(void); // the variable is set
uint64_t coop_local_join(void); // the room NX2NAVI_COOP_LOCAL_JOIN names, 0 none
int coop_local_makes(void); // NX2NAVI_COOP_LOCAL_MAKE=1: this game makes its room at once

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,9 +529,32 @@ static int text_get(const char *name, char out[64]) {
return 1;
}
// A text written into the entry's own buffers (game thread). 0: the game has no such text.
// 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); }
// The area the game is in: its text Sequence_CurrentBanc. 0 while the game has none.
int dbg_area(char out[64]) { return dbg_supported() && text_get("Sequence_CurrentBanc", out) && out[0]; }
// A text written into the entry's own buffers (game thread). 0: the game has no such text.
static int text_set(const char *name, const char *value) {
uint64_t e = gmd_entry(GD_TEXT64, 0x108, hash_of(name)), text = e ? rd_ptr(e + 0x68) : 0, other = e ? rd_ptr(e + 0x18) : 0;
int32_t room = 0;
@@ -777,6 +835,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 +910,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 +956,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 +992,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 +1003,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 +1020,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 +1042,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 +1068,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 +1089,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 +1115,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 +1235,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 +1263,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 +1319,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), and a one-frame flash (NX2NAVI_FLIGHT_FLASH, 1; at most one dump per 30 s; "The flash trigger"
@@ -72,6 +73,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];
@@ -140,7 +142,7 @@ void flight_init(void) {
}
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)
@@ -363,10 +365,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
@@ -380,6 +391,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 = part_file_open(path, "wb");
if (!f) return 0;
static const uint8_t sig[8] = {0x89, 'P', 'N', 'G', 13, 10, 26, 10};
@@ -391,6 +403,17 @@ static int write_png(const char *path, const uint8_t *rgba, PngBufs *pb) {
return part_file_close(f, path, 1);
}
// 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;
@@ -406,12 +429,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);
@@ -423,7 +441,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);
@@ -474,13 +492,16 @@ 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;
@@ -498,6 +519,15 @@ static uint64_t interval_of(uint64_t frame) {
return 0;
}
// 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[]) {
@@ -531,10 +561,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,6 +1,6 @@
// NX2NAVI_FLIGHT=1 flight recorder (flight.c): the last frames' timing and event counts plus a thumbnail each, written to
// disk on F8, after a slow frame or after a one-frame flash, so a glitch or stutter seen in play can be read after the
// fact.
// disk with a bug capture (F8, bugcap.c), after a slow frame or after a one-frame flash, so a glitch or stutter seen
// in play can be read after the fact.
#pragma once
#include <stdint.h>
@@ -18,6 +18,9 @@ void flight_mem(uint64_t *records, uint64_t *thumbs);
// 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
@@ -49,6 +52,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

@@ -21,7 +21,6 @@
#include <stdlib.h>
#include <string.h>
#include "coop_game.h"
#include "fs.h"
#include "host.h"
#include "platform/platform.h"
@@ -1164,7 +1163,6 @@ static int64_t host_read_at(PlatFile *f, void *buf, uint32_t n, uint64_t off) {
static uint32_t open_file(uint64_t *out, const char *path, int mode) {
if (romfs_owns(path)) {
coop_game_rom_open(path); // coop_game.c: the title screen's start
return romfs_open(out, path, mode);
}
fs_trace(mode & FS_OPEN_WRITE ? "write" : "read", path);

View File

@@ -17,7 +17,6 @@
#include "audren.h"
#include "cfg.h"
#include "coop.h"
#include "flight.h"
#include "flight_flash.h"
#include "fs.h"
@@ -97,7 +96,6 @@ void gfx_window_closed(void) {
vk_pipeline_save_exit();
prof_write(); // plat_exit runs no atexit handlers
rtss_limit_restore(); // RivaTuner Statistics Server's profile as it was
coop_shutdown(); // leaves the room, before the process ends
input_rumble_hd_stop(); // a controller on HD rumble gets the neutral value: nothing renews or stops it after the exit
fs_save_flush(); // last: the game's threads still run until plat_exit, and a Commit after this one is refused
if (restart) {
@@ -740,6 +738,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
@@ -1563,7 +1620,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];
@@ -1728,6 +1786,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

@@ -71,7 +71,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

@@ -46,8 +46,6 @@
#include <string.h>
#include "cfg.h"
#include "coop.h"
#include "coop_game.h"
#include "host.h"
#include "logq.h"
#include "prof.h"
@@ -733,8 +731,6 @@ static int main_run(int argc, char **argv) {
cfg.boot = cfg.seconds > 0; // --seconds starts the game like --boot, with its checkpoints
vk_driver_cache_env(); // before the threads below and rt_boot's, any of which may load the Vulkan driver
discord_init(); // the Rich Presence thread (discord_rpc.c); it reads nx2navi.ini itself and idles while off
coop_game_init(); // co-op's game side (coop_game.c), before the thread that hands it messages
coop_init(); // the co-op thread (coop.c); the same, idle while the COOP setting is off
rt_boot();
return 0;
}

View File

@@ -12,7 +12,6 @@
#include "gfx.h"
#include "cfg.h"
#include "coop_game.h"
#include "host.h"
#include "nvn_api.h"
#include "nvn_hmap.h"
@@ -874,7 +873,6 @@ NVN_API(nvnQueuePresentTexture) {
int idx = (int)arg_x(c, 2);
movie_tick(c); // ov_movie.c: hand over decoded movie frames that are due; needs the core, so before the wait
res_present(c); // resolution.c: a DLSS mode change sets the game's render size again, between frames
coop_present(c); // coop_game.c: co-op reads Link and the game's flags and sets the flags the room has, between frames
wide_present(); // widescreen.c: Ocarina's DLSS render scale
NVN_BLOCKING();
if (o->magic != NVN_WIN_MAGIC || idx < 0 || idx >= o->ntex || idx >= 4 || !o->tex[idx])

View File

@@ -6,6 +6,7 @@
#include <string.h>
#include "cfg.h"
#include "bugcap.h"
#include "flight.h"
#include "gfx.h"
#include "host.h"
@@ -830,6 +831,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

@@ -1,474 +0,0 @@
// Steam for co-op (steam.h): the Steamworks library loaded at run time and used through its C entry points.
//
// The library. steam_api64.dll exports one plain C function per method of each interface ("the flat API"):
// SteamAPI_ISteamMatchmaking_CreateLobby(self, ...), with self from an accessor whose name carries the interface's
// version (SteamAPI_SteamMatchmaking_v009). A library of another age exports other accessor versions, so each accessor
// is looked for under the versions known to have the calls below with these parameters, newest first; a library that
// lacks one of them, the manual dispatch calls or the networking messages interface (before 2020) is refused as too
// old. Nothing of the library's headers is used: the declarations here are the documented parameters of each call, a
// CSteamID passed and returned as the 64-bit number it is, a bool as one byte.
//
// The app id. The library signs in as the app SteamAppId names in the environment, set here to 480 before it loads:
// Steam's test app, which every account owns. A game started from Steam as a non-Steam shortcut has SteamGameId set
// to the shortcut's own number; both are set, so the library does not take the shortcut for the app.
//
// Callbacks. With manual dispatch the library queues what happened and steam_pump takes it out: a callback is a
// number and a block of bytes whose layout is fixed per number (8-byte packing on Windows). The numbers and offsets
// used are in the enum below; an asynchronous call (CreateLobby, JoinLobby) ends in callback 703, which names the
// call and the callback that holds its result.
//
// Messages. ISteamNetworkingMessages sends datagrams to a Steam id; Steam opens the session, finds a direct path or
// relays through its own network, encrypts, and vouches for the sender's id. A session a stranger opens is accepted
// only when that id is in the room, and a message is handed out only when its sender is.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "host.h"
#include "platform/platform.h"
#include "steam.h"
#ifdef _WIN32
#define STEAM_LIB "steam_api64.dll"
#else
#define STEAM_LIB "libsteam_api.so"
#endif
enum {
CB_SERVERS_DISCONNECTED = 103,
CB_LOBBY_JOIN_REQUESTED = 333, // u64 lobby, u64 friend
CB_SHUTDOWN = 704, // Steam is closing
CB_CALL_COMPLETED = 703, // u64 call, i32 callback, u32 size
CB_LOBBY_INVITE = 503, // u64 user, u64 lobby, u64 game
CB_LOBBY_ENTER = 504, // u64 lobby, u32 permissions, u8 locked, u32 response at 16
CB_LOBBY_CHAT_UPDATE = 506, // u64 lobby, u64 user changed, u64 user making the change, u32 change at 24
CB_LOBBY_CREATED = 513, // i32 result, u64 lobby at 8
CB_SESSION_REQUEST = 1251, // the identity of who asks
RESULT_OK = 1,
ENTER_OK = 1, ENTER_NO_ROOM = 2, ENTER_NOT_ALLOWED = 3, ENTER_FULL = 4,
CHANGE_ENTERED = 1, // the other bits: left, disconnected, kicked, banned
LOBBY_FRIENDS_ONLY = 1, // friends see and may join it; anyone else needs an invite or its number
FRIENDS_IMMEDIATE = 4, // the flag for "the player's friends"
SEND_UNRELIABLE_NO_DELAY = 5, SEND_RELIABLE = 8, SEND_AUTO_RESTART = 32,
IDENTITY_SIZE = 136, // SteamNetworkingIdentity
MSG_DATA = 0, MSG_SIZE = 8, MSG_PEER = 16, // SteamNetworkingMessage_t: void *data, i32 size, u32 conn, identity
CHANNEL = 0,
RECEIVE_BATCH = 32,
CALL_RESULT_CAP = 64,
};
typedef struct { int32_t user, id; uint8_t *param; int32_t size; } CallbackMsg;
static struct {
void *lib;
int up;
int32_t pipe;
void *user, *friends, *mm, *utils, *msgs;
uint64_t self, room, call; // call: the CreateLobby or JoinLobby that has not answered yet
int creating;
// the library
void (*shutdown)(void);
int32_t (*get_pipe)(void);
void (*md_frame)(int32_t);
uint8_t (*md_next)(int32_t, CallbackMsg *);
void (*md_free)(int32_t);
uint8_t (*md_result)(int32_t, uint64_t, void *, int, int, uint8_t *);
uint64_t (*get_id)(void *);
uint8_t (*overlay)(void *);
const char *(*persona_of)(void *, uint64_t);
const char *(*persona)(void *);
int (*friend_count)(void *, int);
uint64_t (*friend_at)(void *, int, int);
int (*friend_state)(void *, uint64_t);
uint8_t (*friend_game)(void *, uint64_t, void *);
uint8_t (*has_friend)(void *, uint64_t, int);
void (*invite_dialog)(void *, uint64_t);
uint64_t (*create)(void *, int, int);
uint64_t (*join)(void *, uint64_t);
void (*leave)(void *, uint64_t);
uint8_t (*invite)(void *, uint64_t, uint64_t);
uint8_t (*set_data)(void *, uint64_t, const char *, const char *);
const char *(*get_data)(void *, uint64_t, const char *);
int (*member_count)(void *, uint64_t);
uint64_t (*member_at)(void *, uint64_t, int);
uint64_t (*owner)(void *, uint64_t);
int (*send)(void *, const void *, const void *, uint32_t, int, int);
int (*receive)(void *, int, void **, int);
uint8_t (*accept)(void *, const void *);
uint8_t (*close_session)(void *, const void *);
void (*msg_release)(void *);
void (*ident_clear)(void *);
void (*ident_set)(void *, uint64_t);
uint64_t (*ident_get)(void *);
} S;
static void *sym(const char *name) { return plat_lib_sym(S.lib, name); }
// The accessor of an interface under the first of the version names the library has; NULL: none.
static void *interface_of(const char *const *names) {
for (; *names; names++) {
void *(*get)(void) = sym(*names);
if (get) return get();
}
return NULL;
}
static int fail(char *why, size_t cap, int *which, int code, const char *text) {
snprintf(why, cap, "%s", text);
if (which) *which = code;
return 0;
}
int steam_up(void) { return S.up; }
uint64_t steam_self(void) { return S.self; }
uint64_t steam_room(void) { return S.room; }
int steam_start(char *why, size_t cap, int *which) {
if (S.up) return 1;
if (which) *which = STEAM_WHY_OK;
if (!S.lib) {
// beside the game's exe, nowhere else: a path from a settings file would load whatever file a stranger's
// nx2navi.ini names
char path[PLAT_PATH_MAX], exe[PLAT_PATH_MAX];
if (!plat_exe_path(exe, sizeof exe)) return fail(why, cap, which, STEAM_WHY_NO_LIBRARY, "the game's folder is not known");
char *sep = plat_last_sep(exe);
if (sep) *sep = 0;
snprintf(path, sizeof path, "%s/%s", exe, STEAM_LIB);
if (!plat_file_exists(path))
return fail(why, cap, which, STEAM_WHY_NO_LIBRARY, STEAM_LIB " is not beside the game");
plat_setenv("SteamAppId", "480");
plat_setenv("SteamGameId", "480");
S.lib = plat_lib_open(path);
if (!S.lib) return fail(why, cap, which, STEAM_WHY_NO_LIBRARY, STEAM_LIB " beside the game does not load");
}
#define NEED(field, name) \
if (!(S.field = sym(name))) return fail(why, cap, which, STEAM_WHY_OLD_LIBRARY, STEAM_LIB " is too old: it lacks " name);
void (*md_init)(void) = sym("SteamAPI_ManualDispatch_Init");
if (!md_init) return fail(why, cap, which, STEAM_WHY_OLD_LIBRARY, STEAM_LIB " is too old: it lacks SteamAPI_ManualDispatch_Init");
NEED(shutdown, "SteamAPI_Shutdown") NEED(get_pipe, "SteamAPI_GetHSteamPipe")
NEED(md_frame, "SteamAPI_ManualDispatch_RunFrame") NEED(md_next, "SteamAPI_ManualDispatch_GetNextCallback")
NEED(md_free, "SteamAPI_ManualDispatch_FreeLastCallback") NEED(md_result, "SteamAPI_ManualDispatch_GetAPICallResult")
NEED(get_id, "SteamAPI_ISteamUser_GetSteamID") NEED(overlay, "SteamAPI_ISteamUtils_IsOverlayEnabled")
NEED(persona_of, "SteamAPI_ISteamFriends_GetFriendPersonaName") NEED(persona, "SteamAPI_ISteamFriends_GetPersonaName")
NEED(friend_count, "SteamAPI_ISteamFriends_GetFriendCount") NEED(friend_at, "SteamAPI_ISteamFriends_GetFriendByIndex")
NEED(friend_state, "SteamAPI_ISteamFriends_GetFriendPersonaState") NEED(friend_game, "SteamAPI_ISteamFriends_GetFriendGamePlayed")
NEED(has_friend, "SteamAPI_ISteamFriends_HasFriend") NEED(invite_dialog, "SteamAPI_ISteamFriends_ActivateGameOverlayInviteDialog")
NEED(create, "SteamAPI_ISteamMatchmaking_CreateLobby") NEED(join, "SteamAPI_ISteamMatchmaking_JoinLobby")
NEED(leave, "SteamAPI_ISteamMatchmaking_LeaveLobby") NEED(invite, "SteamAPI_ISteamMatchmaking_InviteUserToLobby")
NEED(set_data, "SteamAPI_ISteamMatchmaking_SetLobbyData") NEED(get_data, "SteamAPI_ISteamMatchmaking_GetLobbyData")
NEED(member_count, "SteamAPI_ISteamMatchmaking_GetNumLobbyMembers") NEED(member_at, "SteamAPI_ISteamMatchmaking_GetLobbyMemberByIndex")
NEED(owner, "SteamAPI_ISteamMatchmaking_GetLobbyOwner")
NEED(send, "SteamAPI_ISteamNetworkingMessages_SendMessageToUser") NEED(receive, "SteamAPI_ISteamNetworkingMessages_ReceiveMessagesOnChannel")
NEED(accept, "SteamAPI_ISteamNetworkingMessages_AcceptSessionWithUser") NEED(close_session, "SteamAPI_ISteamNetworkingMessages_CloseSessionWithUser")
NEED(msg_release, "SteamAPI_SteamNetworkingMessage_t_Release") NEED(ident_clear, "SteamAPI_SteamNetworkingIdentity_Clear")
NEED(ident_set, "SteamAPI_SteamNetworkingIdentity_SetSteamID64") NEED(ident_get, "SteamAPI_SteamNetworkingIdentity_GetSteamID64")
#undef NEED
// signing in: the newest entry point says why it failed, the older ones only that they did
int (*init_flat)(char *) = sym("SteamAPI_InitFlat");
uint8_t (*init_safe)(void) = sym("SteamAPI_InitSafe");
uint8_t (*init_old)(void) = sym("SteamAPI_Init");
char err[1024] = "";
int ok = init_flat ? init_flat(err) == 0 : init_safe ? init_safe() : init_old ? init_old() : 0;
if (!ok) {
char text[200];
snprintf(text, sizeof text, "Steam did not answer: is it running and signed in?%s%.100s", *err ? " Steam says: " : "", err);
return fail(why, cap, which, STEAM_WHY_NO_CLIENT, text);
}
md_init();
S.user = interface_of((const char *const[]){"SteamAPI_SteamUser_v023", "SteamAPI_SteamUser_v022", "SteamAPI_SteamUser_v021",
"SteamAPI_SteamUser_v020", NULL});
S.friends = interface_of((const char *const[]){"SteamAPI_SteamFriends_v018", "SteamAPI_SteamFriends_v017", NULL});
S.mm = interface_of((const char *const[]){"SteamAPI_SteamMatchmaking_v009", NULL});
S.utils = interface_of((const char *const[]){"SteamAPI_SteamUtils_v010", "SteamAPI_SteamUtils_v009", NULL});
S.msgs = interface_of((const char *const[]){"SteamAPI_SteamNetworkingMessages_SteamAPI_v002", NULL});
if (!S.user || !S.friends || !S.mm || !S.utils || !S.msgs) {
S.shutdown();
return fail(why, cap, which, STEAM_WHY_OLD_LIBRARY, STEAM_LIB " is too old or too new: an interface this version knows is missing");
}
// Steam's relay network takes a few seconds to measure its routes: started now, the first message does not wait
void *nu = interface_of((const char *const[]){"SteamAPI_SteamNetworkingUtils_SteamAPI_v004",
"SteamAPI_SteamNetworkingUtils_SteamAPI_v003", NULL});
void (*relay_init)(void *) = sym("SteamAPI_ISteamNetworkingUtils_InitRelayNetworkAccess");
if (nu && relay_init) relay_init(nu);
S.pipe = S.get_pipe();
S.self = S.get_id(S.user);
S.room = S.call = 0;
S.up = 1;
return 1;
}
void steam_stop(void) {
if (!S.up) return;
steam_room_leave();
S.shutdown();
S.up = 0;
}
void steam_name_of(uint64_t id, char *out, size_t cap) {
const char *name = !S.up ? "" : id == S.self ? S.persona(S.friends) : S.persona_of(S.friends, id);
// Steam answers "[unknown]" for a player whose name it has not fetched yet
snprintf(out, cap, "%s", name && strcmp(name, "[unknown]") ? name : "");
}
int steam_is_friend(uint64_t id) { return S.up && S.has_friend(S.friends, id, FRIENDS_IMMEDIATE); }
int steam_overlay(void) { return S.up && S.overlay(S.utils); }
int steam_room_create(int max_players) {
if (!S.up || S.room || S.call) return 0;
S.call = S.create(S.mm, LOBBY_FRIENDS_ONLY, max_players);
S.creating = 1;
return S.call != 0;
}
int steam_room_join(uint64_t room) {
if (!S.up || S.room || S.call || !room) return 0;
S.call = S.join(S.mm, room);
S.creating = 0;
return S.call != 0;
}
static void identity_of(uint8_t ident[IDENTITY_SIZE], uint64_t id) {
S.ident_clear(ident);
S.ident_set(ident, id);
}
void steam_room_leave(void) {
if (!S.up || !S.room) return;
uint64_t ids[STEAM_ROOM_MAX];
int n = steam_room_members(ids, STEAM_ROOM_MAX);
for (int i = 0; i < n; i++) {
if (ids[i] == S.self) continue;
uint8_t ident[IDENTITY_SIZE];
identity_of(ident, ids[i]);
S.close_session(S.msgs, ident);
}
S.leave(S.mm, S.room);
S.room = 0;
}
uint64_t steam_room_owner(void) { return S.up && S.room ? S.owner(S.mm, S.room) : 0; }
int steam_room_members(uint64_t *out, int max) {
if (!S.up || !S.room) return 0;
int n = S.member_count(S.mm, S.room);
if (n > max) n = max;
for (int i = 0; i < n; i++) out[i] = S.member_at(S.mm, S.room, i);
return n;
}
static int in_room(uint64_t id) {
uint64_t ids[STEAM_ROOM_MAX];
int n = steam_room_members(ids, STEAM_ROOM_MAX);
for (int i = 0; i < n; i++)
if (ids[i] == id) return 1;
return 0;
}
int steam_room_set(const char *key, const char *value) { return S.up && S.room && S.set_data(S.mm, S.room, key, value); }
void steam_room_get(const char *key, char *out, size_t cap) {
const char *v = S.up && S.room ? S.get_data(S.mm, S.room, key) : NULL;
snprintf(out, cap, "%s", v ? v : "");
}
static int friend_rank(const SteamFriend *f) { return f->in_app ? 0 : f->online ? 1 : 2; }
static int friend_cmp(const void *a, const void *b) {
const SteamFriend *x = a, *y = b;
int d = friend_rank(x) - friend_rank(y);
return d ? d : strcmp(x->name, y->name);
}
int steam_friends(SteamFriend *out, int max) {
if (!S.up) return 0;
int total = S.friend_count(S.friends, FRIENDS_IMMEDIATE), n = 0;
for (int i = 0; i < total && n < max; i++) {
SteamFriend *f = &out[n];
f->id = S.friend_at(S.friends, i, FRIENDS_IMMEDIATE);
steam_name_of(f->id, f->name, sizeof f->name);
if (!f->name[0]) continue;
f->online = S.friend_state(S.friends, f->id) != 0;
// FriendGameInfo_t: u64 game id (the app in its low 24 bits), u32 address, u16 and u16 ports, u64 lobby
uint8_t game[24] = {0};
uint64_t game_id = 0;
if (S.friend_game(S.friends, f->id, game)) memcpy(&game_id, game, 8);
f->in_app = (game_id & 0xffffff) == STEAM_APP_ID;
n++;
}
qsort(out, (size_t)n, sizeof *out, friend_cmp);
return n;
}
int steam_invite(uint64_t friend_id) { return S.up && S.room && S.invite(S.mm, S.room, friend_id); }
void steam_invite_window(void) {
if (S.up && S.room) S.invite_dialog(S.friends, S.room);
}
int steam_send(uint64_t to, const void *data, size_t n, int reliable) {
if (!S.up || !S.room || n > STEAM_MESSAGE_MAX) return 0;
uint8_t ident[IDENTITY_SIZE];
identity_of(ident, to);
// a session that broke (the other player's connection dropped for a moment) is opened again by the next message
int flags = (reliable ? SEND_RELIABLE : SEND_UNRELIABLE_NO_DELAY) | SEND_AUTO_RESTART;
return S.send(S.msgs, ident, data, (uint32_t)n, flags, CHANNEL) == RESULT_OK;
}
static uint64_t u64_at(const uint8_t *p, size_t off) {
uint64_t v;
memcpy(&v, p + off, 8);
return v;
}
static uint32_t u32_at(const uint8_t *p, size_t off) {
uint32_t v;
memcpy(&v, p + off, 4);
return v;
}
static void entered(uint64_t room, uint32_t response, void (*on)(const SteamEvent *, void *), void *user) {
S.call = 0;
if (response == ENTER_OK) {
S.room = room;
on(&(SteamEvent){.kind = STEAM_EV_ROOM_ENTERED, .a = room}, user);
} else {
int code = response == ENTER_NO_ROOM ? STEAM_FAIL_NO_ROOM : response == ENTER_FULL ? STEAM_FAIL_FULL
: response == ENTER_NOT_ALLOWED ? STEAM_FAIL_REFUSED : STEAM_FAIL_OTHER;
on(&(SteamEvent){.kind = STEAM_EV_ROOM_FAILED, .code = code}, user);
}
}
static void callback(int id, const uint8_t *p, int size, void (*on)(const SteamEvent *, void *), void *user) {
switch (id) {
case CB_CALL_COMPLETED: {
if (size < 16) break;
uint64_t call = u64_at(p, 0);
int32_t result_id = (int32_t)u32_at(p, 8);
uint32_t n = u32_at(p, 12);
if (call != S.call || n > CALL_RESULT_CAP) break; // a call of the library's own
uint8_t r[CALL_RESULT_CAP] = {0}, failed = 0;
if (!S.md_result(S.pipe, call, r, (int)n, result_id, &failed) || failed) {
S.call = 0;
on(&(SteamEvent){.kind = STEAM_EV_ROOM_FAILED, .code = S.creating ? STEAM_FAIL_CREATE : STEAM_FAIL_OTHER}, user);
} else if (result_id == CB_LOBBY_CREATED && n >= 16) {
if (u32_at(r, 0) == RESULT_OK) {
entered(u64_at(r, 8), ENTER_OK, on, user);
} else {
S.call = 0;
on(&(SteamEvent){.kind = STEAM_EV_ROOM_FAILED, .code = STEAM_FAIL_CREATE}, user);
}
} else if (result_id == CB_LOBBY_ENTER && n >= 20) {
entered(u64_at(r, 0), u32_at(r, 16), on, user);
}
break;
}
case CB_LOBBY_CHAT_UPDATE:
if (size >= 28 && u64_at(p, 0) == S.room && u64_at(p, 8) != S.self) {
uint64_t who = u64_at(p, 8);
int came = u32_at(p, 24) == CHANGE_ENTERED;
if (!came) {
uint8_t ident[IDENTITY_SIZE];
identity_of(ident, who);
S.close_session(S.msgs, ident);
}
on(&(SteamEvent){.kind = came ? STEAM_EV_MEMBER_JOINED : STEAM_EV_MEMBER_LEFT, .a = who}, user);
}
break;
case CB_LOBBY_INVITE:
if (size >= 24 && (u64_at(p, 16) & 0xffffff) == STEAM_APP_ID)
on(&(SteamEvent){.kind = STEAM_EV_INVITED, .a = u64_at(p, 8), .b = u64_at(p, 0)}, user);
break;
case CB_LOBBY_JOIN_REQUESTED:
if (size >= 16) on(&(SteamEvent){.kind = STEAM_EV_JOIN_ASKED, .a = u64_at(p, 0), .b = u64_at(p, 8)}, user);
break;
case CB_SESSION_REQUEST:
// only a player in the room may open a session: anyone on Steam can ask
if (size >= IDENTITY_SIZE) {
uint8_t ident[IDENTITY_SIZE];
memcpy(ident, p, IDENTITY_SIZE);
if (in_room(S.ident_get(ident))) S.accept(S.msgs, ident);
}
break;
case CB_SERVERS_DISCONNECTED:
case CB_SHUTDOWN:
if (S.room) {
S.room = S.call = 0;
on(&(SteamEvent){.kind = STEAM_EV_LOST}, user);
}
break;
}
}
void steam_pump(void (*on)(const SteamEvent *e, void *user), void *user) {
if (!S.up) return;
S.md_frame(S.pipe);
CallbackMsg m;
while (S.md_next(S.pipe, &m)) {
// the block is the library's until it is freed, and a handler may call the library: copy first
uint8_t copy[512];
int size = m.size < 0 ? 0 : m.size > (int)sizeof copy ? (int)sizeof copy : m.size;
if (size) memcpy(copy, m.param, (size_t)size);
int id = m.id;
S.md_free(S.pipe);
callback(id, copy, size, on, user);
if (!S.up) return;
}
for (;;) {
void *batch[RECEIVE_BATCH];
int n = S.receive(S.msgs, CHANNEL, batch, RECEIVE_BATCH);
for (int i = 0; i < n; i++) {
const uint8_t *msg = batch[i];
const uint8_t *data;
int32_t size;
uint8_t ident[IDENTITY_SIZE];
memcpy(&data, msg + MSG_DATA, sizeof data);
memcpy(&size, msg + MSG_SIZE, 4);
memcpy(ident, msg + MSG_PEER, IDENTITY_SIZE);
uint64_t from = S.ident_get(ident);
if (size > 0 && size <= STEAM_MESSAGE_MAX && from && from != S.self && in_room(from))
on(&(SteamEvent){.kind = STEAM_EV_MESSAGE, .a = from, .data = data, .n = (size_t)size}, user);
S.msg_release(batch[i]);
}
if (n < RECEIVE_BATCH) break;
}
}
// ---- room ids
//
// Every lobby's 64-bit number starts with the same 32 bits (universe 1, the chat type, the lobby flag: 0x01860000); the
// other 32 name the lobby. A room id is those 32 bits and an 8-bit check of them, 40 bits as 8 symbols of 5 bits.
#define LOBBY_HIGH 0x01860000ull
static const char code_symbols[] = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; // no 0, 1, I or O
static uint32_t code_check(uint32_t low) {
uint32_t h = low * 2654435761u;
return (h >> 24) & 0xff;
}
void steam_code_make(uint64_t room, char out[STEAM_CODE_CAP]) {
out[0] = 0;
if (room >> 32 != LOBBY_HIGH) return; // a lobby of a kind this version does not know: it has no room id
uint32_t low = (uint32_t)room;
uint64_t v = (uint64_t)low << 8 | code_check(low);
int o = 0;
for (int i = 7; i >= 0; i--) {
out[o++] = code_symbols[(v >> (5 * i)) & 31];
if (i == 4) out[o++] = '-';
}
out[o] = 0;
}
uint64_t steam_code_parse(const char *text) {
uint64_t v = 0;
int n = 0;
for (; *text; text++) {
char c = *text;
if (c == '-' || c == ' ' || c == '\t') continue;
if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A');
const char *at = strchr(code_symbols, c);
if (!at || !c || ++n > 8) return 0;
v = v << 5 | (uint64_t)(at - code_symbols);
}
if (n != 8) return 0;
uint32_t low = (uint32_t)(v >> 8);
if ((v & 0xff) != code_check(low)) return 0;
return LOBBY_HIGH << 32 | low;
}

View File

@@ -1,84 +0,0 @@
// Steam for co-op (steam.c): rooms are Steam lobbies, players are invited through Steam, and the games talk through
// Steam's networking, so nobody forwards a port and nobody runs a server. NX2navi is no Steam app of its own: it signs
// in as Steam's public test app (id 480, "Spacewar"), which every account may use; Steam then shows the player as
// playing that app.
//
// The Steamworks library is not part of NX2navi and is never in its repository. steam.c declares the functions it
// calls itself and loads steam_api64.dll from beside the game at run time (the launcher copies one there from a
// Steam game the player has, launcher/steamlib.py); without the file, or without a running Steam client that is
// signed in, steam_start fails and says why.
//
// Every function here is called from one thread (the co-op thread, coop.c): the library is used single-threaded.
#pragma once
#include <stddef.h>
#include <stdint.h>
enum { STEAM_APP_ID = 480, STEAM_NAME_CAP = 64, STEAM_ROOM_MAX = 8, STEAM_MESSAGE_MAX = 1200 };
typedef enum {
STEAM_EV_ROOM_ENTERED, // a: the room. This game made or joined it
STEAM_EV_ROOM_FAILED, // code: why (STEAM_FAIL_*)
STEAM_EV_MEMBER_JOINED, // a: the player's id
STEAM_EV_MEMBER_LEFT, // a: the player's id
STEAM_EV_INVITED, // a: the room, b: the friend who invites. Shown to the player, who may join
STEAM_EV_JOIN_ASKED, // a: the room. The player accepted an invite, or chose Join Game, in Steam itself
STEAM_EV_MESSAGE, // a: the sender, data and n: the message. Only from players in the room
STEAM_EV_LOST, // Steam lost its connection or closed: the room is gone
} SteamEventKind;
enum { STEAM_FAIL_CREATE = 1, STEAM_FAIL_NO_ROOM, STEAM_FAIL_FULL, STEAM_FAIL_REFUSED, STEAM_FAIL_OTHER };
typedef struct {
SteamEventKind kind;
uint64_t a, b;
int code;
const uint8_t *data;
size_t n;
} SteamEvent;
typedef struct {
uint64_t id;
char name[STEAM_NAME_CAP];
int online; // signed in to Steam now
int in_app; // shown as playing app 480: probably in NX2navi with co-op on, so an invite can reach the game
} SteamFriend;
// Loads the library, signs in as app 480 and takes the interfaces. 1 when Steam is up; 0 with the reason in why (a
// sentence for the log and the menu's status line; STEAM_WHY_* says which, for the menu's own text).
enum { STEAM_WHY_OK, STEAM_WHY_NO_LIBRARY, STEAM_WHY_OLD_LIBRARY, STEAM_WHY_NO_CLIENT, STEAM_WHY_OTHER_OS };
int steam_start(char *why, size_t cap, int *which);
void steam_stop(void); // leaves the room and signs out
int steam_up(void);
uint64_t steam_self(void);
void steam_name_of(uint64_t id, char *out, size_t cap); // the player's Steam name; "" while Steam has not got it
int steam_is_friend(uint64_t id);
int steam_overlay(void); // Steam's overlay is in this game (it was started from Steam): its invite window works
// Rooms. Create and join answer later with STEAM_EV_ROOM_ENTERED or STEAM_EV_ROOM_FAILED.
int steam_room_create(int max_players);
int steam_room_join(uint64_t room);
void steam_room_leave(void);
uint64_t steam_room(void); // 0: in none
uint64_t steam_room_owner(void); // whose game made it; Steam hands it to another member when that player leaves
int steam_room_members(uint64_t *out, int max);
int steam_room_set(const char *key, const char *value); // the owner's notes on the room, read by everyone
void steam_room_get(const char *key, char *out, size_t cap);
int steam_friends(SteamFriend *out, int max); // the player's friends, those in the app first, then online, then the rest
int steam_invite(uint64_t friend_id); // Steam shows the friend an invite to this room
void steam_invite_window(void); // Steam's own invite window (only with steam_overlay)
// A message to a player in the room. reliable: it arrives, in order; else it may be lost and is never late.
int steam_send(uint64_t to, const void *data, size_t n, int reliable);
// Runs Steam's callbacks and hands out what happened. Call it many times a second.
void steam_pump(void (*on)(const SteamEvent *e, void *user), void *user);
// A room's id as players pass it on, "XXXX-XXXX": the part of the lobby's number that differs between lobbies and a
// check of it, in letters and digits that cannot be mixed up (no 0, 1, I or O). steam_code_parse takes it in any case, with or
// without the dash and spaces; 0 when it is no room id.
enum { STEAM_CODE_CAP = 16 };
void steam_code_make(uint64_t room, char out[STEAM_CODE_CAP]);
uint64_t steam_code_parse(const char *text);

View File

@@ -5,7 +5,6 @@
#include <stdio.h>
#include <string.h>
#include "coop.h"
#include "fs.h"
#include "host.h"
#include "kernel.h"
@@ -244,7 +243,6 @@ static void svc_body(Cpu *c, uint32_t imm, uint64_t pc) {
// profile saved, logs flushed, exit code 0
char at[160];
rt_log("guest ExitProcess at %s; exiting", ldr_describe(pc, at, sizeof at));
coop_shutdown(); // leaves the room, before the process ends
fs_save_flush();
vk_pipeline_prewarm_marker_clear(); // as the window's close (gfx_present.c gfx_window_closed)
vk_mem_exit_log();

View File

@@ -1,527 +0,0 @@
// The menu's Co-op tab and co-op's drawing over the game (ui/coop_page.h).
//
// The page reads the co-op thread's view once a frame (coop_view) and hands it commands (coop_create, coop_join, ...);
// nothing here waits for Steam. What the page shows follows the view's state: off, Steam missing, in no room, on the
// way into one, in one. A press that turns co-op on and wants a room at once (Create a room while co-op is off) is
// kept for a few seconds until the thread has reached Steam.
//
// Names over the game: a player's position is projected with the frame's camera as the upscaler's pass knows it
// (vk_dlaa_fg_camera: position, right, up and forward in the world's metres, the vertical field of view and the
// aspect). Without a temporal upscaler there is no camera and no names; the player list still says where each is.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "imgui.h"
#include "imgui_internal.h"
#include "menu_sound.h"
#include "ui/coop_page.h"
#include "ui/menu_skin.h"
#include "ui/option_rows.h"
extern "C" {
#include "cfg.h"
#include "coop.h"
#include "platform/platform.h"
#include "ui/menu.h"
#include "ui_text.h"
#include "vk_dlaa.h"
}
enum Page { P_NONE, P_JOIN, P_CHAT, P_INVITE, P_REMOVE, P_LEAVE };
enum { FIELD_CAP = COOP_CHAT_CAP + 1, PASTE_FRAMES = 120, PENDING_MS = 8000, CHAT_SHOWN_MS = 8000, CHAT_FADE_MS = 1000 };
static bool g_open, g_window_shown, g_page_new, g_by_pad;
static int g_page;
static char g_field[FIELD_CAP];
static bool g_field_bad, g_paste_empty;
static int g_paste_wait; // frames left to wait for the clipboard's text (gfx_window_paste)
static char g_return[48]; // the row the cursor goes back to when the window closes
static CoopView g_view; // this frame's copy of the layer's state
static int g_layout = -1; // the page's last kind, to move the cursor when its rows change
static uint64_t g_copied_at; // when the room ID was last copied
static uint64_t g_remove_id;
static char g_remove_name[COOP_NAME_CAP];
static char g_invited_name[COOP_NAME_CAP]; // the friend the last invite went to
static uint64_t g_invited_at;
static SteamFriend g_friends[COOP_FRIENDS];
static int g_nfriends;
// a command that waits for co-op to come up: 1 create, 2 join g_pending_code
static int g_pending;
static char g_pending_code[STEAM_CODE_CAP];
static uint64_t g_pending_until;
static bool in_room(void) { return g_view.state == COOP_IN_ROOM; }
static UiTextId note_text(CoopNote n) {
switch (n) {
case COOP_NOTE_NO_LIBRARY: return UI_MENU_COOP_NO_LIBRARY;
case COOP_NOTE_OLD_LIBRARY: return UI_MENU_COOP_OLD_LIBRARY;
case COOP_NOTE_NO_CLIENT:
case COOP_NOTE_OTHER_OS: return UI_MENU_COOP_NO_CLIENT;
case COOP_NOTE_CREATE_FAILED: return UI_MENU_COOP_N_CREATE_FAILED;
case COOP_NOTE_NO_ROOM:
case COOP_NOTE_BAD_CODE: return UI_MENU_COOP_N_NO_ROOM;
case COOP_NOTE_FULL: return UI_MENU_COOP_N_FULL;
case COOP_NOTE_REFUSED: return UI_MENU_COOP_N_REFUSED;
case COOP_NOTE_NOT_OURS: return UI_MENU_COOP_N_NOT_OURS;
case COOP_NOTE_OTHER_VERSION: return UI_MENU_COOP_N_OTHER_VERSION;
case COOP_NOTE_REMOVED: return UI_MENU_COOP_N_REMOVED;
case COOP_NOTE_HOST_SILENT: return UI_MENU_COOP_N_HOST_SILENT;
case COOP_NOTE_LOST: return UI_MENU_COOP_N_LOST;
case COOP_NOTE_LEFT: return UI_MENU_COOP_N_LEFT;
default: return UI_TEXT_COUNT;
}
}
// Create or join, turning co-op on first when it is off: the command then waits for the thread to reach Steam.
static void want_room(int what, const char *code) {
if (g_view.state == COOP_READY) {
if (what == 1) coop_create();
else coop_join(code);
return;
}
if (g_view.state == COOP_OFF) opt_apply("NX2NAVI_COOP_STEAM", "1");
g_pending = what;
snprintf(g_pending_code, sizeof g_pending_code, "%s", code ? code : "");
g_pending_until = plat_now_ms() + PENDING_MS;
}
static void pending_tick(void) {
if (!g_pending) return;
if (g_view.state == COOP_READY) {
if (g_pending == 1) coop_create();
else coop_join(g_pending_code);
g_pending = 0;
} else if (g_view.state == COOP_NO_STEAM || plat_now_ms() > g_pending_until) {
g_pending = 0; // the page says why Steam is not there
}
}
static void open_window(int page, const char *ret) {
g_open = true, g_page = page, g_page_new = true;
g_by_pad = ImGui::IsKeyDown(ImGuiKey_GamepadFaceDown); // a pad's A opened it: no keyboard to type with
g_field_bad = g_paste_empty = false, g_paste_wait = 0;
g_field[0] = 0;
snprintf(g_return, sizeof g_return, "%s", ret);
}
static void settings_rows(void) {
opt_group(UI_MENU_COOP_SETTINGS);
opt_toggle("NX2NAVI_COOP_SHARE", UI_MENU_COOP_SHARE, UI_MENU_COOP_SHARE_DESC);
opt_toggle("NX2NAVI_COOP_NAMES", UI_MENU_COOP_NAMES, UI_MENU_COOP_NAMES_DESC);
opt_toggle("NX2NAVI_COOP_CHAT", UI_MENU_COOP_CHAT_SHOW, UI_MENU_COOP_CHAT_SHOW_DESC);
opt_toggle("NX2NAVI_COOP_STEAM", UI_MENU_COOP_ON, UI_MENU_COOP_ON_DESC);
}
static void chat_text(const CoopChatLine &l, char *out, size_t cap) {
if (l.notice) snprintf(out, cap, menu_text(l.joined ? UI_MENU_COOP_CHAT_JOINED : UI_MENU_COOP_CHAT_LEFT), l.name);
else snprintf(out, cap, "%s: %s", l.name, l.text);
}
static void rows_out(void) {
if (g_view.state == COOP_OFF && !g_pending) {
opt_toggle("NX2NAVI_COOP_STEAM", UI_MENU_COOP_ON, UI_MENU_COOP_ON_DESC);
return;
}
if (g_view.local) opt_text(UI_MENU_COOP_LOCAL);
if (g_view.state == COOP_NO_STEAM) {
const UiTextId why = note_text(g_view.note);
if (why != UI_TEXT_COUNT) opt_text(why, true);
if (opt_button("##coop_retry", UI_MENU_COOP_RETRY, UI_MENU_COOP_RETRY_DESC)) coop_retry();
settings_rows();
return;
}
if (g_view.state == COOP_ENTERING || g_pending) {
if (opt_button("##coop_stop", UI_MENU_COOP_STOP, UI_MENU_COOP_STOP_DESC)) {
g_pending = 0;
coop_leave();
}
opt_text(UI_MENU_COOP_JOINING);
return;
}
if (g_view.invite_room) {
char line[COOP_NAME_CAP + 96];
snprintf(line, sizeof line, menu_text(UI_MENU_COOP_INVITED), g_view.invite_from);
opt_text_str(line);
if (opt_button("##coop_invited_join", UI_MENU_COOP_INVITED_JOIN, UI_MENU_COOP_INVITED_JOIN_DESC)) coop_join_invite();
if (opt_button("##coop_invited_no", UI_MENU_COOP_INVITED_NO, UI_MENU_COOP_INVITED_NO_DESC)) coop_decline_invite();
}
if (opt_button("##coop_create", UI_MENU_COOP_CREATE, UI_MENU_COOP_CREATE_DESC)) want_room(1, nullptr);
if (opt_button("##coop_join", UI_MENU_COOP_JOIN, UI_MENU_COOP_JOIN_DESC)) open_window(P_JOIN, "##coop_join");
const UiTextId why = note_text(g_view.note);
if (why != UI_TEXT_COUNT) opt_text(why, g_view.note != COOP_NOTE_LEFT);
settings_rows();
}
static void rows_room(void) {
const uint64_t now = plat_now_ms();
if (g_view.local) opt_text(UI_MENU_COOP_LOCAL);
if (g_view.code[0]) {
const bool copied = g_copied_at && now - g_copied_at < 3000;
if (opt_text_row("##coop_code", menu_text(UI_MENU_COOP_ROOM_ID), g_view.code, copied ? menu_text(UI_MENU_COOP_COPIED) : nullptr,
menu_text(UI_MENU_COOP_ROOM_ID_DESC), false) == 2 &&
plat_clipboard_set(g_view.code))
g_copied_at = now;
}
if (!g_view.local && opt_button("##coop_invite", UI_MENU_COOP_INVITE, UI_MENU_COOP_INVITE_DESC)) {
coop_friends_refresh();
open_window(P_INVITE, "##coop_invite");
}
if (g_invited_at && now - g_invited_at < 5000) {
char line[COOP_NAME_CAP + 64];
snprintf(line, sizeof line, menu_text(UI_MENU_COOP_INVITE_SENT), g_invited_name);
opt_text_str(line);
}
opt_group(UI_MENU_COOP_PLAYERS);
for (int i = 0; i < g_view.n; i++) {
const CoopPlayer &p = g_view.players[i];
char id[40], note[96], where[COOP_SCENE_CAP + 16];
snprintf(id, sizeof id, "##coop_player%d", i);
snprintf(note, sizeof note, "%s%s%s", p.self ? menu_text(UI_MENU_COOP_YOU) : "", p.self && p.host ? ", " : "",
p.host ? menu_text(UI_MENU_COOP_HOST) : "");
const bool here = p.self ? false : p.has_pose && p.pose.scene[0];
snprintf(where, sizeof where, "%s", p.self ? "" : here ? p.pose.scene : menu_text(UI_MENU_COOP_PLAYER_AWAY));
const bool removable = g_view.host && !p.self;
if (opt_text_row(id, p.name[0] ? p.name : "…", where, note[0] ? note : nullptr,
menu_text(removable ? UI_MENU_COOP_PLAYER_REMOVE_DESC : UI_MENU_COOP_PLAYER_DESC), false) == 2 &&
removable) {
g_remove_id = p.id;
snprintf(g_remove_name, sizeof g_remove_name, "%s", p.name);
open_window(P_REMOVE, id);
}
}
opt_group(UI_MENU_COOP_CHAT);
for (int i = 0; i < g_view.nchat; i++) {
char line[COOP_NAME_CAP + COOP_CHAT_CAP + 8];
chat_text(g_view.chat[i], line, sizeof line);
opt_text_str(line);
}
if (opt_button("##coop_chat", UI_MENU_COOP_CHAT_WRITE, UI_MENU_COOP_CHAT_WRITE_DESC)) open_window(P_CHAT, "##coop_chat");
if (opt_button("##coop_leave", UI_MENU_COOP_LEAVE, UI_MENU_COOP_LEAVE_DESC)) open_window(P_LEAVE, "##coop_leave");
settings_rows();
}
void coop_rows(float scale) {
(void)scale;
coop_view(&g_view);
pending_tick();
// the page changes its rows when the player gets into a room, reaches for one or leaves it: the cursor goes to a row
// of the new page whose press changes nothing at once
const int layout = in_room() ? 2 : g_view.state == COOP_ENTERING || g_pending ? 1 : 0;
if (layout != g_layout) {
if (g_layout >= 0) opt_focus_key(layout == 2 ? "##coop_code" : layout == 1 ? "##coop_stop" : "##coop_join");
g_layout = layout;
}
if (layout == 2) rows_room();
else rows_out();
}
// ---- the window
// The cursor on the item just drawn, shown (as option_rows.cpp puts it on a row). SetItemDefaultFocus as well: on the
// window's first frame ImGui's own pick of a first item would replace the cursor set here.
static void take_cursor(void) {
ImGui::SetItemDefaultFocus();
ImGui::SetFocusID(ImGui::GetItemID(), ImGui::GetCurrentWindow());
ImGui::SetNavCursorVisible(true);
}
static bool field_page(void) { return g_page == P_JOIN || g_page == P_CHAT; }
// Two buttons side by side, the safe one first: 1 the first, 2 the second. The cursor goes to the safe one when the
// window opens (fresh); in a field's window typed by keyboard the field has the cursor instead. ImGui activates a
// button on a press, not on a held key's repeats.
static int two_buttons(const char *no, const char *yes, bool yes_enabled, bool fresh, float scale) {
const ImGuiStyle &st = ImGui::GetStyle();
float bw = (ImGui::CalcTextSize(no).x > ImGui::CalcTextSize(yes).x ? ImGui::CalcTextSize(no).x : ImGui::CalcTextSize(yes).x) +
st.FramePadding.x * 4;
char id[160];
snprintf(id, sizeof id, "%s##no", no);
int r = skin_widget_button(id, ImVec2(bw, 0), scale) ? 1 : 0;
if (fresh && !(field_page() && !g_by_pad)) take_cursor();
ImGui::SameLine(0, st.ItemSpacing.x + skin_cursor_reach(scale));
ImGui::BeginDisabled(!yes_enabled);
snprintf(id, sizeof id, "%s##yes", yes);
if (skin_widget_button(id, ImVec2(bw, 0), scale)) r = 2;
ImGui::EndDisabled();
return r;
}
static void gold(const char *text) {
ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(SKIN_GOLD));
ImGui::TextUnformatted(text);
ImGui::PopStyleColor();
}
static void warn(const char *text) { ImGui::TextColored(ImVec4(0.95f, 0.45f, 0.35f, 1), "%s", text); }
// A pasted room ID: the characters one is typed with, no line ends or tabs.
static void take_paste(const char *text) {
char out[32];
size_t k = 0;
for (const char *p = text; *p && k + 1 < sizeof out; p++)
if ((*p >= '0' && *p <= '9') || (*p >= 'A' && *p <= 'Z') || (*p >= 'a' && *p <= 'z') || *p == '-')
out[k++] = *p >= 'a' && *p <= 'z' ? (char)(*p - 'a' + 'A') : *p;
out[k] = 0;
g_paste_empty = !k;
if (k) snprintf(g_field, sizeof g_field, "%s", out), g_field_bad = false;
}
static void trimmed(char *out, size_t cap) {
const char *s = g_field;
while (*s == ' ') s++;
size_t n = strlen(s);
while (n && s[n - 1] == ' ') n--;
snprintf(out, cap, "%.*s", (int)n, s);
}
// The field's window: a room ID (Cancel, Join; Paste) or a chat line (Cancel, Send).
static void field_window(bool fresh, float scale, float wrap, bool *close, bool *back) {
const bool join = g_page == P_JOIN;
gold(menu_text(join ? UI_MENU_COOP_ROOM_ID : UI_MENU_COOP_CHAT_WRITE));
if (join) ImGui::TextDisabled("%s", menu_text(UI_MENU_COOP_ROOM_ID_HINT));
if (fresh && !g_by_pad) ImGui::SetKeyboardFocusHere();
ImGui::SetNextItemWidth(wrap);
const bool enter = ImGui::InputText("##coop_field", g_field, join ? 24 : sizeof g_field,
ImGuiInputTextFlags_EnterReturnsTrue | (join ? ImGuiInputTextFlags_CharsUppercase : 0));
if (ImGui::IsItemEdited()) g_field_bad = g_paste_empty = false;
if (join) {
char text[256];
if (g_paste_wait > 0 && menu_paste_take(text, sizeof text)) take_paste(text), g_paste_wait = 0;
else if (g_paste_wait > 0) g_paste_wait--;
const float bw = ImGui::CalcTextSize(menu_text(UI_MENU_COOP_PASTE)).x + ImGui::GetStyle().FramePadding.x * 4;
if (skin_widget_button(menu_text(UI_MENU_COOP_PASTE), ImVec2(bw, 0), scale)) {
menu_paste_take(text, sizeof text); // an answer of an earlier Paste is not this one's
gfx_window_paste();
g_paste_wait = PASTE_FRAMES;
}
if (g_field_bad) warn(menu_text(UI_MENU_COOP_ROOM_ID_BAD));
if (g_paste_empty) warn(menu_text(UI_MENU_COOP_PASTE_EMPTY));
}
ImGui::Spacing();
char text[FIELD_CAP];
trimmed(text, sizeof text);
const int r = two_buttons(menu_text(UI_MENU_RESET_NO), menu_text(join ? UI_MENU_COOP_JOIN : UI_MENU_COOP_SEND), text[0] != 0, fresh, scale);
if (r == 1) *back = true;
if ((r != 2 && !enter) || !text[0]) return;
if (join) {
if (!steam_code_parse(text)) {
g_field_bad = true;
return;
}
want_room(2, text);
} else {
coop_chat(text);
}
*close = true;
}
// The player's friends, each a button that sends the invite; Steam's own window when the game was started from Steam.
static void invite_window(bool fresh, float scale, bool *close, bool *back) {
static uint32_t serial;
if (fresh || serial != g_view.friends_serial) serial = g_view.friends_serial, g_nfriends = coop_friends(g_friends, COOP_FRIENDS);
gold(menu_text(UI_MENU_COOP_INVITE_TITLE));
const float bw = ImGui::GetFontSize() * 22;
if (skin_widget_button(menu_text(UI_MENU_COOP_INVITE_CLOSE), ImVec2(bw, 0), scale)) *back = true;
if (fresh) take_cursor();
if (g_view.overlay && skin_widget_button(menu_text(UI_MENU_COOP_INVITE_STEAM), ImVec2(bw, 0), scale)) {
coop_invite_window();
*close = true;
}
if (!g_nfriends) ImGui::TextDisabled("%s", menu_text(UI_MENU_COOP_INVITE_NONE));
ImGui::BeginChild("##coop_friends", ImVec2(bw + ImGui::GetStyle().ScrollbarSize + skin_cursor_reach(scale) * 2, ImGui::GetFontSize() * 14),
ImGuiChildFlags_NavFlattened);
for (int i = 0; i < g_nfriends; i++) {
const SteamFriend &f = g_friends[i];
char label[STEAM_NAME_CAP + 64];
snprintf(label, sizeof label, "%s (%s)##f%d", f.name, menu_text(f.in_app ? UI_MENU_COOP_INVITE_IN_GAME : f.online ? UI_MENU_COOP_INVITE_ONLINE
: UI_MENU_COOP_INVITE_OFFLINE), i);
if (skin_widget_button(label, ImVec2(bw, 0), scale)) {
coop_invite(f.id);
snprintf(g_invited_name, sizeof g_invited_name, "%s", f.name);
g_invited_at = plat_now_ms();
*close = true;
}
}
ImGui::EndChild();
}
static void confirm_window(bool fresh, float scale, bool *close, bool *back) {
const bool remove = g_page == P_REMOVE;
char line[COOP_NAME_CAP + 160];
if (remove) snprintf(line, sizeof line, menu_text(UI_MENU_COOP_REMOVE_CONFIRM), g_remove_name);
else snprintf(line, sizeof line, "%s", menu_text(UI_MENU_COOP_LEAVE_CONFIRM));
gold(line);
if (!remove && g_view.host && g_view.n > 1) ImGui::TextUnformatted(menu_text(UI_MENU_COOP_LEAVE_HOST));
ImGui::Spacing();
const int r = two_buttons(menu_text(remove ? UI_MENU_RESET_NO : UI_MENU_COOP_STAY), menu_text(remove ? UI_MENU_COOP_REMOVE : UI_MENU_COOP_LEAVE),
true, fresh, scale);
if (r == 1) *back = true;
if (r == 2) {
if (remove) coop_remove(g_remove_id);
else coop_leave(), g_return[0] = 0; // the page's rows change; coop_rows puts the cursor on the new page
*close = true;
}
}
void coop_after_page(float scale) {
g_window_shown = false;
if (g_open && !ImGui::IsPopupOpen("##coopwin")) ImGui::OpenPopup("##coopwin");
ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
ImGui::PushStyleVar(ImGuiStyleVar_PopupBorderSize, 0);
const bool shown = ImGui::BeginPopupModal("##coopwin", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize);
ImGui::PopStyleVar();
if (!shown) {
g_open = false;
return;
}
g_window_shown = true;
// a window opened since the last frame: latched and cleared before it is drawn (as the Saves tab's file window)
const bool fresh = g_page_new;
g_page_new = false;
const ImVec2 box = ImGui::GetWindowPos(), box_size = ImGui::GetWindowSize();
skin_panel(ImGui::GetWindowDrawList(), box, ImVec2(box.x + box_size.x, box.y + box_size.y), scale);
const float wrap = ImGui::GetFontSize() * 30;
bool close = false, back = false;
ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + wrap);
const bool needs_room = g_page == P_CHAT || g_page == P_INVITE || g_page == P_REMOVE || g_page == P_LEAVE;
if (needs_room && !in_room()) close = true; // the room ended under the window
else if (field_page()) field_window(fresh, scale, wrap, &close, &back);
else if (g_page == P_INVITE) invite_window(fresh, scale, &close, &back);
else if (g_page == P_REMOVE || g_page == P_LEAVE) confirm_window(fresh, scale, &close, &back);
else close = true;
ImGui::PopTextWrapPos();
if (!fresh && !ImGui::IsAnyItemActive() &&
(ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false))) {
back = true;
menu_sound_play(MENU_SOUND_CANCEL);
}
if (back || close) {
g_open = false;
g_page = P_NONE;
g_field[0] = 0;
ImGui::CloseCurrentPopup();
if (g_return[0]) opt_focus_key(g_return); // back on the row that opened it
}
ImGui::EndPopup();
}
bool coop_modal(void) { return g_open || g_window_shown; }
void coop_cancel(void) {
g_open = false;
g_page = P_NONE;
g_field[0] = 0;
}
int coop_test_set(const char *key, const char *value) {
if (strcmp(key, "NX2NAVI_COOP_DO")) return 0;
coop_view(&g_view);
if (!strcmp(value, "create")) want_room(1, nullptr);
else if (!strcmp(value, "leave")) coop_leave();
else if (!strncmp(value, "join:", 5)) want_room(2, value + 5);
else if (!strncmp(value, "chat:", 5)) coop_chat(value + 5);
else if (!strcmp(value, "page:join")) open_window(P_JOIN, "##coop_join");
else if (!strcmp(value, "page:invite")) coop_friends_refresh(), open_window(P_INVITE, "##coop_invite");
else if (!strcmp(value, "page:chat")) open_window(P_CHAT, "##coop_chat");
else if (!strcmp(value, "page:leave")) open_window(P_LEAVE, "##coop_leave");
g_by_pad = true; // the cursor as a pad's A would leave it: on the safe button
return 1;
}
// ---- over the game
static CoopView g_over;
static bool g_over_on;
bool coop_overlay_tick(void) {
static unsigned cfg_seen = ~0u;
static uint32_t serial;
if (unsigned v = cfg_version(); v != cfg_seen) cfg_seen = v, g_over_on = cfg_bool("NX2NAVI_COOP_STEAM") != 0;
if (!g_over_on) return false;
if (uint32_t s = coop_serial(); s != serial) serial = s, coop_view(&g_over);
if (g_over.invite_room) return true;
if (g_over.state != COOP_IN_ROOM) return false;
if (g_over.n > 1) return true;
const uint64_t now = plat_now_ms();
return g_over.nchat && now - g_over.chat[g_over.nchat - 1].at_ms < CHAT_SHOWN_MS;
}
// The label of a small panel centred on x, its top at y.
static float label(ImDrawList *dl, float x, float y, const char *text, float scale, float alpha) {
const float padx = 10 * scale, pady = 5 * scale;
const ImVec2 sz = ImGui::CalcTextSize(text);
const ImVec2 p(x - sz.x * 0.5f - padx, y);
skin_panel(dl, p, ImVec2(p.x + sz.x + padx * 2, p.y + sz.y + pady * 2), scale * 0.5f, 0.85f * alpha);
dl->AddText(ImVec2(p.x + padx, p.y + pady), IM_COL32(244, 236, 214, (int)(255 * alpha)), text);
return sz.y + pady * 2;
}
void coop_overlay_draw(float w, float h, float scale, bool menu_open) {
if (!g_over_on) return;
const uint64_t now = plat_now_ms();
ImDrawList *dl = menu_open ? ImGui::GetBackgroundDrawList() : ImGui::GetForegroundDrawList();
// the other players' names where their Link stands, in the area this game's Link is in
VkDlaaCamera cam;
const CoopPlayer *me = nullptr;
for (int i = 0; i < g_over.n; i++)
if (g_over.players[i].self) me = &g_over.players[i];
if (!menu_open && g_over.state == COOP_IN_ROOM && cfg_bool("NX2NAVI_COOP_NAMES") && vk_dlaa_fg_camera(&cam)) {
const float ty = tanf(cam.fov_y * 0.5f), tx = ty * cam.aspect;
// the game's picture in the frame: centred, with bars above and below or at the sides when its shape differs
const float pw = cam.aspect > w / h ? w : h * cam.aspect, ph = cam.aspect > w / h ? w / cam.aspect : h;
for (int i = 0; i < g_over.n; i++) {
const CoopPlayer &p = g_over.players[i];
if (p.self || !p.has_pose || !p.pose.scene[0]) continue;
// only a player in the area this game's Link is in
if (me && me->has_pose && me->pose.scene[0] && strcmp(me->pose.scene, p.pose.scene)) continue;
// a moment ahead along the velocity: the pose is up to a twentieth of a second old
float age = (float)p.pose_ms / 1000.0f;
if (age > 0.25f) age = 0.25f;
float d[3];
for (int k = 0; k < 3; k++) d[k] = p.pose.pos[k] + p.pose.vel[k] * age - cam.pos[k];
d[1] += 1.9f; // above the head of an adult Link; a child's name floats a little higher
const float z = d[0] * cam.fwd[0] + d[1] * cam.fwd[1] + d[2] * cam.fwd[2];
float x = d[0] * cam.right[0] + d[1] * cam.right[1] + d[2] * cam.right[2];
float y = d[0] * cam.up[0] + d[1] * cam.up[1] + d[2] * cam.up[2];
const float dist = sqrtf(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
char text[COOP_NAME_CAP + 24];
snprintf(text, sizeof text, "%s %.0f m", p.name[0] ? p.name : "?", dist);
float nx, ny;
bool on_screen = z > 0.1f;
if (on_screen) {
nx = x / (z * tx), ny = y / (z * ty);
on_screen = fabsf(nx) < 0.96f && fabsf(ny) < 0.92f;
}
if (!on_screen) {
// beside or behind the picture: at its edge, in the direction to turn to
float len = sqrtf(x * x + y * y);
if (len < 1e-4f) x = 1, y = 0, len = 1;
nx = x / len, ny = y / len;
const float m = fabsf(nx) / 0.96f > fabsf(ny) / 0.88f ? fabsf(nx) / 0.96f : fabsf(ny) / 0.88f;
nx /= m, ny /= m;
}
label(dl, w * 0.5f + nx * 0.5f * pw, h * 0.5f - ny * 0.5f * ph, text, scale, on_screen ? 1.0f : 0.75f);
}
}
if (menu_open) return;
float y = 12 * scale;
if (g_over.invite_room) {
char text[COOP_NAME_CAP + 160];
snprintf(text, sizeof text, menu_text(UI_MENU_COOP_TOAST_INVITE), g_over.invite_from);
y += label(dl, w * 0.5f, y, text, scale * 1.2f, 1) + 6 * scale;
}
if (g_over.state == COOP_IN_ROOM && cfg_bool("NX2NAVI_COOP_CHAT")) {
// the top middle: the game's hearts and rupees are at the left, the performance overlay at the right
for (int i = 0; i < g_over.nchat; i++) {
const uint64_t age = now - g_over.chat[i].at_ms;
if (age >= CHAT_SHOWN_MS) continue;
const float alpha = age > CHAT_SHOWN_MS - CHAT_FADE_MS ? (float)(CHAT_SHOWN_MS - age) / CHAT_FADE_MS : 1.0f;
char text[COOP_NAME_CAP + COOP_CHAT_CAP + 8];
chat_text(g_over.chat[i], text, sizeof text);
y += label(dl, w * 0.5f, y, text, scale * 1.2f, alpha) + 6 * scale;
}
}
}

View File

@@ -1,24 +0,0 @@
// The menu's Co-op tab and what co-op draws over the game (ui/coop_page.cpp, docs/coop.md). Present path only (ImGui).
#pragma once
// Inside the page's opt_begin / opt_end. Co-op off: its switch. Steam not there: why, and Look for Steam again. In no
// room: an invite that waits, Create a room, Join a room, the settings. In a room: the room ID (a press copies it),
// Invite a friend, the players (the host's press removes one), the chat and Leave.
void coop_rows(float scale);
// After opt_end: the window a row opens: a room ID or a chat line to type, the friends to invite, and the
// confirmations of Remove and Leave, each opening with the cursor on its safe button.
void coop_after_page(float scale);
// The window is open: B, Esc, L / R and the tab keys stay with it.
bool coop_modal(void);
// The menu opened or closed (menu.cpp): the window closes.
void coop_cancel(void);
// NX2NAVI_MENU_TEST_SET pseudo-keys (menu.cpp test_apply_sets), from the environment only: COOP_DO=create | leave |
// join:<room id> | chat:<text> | page:join | page:invite | page:chat | page:leave does what the row or the window's
// button does. 1 when key is one of them.
int coop_test_set(const char *key, const char *value);
// Over the game, menu open or not: the other players' names where they stand, and while the menu is closed the chat's
// new lines and an invite that waits. coop_overlay_tick on every overlay frame (it costs a copy of the co-op view while
// co-op is on): true while there is something to draw. coop_overlay_draw draws into a w x h frame.
bool coop_overlay_tick(void);
void coop_overlay_draw(float w, float h, float scale, bool menu_open);

View File

@@ -37,12 +37,12 @@ static int g_font_bad;
#include "ui/amiibo_page.h"
#include "ui/binds_page.h"
#include "ui/debug_menu.h"
#include "ui/coop_page.h"
#include "ui/option_rows.h"
#include "ui/perf_panel.h"
extern "C" {
#include "amiibo.h"
#include "bugcap.h"
#include "cheats.h"
#include "debug_tools.h"
#include "cfg.h"
@@ -201,7 +201,7 @@ extern "C" void menu_event_mouse_pos(float x, float y) { push({EV_POS, 0, 0, x,
extern "C" void menu_event_mouse_button(int button, int down) { push({EV_BUTTON, button, down, 0, 0}); }
extern "C" void menu_event_wheel(float dx, float dy) { push({EV_WHEEL, 0, 0, dx, dy}); }
extern "C" void menu_event_focus(int focused) { push({EV_FOCUS, focused, 0, 0, 0}); }
// a typed character, for the text fields of the co-op page and the debug menu
// a typed character, for the text fields of the debug menu
extern "C" void menu_event_char(unsigned c) { push({EV_CHAR, (int)c, 0, 0, 0}); }
// The clipboard's text a page asked for (gfx_window_paste): the window thread reads it, the page takes it a frame later.
@@ -515,7 +515,7 @@ static int fonts_up(float scale) {
// what the title face shows in the CJK languages: the menu's title and tabs (Simplified Chinese menu text) and
// the boot screen's title (the game's language)
static const UiTextId titles[] = {UI_MENU_TITLE, UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND,
UI_MENU_TAB_CONTROLS, UI_MENU_TAB_COOP, UI_BOOT_TITLE};
UI_MENU_TAB_CONTROLS, UI_BOOT_TITLE};
for (int i = 0; i < N; i++) {
if (!data[i]) continue;
ImFontGlyphRangesBuilder b;
@@ -581,10 +581,9 @@ extern "C" void menu_vk_release(void) {
// optional) at that presented frame; changes live settings with no input, menu open or not. nx2navi.ini is written only by
// the pseudo-key SAVE=1 (cfg_save, as a row change does; a failed write shows the menu's save note). FOCUS=<key> (the
// NX2NAVI_ prefix optional) puts the cursor on that setting's row and scrolls it into view when the row is next drawn
// (opt_focus_key), so a page's shot shows a row below the first screenful; it does not switch tabs. COOP_DO drives the
// Co-op tab (ui/coop_page.h coop_test_set).
// Ocarina of Time: the options this port has, and co-op (ui/coop_page.cpp)
enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_COOP, TAB_COUNT };
// (opt_focus_key), so a page's shot shows a row below the first screenful; it does not switch tabs.
// Ocarina of Time: the options this port has
enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_COUNT };
enum { TEST_PAGE_FRAMES = 30, TEST_SETS = 16, TEST_OPENS = 8 };
struct TestSet { uint64_t frame; char key[64], value[64]; };
static struct {
@@ -650,11 +649,7 @@ static void test_apply_sets(uint64_t frame) {
char row[80];
snprintf(row, sizeof row, "%s%s", strncmp(t.value, "NX2NAVI_", strlen("NX2NAVI_")) ? "NX2NAVI_" : "", t.value);
opt_focus_key(row);
} else if (!strcmp(t.key, "NX2NAVI_COOP_DO") && !cfg_from_env("NX2NAVI_MENU_TEST_SET")) {
// From nx2navi.ini the hook drives no part of the Co-op tab: a settings file someone hands a player could
// otherwise put them into a room. A test sets it in the environment.
rt_log("menu: test hook: %s is taken from the environment only, not from nx2navi.ini", t.key);
} else if (!coop_test_set(t.key, t.value)) {
} else {
cfg_set(t.key, t.value);
}
}
@@ -1798,16 +1793,8 @@ static void rows_low_end(void) {
#endif
}
// The Co-op tab (ui/coop_page.cpp): the rows, then the window a row opens.
static void tab_coop(float scale) {
opt_begin("##coop", scale);
coop_rows(scale);
opt_end();
coop_after_page(scale);
}
static const UiTextId kTabNames[TAB_COUNT] = {UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND,
UI_MENU_TAB_CONTROLS, UI_MENU_TAB_COOP};
UI_MENU_TAB_CONTROLS};
static int g_tab; // the tab shown
static int g_tab_request = -1; // select this tab at the next layout; -1 none
static int g_focus_page = -1; // this tab's first row takes the cursor once it is shown; -1 none
@@ -1894,7 +1881,7 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) {
}
// a text field takes Q and E as letters, and a window of a page keeps the tab keys
const bool keeps_keys = g_modal || binds_modal() || coop_modal() || ImGui::GetIO().WantTextInput;
const bool keeps_keys = g_modal || binds_modal() || ImGui::GetIO().WantTextInput;
int step = keeps_keys ? 0
: ImGui::IsKeyPressed(ImGuiKey_GamepadR1, false) || ImGui::IsKeyPressed(ImGuiKey_E, false) ? 1
: ImGui::IsKeyPressed(ImGuiKey_GamepadL1, false) || ImGui::IsKeyPressed(ImGuiKey_Q, false) ? -1
@@ -1928,7 +1915,6 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) {
case TAB_GAME: tab_game(scale); break;
case TAB_SOUND: tab_sound(scale); break;
case TAB_CONTROLS: tab_controls(scale); break;
case TAB_COOP: tab_coop(scale); break;
}
ImGui::EndTabItem();
}
@@ -1988,7 +1974,7 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) {
if (skin_widget_button(quit, ImVec2(bw, 0), scale)) g_confirm_quit = true, ImGui::OpenPopup("##confirm");
restart_confirm(scale);
menu_sounds_frame();
bool was_modal = g_modal || binds_modal() || coop_modal() || ImGui::GetIO().WantTextInput;
bool was_modal = g_modal || binds_modal() || ImGui::GetIO().WantTextInput;
if (!was_modal && (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)))
set_open(0);
ImGui::End();
@@ -2154,6 +2140,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) {
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, 12 * scale);
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)
@@ -2169,7 +2173,9 @@ static int overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot)
if (g_perf_save.exchange(0)) cfg_save();
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
@@ -2187,7 +2193,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 && !capture_shows) {
return 0;
}
}
@@ -2221,7 +2227,6 @@ static int overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot)
io.ClearInputKeys();
io.ClearInputMouse();
binds_cancel(); // a cell waiting for a press when the menu closed: no press binds on the next opening
coop_cancel(); // the Co-op tab's window closes
g_sound_fresh = true;
g_last_ns = 0;
g_focus_page = g_tab_request >= 0 ? g_tab_request : g_tab; // opening: the first row has the cursor
@@ -2253,7 +2258,7 @@ static int overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot)
layout_menu(t->width, t->height, scale);
}
perf_draw(t, scale);
if (coop_draws) coop_overlay_draw((float)t->width, (float)t->height, scale, open);
capture_note(t, scale);
ImGui::Render();
if (open) g_save_pending = opt_save_tick(0);
g_cost_ns += plat_now_ns() - t0;

View File

@@ -681,96 +681,9 @@ static const char *const text_en[UI_TEXT_COUNT] = {
[UI_MENU_SAVE_E_NEWER] = "%s was made by a newer NX2navi: update NX2navi first.",
[UI_MENU_SAVE_E_DAMAGED] = "%s is damaged: download it again.",
[UI_MENU_SAVE_E_UNSAFE] = "%s was refused: it holds files outside a save, links, or far more than a save.",
[UI_MENU_TAB_COOP] = "Co-op",
[UI_MENU_COOP_ON] = "Co-op (experimental)",
[UI_MENU_COOP_ON_DESC] = "Play with friends over Steam, each in their own game and save. Nobody sets up a router: rooms "
"and invites go through Steam, which shows you as playing Spacewar, its test app. Needs Steam "
"running; the launcher takes Steam's library file from a Steam game you have installed. Off: the "
"game uses no network.",
[UI_MENU_COOP_NO_LIBRARY] = "Steam's library file, steam_api64.dll, is not beside the game. The launcher puts it there when "
"it starts the game, from a Steam game you have installed: start the game from the launcher, with "
"Steam and at least one game from 2021 or later installed. You can also copy the file yourself "
"from a Steam game's folder into the folder of ocarina.exe.",
[UI_MENU_COOP_OLD_LIBRARY] = "The steam_api64.dll beside the game is too old for co-op. Replace it with one from a newer Steam "
"game.",
[UI_MENU_COOP_NO_CLIENT] = "Steam did not answer. Start Steam and sign in, then choose Look for Steam again.",
[UI_MENU_COOP_RETRY] = "Look for Steam again",
[UI_MENU_COOP_RETRY_DESC] = "Tries now to reach Steam; the game also tries by itself every few seconds.",
[UI_MENU_COOP_CREATE] = "Create a room",
[UI_MENU_COOP_CREATE_DESC] = "Makes a room for up to four players. You get a room ID to pass on, and you can invite Steam "
"friends.",
[UI_MENU_COOP_JOIN] = "Join a room",
[UI_MENU_COOP_JOIN_DESC] = "Joins the room whose ID a friend gave you.",
[UI_MENU_COOP_ROOM_ID] = "Room ID",
[UI_MENU_COOP_ROOM_ID_DESC] = "Friends type this into Join a room. Press to copy it. Anyone who has it can join, so pass it on "
"only to the people you want in your game.",
[UI_MENU_COOP_ROOM_ID_HINT] = "8 letters and digits, as XXXX-XXXX: any case, with or without the dash.",
[UI_MENU_COOP_ROOM_ID_BAD] = "This is not a room ID: check it for a mistyped character.",
[UI_MENU_COOP_PASTE] = "Paste",
[UI_MENU_COOP_PASTE_EMPTY] = "The clipboard has no text.",
[UI_MENU_COOP_COPIED] = "copied",
[UI_MENU_COOP_OK] = "OK",
[UI_MENU_COOP_JOINING] = "Getting into the room…",
[UI_MENU_COOP_STOP] = "Stop",
[UI_MENU_COOP_STOP_DESC] = "Stops trying to get into the room.",
[UI_MENU_COOP_INVITE] = "Invite a friend",
[UI_MENU_COOP_INVITE_DESC] = "Sends a Steam invite to a friend. It reaches a friend whose NX2navi is running with co-op on; "
"anyone else can use the room ID.",
[UI_MENU_COOP_INVITE_TITLE] = "Invite a Steam friend",
[UI_MENU_COOP_INVITE_NONE] = "Steam shows no friends.",
[UI_MENU_COOP_INVITE_SENT] = "Invite sent to %s.",
[UI_MENU_COOP_INVITE_IN_GAME] = "in co-op now",
[UI_MENU_COOP_INVITE_ONLINE] = "online",
[UI_MENU_COOP_INVITE_OFFLINE] = "offline",
[UI_MENU_COOP_INVITE_STEAM] = "Steam's invite window",
[UI_MENU_COOP_INVITE_CLOSE] = "Close",
[UI_MENU_COOP_INVITED] = "%s invites you to a room.",
[UI_MENU_COOP_INVITED_JOIN] = "Join their room",
[UI_MENU_COOP_INVITED_JOIN_DESC] = "Joins the room you were invited to.",
[UI_MENU_COOP_INVITED_NO] = "Not now",
[UI_MENU_COOP_INVITED_NO_DESC] = "Puts the invite away.",
[UI_MENU_COOP_PLAYERS] = "Players",
[UI_MENU_COOP_YOU] = "you",
[UI_MENU_COOP_HOST] = "host",
[UI_MENU_COOP_PLAYER_DESC] = "A player in the room, and the area their Link is in.",
[UI_MENU_COOP_PLAYER_REMOVE_DESC] = "A player in the room. As the host you can press to remove them from the room.",
[UI_MENU_COOP_PLAYER_AWAY] = "not in the world",
[UI_MENU_COOP_REMOVE] = "Remove",
[UI_MENU_COOP_REMOVE_CONFIRM] = "Remove %s from the room? They cannot come back into this room.",
[UI_MENU_COOP_LEAVE] = "Leave the room",
[UI_MENU_COOP_LEAVE_DESC] = "Leaves the room. Your game and save go on as they are.",
[UI_MENU_COOP_LEAVE_CONFIRM] = "Leave the room?",
[UI_MENU_COOP_LEAVE_HOST] = "You are the host: the room goes on with another player as its host.",
[UI_MENU_COOP_STAY] = "Stay",
[UI_MENU_COOP_CHAT] = "Chat",
[UI_MENU_COOP_CHAT_WRITE] = "Write a message",
[UI_MENU_COOP_CHAT_WRITE_DESC] = "Sends a line of text to everyone in the room.",
[UI_MENU_COOP_SEND] = "Send",
[UI_MENU_COOP_CHAT_JOINED] = "%s joined the room",
[UI_MENU_COOP_CHAT_LEFT] = "%s left the room",
[UI_MENU_COOP_SETTINGS] = "Co-op settings",
[UI_MENU_COOP_SHARE] = "Share progress",
[UI_MENU_COOP_SHARE_DESC] = "In a room, what anyone achieves counts for everyone: story progress, chests, doors, items and "
"songs. Before anything from a room reaches your save, the save is copied to coop-backup in the "
"profile folder. Small keys, rupees, ammunition and hearts stay your own. Off: only names and "
"chat are shared.",
[UI_MENU_COOP_NAMES] = "Show player names",
[UI_MENU_COOP_NAMES_DESC] = "Shows the name of each other player where their Link stands in your world, with the distance. "
"Needs DLSS, FSR or TAA on (the game tells the menu where the camera looks only then).",
[UI_MENU_COOP_CHAT_SHOW] = "Show chat over the game",
[UI_MENU_COOP_CHAT_SHOW_DESC] = "New chat lines and who joined or left show for a few seconds while the menu is closed.",
[UI_MENU_COOP_N_CREATE_FAILED] = "Steam could not make the room. Try again in a moment.",
[UI_MENU_COOP_N_NO_ROOM] = "No room has this ID: check it, or ask your friend whether the room is still open.",
[UI_MENU_COOP_N_FULL] = "The room is full.",
[UI_MENU_COOP_N_REFUSED] = "The room did not let you in.",
[UI_MENU_COOP_N_NOT_OURS] = "That is not an NX2navi room.",
[UI_MENU_COOP_N_OTHER_VERSION] = "The room's host runs another version of NX2navi or of the game: use the same versions.",
[UI_MENU_COOP_N_REMOVED] = "The host removed you from the room.",
[UI_MENU_COOP_N_HOST_SILENT] = "The room's host did not answer.",
[UI_MENU_COOP_N_LOST] = "Steam lost its connection; the room is gone.",
[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_BOOT_COMPUTE] = "Compute pipelines: %lld of %lld", [UI_BOOT_DRIVER_CACHE] = "Driver cache: %lld of %lld",
@@ -1374,97 +1287,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
[UI_MENU_SAVE_E_NEWER] = "%s создан более новой версией NX2navi: сначала обновите NX2navi.",
[UI_MENU_SAVE_E_DAMAGED] = "%s повреждён: скачайте его заново.",
[UI_MENU_SAVE_E_UNSAFE] = "%s отклонён: в нём файлы вне сохранения, ссылки или слишком много данных.",
[UI_MENU_TAB_COOP] = "Кооператив",
[UI_MENU_COOP_ON] = "Кооператив (эксперимент)",
[UI_MENU_COOP_ON_DESC] = "Играйте с друзьями через Steam, каждый в своей игре и со своим сохранением. Настраивать роутер "
"не нужно: комнаты и приглашения идут через Steam, который показывает, что вы играете в Spacewar, "
"его тестовое приложение. Нужен запущенный Steam; файл его библиотеки лаунчер берёт из "
"установленной у вас игры Steam. Выкл.: игра не использует сеть.",
[UI_MENU_COOP_NO_LIBRARY] = "Файла библиотеки Steam, steam_api64.dll, нет рядом с игрой. Лаунчер кладёт его туда при запуске "
"игры, из установленной у вас игры Steam: запустите игру из лаунчера при установленном Steam и "
"хотя бы одной игре 2021 года или новее. Можно и самому скопировать файл из папки любой игры "
"Steam в папку с ocarina.exe.",
[UI_MENU_COOP_OLD_LIBRARY] = "Файл steam_api64.dll рядом с игрой слишком старый для кооператива. Замените его файлом из более "
"новой игры Steam.",
[UI_MENU_COOP_NO_CLIENT] = "Steam не ответил. Запустите Steam, войдите в аккаунт и выберите «Искать Steam снова».",
[UI_MENU_COOP_RETRY] = "Искать Steam снова",
[UI_MENU_COOP_RETRY_DESC] = "Пробует связаться со Steam сейчас; игра и сама пробует каждые несколько секунд.",
[UI_MENU_COOP_CREATE] = "Создать комнату",
[UI_MENU_COOP_CREATE_DESC] = "Создаёт комнату до четырёх игроков. Вы получите ID комнаты, который можно передать, и сможете "
"пригласить друзей из Steam.",
[UI_MENU_COOP_JOIN] = "Войти в комнату",
[UI_MENU_COOP_JOIN_DESC] = "Вход в комнату, ID которой вам дал друг.",
[UI_MENU_COOP_ROOM_ID] = "ID комнаты",
[UI_MENU_COOP_ROOM_ID_DESC] = "Друзья вводят его в «Войти в комнату». Нажмите, чтобы скопировать. Войти может любой, у кого он "
"есть, поэтому передавайте его только тем, кого хотите видеть в своей игре.",
[UI_MENU_COOP_ROOM_ID_HINT] = "8 букв и цифр в виде XXXX-XXXX: в любом регистре, с дефисом или без.",
[UI_MENU_COOP_ROOM_ID_BAD] = "Это не ID комнаты: проверьте, нет ли опечатки.",
[UI_MENU_COOP_PASTE] = "Вставить",
[UI_MENU_COOP_PASTE_EMPTY] = "В буфере обмена нет текста.",
[UI_MENU_COOP_COPIED] = "скопировано",
[UI_MENU_COOP_OK] = "ОК",
[UI_MENU_COOP_JOINING] = "Вход в комнату…",
[UI_MENU_COOP_STOP] = "Остановить",
[UI_MENU_COOP_STOP_DESC] = "Прекращает попытку войти в комнату.",
[UI_MENU_COOP_INVITE] = "Пригласить друга",
[UI_MENU_COOP_INVITE_DESC] = "Отправляет другу приглашение через Steam. Оно дойдёт до друга, у которого запущена NX2navi с "
"включённым кооперативом; остальные могут воспользоваться ID комнаты.",
[UI_MENU_COOP_INVITE_TITLE] = "Пригласить друга из Steam",
[UI_MENU_COOP_INVITE_NONE] = "Steam не показывает друзей.",
[UI_MENU_COOP_INVITE_SENT] = "Приглашение отправлено: %s.",
[UI_MENU_COOP_INVITE_IN_GAME] = "сейчас в кооперативе",
[UI_MENU_COOP_INVITE_ONLINE] = "в сети",
[UI_MENU_COOP_INVITE_OFFLINE] = "не в сети",
[UI_MENU_COOP_INVITE_STEAM] = "Окно приглашений Steam",
[UI_MENU_COOP_INVITE_CLOSE] = "Закрыть",
[UI_MENU_COOP_INVITED] = "%s приглашает вас в комнату.",
[UI_MENU_COOP_INVITED_JOIN] = "Войти в их комнату",
[UI_MENU_COOP_INVITED_JOIN_DESC] = "Вход в комнату, в которую вас пригласили.",
[UI_MENU_COOP_INVITED_NO] = "Не сейчас",
[UI_MENU_COOP_INVITED_NO_DESC] = "Убирает приглашение.",
[UI_MENU_COOP_PLAYERS] = "Игроки",
[UI_MENU_COOP_YOU] = "вы",
[UI_MENU_COOP_HOST] = "хост",
[UI_MENU_COOP_PLAYER_DESC] = "Игрок в комнате и область, в которой находится его Линк.",
[UI_MENU_COOP_PLAYER_REMOVE_DESC] = "Игрок в комнате. Как хост вы можете нажать, чтобы удалить его из комнаты.",
[UI_MENU_COOP_PLAYER_AWAY] = "не в мире",
[UI_MENU_COOP_REMOVE] = "Удалить",
[UI_MENU_COOP_REMOVE_CONFIRM] = "Удалить %s из комнаты? Вернуться в эту комнату он не сможет.",
[UI_MENU_COOP_LEAVE] = "Выйти из комнаты",
[UI_MENU_COOP_LEAVE_DESC] = "Выход из комнаты. Ваша игра и сохранение остаются как есть.",
[UI_MENU_COOP_LEAVE_CONFIRM] = "Выйти из комнаты?",
[UI_MENU_COOP_LEAVE_HOST] = "Вы хост: комната продолжит работу, хостом станет другой игрок.",
[UI_MENU_COOP_STAY] = "Остаться",
[UI_MENU_COOP_CHAT] = "Чат",
[UI_MENU_COOP_CHAT_WRITE] = "Написать сообщение",
[UI_MENU_COOP_CHAT_WRITE_DESC] = "Отправляет строку текста всем в комнате.",
[UI_MENU_COOP_SEND] = "Отправить",
[UI_MENU_COOP_CHAT_JOINED] = "%s входит в комнату",
[UI_MENU_COOP_CHAT_LEFT] = "%s выходит из комнаты",
[UI_MENU_COOP_SETTINGS] = "Настройки кооператива",
[UI_MENU_COOP_SHARE] = "Общий прогресс",
[UI_MENU_COOP_SHARE_DESC] = "В комнате достижения любого игрока засчитываются всем: сюжет, сундуки, двери, предметы и песни. "
"Прежде чем что-либо из комнаты попадёт в ваше сохранение, оно копируется в coop-backup в папке "
"профиля. Малые ключи, рупии, боеприпасы и сердца остаются вашими. Выкл.: общими остаются только "
"имена и чат.",
[UI_MENU_COOP_NAMES] = "Показывать имена игроков",
[UI_MENU_COOP_NAMES_DESC] = "Показывает имя каждого другого игрока там, где его Линк стоит в вашем мире, и расстояние до "
"него. Нужны включённые DLSS, FSR или TAA (только тогда меню знает, куда смотрит камера).",
[UI_MENU_COOP_CHAT_SHOW] = "Показывать чат поверх игры",
[UI_MENU_COOP_CHAT_SHOW_DESC] = "Новые строки чата и сообщения о входе и выходе игроков показываются несколько секунд, пока меню "
"закрыто.",
[UI_MENU_COOP_N_CREATE_FAILED] = "Steam не смог создать комнату. Попробуйте ещё раз чуть позже.",
[UI_MENU_COOP_N_NO_ROOM] = "Комнаты с таким ID нет: проверьте его или спросите друга, открыта ли ещё комната.",
[UI_MENU_COOP_N_FULL] = "Комната заполнена.",
[UI_MENU_COOP_N_REFUSED] = "Комната вас не впустила.",
[UI_MENU_COOP_N_NOT_OURS] = "Это не комната NX2navi.",
[UI_MENU_COOP_N_OTHER_VERSION] = "У хоста комнаты другая версия NX2navi или игры: используйте одинаковые версии.",
[UI_MENU_COOP_N_REMOVED] = "Хост удалил вас из комнаты.",
[UI_MENU_COOP_N_HOST_SILENT] = "Хост комнаты не ответил.",
[UI_MENU_COOP_N_LOST] = "Steam потерял соединение; комнаты больше нет.",
[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_BOOT_COMPUTE] = "Вычислительные конвейеры: %lld из %lld", [UI_BOOT_DRIVER_CACHE] = "Кэш драйвера: %lld из %lld",
@@ -2041,96 +1866,9 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
[UI_MENU_SAVE_E_NEWER] = "%s foi feito por um NX2navi mais novo: atualize o NX2navi primeiro.",
[UI_MENU_SAVE_E_DAMAGED] = "%s está danificado: baixe-o de novo.",
[UI_MENU_SAVE_E_UNSAFE] = "%s foi recusado: contém arquivos fora de um save, links ou dados demais.",
[UI_MENU_TAB_COOP] = "Co-op",
[UI_MENU_COOP_ON] = "Co-op (experimental)",
[UI_MENU_COOP_ON_DESC] = "Jogue com amigos pela Steam, cada um no seu jogo e no seu save. Ninguém configura roteador: "
"salas e convites passam pela Steam, que mostra você jogando Spacewar, o app de teste dela. "
"Precisa da Steam aberta; o launcher pega o arquivo da biblioteca da Steam de um jogo da Steam "
"que você tem instalado. Desligado: o jogo não usa a rede.",
[UI_MENU_COOP_NO_LIBRARY] = "O arquivo da biblioteca da Steam, steam_api64.dll, não está ao lado do jogo. O launcher o coloca "
"lá ao iniciar o jogo, a partir de um jogo da Steam que você tem instalado: inicie o jogo pelo "
"launcher, com a Steam e pelo menos um jogo de 2021 ou mais novo instalados. Você também pode "
"copiar o arquivo da pasta de um jogo da Steam para a pasta do ocarina.exe.",
[UI_MENU_COOP_OLD_LIBRARY] = "O steam_api64.dll ao lado do jogo é antigo demais para o co-op. Troque por um de um jogo mais "
"novo da Steam.",
[UI_MENU_COOP_NO_CLIENT] = "A Steam não respondeu. Abra a Steam, entre na sua conta e escolha Procurar a Steam de novo.",
[UI_MENU_COOP_RETRY] = "Procurar a Steam de novo",
[UI_MENU_COOP_RETRY_DESC] = "Tenta falar com a Steam agora; o jogo também tenta sozinho a cada poucos segundos.",
[UI_MENU_COOP_CREATE] = "Criar uma sala",
[UI_MENU_COOP_CREATE_DESC] = "Cria uma sala para até quatro jogadores. Você recebe um ID da sala para passar adiante e pode "
"convidar amigos da Steam.",
[UI_MENU_COOP_JOIN] = "Entrar em uma sala",
[UI_MENU_COOP_JOIN_DESC] = "Entra na sala cujo ID um amigo passou para você.",
[UI_MENU_COOP_ROOM_ID] = "ID da sala",
[UI_MENU_COOP_ROOM_ID_DESC] = "Os amigos digitam isto em Entrar em uma sala. Pressione para copiar. Quem tiver o ID pode "
"entrar, então passe só para quem você quer no seu jogo.",
[UI_MENU_COOP_ROOM_ID_HINT] = "8 letras e números, como XXXX-XXXX: maiúsculas ou minúsculas, com ou sem o traço.",
[UI_MENU_COOP_ROOM_ID_BAD] = "Isto não é um ID de sala: veja se há algum caractere errado.",
[UI_MENU_COOP_PASTE] = "Colar",
[UI_MENU_COOP_PASTE_EMPTY] = "A área de transferência não tem texto.",
[UI_MENU_COOP_COPIED] = "copiado",
[UI_MENU_COOP_OK] = "OK",
[UI_MENU_COOP_JOINING] = "Entrando na sala…",
[UI_MENU_COOP_STOP] = "Parar",
[UI_MENU_COOP_STOP_DESC] = "Para de tentar entrar na sala.",
[UI_MENU_COOP_INVITE] = "Convidar um amigo",
[UI_MENU_COOP_INVITE_DESC] = "Envia um convite da Steam a um amigo. Ele chega a quem está com o NX2navi aberto e o co-op "
"ligado; os outros podem usar o ID da sala.",
[UI_MENU_COOP_INVITE_TITLE] = "Convidar um amigo da Steam",
[UI_MENU_COOP_INVITE_NONE] = "A Steam não mostra amigos.",
[UI_MENU_COOP_INVITE_SENT] = "Convite enviado para %s.",
[UI_MENU_COOP_INVITE_IN_GAME] = "no co-op agora",
[UI_MENU_COOP_INVITE_ONLINE] = "online",
[UI_MENU_COOP_INVITE_OFFLINE] = "offline",
[UI_MENU_COOP_INVITE_STEAM] = "Janela de convites da Steam",
[UI_MENU_COOP_INVITE_CLOSE] = "Fechar",
[UI_MENU_COOP_INVITED] = "%s convida você para uma sala.",
[UI_MENU_COOP_INVITED_JOIN] = "Entrar na sala",
[UI_MENU_COOP_INVITED_JOIN_DESC] = "Entra na sala para a qual você foi convidado.",
[UI_MENU_COOP_INVITED_NO] = "Agora não",
[UI_MENU_COOP_INVITED_NO_DESC] = "Dispensa o convite.",
[UI_MENU_COOP_PLAYERS] = "Jogadores",
[UI_MENU_COOP_YOU] = "você",
[UI_MENU_COOP_HOST] = "anfitrião",
[UI_MENU_COOP_PLAYER_DESC] = "Um jogador da sala e a área em que o Link dele está.",
[UI_MENU_COOP_PLAYER_REMOVE_DESC] = "Um jogador da sala. Como anfitrião, você pode pressionar para removê-lo da sala.",
[UI_MENU_COOP_PLAYER_AWAY] = "fora do mundo",
[UI_MENU_COOP_REMOVE] = "Remover",
[UI_MENU_COOP_REMOVE_CONFIRM] = "Remover %s da sala? Essa pessoa não poderá voltar a esta sala.",
[UI_MENU_COOP_LEAVE] = "Sair da sala",
[UI_MENU_COOP_LEAVE_DESC] = "Sai da sala. Seu jogo e seu save continuam como estão.",
[UI_MENU_COOP_LEAVE_CONFIRM] = "Sair da sala?",
[UI_MENU_COOP_LEAVE_HOST] = "Você é o anfitrião: a sala continua com outro jogador como anfitrião.",
[UI_MENU_COOP_STAY] = "Ficar",
[UI_MENU_COOP_CHAT] = "Chat",
[UI_MENU_COOP_CHAT_WRITE] = "Escrever uma mensagem",
[UI_MENU_COOP_CHAT_WRITE_DESC] = "Envia uma linha de texto a todos na sala.",
[UI_MENU_COOP_SEND] = "Enviar",
[UI_MENU_COOP_CHAT_JOINED] = "%s entrou na sala",
[UI_MENU_COOP_CHAT_LEFT] = "%s saiu da sala",
[UI_MENU_COOP_SETTINGS] = "Configurações do co-op",
[UI_MENU_COOP_SHARE] = "Compartilhar progresso",
[UI_MENU_COOP_SHARE_DESC] = "Em uma sala, o que qualquer um conquista vale para todos: história, baús, portas, itens e "
"canções. Antes de algo da sala chegar ao seu save, ele é copiado para coop-backup na pasta do "
"perfil. Chaves pequenas, rupias, munição e corações continuam seus. Desligado: só nomes e chat "
"são compartilhados.",
[UI_MENU_COOP_NAMES] = "Mostrar nomes dos jogadores",
[UI_MENU_COOP_NAMES_DESC] = "Mostra o nome de cada outro jogador onde o Link dele está no seu mundo, com a distância. Precisa "
"de DLSS, FSR ou TAA ligado (só assim o menu sabe para onde a câmera olha).",
[UI_MENU_COOP_CHAT_SHOW] = "Mostrar o chat sobre o jogo",
[UI_MENU_COOP_CHAT_SHOW_DESC] = "Novas linhas do chat e quem entrou ou saiu aparecem por alguns segundos com o menu fechado.",
[UI_MENU_COOP_N_CREATE_FAILED] = "A Steam não conseguiu criar a sala. Tente de novo em instantes.",
[UI_MENU_COOP_N_NO_ROOM] = "Nenhuma sala tem esse ID: confira, ou pergunte ao seu amigo se a sala ainda está aberta.",
[UI_MENU_COOP_N_FULL] = "A sala está cheia.",
[UI_MENU_COOP_N_REFUSED] = "A sala não deixou você entrar.",
[UI_MENU_COOP_N_NOT_OURS] = "Essa não é uma sala do NX2navi.",
[UI_MENU_COOP_N_OTHER_VERSION] = "O anfitrião da sala usa outra versão do NX2navi ou do jogo: usem as mesmas versões.",
[UI_MENU_COOP_N_REMOVED] = "O anfitrião removeu você da sala.",
[UI_MENU_COOP_N_HOST_SILENT] = "O anfitrião da sala não respondeu.",
[UI_MENU_COOP_N_LOST] = "A Steam perdeu a conexão; a sala acabou.",
[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_BOOT_COMPUTE] = "Pipelines de computação: %lld de %lld", [UI_BOOT_DRIVER_CACHE] = "Cache do driver: %lld de %lld",
@@ -2792,85 +2530,9 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
[UI_MENU_SAVE_E_NEWER] = "%s 由更新版本的 NX2navi 制作:请先更新 NX2navi。",
[UI_MENU_SAVE_E_DAMAGED] = "%s 已损坏:请重新下载。",
[UI_MENU_SAVE_E_UNSAFE] = "%s 被拒绝:其中含有存档以外的文件、链接或过多的数据。",
[UI_MENU_TAB_COOP] = "合作",
[UI_MENU_COOP_ON] = "合作(实验性)",
[UI_MENU_COOP_ON_DESC] = "通过 Steam 与朋友一起玩,各自运行自己的游戏和存档。无需设置路由器:房间和邀请都经由 Steam,Steam 会显示你正在玩它的测试应用 Spacewar。需要 Steam "
"正在运行;启动器会从你已安装的 Steam 游戏里取得 Steam 的库文件。关闭:游戏不使用网络。",
[UI_MENU_COOP_NO_LIBRARY] = "游戏旁边没有 Steam 的库文件 steam_api64.dll。启动器在启动游戏时会从你已安装的 Steam 游戏里把它放到那里:请在安装了 Steam 和至少一款 2021 "
"年或更新的游戏的情况下,从启动器启动游戏。你也可以自己从某个 Steam 游戏的文件夹里把这个文件复制到 ocarina.exe 所在的文件夹。",
[UI_MENU_COOP_OLD_LIBRARY] = "游戏旁边的 steam_api64.dll 对合作模式来说太旧。请换成较新的 Steam 游戏里的那个文件。",
[UI_MENU_COOP_NO_CLIENT] = "Steam 没有响应。请启动 Steam 并登录,然后选择“重新查找 Steam”。",
[UI_MENU_COOP_RETRY] = "重新查找 Steam",
[UI_MENU_COOP_RETRY_DESC] = "立即尝试连接 Steam;游戏每隔几秒也会自动尝试。",
[UI_MENU_COOP_CREATE] = "创建房间",
[UI_MENU_COOP_CREATE_DESC] = "创建一个最多四人的房间。你会得到一个可以告诉别人的房间 ID,也可以邀请 Steam 好友。",
[UI_MENU_COOP_JOIN] = "加入房间",
[UI_MENU_COOP_JOIN_DESC] = "加入朋友给你的房间 ID 对应的房间。",
[UI_MENU_COOP_ROOM_ID] = "房间 ID",
[UI_MENU_COOP_ROOM_ID_DESC] = "朋友在“加入房间”里输入它。按下即可复制。拿到它的人都能加入,所以只告诉你想一起玩的人。",
[UI_MENU_COOP_ROOM_ID_HINT] = "8 位字母和数字,形如 XXXX-XXXX:不分大小写,带不带连字符都可以。",
[UI_MENU_COOP_ROOM_ID_BAD] = "这不是房间 ID:请检查是否输错了字符。",
[UI_MENU_COOP_PASTE] = "粘贴",
[UI_MENU_COOP_PASTE_EMPTY] = "剪贴板里没有文字。",
[UI_MENU_COOP_COPIED] = "已复制",
[UI_MENU_COOP_OK] = "确定",
[UI_MENU_COOP_JOINING] = "正在进入房间…",
[UI_MENU_COOP_STOP] = "停止",
[UI_MENU_COOP_STOP_DESC] = "停止尝试进入房间。",
[UI_MENU_COOP_INVITE] = "邀请好友",
[UI_MENU_COOP_INVITE_DESC] = "向好友发送 Steam 邀请。只有正在运行 NX2navi 并开启了合作模式的好友能收到;其他人可以使用房间 ID。",
[UI_MENU_COOP_INVITE_TITLE] = "邀请 Steam 好友",
[UI_MENU_COOP_INVITE_NONE] = "Steam 没有显示任何好友。",
[UI_MENU_COOP_INVITE_SENT] = "已向 %s 发送邀请。",
[UI_MENU_COOP_INVITE_IN_GAME] = "正在合作模式中",
[UI_MENU_COOP_INVITE_ONLINE] = "在线",
[UI_MENU_COOP_INVITE_OFFLINE] = "离线",
[UI_MENU_COOP_INVITE_STEAM] = "Steam 的邀请窗口",
[UI_MENU_COOP_INVITE_CLOSE] = "关闭",
[UI_MENU_COOP_INVITED] = "%s 邀请你加入房间。",
[UI_MENU_COOP_INVITED_JOIN] = "加入对方的房间",
[UI_MENU_COOP_INVITED_JOIN_DESC] = "加入邀请你的那个房间。",
[UI_MENU_COOP_INVITED_NO] = "暂不",
[UI_MENU_COOP_INVITED_NO_DESC] = "忽略这次邀请。",
[UI_MENU_COOP_PLAYERS] = "玩家",
[UI_MENU_COOP_YOU] = "你",
[UI_MENU_COOP_HOST] = "房主",
[UI_MENU_COOP_PLAYER_DESC] = "房间里的一名玩家,以及其林克所在的区域。",
[UI_MENU_COOP_PLAYER_REMOVE_DESC] = "房间里的一名玩家。作为房主,你可以按下将其移出房间。",
[UI_MENU_COOP_PLAYER_AWAY] = "不在世界中",
[UI_MENU_COOP_REMOVE] = "移出",
[UI_MENU_COOP_REMOVE_CONFIRM] = "将 %s 移出房间?对方将无法再回到这个房间。",
[UI_MENU_COOP_LEAVE] = "离开房间",
[UI_MENU_COOP_LEAVE_DESC] = "离开房间。你的游戏和存档保持现状。",
[UI_MENU_COOP_LEAVE_CONFIRM] = "离开房间?",
[UI_MENU_COOP_LEAVE_HOST] = "你是房主:房间会继续存在,由另一名玩家担任房主。",
[UI_MENU_COOP_STAY] = "留下",
[UI_MENU_COOP_CHAT] = "聊天",
[UI_MENU_COOP_CHAT_WRITE] = "写消息",
[UI_MENU_COOP_CHAT_WRITE_DESC] = "向房间里的所有人发送一行文字。",
[UI_MENU_COOP_SEND] = "发送",
[UI_MENU_COOP_CHAT_JOINED] = "%s 加入了房间",
[UI_MENU_COOP_CHAT_LEFT] = "%s 离开了房间",
[UI_MENU_COOP_SETTINGS] = "合作设置",
[UI_MENU_COOP_SHARE] = "共享进度",
[UI_MENU_COOP_SHARE_DESC] = "在房间里,任何人取得的进展都算作所有人的:剧情、宝箱、门、道具和乐曲。在房间里的任何内容写入你的存档之前,存档会先复制到配置文件夹里的 "
"coop-backup。小钥匙、卢比、弹药和心保持各自独立。关闭:只共享名字和聊天。",
[UI_MENU_COOP_NAMES] = "显示玩家名字",
[UI_MENU_COOP_NAMES_DESC] = "在其他玩家的林克所处的位置显示其名字和距离。需要开启 DLSS、FSR 或 TAA(只有这样菜单才知道摄像机的朝向)。",
[UI_MENU_COOP_CHAT_SHOW] = "在游戏画面上显示聊天",
[UI_MENU_COOP_CHAT_SHOW_DESC] = "菜单关闭时,新的聊天内容以及玩家加入或离开的提示会显示几秒钟。",
[UI_MENU_COOP_N_CREATE_FAILED] = "Steam 无法创建房间。请稍后再试。",
[UI_MENU_COOP_N_NO_ROOM] = "没有使用这个 ID 的房间:请检查一下,或者问问朋友房间是否还开着。",
[UI_MENU_COOP_N_FULL] = "房间已满。",
[UI_MENU_COOP_N_REFUSED] = "房间没有让你进入。",
[UI_MENU_COOP_N_NOT_OURS] = "那不是 NX2navi 的房间。",
[UI_MENU_COOP_N_OTHER_VERSION] = "房主使用的 NX2navi 或游戏版本与你不同:请使用相同的版本。",
[UI_MENU_COOP_N_REMOVED] = "房主已将你移出房间。",
[UI_MENU_COOP_N_HOST_SILENT] = "房主没有响应。",
[UI_MENU_COOP_N_LOST] = "Steam 断开了连接;房间已不存在。",
[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_BOOT_COMPUTE] = "计算管线:%lld / %lld", [UI_BOOT_DRIVER_CACHE] = "驱动缓存:%lld / %lld",

View File

@@ -278,27 +278,9 @@ typedef enum {
UI_MENU_SAVE_E_STAGE,
UI_MENU_SAVE_E_NOT_SAVE, UI_MENU_SAVE_E_OTHER_GAME, UI_MENU_SAVE_E_NEWER, UI_MENU_SAVE_E_DAMAGED,
UI_MENU_SAVE_E_UNSAFE,
// the Co-op tab and what co-op draws over the game (ui/coop_page.cpp, docs/coop.md)
UI_MENU_TAB_COOP, UI_MENU_COOP_ON, UI_MENU_COOP_ON_DESC, UI_MENU_COOP_NO_LIBRARY, UI_MENU_COOP_OLD_LIBRARY,
UI_MENU_COOP_NO_CLIENT, UI_MENU_COOP_RETRY, UI_MENU_COOP_RETRY_DESC, UI_MENU_COOP_CREATE,
UI_MENU_COOP_CREATE_DESC, UI_MENU_COOP_JOIN, UI_MENU_COOP_JOIN_DESC, UI_MENU_COOP_ROOM_ID,
UI_MENU_COOP_ROOM_ID_DESC, UI_MENU_COOP_ROOM_ID_HINT, UI_MENU_COOP_ROOM_ID_BAD, UI_MENU_COOP_PASTE,
UI_MENU_COOP_PASTE_EMPTY, UI_MENU_COOP_COPIED, UI_MENU_COOP_OK, UI_MENU_COOP_JOINING, UI_MENU_COOP_STOP,
UI_MENU_COOP_STOP_DESC, UI_MENU_COOP_INVITE, UI_MENU_COOP_INVITE_DESC, UI_MENU_COOP_INVITE_TITLE,
UI_MENU_COOP_INVITE_NONE, UI_MENU_COOP_INVITE_SENT, UI_MENU_COOP_INVITE_IN_GAME, UI_MENU_COOP_INVITE_ONLINE,
UI_MENU_COOP_INVITE_OFFLINE, UI_MENU_COOP_INVITE_STEAM, UI_MENU_COOP_INVITE_CLOSE, UI_MENU_COOP_INVITED,
UI_MENU_COOP_INVITED_JOIN, UI_MENU_COOP_INVITED_JOIN_DESC, UI_MENU_COOP_INVITED_NO,
UI_MENU_COOP_INVITED_NO_DESC, UI_MENU_COOP_PLAYERS, UI_MENU_COOP_YOU, UI_MENU_COOP_HOST,
UI_MENU_COOP_PLAYER_DESC, UI_MENU_COOP_PLAYER_REMOVE_DESC, UI_MENU_COOP_PLAYER_AWAY, UI_MENU_COOP_REMOVE,
UI_MENU_COOP_REMOVE_CONFIRM, UI_MENU_COOP_LEAVE, UI_MENU_COOP_LEAVE_DESC, UI_MENU_COOP_LEAVE_CONFIRM,
UI_MENU_COOP_LEAVE_HOST, UI_MENU_COOP_STAY, UI_MENU_COOP_CHAT, UI_MENU_COOP_CHAT_WRITE,
UI_MENU_COOP_CHAT_WRITE_DESC, UI_MENU_COOP_SEND, UI_MENU_COOP_CHAT_JOINED, UI_MENU_COOP_CHAT_LEFT,
UI_MENU_COOP_SETTINGS, UI_MENU_COOP_SHARE, UI_MENU_COOP_SHARE_DESC, UI_MENU_COOP_NAMES, UI_MENU_COOP_NAMES_DESC,
UI_MENU_COOP_CHAT_SHOW, UI_MENU_COOP_CHAT_SHOW_DESC, UI_MENU_COOP_N_CREATE_FAILED, UI_MENU_COOP_N_NO_ROOM,
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

@@ -284,6 +284,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>