mirror of
https://github.com/tangerineturtle1/NX2navi.git
synced 2026-11-19 08:39:57 -04:00
Merge co-op, off by default: rooms through a relay, progress sync between the players' own saves, and a Co-op tab.
Without the other players drawn in the world, which are unfinished. No relay address is built in, and with co-op off nothing opens a socket. Built on Windows and tested against a relay on this PC only; two games in one room and any real network have not been tried. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -16,6 +16,7 @@
|
||||
|
||||
#include "cfg.h"
|
||||
#include "cheats.h"
|
||||
#include "coop.h"
|
||||
#include "fs.h"
|
||||
#include "kernel.h"
|
||||
#include "ipc.h"
|
||||
@@ -323,6 +324,7 @@ void rt_frame_presented(const tex_t *t, uint64_t n) {
|
||||
stats_line();
|
||||
fflush(stdout);
|
||||
fflush(stderr);
|
||||
coop_shutdown(); // LEAVE and BYE to the room, before the process ends
|
||||
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)
|
||||
vk_pipeline_save(); // no-op without the Vulkan back end
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
#include <string.h>
|
||||
|
||||
#include "cfg.h"
|
||||
#include "cfg_private.h"
|
||||
#include "coop_app.h"
|
||||
#include "discord_app.h"
|
||||
#include "host.h"
|
||||
#include "platform/platform.h"
|
||||
@@ -73,6 +75,12 @@ static const char *const known[] = {
|
||||
"TEXUP_LOG_MS", "DYN_RES", "DYN_RES_TARGET", "DYN_RES_STEP", "TEXTURE_DETAIL",
|
||||
"RECORDER_CORE", "RECORDER_PRIO", "REPLAY_TIME", "LOCK_TIME", "POOL_CREATE_BUDGET", "POOL_CREATE_MS", "POOL_LOAD_BACKLOG", "POOL_LOAD_MS", "VA_REPORT",
|
||||
"VMA_BLOCK_MB", "ASTC_BC_PROBE", "SYNC_WAKE_ALL", "LOG_ASYNC",
|
||||
"COOP", "COOP_NAME", "COOP_SERVER", "COOP_PORT", "COOP_ROOM", "COOP_AUTO", "COOP_DROP", // co-op (coop.c); the last three have no menu row
|
||||
"COOP_PROGRESS", "COOP_ITEMS", "COOP_SONGS", "COOP_QUEST", "COOP_KEYS", "COOP_RUPEES", "COOP_AMMO", // the room's rules (coop_game.c)
|
||||
"COOP_TEST_SET", // test: sets flags by hash at given frames (coop_game.c); no menu row
|
||||
"COOP_ACCEPT", // accepts a co-op room's members and rules before anything of it is applied (coop_game.c)
|
||||
"COOP_REMOVE", // the room's maker removes a member: its id (coop.c), or a key's fingerprint (coop_game.c); no row (the Co-op tab's Remove)
|
||||
"COOP_RESET_POOLS", // the room's maker resets the pools when it changes to a value other than 0 (coop_game.c); no row (the tab's Reset the pools)
|
||||
};
|
||||
|
||||
// The nx2navi.ini section a key cfg_set may write goes to when the file lacks it (nx2navi.ini.example's sections).
|
||||
@@ -96,6 +104,9 @@ static const struct { const char *key, *section; } sections[] = {
|
||||
{"FRAMEGEN", "display"}, {"FRAMEGEN_MULTIPLIER", "display"}, {"FG_MULT", "display"},
|
||||
{"DEVICE_PROFILE", "display"}, {"ASSUME_FOCUS", "display"},
|
||||
{"DISCORD_RPC", "discord"}, {"DISCORD_APP_ID", "discord"}, {"DISCORD_IMAGE", "discord"},
|
||||
{"COOP", "coop"}, {"COOP_NAME", "coop"}, {"COOP_SERVER", "coop"}, {"COOP_PORT", "coop"},
|
||||
{"COOP_PROGRESS", "coop"}, {"COOP_ITEMS", "coop"}, {"COOP_SONGS", "coop"}, {"COOP_QUEST", "coop"}, {"COOP_KEYS", "coop"},
|
||||
{"COOP_RUPEES", "coop"}, {"COOP_AMMO", "coop"}, {"COOP_ACCEPT", "coop"},
|
||||
{"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"CONTACT_SHADOWS", "display"},
|
||||
{"PCSS", "display"},
|
||||
{"MODS_DIR", "mods"}, {"MODS_ORDER", "mods"}, {"MODS_DISABLED", "mods"}, {"MODS_REBUILD", "mods"},
|
||||
@@ -227,6 +238,18 @@ 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): off until the player turns it on. The server is host[:port] of a relay (tools/coop_relay.py), and has no
|
||||
// default until coop_app.h names one; the name is at most 24 bytes, empty for Player-xxxx; the port is the local UDP port
|
||||
// (0: any). COOP_ROOM, COOP_AUTO, COOP_DROP and COOP_TEST_SET are read with cfg_get, no row.
|
||||
{"COOP", "0", "0|1", LIVE}, {"COOP_NAME", "", NULL, LIVE},
|
||||
{"COOP_SERVER", NX2NAVI_COOP_SERVER_DEFAULT, NULL, LIVE}, {"COOP_PORT", "0", "0..65535", RESTART},
|
||||
// The rules a room made by this player syncs by (coop_state.h, docs/coop.md); a joiner's own are not used in the room.
|
||||
{"COOP_PROGRESS", "shared", "shared|own", LIVE}, {"COOP_ITEMS", "shared", "shared|own", LIVE},
|
||||
{"COOP_SONGS", "shared", "shared|own", LIVE}, {"COOP_QUEST", "shared", "shared|own", LIVE},
|
||||
{"COOP_KEYS", "pool", "pool|own", LIVE}, {"COOP_RUPEES", "own", "own|pool", LIVE}, {"COOP_AMMO", "own", "own|pool", LIVE},
|
||||
// Nothing from a room is applied before its members and rules are accepted (coop_game.c): ask (the log names the
|
||||
// offer's number, which this setting or the menu accepts), always (every room, the save still copied first), or a number.
|
||||
{"COOP_ACCEPT", "ask", NULL, LIVE},
|
||||
// Advanced: scheduling
|
||||
{"ASYNC_PREEMPT", "1", "0|1|2", RESTART}, {"REPLAY_ASYNC", "0", "0|1", RESTART},
|
||||
{"FREE_CORES", "0", "0|1", RESTART}, {"TIMER_1MS", "1", "0|1", RESTART},
|
||||
@@ -982,13 +1005,15 @@ static void log_file_settings(void) {
|
||||
char key[64];
|
||||
snprintf(key, sizeof key, "%s", entries[i].key);
|
||||
for (char *p = key; *p; p++) *p = (char)tolower((unsigned char)*p);
|
||||
size_t vl = strlen(entries[i].value);
|
||||
// a co-op room's secret, the relay, the player's name: only that they are set (cfg_private.h)
|
||||
const char *value = cfg_private_key(entries[i].key) && entries[i].value[0] ? CFG_PRIVATE_SHOWN : entries[i].value;
|
||||
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);
|
||||
k = 0;
|
||||
}
|
||||
k += (size_t)snprintf(line + k, sizeof line - k, "%s%s = %.*s", k ? ", " : "", key, (int)vl, entries[i].value);
|
||||
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 (n_unknown)
|
||||
@@ -1012,6 +1037,43 @@ static void load_ini(void) {
|
||||
}
|
||||
}
|
||||
|
||||
int cfg_ini_read(const char *path, const char *key, char *out, size_t cap) {
|
||||
if (cap) out[0] = 0;
|
||||
uint64_t size = 0;
|
||||
uint8_t *data = plat_file_read(path, &size);
|
||||
if (!data || !size) { // gone or empty for a moment (an editor saving it), or locked: no reading, not "no value"
|
||||
free(data);
|
||||
return -1;
|
||||
}
|
||||
int found = 0;
|
||||
char *p = (char *)data;
|
||||
if (size >= 3 && !memcmp(p, "\xEF\xBB\xBF", 3)) p += 3; // as cfg_load: editors add a BOM
|
||||
for (;;) {
|
||||
char *eol = strchr(p, '\n');
|
||||
if (eol) *eol = 0;
|
||||
char *s = trim(p), *eq = strchr(s, '=');
|
||||
if (*s && *s != '#' && *s != ';' && *s != '[' && eq) {
|
||||
*eq = 0;
|
||||
const char *k = trim(s);
|
||||
size_t i = 0;
|
||||
while (k[i] && key[i] && tolower((unsigned char)k[i]) == tolower((unsigned char)key[i])) i++;
|
||||
if (!k[i] && !key[i]) { // as cfg_load: a repeated key's later line wins, quotes go, "key =" sets nothing
|
||||
char *v = trim(eq + 1);
|
||||
size_t vl = strlen(v);
|
||||
if (vl >= 2 && v[0] == '"' && v[vl - 1] == '"') v[vl - 1] = 0, v++;
|
||||
snprintf(out, cap, "%s", v);
|
||||
found = *v != 0;
|
||||
}
|
||||
}
|
||||
if (!eol) break;
|
||||
p = eol + 1;
|
||||
}
|
||||
free(data);
|
||||
return found;
|
||||
}
|
||||
|
||||
int cfg_ini_now(const char *key, char *out, size_t cap) { return find_ini() ? cfg_ini_read(ini_path, key, out, cap) : 0; }
|
||||
|
||||
void cfg_init(void) {
|
||||
load_ini();
|
||||
if (profile_of())
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// Settings: the NX2NAVI_* environment variables, with nx2navi.ini next to nx2navi.exe behind them.
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
|
||||
// getenv for a setting: the environment variable when set, else the nx2navi.ini key (the name without "NX2NAVI_", any
|
||||
// case), else the device profile's default (cfg.c: the Steam Deck), else NULL. Same string semantics as getenv; the pointer stays valid for the process (a value cfg_set replaces
|
||||
@@ -23,6 +24,13 @@ unsigned cfg_version(void);
|
||||
int cfg_setenv(const char *name, const char *value);
|
||||
// 1 when the environment sets name: cfg_set cannot change what cfg_get returns (the menu greys the setting out).
|
||||
int cfg_from_env(const char *name);
|
||||
// The value of key, as nx2navi.ini spells it ("coop_accept"), in nx2navi.ini as the file is now: the file is read again,
|
||||
// for the few settings that act while the game runs without the menu (co-op's acceptance and the room maker's
|
||||
// remedies; everything else is read at start). Read as at start: a BOM is skipped, a repeated key's later line wins,
|
||||
// quotes go and "key =" sets nothing. 1 and the value in out when the file sets it, 0 when it does not, -1 when the
|
||||
// file cannot be read now or is empty (an editor saving it, a lock): the caller skips that reading.
|
||||
int cfg_ini_now(const char *key, char *out, size_t cap);
|
||||
int cfg_ini_read(const char *path, const char *key, char *out, size_t cap); // the same, of the file at path
|
||||
// 1 when the player set name (the environment or nx2navi.ini), 0 when cfg_get gives a device profile's default or NULL.
|
||||
int cfg_is_set(const char *name);
|
||||
// The keys of the file's lines that are no settings of this version, lower-case with ", " between them ("" when there
|
||||
|
||||
71
runtime/cfg_private.h
Normal file
71
runtime/cfg_private.h
Normal file
@@ -0,0 +1,71 @@
|
||||
// Settings whose values stay on the player's PC: a co-op room's secret and the offer number made for it, the relay's
|
||||
// address, the player's name, the key a maker removes, and the menu's test hook (which can carry a secret). The log's
|
||||
// line of what nx2navi.ini sets (cfg.c log_file_settings), "Copy system info" (sysinfo.c) and the copy of nx2navi.ini a
|
||||
// bug report takes along (save_share.c; launcher/saves.py has the same list) show only that such a key is set.
|
||||
// Header only, so that the tests that build one of those files alone need nothing else.
|
||||
#ifndef NX2NAVI_CFG_PRIVATE_H
|
||||
#define NX2NAVI_CFG_PRIVATE_H
|
||||
|
||||
#include <ctype.h>
|
||||
#include <stddef.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define CFG_PRIVATE_SHOWN "(set, not shown)"
|
||||
|
||||
// key: a setting's name without the NX2NAVI_ prefix, in any case, n bytes of it.
|
||||
static inline int cfg_private_key_n(const char *key, size_t n) {
|
||||
static const char *const keys[] = {"COOP_ROOM", "COOP_SERVER", "COOP_NAME", "COOP_ACCEPT", "COOP_REMOVE",
|
||||
"MENU_TEST_SET"};
|
||||
for (size_t i = 0; i < sizeof keys / sizeof *keys; i++) {
|
||||
size_t k = 0;
|
||||
while (k < n && keys[i][k] && toupper((unsigned char)key[k]) == keys[i][k]) k++;
|
||||
if (k == n && !keys[i][k]) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static inline int cfg_private_key(const char *key) { return cfg_private_key_n(key, strlen(key)); }
|
||||
|
||||
// A copy of the text of an nx2navi.ini (n bytes) in which every private key that has a value reads
|
||||
// "key = (set, not shown)"; everything else, comments and line ends included, byte for byte. malloc'd, *out_n its
|
||||
// length; NULL when memory runs out.
|
||||
static inline char *cfg_ini_scrub(const char *text, size_t n, size_t *out_n) {
|
||||
size_t lines = 1;
|
||||
for (size_t i = 0; i < n; i++) lines += text[i] == '\n';
|
||||
char *out = malloc(n + lines * sizeof CFG_PRIVATE_SHOWN + 1);
|
||||
if (!out) return NULL;
|
||||
size_t o = 0;
|
||||
for (size_t at = 0; at < n;) {
|
||||
size_t end = at;
|
||||
while (end < n && text[end] != '\n') end++;
|
||||
size_t stop = end; // the line's text without its line end
|
||||
if (stop > at && text[stop - 1] == '\r') stop--;
|
||||
size_t k0 = at;
|
||||
if (at == 0 && n >= 3 && !memcmp(text, "\xEF\xBB\xBF", 3)) k0 = 3; // a byte order mark before the first key
|
||||
while (k0 < stop && (text[k0] == ' ' || text[k0] == '\t')) k0++;
|
||||
size_t eq = k0;
|
||||
while (eq < stop && text[eq] != '=') eq++;
|
||||
size_t k1 = eq;
|
||||
while (k1 > k0 && (text[k1 - 1] == ' ' || text[k1 - 1] == '\t')) k1--;
|
||||
size_t v0 = eq < stop ? eq + 1 : stop;
|
||||
while (v0 < stop && (text[v0] == ' ' || text[v0] == '\t')) v0++;
|
||||
int hide = eq < stop && v0 < stop && text[k0] != '#' && text[k0] != ';' && text[k0] != '[' &&
|
||||
cfg_private_key_n(text + k0, k1 - k0);
|
||||
if (hide) {
|
||||
memcpy(out + o, text + at, eq + 1 - at), o += eq + 1 - at;
|
||||
out[o++] = ' ';
|
||||
memcpy(out + o, CFG_PRIVATE_SHOWN, sizeof CFG_PRIVATE_SHOWN - 1), o += sizeof CFG_PRIVATE_SHOWN - 1;
|
||||
memcpy(out + o, text + stop, end - stop), o += end - stop; // a carriage return, if the line had one
|
||||
} else {
|
||||
memcpy(out + o, text + at, end - at), o += end - at;
|
||||
}
|
||||
if (end < n) out[o++] = '\n';
|
||||
at = end + 1;
|
||||
}
|
||||
out[o] = 0;
|
||||
*out_n = o;
|
||||
return out;
|
||||
}
|
||||
|
||||
#endif
|
||||
1354
runtime/coop.c
Normal file
1354
runtime/coop.c
Normal file
File diff suppressed because it is too large
Load Diff
143
runtime/coop.h
Normal file
143
runtime/coop.h
Normal file
@@ -0,0 +1,143 @@
|
||||
// Co-op session layer: one host thread, "coop", owns a UDP socket to a relay (tools/coop_relay.py), keeps the player in a
|
||||
// room of up to 8 and carries the messages the players send each other (coop_proto.h: the wire format). It never holds a
|
||||
// virtual core and never touches game state: progress sync is a layer above this one, which send
|
||||
// with coop_send and receive with coop_on_message. The game's own nn::socket stays offline.
|
||||
//
|
||||
// Threads. Everything below the "process" heading may be called from any thread; the callbacks run on the coop thread
|
||||
// (keep them short, they hold up the socket) and must not call coop_command. coop_send copies the message into an outbox the
|
||||
// coop thread flushes within about 8 ms; coop_view_get and coop_command take a lock the coop thread holds only to copy.
|
||||
//
|
||||
// The session is off until the COOP setting (nx2navi.ini [coop], the menu) is on; docs/coop.md has the settings.
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "coop_proto.h"
|
||||
|
||||
typedef enum {
|
||||
COOP_OFF, // the COOP setting is off: no socket, no thread work
|
||||
COOP_LEFT, // on, in no room (the status says why after a failure)
|
||||
COOP_CONNECTING, // reaching the relay to create or join a room
|
||||
COOP_JOINED, // in a room
|
||||
COOP_RECONNECTING, // the relay went silent; joining the same room again as the same member
|
||||
} CoopState;
|
||||
|
||||
typedef enum { COOP_CMD_CREATE = 1, COOP_CMD_JOIN, COOP_CMD_LEAVE } CoopCmd;
|
||||
|
||||
typedef struct {
|
||||
uint8_t id; // member id 1..8
|
||||
uint8_t away; // the relay has not heard from the member for a while
|
||||
uint8_t maker; // made the room (the relay says so); the rules are the ones its key signs (coop_state.h)
|
||||
char name[COOP_NAME_MAX + 1];
|
||||
uint64_t session; // its session in the room, as the relay lists it (progress sync binds its identity to it)
|
||||
uint32_t heard_ms; // milliseconds since the last message of this member that opened with the room's key;
|
||||
// UINT32_MAX never (a member the relay lists but that has not shown it knows the secret)
|
||||
} CoopPeer;
|
||||
|
||||
typedef struct {
|
||||
CoopState state;
|
||||
unsigned version; // changes with the state, the room, the roster and the status text
|
||||
char code[COOP_SECRET_TEXT + 1]; // the room's secret, XXXXXX-XXXXXX-XXXXXX, in a room or while joining one; else ""
|
||||
char label[8]; // its first characters, for logs ("XXX…")
|
||||
int self; // this player's member id; 0 outside a room
|
||||
int maker; // the member id of the room's maker, 0 when the maker is not in the room
|
||||
int made; // this player's session made the room (its own CREATE, not the relay's mark: its
|
||||
// settings are the room's rules, coop_state.h)
|
||||
uint64_t session; // this player's session in the room, the one it joined with (0 outside a room); a roster
|
||||
// may list another for it, which progress sync does not sign for
|
||||
char name[COOP_NAME_MAX + 1]; // this player's own name (COOP_NAME, cleaned), whatever the relay's roster says
|
||||
int n; // members of the room, this player included, by id
|
||||
CoopPeer member[COOP_MAX_MEMBERS];
|
||||
uint32_t ping_ms; // round trip to the relay; 0 until measured
|
||||
char status[96]; // what is going on or what went wrong, in words
|
||||
uint32_t tx, rx, lost; // datagrams sent, accepted, and received but not accepted (bad tag, wrong sender, replay)
|
||||
} CoopView;
|
||||
|
||||
// ---- the process's session (the one the settings drive)
|
||||
|
||||
// Starts the coop thread. It re-reads the settings when cfg_version changes and does nothing while COOP is off.
|
||||
void coop_init(void);
|
||||
// Leaves the room and says BYE to the others, best effort, for the three ways the process ends (boot.c, svc.c,
|
||||
// gfx_present.c, before fs_save_flush): waits at most about 0.4 s for the coop thread, then returns whatever happened.
|
||||
// A session still connecting is left running (the process ends next; the relay drops a member it never hears from).
|
||||
void coop_shutdown(void);
|
||||
// Create, join or leave a room. secret (as typed: any case, '-' and spaces allowed) is required by JOIN; CREATE makes a
|
||||
// room of that secret, or of a new random one when it is NULL or empty (the view shows it: the player passes it on to
|
||||
// the others out of band). 1 when queued, 0 when the secret is not one or co-op is off. The outcome shows in coop_view_get.
|
||||
int coop_command(CoopCmd cmd, const char *secret);
|
||||
// The room's maker removes a member (its id): every game drops its identity (progress sync signs the removal with the
|
||||
// maker's key, coop_state.h), and when the relay names this player the maker, the relay drops the member and refuses
|
||||
// it again under that identity. 1 when either was done.
|
||||
int coop_remove_member(int member);
|
||||
// fn(member, user) when coop_remove_member is called, on the caller's thread, before the relay is asked: the layer that
|
||||
// signs removals (progress sync) registers here; 1 when it removed the member. One hook.
|
||||
typedef int (*CoopRemoveFn)(int member, void *user);
|
||||
int coop_on_remove(CoopRemoveFn fn, void *user);
|
||||
void coop_view_get(CoopView *out);
|
||||
// This player's id towards the relay: random for each start of the game, never sent to the other players.
|
||||
uint64_t coop_client_id(void);
|
||||
|
||||
// Peer messages. kind is COOP_K_*; bytes follow it in the datagram. coop_send goes to every other member, coop_send_to to
|
||||
// one (a member id). 1 when queued, 0 when not in a room, the message is too long (COOP_MAX_MESSAGE bytes) or the
|
||||
// outbox is full: a message is a datagram and may be lost anyway. Every message is sealed with the room's message key.
|
||||
int coop_send(uint8_t kind, const void *bytes, size_t n);
|
||||
int coop_send_to(int member, uint8_t kind, const void *bytes, size_t n);
|
||||
// fn(from member id, the message bytes after the kind, their count, user) for every message of that kind that opened
|
||||
// with the room's key and came from the session the roster names for its sender. One handler per kind; register before
|
||||
// the message can arrive (at start-up). Not once only: the window refuses a repeat within the last 64 it took, but
|
||||
// four older messages in a row start it again, after which a recorded message of that session can arrive again (a
|
||||
// relay without the secret can do that), and anyone with the secret can seal one again under a new counter. A handler
|
||||
// for which a repeat or an old message matters keeps a counter of its own per sender and session inside its messages
|
||||
// and takes only one above the last it took (a position message, say, so that an old pose does not move a player
|
||||
// back); progress sync signs its counter, which only the sender can then move.
|
||||
typedef void (*CoopMsgFn)(int from, const uint8_t *bytes, size_t n, void *user);
|
||||
int coop_on_message(uint8_t kind, CoopMsgFn fn, void *user);
|
||||
// fn(view, user) after the state, the room, the roster or the status changed; up to 8 hooks. A layer that sends a HELLO to
|
||||
// every new member listens here.
|
||||
typedef void (*CoopViewFn)(const CoopView *view, void *user);
|
||||
int coop_on_view(CoopViewFn fn, void *user);
|
||||
// fn(now in ms, user) at every step of the coop thread (every 8 ms or less in a room, 250 ms idle); up to 4 hooks. A layer
|
||||
// with timers of its own (digests, repeated sends) runs them here.
|
||||
typedef void (*CoopTickFn)(uint64_t now_ms, void *user);
|
||||
int coop_on_tick(CoopTickFn fn, void *user);
|
||||
|
||||
// "host", "host:port", "[v6]:port" or a bare IPv6 address into host (cap bytes) and port (default 24680). 0 when text is
|
||||
// empty or does not fit.
|
||||
int coop_server_parse(const char *text, char *host, size_t cap, uint16_t *port);
|
||||
|
||||
// ---- a session of its own (--probe-coop runs two in one process; the process's session is one of these driven by the settings)
|
||||
typedef struct CoopSess CoopSess;
|
||||
typedef struct {
|
||||
const char *tag; // names the session in log lines ("coop[A]: ..."); NULL for none
|
||||
const char *server; // "host[:port]"
|
||||
const char *name; // the player's name
|
||||
uint64_t client_id; // the same one on every reconnect keeps the member id for a minute (with the rejoin token)
|
||||
int on; // 0: off (COOP_OFF), the COOP setting; 1: on, in no room until a command says
|
||||
uint16_t local_port; // 0: any
|
||||
unsigned drop_pct; // percent of received datagrams thrown away, for tests
|
||||
int retry; // a room the relay lost (a restart) is made or waited for again instead of ending the session
|
||||
// timings in ms, 0 for the defaults (2000, 8000, 250, 1000, 15000); tests shorten them
|
||||
uint32_t ping_ms, silence_ms, burst_gap_ms, backoff_first_ms, backoff_max_ms;
|
||||
} CoopParams;
|
||||
CoopSess *coop_sess_new(const CoopParams *p); // p's strings are copied
|
||||
void coop_sess_free(CoopSess *s); // the stepping thread must be gone
|
||||
// The stepping thread calls this in a loop: handles commands, the outbox, one batch of datagrams and the timers, waiting at
|
||||
// most 8 ms (in a room), 50 ms (reaching the relay) or 250 ms (idle) for the next datagram.
|
||||
void coop_sess_step(CoopSess *s);
|
||||
int coop_sess_command(CoopSess *s, CoopCmd cmd, const char *secret); // as coop_command, for this session
|
||||
int coop_sess_remove(CoopSess *s, int member); // as coop_remove_member
|
||||
int coop_sess_send(CoopSess *s, int member, uint8_t kind, const void *bytes, size_t n); // member 0 or COOP_DST_ALL: all
|
||||
int coop_sess_on_message(CoopSess *s, uint8_t kind, CoopMsgFn fn, void *user);
|
||||
int coop_sess_on_view(CoopSess *s, CoopViewFn fn, void *user);
|
||||
int coop_sess_on_tick(CoopSess *s, CoopTickFn fn, void *user);
|
||||
void coop_sess_view(CoopSess *s, CoopView *out);
|
||||
// Replaces the settings the session reads with those of p (the timings stay as they were made); the stepping thread
|
||||
// applies them, on or off included. A new server ends the room; a new name, once the room is joined, joins it again under the new name a
|
||||
// second after the last change, so typing a name does not rejoin at every letter.
|
||||
void coop_sess_configure(CoopSess *s, const CoopParams *p);
|
||||
// Ends the session as coop_sess_configure with on = 0 would: LEAVE and BYE, socket closed, state COOP_OFF.
|
||||
void coop_sess_stop(CoopSess *s);
|
||||
// Waits at most ms for the stepping thread to have carried out a stop (or a configure with on = 0); 1 when it did.
|
||||
int coop_sess_wait_off(CoopSess *s, uint32_t ms);
|
||||
|
||||
int probe_coop(void); // coop_probe.c: --probe-coop
|
||||
7
runtime/coop_app.h
Normal file
7
runtime/coop_app.h
Normal file
@@ -0,0 +1,7 @@
|
||||
// The relay NX2navi's co-op (coop.c) joins when coop_server is not set: the one place that default lives, like
|
||||
// discord_app.h for the Rich Presence. Empty until the project hosts a relay: with no server the session stays idle and
|
||||
// logs why, rather than sending a player's room code to a server nobody chose. Anyone can run tools/coop_relay.py and set
|
||||
// coop_server in nx2navi.ini (docs/coop.md).
|
||||
#pragma once
|
||||
|
||||
#define NX2NAVI_COOP_SERVER_DEFAULT "" // "host" or "host:port"; the default port is 24680
|
||||
1228
runtime/coop_game.c
Normal file
1228
runtime/coop_game.c
Normal file
File diff suppressed because it is too large
Load Diff
22
runtime/coop_game.h
Normal file
22
runtime/coop_game.h
Normal file
@@ -0,0 +1,22 @@
|
||||
// Co-op progress sync, the game side (Ocarina 1.1.1): reads the game's flag database between frames, hands what changed
|
||||
// to the merge engine (coop_state.c), and gives the game what the room has through the game's own set routines, so the
|
||||
// game takes it as if the player had done it. Nothing is read or written while the game is on its title screen, loading
|
||||
// or changing scene; what arrives meanwhile waits. docs/coop.md says what is shared.
|
||||
#pragma once
|
||||
#include "coop_offer.h"
|
||||
#include "coop_proto.h"
|
||||
#include "coop_state.h"
|
||||
#include "host.h"
|
||||
|
||||
// Registers the message handlers and the coop thread's hooks (main.c, after coop_init). Allocates nothing until the COOP
|
||||
// setting is on.
|
||||
void coop_game_init(void);
|
||||
// nvnQueuePresentTexture, between frames on the game's thread with its core held (as res_present). With COOP off it reads
|
||||
// one counter and returns.
|
||||
void coop_present(Cpu *c);
|
||||
|
||||
// The offer the player accepts before anything of a room is applied, the maker's remedies and the pools' contributors:
|
||||
// coop_offer.h (coop_game_offer, coop_game_accept, coop_game_reset_pools, coop_game_remove_key, coop_game_contributors).
|
||||
// fs_host.c, at every RomFS file open on any thread: notes the start of the title screen, after which sync waits for a
|
||||
// save to be loaded. With COOP off it reads one value and returns.
|
||||
void coop_game_rom_open(const char *path);
|
||||
45
runtime/coop_offer.h
Normal file
45
runtime/coop_offer.h
Normal file
@@ -0,0 +1,45 @@
|
||||
// What the menu's Co-op tab reads of a room and asks of it (coop_game.c), in a header of its own without host.h so that
|
||||
// the menu's C++ can include it. Every call may be made from any thread and never waits for the sync engine: what is
|
||||
// read is a copy the coop thread publishes at each of its steps, and what is asked is carried out by the coop thread at
|
||||
// its next step (a few ms in a room), which logs the outcome.
|
||||
#pragma once
|
||||
#include "coop_proto.h"
|
||||
#include "coop_state.h"
|
||||
|
||||
// What joining the room means, for the player to accept: the engine's offer (coop_state.h: CoopOffer), with the
|
||||
// relay's names for members not identified yet. Nothing from a room is applied to the game before the player accepted
|
||||
// its offer and a copy of the save was made (<profile>/coop-backup/<time>/, docs/coop.md; the first copy for a room is
|
||||
// "first-<time>" and is never pruned). An accepted offer stays accepted while every member is an identity accepted,
|
||||
// the rules and the key that signs them stay the same and the same save is played; anything else is a new offer, and
|
||||
// nothing more is applied until that one is accepted. A member in the room that never identified itself keeps the room
|
||||
// unaccepted. The offer's number is random for each start of the game. The COOP_ACCEPT setting accepts one offer by its
|
||||
// number (the log shows it) or, from the environment only, every offer with "always"; the menu calls coop_game_accept.
|
||||
// 1 when there is an offer; without one (token 0) the members and disagree are still filled in while in a room.
|
||||
int coop_game_offer(CoopOffer *out);
|
||||
// Accepts the offer of that number, the one the player was shown: 1 when it is the offer published last (or that offer
|
||||
// is accepted already) and no member in the room is unidentified; 0 otherwise, and nothing changes (ask again once
|
||||
// unidentified is 0). The coop thread accepts it at its next step only while it is still the room's offer.
|
||||
int coop_game_accept(uint32_t token);
|
||||
// The room's maker (its game holds the key that signs the rules, kept in the profile across restarts) resets the pools:
|
||||
// every game joins them again with what they held for the players in the room. 1 when asked (this game is the maker).
|
||||
// The setting COOP_RESET_POOLS does it too (when it changes to a value other than 0).
|
||||
int coop_game_reset_pools(void);
|
||||
// The room's maker removes a key by its fingerprint (xxxx-xxxx-xxxx-xxxx, as the offer, the contributors and the log
|
||||
// show it), also of a member that left: every game drops it and its pool records, and a member in the room that holds
|
||||
// it is removed at the relay too. 1 when asked (a fingerprint, and this game is the maker). The setting COOP_REMOVE
|
||||
// takes a fingerprint too. A member is never removed by its id from here: ids pass to other players as members come
|
||||
// and go.
|
||||
int coop_game_remove_key(const char *fingerprint);
|
||||
// The identities the pools admit and what each took beyond what it brought, per pool (coop_state.h: CoopContributor):
|
||||
// whom the maker would remove after a drain. Their count (at most max), as published at most half a second ago.
|
||||
int coop_game_contributors(CoopContributor *out, int max);
|
||||
// This game holds the key that signs the room's rules (it made the room, in this start of the game or an earlier one):
|
||||
// its removals and pool resets act.
|
||||
int coop_game_is_maker(void);
|
||||
// The members this game would show in its world (nothing draws them in this build), one bit per member id: identified (heard, so not disputed
|
||||
// between two keys), not removed, and with a key this player accepted under the name it signs now (no accepted_as).
|
||||
// A member the player has not accepted, or who is not identified, shows no puppet. accepted(key fingerprint, user): 1
|
||||
// when this player accepted that key. Kept apart from the game so that --probe-coop checks it (coop_proto.c).
|
||||
uint32_t coop_offer_shown(const CoopOffer *o, int (*accepted)(const char *key, void *user), void *user);
|
||||
// The same, as the coop thread last published it (0 outside a room).
|
||||
uint32_t coop_game_shown(void);
|
||||
1592
runtime/coop_probe.c
Normal file
1592
runtime/coop_probe.c
Normal file
File diff suppressed because it is too large
Load Diff
513
runtime/coop_proto.c
Normal file
513
runtime/coop_proto.c
Normal file
@@ -0,0 +1,513 @@
|
||||
// The co-op wire format (coop_proto.h): room secrets and their keys, HMAC tags, the datagram header, the client and
|
||||
// relay messages and the sealed player messages. Pure functions on bytes.
|
||||
#include "coop_proto.h"
|
||||
#include "coop_offer.h" // coop_offer_shown: who the puppets show
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#include "sha256.h"
|
||||
#include "third_party/monocypher/monocypher.h"
|
||||
|
||||
static const char secret_alphabet[] = "23456789BCDFGHJKMNPRSTVWXYZ";
|
||||
|
||||
static int secret_char(char c) { return c && strchr(secret_alphabet, c) != NULL; }
|
||||
|
||||
// The length of the string at s, at most max.
|
||||
static size_t bounded_len(const char *s, size_t max) {
|
||||
size_t n = 0;
|
||||
while (n < max && s[n]) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
int coop_secret_normalize(const char *text, char out[COOP_SECRET_LEN + 1]) {
|
||||
size_t n = 0;
|
||||
for (const char *p = text; *p; p++) {
|
||||
char c = *p;
|
||||
if (c == '-' || c == ' ') continue;
|
||||
if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A');
|
||||
if (n == COOP_SECRET_LEN || !secret_char(c)) return 0;
|
||||
out[n++] = c;
|
||||
}
|
||||
if (n != COOP_SECRET_LEN) return 0;
|
||||
out[n] = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
void coop_secret_format(const char secret[COOP_SECRET_LEN], char out[COOP_SECRET_TEXT + 1]) {
|
||||
for (int g = 0, at = 0; g < 3; g++) {
|
||||
if (g) out[at++] = '-';
|
||||
memcpy(out + at, secret + 6 * g, 6);
|
||||
at += 6;
|
||||
}
|
||||
out[COOP_SECRET_TEXT] = 0;
|
||||
}
|
||||
|
||||
int coop_secret_from_random(const uint8_t random[32], char out[COOP_SECRET_LEN + 1]) {
|
||||
int n = 0;
|
||||
for (int i = 0; i < 32 && n < COOP_SECRET_LEN; i++)
|
||||
if (random[i] < 243) out[n++] = secret_alphabet[random[i] % 27]; // 243 = 9 x 27: every symbol as likely
|
||||
out[n] = 0;
|
||||
return n == COOP_SECRET_LEN;
|
||||
}
|
||||
|
||||
// Three characters of the secret's alphabet taken from a hash of the secret, not from the secret itself: every game
|
||||
// in the room gets the same label, and a log that is passed on gives away none of the secret's characters.
|
||||
void coop_secret_short(const char secret[COOP_SECRET_LEN], char out[8]) {
|
||||
static const char label_key[] = "nx2navi co-op room label";
|
||||
uint8_t h[4];
|
||||
coop_blake2b(h, sizeof h, label_key, sizeof label_key - 1, secret, COOP_SECRET_LEN);
|
||||
uint32_t v = (uint32_t)h[0] | (uint32_t)h[1] << 8 | (uint32_t)h[2] << 16;
|
||||
for (int i = 0; i < 3; i++, v /= 27) out[i] = secret_alphabet[v % 27];
|
||||
memcpy(out + 3, "\xe2\x80\xa6", 4); // U+2026 and the NUL
|
||||
}
|
||||
|
||||
// ---- keys and tags
|
||||
|
||||
static void sha_two(Sha256 *s, const void *a, size_t an, const void *b, size_t bn) {
|
||||
if (an) sha256_update(s, a, an);
|
||||
if (bn) sha256_update(s, b, bn);
|
||||
}
|
||||
|
||||
void coop_hmac_sha256(const void *key, size_t klen, const void *a, size_t an, const void *b, size_t bn, uint8_t out[32]) {
|
||||
uint8_t k[64] = {0}, pad[64], inner[32];
|
||||
Sha256 s;
|
||||
if (klen > sizeof k) sha256(key, klen, k);
|
||||
else if (klen) memcpy(k, key, klen);
|
||||
for (int i = 0; i < 64; i++) pad[i] = k[i] ^ 0x36;
|
||||
sha256_init(&s);
|
||||
sha256_update(&s, pad, sizeof pad);
|
||||
sha_two(&s, a, an, b, bn);
|
||||
sha256_final(&s, inner);
|
||||
for (int i = 0; i < 64; i++) pad[i] = k[i] ^ 0x5c;
|
||||
sha256_init(&s);
|
||||
sha256_update(&s, pad, sizeof pad);
|
||||
sha256_update(&s, inner, sizeof inner);
|
||||
sha256_final(&s, out);
|
||||
}
|
||||
|
||||
void coop_room_keys(const char secret[COOP_SECRET_LEN], uint8_t locator[COOP_KEY_LEN], uint8_t msg_key[COOP_MSG_KEY_LEN]) {
|
||||
static const char room[] = "nx2navi-coop/2 room", messages[] = "nx2navi-coop/2 messages";
|
||||
if (locator) crypto_blake2b_keyed(locator, COOP_KEY_LEN, (const uint8_t *)secret, COOP_SECRET_LEN, (const uint8_t *)room, sizeof room - 1);
|
||||
if (msg_key)
|
||||
crypto_blake2b_keyed(msg_key, COOP_MSG_KEY_LEN, (const uint8_t *)secret, COOP_SECRET_LEN, (const uint8_t *)messages,
|
||||
sizeof messages - 1);
|
||||
}
|
||||
|
||||
static void make_tag(const uint8_t key[COOP_KEY_LEN], const uint8_t *hdr16, const uint8_t *payload, size_t n,
|
||||
uint8_t tag[COOP_TAG_LEN]) {
|
||||
uint8_t full[32];
|
||||
coop_hmac_sha256(key, COOP_KEY_LEN, hdr16, 16, payload, n, full);
|
||||
memcpy(tag, full, COOP_TAG_LEN);
|
||||
}
|
||||
|
||||
// ---- little-endian fields
|
||||
|
||||
static void put16(uint8_t *p, uint32_t v) { p[0] = (uint8_t)v, p[1] = (uint8_t)(v >> 8); }
|
||||
static void put32(uint8_t *p, uint32_t v) { put16(p, v), put16(p + 2, v >> 16); }
|
||||
static void put64(uint8_t *p, uint64_t v) { put32(p, (uint32_t)v), put32(p + 4, (uint32_t)(v >> 32)); }
|
||||
static uint32_t get16(const uint8_t *p) { return (uint32_t)p[0] | (uint32_t)p[1] << 8; }
|
||||
static uint32_t get32(const uint8_t *p) { return get16(p) | get16(p + 2) << 16; }
|
||||
static uint64_t get64(const uint8_t *p) { return get32(p) | (uint64_t)get32(p + 4) << 32; }
|
||||
|
||||
// ---- datagrams
|
||||
|
||||
size_t coop_dgram_pack(uint8_t *out, size_t cap, const CoopHdr *h, const void *payload, size_t n,
|
||||
const uint8_t key[COOP_KEY_LEN]) {
|
||||
if (n > COOP_MAX_PAYLOAD || cap < COOP_HDR_LEN + n) return 0;
|
||||
put16(out, COOP_MAGIC);
|
||||
out[2] = h->ver, out[3] = h->type;
|
||||
put32(out + 4, h->room);
|
||||
out[8] = h->src, out[9] = h->dst;
|
||||
put16(out + 10, (uint32_t)n);
|
||||
put32(out + 12, h->seq);
|
||||
if (n) memmove(out + COOP_HDR_LEN, payload, n); // the payload may already sit where it goes
|
||||
if (key) make_tag(key, out, out + COOP_HDR_LEN, n, out + 16);
|
||||
else memset(out + 16, 0, COOP_TAG_LEN);
|
||||
return COOP_HDR_LEN + n;
|
||||
}
|
||||
|
||||
int coop_dgram_parse(const uint8_t *d, size_t n, CoopHdr *h, const uint8_t **payload) {
|
||||
if (n < COOP_HDR_LEN || n > COOP_MAX_DGRAM || get16(d) != COOP_MAGIC) return 0;
|
||||
uint32_t len = get16(d + 10);
|
||||
if (len != n - COOP_HDR_LEN) return 0;
|
||||
h->ver = d[2], h->type = d[3];
|
||||
h->room = get32(d + 4);
|
||||
h->src = d[8], h->dst = d[9];
|
||||
h->len = (uint16_t)len;
|
||||
h->seq = get32(d + 12);
|
||||
*payload = d + COOP_HDR_LEN;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int coop_dgram_verify(const uint8_t *d, size_t n, const uint8_t key[COOP_KEY_LEN]) {
|
||||
uint8_t tag[COOP_TAG_LEN], diff = 0;
|
||||
if (n < COOP_HDR_LEN) return 0;
|
||||
make_tag(key, d, d + COOP_HDR_LEN, n - COOP_HDR_LEN, tag);
|
||||
for (int i = 0; i < COOP_TAG_LEN; i++) diff |= (uint8_t)(tag[i] ^ d[16 + i]);
|
||||
return diff == 0;
|
||||
}
|
||||
|
||||
int coop_dgram_tag_zero(const uint8_t *d) {
|
||||
uint8_t any = 0;
|
||||
for (int i = 0; i < COOP_TAG_LEN; i++) any |= d[16 + i];
|
||||
return any == 0;
|
||||
}
|
||||
|
||||
// ---- names
|
||||
|
||||
// The length of the valid UTF-8 character at p (n bytes left), 0 when the bytes there are not one: no overlong forms,
|
||||
// no surrogates, nothing above U+10FFFF.
|
||||
static size_t utf8_len(const uint8_t *p, size_t n) {
|
||||
uint8_t c = p[0];
|
||||
if (c < 0x80) return 1;
|
||||
size_t len = c >= 0xC2 && c <= 0xDF ? 2 : c >= 0xE0 && c <= 0xEF ? 3 : c >= 0xF0 && c <= 0xF4 ? 4 : 0;
|
||||
if (!len || len > n) return 0;
|
||||
for (size_t i = 1; i < len; i++)
|
||||
if ((p[i] & 0xC0) != 0x80) return 0;
|
||||
if (c == 0xE0 && p[1] < 0xA0) return 0; // overlong
|
||||
if (c == 0xED && p[1] > 0x9F) return 0; // a surrogate
|
||||
if (c == 0xF0 && p[1] < 0x90) return 0; // overlong
|
||||
if (c == 0xF4 && p[1] > 0x8F) return 0; // above U+10FFFF
|
||||
return len;
|
||||
}
|
||||
|
||||
// A character a log or a console may act on: C0, DEL, C1 (U+0080-U+009F), and the bidi controls U+061C, U+200E,
|
||||
// U+200F, U+202A-U+202E and U+2066-U+2069.
|
||||
static int control_char(const uint8_t *p, size_t len) {
|
||||
if (len == 1) return p[0] < 0x20 || p[0] == 0x7F;
|
||||
if (len == 2) return (p[0] == 0xC2 && p[1] < 0xA0) || (p[0] == 0xD8 && p[1] == 0x9C);
|
||||
if (len == 3 && p[0] == 0xE2 && p[1] == 0x80) return p[2] == 0x8E || p[2] == 0x8F || (p[2] >= 0xAA && p[2] <= 0xAE);
|
||||
if (len == 3 && p[0] == 0xE2 && p[1] == 0x81) return p[2] >= 0xA6 && p[2] <= 0xA9;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// At most max bytes of raw as valid UTF-8 into out (cap bytes, NUL-terminated): a control character and each byte that is
|
||||
// not valid UTF-8 become '?', and the text is cut before the character that would not fit.
|
||||
static size_t text_clean(char *out, size_t cap, const uint8_t *raw, size_t n, size_t max) {
|
||||
size_t at = 0, i = 0;
|
||||
if (!cap) return 0;
|
||||
while (i < n) {
|
||||
size_t len = utf8_len(raw + i, n - i), take = len ? len : 1;
|
||||
int bad = !len || control_char(raw + i, len);
|
||||
if (at + (bad ? 1 : take) > max || at + (bad ? 1 : take) + 1 > cap) break;
|
||||
if (bad) out[at++] = '?';
|
||||
else memcpy(out + at, raw + i, len), at += len;
|
||||
i += take;
|
||||
}
|
||||
out[at] = 0;
|
||||
return at;
|
||||
}
|
||||
|
||||
size_t coop_name_clean(char *out, size_t cap, const uint8_t *raw, size_t n) {
|
||||
return text_clean(out, cap, raw, n, COOP_NAME_MAX);
|
||||
}
|
||||
|
||||
// ---- client and relay messages
|
||||
|
||||
enum { CONNECT_FIXED = 43 }; // the fields before the name
|
||||
|
||||
size_t coop_connect_pack(uint8_t *out, size_t cap, const CoopConnect *c) {
|
||||
size_t nlen = bounded_len(c->name, COOP_NAME_MAX);
|
||||
size_t len = CONNECT_FIXED + nlen + 2 * COOP_COOKIE_LEN;
|
||||
size_t padded = len < COOP_CONNECT_MIN - COOP_HDR_LEN ? COOP_CONNECT_MIN - COOP_HDR_LEN : len;
|
||||
if (cap < padded) return 0;
|
||||
memset(out, 0, padded);
|
||||
out[0] = c->intent, out[1] = c->flags;
|
||||
memcpy(out + 2, c->locator, COOP_KEY_LEN);
|
||||
put64(out + 18, c->client_id);
|
||||
put64(out + 26, c->session);
|
||||
put64(out + 34, c->nonce);
|
||||
out[42] = (uint8_t)nlen;
|
||||
memcpy(out + CONNECT_FIXED, c->name, nlen);
|
||||
memcpy(out + CONNECT_FIXED + nlen, c->cookie, COOP_COOKIE_LEN);
|
||||
memcpy(out + CONNECT_FIXED + nlen + COOP_COOKIE_LEN, c->token, COOP_COOKIE_LEN);
|
||||
return padded;
|
||||
}
|
||||
|
||||
int coop_connect_parse(const uint8_t *p, size_t n, CoopConnect *c) {
|
||||
if (n < CONNECT_FIXED) return 0;
|
||||
size_t nlen = p[42];
|
||||
if (nlen > COOP_NAME_MAX || CONNECT_FIXED + nlen + 2 * COOP_COOKIE_LEN > n) return 0;
|
||||
memset(c, 0, sizeof *c);
|
||||
c->intent = p[0], c->flags = p[1];
|
||||
memcpy(c->locator, p + 2, COOP_KEY_LEN);
|
||||
c->client_id = get64(p + 18);
|
||||
c->session = get64(p + 26);
|
||||
c->nonce = get64(p + 34);
|
||||
coop_name_clean(c->name, sizeof c->name, p + CONNECT_FIXED, nlen);
|
||||
memcpy(c->cookie, p + CONNECT_FIXED + nlen, COOP_COOKIE_LEN);
|
||||
memcpy(c->token, p + CONNECT_FIXED + nlen + COOP_COOKIE_LEN, COOP_COOKIE_LEN);
|
||||
return 1;
|
||||
}
|
||||
|
||||
size_t coop_challenge_pack(uint8_t *out, size_t cap, uint64_t nonce, const uint8_t cookie[COOP_COOKIE_LEN]) {
|
||||
if (cap < 8 + COOP_COOKIE_LEN) return 0;
|
||||
put64(out, nonce);
|
||||
memcpy(out + 8, cookie, COOP_COOKIE_LEN);
|
||||
return 8 + COOP_COOKIE_LEN;
|
||||
}
|
||||
|
||||
int coop_challenge_parse(const uint8_t *p, size_t n, uint64_t *nonce, uint8_t cookie[COOP_COOKIE_LEN]) {
|
||||
if (n != 8 + COOP_COOKIE_LEN) return 0;
|
||||
*nonce = get64(p);
|
||||
memcpy(cookie, p + 8, COOP_COOKIE_LEN);
|
||||
return 1;
|
||||
}
|
||||
|
||||
size_t coop_roster_pack(uint8_t *out, size_t cap, const CoopRoster *r) {
|
||||
size_t at = 1;
|
||||
if (!cap || r->n > COOP_MAX_MEMBERS) return 0;
|
||||
out[0] = r->n;
|
||||
for (int i = 0; i < r->n; i++) {
|
||||
size_t nlen = bounded_len(r->m[i].name, COOP_NAME_MAX);
|
||||
if (at + 11 + nlen > cap) return 0;
|
||||
out[at] = r->m[i].id, out[at + 1] = r->m[i].flags;
|
||||
put64(out + at + 2, r->m[i].session);
|
||||
out[at + 10] = (uint8_t)nlen;
|
||||
memcpy(out + at + 11, r->m[i].name, nlen);
|
||||
at += 11 + nlen;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
int coop_roster_parse(const uint8_t *p, size_t n, CoopRoster *r, size_t *used) {
|
||||
if (n < 1 || p[0] > COOP_MAX_MEMBERS) return 0;
|
||||
size_t at = 1;
|
||||
memset(r, 0, sizeof *r);
|
||||
r->n = p[0];
|
||||
for (int i = 0; i < r->n; i++) {
|
||||
if (at + 11 > n) return 0;
|
||||
size_t nlen = p[at + 10];
|
||||
if (nlen > COOP_NAME_MAX || at + 11 + nlen > n) return 0;
|
||||
r->m[i].id = p[at], r->m[i].flags = p[at + 1];
|
||||
r->m[i].session = get64(p + at + 2);
|
||||
coop_name_clean(r->m[i].name, sizeof r->m[i].name, p + at + 11, nlen);
|
||||
at += 11 + nlen;
|
||||
}
|
||||
if (used) *used = at;
|
||||
return 1;
|
||||
}
|
||||
|
||||
size_t coop_joined_pack(uint8_t *out, size_t cap, const CoopJoined *j) {
|
||||
if (cap < 9 + COOP_COOKIE_LEN) return 0;
|
||||
out[0] = j->member;
|
||||
put64(out + 1, j->nonce);
|
||||
memcpy(out + 9, j->token, COOP_COOKIE_LEN);
|
||||
size_t k = coop_roster_pack(out + 9 + COOP_COOKIE_LEN, cap - 9 - COOP_COOKIE_LEN, &j->roster);
|
||||
return k ? 9 + COOP_COOKIE_LEN + k : 0;
|
||||
}
|
||||
|
||||
int coop_joined_parse(const uint8_t *p, size_t n, CoopJoined *j) {
|
||||
if (n < 9 + COOP_COOKIE_LEN) return 0;
|
||||
memset(j, 0, sizeof *j);
|
||||
j->member = p[0];
|
||||
j->nonce = get64(p + 1);
|
||||
memcpy(j->token, p + 9, COOP_COOKIE_LEN);
|
||||
return coop_roster_parse(p + 9 + COOP_COOKIE_LEN, n - 9 - COOP_COOKIE_LEN, &j->roster, NULL);
|
||||
}
|
||||
|
||||
size_t coop_error_pack(uint8_t *out, size_t cap, const CoopError *e) {
|
||||
size_t tlen = bounded_len(e->text, sizeof e->text - 1);
|
||||
if (cap < 10 + tlen) return 0;
|
||||
out[0] = e->reason;
|
||||
put64(out + 1, e->nonce);
|
||||
out[9] = (uint8_t)tlen;
|
||||
memcpy(out + 10, e->text, tlen);
|
||||
return 10 + tlen;
|
||||
}
|
||||
|
||||
int coop_error_parse(const uint8_t *p, size_t n, CoopError *e) {
|
||||
if (n < 10 || 10u + p[9] > n) return 0;
|
||||
memset(e, 0, sizeof *e);
|
||||
e->reason = p[0];
|
||||
e->nonce = get64(p + 1);
|
||||
text_clean(e->text, sizeof e->text, p + 10, p[9], sizeof e->text - 1); // for the log: printable UTF-8 only
|
||||
return 1;
|
||||
}
|
||||
|
||||
size_t coop_kick_pack(uint8_t *out, size_t cap, uint8_t member, uint64_t session) {
|
||||
if (cap < 9) return 0;
|
||||
out[0] = member;
|
||||
put64(out + 1, session);
|
||||
return 9;
|
||||
}
|
||||
|
||||
int coop_kick_parse(const uint8_t *p, size_t n, uint8_t *member, uint64_t *session) {
|
||||
if (n != 9) return 0;
|
||||
*member = p[0];
|
||||
*session = get64(p + 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
size_t coop_u32_pack(uint8_t *out, size_t cap, uint32_t v) {
|
||||
if (cap < 4) return 0;
|
||||
put32(out, v);
|
||||
return 4;
|
||||
}
|
||||
|
||||
int coop_u32_parse(const uint8_t *p, size_t n, uint32_t *v) {
|
||||
if (n < 4) return 0;
|
||||
*v = get32(p);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// ---- sealed player messages
|
||||
|
||||
static void env_nonce(uint8_t nonce[24], uint64_t session, uint32_t counter, uint8_t src) {
|
||||
memset(nonce, 0, 24);
|
||||
put64(nonce, session);
|
||||
put32(nonce + 8, counter);
|
||||
nonce[12] = src;
|
||||
}
|
||||
|
||||
size_t coop_seal(uint8_t *out, size_t cap, const uint8_t key[COOP_MSG_KEY_LEN], uint8_t src, uint8_t dst, uint64_t session,
|
||||
uint32_t counter, uint8_t kind, const void *bytes, size_t n) {
|
||||
size_t total = COOP_ENV_OVERHEAD + 1 + n;
|
||||
if (n > COOP_MAX_MESSAGE || cap < total) return 0;
|
||||
uint8_t nonce[24], ad[2] = {dst, COOP_ENV_V1};
|
||||
out[0] = COOP_ENV_V1;
|
||||
put64(out + 1, session);
|
||||
put32(out + 9, counter);
|
||||
uint8_t *plain = out + COOP_ENV_HDR;
|
||||
if (n) memmove(plain + 1, bytes, n);
|
||||
plain[0] = kind;
|
||||
env_nonce(nonce, session, counter, src);
|
||||
crypto_aead_lock(plain, out + COOP_ENV_HDR + 1 + n, key, nonce, ad, sizeof ad, plain, 1 + n);
|
||||
return total;
|
||||
}
|
||||
|
||||
int coop_envelope_peek(const uint8_t *p, size_t n, uint64_t *session, uint32_t *counter) {
|
||||
if (n < COOP_ENV_OVERHEAD + 1 || p[0] != COOP_ENV_V1) return 0;
|
||||
*session = get64(p + 1);
|
||||
*counter = get32(p + 9);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int coop_open(const uint8_t *p, size_t n, const uint8_t key[COOP_MSG_KEY_LEN], uint8_t src, uint8_t dst, uint8_t *kind,
|
||||
uint8_t *out, size_t cap, size_t *nout) {
|
||||
uint64_t session;
|
||||
uint32_t counter;
|
||||
if (!coop_envelope_peek(p, n, &session, &counter)) return 0;
|
||||
size_t len = n - COOP_ENV_OVERHEAD; // kind and bytes
|
||||
uint8_t plain[COOP_MAX_PAYLOAD], nonce[24], ad[2] = {dst, COOP_ENV_V1};
|
||||
if (len > sizeof plain || cap < len - 1) return 0;
|
||||
env_nonce(nonce, session, counter, src);
|
||||
if (crypto_aead_unlock(plain, p + n - COOP_ENV_MAC, key, nonce, ad, sizeof ad, p + COOP_ENV_HDR, len)) return 0;
|
||||
*kind = plain[0];
|
||||
if (len > 1) memcpy(out, plain + 1, len - 1);
|
||||
*nout = len - 1;
|
||||
crypto_wipe(plain, len);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// ---- signatures
|
||||
|
||||
void coop_sign_keypair(const uint8_t seed[32], uint8_t sk[COOP_SK_LEN], uint8_t pk[COOP_PK_LEN]) {
|
||||
uint8_t s[32];
|
||||
memcpy(s, seed, sizeof s); // the library wipes the seed it is given
|
||||
crypto_eddsa_key_pair(sk, pk, s);
|
||||
}
|
||||
|
||||
void coop_sign(uint8_t sig[COOP_SIG_LEN], const uint8_t sk[COOP_SK_LEN], const void *msg, size_t n) {
|
||||
crypto_eddsa_sign(sig, sk, msg, n);
|
||||
}
|
||||
|
||||
int coop_sign_check(const uint8_t sig[COOP_SIG_LEN], const uint8_t pk[COOP_PK_LEN], const void *msg, size_t n) {
|
||||
return crypto_eddsa_check(sig, pk, msg, n) == 0;
|
||||
}
|
||||
|
||||
void coop_blake2b(uint8_t *out, size_t outlen, const void *key, size_t klen, const void *msg, size_t n) {
|
||||
crypto_blake2b_keyed(out, outlen, key, klen, msg, n);
|
||||
}
|
||||
|
||||
// ---- POS
|
||||
|
||||
static void putf(uint8_t *p, float f) {
|
||||
uint32_t v;
|
||||
memcpy(&v, &f, 4);
|
||||
put32(p, v);
|
||||
}
|
||||
|
||||
// The f32 at p into *f; 0 when it is an infinity or a NaN (all exponent bits set), which a pose never holds.
|
||||
static int getf(const uint8_t *p, float *f) {
|
||||
uint32_t v = get32(p);
|
||||
memcpy(f, &v, 4);
|
||||
return (v & 0x7f800000u) != 0x7f800000u;
|
||||
}
|
||||
|
||||
// 1 when p[0..n) is printable ASCII: a POS's names reach the log and the game's animation lookup.
|
||||
static int printable(const uint8_t *p, size_t n) {
|
||||
for (size_t i = 0; i < n; i++)
|
||||
if (p[i] < 0x20 || p[i] > 0x7e) return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
enum { POS_HEAD = 11 }; // version, pseq, t_ms, flags, area length
|
||||
|
||||
size_t coop_pos_pack(uint8_t *out, size_t cap, const CoopPos *p) {
|
||||
size_t alen = bounded_len(p->area, COOP_POS_TEXT), n = POS_HEAD + alen + 17;
|
||||
int slots = p->nslots < COOP_POS_SLOTS ? p->nslots : COOP_POS_SLOTS;
|
||||
for (int i = 0; i < slots; i++) n += 1 + bounded_len(p->slot[i].node, COOP_POS_TEXT) + 4;
|
||||
if (cap < n) return 0;
|
||||
out[0] = COOP_POS_VERSION;
|
||||
put32(out + 1, p->pseq);
|
||||
put32(out + 5, p->t_ms);
|
||||
out[9] = p->flags, out[10] = (uint8_t)alen;
|
||||
memcpy(out + POS_HEAD, p->area, alen);
|
||||
uint8_t *q = out + POS_HEAD + alen;
|
||||
for (int k = 0; k < 3; k++) putf(q + 4 * k, p->pos[k]);
|
||||
putf(q + 12, p->yaw);
|
||||
q[16] = (uint8_t)slots, q += 17;
|
||||
for (int i = 0; i < slots; i++) {
|
||||
size_t len = bounded_len(p->slot[i].node, COOP_POS_TEXT);
|
||||
q[0] = (uint8_t)len;
|
||||
memcpy(q + 1, p->slot[i].node, len);
|
||||
putf(q + 1 + len, p->slot[i].frame);
|
||||
q += 1 + len + 4;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
int coop_pos_parse(const uint8_t *p, size_t n, CoopPos *out) {
|
||||
if (n < POS_HEAD || p[0] != COOP_POS_VERSION || p[10] > COOP_POS_TEXT || n < POS_HEAD + p[10] + 17u ||
|
||||
!printable(p + POS_HEAD, p[10]))
|
||||
return 0;
|
||||
CoopPos r;
|
||||
memset(&r, 0, sizeof r);
|
||||
r.pseq = get32(p + 1), r.t_ms = get32(p + 5), r.flags = p[9];
|
||||
memcpy(r.area, p + POS_HEAD, p[10]);
|
||||
size_t at = POS_HEAD + (size_t)p[10];
|
||||
int finite = 1;
|
||||
for (int k = 0; k < 3; k++) finite &= getf(p + at + 4 * k, &r.pos[k]);
|
||||
finite &= getf(p + at + 12, &r.yaw);
|
||||
r.nslots = p[at + 16], at += 17;
|
||||
if (!finite || r.nslots > COOP_POS_SLOTS) return 0;
|
||||
for (int i = 0; i < r.nslots; i++) {
|
||||
if (at >= n || p[at] > COOP_POS_TEXT || at + 1 + p[at] + 4 > n || !printable(p + at + 1, p[at]) ||
|
||||
!getf(p + at + 1 + p[at], &r.slot[i].frame))
|
||||
return 0;
|
||||
memcpy(r.slot[i].node, p + at + 1, p[at]);
|
||||
at += 1u + p[at] + 4;
|
||||
}
|
||||
if (at != n) return 0;
|
||||
*out = r;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int coop_pos_fresh(CoopPosSeen *s, uint64_t session, uint32_t pseq, uint64_t now_ms) {
|
||||
int again = !s->any || s->session != session || now_ms - s->at_ms >= COOP_POS_QUIET_MS;
|
||||
if (!again && pseq <= s->last) return 0;
|
||||
s->any = 1, s->session = session, s->last = pseq, s->at_ms = now_ms;
|
||||
return again ? 2 : 1;
|
||||
}
|
||||
|
||||
uint32_t coop_offer_shown(const CoopOffer *o, int (*accepted)(const char *key, void *user), void *user) {
|
||||
uint32_t shown = 0;
|
||||
for (int i = 0; i < o->n && i < COOP_MAX_MEMBERS; i++) {
|
||||
const CoopOfferMember *m = &o->member[i];
|
||||
if (m->id >= 1 && m->id <= COOP_MAX_MEMBERS && m->heard && !m->removed && !m->accepted_as[0] && m->key[0] &&
|
||||
accepted(m->key, user))
|
||||
shown |= 1u << m->id;
|
||||
}
|
||||
return shown;
|
||||
}
|
||||
209
runtime/coop_proto.h
Normal file
209
runtime/coop_proto.h
Normal file
@@ -0,0 +1,209 @@
|
||||
// The co-op wire format, as pure functions on bytes: no sockets, no threads, no game state. docs/coop.md ("The room's
|
||||
// secret and the wire") is the description a reviewer checks this file against.
|
||||
//
|
||||
// A room is named by a secret the players share out of band: 18 characters of a 27-symbol alphabet (85 bits), shown
|
||||
// XXXXXX-XXXXXX-XXXXXX. The relay never sees it. Two values are derived from it with keyed BLAKE2b (the key is the
|
||||
// secret's 18 canonical characters): the room's locator (16 bytes), which the relay knows the room by and which keys
|
||||
// the tag of every datagram between a client and the relay, and the message key (32 bytes), which seals every message
|
||||
// between the players (XChaCha20-Poly1305), so that the relay and anyone on the path can neither read nor change nor
|
||||
// make one.
|
||||
//
|
||||
// A datagram is a 24-byte header (little-endian) and a payload; the header carries an 8-byte tag, the start of an
|
||||
// HMAC-SHA256 over the first 16 header bytes and the payload, keyed with the locator. The client and relay messages
|
||||
// are CONNECT .. LEAVE and KICK (tools/coop_relay.py, the same format in Python); DATA carries a sealed player message:
|
||||
// the envelope (sender's session, counter) and, sealed, one kind byte and the message bytes the layers above coop.c
|
||||
// define. tests/coop_vectors.txt holds byte vectors that this file and the relay's Python are checked against
|
||||
// (--probe-coop, tests/coop_relay_test.py). Every parser checks every length against the bytes it was given and fails
|
||||
// closed.
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
enum {
|
||||
COOP_MAGIC = 0x434E, // bytes 4E 43
|
||||
COOP_PROTO = 2, // protocol major: a relay and a client talk only when it is equal
|
||||
COOP_HDR_LEN = 24,
|
||||
COOP_MAX_DGRAM = 1200, // a datagram's size at most: it crosses any path without fragmenting
|
||||
COOP_MAX_PAYLOAD = COOP_MAX_DGRAM - COOP_HDR_LEN,
|
||||
COOP_TAG_LEN = 8,
|
||||
COOP_KEY_LEN = 16, // the locator, which keys the tags
|
||||
COOP_MSG_KEY_LEN = 32,
|
||||
COOP_DST_ALL = 0xFF, // dst: every other member of the room
|
||||
COOP_SECRET_LEN = 18, // characters of a room secret
|
||||
COOP_SECRET_TEXT = COOP_SECRET_LEN + 2, // shown with two '-'
|
||||
COOP_MAX_MEMBERS = 8,
|
||||
COOP_NAME_MAX = 24, // a player's name in bytes of UTF-8
|
||||
COOP_COOKIE_LEN = 16,
|
||||
COOP_CONNECT_MIN = 64, // a CONNECT datagram's smallest size, so that no answer to it is larger
|
||||
COOP_ENV_V1 = 1, // the envelope of a player message
|
||||
COOP_ENV_HDR = 13, // u8 envelope version, u64 session, u32 counter
|
||||
COOP_ENV_MAC = 16,
|
||||
COOP_ENV_OVERHEAD = COOP_ENV_HDR + COOP_ENV_MAC,
|
||||
COOP_MAX_MESSAGE = COOP_MAX_PAYLOAD - COOP_ENV_OVERHEAD - 1, // a player message's bytes after its kind, at most
|
||||
};
|
||||
|
||||
// Datagram types. CONNECT .. LEAVE and KICK are between a client and the relay, DATA carries the players' messages.
|
||||
enum { COOP_T_CONNECT = 1, COOP_T_CHALLENGE = 2, COOP_T_JOINED = 3, COOP_T_ERROR = 5, COOP_T_ROSTER = 6, COOP_T_PING = 7,
|
||||
COOP_T_PONG = 8, COOP_T_LEAVE = 9, COOP_T_KICK = 11, COOP_T_DATA = 0x10 };
|
||||
enum { COOP_INTENT_CREATE = 1, COOP_INTENT_JOIN = 2 }; // CONNECT: make the room of a locator or join it
|
||||
enum { COOP_E_NO_ROOM = 1, COOP_E_ROOM_FULL = 2, COOP_E_PROTO = 3, COOP_E_RATE = 4, COOP_E_BAD_TAG = 5, COOP_E_SERVER_FULL = 6,
|
||||
COOP_E_ROOM_EXISTS = 7, COOP_E_REMOVED = 8, COOP_E_SESSION_USED = 9 }; // 9: a session used in the room before
|
||||
enum { COOP_FLAG_AWAY = 1, COOP_FLAG_MAKER = 2 }; // roster flags: not heard from for a while; made the room
|
||||
|
||||
// The kinds of player messages (the first byte of a sealed message). coop.c only carries them; HELLO, POS, DIGEST,
|
||||
// SECTION, SYNC_NEED and NOTICE belong to the layers that send them. A kind of 0xF0 and above is free for tests.
|
||||
enum { COOP_K_HELLO = 1, COOP_K_POS = 2, COOP_K_DIGEST = 3, COOP_K_SECTION = 4, COOP_K_SYNC_NEED = 5, COOP_K_NOTICE = 6,
|
||||
COOP_K_BYE = 7, COOP_K_TEST = 0xF0 };
|
||||
|
||||
typedef struct {
|
||||
uint8_t ver, type;
|
||||
uint8_t src, dst; // member ids 1..8; src 0 is the relay; dst COOP_DST_ALL: every other member
|
||||
uint16_t len; // payload bytes
|
||||
uint32_t room, seq; // room 0 until joined; seq counts the sender's datagrams
|
||||
} CoopHdr;
|
||||
|
||||
// ---- room secrets: 18 characters of "23456789BCDFGHJKMNPRSTVWXYZ" (27 symbols, 85.6 bits; no vowels, 0/1/O/I/L, Q or
|
||||
// E, so a secret spoken or typed does not read as a word), shown as XXXXXX-XXXXXX-XXXXXX. Any ASCII case, '-' and spaces
|
||||
// ignored. 1 and the canonical 18 characters plus a NUL in out when text is a secret.
|
||||
int coop_secret_normalize(const char *text, char out[COOP_SECRET_LEN + 1]);
|
||||
void coop_secret_format(const char secret[COOP_SECRET_LEN], char out[COOP_SECRET_TEXT + 1]);
|
||||
// A new secret from 32 random bytes (each symbol from one byte below 243, the rest skipped); 0 when they ran out.
|
||||
int coop_secret_from_random(const uint8_t random[32], char out[COOP_SECRET_LEN + 1]);
|
||||
// The secret's first characters and an ellipsis, for logs: "XXX…".
|
||||
void coop_secret_short(const char secret[COOP_SECRET_LEN], char out[8]);
|
||||
|
||||
// ---- keys. BLAKE2b keyed with the secret's canonical characters: locator = BLAKE2b-128("nx2navi-coop/2 room"),
|
||||
// message key = BLAKE2b-256("nx2navi-coop/2 messages"). The tag of a datagram: HMAC-SHA256(locator, header[0:16] +
|
||||
// payload)[0:8].
|
||||
void coop_hmac_sha256(const void *key, size_t klen, const void *a, size_t an, const void *b, size_t bn, uint8_t out[32]);
|
||||
void coop_room_keys(const char secret[COOP_SECRET_LEN], uint8_t locator[COOP_KEY_LEN], uint8_t msg_key[COOP_MSG_KEY_LEN]);
|
||||
|
||||
// ---- datagrams
|
||||
// The datagram of hdr (its len is ignored: n is the payload length) and payload into out. key NULL: a zero tag (what a
|
||||
// relay of another protocol version answers). Bytes written, 0 when it does not fit cap or n is too long.
|
||||
size_t coop_dgram_pack(uint8_t *out, size_t cap, const CoopHdr *hdr, const void *payload, size_t n,
|
||||
const uint8_t key[COOP_KEY_LEN]);
|
||||
// 1 when d is exactly one datagram of this format (magic, a length that matches); *payload points into d. The version
|
||||
// and the tag are not checked here.
|
||||
int coop_dgram_parse(const uint8_t *d, size_t n, CoopHdr *hdr, const uint8_t **payload);
|
||||
// 1 when the tag of the parsed datagram d (n bytes) is the one key makes; time independent of where they differ.
|
||||
int coop_dgram_verify(const uint8_t *d, size_t n, const uint8_t key[COOP_KEY_LEN]);
|
||||
int coop_dgram_tag_zero(const uint8_t *d);
|
||||
|
||||
// ---- names: a player's name from untrusted bytes. At most COOP_NAME_MAX bytes of valid UTF-8; a control character
|
||||
// (C0, DEL, C1) and each byte that is not valid UTF-8 become '?', and so do the characters that reorder text (bidi
|
||||
// controls). out is NUL-terminated (cap at least COOP_NAME_MAX + 1); the length.
|
||||
size_t coop_name_clean(char *out, size_t cap, const uint8_t *raw, size_t n);
|
||||
|
||||
// ---- client and relay messages
|
||||
// CONNECT: u8 intent, u8 flags, u8[16] locator, u64 client id, u64 session, u64 nonce, u8 name length, name,
|
||||
// u8[16] cookie (zero, or the CHALLENGE's), u8[16] rejoin token (zero, or the JOINED's of this room).
|
||||
typedef struct {
|
||||
uint8_t intent, flags;
|
||||
uint8_t locator[COOP_KEY_LEN];
|
||||
uint64_t client_id; // random for each start of the game; the relay knows a rejoin of the same member by it
|
||||
uint64_t session; // random for each join: the others take messages only of the session the roster names
|
||||
uint64_t nonce; // random for each attempt: every answer carries it
|
||||
char name[COOP_NAME_MAX + 1];
|
||||
uint8_t cookie[COOP_COOKIE_LEN], token[COOP_COOKIE_LEN];
|
||||
} CoopConnect;
|
||||
size_t coop_connect_pack(uint8_t *out, size_t cap, const CoopConnect *c); // zero-padded to COOP_CONNECT_MIN as a datagram
|
||||
int coop_connect_parse(const uint8_t *p, size_t n, CoopConnect *c);
|
||||
|
||||
// CHALLENGE: u64 nonce, u8[16] cookie.
|
||||
size_t coop_challenge_pack(uint8_t *out, size_t cap, uint64_t nonce, const uint8_t cookie[COOP_COOKIE_LEN]);
|
||||
int coop_challenge_parse(const uint8_t *p, size_t n, uint64_t *nonce, uint8_t cookie[COOP_COOKIE_LEN]);
|
||||
|
||||
// ROSTER: u8 n, n x (u8 id, u8 flags, u64 session, u8 name length, name).
|
||||
typedef struct { uint8_t id, flags; uint64_t session; char name[COOP_NAME_MAX + 1]; } CoopMemberInfo;
|
||||
typedef struct { uint8_t n; CoopMemberInfo m[COOP_MAX_MEMBERS]; } CoopRoster;
|
||||
size_t coop_roster_pack(uint8_t *out, size_t cap, const CoopRoster *r);
|
||||
// used (may be NULL): the bytes the roster took.
|
||||
int coop_roster_parse(const uint8_t *p, size_t n, CoopRoster *r, size_t *used);
|
||||
|
||||
// JOINED: u8 member, u64 nonce, u8[16] rejoin token, roster.
|
||||
typedef struct { uint8_t member; uint64_t nonce; uint8_t token[COOP_COOKIE_LEN]; CoopRoster roster; } CoopJoined;
|
||||
size_t coop_joined_pack(uint8_t *out, size_t cap, const CoopJoined *j);
|
||||
int coop_joined_parse(const uint8_t *p, size_t n, CoopJoined *j);
|
||||
|
||||
// ERROR: u8 reason, u64 nonce (of the CONNECT it answers, 0 else), u8 text length, text.
|
||||
typedef struct { uint8_t reason; uint64_t nonce; char text[61]; } CoopError; // text for the log, at most 60 bytes
|
||||
size_t coop_error_pack(uint8_t *out, size_t cap, const CoopError *e);
|
||||
int coop_error_parse(const uint8_t *p, size_t n, CoopError *e);
|
||||
|
||||
// KICK (the room's maker to the relay): u8 member, u64 its session.
|
||||
size_t coop_kick_pack(uint8_t *out, size_t cap, uint8_t member, uint64_t session);
|
||||
int coop_kick_parse(const uint8_t *p, size_t n, uint8_t *member, uint64_t *session);
|
||||
|
||||
size_t coop_u32_pack(uint8_t *out, size_t cap, uint32_t v); // PING and PONG: the token
|
||||
int coop_u32_parse(const uint8_t *p, size_t n, uint32_t *v);
|
||||
|
||||
// ---- player messages: the payload of a DATA datagram, sealed with the message key.
|
||||
// u8 envelope version (COOP_ENV_V1), u64 sender's session, u32 counter, ciphertext of (u8 kind, bytes), u8[16] tag
|
||||
// XChaCha20-Poly1305: nonce = session (8 bytes LE), counter (4 LE), src (1), 11 zero bytes; associated data = dst and
|
||||
// the envelope version. A session and counter are used once (a new session for every join, the counter from 1), so a
|
||||
// nonce never repeats under the room's key. A later envelope version can carry other fields; the kind byte and the
|
||||
// message inside stay as they are, so a new kind (a pose, say) only needs a number.
|
||||
// Seal: the payload into out (cap); its length, 0 when n is above COOP_MAX_MESSAGE or it does not fit.
|
||||
size_t coop_seal(uint8_t *out, size_t cap, const uint8_t key[COOP_MSG_KEY_LEN], uint8_t src, uint8_t dst, uint64_t session,
|
||||
uint32_t counter, uint8_t kind, const void *bytes, size_t n);
|
||||
// The envelope's clear fields; 0 when p is not an envelope of a version this build reads.
|
||||
int coop_envelope_peek(const uint8_t *p, size_t n, uint64_t *session, uint32_t *counter);
|
||||
// Open: 1 and the kind and bytes (into out, cap at least n) when the tag is right for this key, src and dst.
|
||||
int coop_open(const uint8_t *p, size_t n, const uint8_t key[COOP_MSG_KEY_LEN], uint8_t src, uint8_t dst, uint8_t *kind,
|
||||
uint8_t *out, size_t cap, size_t *nout);
|
||||
|
||||
// ---- signatures: EdDSA over Curve25519 with BLAKE2b (the library's crypto_eddsa). The room's message key cannot tell
|
||||
// one member from another, and the sync layer's state travels through every member, so what only one member may make
|
||||
// is signed with that member's key: its identity in the room, the maker's rules, and each pool contributor's counts
|
||||
// (coop_state.c). Every member can then pass them on, and nobody but the key's holder can make or change them.
|
||||
enum { COOP_PK_LEN = 32, COOP_SK_LEN = 64, COOP_SIG_LEN = 64 };
|
||||
void coop_sign_keypair(const uint8_t seed[32], uint8_t sk[COOP_SK_LEN], uint8_t pk[COOP_PK_LEN]);
|
||||
void coop_sign(uint8_t sig[COOP_SIG_LEN], const uint8_t sk[COOP_SK_LEN], const void *msg, size_t n);
|
||||
int coop_sign_check(const uint8_t sig[COOP_SIG_LEN], const uint8_t pk[COOP_PK_LEN], const void *msg, size_t n); // 1: valid
|
||||
// BLAKE2b of msg keyed with key (klen at most 64, 0 for none), outlen bytes (1 to 64): the sync layer's derivations.
|
||||
void coop_blake2b(uint8_t *out, size_t outlen, const void *key, size_t klen, const void *msg, size_t n);
|
||||
|
||||
// ---- POS (COOP_K_POS): where a player is and what Link plays, for showing the other players (nothing sends it in this build), meant to be sent about 15
|
||||
// times a second as a sealed player message (above). The bytes after the kind, little endian: u8 version
|
||||
// (COOP_POS_VERSION), u32 pseq (the sender's counter: one more for each POS it sends), u32 t_ms (the sender's clock), u8
|
||||
// flags, u8 area length (<= COOP_POS_TEXT) and the area's name (the game's current-area text), f32 x y z, f32 yaw
|
||||
// (radians, 0 facing +z), u8 slot count (<= COOP_POS_SLOTS), per AS slot u8 node name length (<= COOP_POS_TEXT), the
|
||||
// node's name, f32 frame. A parser takes exactly one message of its version: another version is another format this
|
||||
// build cannot read (version 1 had a u16 pseq). The names come from another player's game and reach this one's log and
|
||||
// its animation lookup, so a name with a byte outside printable ASCII (0x20..0x7e) is refused, and so is a number that
|
||||
// is not finite.
|
||||
#define COOP_POS_VERSION 2
|
||||
#define COOP_POS_TEXT 47
|
||||
#define COOP_POS_SLOTS 4
|
||||
enum { COOP_POS_ADULT = 1, COOP_POS_IN_WORLD = 2 };
|
||||
typedef struct {
|
||||
uint32_t pseq;
|
||||
uint32_t t_ms;
|
||||
uint8_t flags, nslots;
|
||||
char area[COOP_POS_TEXT + 1];
|
||||
float pos[3], yaw;
|
||||
struct { char node[COOP_POS_TEXT + 1]; float frame; } slot[COOP_POS_SLOTS];
|
||||
} CoopPos;
|
||||
size_t coop_pos_pack(uint8_t *out, size_t cap, const CoopPos *p); // 0 when it does not fit cap
|
||||
int coop_pos_parse(const uint8_t *p, size_t n, CoopPos *out);
|
||||
|
||||
// The receiver's counter of one POS sender (coop.h: a handler is not called once only). A pose is taken only above the
|
||||
// last one taken from the same member id in the same session, so neither a pose sent again nor one recorded earlier
|
||||
// in the session moves the puppet back while that sender's poses keep being taken; the first pose of another session
|
||||
// (another player given the id, the member back in a new session, or a roster that lists an earlier session) starts the
|
||||
// counter again. After COOP_POS_QUIET_MS with none taken (below), whoever holds the sender's datagrams back that long can
|
||||
// send its recorded poses of the session again (no secret needed), and they are taken: only the puppet moves. Someone
|
||||
// with the room's secret can seal a POS in a member's name with a counter far ahead: it becomes the newest pose, so the
|
||||
// puppet stands where it says (or is hidden, if it names another area) and the member's own poses are kept out until
|
||||
// nothing was taken from the sender for COOP_POS_QUIET_MS; then the next pose is taken whatever its counter and starts
|
||||
// the counter again. One forged pose every COOP_POS_QUIET_MS keeps the member's own out while the forger goes on.
|
||||
// session: the one the roster lists for the member (CoopView). Returns 0 to drop the pose, 1 to take it, 2 to take it
|
||||
// and drop what was kept of the sender's earlier poses.
|
||||
#define COOP_POS_QUIET_MS 3000
|
||||
typedef struct {
|
||||
uint64_t session, at_ms; // the session of the last pose taken, and when it was taken
|
||||
uint32_t last; // its counter
|
||||
int any; // a pose was taken
|
||||
} CoopPosSeen;
|
||||
int coop_pos_fresh(CoopPosSeen *s, uint64_t session, uint32_t pseq, uint64_t now_ms);
|
||||
2107
runtime/coop_state.c
Normal file
2107
runtime/coop_state.c
Normal file
File diff suppressed because it is too large
Load Diff
277
runtime/coop_state.h
Normal file
277
runtime/coop_state.h
Normal file
@@ -0,0 +1,277 @@
|
||||
// Co-op progress sync: the merge engine, without the game. Each player's game reports its flags here (coop_game.c reads
|
||||
// them from the game's flag database); the engine keeps the merged state of the room, gossips it between the players
|
||||
// (coop.c carries the messages) and hands back what the local game lacks. It knows flags only as (category, 32-bit hash,
|
||||
// value), so the probe drives it with a fake flag store.
|
||||
//
|
||||
// The state is a set of registers, each merged by keeping the highest value: a flag's register holds 1 for a flag that
|
||||
// changed from its default (it stays changed), or the count of an item (the highest wins). Merging is commutative,
|
||||
// associative and idempotent, so lost, repeated and reordered messages do no harm, and nothing a player has shrinks.
|
||||
// Spendable counters (rupees, ammunition, small keys) in a shared pool are records, one per contributor (a member's
|
||||
// identity) and pool: the base it brought when it joined the pool, and the units it gained and spent, signed with the
|
||||
// member's key, so every member passes them on and nobody but their owner can change them. The pool's value is the
|
||||
// highest base (at least 0) + all gains - all spends, where no contributor's spends count beyond its own gains plus the
|
||||
// counter's limit: a contributor can take at most what the pool can hold. Only identities the maker admitted
|
||||
// contribute, and a game counts only the records of the keys its own player accepted (and its own). A game remembers
|
||||
// what it joined a pool with and the records it saw then, and makes its claim again when the records it counts change
|
||||
// (a removal, or its player accepting more keys), so a removed player takes no keys another player brought.
|
||||
//
|
||||
// Gossip. Registers are split into COOP_SYNC_SECTIONS sections by hash; a DIGEST carries a sum per section (and the
|
||||
// room's rules), every 2 s and at once to a member who joins; a section whose sum differs from a peer's is sent to it in
|
||||
// SYNC messages, so two players converge within a few digests and a late joiner catches up with everything. A local
|
||||
// change goes out at once and again 80 and 250 ms later. Sending is paced (32 KB/s) under the relay's per-member limit.
|
||||
// Every SECTION (a push or an answer) carries its sender's signature over the room, its member id and session, a
|
||||
// counter and its bytes, checked before anything of it counts: the room's message key, which every holder of the
|
||||
// secret has (a relay run by one, a sender on a player's network), makes no values in a member's name.
|
||||
//
|
||||
// Identities. Each game has a signing key for each room and start of the game (from coop_sync_seed's random value and the
|
||||
// room's secret; the room's maker keeps one per room across starts, coop_sync_room_seed), and signs its identity in that
|
||||
// room: the key, the name, the session the relay lists for it and its session in the room before that one. A game takes
|
||||
// values only from a member whose identity it checked, an identity is bound to one session, and a session a member's
|
||||
// later identity names as the one before is never taken again, so an identity cannot be copied or reused by another
|
||||
// member; nothing else (a roster, a lost room) ends a session, since anyone on the path can send those. A signature
|
||||
// that fails its check counts against the member that sent it, as a refused value does (a section's against the
|
||||
// member's budget of checks only: someone else made it), and each member gets a bounded number of checks a second.
|
||||
//
|
||||
// Rules belong to the room: every game merges the same way. The maker's game signs a charter: the rules (the maker's
|
||||
// settings, coop_sync_settings), the identities admitted to the pools, the identities removed and the pools' epoch,
|
||||
// with an epoch it raises at each change; it rides in every DIGEST, so every member passes it on. A game takes a
|
||||
// charter only signed by the key it pinned when its player accepted the room (coop_sync_accept); before that, its own
|
||||
// for a room it made in this session; else the key of the member the relay names as the maker, but only while no
|
||||
// identified member carries a charter of another key; else, while no maker is there, the one key every member's
|
||||
// charter carries. A member the relay marks later (a restart, a hostile relay) changes nothing for a player who
|
||||
// accepted. A category switched to shared starts merging (its digest sums differ, the sections are exchanged); one
|
||||
// switched to per player stops; what was merged stays. A removed identity's messages are ignored and its records
|
||||
// dropped everywhere, and each game keeps every removal it saw in the room; a pool reset starts a new pools' epoch in
|
||||
// which the games join the pools again with what each held for the identities the reset admits.
|
||||
//
|
||||
// Acceptance. Flags are taken (stored, passed on, applied) only from a member whose key this player accepted in this
|
||||
// room: what a member brings that the player did not accept never enters this game's state. Acceptance is transitive:
|
||||
// a member the player accepted passes on what it took from members it accepted. Pool records are stored and passed on
|
||||
// as the maker admits them, so the games converge, but a pool counts only the records of keys this player accepted
|
||||
// (and its own), and joins the pools only once the player accepted the room: those are not transitive. Nothing is
|
||||
// handed to the game (coop_sync_take) until its player accepted the room as it is now (the identities in it, the
|
||||
// rules, the maker's key and the save being played: coop_sync_offer) and a copy of the save was made
|
||||
// (coop_sync_copied), and another save joins the pools only once it is accepted too; a member that is
|
||||
// present and has not identified itself after a few seconds keeps the room unaccepted. The offer's number is keyed
|
||||
// with this start's random value, so nobody can compute it in advance; it changes with any of those, and so does the
|
||||
// acceptance.
|
||||
//
|
||||
// Threads: none of its own and no lock. coop_game.c holds one lock around every call.
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
// Categories of shared state (coop_game.c classifies the game's flags) and their modes.
|
||||
enum {
|
||||
COOP_CAT_PROGRESS, // story, world and dungeon flags: shared | own
|
||||
COOP_CAT_ITEMS, // equipment, key items, upgrades and capacities: shared | own
|
||||
COOP_CAT_SONGS, // shared | own
|
||||
COOP_CAT_QUEST, // medallions, stones and the other quest items: shared | own
|
||||
COOP_CAT_KEYS, // small keys, per dungeon: pool | own
|
||||
COOP_CAT_RUPEES, // own | pool
|
||||
COOP_CAT_AMMO, // own | pool
|
||||
COOP_CAT_N
|
||||
};
|
||||
enum { COOP_MODE_OWN = 0, COOP_MODE_SHARED = 1, COOP_MODE_POOL = 2 };
|
||||
|
||||
typedef struct {
|
||||
uint32_t epoch; // 0: no rules
|
||||
uint8_t maker; // the member whose rules they are (this game's view: who sent them)
|
||||
uint8_t mode[COOP_CAT_N];
|
||||
} CoopRules;
|
||||
|
||||
const char *coop_cat_name(int cat); // "progress", ... (the settings key without "coop_")
|
||||
const char *coop_mode_name(int mode); // "own", "shared", "pool"
|
||||
int coop_cat_is_pool(int cat); // keys, rupees, ammo: own | pool; the others own | shared
|
||||
// The defaults: everything shared, keys in a pool, rupees and ammunition per player.
|
||||
void coop_rules_default(CoopRules *r);
|
||||
// Makes r a set the engine can run: a mode a category does not have becomes its default; with progress per player, keys
|
||||
// are per player too (a pool would pay twice for a key each world still holds); with progress shared, items, songs and
|
||||
// quest items are shared (per player, the one who took one from the shared world would leave the others without it).
|
||||
// The categories it changed, as a bit mask.
|
||||
unsigned coop_rules_normalize(CoopRules *r);
|
||||
// "progress shared, items shared, ..." into out.
|
||||
void coop_rules_text(const CoopRules *r, char *out, size_t cap);
|
||||
|
||||
// Register kinds on the wire (2 to 4 were protocol 2's unsigned pool registers).
|
||||
enum { COOP_R_FLAG = 1, COOP_R_POOL = 5 };
|
||||
enum { COOP_SYNC_SECTIONS = 64, COOP_K_DIGEST_VER = 4 }; // 4: signed sections, identities that name the session before
|
||||
|
||||
typedef struct CoopSync CoopSync;
|
||||
// self_id: random for this start of the game (contributor ids derive from it). schema: games merge only with the same
|
||||
// (this layer's version, the game's, and the classified table); 0 until the table is known.
|
||||
CoopSync *coop_sync_new(uint64_t self_id, uint32_t schema);
|
||||
void coop_sync_free(CoopSync *s);
|
||||
// Trace lines (sent, received, by hash and value) go to fn when set.
|
||||
void coop_sync_trace(CoopSync *s, void (*fn)(void *user, const char *line), void *user);
|
||||
// What the local game takes from the room: the highest value of flag or counter (cat, hash), 0 when this game does not
|
||||
// share that hash in that category (a flag: 1 for a Bool; a pool counter: what the game can show). Every value a
|
||||
// member sends is checked against it before it is stored or passed on; one that fails is dropped and counted, and a
|
||||
// member that sends many is ignored while it stays in the room. Called with the engine's lock held; no limits, nothing
|
||||
// is taken.
|
||||
typedef uint32_t (*CoopSyncLimitFn)(int cat, uint32_t hash, void *user);
|
||||
void coop_sync_limits(CoopSync *s, CoopSyncLimitFn fn, void *user);
|
||||
// A random key of this process for the register index (SipHash-2-4), so a peer cannot choose where its registers go.
|
||||
void coop_sync_index_key(CoopSync *s, const uint8_t key[16]);
|
||||
uint64_t coop_siphash24(uint64_t k0, uint64_t k1, const uint8_t *m, size_t n);
|
||||
// The schema, once the local game's table is known: a new one forgets everything merged.
|
||||
void coop_sync_schema(CoopSync *s, uint32_t schema);
|
||||
// Members (a bit per id) whose messages are ignored for sending values this game refuses.
|
||||
unsigned coop_sync_ignored(const CoopSync *s);
|
||||
|
||||
// ---- the room (the coop thread)
|
||||
// The room and who is in it: code "" when in none. A new code (or none) forgets the peers and everything merged:
|
||||
// nothing of one room reaches the next. The acceptance, the pinned maker, the charter, the removals, the sessions that
|
||||
// ended and this game's own pool records stay while the code comes back the same (the session reached the room again);
|
||||
// another room starts them anew.
|
||||
// self: this player's member id; ids and sessions: every member's (self included: this game's own session, the one it
|
||||
// joined with, which its identity and sections are signed for; sessions NULL: each id's own number); maker: the member
|
||||
// the relay names as the room's maker, 0 when none is in the room.
|
||||
void coop_sync_room(CoopSync *s, const char *code, int self, const int *ids, const uint64_t *sessions, int n, int maker,
|
||||
uint64_t now_ms);
|
||||
// The room's own seed for this player's key in the room of that code (the maker's, kept in its profile so that its key
|
||||
// outlives a restart of the game); without it the key comes from coop_sync_seed's value of this start.
|
||||
void coop_sync_room_seed(CoopSync *s, const char *code, const uint8_t seed[32]);
|
||||
// This player's own rule settings, and whether it made the room in this session (its settings are the room's).
|
||||
void coop_sync_settings(CoopSync *s, const CoopRules *mine, int made_room);
|
||||
// A peer message (kind COOP_K_DIGEST or COOP_K_SECTION, the bytes after the kind) from member from.
|
||||
void coop_sync_receive(CoopSync *s, int from, uint8_t kind, const uint8_t *bytes, size_t n, uint64_t now_ms);
|
||||
// Timers: digests, repeated pushes, answers to digests. send(member or 0 for all, kind, bytes, n, user) queues one
|
||||
// message (1 when queued); call it every few ms.
|
||||
typedef int (*CoopSyncSendFn)(int member, uint8_t kind, const uint8_t *bytes, size_t n, void *user);
|
||||
void coop_sync_tick(CoopSync *s, uint64_t now_ms, CoopSyncSendFn send, void *user);
|
||||
// The rules in force (epoch 0: none yet; maker: the member holding the key that signed them, 0 none) and a counter
|
||||
// that changes when they do.
|
||||
unsigned coop_sync_rules(const CoopSync *s, CoopRules *out);
|
||||
|
||||
// ---- identity, the offer and acceptance
|
||||
// A random value of this start of the game: the identity keys (one per room) and the offer's number derive from it.
|
||||
void coop_sync_seed(CoopSync *s, const uint8_t seed[32]);
|
||||
void coop_sync_name(CoopSync *s, const char *name); // this player's name, signed into its identity
|
||||
// What joining the room means, for the player to accept: the other members (by the names their identities carry), the
|
||||
// rules and the key that signed them. heard: its identity was checked (a member not identified a few seconds after
|
||||
// it appeared shows with heard 0, counts in unidentified and keeps the room unaccepted); removed: the maker removed
|
||||
// it. A key the player accepted counts as accepted only under the name it signed then: under another name it is a new
|
||||
// offer (accepted_as says the name it was accepted as). No offer (token 0) outside a room, before the rules are known
|
||||
// (the members and disagree are filled in), and while a member that just appeared is not identified yet.
|
||||
typedef struct {
|
||||
int id, heard, maker, removed;
|
||||
char name[COOP_NAME_MAX + 1]; // the name it signed; "" until heard (coop_game.c shows the relay's)
|
||||
char key[20]; // its key's fingerprint, xxxx-xxxx-xxxx-xxxx; "" until heard
|
||||
char accepted_as[COOP_NAME_MAX + 1]; // its key was accepted under this other name ("" when not, or under this one)
|
||||
} CoopOfferMember;
|
||||
typedef struct {
|
||||
uint32_t token; // the offer's number, random for each start of the game; 0: none
|
||||
int accepted; // the player accepted this offer (values are applied once the copy is made: copy)
|
||||
int n; // the other members
|
||||
CoopOfferMember member[COOP_MAX_MEMBERS];
|
||||
CoopRules rules;
|
||||
char maker_key[20]; // the fingerprint of the key that signed the rules
|
||||
int maker_moved; // the relay names another member as the maker than the one whose key signs the rules
|
||||
int new_save; // another save was loaded since the last acceptance: it gets the room's progress, which holds
|
||||
// what every save played in the room brought (the last one's too)
|
||||
int copy; // the copy of the save for this acceptance: 0 not yet, 1 made, -1 failed (accept again to retry)
|
||||
int unidentified; // members in the room that never identified themselves: the room cannot be accepted meanwhile
|
||||
int disagree; // members carry rules signed by different keys (or by another than the one in force)
|
||||
} CoopOffer;
|
||||
int coop_sync_offer(CoopSync *s, CoopOffer *out, uint64_t now_ms); // 1 when there is an offer
|
||||
// Accepts the offer of that number: its identities, rules and maker's key (pinned from now on in this room). 1 when
|
||||
// token is the current offer's and no member in the room is unidentified. A copy of the save is wanted when none was
|
||||
// made for the save being played.
|
||||
int coop_sync_accept(CoopSync *s, uint32_t token);
|
||||
int coop_sync_copy_wanted(const CoopSync *s);
|
||||
void coop_sync_copied(CoopSync *s, int ok);
|
||||
// Values are handed out: the current offer is accepted and its copy made (coop_sync_take checks it itself).
|
||||
int coop_sync_open(CoopSync *s);
|
||||
// The maker's game (it holds the key the charter is signed with): removes a member in the room (by member id) or any
|
||||
// key the room knew (admitted to the pools, accepted by this player, or a member's; by key id, also once it left): its
|
||||
// identity is dropped by every game, its messages ignored, its pool records gone. Or resets the pools: a new pools'
|
||||
// epoch that admits this player and the members it accepted that are in the room, and in which every game joins the
|
||||
// pools again with what they held for those. 1 when done.
|
||||
int coop_sync_remove(CoopSync *s, int member);
|
||||
int coop_sync_remove_key(CoopSync *s, uint64_t kid);
|
||||
int coop_sync_reset_pools(CoopSync *s);
|
||||
int coop_sync_is_maker(const CoopSync *s);
|
||||
// A key's fingerprint as the offer shows it (xxxx-xxxx-xxxx-xxxx, or the 16 hex digits) into its id; 1 when it is one.
|
||||
int coop_sync_key_parse(const char *text, uint64_t *kid);
|
||||
// The identities the pools admit, with what each took beyond what it brought (per pool, what its spends took up to its
|
||||
// gains plus the counter's limit and what entered the pool, beyond its gains; summed over the pools of keys, rupees and
|
||||
// ammunition): whom a maker would remove after a drain. Their count (at most max).
|
||||
typedef struct {
|
||||
char key[20]; // its fingerprint
|
||||
int member; // its member id in the room, 0 when it is not in it
|
||||
int self; // this player's
|
||||
int removed; // the maker removed it
|
||||
char name[COOP_NAME_MAX + 1]; // the name its identity signed, while it is in the room
|
||||
int64_t spent[3]; // keys, rupees, ammunition taken beyond what it brought, in pools it took from (>= 0)
|
||||
} CoopContributor;
|
||||
int coop_sync_contributors(const CoopSync *s, CoopContributor *out, int max);
|
||||
// 1 once every peer's digest matched this player's after it joined (or it is alone): the room's pools are known.
|
||||
int coop_sync_caught_up(const CoopSync *s);
|
||||
|
||||
// ---- the local game (the game thread)
|
||||
// A save is being played (the game calls it at every bind). After the first one: another save was loaded, so
|
||||
// everything merged is forgotten, the pools bind again (this game's own pool records stay: they are the room's), and
|
||||
// the acceptance is asked again with a new copy, since the room's progress holds what the last save brought.
|
||||
void coop_sync_rebind(CoopSync *s);
|
||||
// A flag's local value: 1 for a flag that differs from its default, a count for an item. Values only grow the merged state.
|
||||
void coop_sync_local(CoopSync *s, int cat, uint32_t hash, uint32_t value, uint64_t now_ms);
|
||||
// A pool counter's local value and its cap (-1: none). Before the room is known and accepted it is only remembered;
|
||||
// then it joins the pool (the pool rises to it if lower: nothing is taken away) and each later change counts as a gain
|
||||
// or a spend.
|
||||
void coop_sync_pool_local(CoopSync *s, int cat, uint32_t hash, int32_t value, int32_t cap, uint64_t now_ms);
|
||||
|
||||
typedef struct {
|
||||
uint8_t pool; // 0: a flag (value: the merged value), 1: a pool counter (value: what to show, within its cap)
|
||||
uint8_t cat;
|
||||
uint32_t hash;
|
||||
int32_t value;
|
||||
} CoopApply;
|
||||
// Up to max values the local game should take. A flag is handed out once per merged value, so the game may lower it
|
||||
// afterwards (spend, lose) without getting it back; a pool counter until the game shows it (coop_sync_pool_wrote).
|
||||
int coop_sync_take(CoopSync *s, CoopApply *out, int max);
|
||||
// The game was given the value of a pool counter (coop_sync_take): it is the expected local value from now on.
|
||||
void coop_sync_pool_wrote(CoopSync *s, uint32_t hash, int32_t value);
|
||||
// Put a taken apply back (the game could not take it this frame).
|
||||
void coop_sync_untake(CoopSync *s, const CoopApply *a);
|
||||
|
||||
// ---- inspection (tests, logs)
|
||||
typedef struct {
|
||||
unsigned regs, synced; // registers, and those under the room's rules
|
||||
unsigned sent_msgs, recv_msgs, sent_bytes;
|
||||
unsigned merged; // registers a message raised
|
||||
unsigned pools_bound;
|
||||
unsigned rejected; // values refused (not shared here, out of range, the state full, failed record signatures)
|
||||
unsigned unaccepted; // flags dropped because their sender's key is not one this player accepted
|
||||
unsigned sig_checks; // signatures checked
|
||||
unsigned sig_skipped; // messages dropped because their sender's budget of checks was spent
|
||||
unsigned forged; // sections, and identities or charters in digests, whose signature did not check out (made
|
||||
// in a member's name by someone else); never held against that member
|
||||
unsigned replayed; // sections whose counter was taken before (sealed again by someone with the secret)
|
||||
unsigned rate_dropped; // messages over a member's rate
|
||||
unsigned probe_max; // the longest run of index slots an insert walked
|
||||
unsigned own_key; // identities of another member signed with this game's own key (a copy of its key file)
|
||||
int own_key_member; // the member that sent the last of them
|
||||
unsigned key_changes; // another key's identity for an identified member's session checked out: a dispute
|
||||
int key_change_member; // began, or the other key took the place; the member of the last of them
|
||||
unsigned key_moves; // a key this player accepted identified as another member number or under another
|
||||
int key_move_member, key_move_from; // name than before: the member it is now, the number it had (0 none)
|
||||
} CoopSyncStats;
|
||||
void coop_sync_stats(const CoopSync *s, CoopSyncStats *out);
|
||||
// The merged value of a flag (0 when absent), and a pool's value (as this game counts it) and whether it is bound.
|
||||
uint32_t coop_sync_flag(const CoopSync *s, int cat, uint32_t hash);
|
||||
int coop_sync_pool(const CoopSync *s, uint32_t hash, int64_t *value);
|
||||
// The record this game signed for a pool in the pools' epoch in force (tests): 1 when it has one.
|
||||
int coop_sync_own_record(const CoopSync *s, uint32_t hash, int32_t *base, uint32_t *gain, uint32_t *spend);
|
||||
// The record of key kid this game holds for a pool in the pools' epoch in force, and that epoch (tests).
|
||||
int coop_sync_record(const CoopSync *s, uint32_t hash, uint64_t kid, int32_t *base, uint32_t *gain, uint32_t *spend);
|
||||
uint32_t coop_sync_pool_epoch(const CoopSync *s);
|
||||
// 1 when this player accepted key kid in the room (its own key counts as accepted).
|
||||
int coop_sync_accepted_key(const CoopSync *s, uint64_t kid);
|
||||
// A SECTION message of n bytes in msg (cap at most) as this game sends one: its next counter and its signature for its
|
||||
// member id and session appended (tests that hand an engine what a member sends). The new length, 0 when it does not fit.
|
||||
size_t coop_sync_sign_section(CoopSync *s, uint8_t *msg, size_t n, size_t cap);
|
||||
// The digest sums, for tests: two engines with equal sums hold the same synced state.
|
||||
void coop_sync_sums(const CoopSync *s, uint32_t out[COOP_SYNC_SECTIONS]);
|
||||
|
||||
int probe_coop_sync(void); // coop_sync_probe.c: the engine's part of --probe-coop; failures
|
||||
3500
runtime/coop_sync_probe.c
Normal file
3500
runtime/coop_sync_probe.c
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
// The host's own folder and file dialogs, for menu pages that point at a folder (the Amiibo tab) or a file (a shared
|
||||
// save's zip, the Game tab), and the player's Downloads folder: folder_pick_win.cpp with Win32, folder_pick_sdl.c with
|
||||
// SDL. The menu has no text entry, so a folder is chosen here or by walking the page's list.
|
||||
// SDL. A folder is chosen here or by walking the page's list, not typed.
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
|
||||
|
||||
@@ -79,3 +79,12 @@ int fs_save_import_waiting(void); // 1 while an import
|
||||
int fs_save_import_cancel(void); // drops it; 0 on success
|
||||
const char *fs_save_import_done(void); // the backup of the save an import replaced at this start,
|
||||
// "-" when there was none, "" when no import ran
|
||||
// A copy of the newest committed save (every slot) in <profile>/<folder>/<UTC time>/, flushed, taken while no Commit
|
||||
// runs; the newest keep copies stay. prefix (NULL: none) goes before the time, and a copy whose name it begins is
|
||||
// never pruned: the copy from before a co-op room, say, outlasts the ones made later. 1 and the copy's path in out
|
||||
// (empty when nothing is saved yet: nothing to copy), 0 when it could not be made (logged). Slow (the whole save): not
|
||||
// on the game's thread.
|
||||
int fs_save_snapshot(const char *folder, const char *prefix, int keep, char *out, size_t cap);
|
||||
// <profile>/rel into out: a file of the profile folder beside the saves (the co-op maker's room keys). 0 when there is
|
||||
// no profile folder or the path does not fit.
|
||||
int fs_profile_path(const char *rel, char *out, size_t cap);
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "coop_game.h"
|
||||
#include "fs.h"
|
||||
#include "host.h"
|
||||
#include "platform/platform.h"
|
||||
@@ -599,6 +600,66 @@ void fs_save_crash_wait(void) {
|
||||
(unsigned long long)(plat_now_ms() - t0));
|
||||
}
|
||||
|
||||
int fs_profile_path(const char *rel, char *out, size_t cap) {
|
||||
if (cap) out[0] = 0;
|
||||
return *profile && snprintf(out, cap, "%s/%s", profile, rel) < (int)cap;
|
||||
}
|
||||
|
||||
int fs_save_snapshot(const char *folder, const char *prefix, int keep, char *out, size_t cap) {
|
||||
char root[1100];
|
||||
if (cap) out[0] = 0;
|
||||
if (!*profile || snprintf(root, sizeof root, "%s/%s", profile, folder) >= (int)sizeof root) return 0;
|
||||
make_dirs(root);
|
||||
uint64_t ns = plat_unix_time_ns();
|
||||
struct tm t;
|
||||
plat_gmtime((int64_t)(ns / 1000000000u), &t);
|
||||
char name[64];
|
||||
if (!prefix) prefix = "";
|
||||
if (*prefix >= '0' && *prefix <= '9') return 0; // a name that begins with a digit is one the pruning may take
|
||||
int len = snprintf(name, sizeof name, "%.16s%04d%02d%02d-%02d%02d%02d-%03u", prefix, t.tm_year + 1900, t.tm_mon + 1,
|
||||
t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, (unsigned)(ns / 1000000u % 1000u));
|
||||
char *dst = join(root, name);
|
||||
for (unsigned k = 1; exists(dst) && k < 1000; k++) { // two in one millisecond
|
||||
free(dst);
|
||||
snprintf(name + len, sizeof name - (size_t)len, "-%03u", k);
|
||||
dst = join(root, name);
|
||||
}
|
||||
int nfiles = 0, nlinked = 0, have = 0, ok = 0;
|
||||
uint64_t bytes = 0;
|
||||
plat_mutex_lock(&tx_lock); // no Commit swaps the save while it is copied
|
||||
const char *src = newest_save();
|
||||
have = exists(src);
|
||||
if (have) ok = !copy_tree(src, dst, NULL, 1, &nfiles, &nlinked, &bytes);
|
||||
plat_mutex_unlock(&tx_lock);
|
||||
if (!have) {
|
||||
free(dst);
|
||||
return 1; // nothing saved yet: nothing to go back to
|
||||
}
|
||||
if (!ok) {
|
||||
rt_log("fs: cannot copy the save to %s", dst);
|
||||
remove_tree(dst);
|
||||
free(dst);
|
||||
return 0;
|
||||
}
|
||||
if (cap) snprintf(out, cap, "%s", dst);
|
||||
free(dst);
|
||||
Listing l; // the newest keep copies stay; their names sort by time; a prefixed one is never pruned
|
||||
if (!list_dir(root, &l)) {
|
||||
qsort(l.e, (size_t)l.n, sizeof *l.e, listed_cmp);
|
||||
int dirs = 0;
|
||||
for (int i = 0; i < l.n; i++) dirs += l.e[i].kind == PLAT_FS_DIR && l.e[i].name[0] >= '0' && l.e[i].name[0] <= '9';
|
||||
for (int i = 0; i < l.n && dirs > keep; i++) {
|
||||
if (l.e[i].kind != PLAT_FS_DIR || l.e[i].name[0] < '0' || l.e[i].name[0] > '9') continue;
|
||||
char *p = join(root, l.e[i].name);
|
||||
remove_tree(p);
|
||||
free(p);
|
||||
dirs--;
|
||||
}
|
||||
listing_free(l.e, l.n);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static uint32_t commit_run(void) {
|
||||
committing = 1;
|
||||
plat_mutex_lock(&tx_lock);
|
||||
@@ -1107,7 +1168,10 @@ 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)) return romfs_open(out, path, 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);
|
||||
if (!out || !(mode & (FS_OPEN_READ | FS_OPEN_WRITE)) || (mode & ~7)) return FS_R_INVALID_ARGUMENT;
|
||||
char p[PATH_CAP];
|
||||
@@ -2010,6 +2074,21 @@ static void probe_storage(void) {
|
||||
CHECK(tx_commit() == 0 && !fs_save_busy(), "Commit after the changes");
|
||||
probe_save_tx(uid);
|
||||
|
||||
// copies of the save: the first one, prefixed, outlasts the rotation of the later ones
|
||||
char first[PLAT_PATH_MAX], later[PLAT_PATH_MAX];
|
||||
int copies = fs_save_snapshot("coop-backup", "first-", 3, first, sizeof first);
|
||||
for (int i = 0; i < 6; i++) copies += fs_save_snapshot("coop-backup", NULL, 3, later, sizeof later);
|
||||
char backup[PLAT_PATH_MAX * 3 + 96];
|
||||
snprintf(backup, sizeof backup, "%s/coop-backup", dir);
|
||||
Listing bl;
|
||||
int dated = 0, prefixed = 0;
|
||||
if (!list_dir(backup, &bl)) {
|
||||
for (int i = 0; i < bl.n; i++) dated += bl.e[i].name[0] >= '0' && bl.e[i].name[0] <= '9', prefixed += !strncmp(bl.e[i].name, "first-", 6);
|
||||
listing_free(bl.e, bl.n);
|
||||
}
|
||||
CHECK(copies == 7 && first[0] && exists(first) && prefixed == 1 && dated == 3,
|
||||
"save copies: the first (prefixed) stays beside the newest 3 of 6 later ones (%d made, %d first, %d dated)", copies, prefixed, dated);
|
||||
|
||||
// temporary and cache storage
|
||||
CHECK(RES(S_MOUNT_TEMP, U("temp")) == 0 && RES(S_CREATE_FILE, U("temp:/t.bin"), 4) == 0 && !fs_save_busy(),
|
||||
"temporary storage");
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
|
||||
#include "audren.h"
|
||||
#include "cfg.h"
|
||||
#include "coop.h"
|
||||
#include "flight.h"
|
||||
#include "fs.h"
|
||||
#include "gfx.h"
|
||||
@@ -88,6 +89,7 @@ void gfx_window_closed(void) {
|
||||
vk_pipeline_save();
|
||||
prof_write(); // plat_exit runs no atexit handlers
|
||||
rtss_limit_restore(); // RivaTuner Statistics Server's profile as it was
|
||||
coop_shutdown(); // LEAVE and BYE to the room, before the process ends
|
||||
fs_save_flush(); // last: the game's threads still run until plat_exit, and a Commit after this one is refused
|
||||
if (restart) {
|
||||
cfg_setenv("NX2NAVI_REEXEC", NULL); // the new process counts its own address-space retries (memory.c)
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
static SDL_Window *g_win;
|
||||
static uint32_t g_ev_base; // SDL_RegisterEvents: the user events below
|
||||
enum { EV_RUN, EV_SETTINGS, EV_CLOSE, EV_COUNT };
|
||||
enum { EV_RUN, EV_SETTINGS, EV_CLOSE, EV_TEXT_ON, EV_TEXT_OFF, EV_PASTE, EV_COUNT };
|
||||
static PlatEvent g_video_ready; // manual-reset: SDL video is up (or failed)
|
||||
static int g_video_ok;
|
||||
static PlatOnce g_thread_once = PLAT_ONCE_INIT;
|
||||
@@ -121,6 +121,17 @@ void gfx_window_request_close(void) {
|
||||
if (g_win) post(EV_CLOSE);
|
||||
}
|
||||
|
||||
// SDL sends SDL_EVENT_TEXT_INPUT between SDL_StartTextInput and SDL_StopTextInput only (and shows an on-screen keyboard
|
||||
// there where the system has one, as Steam's on a handheld); the window thread makes the calls.
|
||||
void gfx_window_text_input(int on) {
|
||||
if (g_win) post(on ? EV_TEXT_ON : EV_TEXT_OFF);
|
||||
}
|
||||
|
||||
// SDL's clipboard belongs to the window thread: the text is read there and handed to the menu.
|
||||
void gfx_window_paste(void) {
|
||||
if (g_win) post(EV_PASTE);
|
||||
}
|
||||
|
||||
// ---- the display's refresh rate
|
||||
static void refresh_rate_update(void) {
|
||||
const SDL_DisplayMode *m = SDL_GetCurrentDisplayMode(SDL_GetDisplayForWindow(g_win));
|
||||
@@ -158,6 +169,17 @@ static void handle(const SDL_Event *e) {
|
||||
if (g_win) apply_settings();
|
||||
return;
|
||||
}
|
||||
if (e->type == g_ev_base + EV_TEXT_ON || e->type == g_ev_base + EV_TEXT_OFF) {
|
||||
if (g_win && e->type == g_ev_base + EV_TEXT_ON) SDL_StartTextInput(g_win);
|
||||
else if (g_win) SDL_StopTextInput(g_win);
|
||||
return;
|
||||
}
|
||||
if (e->type == g_ev_base + EV_PASTE) {
|
||||
char text[256];
|
||||
plat_clipboard_get(text, sizeof text);
|
||||
menu_event_paste(text);
|
||||
return;
|
||||
}
|
||||
if (e->type == g_ev_base + EV_CLOSE) gfx_window_closed();
|
||||
if (!g_win) return;
|
||||
input_sdl_event(e);
|
||||
|
||||
@@ -52,6 +52,8 @@ int gfx_window_vk_presentable(VkInstance inst, VkPhysicalDevice pd, uint32_t fam
|
||||
#define WND_STYLE WS_OVERLAPPEDWINDOW
|
||||
#define WM_APP_SETTINGS (WM_APP + 1)
|
||||
#define WM_APP_FULLSCREEN (WM_APP + 2) // the fullscreen setting, retried at the first activation
|
||||
#define WM_APP_TEXT_INPUT (WM_APP + 3) // the menu's text field takes text (wParam 1) or no longer (0)
|
||||
#define WM_APP_PASTE (WM_APP + 4) // the menu's Paste: the clipboard's text, read on the window thread
|
||||
|
||||
static WINDOWPLACEMENT g_saved_place = {sizeof g_saved_place}; // the window behind fullscreen (window thread)
|
||||
|
||||
@@ -189,6 +191,18 @@ void gfx_window_request_close(void) {
|
||||
if (g_hwnd) PostMessageW(g_hwnd, WM_CLOSE, 0, 0);
|
||||
}
|
||||
|
||||
// The menu's text field lives in this window, which has no IME (detached at creation, below): while the field takes
|
||||
// text the window gets the default one, so a player can type a name in Chinese, Japanese or Korean (Windows hands the
|
||||
// composed characters over as WM_CHAR, which menu_window_msg passes on), and it is detached again after. Posted to
|
||||
// the window thread, which owns the window's input context.
|
||||
void gfx_window_text_input(int on) {
|
||||
if (g_hwnd) PostMessageW(g_hwnd, WM_APP_TEXT_INPUT, (WPARAM)(on != 0), 0);
|
||||
}
|
||||
|
||||
void gfx_window_paste(void) {
|
||||
if (g_hwnd) PostMessageW(g_hwnd, WM_APP_PASTE, 0, 0);
|
||||
}
|
||||
|
||||
// ---- refresh rate of the window's monitor (NX2NAVI_FPS_LIMIT=display), measured when the window opens, lands on another
|
||||
// monitor or the display mode changes (gfx_window_set_refresh keeps it). QueryDisplayConfig gives the exact rational
|
||||
// rate (59.94, 143.998); EnumDisplaySettings' whole hertz is the fallback.
|
||||
@@ -496,6 +510,16 @@ static LRESULT CALLBACK wnd_proc(HWND h, UINT m, WPARAM w, LPARAM l) {
|
||||
input_cursor_suspend(0);
|
||||
}
|
||||
return 0;
|
||||
case WM_APP_TEXT_INPUT:
|
||||
if (w) ImmAssociateContextEx(h, NULL, IACE_DEFAULT);
|
||||
else ImmAssociateContext(h, NULL);
|
||||
return 0;
|
||||
case WM_APP_PASTE: {
|
||||
char text[256];
|
||||
plat_clipboard_get(text, sizeof text);
|
||||
menu_event_paste(text);
|
||||
return 0;
|
||||
}
|
||||
case WM_SIZE:
|
||||
keep_awake(w != SIZE_MINIMIZED);
|
||||
if (w != SIZE_MINIMIZED) gfx_window_mark_dirty();
|
||||
@@ -681,7 +705,8 @@ static void window_main(void *arg) {
|
||||
// An IME switched on over the game attaches to this window and then shows its candidate window and eats the keys
|
||||
// it composes, although there is nothing here to type into (a Chinese IME takes Shift, the B button by default).
|
||||
// Detaching the game's window leaves the software keyboard alone: its edit box sits in a window of its own
|
||||
// (swkbd_win.c) and gets the IME it needs.
|
||||
// (swkbd_win.c) and gets the IME it needs. The menu's text field attaches one while it takes text
|
||||
// (gfx_window_text_input).
|
||||
ImmAssociateContext(g_hwnd, NULL);
|
||||
// The frame was measured at the system DPI (or the chosen monitor's); the window may have opened on a monitor at
|
||||
// another scale. When the size changes on a chosen monitor, the window is centred again in its work area;
|
||||
|
||||
@@ -25,8 +25,8 @@ void rt_log_raw(const char *p, size_t n);
|
||||
const char *rt_log_path(void); // the log file, NULL when this run writes none
|
||||
void rt_log_sync(void); // writes the queued log lines now; later lines are written as they are made
|
||||
enum { RT_TRACE_SVC = 1, RT_TRACE_HOSTCALL = 2, RT_TRACE_IPC = 4, RT_TRACE_FS = 8, RT_TRACE_GFX = 16, RT_TRACE_PERF = 32,
|
||||
RT_TRACE_SCHED = 64, RT_TRACE_AUDIO = 128, RT_TRACE_PRESENT = 256 };
|
||||
extern unsigned rt_trace; // from NX2NAVI_TRACE=svc,host,ipc,fs,gfx,perf,sched,audio,present (or all)
|
||||
RT_TRACE_SCHED = 64, RT_TRACE_AUDIO = 128, RT_TRACE_PRESENT = 256, RT_TRACE_COOP = 512 };
|
||||
extern unsigned rt_trace; // from NX2NAVI_TRACE=svc,host,ipc,fs,gfx,perf,sched,audio,present,coop (or all)
|
||||
// prof_win.c: NX2NAVI_PROFILE=<path> sampling profiler; NX2NAVI_TRACE=perf frame timing (waits of the render thread)
|
||||
// PERF_TEX: texture uploads on the render thread (deswizzle, decode, staging), PERF_ASTC included
|
||||
enum { PERF_PACE, PERF_FENCE, PERF_DRAIN, PERF_PIPE, PERF_XLATE, PERF_TEX, PERF_ASTC, PERF_N };
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
// --probe-loader load and relocate the modules, check them against the measured 1.2.1 values
|
||||
// --probe-kernel, --probe-ipc, --probe-services, --probe-fs host probes
|
||||
// --probe-discord the Rich Presence IPC exchange; skips without a Discord client; no game files
|
||||
// --probe-coop the co-op codec, two sessions through a relay on 127.0.0.1 (NX2NAVI_COOP_RELAY, else its own); no game files
|
||||
// --probe-dpi the process DPI awareness (per-monitor v2) and the primary monitor's size; no game files
|
||||
// --probe-gfx-abi NVN object layouts against nvn.h's reserved sizes; needs no game files
|
||||
// --probe-nvn, --probe-nvn-tex, --probe-window, --probe-shader, --probe-vkmem, --probe-vkexec graphics probes
|
||||
@@ -42,6 +43,8 @@
|
||||
#include <string.h>
|
||||
|
||||
#include "cfg.h"
|
||||
#include "coop.h"
|
||||
#include "coop_game.h"
|
||||
#include "host.h"
|
||||
#include "logq.h"
|
||||
#include "prof.h"
|
||||
@@ -169,13 +172,13 @@ static void parse_trace(void) {
|
||||
static const struct { const char *name; unsigned bit; } names[] = {
|
||||
{"svc", RT_TRACE_SVC}, {"host", RT_TRACE_HOSTCALL}, {"ipc", RT_TRACE_IPC}, {"fs", RT_TRACE_FS},
|
||||
{"gfx", RT_TRACE_GFX}, {"perf", RT_TRACE_PERF}, {"sched", RT_TRACE_SCHED}, {"audio", RT_TRACE_AUDIO},
|
||||
{"present", RT_TRACE_PRESENT}, {"all", ~0u}};
|
||||
{"present", RT_TRACE_PRESENT}, {"coop", RT_TRACE_COOP}, {"all", ~0u}};
|
||||
for (const char *p = e; *p;) {
|
||||
size_t n = strcspn(p, ",");
|
||||
int known = 0;
|
||||
for (unsigned i = 0; i < sizeof names / sizeof *names; i++)
|
||||
if (strlen(names[i].name) == n && !strncmp(p, names[i].name, n)) rt_trace |= names[i].bit, known = 1;
|
||||
if (!known && n) rt_log("NX2NAVI_TRACE: unknown item '%.*s' (svc, host, ipc, fs, gfx, perf, sched, audio, present, all)", (int)n, p);
|
||||
if (!known && n) rt_log("NX2NAVI_TRACE: unknown item '%.*s' (svc, host, ipc, fs, gfx, perf, sched, audio, present, coop, all)", (int)n, p);
|
||||
p += n + (p[n] == ',');
|
||||
}
|
||||
}
|
||||
@@ -530,7 +533,7 @@ static int usage(const char *argv0) {
|
||||
fprintf(stderr, "usage: %s [--exefs DIR] [--romfs DIR] [--profile DIR] [--audio-device VALUE] [--monitor VALUE] [--list-audio-devices | --list-monitors | --selftest | --probe-loader | "
|
||||
"--probe-cfg | --probe-dpi | --probe-mods | --probe-kernel | --probe-ipc | --probe-services | --probe-fs | --probe-gfx-abi | "
|
||||
"--probe-nvn | --probe-nvn-tex | --probe-window | --probe-shader | --probe-vkmem | "
|
||||
"--probe-vkexec | --probe-astc | --probe-zstd | --probe-input | --probe-movie | --probe-crash-call | --probe-crash-null | --probe-discord | "
|
||||
"--probe-vkexec | --probe-astc | --probe-zstd | --probe-input | --probe-movie | --probe-crash-call | --probe-crash-null | --probe-discord | --probe-coop | "
|
||||
"--prepare-shaders | --warm-shaders | --prepare-pipelines | --probe-prewarm | --boot |--seconds S [--shot PNG]]\n", argv0);
|
||||
return 2;
|
||||
}
|
||||
@@ -649,6 +652,8 @@ int main(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_init(); // the co-op thread (coop.c); the same, idle while the COOP setting is off
|
||||
coop_game_init(); // progress sync's hooks on that thread and the game's frames (coop_game.c)
|
||||
rt_boot();
|
||||
return 0;
|
||||
}
|
||||
@@ -664,6 +669,7 @@ int main(int argc, char **argv) {
|
||||
#endif
|
||||
if (!strcmp(mode, "--probe-mods")) return probe_mods();
|
||||
if (!strcmp(mode, "--probe-discord")) return probe_discord();
|
||||
if (!strcmp(mode, "--probe-coop")) return probe_coop();
|
||||
if (!strcmp(mode, "--probe-kernel")) return probe_kernel();
|
||||
if (!strcmp(mode, "--probe-ipc")) return probe_ipc();
|
||||
if (!strcmp(mode, "--probe-services")) return probe_services();
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
#include "gfx.h"
|
||||
#include "cfg.h"
|
||||
#include "coop_game.h"
|
||||
#include "host.h"
|
||||
#include "nvn_api.h"
|
||||
#include "nvn_hmap.h"
|
||||
@@ -864,6 +865,7 @@ NVN_API(nvnQueuePresentTexture) {
|
||||
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
|
||||
wide_present(); // widescreen.c: Ocarina's DLSS render scale
|
||||
coop_present(c); // coop_game.c: co-op progress sync reads and sets the game's flags, between frames
|
||||
NVN_BLOCKING();
|
||||
if (o->magic != NVN_WIN_MAGIC || idx < 0 || idx >= o->ntex || idx >= 4 || !o->tex[idx])
|
||||
rt_fatal("nvn: QueuePresentTexture of image %d on window %p", idx, (void *)o);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// The parts of platform.h built on its locks rather than on the OS: recursive mutexes, one-time initialisation and
|
||||
// events. Every OS shares them.
|
||||
// events, and the network address helpers. Every OS shares them.
|
||||
#include "platform.h"
|
||||
#include <string.h>
|
||||
|
||||
// ---- recursive mutex: owner is the holder's thread id (0 when free); only the holder writes depth.
|
||||
|
||||
@@ -100,3 +101,61 @@ int plat_event_wait_ns(PlatEvent *e, uint64_t ns) {
|
||||
plat_mutex_unlock(&e->m);
|
||||
return got;
|
||||
}
|
||||
|
||||
// ---- network addresses: the OS-free part of platform.h's UDP sockets. Layout of PlatAddr.b: the IPv6 address at 0 (an
|
||||
// IPv4 one as ::ffff:a.b.c.d), the port big-endian at 16, the scope id little-endian at 18, zeros after.
|
||||
|
||||
void plat_addr_set(PlatAddr *a, const uint8_t ip[16], uint16_t port, uint32_t scope) {
|
||||
memset(a, 0, sizeof *a);
|
||||
memcpy(a->b, ip, 16);
|
||||
a->b[16] = (uint8_t)(port >> 8), a->b[17] = (uint8_t)port;
|
||||
for (int i = 0; i < 4; i++) a->b[18 + i] = (uint8_t)(scope >> (8 * i));
|
||||
}
|
||||
|
||||
void plat_addr_get(const PlatAddr *a, uint8_t ip[16], uint32_t *scope) {
|
||||
memcpy(ip, a->b, 16);
|
||||
if (scope) *scope = (uint32_t)a->b[18] | (uint32_t)a->b[19] << 8 | (uint32_t)a->b[20] << 16 | (uint32_t)a->b[21] << 24;
|
||||
}
|
||||
|
||||
uint16_t plat_addr_port(const PlatAddr *a) { return (uint16_t)(a->b[16] << 8 | a->b[17]); }
|
||||
|
||||
int plat_addr_eq(const PlatAddr *a, const PlatAddr *b) { return !memcmp(a, b, sizeof *a); }
|
||||
|
||||
static int addr_is_v4(const uint8_t *ip) {
|
||||
static const uint8_t mapped[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff};
|
||||
return !memcmp(ip, mapped, sizeof mapped);
|
||||
}
|
||||
|
||||
int plat_addr_str(const PlatAddr *a, char *out, size_t cap) {
|
||||
char s[96];
|
||||
int n;
|
||||
uint32_t scope;
|
||||
uint8_t ip[16];
|
||||
plat_addr_get(a, ip, &scope);
|
||||
if (addr_is_v4(ip)) {
|
||||
n = snprintf(s, sizeof s, "%u.%u.%u.%u:%u", ip[12], ip[13], ip[14], ip[15], plat_addr_port(a));
|
||||
} else {
|
||||
unsigned g[8];
|
||||
for (int i = 0; i < 8; i++) g[i] = (unsigned)ip[2 * i] << 8 | ip[2 * i + 1];
|
||||
int best = -1, best_len = 1; // the longest run of two or more zero groups becomes "::"
|
||||
for (int i = 0, run; i < 8; i += run ? run : 1) {
|
||||
run = 0;
|
||||
while (i + run < 8 && !g[i + run]) run++;
|
||||
if (run > best_len) best = i, best_len = run;
|
||||
}
|
||||
n = snprintf(s, sizeof s, "[");
|
||||
for (int i = 0; i < 8; i++) {
|
||||
if (i == best) {
|
||||
n += snprintf(s + n, sizeof s - (size_t)n, "::");
|
||||
i += best_len - 1;
|
||||
continue;
|
||||
}
|
||||
n += snprintf(s + n, sizeof s - (size_t)n, "%s%x", i && i != best + best_len ? ":" : "", g[i]);
|
||||
}
|
||||
if (scope) n += snprintf(s + n, sizeof s - (size_t)n, "%%%u", scope);
|
||||
n += snprintf(s + n, sizeof s - (size_t)n, "]:%u", plat_addr_port(a));
|
||||
}
|
||||
if (n <= 0 || (size_t)n >= sizeof s || (size_t)n >= cap) return 0;
|
||||
memcpy(out, s, (size_t)n + 1);
|
||||
return n;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
#include <linux/fs.h>
|
||||
#include <linux/futex.h>
|
||||
#include <linux/userfaultfd.h>
|
||||
#include <netdb.h>
|
||||
#include <netinet/in.h>
|
||||
#include <poll.h>
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
@@ -1072,6 +1074,12 @@ int plat_file_set_readonly(const char *path, int on) {
|
||||
return chmod(path, m & 07777) == 0;
|
||||
}
|
||||
|
||||
int plat_file_private(const char *path) {
|
||||
struct stat st;
|
||||
if (stat(path, &st)) return 0;
|
||||
return chmod(path, S_ISDIR(st.st_mode) ? 0700 : 0600) == 0;
|
||||
}
|
||||
|
||||
int plat_file_list(const char *dir, const char *ext, int (*cb)(const char *name, void *ctx), void *ctx) {
|
||||
DIR *d = opendir(dir);
|
||||
if (!d) return 0;
|
||||
@@ -1828,6 +1836,22 @@ int plat_random(void *out, size_t n) {
|
||||
|
||||
int plat_clipboard_set(const char *utf8) { return SDL_SetClipboardText(utf8); }
|
||||
|
||||
int plat_clipboard_get(char *out, size_t cap) {
|
||||
if (!cap) return 0;
|
||||
out[0] = 0;
|
||||
char *t = SDL_GetClipboardText(); // "" when there is none, never NULL but on failure
|
||||
if (!t) return 0;
|
||||
size_t n = strlen(t);
|
||||
if (n >= cap) { // cut where a character starts, not inside one
|
||||
n = cap - 1;
|
||||
while (n && ((unsigned char)t[n] & 0xc0) == 0x80) n--;
|
||||
}
|
||||
memcpy(out, t, n);
|
||||
out[n] = 0;
|
||||
SDL_free(t);
|
||||
return n != 0;
|
||||
}
|
||||
|
||||
static void reap_main(void *arg) {
|
||||
waitpid((pid_t)(intptr_t)arg, NULL, 0);
|
||||
}
|
||||
@@ -2358,6 +2382,142 @@ void plat_ipc_close(PlatIpc *p) {
|
||||
free(p);
|
||||
}
|
||||
|
||||
// ---- UDP sockets (platform.h): the co-op layer's transport
|
||||
struct PlatUdp { int fd, v6; };
|
||||
|
||||
static void addr_from_sockaddr(PlatAddr *out, const struct sockaddr_storage *ss) {
|
||||
uint8_t ip[16] = {0};
|
||||
if (ss->ss_family == AF_INET6) {
|
||||
const struct sockaddr_in6 *a = (const struct sockaddr_in6 *)ss;
|
||||
memcpy(ip, &a->sin6_addr, 16);
|
||||
plat_addr_set(out, ip, ntohs(a->sin6_port), a->sin6_scope_id);
|
||||
} else {
|
||||
const struct sockaddr_in *a = (const struct sockaddr_in *)ss;
|
||||
ip[10] = ip[11] = 0xff;
|
||||
memcpy(ip + 12, &a->sin_addr, 4);
|
||||
plat_addr_set(out, ip, ntohs(a->sin_port), 0);
|
||||
}
|
||||
}
|
||||
|
||||
// The socket address of a for a socket of family v6 (1: AF_INET6, 0: AF_INET); 0 when an IPv4 socket cannot reach it.
|
||||
static int addr_to_sockaddr(const PlatAddr *a, int v6, struct sockaddr_storage *ss, socklen_t *len) {
|
||||
uint8_t ip[16];
|
||||
uint32_t scope;
|
||||
plat_addr_get(a, ip, &scope);
|
||||
memset(ss, 0, sizeof *ss);
|
||||
if (v6) {
|
||||
struct sockaddr_in6 *s = (struct sockaddr_in6 *)ss;
|
||||
s->sin6_family = AF_INET6;
|
||||
s->sin6_port = htons(plat_addr_port(a));
|
||||
s->sin6_scope_id = scope;
|
||||
memcpy(&s->sin6_addr, ip, 16);
|
||||
*len = sizeof *s;
|
||||
return 1;
|
||||
}
|
||||
static const uint8_t mapped[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff};
|
||||
if (memcmp(ip, mapped, sizeof mapped)) return 0;
|
||||
struct sockaddr_in *s = (struct sockaddr_in *)ss;
|
||||
s->sin_family = AF_INET;
|
||||
s->sin_port = htons(plat_addr_port(a));
|
||||
memcpy(&s->sin_addr, ip + 12, 4);
|
||||
*len = sizeof *s;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int plat_net_resolve(const char *host, uint16_t port, PlatAddr *out) {
|
||||
struct addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM}, *res = NULL, *pick = NULL;
|
||||
if (!host || !*host || getaddrinfo(host, NULL, &hints, &res) != 0) return 0;
|
||||
for (struct addrinfo *r = res; r; r = r->ai_next) {
|
||||
if (r->ai_addrlen > sizeof(struct sockaddr_storage) || (r->ai_family != AF_INET && r->ai_family != AF_INET6)) continue;
|
||||
if (!pick || (r->ai_family == AF_INET && pick->ai_family != AF_INET)) pick = r; // IPv4 first
|
||||
}
|
||||
int ok = pick != NULL;
|
||||
if (ok) {
|
||||
struct sockaddr_storage ss;
|
||||
memset(&ss, 0, sizeof ss);
|
||||
memcpy(&ss, pick->ai_addr, pick->ai_addrlen);
|
||||
addr_from_sockaddr(out, &ss);
|
||||
uint8_t ip[16];
|
||||
uint32_t scope;
|
||||
plat_addr_get(out, ip, &scope);
|
||||
plat_addr_set(out, ip, port, scope);
|
||||
}
|
||||
freeaddrinfo(res);
|
||||
return ok;
|
||||
}
|
||||
|
||||
PlatUdp *plat_udp_open(uint16_t port, int dual_stack) {
|
||||
int v6 = dual_stack;
|
||||
int fd = v6 ? socket(AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0) : -1;
|
||||
if (fd >= 0) {
|
||||
int off = 0;
|
||||
setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &off, sizeof off);
|
||||
struct sockaddr_in6 a = {.sin6_family = AF_INET6, .sin6_addr = in6addr_any, .sin6_port = htons(port)};
|
||||
if (bind(fd, (struct sockaddr *)&a, sizeof a) != 0) close(fd), fd = -1;
|
||||
}
|
||||
if (fd < 0) { // IPv4 only, asked for or all the machine has
|
||||
v6 = 0;
|
||||
fd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
|
||||
if (fd < 0) return NULL;
|
||||
struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons(port)};
|
||||
a.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
if (bind(fd, (struct sockaddr *)&a, sizeof a) != 0) {
|
||||
close(fd);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
PlatUdp *u = malloc(sizeof *u);
|
||||
if (!u) {
|
||||
close(fd);
|
||||
return NULL;
|
||||
}
|
||||
u->fd = fd, u->v6 = v6;
|
||||
return u;
|
||||
}
|
||||
|
||||
uint16_t plat_udp_port(const PlatUdp *u) {
|
||||
struct sockaddr_storage ss;
|
||||
socklen_t len = sizeof ss;
|
||||
if (!u || getsockname(u->fd, (struct sockaddr *)&ss, &len) != 0) return 0;
|
||||
PlatAddr a;
|
||||
addr_from_sockaddr(&a, &ss);
|
||||
return plat_addr_port(&a);
|
||||
}
|
||||
|
||||
int plat_udp_send(PlatUdp *u, const PlatAddr *to, const void *p, size_t n) {
|
||||
struct sockaddr_storage ss;
|
||||
socklen_t len;
|
||||
if (!u || !addr_to_sockaddr(to, u->v6, &ss, &len)) return 0;
|
||||
for (;;) {
|
||||
ssize_t k = sendto(u->fd, p, n, MSG_NOSIGNAL, (struct sockaddr *)&ss, len);
|
||||
if (k >= 0) return 1;
|
||||
if (errno == EINTR) continue;
|
||||
// a full buffer, a missing route or an ICMP error is a lost datagram; a datagram too long or a socket that is not
|
||||
// ours to use can never be sent
|
||||
return errno != EMSGSIZE && errno != EBADF && errno != EINVAL && errno != EAFNOSUPPORT && errno != ENOTSOCK;
|
||||
}
|
||||
}
|
||||
|
||||
int plat_udp_recv(PlatUdp *u, void *buf, size_t cap, PlatAddr *from, uint32_t ms) {
|
||||
if (!u) return -1;
|
||||
struct pollfd pf = {.fd = u->fd, .events = POLLIN};
|
||||
int r = poll(&pf, 1, ms > (uint32_t)INT32_MAX ? INT32_MAX : (int)ms);
|
||||
if (r < 0) return errno == EINTR ? 0 : -1;
|
||||
if (r == 0) return 0;
|
||||
struct sockaddr_storage ss;
|
||||
socklen_t len = sizeof ss;
|
||||
ssize_t k = recvfrom(u->fd, buf, cap, MSG_DONTWAIT, (struct sockaddr *)&ss, &len);
|
||||
if (k < 0) return errno == EAGAIN || errno == EINTR || errno == ECONNREFUSED || errno == EHOSTUNREACH ? 0 : -1;
|
||||
if (from) addr_from_sockaddr(from, &ss);
|
||||
return (int)k;
|
||||
}
|
||||
|
||||
void plat_udp_close(PlatUdp *u) {
|
||||
if (!u) return;
|
||||
close(u->fd);
|
||||
free(u);
|
||||
}
|
||||
|
||||
|
||||
// ---- restart
|
||||
// NX2NAVI_RESTART_WAIT names the process that called plat_restart, as its id and start time (field 22 of /proc/<pid>/stat,
|
||||
|
||||
@@ -359,6 +359,7 @@ void plat_file_delete(const char *path);
|
||||
int plat_file_truncate(const char *path, uint64_t size); // 1 on success
|
||||
int64_t plat_file_size(const char *path); // bytes of a file, -1 when missing or unreadable
|
||||
int plat_file_set_readonly(const char *path, int on); // sets or clears the read-only attribute; 1 on success
|
||||
int plat_file_private(const char *path); // only this account may read it (0600, a folder 0700); 1 on success
|
||||
// A file that only grows and other processes may read meanwhile: each write lands whole at its end, from any thread,
|
||||
// and reaches the file even if the process dies right after (no user-space buffer, no flush to the disk).
|
||||
typedef struct PlatAppend PlatAppend;
|
||||
@@ -447,8 +448,12 @@ int plat_is_wine(void); // 1 when the Windows
|
||||
// The file the process's stderr (the log) goes to, as a UTF-8 path; 0 when stderr is not a file (a console, a pipe).
|
||||
int plat_stderr_path(char *out, size_t cap);
|
||||
|
||||
// ---- desktop: the in-game menu's "Copy system info" and "Open log folder"
|
||||
// ---- desktop: the in-game menu's "Copy system info", "Open log folder" and the Co-op tab's secret
|
||||
int plat_clipboard_set(const char *utf8); // replaces the clipboard's text; 1 on success
|
||||
// The clipboard's text as UTF-8 in out (cap bytes with the NUL; a longer text: "" on Windows, cut at a character
|
||||
// elsewhere); 1 when it had text. With SDL only on the window thread, as SDL asks: the menu goes through
|
||||
// gfx_window_paste (ui/menu.h).
|
||||
int plat_clipboard_get(char *out, size_t cap);
|
||||
int plat_open_folder(const char *path); // shows the folder in the file manager; 1 on success
|
||||
|
||||
// ---- dynamic libraries: a library some machines lack (a GPU vendor's), loaded at run time. A bare name is searched
|
||||
@@ -519,6 +524,34 @@ int plat_ipc_read(PlatIpc *p, void *buf, size_t n, uint32_t ms);
|
||||
int plat_ipc_write(PlatIpc *p, const void *buf, size_t n); // 1 when all n bytes were written, 0 the connection broke
|
||||
void plat_ipc_close(PlatIpc *p);
|
||||
|
||||
// ---- UDP sockets: the co-op layer's transport (coop.c). One unconnected datagram socket per PlatUdp; who a datagram
|
||||
// came from is checked by the protocol, not by the OS. On Windows the first call of any of these starts Winsock.
|
||||
// A PlatAddr is an IPv6 address (an IPv4 one as ::ffff:a.b.c.d), the port and the scope id in the same layout on every
|
||||
// OS, so two equal addresses compare equal bytewise (plat_addr_eq) whichever way the OS reported them.
|
||||
typedef struct PlatUdp PlatUdp;
|
||||
typedef struct { uint8_t b[32]; } PlatAddr;
|
||||
// host (a name, or an IPv4 or IPv6 literal without brackets) and port into *out. Blocks while the resolver runs: call
|
||||
// it on a thread that may wait, never on the game's. An IPv4 answer is preferred over an IPv6 one. 1 on success.
|
||||
int plat_net_resolve(const char *host, uint16_t port, PlatAddr *out);
|
||||
// A non-blocking UDP socket bound to port (0: any free port) on every local address. dual_stack 1: IPv6 with IPv4 in the
|
||||
// same socket (IPv4 alone where the machine has no IPv6); 0: IPv4 only. NULL on failure.
|
||||
PlatUdp *plat_udp_open(uint16_t port, int dual_stack);
|
||||
uint16_t plat_udp_port(const PlatUdp *u); // the port it is bound to; 0 on failure
|
||||
// One datagram to *to; never blocks. 1 when it was sent or the OS dropped it (a full send buffer, no route, an ICMP
|
||||
// error: a datagram may be lost anyway), 0 when it can never be sent (too long, an address the socket cannot reach).
|
||||
int plat_udp_send(PlatUdp *u, const PlatAddr *to, const void *p, size_t n);
|
||||
// The next datagram into buf, waiting at most ms for it; *from (may be NULL) gets its sender. Bytes received (a datagram
|
||||
// longer than cap is cut to cap), 0 when none came in time, -1 when the socket is unusable.
|
||||
int plat_udp_recv(PlatUdp *u, void *buf, size_t cap, PlatAddr *from, uint32_t ms);
|
||||
void plat_udp_close(PlatUdp *u);
|
||||
// Address helpers that need no OS (common.c); the back ends build addresses with plat_addr_set.
|
||||
void plat_addr_set(PlatAddr *a, const uint8_t ip[16], uint16_t port, uint32_t scope);
|
||||
void plat_addr_get(const PlatAddr *a, uint8_t ip[16], uint32_t *scope);
|
||||
uint16_t plat_addr_port(const PlatAddr *a);
|
||||
int plat_addr_eq(const PlatAddr *a, const PlatAddr *b);
|
||||
// "1.2.3.4:5" or "[::1]:5" ("%scope" after a link-local address) into out; its length, 0 when it does not fit cap.
|
||||
int plat_addr_str(const PlatAddr *a, char *out, size_t cap);
|
||||
|
||||
// ---- restart: this program again, in a new process that starts once this one is gone
|
||||
// Starts this executable again with the same command line, environment and working folder, and no handle of this
|
||||
// process. 1 when it started; the caller then exits.
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
// Windows implementation of platform.h: CreateThread, QueryPerformanceCounter, high-resolution waitable timers,
|
||||
// SRW locks and condition variables.
|
||||
#include <io.h>
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <winsock2.h> // before windows.h, which would otherwise pull in the old winsock.h
|
||||
#include <ws2tcpip.h>
|
||||
#include <windows.h>
|
||||
#include <aclapi.h> // SetNamedSecurityInfoW (plat_file_private)
|
||||
#include <bcrypt.h>
|
||||
#include <pdh.h>
|
||||
#include <pdhmsg.h>
|
||||
@@ -753,6 +757,27 @@ int plat_file_set_readonly(const char *path, int on) {
|
||||
return SetFileAttributesW(w, on ? a | FILE_ATTRIBUTE_READONLY : a & ~(DWORD)FILE_ATTRIBUTE_READONLY) != 0;
|
||||
}
|
||||
|
||||
// The file or folder gets an access list of its own with one entry, full control for the account the game runs as,
|
||||
// and inherits none from its folder: a game folder outside the user's own folders is often readable by every account
|
||||
// of the PC. Administrators can still take ownership, as on any file.
|
||||
int plat_file_private(const char *path) {
|
||||
wchar_t w[WPATH];
|
||||
if (!widen(path, w, WPATH) || GetFileAttributesW(w) == INVALID_FILE_ATTRIBUTES) return 0;
|
||||
HANDLE tok = NULL;
|
||||
union { TOKEN_USER u; BYTE raw[sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE]; } user;
|
||||
DWORD got = 0;
|
||||
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &tok)) return 0;
|
||||
BOOL have = GetTokenInformation(tok, TokenUser, &user, sizeof user, &got);
|
||||
CloseHandle(tok);
|
||||
if (!have) return 0;
|
||||
union { ACL acl; BYTE raw[sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + SECURITY_MAX_SID_SIZE]; } list;
|
||||
if (!InitializeAcl(&list.acl, sizeof list, ACL_REVISION) ||
|
||||
!AddAccessAllowedAceEx(&list.acl, ACL_REVISION, OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE, GENERIC_ALL, user.u.User.Sid))
|
||||
return 0;
|
||||
return SetNamedSecurityInfoW(w, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, NULL,
|
||||
NULL, &list.acl, NULL) == ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
int plat_file_list(const char *dir, const char *ext, int (*cb)(const char *name, void *ctx), void *ctx) {
|
||||
wchar_t wd[WPATH], we[64], pat[WPATH + 64];
|
||||
if (!widen(dir, wd, WPATH) || !widen(ext, we, 64)) return 0;
|
||||
@@ -1690,6 +1715,19 @@ int plat_clipboard_set(const char *utf8) {
|
||||
return ok;
|
||||
}
|
||||
|
||||
int plat_clipboard_get(char *out, size_t cap) {
|
||||
if (!cap) return 0;
|
||||
out[0] = 0;
|
||||
if (!OpenClipboard(NULL)) return 0; // reading needs no owner window
|
||||
HANDLE h = GetClipboardData(CF_UNICODETEXT);
|
||||
const wchar_t *w = h ? GlobalLock(h) : NULL;
|
||||
int n = w ? WideCharToMultiByte(CP_UTF8, 0, w, -1, out, (int)cap, NULL, NULL) : 0; // 0 when it does not fit
|
||||
if (w) GlobalUnlock(h);
|
||||
CloseClipboard();
|
||||
if (n <= 0) out[0] = 0;
|
||||
return out[0] != 0;
|
||||
}
|
||||
|
||||
static DWORD WINAPI open_folder_main(void *arg) {
|
||||
ShellExecuteW(NULL, L"open", arg, NULL, NULL, SW_SHOWNORMAL);
|
||||
free(arg);
|
||||
@@ -2100,6 +2138,194 @@ void plat_ipc_close(PlatIpc *p) {
|
||||
free(p);
|
||||
}
|
||||
|
||||
// ---- UDP sockets (platform.h): the co-op layer's transport. Winsock starts at the first call that needs it.
|
||||
#ifndef SIO_UDP_CONNRESET
|
||||
#define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR, 12)
|
||||
#endif
|
||||
#ifndef WSA_FLAG_NO_HANDLE_INHERIT
|
||||
#define WSA_FLAG_NO_HANDLE_INHERIT 0x80
|
||||
#endif
|
||||
|
||||
struct PlatUdp { SOCKET s; int v6; };
|
||||
|
||||
static PlatOnce wsa_once = PLAT_ONCE_INIT;
|
||||
static int wsa_ok;
|
||||
|
||||
static void wsa_start(void *arg) {
|
||||
WSADATA d;
|
||||
(void)arg;
|
||||
wsa_ok = WSAStartup(MAKEWORD(2, 2), &d) == 0;
|
||||
}
|
||||
|
||||
static int net_ready(void) {
|
||||
plat_once(&wsa_once, wsa_start, NULL);
|
||||
return wsa_ok;
|
||||
}
|
||||
|
||||
static void addr_from_sockaddr(PlatAddr *out, const SOCKADDR_STORAGE *ss) {
|
||||
uint8_t ip[16] = {0};
|
||||
if (ss->ss_family == AF_INET6) {
|
||||
const SOCKADDR_IN6 *a = (const SOCKADDR_IN6 *)ss;
|
||||
memcpy(ip, &a->sin6_addr, 16);
|
||||
plat_addr_set(out, ip, ntohs(a->sin6_port), a->sin6_scope_id);
|
||||
} else {
|
||||
const SOCKADDR_IN *a = (const SOCKADDR_IN *)ss;
|
||||
ip[10] = ip[11] = 0xff;
|
||||
memcpy(ip + 12, &a->sin_addr, 4);
|
||||
plat_addr_set(out, ip, ntohs(a->sin_port), 0);
|
||||
}
|
||||
}
|
||||
|
||||
// The socket address of a for a socket of family v6 (1: AF_INET6, 0: AF_INET); 0 when an IPv4 socket cannot reach it.
|
||||
static int addr_to_sockaddr(const PlatAddr *a, int v6, SOCKADDR_STORAGE *ss, int *len) {
|
||||
uint8_t ip[16];
|
||||
uint32_t scope;
|
||||
plat_addr_get(a, ip, &scope);
|
||||
memset(ss, 0, sizeof *ss);
|
||||
if (v6) {
|
||||
SOCKADDR_IN6 *s = (SOCKADDR_IN6 *)ss;
|
||||
s->sin6_family = AF_INET6;
|
||||
s->sin6_port = htons(plat_addr_port(a));
|
||||
s->sin6_scope_id = scope;
|
||||
memcpy(&s->sin6_addr, ip, 16);
|
||||
*len = (int)sizeof *s;
|
||||
return 1;
|
||||
}
|
||||
static const uint8_t mapped[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff};
|
||||
if (memcmp(ip, mapped, sizeof mapped)) return 0;
|
||||
SOCKADDR_IN *s = (SOCKADDR_IN *)ss;
|
||||
s->sin_family = AF_INET;
|
||||
s->sin_port = htons(plat_addr_port(a));
|
||||
memcpy(&s->sin_addr, ip + 12, 4);
|
||||
*len = (int)sizeof *s;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int plat_net_resolve(const char *host, uint16_t port, PlatAddr *out) {
|
||||
wchar_t whost[256];
|
||||
if (!host || !*host || !net_ready() || !widen(host, whost, 256)) return 0;
|
||||
ADDRINFOW hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM}, *res = NULL, *pick = NULL;
|
||||
if (GetAddrInfoW(whost, NULL, &hints, &res) != 0) return 0;
|
||||
for (ADDRINFOW *r = res; r; r = r->ai_next) {
|
||||
if (r->ai_addrlen > sizeof(SOCKADDR_STORAGE) || (r->ai_family != AF_INET && r->ai_family != AF_INET6)) continue;
|
||||
if (!pick || (r->ai_family == AF_INET && pick->ai_family != AF_INET)) pick = r; // IPv4 first
|
||||
}
|
||||
int ok = pick != NULL;
|
||||
if (ok) {
|
||||
SOCKADDR_STORAGE ss;
|
||||
memset(&ss, 0, sizeof ss);
|
||||
memcpy(&ss, pick->ai_addr, pick->ai_addrlen);
|
||||
addr_from_sockaddr(out, &ss);
|
||||
uint8_t ip[16];
|
||||
uint32_t scope;
|
||||
plat_addr_get(out, ip, &scope);
|
||||
plat_addr_set(out, ip, port, scope);
|
||||
}
|
||||
FreeAddrInfoW(res);
|
||||
return ok;
|
||||
}
|
||||
|
||||
// A non-blocking UDP socket of family af that no child process inherits, with Windows' report of an ICMP port-unreachable
|
||||
// as a failed receive (WSAECONNRESET on an unconnected socket) switched off: a peer that is gone is not an error here.
|
||||
static SOCKET udp_socket(int af) {
|
||||
SOCKET s = WSASocketW(af, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT);
|
||||
if (s == INVALID_SOCKET) return s;
|
||||
u_long nonblocking = 1;
|
||||
BOOL report = FALSE;
|
||||
DWORD got = 0;
|
||||
if (ioctlsocket(s, FIONBIO, &nonblocking) != 0) {
|
||||
closesocket(s);
|
||||
return INVALID_SOCKET;
|
||||
}
|
||||
WSAIoctl(s, SIO_UDP_CONNRESET, &report, sizeof report, NULL, 0, &got, NULL, NULL);
|
||||
return s;
|
||||
}
|
||||
|
||||
PlatUdp *plat_udp_open(uint16_t port, int dual_stack) {
|
||||
if (!net_ready()) return NULL;
|
||||
int v6 = dual_stack;
|
||||
SOCKET s = v6 ? udp_socket(AF_INET6) : INVALID_SOCKET;
|
||||
if (s != INVALID_SOCKET) {
|
||||
DWORD only_v6 = 0; // Windows defaults to IPv6 only
|
||||
setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, (const char *)&only_v6, sizeof only_v6);
|
||||
SOCKADDR_IN6 a;
|
||||
memset(&a, 0, sizeof a); // in6addr_any
|
||||
a.sin6_family = AF_INET6;
|
||||
a.sin6_port = htons(port);
|
||||
if (bind(s, (SOCKADDR *)&a, sizeof a) != 0) closesocket(s), s = INVALID_SOCKET;
|
||||
}
|
||||
if (s == INVALID_SOCKET) { // IPv4 only, asked for or all the machine has
|
||||
v6 = 0;
|
||||
s = udp_socket(AF_INET);
|
||||
if (s == INVALID_SOCKET) return NULL;
|
||||
SOCKADDR_IN a;
|
||||
memset(&a, 0, sizeof a);
|
||||
a.sin_family = AF_INET;
|
||||
a.sin_port = htons(port);
|
||||
a.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
if (bind(s, (SOCKADDR *)&a, sizeof a) != 0) {
|
||||
closesocket(s);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
PlatUdp *u = malloc(sizeof *u);
|
||||
if (!u) {
|
||||
closesocket(s);
|
||||
return NULL;
|
||||
}
|
||||
u->s = s, u->v6 = v6;
|
||||
return u;
|
||||
}
|
||||
|
||||
uint16_t plat_udp_port(const PlatUdp *u) {
|
||||
SOCKADDR_STORAGE ss;
|
||||
int len = (int)sizeof ss;
|
||||
if (!u || getsockname(u->s, (SOCKADDR *)&ss, &len) != 0) return 0;
|
||||
PlatAddr a;
|
||||
addr_from_sockaddr(&a, &ss);
|
||||
return plat_addr_port(&a);
|
||||
}
|
||||
|
||||
int plat_udp_send(PlatUdp *u, const PlatAddr *to, const void *p, size_t n) {
|
||||
SOCKADDR_STORAGE ss;
|
||||
int len;
|
||||
if (!u || n > 65507 || !addr_to_sockaddr(to, u->v6, &ss, &len)) return 0;
|
||||
if (sendto(u->s, (const char *)p, (int)n, 0, (SOCKADDR *)&ss, len) != SOCKET_ERROR) return 1;
|
||||
// a full buffer, a missing route or an ICMP error is a lost datagram; a datagram too long or a socket that is not
|
||||
// ours to use can never be sent
|
||||
int e = WSAGetLastError();
|
||||
return e != WSAEMSGSIZE && e != WSAENOTSOCK && e != WSAEINVAL && e != WSAEAFNOSUPPORT;
|
||||
}
|
||||
|
||||
int plat_udp_recv(PlatUdp *u, void *buf, size_t cap, PlatAddr *from, uint32_t ms) {
|
||||
if (!u) return -1;
|
||||
WSAPOLLFD pf = {.fd = u->s, .events = POLLRDNORM};
|
||||
int r = WSAPoll(&pf, 1, ms > (uint32_t)INT_MAX ? INT_MAX : (int)ms);
|
||||
if (r == SOCKET_ERROR) return WSAGetLastError() == WSAEINTR ? 0 : -1;
|
||||
if (r == 0) return 0;
|
||||
SOCKADDR_STORAGE ss;
|
||||
int len = (int)sizeof ss;
|
||||
int k = recvfrom(u->s, (char *)buf, cap > (size_t)INT_MAX ? INT_MAX : (int)cap, 0, (SOCKADDR *)&ss, &len);
|
||||
if (k == SOCKET_ERROR) {
|
||||
int e = WSAGetLastError();
|
||||
if (e == WSAEMSGSIZE) { // longer than buf: Windows reports it as an error but has filled buf
|
||||
k = cap > (size_t)INT_MAX ? INT_MAX : (int)cap;
|
||||
} else {
|
||||
return e == WSAEWOULDBLOCK || e == WSAEINTR || e == WSAECONNRESET || e == WSAENETRESET || e == WSAEHOSTUNREACH ||
|
||||
e == WSAENETUNREACH
|
||||
? 0 : -1;
|
||||
}
|
||||
}
|
||||
if (from) addr_from_sockaddr(from, &ss);
|
||||
return k;
|
||||
}
|
||||
|
||||
void plat_udp_close(PlatUdp *u) {
|
||||
if (!u) return;
|
||||
closesocket(u->s);
|
||||
free(u);
|
||||
}
|
||||
|
||||
|
||||
// ---- restart
|
||||
// NX2NAVI_RESTART_WAIT names the process that called plat_restart, as its id and creation time: a process that has only
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "cfg_private.h"
|
||||
#include "folder_pick.h"
|
||||
#include "fs.h"
|
||||
#include "host.h"
|
||||
@@ -118,6 +119,19 @@ static void add_file(Export *e, const char *name, const char *path) {
|
||||
free(data);
|
||||
}
|
||||
|
||||
// nx2navi.ini for a bug report: as it is, except that the values of the private settings (cfg_private.h: a co-op
|
||||
// room's secret, the relay, the player's name) read "(set, not shown)". A report goes to people the player does not
|
||||
// know, and the secret lets anyone into the room.
|
||||
static void add_settings_file(Export *e, const char *name, const char *path) {
|
||||
uint64_t n = 0;
|
||||
uint8_t *data = plat_file_read(path, &n);
|
||||
size_t sn = 0;
|
||||
char *scrubbed = data ? cfg_ini_scrub((const char *)data, (size_t)n, &sn) : NULL;
|
||||
if (scrubbed) sz_writer_add(&e->w, name, scrubbed, sn);
|
||||
free(scrubbed);
|
||||
free(data);
|
||||
}
|
||||
|
||||
SaveShareResult save_share_export(const char *dir, int bug_report, char *path, size_t cap) {
|
||||
*path = 0;
|
||||
struct tm t;
|
||||
@@ -137,7 +151,7 @@ SaveShareResult save_share_export(const char *dir, int bug_report, char *path, s
|
||||
add_file(&e, "bug-report/nx2navi.log", rt_log_path());
|
||||
if (exe_dir(base, sizeof base)) {
|
||||
snprintf(file, sizeof file, "%s/nx2navi.ini", base);
|
||||
add_file(&e, "bug-report/nx2navi.ini", file);
|
||||
add_settings_file(&e, "bug-report/nx2navi.ini", file);
|
||||
}
|
||||
}
|
||||
struct tm u;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "coop.h"
|
||||
#include "fs.h"
|
||||
#include "host.h"
|
||||
#include "kernel.h"
|
||||
@@ -243,6 +244,7 @@ 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(); // LEAVE and BYE to 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_pipeline_save();
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#endif
|
||||
|
||||
#include "cfg.h"
|
||||
#include "cfg_private.h"
|
||||
#include "host.h"
|
||||
#include "platform/platform.h"
|
||||
#include "sysinfo.h"
|
||||
@@ -52,7 +53,12 @@ static void put(Out *o, const char *fmt, ...) {
|
||||
if (k > 0) o->at = o->at + (size_t)k < o->n ? o->at + (size_t)k : o->n - 1;
|
||||
}
|
||||
|
||||
// The co-op room's secret and the offer number made from it, the relay's address and the player's name stay out of a
|
||||
// text that ends up in bug reports: only whether they are set.
|
||||
static int private_setting(const char *key) { return cfg_private_key(key); } // cfg_private.h: one list for all
|
||||
|
||||
static void put_setting(const char *key, const char *value, int from_env, void *ctx) {
|
||||
if (private_setting(key)) value = CFG_PRIVATE_SHOWN;
|
||||
put(ctx, from_env ? " NX2NAVI_%s=%s (environment)\n" : " %s = %s\n", key, value);
|
||||
}
|
||||
|
||||
|
||||
167
runtime/third_party/monocypher/LICENCE.md
vendored
Normal file
167
runtime/third_party/monocypher/LICENCE.md
vendored
Normal file
@@ -0,0 +1,167 @@
|
||||
Monocypher as a whole is dual-licensed. Choose whichever licence you
|
||||
want from the two licences listed below.
|
||||
|
||||
The first licence is a regular 2-clause BSD licence. The second licence
|
||||
is the CC-0 from Creative Commons. It is intended to release Monocypher
|
||||
to the public domain. The BSD licence serves as a fallback option.
|
||||
|
||||
See the individual files for specific information about who contributed
|
||||
to what file during which years. See below for special notes.
|
||||
|
||||
Licence 1 (2-clause BSD)
|
||||
------------------------
|
||||
|
||||
Copyright (c) 2017-2023, Loup Vaillant
|
||||
Copyright (c) 2017-2019, Michael Savage
|
||||
Copyright (c) 2017-2023, Fabio Scotoni
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the
|
||||
distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
Licence 2 (CC-0)
|
||||
----------------
|
||||
|
||||
> CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
|
||||
> LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
|
||||
> ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
|
||||
> INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
|
||||
> REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
|
||||
> PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
|
||||
> THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
|
||||
> HEREUNDER.
|
||||
|
||||
### Statement of Purpose
|
||||
|
||||
The laws of most jurisdictions throughout the world automatically confer
|
||||
exclusive Copyright and Related Rights (defined below) upon the creator
|
||||
and subsequent owner(s) (each and all, an "owner") of an original work
|
||||
of authorship and/or a database (each, a "Work").
|
||||
|
||||
Certain owners wish to permanently relinquish those rights to a Work for
|
||||
the purpose of contributing to a commons of creative, cultural and
|
||||
scientific works ("Commons") that the public can reliably and without
|
||||
fear of later claims of infringement build upon, modify, incorporate in
|
||||
other works, reuse and redistribute as freely as possible in any form
|
||||
whatsoever and for any purposes, including without limitation commercial
|
||||
purposes. These owners may contribute to the Commons to promote the
|
||||
ideal of a free culture and the further production of creative, cultural
|
||||
and scientific works, or to gain reputation or greater distribution for
|
||||
their Work in part through the use and efforts of others.
|
||||
|
||||
For these and/or other purposes and motivations, and without any
|
||||
expectation of additional consideration or compensation, the person
|
||||
associating CC0 with a Work (the "Affirmer"), to the extent that he or
|
||||
she is an owner of Copyright and Related Rights in the Work, voluntarily
|
||||
elects to apply CC0 to the Work and publicly distribute the Work under
|
||||
its terms, with knowledge of his or her Copyright and Related Rights in
|
||||
the Work and the meaning and intended legal effect of CC0 on those
|
||||
rights.
|
||||
|
||||
1. **Copyright and Related Rights.** A Work made available under CC0 may
|
||||
be protected by copyright and related or neighboring rights
|
||||
("Copyright and Related Rights"). Copyright and Related Rights
|
||||
include, but are not limited to, the following:
|
||||
|
||||
- the right to reproduce, adapt, distribute, perform, display,
|
||||
communicate, and translate a Work;
|
||||
- moral rights retained by the original author(s) and/or
|
||||
performer(s); publicity and privacy rights pertaining to a person's
|
||||
image or likeness depicted in a Work;
|
||||
- rights protecting against unfair competition in regards to a Work,
|
||||
subject to the limitations in paragraph 4(a), below;
|
||||
- rights protecting the extraction, dissemination, use and reuse of
|
||||
data in a Work;
|
||||
- database rights (such as those arising under Directive 96/9/EC of
|
||||
the European Parliament and of the Council of 11 March 1996 on the
|
||||
legal protection of databases, and under any national
|
||||
implementation thereof, including any amended or successor version
|
||||
of such directive); and
|
||||
- other similar, equivalent or corresponding rights throughout the
|
||||
world based on applicable law or treaty, and any national
|
||||
implementations thereof.
|
||||
|
||||
2. **Waiver.** To the greatest extent permitted by, but not in
|
||||
contravention of, applicable law, Affirmer hereby overtly, fully,
|
||||
permanently, irrevocably and unconditionally waives, abandons, and
|
||||
surrenders all of Affirmer's Copyright and Related Rights and
|
||||
associated claims and causes of action, whether now known or unknown
|
||||
(including existing as well as future claims and causes of action),
|
||||
in the Work (i) in all territories worldwide, (ii) for the maximum
|
||||
duration provided by applicable law or treaty (including future time
|
||||
extensions), (iii) in any current or future medium and for any number
|
||||
of copies, and (iv) for any purpose whatsoever, including without
|
||||
limitation commercial, advertising or promotional purposes (the
|
||||
"Waiver"). Affirmer makes the Waiver for the benefit of each member
|
||||
of the public at large and to the detriment of Affirmer's heirs and
|
||||
successors, fully intending that such Waiver shall not be subject to
|
||||
revocation, rescission, cancellation, termination, or any other legal
|
||||
or equitable action to disrupt the quiet enjoyment of the Work by the
|
||||
public as contemplated by Affirmer's express Statement of Purpose.
|
||||
|
||||
3. **Public License Fallback.** Should any part of the Waiver for any
|
||||
reason be judged legally invalid or ineffective under applicable law,
|
||||
then the Waiver shall be preserved to the maximum extent permitted
|
||||
taking into account Affirmer's express Statement of Purpose. In
|
||||
addition, to the extent the Waiver is so judged Affirmer hereby
|
||||
grants to each affected person a royalty-free, non transferable, non
|
||||
sublicensable, non exclusive, irrevocable and unconditional license
|
||||
to exercise Affirmer's Copyright and Related Rights in the Work (i)
|
||||
in all territories worldwide, (ii) for the maximum duration provided
|
||||
by applicable law or treaty (including future time extensions), (iii)
|
||||
in any current or future medium and for any number of copies, and
|
||||
(iv) for any purpose whatsoever, including without limitation
|
||||
commercial, advertising or promotional purposes (the "License"). The
|
||||
License shall be deemed effective as of the date CC0 was applied by
|
||||
Affirmer to the Work. Should any part of the License for any reason
|
||||
be judged legally invalid or ineffective under applicable law, such
|
||||
partial invalidity or ineffectiveness shall not invalidate the
|
||||
remainder of the License, and in such case Affirmer hereby affirms
|
||||
that he or she will not (i) exercise any of his or her remaining
|
||||
Copyright and Related Rights in the Work or (ii) assert any
|
||||
associated claims and causes of action with respect to the Work, in
|
||||
either case contrary to Affirmer's express Statement of Purpose.
|
||||
|
||||
4. **Limitations and Disclaimers.**
|
||||
|
||||
- No trademark or patent rights held by Affirmer are waived,
|
||||
abandoned, surrendered, licensed or otherwise affected by this
|
||||
document.
|
||||
- Affirmer offers the Work as-is and makes no representations or
|
||||
warranties of any kind concerning the Work, express, implied,
|
||||
statutory or otherwise, including without limitation warranties of
|
||||
title, merchantability, fitness for a particular purpose, non
|
||||
infringement, or the absence of latent or other defects, accuracy,
|
||||
or the present or absence of errors, whether or not discoverable,
|
||||
all to the greatest extent permissible under applicable law.
|
||||
- Affirmer disclaims responsibility for clearing rights of other
|
||||
persons that may apply to the Work or any use thereof, including
|
||||
without limitation any person's Copyright and Related Rights in the
|
||||
Work. Further, Affirmer disclaims responsibility for obtaining any
|
||||
necessary consents, permissions or other rights required for any
|
||||
use of the Work.
|
||||
- Affirmer understands and acknowledges that Creative Commons is not
|
||||
a party to this document and has no duty or obligation with respect
|
||||
to this CC0 or use of the Work.
|
||||
2956
runtime/third_party/monocypher/monocypher.c
vendored
Normal file
2956
runtime/third_party/monocypher/monocypher.c
vendored
Normal file
File diff suppressed because it is too large
Load Diff
321
runtime/third_party/monocypher/monocypher.h
vendored
Normal file
321
runtime/third_party/monocypher/monocypher.h
vendored
Normal file
@@ -0,0 +1,321 @@
|
||||
// Monocypher version 4.0.2
|
||||
//
|
||||
// This file is dual-licensed. Choose whichever licence you want from
|
||||
// the two licences listed below.
|
||||
//
|
||||
// The first licence is a regular 2-clause BSD licence. The second licence
|
||||
// is the CC-0 from Creative Commons. It is intended to release Monocypher
|
||||
// to the public domain. The BSD licence serves as a fallback option.
|
||||
//
|
||||
// SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0
|
||||
//
|
||||
// ------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright (c) 2017-2019, Loup Vaillant
|
||||
// All rights reserved.
|
||||
//
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// 1. Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
//
|
||||
// 2. Redistributions in binary form must reproduce the above copyright
|
||||
// notice, this list of conditions and the following disclaimer in the
|
||||
// documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// ------------------------------------------------------------------------
|
||||
//
|
||||
// Written in 2017-2019 by Loup Vaillant
|
||||
//
|
||||
// To the extent possible under law, the author(s) have dedicated all copyright
|
||||
// and related neighboring rights to this software to the public domain
|
||||
// worldwide. This software is distributed without any warranty.
|
||||
//
|
||||
// You should have received a copy of the CC0 Public Domain Dedication along
|
||||
// with this software. If not, see
|
||||
// <https://creativecommons.org/publicdomain/zero/1.0/>
|
||||
|
||||
#ifndef MONOCYPHER_H
|
||||
#define MONOCYPHER_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef MONOCYPHER_CPP_NAMESPACE
|
||||
namespace MONOCYPHER_CPP_NAMESPACE {
|
||||
#elif defined(__cplusplus)
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
// Constant time comparisons
|
||||
// -------------------------
|
||||
|
||||
// Return 0 if a and b are equal, -1 otherwise
|
||||
int crypto_verify16(const uint8_t a[16], const uint8_t b[16]);
|
||||
int crypto_verify32(const uint8_t a[32], const uint8_t b[32]);
|
||||
int crypto_verify64(const uint8_t a[64], const uint8_t b[64]);
|
||||
|
||||
|
||||
// Erase sensitive data
|
||||
// --------------------
|
||||
void crypto_wipe(void *secret, size_t size);
|
||||
|
||||
|
||||
// Authenticated encryption
|
||||
// ------------------------
|
||||
void crypto_aead_lock(uint8_t *cipher_text,
|
||||
uint8_t mac [16],
|
||||
const uint8_t key [32],
|
||||
const uint8_t nonce[24],
|
||||
const uint8_t *ad, size_t ad_size,
|
||||
const uint8_t *plain_text, size_t text_size);
|
||||
int crypto_aead_unlock(uint8_t *plain_text,
|
||||
const uint8_t mac [16],
|
||||
const uint8_t key [32],
|
||||
const uint8_t nonce[24],
|
||||
const uint8_t *ad, size_t ad_size,
|
||||
const uint8_t *cipher_text, size_t text_size);
|
||||
|
||||
// Authenticated stream
|
||||
// --------------------
|
||||
typedef struct {
|
||||
uint64_t counter;
|
||||
uint8_t key[32];
|
||||
uint8_t nonce[8];
|
||||
} crypto_aead_ctx;
|
||||
|
||||
void crypto_aead_init_x(crypto_aead_ctx *ctx,
|
||||
const uint8_t key[32], const uint8_t nonce[24]);
|
||||
void crypto_aead_init_djb(crypto_aead_ctx *ctx,
|
||||
const uint8_t key[32], const uint8_t nonce[8]);
|
||||
void crypto_aead_init_ietf(crypto_aead_ctx *ctx,
|
||||
const uint8_t key[32], const uint8_t nonce[12]);
|
||||
|
||||
void crypto_aead_write(crypto_aead_ctx *ctx,
|
||||
uint8_t *cipher_text,
|
||||
uint8_t mac[16],
|
||||
const uint8_t *ad , size_t ad_size,
|
||||
const uint8_t *plain_text, size_t text_size);
|
||||
int crypto_aead_read(crypto_aead_ctx *ctx,
|
||||
uint8_t *plain_text,
|
||||
const uint8_t mac[16],
|
||||
const uint8_t *ad , size_t ad_size,
|
||||
const uint8_t *cipher_text, size_t text_size);
|
||||
|
||||
|
||||
// General purpose hash (BLAKE2b)
|
||||
// ------------------------------
|
||||
|
||||
// Direct interface
|
||||
void crypto_blake2b(uint8_t *hash, size_t hash_size,
|
||||
const uint8_t *message, size_t message_size);
|
||||
|
||||
void crypto_blake2b_keyed(uint8_t *hash, size_t hash_size,
|
||||
const uint8_t *key, size_t key_size,
|
||||
const uint8_t *message, size_t message_size);
|
||||
|
||||
// Incremental interface
|
||||
typedef struct {
|
||||
// Do not rely on the size or contents of this type,
|
||||
// for they may change without notice.
|
||||
uint64_t hash[8];
|
||||
uint64_t input_offset[2];
|
||||
uint64_t input[16];
|
||||
size_t input_idx;
|
||||
size_t hash_size;
|
||||
} crypto_blake2b_ctx;
|
||||
|
||||
void crypto_blake2b_init(crypto_blake2b_ctx *ctx, size_t hash_size);
|
||||
void crypto_blake2b_keyed_init(crypto_blake2b_ctx *ctx, size_t hash_size,
|
||||
const uint8_t *key, size_t key_size);
|
||||
void crypto_blake2b_update(crypto_blake2b_ctx *ctx,
|
||||
const uint8_t *message, size_t message_size);
|
||||
void crypto_blake2b_final(crypto_blake2b_ctx *ctx, uint8_t *hash);
|
||||
|
||||
|
||||
// Password key derivation (Argon2)
|
||||
// --------------------------------
|
||||
#define CRYPTO_ARGON2_D 0
|
||||
#define CRYPTO_ARGON2_I 1
|
||||
#define CRYPTO_ARGON2_ID 2
|
||||
|
||||
typedef struct {
|
||||
uint32_t algorithm; // Argon2d, Argon2i, Argon2id
|
||||
uint32_t nb_blocks; // memory hardness, >= 8 * nb_lanes
|
||||
uint32_t nb_passes; // CPU hardness, >= 1 (>= 3 recommended for Argon2i)
|
||||
uint32_t nb_lanes; // parallelism level (single threaded anyway)
|
||||
} crypto_argon2_config;
|
||||
|
||||
typedef struct {
|
||||
const uint8_t *pass;
|
||||
const uint8_t *salt;
|
||||
uint32_t pass_size;
|
||||
uint32_t salt_size; // 16 bytes recommended
|
||||
} crypto_argon2_inputs;
|
||||
|
||||
typedef struct {
|
||||
const uint8_t *key; // may be NULL if no key
|
||||
const uint8_t *ad; // may be NULL if no additional data
|
||||
uint32_t key_size; // 0 if no key (32 bytes recommended otherwise)
|
||||
uint32_t ad_size; // 0 if no additional data
|
||||
} crypto_argon2_extras;
|
||||
|
||||
extern const crypto_argon2_extras crypto_argon2_no_extras;
|
||||
|
||||
void crypto_argon2(uint8_t *hash, uint32_t hash_size, void *work_area,
|
||||
crypto_argon2_config config,
|
||||
crypto_argon2_inputs inputs,
|
||||
crypto_argon2_extras extras);
|
||||
|
||||
|
||||
// Key exchange (X-25519)
|
||||
// ----------------------
|
||||
|
||||
// Shared secrets are not quite random.
|
||||
// Hash them to derive an actual shared key.
|
||||
void crypto_x25519_public_key(uint8_t public_key[32],
|
||||
const uint8_t secret_key[32]);
|
||||
void crypto_x25519(uint8_t raw_shared_secret[32],
|
||||
const uint8_t your_secret_key [32],
|
||||
const uint8_t their_public_key [32]);
|
||||
|
||||
// Conversion to EdDSA
|
||||
void crypto_x25519_to_eddsa(uint8_t eddsa[32], const uint8_t x25519[32]);
|
||||
|
||||
// scalar "division"
|
||||
// Used for OPRF. Be aware that exponential blinding is less secure
|
||||
// than Diffie-Hellman key exchange.
|
||||
void crypto_x25519_inverse(uint8_t blind_salt [32],
|
||||
const uint8_t private_key[32],
|
||||
const uint8_t curve_point[32]);
|
||||
|
||||
// "Dirty" versions of x25519_public_key().
|
||||
// Use with crypto_elligator_rev().
|
||||
// Leaks 3 bits of the private key.
|
||||
void crypto_x25519_dirty_small(uint8_t pk[32], const uint8_t sk[32]);
|
||||
void crypto_x25519_dirty_fast (uint8_t pk[32], const uint8_t sk[32]);
|
||||
|
||||
|
||||
// Signatures
|
||||
// ----------
|
||||
|
||||
// EdDSA with curve25519 + BLAKE2b
|
||||
void crypto_eddsa_key_pair(uint8_t secret_key[64],
|
||||
uint8_t public_key[32],
|
||||
uint8_t seed[32]);
|
||||
void crypto_eddsa_sign(uint8_t signature [64],
|
||||
const uint8_t secret_key[64],
|
||||
const uint8_t *message, size_t message_size);
|
||||
int crypto_eddsa_check(const uint8_t signature [64],
|
||||
const uint8_t public_key[32],
|
||||
const uint8_t *message, size_t message_size);
|
||||
|
||||
// Conversion to X25519
|
||||
void crypto_eddsa_to_x25519(uint8_t x25519[32], const uint8_t eddsa[32]);
|
||||
|
||||
// EdDSA building blocks
|
||||
void crypto_eddsa_trim_scalar(uint8_t out[32], const uint8_t in[32]);
|
||||
void crypto_eddsa_reduce(uint8_t reduced[32], const uint8_t expanded[64]);
|
||||
void crypto_eddsa_mul_add(uint8_t r[32],
|
||||
const uint8_t a[32],
|
||||
const uint8_t b[32],
|
||||
const uint8_t c[32]);
|
||||
void crypto_eddsa_scalarbase(uint8_t point[32], const uint8_t scalar[32]);
|
||||
int crypto_eddsa_check_equation(const uint8_t signature[64],
|
||||
const uint8_t public_key[32],
|
||||
const uint8_t h_ram[32]);
|
||||
|
||||
|
||||
// Chacha20
|
||||
// --------
|
||||
|
||||
// Specialised hash.
|
||||
// Used to hash X25519 shared secrets.
|
||||
void crypto_chacha20_h(uint8_t out[32],
|
||||
const uint8_t key[32],
|
||||
const uint8_t in [16]);
|
||||
|
||||
// Unauthenticated stream cipher.
|
||||
// Don't forget to add authentication.
|
||||
uint64_t crypto_chacha20_djb(uint8_t *cipher_text,
|
||||
const uint8_t *plain_text,
|
||||
size_t text_size,
|
||||
const uint8_t key[32],
|
||||
const uint8_t nonce[8],
|
||||
uint64_t ctr);
|
||||
uint32_t crypto_chacha20_ietf(uint8_t *cipher_text,
|
||||
const uint8_t *plain_text,
|
||||
size_t text_size,
|
||||
const uint8_t key[32],
|
||||
const uint8_t nonce[12],
|
||||
uint32_t ctr);
|
||||
uint64_t crypto_chacha20_x(uint8_t *cipher_text,
|
||||
const uint8_t *plain_text,
|
||||
size_t text_size,
|
||||
const uint8_t key[32],
|
||||
const uint8_t nonce[24],
|
||||
uint64_t ctr);
|
||||
|
||||
|
||||
// Poly 1305
|
||||
// ---------
|
||||
|
||||
// This is a *one time* authenticator.
|
||||
// Disclosing the mac reveals the key.
|
||||
// See crypto_lock() on how to use it properly.
|
||||
|
||||
// Direct interface
|
||||
void crypto_poly1305(uint8_t mac[16],
|
||||
const uint8_t *message, size_t message_size,
|
||||
const uint8_t key[32]);
|
||||
|
||||
// Incremental interface
|
||||
typedef struct {
|
||||
// Do not rely on the size or contents of this type,
|
||||
// for they may change without notice.
|
||||
uint8_t c[16]; // chunk of the message
|
||||
size_t c_idx; // How many bytes are there in the chunk.
|
||||
uint32_t r [4]; // constant multiplier (from the secret key)
|
||||
uint32_t pad[4]; // random number added at the end (from the secret key)
|
||||
uint32_t h [5]; // accumulated hash
|
||||
} crypto_poly1305_ctx;
|
||||
|
||||
void crypto_poly1305_init (crypto_poly1305_ctx *ctx, const uint8_t key[32]);
|
||||
void crypto_poly1305_update(crypto_poly1305_ctx *ctx,
|
||||
const uint8_t *message, size_t message_size);
|
||||
void crypto_poly1305_final (crypto_poly1305_ctx *ctx, uint8_t mac[16]);
|
||||
|
||||
|
||||
// Elligator 2
|
||||
// -----------
|
||||
|
||||
// Elligator mappings proper
|
||||
void crypto_elligator_map(uint8_t curve [32], const uint8_t hidden[32]);
|
||||
int crypto_elligator_rev(uint8_t hidden[32], const uint8_t curve [32],
|
||||
uint8_t tweak);
|
||||
|
||||
// Easy to use key pair generation
|
||||
void crypto_elligator_key_pair(uint8_t hidden[32], uint8_t secret_key[32],
|
||||
uint8_t seed[32]);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // MONOCYPHER_H
|
||||
872
runtime/ui/coop_page.cpp
Normal file
872
runtime/ui/coop_page.cpp
Normal file
@@ -0,0 +1,872 @@
|
||||
// The Co-op tab (coop_page.h, docs/coop.md). The page reads the co-op layer only through the copies the layer hands out
|
||||
// and drives it only through the calls the layer makes safe from any thread, all in the section "the co-op layer"
|
||||
// below, so the menu's present thread never waits for the coop thread's work. What it writes (the name, the relay, the
|
||||
// rules, the co-op switch) are settings, through cfg like every row, and reach nx2navi.ini as theirs do; the room's
|
||||
// secret is never a setting, never logged, and shown only when asked.
|
||||
//
|
||||
// Every window that acts on the room (Accept, Remove, Reset the pools, Leave) opens with the cursor on its safe button
|
||||
// (Not now, Cancel, Stay) whenever it opens, and its acting button has an ID of its own, so a second press of the button
|
||||
// that opened it, a held button's repeats or a double tap land on the safe one.
|
||||
#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 "coop_offer.h"
|
||||
#include "platform/platform.h"
|
||||
#include "ui/menu.h"
|
||||
#include "ui_text.h"
|
||||
}
|
||||
|
||||
enum Page { P_NONE, P_NAME, P_SERVER, P_JOIN, P_ACCEPT, P_REMOVE, P_RESET, P_LEAVE };
|
||||
enum { FIELD_CAP = 160, PASTE_FRAMES = 120, CONTRIBUTORS = 24 };
|
||||
|
||||
static bool g_open, g_window_shown, g_page_new, g_by_pad;
|
||||
static int g_page;
|
||||
static char g_field[FIELD_CAP]; // the text of the window's field (a name, an address, a secret)
|
||||
static bool g_field_bad, g_paste_empty; // the secret typed is not one; the clipboard had no text
|
||||
static int g_paste_wait; // frames left to wait for the clipboard's text (gfx_window_paste)
|
||||
static CoopOffer g_shown; // the offer the Accept window shows (its number: g_shown.token)
|
||||
// The player the Remove window names: by the key's fingerprint when they have one (identified, or a pool contributor
|
||||
// not in the room), else by their member id while the same session holds it (a player who is not identified: they
|
||||
// never said who they are, or two keys present themselves for their session)
|
||||
static int g_member;
|
||||
static uint64_t g_member_session;
|
||||
static char g_member_name[COOP_NAME_MAX + 1], g_member_key[20];
|
||||
static char g_return[48]; // the row the cursor goes back to when the window closes
|
||||
|
||||
static CoopView g_view; // this frame's copies of the layer's state
|
||||
static CoopOffer g_offer;
|
||||
static CoopContributor g_contrib[CONTRIBUTORS];
|
||||
static int g_ncontrib;
|
||||
static bool g_maker; // this game holds the key that signs the room's rules (coop_game_is_maker)
|
||||
static bool g_accepted_once; // an Accept went through in this start: the warnings were read before it
|
||||
static bool g_refused; // the last Accept was refused by the layer (the room changed meanwhile)
|
||||
static int g_layout = -1; // the page's last kind: 0 not in a room, 1 reaching one, 2 in one
|
||||
static bool g_show_secret;
|
||||
static int g_msg = -1; // a line under the rows (UiTextId), -1 none
|
||||
static bool g_msg_warn;
|
||||
static int g_copied; // the secret's copy: 1 done, -1 failed, 0 nothing to say
|
||||
static uint64_t g_copied_at;
|
||||
// A Make or Join while co-op is off: the switch is turned on and the command waits until the coop thread has come up.
|
||||
static int g_pending; // the CoopCmd, 0 none
|
||||
static char g_pending_secret[COOP_SECRET_LEN + 1];
|
||||
static uint64_t g_pending_until;
|
||||
static bool g_joining; // the last command was a join: "no such room" then means the secret is wrong
|
||||
|
||||
static const char *const kRuleKeys[COOP_CAT_N] = {"NX2NAVI_COOP_PROGRESS", "NX2NAVI_COOP_ITEMS", "NX2NAVI_COOP_SONGS",
|
||||
"NX2NAVI_COOP_QUEST", "NX2NAVI_COOP_KEYS", "NX2NAVI_COOP_RUPEES",
|
||||
"NX2NAVI_COOP_AMMO"};
|
||||
|
||||
static bool in_room(const CoopView &v) { return v.state == COOP_JOINED || v.state == COOP_RECONNECTING; }
|
||||
|
||||
static void say(int text, bool warn) { g_msg = text, g_msg_warn = warn; }
|
||||
|
||||
// ---- the co-op layer: every call the page makes to it. The page knows a member by the id the view gives and, once it
|
||||
// said who it is, by its key's fingerprint, never by its name; an offer's number and whether it is accepted are the
|
||||
// layer's, and the page passes back only the number of the offer it showed the player. A removal goes by the key; only
|
||||
// a player who is not identified goes by member id, checked against the session that held the id when the
|
||||
// window opened.
|
||||
|
||||
// This frame's copies: the view (coop.h) and, in a room, the offer (coop_offer.h: without a number while there is none
|
||||
// to accept, with the members and whether their rules disagree all the same), the pools' contributors and whether this
|
||||
// game is the room's maker; outside a room none of them.
|
||||
static void layer_read(CoopView *v, CoopOffer *o, CoopContributor *c = nullptr, int *nc = nullptr, bool *maker = nullptr) {
|
||||
coop_view_get(v);
|
||||
coop_game_offer(o);
|
||||
const bool room = in_room(*v);
|
||||
if (!room) memset(o, 0, sizeof *o);
|
||||
if (c) *nc = room ? coop_game_contributors(c, CONTRIBUTORS) : 0;
|
||||
if (maker) *maker = room && coop_game_is_maker();
|
||||
}
|
||||
|
||||
// Make (secret NULL: a new one), join (secret: canonical) or leave; false when the layer took nothing (co-op off).
|
||||
static bool layer_command(int cmd, const char *secret) { return coop_command((CoopCmd)cmd, secret) != 0; }
|
||||
|
||||
// The maker's removal of a key (also of a player who left; one in the room is removed at the relay too).
|
||||
static void layer_remove_key(const char *fingerprint) { coop_game_remove_key(fingerprint); }
|
||||
|
||||
// The maker's removal of a player who is not identified, by member id.
|
||||
static void layer_remove_member(int id) { coop_remove_member(id); }
|
||||
|
||||
static void layer_reset_pools(void) { coop_game_reset_pools(); }
|
||||
|
||||
// Accepts the offer the player was shown, and no other: false when the layer refuses it (the room has changed
|
||||
// meanwhile, or a player in it is not identified).
|
||||
static bool layer_accept(const CoopOffer &shown) { return coop_game_accept(shown.token) != 0; }
|
||||
|
||||
static bool layer_same_offer(const CoopOffer &a, const CoopOffer &b) { return a.token == b.token; }
|
||||
|
||||
// A secret as typed or pasted (any case, '-' and spaces) into its 18 characters; false when it is not one.
|
||||
static bool layer_secret(const char *typed, char canon[COOP_SECRET_LEN + 1]) { return coop_secret_normalize(typed, canon) != 0; }
|
||||
|
||||
static UiTextId mode_name(int mode) {
|
||||
return mode == COOP_MODE_SHARED ? UI_MENU_COOP_SHARED : mode == COOP_MODE_POOL ? UI_MENU_COOP_POOL : UI_MENU_COOP_OWN;
|
||||
}
|
||||
|
||||
// The setting's text as the engine reads it (coop_game.c mode_of): anything but the category's other mode is own.
|
||||
static int mode_of_setting(int cat) {
|
||||
const char *v = cfg_value(kRuleKeys[cat]);
|
||||
if (coop_cat_is_pool(cat)) return !strcmp(v, "pool") ? COOP_MODE_POOL : COOP_MODE_OWN;
|
||||
return !strcmp(v, "shared") ? COOP_MODE_SHARED : COOP_MODE_OWN;
|
||||
}
|
||||
|
||||
// Make or join (secret: canonical, or NULL for a new room). Co-op off: it is turned on first, as the switch's row would.
|
||||
static void command(int cmd, const char *secret) {
|
||||
g_msg = -1;
|
||||
g_joining = cmd == COOP_CMD_JOIN;
|
||||
if (g_view.state == COOP_OFF) {
|
||||
opt_apply("NX2NAVI_COOP", "1");
|
||||
g_pending = cmd;
|
||||
snprintf(g_pending_secret, sizeof g_pending_secret, "%s", secret ? secret : "");
|
||||
g_pending_until = plat_now_ms() + 3000;
|
||||
return;
|
||||
}
|
||||
if (!layer_command(cmd, secret)) say(UI_MENU_COOP_NOT_STARTED, true);
|
||||
}
|
||||
|
||||
static void pending_tick(void) {
|
||||
if (!g_pending) return;
|
||||
if (g_view.state != COOP_OFF) {
|
||||
if (!layer_command(g_pending, g_pending_secret[0] ? g_pending_secret : nullptr)) say(UI_MENU_COOP_NOT_STARTED, true);
|
||||
g_pending = 0;
|
||||
} else if (plat_now_ms() > g_pending_until) {
|
||||
say(UI_MENU_COOP_NOT_STARTED, true);
|
||||
g_pending = 0;
|
||||
}
|
||||
if (!g_pending) memset(g_pending_secret, 0, sizeof g_pending_secret);
|
||||
}
|
||||
|
||||
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;
|
||||
snprintf(g_return, sizeof g_return, "%s", ret);
|
||||
}
|
||||
|
||||
static void open_field(int page, const char *initial, const char *ret) {
|
||||
open_window(page, ret);
|
||||
snprintf(g_field, sizeof g_field, "%s", initial);
|
||||
}
|
||||
|
||||
static void open_accept(void) {
|
||||
g_shown = g_offer;
|
||||
g_refused = false;
|
||||
open_window(P_ACCEPT, "##coop_answer");
|
||||
}
|
||||
|
||||
// The offer's entry for member id (its signed name, its key, whether it is identified or removed); NULL when none.
|
||||
static const CoopOfferMember *offer_member(const CoopOffer &o, int id) {
|
||||
for (int i = 0; i < o.n; i++)
|
||||
if (o.member[i].id == id) return &o.member[i];
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// The Remove window for a player: key, their key's fingerprint ("" for a player who is not identified, who is
|
||||
// then removed by member id while session still holds it); id 0 for a contributor not in the room. ret: the row the
|
||||
// cursor goes back to.
|
||||
static void open_remove(int id, uint64_t session, const char *name, const char *key, const char *ret) {
|
||||
g_member = id, g_member_session = session;
|
||||
snprintf(g_member_name, sizeof g_member_name, "%s", name);
|
||||
snprintf(g_member_key, sizeof g_member_key, "%s", key);
|
||||
open_window(P_REMOVE, ret);
|
||||
}
|
||||
|
||||
// The name a member is shown by: this player's own name, else the name its game signed once it said who it is, else
|
||||
// the relay's.
|
||||
static const char *member_name(const CoopPeer &m, const CoopOfferMember *om) {
|
||||
if (m.id == g_view.self) return g_view.name[0] ? g_view.name : m.name;
|
||||
return om && om->heard && om->name[0] ? om->name : m.name;
|
||||
}
|
||||
|
||||
static void open_remove_member(const CoopPeer &m) {
|
||||
const CoopOfferMember *om = offer_member(g_offer, m.id);
|
||||
char ret[32];
|
||||
snprintf(ret, sizeof ret, "##coop_member%d", m.id);
|
||||
open_remove(m.id, m.session, member_name(m, om), om && om->heard ? om->key : "", ret);
|
||||
}
|
||||
|
||||
// "Alice (made the room), Bob (not identified), Dave (a key you accepted as Carol)" and the rules' categories by mode,
|
||||
// as the offer and the Accept window say them. A key the player accepted under another name than it signs now is a new
|
||||
// offer (coop_state.h: CoopOfferMember.accepted_as): the name it was accepted as is said beside the one it signs.
|
||||
static void offer_lines(const CoopOffer &o, char *who, size_t who_cap, char *shared, size_t shared_cap, char *pooled,
|
||||
size_t pooled_cap) {
|
||||
char names[COOP_MAX_MEMBERS * (2 * COOP_NAME_MAX + 200)] = "";
|
||||
size_t k = 0;
|
||||
for (int i = 0; i < o.n && k < sizeof names; i++) {
|
||||
const CoopOfferMember &m = o.member[i];
|
||||
const char *note = m.removed ? menu_text(UI_MENU_COOP_REMOVED)
|
||||
: !m.heard ? menu_text(UI_MENU_COOP_NOT_IDENTIFIED)
|
||||
: m.maker ? menu_text(UI_MENU_COOP_MAKER)
|
||||
: "";
|
||||
char moved[COOP_NAME_MAX + 128] = "";
|
||||
if (m.heard && !m.removed && m.accepted_as[0])
|
||||
snprintf(moved, sizeof moved, menu_text(UI_MENU_COOP_ACCEPTED_AS), m.accepted_as);
|
||||
const bool paren = *note || *moved;
|
||||
k += (size_t)snprintf(names + k, sizeof names - k, "%s%s%s%s%s%s%s", i ? ", " : "", m.name, paren ? " (" : "", note,
|
||||
*note && *moved ? "; " : "", moved, paren ? ")" : "");
|
||||
}
|
||||
snprintf(who, who_cap, menu_text(UI_MENU_COOP_OFFER_WHO), o.n ? names : menu_text(UI_MENU_COOP_OFFER_NOBODY));
|
||||
char s[256] = "", p[256] = "";
|
||||
size_t ks = 0, kp = 0;
|
||||
for (int c = 0; c < COOP_CAT_N; c++) {
|
||||
const char *label = menu_text((UiTextId)(UI_MENU_COOP_R_PROGRESS + c));
|
||||
if (o.rules.mode[c] == COOP_MODE_SHARED && ks < sizeof s)
|
||||
ks += (size_t)snprintf(s + ks, sizeof s - ks, "%s%s", ks ? ", " : "", label);
|
||||
if (o.rules.mode[c] == COOP_MODE_POOL && kp < sizeof p)
|
||||
kp += (size_t)snprintf(p + kp, sizeof p - kp, "%s%s", kp ? ", " : "", label);
|
||||
}
|
||||
shared[0] = pooled[0] = 0;
|
||||
if (s[0]) snprintf(shared, shared_cap, menu_text(UI_MENU_COOP_OFFER_SHARED), s);
|
||||
if (p[0]) snprintf(pooled, pooled_cap, menu_text(UI_MENU_COOP_OFFER_POOLED), p);
|
||||
if (!s[0] && !p[0]) snprintf(shared, shared_cap, "%s", menu_text(UI_MENU_COOP_OFFER_NOTHING));
|
||||
}
|
||||
|
||||
// The rules, a row each in coop_state.h's order. editable (not in a room, or this player made it): the rows change this
|
||||
// player's settings, which are the rules of a room it makes; a category the others force (items, songs and quest
|
||||
// items follow Progress shared, keys follow Progress own: coop_rules_normalize) is greyed out with its value in effect.
|
||||
// Otherwise the room's rules, to read.
|
||||
static void rule_rows(bool editable, const CoopRules *room) {
|
||||
CoopRules r;
|
||||
if (editable) {
|
||||
coop_rules_default(&r);
|
||||
for (int c = 0; c < COOP_CAT_N; c++) r.mode[c] = (uint8_t)mode_of_setting(c);
|
||||
coop_rules_normalize(&r);
|
||||
} else {
|
||||
r = *room;
|
||||
}
|
||||
for (int c = 0; c < COOP_CAT_N; c++) {
|
||||
const bool pool = coop_cat_is_pool(c) != 0;
|
||||
const UiTextId label = (UiTextId)(UI_MENU_COOP_R_PROGRESS + c), desc = (UiTextId)(UI_MENU_COOP_R_PROGRESS_DESC + c);
|
||||
if (!editable) {
|
||||
char id[24];
|
||||
snprintf(id, sizeof id, "##coop_room_rule%d", c);
|
||||
opt_disable_next(UI_MENU_COOP_RULES_SET_BY);
|
||||
opt_text_row(id, menu_text(label), menu_text(mode_name(r.mode[c])), nullptr, menu_text(desc), false);
|
||||
continue;
|
||||
}
|
||||
// the values in the order of the setting's list (cfg.c), the default first
|
||||
const char *values[2];
|
||||
int modes[2];
|
||||
if (!pool) values[0] = "shared", values[1] = "own", modes[0] = COOP_MODE_SHARED, modes[1] = COOP_MODE_OWN;
|
||||
else if (c == COOP_CAT_KEYS) values[0] = "pool", values[1] = "own", modes[0] = COOP_MODE_POOL, modes[1] = COOP_MODE_OWN;
|
||||
else values[0] = "own", values[1] = "pool", modes[0] = COOP_MODE_OWN, modes[1] = COOP_MODE_POOL;
|
||||
const char *names[2] = {menu_text(mode_name(modes[0])), menu_text(mode_name(modes[1]))};
|
||||
const int cur = r.mode[c] == modes[0] ? 0 : 1;
|
||||
CoopRules t = r; // the other mode, as the engine would take it: a forced category does not keep it
|
||||
t.mode[c] = (uint8_t)modes[1 - cur];
|
||||
coop_rules_normalize(&t);
|
||||
if (t.mode[c] != modes[1 - cur]) opt_disable_next(UI_MENU_COOP_RULE_FOLLOWS);
|
||||
opt_choice_list(kRuleKeys[c], label, values, names, 2, desc, cur);
|
||||
}
|
||||
}
|
||||
|
||||
static void status_line(void) {
|
||||
char line[256];
|
||||
if (g_view.state == COOP_CONNECTING || g_pending) {
|
||||
snprintf(line, sizeof line, menu_text(UI_MENU_COOP_CONNECTING), g_view.state == COOP_CONNECTING ? g_view.status : "…");
|
||||
opt_text_str(line, false);
|
||||
} else if (g_view.state == COOP_RECONNECTING) {
|
||||
snprintf(line, sizeof line, menu_text(UI_MENU_COOP_RECONNECTING), g_view.status);
|
||||
opt_text_str(line, true);
|
||||
} else if (g_view.state == COOP_LEFT && g_view.status[0]) {
|
||||
snprintf(line, sizeof line, menu_text(UI_MENU_COOP_LEFT), g_view.status);
|
||||
opt_text_str(line, strcmp(g_view.status, "you left the room") != 0);
|
||||
if (g_joining && strstr(g_view.status, "no such room")) opt_text(UI_MENU_COOP_NO_ROOM, true);
|
||||
}
|
||||
// the relay's limit on joins from one network: the session waits a minute and tries again by itself
|
||||
if (g_view.state != COOP_LEFT && strstr(g_view.status, "trying again in a minute")) opt_text(UI_MENU_COOP_JOIN_LIMIT, true);
|
||||
// a room the relay lost (its restart): the session makes it again or waits for it, and says so in its status
|
||||
if (g_view.state != COOP_LEFT && strstr(g_view.status, "the room was lost")) opt_text(UI_MENU_COOP_LOST, true);
|
||||
}
|
||||
|
||||
static void rows_out(void) {
|
||||
const bool reaching = g_view.state == COOP_CONNECTING || g_pending;
|
||||
const char *server = cfg_value("NX2NAVI_COOP_SERVER");
|
||||
if (reaching) {
|
||||
if (opt_button("##coop_stop", UI_MENU_COOP_STOP, UI_MENU_COOP_STOP_DESC)) {
|
||||
if (g_pending) g_pending = 0;
|
||||
else layer_command(COOP_CMD_LEAVE, nullptr);
|
||||
}
|
||||
status_line();
|
||||
return;
|
||||
}
|
||||
const char *name = cfg_value("NX2NAVI_COOP_NAME");
|
||||
if (opt_text_row("NX2NAVI_COOP_NAME", menu_text(UI_MENU_COOP_NAME), *name ? name : menu_text(UI_MENU_COOP_AUTO),
|
||||
nullptr, menu_text(UI_MENU_COOP_NAME_DESC), false) == 2)
|
||||
open_field(P_NAME, name, "NX2NAVI_COOP_NAME");
|
||||
if (opt_text_row("NX2NAVI_COOP_SERVER", menu_text(UI_MENU_COOP_SERVER), *server ? server : menu_text(UI_MENU_COOP_NONE),
|
||||
nullptr, menu_text(UI_MENU_COOP_SERVER_DESC), false) == 2)
|
||||
open_field(P_SERVER, server, "NX2NAVI_COOP_SERVER");
|
||||
if (!*server) opt_disable_next(UI_MENU_COOP_NEED_SERVER);
|
||||
if (opt_button("##coop_make", UI_MENU_COOP_MAKE, UI_MENU_COOP_MAKE_DESC)) command(COOP_CMD_CREATE, nullptr);
|
||||
if (!*server) opt_disable_next(UI_MENU_COOP_NEED_SERVER);
|
||||
if (opt_button("##coop_join", UI_MENU_COOP_JOIN, UI_MENU_COOP_JOIN_DESC)) open_field(P_JOIN, "", "##coop_join");
|
||||
status_line();
|
||||
opt_group(UI_MENU_COOP_RULES_MINE);
|
||||
rule_rows(true, nullptr);
|
||||
opt_group(UI_MENU_COOP_ON);
|
||||
opt_toggle("NX2NAVI_COOP", UI_MENU_COOP_ON, UI_MENU_COOP_ON_DESC);
|
||||
}
|
||||
|
||||
// The room's offer while the player has not accepted it: who, what is shared, the key that signs the rules (to compare
|
||||
// with the maker's), why it cannot be accepted yet, and the row that opens Accept or not. Members whose rules disagree
|
||||
// are said also while there is no offer.
|
||||
static void offer_rows(const CoopOffer &o) {
|
||||
char line[640];
|
||||
if (o.token && !o.accepted) {
|
||||
opt_group(UI_MENU_COOP_OFFER);
|
||||
char who[2400], shared[320], pooled[320];
|
||||
offer_lines(o, who, sizeof who, shared, sizeof shared, pooled, sizeof pooled);
|
||||
opt_text_str(who, false);
|
||||
if (shared[0]) opt_text_str(shared, false);
|
||||
if (pooled[0]) opt_text_str(pooled, false);
|
||||
if (o.new_save) opt_text(UI_MENU_COOP_NEW_SAVE);
|
||||
if (o.maker_key[0] && !g_maker) {
|
||||
snprintf(line, sizeof line, menu_text(UI_MENU_COOP_OFFER_KEY), o.maker_key);
|
||||
opt_text_str(line, false);
|
||||
opt_text(UI_MENU_COOP_OFFER_COMPARE);
|
||||
}
|
||||
if (o.disagree) opt_text(UI_MENU_COOP_DISAGREE, true);
|
||||
if (o.unidentified) {
|
||||
snprintf(line, sizeof line, menu_text(UI_MENU_COOP_UNIDENTIFIED), o.unidentified);
|
||||
opt_text_str(line, true);
|
||||
}
|
||||
if (opt_button("##coop_answer", UI_MENU_COOP_ANSWER, UI_MENU_COOP_ANSWER_DESC)) open_accept();
|
||||
} else if (!o.token && o.disagree) {
|
||||
opt_group(UI_MENU_COOP_OFFER);
|
||||
opt_text(UI_MENU_COOP_DISAGREE, true);
|
||||
}
|
||||
}
|
||||
|
||||
// The note under a player's row: the name the player accepted that key as when it now signs another (a new offer),
|
||||
// first, since a row shows only the start of a long note (option_rows.cpp: at most 60 % of the row); then made the room,
|
||||
// when they were last heard, their key (or not identified, or removed). om: NULL for this player.
|
||||
static void member_note(const CoopPeer &m, const CoopOfferMember *om, bool self, char *note, size_t cap) {
|
||||
char heard[64] = "", key[64] = "", moved[COOP_NAME_MAX + 128] = "";
|
||||
if (!self) {
|
||||
if (m.away) snprintf(heard, sizeof heard, "%s", menu_text(UI_MENU_COOP_AWAY));
|
||||
else if (m.heard_ms == UINT32_MAX) snprintf(heard, sizeof heard, "%s", menu_text(UI_MENU_COOP_NOT_HEARD));
|
||||
else snprintf(heard, sizeof heard, menu_text(UI_MENU_COOP_HEARD), (unsigned)(m.heard_ms / 1000));
|
||||
}
|
||||
if (om && om->removed) snprintf(key, sizeof key, "%s", menu_text(UI_MENU_COOP_REMOVED));
|
||||
else if (om && om->heard) snprintf(key, sizeof key, menu_text(UI_MENU_COOP_KEY), om->key);
|
||||
else if (om) snprintf(key, sizeof key, "%s", menu_text(UI_MENU_COOP_NOT_IDENTIFIED));
|
||||
if (om && om->heard && !om->removed && om->accepted_as[0])
|
||||
snprintf(moved, sizeof moved, menu_text(UI_MENU_COOP_ACCEPTED_AS), om->accepted_as);
|
||||
const char *const parts[] = {moved, m.maker ? menu_text(UI_MENU_COOP_MAKER) : "", heard, key};
|
||||
size_t k = 0;
|
||||
note[0] = 0;
|
||||
for (const char *part : parts)
|
||||
if (part[0] && k < cap) k += (size_t)snprintf(note + k, cap - k, "%s%s", k ? " · " : "", part);
|
||||
}
|
||||
|
||||
// The players in the room, by the name their game signed once it said who it is; each with its key or "not
|
||||
// identified". The maker sees its own key to read out to the others, and a Remove on every other row.
|
||||
static void player_rows(const CoopOffer &o) {
|
||||
opt_group(UI_MENU_COOP_PLAYERS);
|
||||
if (g_maker && o.maker_key[0]) {
|
||||
char line[640];
|
||||
snprintf(line, sizeof line, menu_text(UI_MENU_COOP_MY_KEY), o.maker_key);
|
||||
opt_text_str(line, false);
|
||||
}
|
||||
if (o.unidentified && (!o.token || o.accepted)) { // else the offer above says it
|
||||
char line[640];
|
||||
snprintf(line, sizeof line, menu_text(UI_MENU_COOP_UNIDENTIFIED), o.unidentified);
|
||||
opt_text_str(line, true);
|
||||
}
|
||||
for (int i = 0; i < g_view.n; i++) {
|
||||
const CoopPeer &m = g_view.member[i];
|
||||
const bool self = m.id == g_view.self, removable = g_maker && !self;
|
||||
const CoopOfferMember *om = self ? nullptr : offer_member(o, m.id);
|
||||
const char *name = member_name(m, om);
|
||||
char id[32], note[400], desc[UI_DESC_BYTES - 256];
|
||||
snprintf(id, sizeof id, "##coop_member%d", m.id);
|
||||
member_note(m, om, self, note, sizeof note);
|
||||
snprintf(desc, sizeof desc, "%s%s%s", menu_text(UI_MENU_COOP_MEMBER_DESC), removable ? "\n\n" : "",
|
||||
removable ? menu_text(UI_MENU_COOP_REMOVE_DESC) : "");
|
||||
const char *value = self ? menu_text(UI_MENU_COOP_YOU) : removable ? menu_text(UI_MENU_COOP_REMOVE) : "";
|
||||
if (opt_text_row(id, name, value, note[0] ? note : nullptr, desc, false) == 2 && removable) open_remove_member(m);
|
||||
}
|
||||
}
|
||||
|
||||
// For the maker: the keys that took more from the pools than they brought (in the room or not; a player who used keys
|
||||
// others found is among them), each with a Remove of its key, and the pool reset.
|
||||
static void pool_rows(void) {
|
||||
if (!g_maker) return;
|
||||
opt_group(UI_MENU_COOP_POOLS);
|
||||
int listed = 0;
|
||||
for (int i = 0; i < g_ncontrib; i++) {
|
||||
const CoopContributor &c = g_contrib[i];
|
||||
if (c.self || c.removed || !(c.spent[0] > 0 || c.spent[1] > 0 || c.spent[2] > 0)) continue;
|
||||
char id[48], label[COOP_NAME_MAX + 64], key[64], spent[200], note[280];
|
||||
snprintf(id, sizeof id, "##coop_spent%s", c.key);
|
||||
snprintf(label, sizeof label, "%s", c.member && c.name[0] ? c.name : menu_text(UI_MENU_COOP_NOT_IN_ROOM));
|
||||
snprintf(key, sizeof key, menu_text(UI_MENU_COOP_KEY), c.key);
|
||||
snprintf(spent, sizeof spent, menu_text(UI_MENU_COOP_SPENT), (long long)c.spent[0], (long long)c.spent[1],
|
||||
(long long)c.spent[2]);
|
||||
snprintf(note, sizeof note, "%s · %s", key, spent);
|
||||
if (opt_text_row(id, label, menu_text(UI_MENU_COOP_REMOVE), note, menu_text(UI_MENU_COOP_SPENT_DESC), false) == 2) {
|
||||
uint64_t session = 0;
|
||||
for (int j = 0; j < g_view.n; j++)
|
||||
if (c.member && g_view.member[j].id == c.member) session = g_view.member[j].session;
|
||||
open_remove(c.member, session, label, c.key, id);
|
||||
}
|
||||
listed++;
|
||||
}
|
||||
if (!listed) opt_text(UI_MENU_COOP_SPENT_NONE);
|
||||
if (opt_button("##coop_reset", UI_MENU_COOP_RESET, UI_MENU_COOP_RESET_DESC)) open_window(P_RESET, "##coop_reset");
|
||||
}
|
||||
|
||||
static void rows_room(void) {
|
||||
status_line();
|
||||
const CoopOffer &o = g_offer;
|
||||
offer_rows(o);
|
||||
player_rows(o);
|
||||
pool_rows();
|
||||
opt_group(UI_MENU_COOP_SECRET);
|
||||
char shown[COOP_SECRET_TEXT + 1];
|
||||
snprintf(shown, sizeof shown, "%s", g_show_secret ? g_view.code : "******-******-******");
|
||||
if (opt_text_row("##coop_secret", menu_text(UI_MENU_COOP_SECRET), shown,
|
||||
menu_text(g_show_secret ? UI_MENU_COOP_HIDE : UI_MENU_COOP_SHOW), menu_text(UI_MENU_COOP_SECRET_DESC),
|
||||
false) == 2)
|
||||
g_show_secret = !g_show_secret;
|
||||
if (g_copied && plat_now_ms() - g_copied_at > 3000) g_copied = 0;
|
||||
const char *copied = g_copied > 0 ? menu_text(UI_MENU_COPY_INFO_DONE) : g_copied < 0 ? menu_text(UI_MENU_ACTION_FAILED) : "";
|
||||
if (opt_button("##coop_copy", UI_MENU_COOP_COPY, UI_MENU_COOP_COPY_DESC, copied)) {
|
||||
g_copied = g_view.code[0] && plat_clipboard_set(g_view.code) ? 1 : -1;
|
||||
g_copied_at = plat_now_ms();
|
||||
}
|
||||
if (o.token && o.accepted && o.copy) opt_text(o.copy > 0 ? UI_MENU_COOP_ACCEPTED : UI_MENU_COOP_COPY_FAILED, o.copy < 0);
|
||||
opt_group(UI_MENU_COOP_RULES_ROOM);
|
||||
if (g_view.made) {
|
||||
rule_rows(true, nullptr);
|
||||
opt_text(UI_MENU_COOP_RULES_CHANGE);
|
||||
} else if (o.token) {
|
||||
rule_rows(false, &o.rules);
|
||||
} else {
|
||||
opt_text(UI_MENU_COOP_RULES_UNKNOWN);
|
||||
}
|
||||
opt_group(UI_MENU_COOP_LEAVE);
|
||||
if (opt_button("##coop_leave", UI_MENU_COOP_LEAVE, UI_MENU_COOP_LEAVE_DESC)) open_window(P_LEAVE, "##coop_leave");
|
||||
}
|
||||
|
||||
void coop_rows(float scale) {
|
||||
(void)scale;
|
||||
layer_read(&g_view, &g_offer, g_contrib, &g_ncontrib, &g_maker);
|
||||
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 (never Leave, Make or the secret)
|
||||
const int layout = in_room(g_view) ? 2 : g_view.state == COOP_CONNECTING || g_pending ? 1 : 0;
|
||||
if (layout != g_layout) {
|
||||
if (g_layout >= 0) {
|
||||
char key[32];
|
||||
if (layout == 2) snprintf(key, sizeof key, "##coop_member%d", g_view.self);
|
||||
else snprintf(key, sizeof key, "%s", layout == 1 ? "##coop_stop" : "NX2NAVI_COOP_NAME");
|
||||
opt_focus_key(key);
|
||||
}
|
||||
if (layout != 2) g_show_secret = false;
|
||||
g_layout = layout;
|
||||
}
|
||||
if (layout == 2) rows_room();
|
||||
else rows_out();
|
||||
if (g_msg >= 0) opt_text((UiTextId)g_msg, g_msg_warn);
|
||||
}
|
||||
|
||||
// ---- 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_NAME || g_page == P_SERVER || g_page == P_JOIN; }
|
||||
|
||||
// Two buttons side by side, the safe one first: 1 the first, 2 the second. The cursor goes to the safe one whenever a
|
||||
// step opens (fresh), not only when the window appears, and the second has an ID of its own ("##yes"): ImGui keeps the
|
||||
// cursor on an ID across steps, and SetItemDefaultFocus works only on a window's first frame. 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 secret: the characters a secret is typed with, no line ends or tabs, at most the field's room.
|
||||
static void take_paste(const char *text) {
|
||||
char out[FIELD_CAP];
|
||||
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 == '-' || *p == ' ')
|
||||
out[k++] = *p >= 'a' && *p <= 'z' ? (char)(*p - 'a' + 'A') : *p;
|
||||
out[k] = 0;
|
||||
while (k && out[k - 1] == ' ') out[--k] = 0;
|
||||
const char *s = out;
|
||||
while (*s == ' ') s++;
|
||||
g_paste_empty = !*s;
|
||||
if (*s) snprintf(g_field, sizeof g_field, "%s", s), g_field_bad = false;
|
||||
}
|
||||
|
||||
// The text of the field without the spaces around it.
|
||||
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: Cancel and OK (Join): the name, the relay's address or the room's secret.
|
||||
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_SECRET : g_page == P_NAME ? UI_MENU_COOP_NAME : UI_MENU_COOP_SERVER));
|
||||
ImGui::TextDisabled("%s", menu_text(join ? UI_MENU_COOP_SECRET_HINT : g_page == P_NAME ? UI_MENU_COOP_NAME_DESC
|
||||
: UI_MENU_COOP_SERVER_DESC));
|
||||
if (fresh && !g_by_pad) ImGui::SetKeyboardFocusHere();
|
||||
ImGui::SetNextItemWidth(wrap);
|
||||
// the name: at most COOP_NAME_MAX bytes, as the relay takes it
|
||||
const size_t cap = g_page == P_NAME ? COOP_NAME_MAX + 1 : join ? 64 : sizeof g_field;
|
||||
const bool enter = ImGui::InputText("##coop_field", g_field, cap,
|
||||
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_SECRET_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_OK),
|
||||
!join || text[0], fresh, scale);
|
||||
if (r == 1) *back = true;
|
||||
if (r != 2 && !enter) return;
|
||||
if (g_page == P_NAME || g_page == P_SERVER) {
|
||||
opt_apply(g_page == P_NAME ? "NX2NAVI_COOP_NAME" : "NX2NAVI_COOP_SERVER", text); // "": automatic, the default
|
||||
*close = true;
|
||||
return;
|
||||
}
|
||||
char canon[COOP_SECRET_LEN + 1];
|
||||
if (!text[0]) return;
|
||||
if (!layer_secret(text, canon)) {
|
||||
g_field_bad = true;
|
||||
return;
|
||||
}
|
||||
command(COOP_CMD_JOIN, canon);
|
||||
memset(canon, 0, sizeof canon);
|
||||
memset(g_field, 0, sizeof g_field);
|
||||
*close = true;
|
||||
}
|
||||
|
||||
// The offer: who, what is shared, the key that signs the rules, where the save is copied, before the first Accept of
|
||||
// this start the three warnings of docs/coop.md ("Before you join a room with strangers"), and Not now (the cursor) /
|
||||
// Accept. A new offer while the window is open replaces the one shown and puts the cursor back on Not now: Accept takes
|
||||
// only the offer the player read. While a player in the room is not identified, Accept is greyed and the window
|
||||
// says why (the layer would refuse it).
|
||||
static void accept_window(bool fresh, float scale, float wrap, bool *close, bool *back) {
|
||||
(void)wrap;
|
||||
if (!g_offer.token || g_offer.accepted) { // gone, or accepted meanwhile (coop_accept)
|
||||
*close = true;
|
||||
return;
|
||||
}
|
||||
if (!layer_same_offer(g_offer, g_shown)) g_shown = g_offer, fresh = true, g_refused = false;
|
||||
gold(menu_text(UI_MENU_COOP_ACCEPT_CONFIRM));
|
||||
char who[2400], shared[320], pooled[320], line[640];
|
||||
offer_lines(g_shown, who, sizeof who, shared, sizeof shared, pooled, sizeof pooled);
|
||||
ImGui::TextUnformatted(who);
|
||||
if (shared[0]) ImGui::TextUnformatted(shared);
|
||||
if (pooled[0]) ImGui::TextUnformatted(pooled);
|
||||
if (g_shown.new_save) ImGui::TextUnformatted(menu_text(UI_MENU_COOP_NEW_SAVE));
|
||||
if (g_shown.maker_key[0] && !g_maker) {
|
||||
snprintf(line, sizeof line, menu_text(UI_MENU_COOP_OFFER_KEY), g_shown.maker_key);
|
||||
ImGui::TextUnformatted(line);
|
||||
ImGui::TextUnformatted(menu_text(UI_MENU_COOP_OFFER_COMPARE));
|
||||
}
|
||||
if (g_offer.disagree) warn(menu_text(UI_MENU_COOP_DISAGREE));
|
||||
ImGui::Spacing();
|
||||
ImGui::TextUnformatted(menu_text(UI_MENU_COOP_OFFER_COPY));
|
||||
warn(menu_text(UI_MENU_COOP_OFFER_TRUST));
|
||||
if (!g_accepted_once) {
|
||||
ImGui::Spacing();
|
||||
gold(menu_text(UI_MENU_COOP_WARNINGS));
|
||||
ImGui::TextUnformatted(menu_text(UI_MENU_COOP_WARN_SAVE));
|
||||
ImGui::TextUnformatted(menu_text(UI_MENU_COOP_WARN_ROOM));
|
||||
ImGui::TextUnformatted(menu_text(UI_MENU_COOP_WARN_KEY));
|
||||
}
|
||||
const bool can = g_offer.unidentified == 0;
|
||||
if (!can) {
|
||||
snprintf(line, sizeof line, menu_text(UI_MENU_COOP_UNIDENTIFIED), g_offer.unidentified);
|
||||
warn(line);
|
||||
}
|
||||
if (g_refused) warn(menu_text(UI_MENU_COOP_NOT_ACCEPTED));
|
||||
ImGui::Spacing();
|
||||
const int r = two_buttons(menu_text(UI_MENU_COOP_NOT_NOW), menu_text(UI_MENU_COOP_ACCEPT), can, fresh, scale);
|
||||
if (r == 1) *back = true;
|
||||
if (r == 2 && layer_accept(g_shown)) {
|
||||
g_accepted_once = true;
|
||||
snprintf(g_return, sizeof g_return, "##coop_member%d", g_view.self); // the Accept row goes with the offer
|
||||
*close = true;
|
||||
} else if (r == 2) {
|
||||
g_refused = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove: by the key's fingerprint when the player has one, which every game drops (also once the player left);
|
||||
// otherwise by member id, and only while the session that held the id when the window opened still holds it.
|
||||
static void remove_window(bool fresh, float scale, bool *close, bool *back) {
|
||||
bool there = false;
|
||||
for (int i = 0; i < g_view.n; i++)
|
||||
there |= g_view.member[i].id == g_member && g_view.member[i].session == g_member_session;
|
||||
if (!g_maker || (!g_member_key[0] && !there)) {
|
||||
*close = true;
|
||||
return;
|
||||
}
|
||||
char text[256];
|
||||
if (g_member_key[0]) snprintf(text, sizeof text, menu_text(UI_MENU_COOP_REMOVE_KEY_CONFIRM), g_member_name, g_member_key);
|
||||
else snprintf(text, sizeof text, menu_text(UI_MENU_COOP_REMOVE_CONFIRM), g_member_name);
|
||||
gold(text);
|
||||
if (!g_member_key[0]) ImGui::TextUnformatted(menu_text(UI_MENU_COOP_NOT_IDENTIFIED));
|
||||
ImGui::TextUnformatted(menu_text(UI_MENU_COOP_REMOVE_DESC));
|
||||
ImGui::Spacing();
|
||||
const int r = two_buttons(menu_text(UI_MENU_RESET_NO), menu_text(UI_MENU_COOP_REMOVE), true, fresh, scale);
|
||||
if (r == 1) *back = true;
|
||||
if (r == 2) {
|
||||
if (g_member_key[0]) layer_remove_key(g_member_key);
|
||||
else layer_remove_member(g_member);
|
||||
snprintf(g_return, sizeof g_return, "##coop_member%d", g_view.self);
|
||||
*close = true;
|
||||
}
|
||||
}
|
||||
|
||||
static void reset_window(bool fresh, float scale, bool *close, bool *back) {
|
||||
if (!g_maker) {
|
||||
*close = true;
|
||||
return;
|
||||
}
|
||||
gold(menu_text(UI_MENU_COOP_RESET_CONFIRM));
|
||||
ImGui::TextUnformatted(menu_text(UI_MENU_COOP_RESET_DESC));
|
||||
ImGui::Spacing();
|
||||
const int r = two_buttons(menu_text(UI_MENU_RESET_NO), menu_text(UI_MENU_COOP_RESET), true, fresh, scale);
|
||||
if (r == 1) *back = true;
|
||||
if (r == 2) {
|
||||
layer_reset_pools();
|
||||
*close = true;
|
||||
}
|
||||
}
|
||||
|
||||
static void leave_window(bool fresh, float scale, bool *close, bool *back) {
|
||||
gold(menu_text(UI_MENU_COOP_LEAVE_CONFIRM));
|
||||
if (g_maker) warn(menu_text(UI_MENU_COOP_LEAVE_MAKER));
|
||||
ImGui::Spacing();
|
||||
const int r = two_buttons(menu_text(UI_MENU_COOP_STAY), menu_text(UI_MENU_COOP_LEAVE), true, fresh, scale);
|
||||
if (r == 1) *back = true;
|
||||
if (r == 2) {
|
||||
layer_command(COOP_CMD_LEAVE, nullptr);
|
||||
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 leaves_room = g_page == P_ACCEPT || g_page == P_REMOVE || g_page == P_RESET || g_page == P_LEAVE;
|
||||
if (leaves_room && !in_room(g_view)) close = true; // the room ended under the window
|
||||
else if (field_page()) field_window(fresh, scale, wrap, &close, &back);
|
||||
else if (g_page == P_ACCEPT) accept_window(fresh, scale, wrap, &close, &back);
|
||||
else if (g_page == P_REMOVE) remove_window(fresh, scale, &close, &back);
|
||||
else if (g_page == P_RESET) reset_window(fresh, scale, &close, &back);
|
||||
else if (g_page == P_LEAVE) leave_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;
|
||||
memset(g_field, 0, sizeof g_field);
|
||||
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_show_secret = false;
|
||||
memset(g_field, 0, sizeof g_field);
|
||||
}
|
||||
|
||||
int coop_test_set(const char *key, const char *value) {
|
||||
if (!strcmp(key, "NX2NAVI_COOP_PAGE")) {
|
||||
layer_read(&g_view, &g_offer, g_contrib, &g_ncontrib, &g_maker);
|
||||
if (!strcmp(value, "name")) open_field(P_NAME, cfg_value("NX2NAVI_COOP_NAME"), "NX2NAVI_COOP_NAME");
|
||||
else if (!strcmp(value, "server")) open_field(P_SERVER, cfg_value("NX2NAVI_COOP_SERVER"), "NX2NAVI_COOP_SERVER");
|
||||
else if (!strcmp(value, "join")) open_field(P_JOIN, "", "##coop_join");
|
||||
else if (!strcmp(value, "accept")) open_accept();
|
||||
else if (!strcmp(value, "leave")) open_window(P_LEAVE, "##coop_leave");
|
||||
else if (!strcmp(value, "reset")) open_window(P_RESET, "##coop_reset");
|
||||
else if (!strncmp(value, "remove:", 7)) {
|
||||
const int id = atoi(value + 7);
|
||||
int i = 0;
|
||||
while (i < g_view.n && g_view.member[i].id != id) i++;
|
||||
if (i == g_view.n) return 0;
|
||||
open_remove_member(g_view.member[i]);
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
g_by_pad = true; // the cursor as a pad's A would leave it: on the safe button
|
||||
} else if (!strcmp(key, "NX2NAVI_COOP_JOIN")) {
|
||||
char canon[COOP_SECRET_LEN + 1];
|
||||
layer_read(&g_view, &g_offer);
|
||||
if (layer_secret(value, canon)) command(COOP_CMD_JOIN, canon);
|
||||
else g_field_bad = true;
|
||||
} else if (!strcmp(key, "NX2NAVI_COOP_ACCEPT_OFFER")) {
|
||||
CoopView v;
|
||||
CoopOffer o;
|
||||
layer_read(&v, &o);
|
||||
if (o.token && !o.accepted) layer_accept(o);
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
// ---- toasts
|
||||
|
||||
enum { TOASTS = 3 };
|
||||
static struct {
|
||||
char text[COOP_NAME_MAX + 128];
|
||||
uint64_t until;
|
||||
} g_toast[TOASTS];
|
||||
static unsigned g_toast_version;
|
||||
static CoopPeer g_toast_room[COOP_MAX_MEMBERS]; // the members as last seen, to tell who came and went
|
||||
static int g_toast_n = -1; // -1: not in a room when last seen
|
||||
static bool g_toast_waiting; // the room waited for an answer when last seen
|
||||
|
||||
static void toast(UiTextId fmt, const char *arg) {
|
||||
int slot = 0;
|
||||
for (int i = 1; i < TOASTS; i++)
|
||||
if (g_toast[i].until < g_toast[slot].until) slot = i;
|
||||
snprintf(g_toast[slot].text, sizeof g_toast[slot].text, menu_text(fmt), arg);
|
||||
g_toast[slot].until = plat_now_ms() + 5000;
|
||||
}
|
||||
|
||||
static bool has(const CoopPeer *list, int n, int id) {
|
||||
for (int i = 0; i < n; i++)
|
||||
if (list[i].id == id) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool coop_toast_tick(void) {
|
||||
static unsigned cfg_seen = ~0u;
|
||||
static bool on;
|
||||
if (unsigned v = cfg_version(); v != cfg_seen) cfg_seen = v, on = cfg_bool("NX2NAVI_COOP") != 0;
|
||||
const uint64_t now = plat_now_ms();
|
||||
if (on) {
|
||||
CoopView v;
|
||||
CoopOffer o;
|
||||
layer_read(&v, &o);
|
||||
if (v.version != g_toast_version) {
|
||||
g_toast_version = v.version;
|
||||
const int n = in_room(v) ? v.n : -1;
|
||||
if (n >= 0 && g_toast_n >= 0 && !menu_is_open()) { // only changes within a room, not its first roster
|
||||
for (int i = 0; i < v.n; i++)
|
||||
if (v.member[i].id != v.self && !has(g_toast_room, g_toast_n, v.member[i].id))
|
||||
toast(UI_MENU_COOP_TOAST_JOINED, v.member[i].name);
|
||||
for (int i = 0; i < g_toast_n; i++)
|
||||
if (g_toast_room[i].id != v.self && !has(v.member, v.n, g_toast_room[i].id))
|
||||
toast(UI_MENU_COOP_TOAST_LEFT, g_toast_room[i].name);
|
||||
}
|
||||
g_toast_n = n;
|
||||
if (n > 0) memcpy(g_toast_room, v.member, sizeof(CoopPeer) * (size_t)n);
|
||||
}
|
||||
// a room that waits for an answer again (a new player, other rules): once per wait, not per offer
|
||||
const bool waiting = o.token && !o.accepted;
|
||||
if (waiting && !g_toast_waiting && !menu_is_open()) toast(UI_MENU_COOP_TOAST_OFFER, "");
|
||||
g_toast_waiting = waiting;
|
||||
}
|
||||
bool any = false;
|
||||
for (int i = 0; i < TOASTS; i++) any |= g_toast[i].until > now;
|
||||
return any;
|
||||
}
|
||||
|
||||
void coop_toast_draw(float w, float h, float scale) {
|
||||
(void)h;
|
||||
const uint64_t now = plat_now_ms();
|
||||
ImDrawList *dl = ImGui::GetForegroundDrawList();
|
||||
const float padx = 14 * scale, pady = 9 * scale;
|
||||
float y = 12 * scale;
|
||||
for (int i = 0; i < TOASTS; i++) {
|
||||
if (g_toast[i].until <= now) continue;
|
||||
// the top middle: the game's hearts and rupees are at the left, the performance overlay at the right; the same
|
||||
// small panel as that overlay
|
||||
const ImVec2 sz = ImGui::CalcTextSize(g_toast[i].text);
|
||||
const ImVec2 p(w * 0.5f - 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.6f, 0.9f);
|
||||
dl->AddText(ImVec2(p.x + padx, p.y + pady), SKIN_TEXT, g_toast[i].text);
|
||||
y += sz.y + pady * 2 + 6 * scale;
|
||||
}
|
||||
}
|
||||
25
runtime/ui/coop_page.h
Normal file
25
runtime/ui/coop_page.h
Normal file
@@ -0,0 +1,25 @@
|
||||
// The menu's Co-op tab (ui/coop_page.cpp, docs/coop.md): make, join, accept and leave a room. Present path only (ImGui).
|
||||
#pragma once
|
||||
|
||||
// Inside the page's opt_begin / opt_end. Not in a room: the player's name, the relay's address, Make a room, Join a
|
||||
// room, a status line, the rules of a room this player makes and the co-op switch. In a room: the room's offer while it
|
||||
// waits for an answer, the players (each one's Remove for the room's maker), the secret (hidden until asked) and its
|
||||
// copy, the room's rules (the maker changes them, the others read them) and Leave.
|
||||
void coop_rows(float scale);
|
||||
// After opt_end: the window a row opens: a name, an address or a secret to type, and the confirmations of Accept,
|
||||
// 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 and the secret is hidden again.
|
||||
void coop_cancel(void);
|
||||
// NX2NAVI_MENU_TEST_SET pseudo-keys (menu.cpp test_apply_sets): COOP_PAGE=name|server|join|accept|leave|remove:<id>
|
||||
// opens that window as its row does, COOP_JOIN=<secret> joins as the Join window's button does, COOP_ACCEPT_OFFER=1
|
||||
// accepts the room's offer as the Accept window's button does. 1 when key is one of them.
|
||||
int coop_test_set(const char *key, const char *value);
|
||||
|
||||
// Toasts over the game while the menu is closed: a player joined or left the room, a room waits for an answer.
|
||||
// coop_toast_tick on every overlay frame (menu open or not; it costs a copy of the co-op view while co-op is on): true
|
||||
// while a toast is to be drawn. coop_toast_draw draws them into the foreground of a w x h frame.
|
||||
bool coop_toast_tick(void);
|
||||
void coop_toast_draw(float w, float h, float scale);
|
||||
@@ -36,6 +36,7 @@ static int g_font_bad;
|
||||
#pragma clang diagnostic pop
|
||||
#include "ui/amiibo_page.h"
|
||||
#include "ui/binds_page.h"
|
||||
#include "ui/coop_page.h"
|
||||
#include "ui/option_rows.h"
|
||||
#include "ui/perf_panel.h"
|
||||
|
||||
@@ -139,7 +140,7 @@ extern "C" void menu_toggle(void) {
|
||||
}
|
||||
|
||||
// ---- events from the window adapter, queued while the menu is open; the present path hands them to ImGui
|
||||
enum { EV_KEY, EV_POS, EV_BUTTON, EV_WHEEL, EV_FOCUS, EV_MAX = 256 };
|
||||
enum { EV_KEY, EV_POS, EV_BUTTON, EV_WHEEL, EV_FOCUS, EV_CHAR, EV_MAX = 256 };
|
||||
struct Ev { int type, a, b; float x, y; };
|
||||
static Ev ev_q[EV_MAX];
|
||||
|
||||
@@ -162,6 +163,28 @@ 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}); }
|
||||
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.
|
||||
static PlatMutex paste_lock = PLAT_MUTEX_INIT;
|
||||
static char paste_text[256];
|
||||
static int paste_ready;
|
||||
|
||||
extern "C" void menu_event_paste(const char *utf8) {
|
||||
plat_mutex_lock(&paste_lock);
|
||||
snprintf(paste_text, sizeof paste_text, "%s", utf8 ? utf8 : "");
|
||||
paste_ready = 1;
|
||||
plat_mutex_unlock(&paste_lock);
|
||||
}
|
||||
|
||||
extern "C" int menu_paste_take(char *out, size_t cap) {
|
||||
plat_mutex_lock(&paste_lock);
|
||||
int ready = paste_ready;
|
||||
if (ready && cap) snprintf(out, cap, "%s", paste_text);
|
||||
paste_ready = 0;
|
||||
plat_mutex_unlock(&paste_lock);
|
||||
return ready;
|
||||
}
|
||||
|
||||
static void drain_events(ImGuiIO &io) {
|
||||
Ev q[EV_MAX];
|
||||
@@ -183,6 +206,7 @@ static void drain_events(ImGuiIO &io) {
|
||||
case EV_BUTTON: io.AddMouseButtonEvent(e.a, e.b != 0); break;
|
||||
case EV_WHEEL: io.AddMouseWheelEvent(e.x, e.y); break;
|
||||
case EV_FOCUS: io.AddFocusEvent(e.a != 0); break;
|
||||
case EV_CHAR: io.AddInputCharacter((unsigned)e.a); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -452,7 +476,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_BOOT_TITLE};
|
||||
UI_MENU_TAB_CONTROLS, UI_MENU_TAB_COOP, UI_BOOT_TITLE};
|
||||
for (int i = 0; i < N; i++) {
|
||||
if (!data[i]) continue;
|
||||
ImFontGlyphRangesBuilder b;
|
||||
@@ -509,34 +533,44 @@ extern "C" void menu_vk_release(void) {
|
||||
}
|
||||
|
||||
// ---- test hooks
|
||||
// NX2NAVI_MENU_TEST=<frame>[:<frames per page>]: at that presented frame the menu opens on its first tab; each tab stays
|
||||
// <frames per page> frames (default 30) and its last frame's swapchain image goes to NX2NAVI_MENU_TEST_DIR (default: the
|
||||
// working directory) as menu-test-<frame>-<page>.png; after the last tab the menu closes.
|
||||
// NX2NAVI_MENU_TEST=<frame>[,<frame>...][:<frames per page>]: at each such presented frame (up to 8) the menu opens on
|
||||
// its first tab; each tab stays <frames per page> frames (default 30) and its last frame's swapchain image goes to
|
||||
// NX2NAVI_MENU_TEST_DIR (default: the working directory) as menu-test-<frame>-<page>.png; after the last tab the menu
|
||||
// closes.
|
||||
// NX2NAVI_MENU_TEST_CLICK=<key>:<part>[,...]: mouse clicks on the rows of the page shown (ui/option_rows.cpp click_test).
|
||||
// NX2NAVI_MENU_TEST_SET=<frame>:<key>=<value>[,<key>=<value>...][;<frame>:...]: cfg_set of each key (NX2NAVI_ prefix
|
||||
// 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.
|
||||
enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_COUNT }; // Ocarina of Time: the options this port has
|
||||
enum { TEST_PAGE_FRAMES = 30, TEST_SETS = 16 };
|
||||
// (opt_focus_key), so a page's shot shows a row below the first screenful; it does not switch tabs. COOP_PAGE, COOP_JOIN
|
||||
// and COOP_ACCEPT_OFFER drive 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 };
|
||||
enum { TEST_PAGE_FRAMES = 30, TEST_SETS = 16, TEST_OPENS = 8 };
|
||||
struct TestSet { uint64_t frame; char key[64], value[64]; };
|
||||
static struct {
|
||||
int parsed;
|
||||
uint64_t at; // NX2NAVI_MENU_TEST frame; 0 none
|
||||
uint64_t at[TEST_OPENS]; // NX2NAVI_MENU_TEST frames, in order
|
||||
int n_at, next_at; // how many; the next to open at
|
||||
uint64_t per_page;
|
||||
uint64_t opened; // the frame the hook opened the menu; 0 not yet
|
||||
int page; // the tab being shot; -1 none
|
||||
TestSet sets[TEST_SETS];
|
||||
int n_sets, next_set; // NX2NAVI_MENU_TEST_SET, in frame order
|
||||
} g_test = {0, 0, 0, 0, -1, {}, 0, 0};
|
||||
} g_test = {0, {}, 0, 0, 0, 0, -1, {}, 0, 0};
|
||||
|
||||
static void test_parse(void) {
|
||||
g_test.parsed = 1;
|
||||
if (const char *e = cfg_get("NX2NAVI_MENU_TEST")) {
|
||||
long long at = atoll(e), per = 0;
|
||||
long long per = 0;
|
||||
if (const char *c = strchr(e, ':')) per = atoll(c + 1);
|
||||
g_test.at = at > 0 ? (uint64_t)at : 0;
|
||||
for (const char *s = e; *s && *s != ':' && g_test.n_at < TEST_OPENS;) {
|
||||
char *end;
|
||||
unsigned long long at = strtoull(s, &end, 10);
|
||||
if (end == s) break;
|
||||
if (at > 0 && (!g_test.n_at || at > g_test.at[g_test.n_at - 1])) g_test.at[g_test.n_at++] = at;
|
||||
s = *end == ',' ? end + 1 : end;
|
||||
}
|
||||
g_test.per_page = per > 0 ? (uint64_t)per : TEST_PAGE_FRAMES;
|
||||
}
|
||||
const char *s = cfg_get("NX2NAVI_MENU_TEST_SET");
|
||||
@@ -561,22 +595,30 @@ static void test_parse(void) {
|
||||
while (*s && *s != ';') s++;
|
||||
if (*s == ';') s++;
|
||||
}
|
||||
if (g_test.at || g_test.n_sets)
|
||||
rt_log("menu: test hook: open at frame %llu, %llu frames per page, %d settings changes",
|
||||
(unsigned long long)g_test.at, (unsigned long long)g_test.per_page, g_test.n_sets);
|
||||
if (g_test.n_at || g_test.n_sets)
|
||||
rt_log("menu: test hook: open at frame %llu (%d times), %llu frames per page, %d settings changes",
|
||||
(unsigned long long)(g_test.n_at ? g_test.at[0] : 0), g_test.n_at, (unsigned long long)g_test.per_page,
|
||||
g_test.n_sets);
|
||||
}
|
||||
|
||||
static void test_apply_sets(uint64_t frame) {
|
||||
for (; g_test.next_set < g_test.n_sets && g_test.sets[g_test.next_set].frame <= frame; g_test.next_set++) {
|
||||
const TestSet &t = g_test.sets[g_test.next_set];
|
||||
rt_log("menu: test hook: frame %llu: %s=%s", (unsigned long long)frame, t.key, t.value);
|
||||
// a room's secret stays out of the log here too
|
||||
const bool secret = !strcmp(t.key, "NX2NAVI_COOP_JOIN") || !strcmp(t.key, "NX2NAVI_COOP_ROOM");
|
||||
rt_log("menu: test hook: frame %llu: %s=%s", (unsigned long long)frame, t.key, secret ? "(set, not shown)" : t.value);
|
||||
if (!strcmp(t.key, "NX2NAVI_SAVE")) {
|
||||
rt_log("menu: test hook: cfg_save %s", cfg_save() ? "wrote" : "failed");
|
||||
} else if (!strcmp(t.key, "NX2NAVI_FOCUS")) {
|
||||
char row[80];
|
||||
snprintf(row, sizeof row, "%s%s", strncmp(t.value, "NX2NAVI_", strlen("NX2NAVI_")) ? "NX2NAVI_" : "", t.value);
|
||||
opt_focus_key(row);
|
||||
} else {
|
||||
} else if (!strncmp(t.key, "NX2NAVI_COOP_", 13) && !cfg_from_env("NX2NAVI_MENU_TEST_SET")) {
|
||||
// From nx2navi.ini the hook sets no co-op key and drives no part of the Co-op tab: a settings file
|
||||
// someone hands a player could otherwise turn co-op on, join a room and accept its offer for them
|
||||
// (COOP_JOIN, COOP_ACCEPT_OFFER). 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)) {
|
||||
cfg_set(t.key, t.value);
|
||||
}
|
||||
}
|
||||
@@ -1402,7 +1444,16 @@ static void tab_controls(float scale) {
|
||||
binds_after_page();
|
||||
}
|
||||
|
||||
static const UiTextId kTabNames[TAB_COUNT] = {UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND, UI_MENU_TAB_CONTROLS};
|
||||
// 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};
|
||||
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
|
||||
@@ -1488,7 +1539,9 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) {
|
||||
ImGui::TextDisabled("%s", version);
|
||||
}
|
||||
|
||||
int step = g_modal || binds_modal() ? 0
|
||||
// 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;
|
||||
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
|
||||
: 0;
|
||||
@@ -1520,6 +1573,7 @@ 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();
|
||||
}
|
||||
@@ -1579,7 +1633,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();
|
||||
bool was_modal = g_modal || binds_modal() || coop_modal() || ImGui::GetIO().WantTextInput;
|
||||
if (!was_modal && (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)))
|
||||
set_open(0);
|
||||
ImGui::End();
|
||||
@@ -1735,7 +1789,7 @@ static void perf_draw(const MenuTarget *t, float scale) {
|
||||
dl->AddText(ImVec2(p.x + padx, p.y + pady), SKIN_TEXT, g_perf_text);
|
||||
}
|
||||
|
||||
extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot) {
|
||||
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)
|
||||
VkPhysicalDeviceProperties props;
|
||||
@@ -1750,6 +1804,7 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha
|
||||
if (g_perf_save.exchange(0)) cfg_save();
|
||||
perf_tick(plat_now_ns(), t);
|
||||
amiibo_tick();
|
||||
const bool toast = coop_toast_tick(); // a co-op player came or went: a toast over the game, the menu closed
|
||||
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
|
||||
@@ -1759,13 +1814,13 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha
|
||||
was_open = open;
|
||||
if (!open) {
|
||||
if (g_save_pending) g_save_pending = opt_save_tick(1); // closed: the last change goes to nx2navi.ini now
|
||||
if (g_test.at && !g_test.opened && frame >= g_test.at) {
|
||||
if (g_test.next_at < g_test.n_at && !g_test.opened && frame >= g_test.at[g_test.next_at]) {
|
||||
g_test.opened = frame;
|
||||
g_test.page = 0;
|
||||
g_tab_request = 0;
|
||||
set_open(1);
|
||||
open = true;
|
||||
} else if (!g_perf_mode) {
|
||||
} else if (!g_perf_mode && !toast) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1799,6 +1854,7 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha
|
||||
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 and its secret hides
|
||||
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
|
||||
@@ -1823,6 +1879,7 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha
|
||||
ImGui::NewFrame();
|
||||
if (open) layout_menu(t->width, t->height, scale);
|
||||
perf_draw(t, scale);
|
||||
if (!open && toast) coop_toast_draw((float)t->width, (float)t->height, scale);
|
||||
ImGui::Render();
|
||||
if (open) g_save_pending = opt_save_tick(0);
|
||||
g_cost_ns += plat_now_ns() - t0;
|
||||
@@ -1833,6 +1890,7 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha
|
||||
*shot = path;
|
||||
if (++g_test.page == TAB_COUNT) {
|
||||
g_test.page = -1;
|
||||
g_test.opened = 0, g_test.next_at++; // the next NX2NAVI_MENU_TEST frame opens it again
|
||||
set_open(0); // the next frame lays out nothing
|
||||
} else {
|
||||
g_tab_request = g_test.page;
|
||||
@@ -1841,6 +1899,16 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha
|
||||
return ImGui::GetDrawData()->TotalVtxCount > 0;
|
||||
}
|
||||
|
||||
// A text field takes typing: the window delivers characters (and a handheld shows its keyboard) while one is active.
|
||||
// Every overlay frame lets the window follow, also those overlay_frame leaves early because the menu is closed: when
|
||||
// only the frames the menu laid out did, closing it with a field active (F1, Minus and Plus) left SDL's text input on,
|
||||
// and on Windows the input method attached to the game window, until the menu opened again.
|
||||
extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot) {
|
||||
int r = overlay_frame(frame, t, shot);
|
||||
menu_text_input_follow(g_ctx_ok && g_open.load(std::memory_order_relaxed) && ImGui::GetIO().WantTextInput);
|
||||
return r;
|
||||
}
|
||||
|
||||
// ---- the boot screen (boot.c's wait for the prewarm; gfx_present_boot presents it on a black frame)
|
||||
|
||||
static std::atomic<int> g_boot_phase;
|
||||
|
||||
@@ -34,6 +34,10 @@ void menu_event_mouse_pos(float x, float y);
|
||||
void menu_event_mouse_button(int button, int down); // 0 left, 1 right, 2 middle
|
||||
void menu_event_wheel(float dx, float dy);
|
||||
void menu_event_focus(int focused);
|
||||
void menu_event_char(unsigned c); // a character typed, a Unicode code point (a text field takes it)
|
||||
void menu_event_paste(const char *utf8); // the clipboard's text gfx_window_paste read ("" none), on the window thread
|
||||
// The text the last gfx_window_paste brought, once: 1 and the text in out (cap bytes), 0 while none has arrived.
|
||||
int menu_paste_take(char *out, size_t cap);
|
||||
|
||||
// ---- the overlay, drawn into the swapchain image after the game image (gfx_present.c, present lock held)
|
||||
typedef struct {
|
||||
@@ -63,11 +67,18 @@ void menu_vk_release(void); // before the device goes away (gfx_wi
|
||||
// The check the font atlas runs on a system font, on the embedded font and damaged copies of it: 1 when it takes the
|
||||
// whole font and refuses a cut-off one, one without a character map and one with an unknown tag (--probe-window).
|
||||
int menu_font_check(void);
|
||||
// The window's text input follows the menu's text fields (ui/menu_text_input.cpp): menu_overlay_frame calls this on
|
||||
// each of its frames, those of a closed menu too, with whether the open menu has a field taking typing, and it calls
|
||||
// gfx_window_text_input when that changes.
|
||||
void menu_text_input_follow(int want);
|
||||
|
||||
// ---- what the menu asks of the platform side (gfx_window_win.c, gfx_window_sdl.c)
|
||||
void gfx_window_apply_settings(void); // NX2NAVI_FULLSCREEN or NX2NAVI_WINDOW_SIZE changed: the window follows
|
||||
void gfx_window_request_close(void); // as the window's close button: the process ends
|
||||
void gfx_window_request_restart(void); // the same, then nx2navi.exe starts again with the same command line
|
||||
void gfx_window_text_input(int on); // a menu text field is active (on) or no longer: the window delivers typed
|
||||
// characters to menu_event_char meanwhile, and a handheld shows its keyboard
|
||||
void gfx_window_paste(void); // reads the clipboard on the window thread and hands it to menu_event_paste
|
||||
int gfx_window_monitor_size(int *w, int *h); // pixels of the monitor the window is on; 0 when unknown
|
||||
double gfx_window_refresh_hz(void); // its refresh rate (NX2NAVI_FPS_LIMIT=display); 0 when unknown
|
||||
unsigned gfx_window_dpi(void); // the window's DPI (96 at 100% display scale); any thread
|
||||
|
||||
@@ -60,6 +60,15 @@ extern "C" void menu_sdl_event(const SDL_Event *e) {
|
||||
if (!menu_is_open()) return;
|
||||
if (ImGuiKey k = key_of(e->key.scancode)) menu_event_key(k, e->type == SDL_EVENT_KEY_DOWN);
|
||||
return;
|
||||
case SDL_EVENT_TEXT_INPUT: // UTF-8, between SDL_StartTextInput and SDL_StopTextInput (gfx_window_text_input)
|
||||
if (!menu_is_open() || !e->text.text) return;
|
||||
for (const unsigned char *p = (const unsigned char *)e->text.text; *p;) {
|
||||
unsigned c = *p++, more = c >= 0xf0 ? 3 : c >= 0xe0 ? 2 : c >= 0xc0 ? 1 : 0;
|
||||
if (more) c &= 0x3f >> more;
|
||||
for (; more && (*p & 0xc0) == 0x80; more--) c = c << 6 | (*p++ & 0x3f);
|
||||
if (!more && c >= 0x20 && c != 0x7f) menu_event_char(c);
|
||||
}
|
||||
return;
|
||||
case SDL_EVENT_MOUSE_MOTION:
|
||||
if (menu_is_open()) menu_event_mouse_pos(e->motion.x * d, e->motion.y * d);
|
||||
return;
|
||||
|
||||
12
runtime/ui/menu_text_input.cpp
Normal file
12
runtime/ui/menu_text_input.cpp
Normal file
@@ -0,0 +1,12 @@
|
||||
// The window's text input follows the menu's text fields (ui/menu.h menu_text_input_follow). Its own file, so that a
|
||||
// page test can run the same switch the menu does without the menu's Vulkan side.
|
||||
#include "ui/menu.h"
|
||||
|
||||
static int g_text_on; // what the window was last told; off at start, as the window makes it
|
||||
|
||||
void menu_text_input_follow(int want) {
|
||||
want = want != 0;
|
||||
if (want == g_text_on) return;
|
||||
g_text_on = want;
|
||||
gfx_window_text_input(want);
|
||||
}
|
||||
@@ -69,6 +69,18 @@ extern "C" int menu_window_msg(HWND h, UINT m, WPARAM w, LPARAM l, LRESULT *res)
|
||||
if (!menu_is_open()) return 0;
|
||||
if (ImGuiKey k = key_of(w)) menu_event_key(k, m == WM_KEYDOWN || m == WM_SYSKEYDOWN);
|
||||
return 0; // F11 and the system keys keep working
|
||||
case WM_CHAR: { // UTF-16 units (TranslateMessage); a character outside the BMP comes as a surrogate pair
|
||||
static unsigned high;
|
||||
unsigned c = (unsigned)w;
|
||||
if (c >= 0xd800 && c < 0xdc00) {
|
||||
high = c;
|
||||
return 0;
|
||||
}
|
||||
if (c >= 0xdc00 && c < 0xe000) c = high ? 0x10000 + ((high - 0xd800) << 10) + (c - 0xdc00) : 0;
|
||||
high = 0;
|
||||
if (menu_is_open() && c >= 0x20 && c != 0x7f) menu_event_char(c);
|
||||
return 0;
|
||||
}
|
||||
case WM_MOUSEMOVE:
|
||||
if (menu_is_open()) menu_event_mouse_pos((float)GET_X_LPARAM(l), (float)GET_Y_LPARAM(l));
|
||||
return 0;
|
||||
|
||||
@@ -557,6 +557,146 @@ 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",
|
||||
[UI_MENU_COOP_ON_DESC] = "Play with friends, each in their own game and save: a room on a relay shares story progress "
|
||||
"between them by its rules (docs/coop.md). Off: the game uses no network at all. Make a room "
|
||||
"and Join a room turn it on.",
|
||||
[UI_MENU_COOP_NAME] = "Your name",
|
||||
[UI_MENU_COOP_NAME_DESC] = "The name the other players in a room see; the relay sees it too. At most 24 bytes. Empty: "
|
||||
"Player- and four random digits.",
|
||||
[UI_MENU_COOP_AUTO] = "automatic",
|
||||
[UI_MENU_COOP_SERVER] = "Relay address",
|
||||
[UI_MENU_COOP_SERVER_DESC] = "The relay that connects the players' games: host, host:port or [IPv6]:port (port 24680 "
|
||||
"when none is given). Whoever runs it (python tools/coop_relay.py) gives its address to "
|
||||
"the others. The log and the system info do not show it.",
|
||||
[UI_MENU_COOP_NONE] = "none",
|
||||
[UI_MENU_COOP_MAKE] = "Make a room",
|
||||
[UI_MENU_COOP_MAKE_DESC] = "Makes a room with a new secret of 18 characters, which you pass on to the players you "
|
||||
"invite (by voice or a private message). A room you make shares by the rules below, and you "
|
||||
"can change them while you play.",
|
||||
[UI_MENU_COOP_JOIN] = "Join a room",
|
||||
[UI_MENU_COOP_JOIN_DESC] = "Joins the room whose secret another player gave you. Nothing from the room reaches your "
|
||||
"save until you have seen who is in it and what it shares, and accepted it here.",
|
||||
[UI_MENU_COOP_NEED_SERVER] = "set the relay address first",
|
||||
[UI_MENU_COOP_SECRET] = "Room secret",
|
||||
[UI_MENU_COOP_SECRET_HINT] = "18 characters, as XXXXXX-XXXXXX-XXXXXX: any case, with or without dashes.",
|
||||
[UI_MENU_COOP_SECRET_BAD] = "This is not a room secret: it has 18 characters of 23456789BCDFGHJKMNPRSTVWXYZ.",
|
||||
[UI_MENU_COOP_PASTE] = "Paste", [UI_MENU_COOP_PASTE_EMPTY] = "The clipboard has no text.",
|
||||
[UI_MENU_COOP_OK] = "OK", [UI_MENU_COOP_STOP] = "Stop",
|
||||
[UI_MENU_COOP_STOP_DESC] = "Stops trying to reach the room.",
|
||||
[UI_MENU_COOP_CONNECTING] = "Connecting: %s",
|
||||
[UI_MENU_COOP_RECONNECTING] = "The relay went silent; getting back into the room: %s",
|
||||
[UI_MENU_COOP_LEFT] = "Not in a room: %s",
|
||||
[UI_MENU_COOP_NO_ROOM] = "No open room on the relay has this secret: check it, or ask its maker whether the room is "
|
||||
"still open.",
|
||||
[UI_MENU_COOP_NOT_STARTED] = "Co-op did not start; the log says why.",
|
||||
[UI_MENU_COOP_PLAYERS] = "Players", [UI_MENU_COOP_YOU] = "you", [UI_MENU_COOP_MAKER] = "made the room",
|
||||
[UI_MENU_COOP_HEARD] = "heard %u s ago", [UI_MENU_COOP_NOT_HEARD] = "not heard from yet", [UI_MENU_COOP_AWAY] = "away",
|
||||
[UI_MENU_COOP_MEMBER_DESC] = "A player in the room. Heard: when a message of theirs last arrived sealed with the "
|
||||
"room's secret; a player not heard from yet has not shown that they know it.",
|
||||
[UI_MENU_COOP_REMOVE] = "Remove",
|
||||
[UI_MENU_COOP_REMOVE_DESC] = "As the room's maker you can remove a player by their key: every game drops that key and "
|
||||
"gives back what it took from the pools, and the relay drops the player and refuses them "
|
||||
"again. Someone who knows the secret can come back under a new key, and everyone then gets "
|
||||
"a new offer to accept or not; to be sure, make a new room.",
|
||||
[UI_MENU_COOP_REMOVE_CONFIRM] = "Remove %s from the room?",
|
||||
[UI_MENU_COOP_SECRET_DESC] = "Anyone who has the secret can join the room: pass it on only to the players you invite, "
|
||||
"by voice or a private message. It shows only when you ask; hide it before you share your "
|
||||
"screen. The relay never learns it.",
|
||||
[UI_MENU_COOP_SHOW] = "press to show", [UI_MENU_COOP_HIDE] = "press to hide",
|
||||
[UI_MENU_COOP_COPY] = "Copy the secret",
|
||||
[UI_MENU_COOP_COPY_DESC] = "Puts the room's secret on the clipboard, to paste into a private message.",
|
||||
[UI_MENU_COOP_OFFER] = "This room waits for your answer",
|
||||
[UI_MENU_COOP_OFFER_WHO] = "In the room: %s.", [UI_MENU_COOP_OFFER_NOBODY] = "nobody else yet",
|
||||
[UI_MENU_COOP_OFFER_SHARED] = "Shared by everyone: %s.", [UI_MENU_COOP_OFFER_POOLED] = "In one pool for everyone: %s.",
|
||||
[UI_MENU_COOP_OFFER_NOTHING] = "The rules share nothing.",
|
||||
[UI_MENU_COOP_OFFER_COPY] = "Nothing from the room reaches your save before you accept. Then your whole save (every "
|
||||
"slot) is first copied to coop-backup/<date and time> in the profile folder, and only after "
|
||||
"that does the room's progress arrive.",
|
||||
[UI_MENU_COOP_OFFER_TRUST] = "A player in the room can do in your world what the rules share (open a chest, spend a "
|
||||
"pooled key), and the game cannot undo it: accept only players you trust with your save.",
|
||||
[UI_MENU_COOP_ANSWER] = "Accept or not",
|
||||
[UI_MENU_COOP_ANSWER_DESC] = "Shows the offer with Accept and Not now. A new player or other rules make a new offer, "
|
||||
"which waits for your answer again.",
|
||||
[UI_MENU_COOP_ACCEPT_CONFIRM] = "Accept this room?", [UI_MENU_COOP_ACCEPT] = "Accept", [UI_MENU_COOP_NOT_NOW] = "Not now",
|
||||
[UI_MENU_COOP_ACCEPTED] = "Accepted: the room's progress reaches your save. Your save as it was is in coop-backup in "
|
||||
"the profile folder.",
|
||||
[UI_MENU_COOP_COPY_FAILED] = "Accepted, but your save could not be copied, so nothing from the room is applied; the "
|
||||
"log says why.",
|
||||
[UI_MENU_COOP_RULES_ROOM] = "The room's rules", [UI_MENU_COOP_RULES_MINE] = "Rules of a room you make",
|
||||
[UI_MENU_COOP_RULES_UNKNOWN] = "The room's rules have not arrived yet.",
|
||||
[UI_MENU_COOP_RULES_CHANGE] = "A change is a new offer: the others take nothing more from the room until they accept it.",
|
||||
[UI_MENU_COOP_RULES_SET_BY] = "set by the room's maker", [UI_MENU_COOP_RULE_FOLLOWS] = "follows Progress",
|
||||
[UI_MENU_COOP_R_PROGRESS] = "Progress", [UI_MENU_COOP_R_ITEMS] = "Items", [UI_MENU_COOP_R_SONGS] = "Songs",
|
||||
[UI_MENU_COOP_R_QUEST] = "Quest items", [UI_MENU_COOP_R_KEYS] = "Small keys", [UI_MENU_COOP_R_RUPEES] = "Rupees",
|
||||
[UI_MENU_COOP_R_AMMO] = "Ammunition",
|
||||
[UI_MENU_COOP_R_PROGRESS_DESC] = "Story, world and dungeon flags: events, talks, chests, doors, switches, bosses, map "
|
||||
"and compass. Shared: what one player does happens in every world. Own: each world "
|
||||
"keeps its own, and small keys are then own too.",
|
||||
[UI_MENU_COOP_R_ITEMS_DESC] = "Equipment, key items, bottles owned, wallet, bag and quiver sizes, magic meter size; of "
|
||||
"a count, the highest wins. Own is possible only with Progress own: in a shared world a "
|
||||
"chest one player opened is empty for the others.",
|
||||
[UI_MENU_COOP_R_SONGS_DESC] = "The songs learned. Own is possible only with Progress own.",
|
||||
[UI_MENU_COOP_R_QUEST_DESC] = "Medallions, spiritual stones, the Stone of Agony and the Gerudo card. Own is possible "
|
||||
"only with Progress own.",
|
||||
[UI_MENU_COOP_R_KEYS_DESC] = "Small keys, per dungeon. Pool: a key anyone picks up goes into the dungeon's pool and a "
|
||||
"door anyone opens takes one out. Own with Progress own.",
|
||||
[UI_MENU_COOP_R_RUPEES_DESC] = "Pool: one purse that every player adds to and spends from. Own: each keeps their own.",
|
||||
[UI_MENU_COOP_R_AMMO_DESC] = "Bombs, bombchus, arrows, deku nuts, seeds and sticks, magic beans. Pool: one count that "
|
||||
"every player adds to and spends from.",
|
||||
[UI_MENU_COOP_SHARED] = "shared", [UI_MENU_COOP_OWN] = "own", [UI_MENU_COOP_POOL] = "pool",
|
||||
[UI_MENU_COOP_LEAVE] = "Leave the room",
|
||||
[UI_MENU_COOP_LEAVE_DESC] = "Leaves the room. What the room gave your save stays in it.",
|
||||
[UI_MENU_COOP_LEAVE_CONFIRM] = "Leave the room? What it gave your save stays.",
|
||||
[UI_MENU_COOP_LEAVE_MAKER] = "You made this room: while you are away nobody can change its rules or remove a player, "
|
||||
"and if nobody else is in it, it closes.",
|
||||
[UI_MENU_COOP_STAY] = "Stay",
|
||||
[UI_MENU_COOP_TOAST_JOINED] = "%s joined the room", [UI_MENU_COOP_TOAST_LEFT] = "%s left the room",
|
||||
[UI_MENU_COOP_TOAST_OFFER] = "The co-op room waits for your answer in the menu's Co-op tab",
|
||||
[UI_MENU_COOP_LOST] = "The relay lost the room; the game is getting back into it.",
|
||||
[UI_MENU_COOP_JOIN_LIMIT] = "The relay takes no more joins from your network for now; the game tries again in a minute.",
|
||||
[UI_MENU_COOP_NOT_IDENTIFIED] = "not identified", [UI_MENU_COOP_REMOVED] = "removed by the maker",
|
||||
[UI_MENU_COOP_KEY] = "key %s",
|
||||
[UI_MENU_COOP_OFFER_KEY] = "The rules are signed by key %s.",
|
||||
[UI_MENU_COOP_OFFER_COMPARE] = "Before you accept, ask the room's maker to read you their key, by voice or chat, and "
|
||||
"compare it with this one.",
|
||||
[UI_MENU_COOP_MY_KEY] = "Your key, which signs this room's rules: %s. Read it to the others, by voice or chat, so that "
|
||||
"they can compare it before they accept.",
|
||||
[UI_MENU_COOP_UNIDENTIFIED] = "Players in the room who are not identified: %d (they have not said who they are, or two "
|
||||
"keys say they are the same player). Nobody can accept the room while they are in it: the "
|
||||
"maker can remove them, or everyone moves to a new room.",
|
||||
[UI_MENU_COOP_DISAGREE] = "The players carry rules signed by different keys: ask the room's maker which key is theirs "
|
||||
"before you accept.",
|
||||
[UI_MENU_COOP_NEW_SAVE] = "Another save is played in this room: it gets the room's progress, which holds what the last "
|
||||
"save brought.",
|
||||
[UI_MENU_COOP_WARNINGS] = "Before you join a room with strangers",
|
||||
[UI_MENU_COOP_WARN_SAVE] = "1. Keep a save you can go back to. Anyone you accept can set story flags in your save, and so "
|
||||
"can anyone they accepted; a player in your pools can empty a dungeon's small keys. No "
|
||||
"removal takes a flag back: the copy in coop-backup/first-<date and time> does.",
|
||||
[UI_MENU_COOP_WARN_ROOM] = "2. Your acceptance is yours, the room is not. The players you accept pass on the flags of the "
|
||||
"players they accepted, and the maker alone decides who may use the pools. If anyone you do "
|
||||
"not know is in the room, do not accept: leave, and ask the maker for a new room.",
|
||||
[UI_MENU_COOP_WARN_KEY] = "3. Check the maker's key, and keep yours to yourself. Compare the key that signs the rules "
|
||||
"with the maker's, never start the game with settings or a script someone hands you, and "
|
||||
"never hand out a copy of your profile folder.",
|
||||
[UI_MENU_COOP_POOLS] = "Pools",
|
||||
[UI_MENU_COOP_SPENT] = "took %lld keys, %lld rupees, %lld ammunition beyond what it brought",
|
||||
[UI_MENU_COOP_NOT_IN_ROOM] = "not in the room",
|
||||
[UI_MENU_COOP_SPENT_NONE] = "Nobody took more from the pools than they brought.",
|
||||
[UI_MENU_COOP_SPENT_DESC] = "This key took more from the pools than it brought. A player who used keys others found is "
|
||||
"listed too; one nobody expected drained the pools. Removing the key gives back what it "
|
||||
"took, in every game, also after the player left. Remove it before a pool reset: a reset "
|
||||
"keeps what a player still in the room took.",
|
||||
[UI_MENU_COOP_RESET] = "Reset the pools",
|
||||
[UI_MENU_COOP_RESET_DESC] = "Every game joins the pools again with what it held for the players in the room. This "
|
||||
"recovers a pool that a player who left had emptied; flags stay as they are. A player who "
|
||||
"drained a pool and is still in the room keeps what they took: remove them first, then reset.",
|
||||
[UI_MENU_COOP_RESET_CONFIRM] = "Reset the pools for everyone in the room?",
|
||||
[UI_MENU_COOP_REMOVE_KEY_CONFIRM] = "Remove %s, key %s, from the room?",
|
||||
[UI_MENU_COOP_NOT_ACCEPTED] = "Not accepted: the room changed or a player in it is not identified. Look at the offer "
|
||||
"again.",
|
||||
[UI_MENU_COOP_ACCEPTED_AS] = "a key you accepted as %s",
|
||||
[UI_BOOT_TITLE] = "Preparing shaders",
|
||||
[UI_BOOT_STARTING] = "Starting", [UI_BOOT_SHADERS] = "Shaders: %lld of %lld", [UI_BOOT_PIPELINES] = "Pipelines: %lld of %lld",
|
||||
[UI_MENU_UPSCALING] = "Upscaling",
|
||||
@@ -1133,6 +1273,149 @@ 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] = "Игра с друзьями, у каждого своя игра и своё сохранение: комната на ретрансляторе делит между "
|
||||
"ними прогресс сюжета по своим правилам (docs/coop.md). Выкл.: игра совсем не использует "
|
||||
"сеть. «Создать комнату» и «Войти в комнату» включают его.",
|
||||
[UI_MENU_COOP_NAME] = "Ваше имя",
|
||||
[UI_MENU_COOP_NAME_DESC] = "Имя, которое видят другие игроки в комнате; его видит и ретранслятор. Не больше 24 байт. "
|
||||
"Пусто: Player- и четыре случайные цифры.",
|
||||
[UI_MENU_COOP_AUTO] = "автоматически",
|
||||
[UI_MENU_COOP_SERVER] = "Адрес ретранслятора",
|
||||
[UI_MENU_COOP_SERVER_DESC] = "Ретранслятор, который соединяет игры игроков: host, host:port или [IPv6]:port (порт "
|
||||
"24680, если не указан). Тот, кто его запускает (python tools/coop_relay.py), сообщает "
|
||||
"адрес остальным. Журнал и сведения о системе его не показывают.",
|
||||
[UI_MENU_COOP_NONE] = "нет",
|
||||
[UI_MENU_COOP_MAKE] = "Создать комнату",
|
||||
[UI_MENU_COOP_MAKE_DESC] = "Создаёт комнату с новым секретом из 18 символов, который вы передаёте приглашённым игрокам "
|
||||
"(голосом или личным сообщением). Созданная вами комната делит прогресс по правилам ниже, и "
|
||||
"их можно менять во время игры.",
|
||||
[UI_MENU_COOP_JOIN] = "Войти в комнату",
|
||||
[UI_MENU_COOP_JOIN_DESC] = "Входит в комнату, секрет которой вам дал другой игрок. Ничего из комнаты не попадёт в ваше "
|
||||
"сохранение, пока вы не увидите, кто в ней и что она делит, и не примете её здесь.",
|
||||
[UI_MENU_COOP_NEED_SERVER] = "сначала укажите адрес ретранслятора",
|
||||
[UI_MENU_COOP_SECRET] = "Секрет комнаты",
|
||||
[UI_MENU_COOP_SECRET_HINT] = "18 символов, вида XXXXXX-XXXXXX-XXXXXX: в любом регистре, с дефисами или без.",
|
||||
[UI_MENU_COOP_SECRET_BAD] = "Это не секрет комнаты: в нём 18 символов из 23456789BCDFGHJKMNPRSTVWXYZ.",
|
||||
[UI_MENU_COOP_PASTE] = "Вставить", [UI_MENU_COOP_PASTE_EMPTY] = "В буфере обмена нет текста.",
|
||||
[UI_MENU_COOP_OK] = "ОК", [UI_MENU_COOP_STOP] = "Остановить",
|
||||
[UI_MENU_COOP_STOP_DESC] = "Перестаёт пытаться попасть в комнату.",
|
||||
[UI_MENU_COOP_CONNECTING] = "Подключение: %s",
|
||||
[UI_MENU_COOP_RECONNECTING] = "Ретранслятор замолчал; возвращение в комнату: %s",
|
||||
[UI_MENU_COOP_LEFT] = "Не в комнате: %s",
|
||||
[UI_MENU_COOP_NO_ROOM] = "На ретрансляторе нет открытой комнаты с этим секретом: проверьте его или спросите создателя, "
|
||||
"открыта ли ещё комната.",
|
||||
[UI_MENU_COOP_NOT_STARTED] = "Кооператив не запустился; причина в журнале.",
|
||||
[UI_MENU_COOP_PLAYERS] = "Игроки", [UI_MENU_COOP_YOU] = "вы", [UI_MENU_COOP_MAKER] = "создатель комнаты",
|
||||
[UI_MENU_COOP_HEARD] = "на связи %u с назад", [UI_MENU_COOP_NOT_HEARD] = "ещё не на связи", [UI_MENU_COOP_AWAY] = "отошёл",
|
||||
[UI_MENU_COOP_MEMBER_DESC] = "Игрок в комнате. «На связи»: когда последний раз пришло его сообщение, запечатанное "
|
||||
"секретом комнаты; игрок, который ещё не на связи, пока не показал, что знает секрет.",
|
||||
[UI_MENU_COOP_REMOVE] = "Удалить",
|
||||
[UI_MENU_COOP_REMOVE_DESC] = "Как создатель комнаты вы можете удалить игрока по его ключу: каждая игра отбрасывает этот "
|
||||
"ключ и возвращает взятое им из запасов, а ретранслятор отключает игрока и больше не "
|
||||
"пускает. Тот, кто знает секрет, может вернуться с новым ключом, и тогда все получат новое "
|
||||
"предложение, которое можно принять или нет; для надёжности создайте новую комнату.",
|
||||
[UI_MENU_COOP_REMOVE_CONFIRM] = "Удалить %s из комнаты?",
|
||||
[UI_MENU_COOP_SECRET_DESC] = "Любой, у кого есть секрет, может войти в комнату: передавайте его только приглашённым "
|
||||
"игрокам, голосом или личным сообщением. Он показывается, только когда вы попросите; "
|
||||
"скройте его, прежде чем показывать экран другим. Ретранслятор его никогда не узнаёт.",
|
||||
[UI_MENU_COOP_SHOW] = "нажмите, чтобы показать", [UI_MENU_COOP_HIDE] = "нажмите, чтобы скрыть",
|
||||
[UI_MENU_COOP_COPY] = "Копировать секрет",
|
||||
[UI_MENU_COOP_COPY_DESC] = "Помещает секрет комнаты в буфер обмена, чтобы вставить его в личное сообщение.",
|
||||
[UI_MENU_COOP_OFFER] = "Комната ждёт вашего ответа",
|
||||
[UI_MENU_COOP_OFFER_WHO] = "В комнате: %s.", [UI_MENU_COOP_OFFER_NOBODY] = "больше пока никого",
|
||||
[UI_MENU_COOP_OFFER_SHARED] = "Общее для всех: %s.", [UI_MENU_COOP_OFFER_POOLED] = "Общий запас на всех: %s.",
|
||||
[UI_MENU_COOP_OFFER_NOTHING] = "Правила ничего не делят.",
|
||||
[UI_MENU_COOP_OFFER_COPY] = "Ничего из комнаты не попадёт в ваше сохранение, пока вы её не примете. Затем сначала всё "
|
||||
"ваше сохранение (все слоты) копируется в coop-backup/<дата и время> в папке профиля, и "
|
||||
"только после этого приходит прогресс комнаты.",
|
||||
[UI_MENU_COOP_OFFER_TRUST] = "Игрок в комнате может делать в вашем мире то, что делят правила (открыть сундук, "
|
||||
"потратить общий ключ), и игра не может это отменить: принимайте только тех, кому "
|
||||
"доверяете своё сохранение.",
|
||||
[UI_MENU_COOP_ANSWER] = "Принять или нет",
|
||||
[UI_MENU_COOP_ANSWER_DESC] = "Показывает предложение с кнопками «Принять» и «Не сейчас». Новый игрок или другие правила "
|
||||
"создают новое предложение, которое снова ждёт вашего ответа.",
|
||||
[UI_MENU_COOP_ACCEPT_CONFIRM] = "Принять эту комнату?", [UI_MENU_COOP_ACCEPT] = "Принять",
|
||||
[UI_MENU_COOP_NOT_NOW] = "Не сейчас",
|
||||
[UI_MENU_COOP_ACCEPTED] = "Принято: прогресс комнаты попадает в ваше сохранение. Ваше прежнее сохранение лежит в "
|
||||
"coop-backup в папке профиля.",
|
||||
[UI_MENU_COOP_COPY_FAILED] = "Принято, но сохранение не удалось скопировать, поэтому ничего из комнаты не применяется; "
|
||||
"причина в журнале.",
|
||||
[UI_MENU_COOP_RULES_ROOM] = "Правила комнаты", [UI_MENU_COOP_RULES_MINE] = "Правила комнаты, которую создадите вы",
|
||||
[UI_MENU_COOP_RULES_UNKNOWN] = "Правила комнаты ещё не пришли.",
|
||||
[UI_MENU_COOP_RULES_CHANGE] = "Изменение — это новое предложение: остальные ничего больше не берут из комнаты, пока не "
|
||||
"примут его.",
|
||||
[UI_MENU_COOP_RULES_SET_BY] = "задаёт создатель комнаты", [UI_MENU_COOP_RULE_FOLLOWS] = "следует за «Прогрессом»",
|
||||
[UI_MENU_COOP_R_PROGRESS] = "Прогресс", [UI_MENU_COOP_R_ITEMS] = "Предметы", [UI_MENU_COOP_R_SONGS] = "Мелодии",
|
||||
[UI_MENU_COOP_R_QUEST] = "Квестовые предметы", [UI_MENU_COOP_R_KEYS] = "Малые ключи", [UI_MENU_COOP_R_RUPEES] = "Рупии",
|
||||
[UI_MENU_COOP_R_AMMO] = "Боеприпасы",
|
||||
[UI_MENU_COOP_R_PROGRESS_DESC] = "Флаги сюжета, мира и подземелий: события, разговоры, сундуки, двери, переключатели, "
|
||||
"боссы, карта и компас. Общее: то, что делает один игрок, происходит в каждом мире. "
|
||||
"Своё: каждый мир хранит своё, и малые ключи тогда тоже свои.",
|
||||
[UI_MENU_COOP_R_ITEMS_DESC] = "Снаряжение, ключевые предметы, имеющиеся бутылки, размеры кошелька, сумки и колчана, "
|
||||
"размер шкалы магии; из количеств побеждает наибольшее. «Своё» возможно только при своём "
|
||||
"«Прогрессе»: в общем мире сундук, открытый одним игроком, пуст для остальных.",
|
||||
[UI_MENU_COOP_R_SONGS_DESC] = "Выученные мелодии. «Своё» возможно только при своём «Прогрессе».",
|
||||
[UI_MENU_COOP_R_QUEST_DESC] = "Медальоны, духовные камни, Камень Агонии и карта Герудо. «Своё» возможно только при своём "
|
||||
"«Прогрессе».",
|
||||
[UI_MENU_COOP_R_KEYS_DESC] = "Малые ключи, по подземельям. Запас: ключ, подобранный кем угодно, идёт в запас "
|
||||
"подземелья, а дверь, открытая кем угодно, забирает один. «Своё» при своём «Прогрессе».",
|
||||
[UI_MENU_COOP_R_RUPEES_DESC] = "Запас: один кошелёк, который все игроки пополняют и тратят. Своё: у каждого свой.",
|
||||
[UI_MENU_COOP_R_AMMO_DESC] = "Бомбы, бомбчу, стрелы, орехи деку, семена и палки, волшебные бобы. Запас: одно "
|
||||
"количество, которое все игроки пополняют и тратят.",
|
||||
[UI_MENU_COOP_SHARED] = "общее", [UI_MENU_COOP_OWN] = "своё", [UI_MENU_COOP_POOL] = "запас",
|
||||
[UI_MENU_COOP_LEAVE] = "Покинуть комнату",
|
||||
[UI_MENU_COOP_LEAVE_DESC] = "Выходит из комнаты. То, что комната дала вашему сохранению, остаётся в нём.",
|
||||
[UI_MENU_COOP_LEAVE_CONFIRM] = "Покинуть комнату? То, что она дала вашему сохранению, останется.",
|
||||
[UI_MENU_COOP_LEAVE_MAKER] = "Эту комнату создали вы: пока вас нет, никто не может менять её правила или удалять "
|
||||
"игроков, а если в ней больше никого нет, она закроется.",
|
||||
[UI_MENU_COOP_STAY] = "Остаться",
|
||||
[UI_MENU_COOP_TOAST_JOINED] = "%s входит в комнату", [UI_MENU_COOP_TOAST_LEFT] = "%s покидает комнату",
|
||||
[UI_MENU_COOP_TOAST_OFFER] = "Комната кооператива ждёт вашего ответа во вкладке «Кооператив» меню",
|
||||
[UI_MENU_COOP_LOST] = "Ретранслятор потерял комнату; игра возвращается в неё.",
|
||||
[UI_MENU_COOP_JOIN_LIMIT] = "Ретранслятор пока не принимает новых входов из вашей сети; игра попробует снова через минуту.",
|
||||
[UI_MENU_COOP_NOT_IDENTIFIED] = "не назвался", [UI_MENU_COOP_REMOVED] = "удалён создателем",
|
||||
[UI_MENU_COOP_KEY] = "ключ %s",
|
||||
[UI_MENU_COOP_OFFER_KEY] = "Правила подписаны ключом %s.",
|
||||
[UI_MENU_COOP_OFFER_COMPARE] = "Прежде чем принять, попросите создателя комнаты прочитать вам свой ключ голосом или в "
|
||||
"чате и сравните его с этим.",
|
||||
[UI_MENU_COOP_MY_KEY] = "Ваш ключ, которым подписаны правила этой комнаты: %s. Прочитайте его остальным голосом или в "
|
||||
"чате, чтобы они могли сравнить его, прежде чем принять.",
|
||||
[UI_MENU_COOP_UNIDENTIFIED] = "Игроков в комнате, которые не опознаны: %d (не назвались, или два ключа называют себя одним "
|
||||
"и тем же игроком). Пока они в ней, никто не может принять комнату: создатель может удалить "
|
||||
"их, или все переходят в новую комнату.",
|
||||
[UI_MENU_COOP_DISAGREE] = "У игроков правила, подписанные разными ключами: прежде чем принять, спросите создателя "
|
||||
"комнаты, какой ключ его.",
|
||||
[UI_MENU_COOP_NEW_SAVE] = "В этой комнате играют другое сохранение: оно получает прогресс комнаты, в котором есть то, "
|
||||
"что принесло прошлое сохранение.",
|
||||
[UI_MENU_COOP_WARNINGS] = "Прежде чем войти в комнату с незнакомцами",
|
||||
[UI_MENU_COOP_WARN_SAVE] = "1. Держите сохранение, к которому можно вернуться. Любой, кого вы приняли, может ставить "
|
||||
"сюжетные флаги в вашем сохранении, как и любой, кого принял он; игрок в ваших запасах может "
|
||||
"опустошить малые ключи подземелья. Никакое удаление не возвращает флаг: это делает копия в "
|
||||
"coop-backup/first-<дата и время>.",
|
||||
[UI_MENU_COOP_WARN_ROOM] = "2. Ваше согласие — ваше, комната — нет. Принятые вами игроки передают флаги тех, кого "
|
||||
"приняли они, а кто может пользоваться запасами, решает только создатель. Если в комнате "
|
||||
"есть кто-то незнакомый, не принимайте: выйдите и попросите у создателя новую комнату.",
|
||||
[UI_MENU_COOP_WARN_KEY] = "3. Сверьте ключ создателя и не отдавайте свой. Сравните ключ, которым подписаны правила, с "
|
||||
"ключом создателя, никогда не запускайте игру с настройками или скриптом, которые вам дали, "
|
||||
"и никому не отдавайте копию папки профиля.",
|
||||
[UI_MENU_COOP_POOLS] = "Запасы",
|
||||
[UI_MENU_COOP_SPENT] = "взял сверх принесённого: ключей %lld, рупий %lld, боеприпасов %lld",
|
||||
[UI_MENU_COOP_NOT_IN_ROOM] = "не в комнате",
|
||||
[UI_MENU_COOP_SPENT_NONE] = "Никто не взял из запасов больше, чем принёс.",
|
||||
[UI_MENU_COOP_SPENT_DESC] = "Этот ключ взял из запасов больше, чем принёс. Здесь и игрок, который пользовался ключами, "
|
||||
"найденными другими; тот, кого никто не ждал, опустошил запасы. Удаление ключа возвращает "
|
||||
"взятое во всех играх, и после ухода игрока тоже. Удалите ключ до сброса запасов: сброс "
|
||||
"оставляет взятое игроку, который ещё в комнате.",
|
||||
[UI_MENU_COOP_RESET] = "Сбросить запасы",
|
||||
[UI_MENU_COOP_RESET_DESC] = "Каждая игра заново входит в запасы с тем, что у неё было для игроков в комнате. Так "
|
||||
"восстанавливается запас, который опустошил ушедший игрок; флаги остаются как есть. Игрок, "
|
||||
"опустошивший запас и оставшийся в комнате, сохраняет взятое: сначала удалите его, потом сбросьте.",
|
||||
[UI_MENU_COOP_RESET_CONFIRM] = "Сбросить запасы для всех в комнате?",
|
||||
[UI_MENU_COOP_REMOVE_KEY_CONFIRM] = "Удалить %s (ключ %s) из комнаты?",
|
||||
[UI_MENU_COOP_NOT_ACCEPTED] = "Не принято: комната изменилась или кто-то в ней не опознан. Посмотрите предложение ещё раз.",
|
||||
[UI_MENU_COOP_ACCEPTED_AS] = "ключ, который вы приняли как %s",
|
||||
[UI_BOOT_TITLE] = "Подготовка шейдеров",
|
||||
[UI_BOOT_STARTING] = "Запуск", [UI_BOOT_SHADERS] = "Шейдеры: %lld из %lld", [UI_BOOT_PIPELINES] = "Конвейеры: %lld из %lld",
|
||||
[UI_MENU_CHEATS_REBUILD] = "Пересобрать игру сейчас",
|
||||
@@ -1694,6 +1977,151 @@ 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] = "Cooperativo",
|
||||
[UI_MENU_COOP_ON] = "Cooperativo",
|
||||
[UI_MENU_COOP_ON_DESC] = "Jogue com amigos, cada um no seu próprio jogo e save: uma sala em um relay compartilha o "
|
||||
"progresso da história entre eles conforme as regras dela (docs/coop.md). Desligado: o jogo "
|
||||
"não usa a rede. Criar uma sala e Entrar em uma sala o ligam.",
|
||||
[UI_MENU_COOP_NAME] = "Seu nome",
|
||||
[UI_MENU_COOP_NAME_DESC] = "O nome que os outros jogadores da sala veem; o relay também o vê. No máximo 24 bytes. "
|
||||
"Vazio: Player- e quatro dígitos aleatórios.",
|
||||
[UI_MENU_COOP_AUTO] = "automático",
|
||||
[UI_MENU_COOP_SERVER] = "Endereço do relay",
|
||||
[UI_MENU_COOP_SERVER_DESC] = "O relay que conecta os jogos dos jogadores: host, host:porta ou [IPv6]:porta (porta 24680 "
|
||||
"se nenhuma for dada). Quem o executa (python tools/coop_relay.py) passa o endereço aos "
|
||||
"outros. O log e as informações do sistema não o mostram.",
|
||||
[UI_MENU_COOP_NONE] = "nenhum",
|
||||
[UI_MENU_COOP_MAKE] = "Criar uma sala",
|
||||
[UI_MENU_COOP_MAKE_DESC] = "Cria uma sala com um novo segredo de 18 caracteres, que você passa aos jogadores que "
|
||||
"convidar (por voz ou mensagem privada). Uma sala criada por você compartilha conforme as "
|
||||
"regras abaixo, e você pode mudá-las enquanto joga.",
|
||||
[UI_MENU_COOP_JOIN] = "Entrar em uma sala",
|
||||
[UI_MENU_COOP_JOIN_DESC] = "Entra na sala cujo segredo outro jogador lhe deu. Nada da sala chega ao seu save antes de "
|
||||
"você ver quem está nela e o que ela compartilha, e aceitá-la aqui.",
|
||||
[UI_MENU_COOP_NEED_SERVER] = "defina antes o endereço do relay",
|
||||
[UI_MENU_COOP_SECRET] = "Segredo da sala",
|
||||
[UI_MENU_COOP_SECRET_HINT] = "18 caracteres, como XXXXXX-XXXXXX-XXXXXX: maiúsculas ou minúsculas, com ou sem hífens.",
|
||||
[UI_MENU_COOP_SECRET_BAD] = "Isto não é um segredo de sala: ele tem 18 caracteres de 23456789BCDFGHJKMNPRSTVWXYZ.",
|
||||
[UI_MENU_COOP_PASTE] = "Colar", [UI_MENU_COOP_PASTE_EMPTY] = "A área de transferência não tem texto.",
|
||||
[UI_MENU_COOP_OK] = "OK", [UI_MENU_COOP_STOP] = "Parar",
|
||||
[UI_MENU_COOP_STOP_DESC] = "Para de tentar chegar à sala.",
|
||||
[UI_MENU_COOP_CONNECTING] = "Conectando: %s",
|
||||
[UI_MENU_COOP_RECONNECTING] = "O relay ficou em silêncio; voltando para a sala: %s",
|
||||
[UI_MENU_COOP_LEFT] = "Fora de uma sala: %s",
|
||||
[UI_MENU_COOP_NO_ROOM] = "Nenhuma sala aberta no relay tem este segredo: confira-o ou pergunte a quem criou a sala se "
|
||||
"ela ainda está aberta.",
|
||||
[UI_MENU_COOP_NOT_STARTED] = "O cooperativo não iniciou; o log diz por quê.",
|
||||
[UI_MENU_COOP_PLAYERS] = "Jogadores", [UI_MENU_COOP_YOU] = "você", [UI_MENU_COOP_MAKER] = "criou a sala",
|
||||
[UI_MENU_COOP_HEARD] = "ouvido há %u s", [UI_MENU_COOP_NOT_HEARD] = "ainda não ouvido", [UI_MENU_COOP_AWAY] = "ausente",
|
||||
[UI_MENU_COOP_MEMBER_DESC] = "Um jogador da sala. Ouvido: quando chegou a última mensagem dele selada com o segredo da "
|
||||
"sala; um jogador ainda não ouvido não mostrou que o conhece.",
|
||||
[UI_MENU_COOP_REMOVE] = "Remover",
|
||||
[UI_MENU_COOP_REMOVE_DESC] = "Como criador da sala, você pode remover um jogador pela chave dele: cada jogo descarta essa "
|
||||
"chave e devolve o que ela pegou dos estoques, e o relay desconecta o jogador e o recusa de "
|
||||
"novo. Quem conhece o segredo pode voltar com uma nova chave, e todos então recebem uma "
|
||||
"nova oferta para aceitar ou não; para ter certeza, crie uma nova sala.",
|
||||
[UI_MENU_COOP_REMOVE_CONFIRM] = "Remover %s da sala?",
|
||||
[UI_MENU_COOP_SECRET_DESC] = "Qualquer pessoa com o segredo pode entrar na sala: passe-o só aos jogadores que convidar, "
|
||||
"por voz ou mensagem privada. Ele só aparece quando você pede; esconda-o antes de "
|
||||
"compartilhar a tela. O relay nunca o conhece.",
|
||||
[UI_MENU_COOP_SHOW] = "pressione para mostrar", [UI_MENU_COOP_HIDE] = "pressione para esconder",
|
||||
[UI_MENU_COOP_COPY] = "Copiar o segredo",
|
||||
[UI_MENU_COOP_COPY_DESC] = "Coloca o segredo da sala na área de transferência, para colar em uma mensagem privada.",
|
||||
[UI_MENU_COOP_OFFER] = "Esta sala aguarda sua resposta",
|
||||
[UI_MENU_COOP_OFFER_WHO] = "Na sala: %s.", [UI_MENU_COOP_OFFER_NOBODY] = "ninguém mais ainda",
|
||||
[UI_MENU_COOP_OFFER_SHARED] = "Compartilhado por todos: %s.",
|
||||
[UI_MENU_COOP_OFFER_POOLED] = "Em um estoque comum para todos: %s.",
|
||||
[UI_MENU_COOP_OFFER_NOTHING] = "As regras não compartilham nada.",
|
||||
[UI_MENU_COOP_OFFER_COPY] = "Nada da sala chega ao seu save antes de você aceitar. Então todo o seu save (todos os "
|
||||
"slots) é primeiro copiado para coop-backup/<data e hora> na pasta do perfil, e só depois "
|
||||
"disso chega o progresso da sala.",
|
||||
[UI_MENU_COOP_OFFER_TRUST] = "Um jogador da sala pode fazer no seu mundo o que as regras compartilham (abrir um baú, "
|
||||
"gastar uma chave comum), e o jogo não pode desfazer: aceite só jogadores a quem você "
|
||||
"confiaria o seu save.",
|
||||
[UI_MENU_COOP_ANSWER] = "Aceitar ou não",
|
||||
[UI_MENU_COOP_ANSWER_DESC] = "Mostra a oferta com Aceitar e Agora não. Um novo jogador ou outras regras criam uma nova "
|
||||
"oferta, que aguarda sua resposta outra vez.",
|
||||
[UI_MENU_COOP_ACCEPT_CONFIRM] = "Aceitar esta sala?", [UI_MENU_COOP_ACCEPT] = "Aceitar",
|
||||
[UI_MENU_COOP_NOT_NOW] = "Agora não",
|
||||
[UI_MENU_COOP_ACCEPTED] = "Aceita: o progresso da sala chega ao seu save. O seu save como era está em coop-backup na "
|
||||
"pasta do perfil.",
|
||||
[UI_MENU_COOP_COPY_FAILED] = "Aceita, mas não foi possível copiar o seu save, então nada da sala é aplicado; o log diz "
|
||||
"por quê.",
|
||||
[UI_MENU_COOP_RULES_ROOM] = "Regras da sala", [UI_MENU_COOP_RULES_MINE] = "Regras de uma sala criada por você",
|
||||
[UI_MENU_COOP_RULES_UNKNOWN] = "As regras da sala ainda não chegaram.",
|
||||
[UI_MENU_COOP_RULES_CHANGE] = "Uma mudança é uma nova oferta: os outros não recebem mais nada da sala até aceitá-la.",
|
||||
[UI_MENU_COOP_RULES_SET_BY] = "definido por quem criou a sala", [UI_MENU_COOP_RULE_FOLLOWS] = "segue o Progresso",
|
||||
[UI_MENU_COOP_R_PROGRESS] = "Progresso", [UI_MENU_COOP_R_ITEMS] = "Itens", [UI_MENU_COOP_R_SONGS] = "Músicas",
|
||||
[UI_MENU_COOP_R_QUEST] = "Itens de missão", [UI_MENU_COOP_R_KEYS] = "Chaves pequenas", [UI_MENU_COOP_R_RUPEES] = "Rupias",
|
||||
[UI_MENU_COOP_R_AMMO] = "Munição",
|
||||
[UI_MENU_COOP_R_PROGRESS_DESC] = "Flags da história, do mundo e das masmorras: eventos, conversas, baús, portas, "
|
||||
"interruptores, chefes, mapa e bússola. Compartilhado: o que um jogador faz acontece "
|
||||
"em todos os mundos. Próprio: cada mundo mantém o seu, e as chaves pequenas também "
|
||||
"ficam próprias.",
|
||||
[UI_MENU_COOP_R_ITEMS_DESC] = "Equipamento, itens-chave, garrafas obtidas, tamanhos da carteira, da bolsa e da aljava, "
|
||||
"tamanho do medidor de magia; de uma quantidade, vence a maior. Próprio só é possível com "
|
||||
"Progresso próprio: num mundo compartilhado, um baú que um jogador abriu fica vazio para "
|
||||
"os outros.",
|
||||
[UI_MENU_COOP_R_SONGS_DESC] = "As músicas aprendidas. Próprio só é possível com Progresso próprio.",
|
||||
[UI_MENU_COOP_R_QUEST_DESC] = "Medalhões, pedras espirituais, a Pedra da Agonia e o cartão Gerudo. Próprio só é "
|
||||
"possível com Progresso próprio.",
|
||||
[UI_MENU_COOP_R_KEYS_DESC] = "Chaves pequenas, por masmorra. Estoque: uma chave que qualquer um pega vai para o estoque "
|
||||
"da masmorra, e uma porta que qualquer um abre tira uma. Próprio com Progresso próprio.",
|
||||
[UI_MENU_COOP_R_RUPEES_DESC] = "Estoque: uma carteira que todos os jogadores enchem e gastam. Próprio: cada um tem a sua.",
|
||||
[UI_MENU_COOP_R_AMMO_DESC] = "Bombas, bombchus, flechas, nozes deku, sementes e galhos, feijões mágicos. Estoque: uma "
|
||||
"quantidade que todos os jogadores enchem e gastam.",
|
||||
[UI_MENU_COOP_SHARED] = "compartilhado", [UI_MENU_COOP_OWN] = "próprio", [UI_MENU_COOP_POOL] = "estoque",
|
||||
[UI_MENU_COOP_LEAVE] = "Sair da sala",
|
||||
[UI_MENU_COOP_LEAVE_DESC] = "Sai da sala. O que a sala deu ao seu save fica nele.",
|
||||
[UI_MENU_COOP_LEAVE_CONFIRM] = "Sair da sala? O que ela deu ao seu save fica.",
|
||||
[UI_MENU_COOP_LEAVE_MAKER] = "Você criou esta sala: enquanto estiver fora, ninguém pode mudar as regras nem remover um "
|
||||
"jogador, e se não houver mais ninguém nela, ela fecha.",
|
||||
[UI_MENU_COOP_STAY] = "Ficar",
|
||||
[UI_MENU_COOP_TOAST_JOINED] = "%s entrou na sala", [UI_MENU_COOP_TOAST_LEFT] = "%s saiu da sala",
|
||||
[UI_MENU_COOP_TOAST_OFFER] = "A sala cooperativa aguarda sua resposta na aba Cooperativo do menu",
|
||||
[UI_MENU_COOP_LOST] = "O relay perdeu a sala; o jogo está voltando a ela.",
|
||||
[UI_MENU_COOP_JOIN_LIMIT] = "O relay não aceita mais entradas da sua rede por enquanto; o jogo tenta de novo em um minuto.",
|
||||
[UI_MENU_COOP_NOT_IDENTIFIED] = "não identificado", [UI_MENU_COOP_REMOVED] = "removido pelo criador",
|
||||
[UI_MENU_COOP_KEY] = "chave %s",
|
||||
[UI_MENU_COOP_OFFER_KEY] = "As regras são assinadas pela chave %s.",
|
||||
[UI_MENU_COOP_OFFER_COMPARE] = "Antes de aceitar, peça ao criador da sala que leia a chave dele para você, por voz ou "
|
||||
"chat, e compare-a com esta.",
|
||||
[UI_MENU_COOP_MY_KEY] = "Sua chave, que assina as regras desta sala: %s. Leia-a para os outros, por voz ou chat, para "
|
||||
"que possam compará-la antes de aceitar.",
|
||||
[UI_MENU_COOP_UNIDENTIFIED] = "Jogadores na sala que não estão identificados: %d (não disseram quem são, ou duas chaves "
|
||||
"dizem ser o mesmo jogador). Ninguém pode aceitar a sala enquanto eles estiverem nela: o "
|
||||
"criador pode removê-los, ou todos vão para uma nova sala.",
|
||||
[UI_MENU_COOP_DISAGREE] = "Os jogadores trazem regras assinadas por chaves diferentes: pergunte ao criador da sala qual "
|
||||
"chave é a dele antes de aceitar.",
|
||||
[UI_MENU_COOP_NEW_SAVE] = "Outro save é jogado nesta sala: ele recebe o progresso da sala, que inclui o que o último "
|
||||
"save trouxe.",
|
||||
[UI_MENU_COOP_WARNINGS] = "Antes de entrar em uma sala com desconhecidos",
|
||||
[UI_MENU_COOP_WARN_SAVE] = "1. Tenha um save para o qual possa voltar. Qualquer um que você aceitar pode definir flags da "
|
||||
"história no seu save, assim como quem essa pessoa aceitou; um jogador nos seus estoques pode "
|
||||
"esvaziar as chaves pequenas de uma masmorra. Nenhuma remoção desfaz uma flag: a cópia em "
|
||||
"coop-backup/first-<data e hora> desfaz.",
|
||||
[UI_MENU_COOP_WARN_ROOM] = "2. Sua aceitação é sua, a sala não. Os jogadores que você aceita repassam as flags dos "
|
||||
"jogadores que eles aceitaram, e só o criador decide quem pode usar os estoques. Se houver "
|
||||
"alguém que você não conhece na sala, não aceite: saia e peça ao criador uma nova sala.",
|
||||
[UI_MENU_COOP_WARN_KEY] = "3. Confira a chave do criador e guarde a sua. Compare a chave que assina as regras com a do "
|
||||
"criador, nunca inicie o jogo com configurações ou um script que alguém lhe passou, e nunca "
|
||||
"entregue uma cópia da sua pasta de perfil.",
|
||||
[UI_MENU_COOP_POOLS] = "Estoques",
|
||||
[UI_MENU_COOP_SPENT] = "pegou além do que trouxe: %lld chaves, %lld rupias, %lld munições",
|
||||
[UI_MENU_COOP_NOT_IN_ROOM] = "fora da sala",
|
||||
[UI_MENU_COOP_SPENT_NONE] = "Ninguém pegou dos estoques mais do que trouxe.",
|
||||
[UI_MENU_COOP_SPENT_DESC] = "Esta chave pegou dos estoques mais do que trouxe. Um jogador que usou chaves que outros "
|
||||
"acharam também aparece; alguém que ninguém esperava esvaziou os estoques. Remover a chave "
|
||||
"devolve o que ela pegou, em todos os jogos, também depois que o jogador saiu. Remova-a antes "
|
||||
"de redefinir os estoques: a redefinição mantém o que pegou um jogador que ainda está na sala.",
|
||||
[UI_MENU_COOP_RESET] = "Redefinir os estoques",
|
||||
[UI_MENU_COOP_RESET_DESC] = "Cada jogo entra de novo nos estoques com o que tinha para os jogadores na sala. Isso "
|
||||
"recupera um estoque que um jogador que saiu esvaziou; as flags ficam como estão. Um jogador "
|
||||
"que esvaziou um estoque e ainda está na sala fica com o que pegou: remova-o primeiro, depois redefina.",
|
||||
[UI_MENU_COOP_RESET_CONFIRM] = "Redefinir os estoques para todos na sala?",
|
||||
[UI_MENU_COOP_REMOVE_KEY_CONFIRM] = "Remover %s, chave %s, da sala?",
|
||||
[UI_MENU_COOP_NOT_ACCEPTED] = "Não aceito: a sala mudou ou alguém nela não está identificado. Veja a oferta de novo.",
|
||||
[UI_MENU_COOP_ACCEPTED_AS] = "uma chave que você aceitou como %s",
|
||||
[UI_BOOT_TITLE] = "Preparando shaders",
|
||||
[UI_BOOT_STARTING] = "Iniciando", [UI_BOOT_SHADERS] = "Shaders: %lld de %lld", [UI_BOOT_PIPELINES] = "Pipelines: %lld de %lld",
|
||||
[UI_MENU_CHEATS_REBUILD] = "Recompilar o jogo agora",
|
||||
@@ -2343,6 +2771,120 @@ 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] = "与朋友一起玩,各自运行自己的游戏和存档:中继服务器上的房间按其规则在玩家之间共享剧情进度"
|
||||
"(docs/coop.md)。关闭:游戏完全不使用网络。“创建房间”和“加入房间”会将其打开。",
|
||||
[UI_MENU_COOP_NAME] = "你的名字",
|
||||
[UI_MENU_COOP_NAME_DESC] = "房间中其他玩家看到的名字,中继服务器也能看到。最多 24 字节。留空:Player- 加四位随机数字。",
|
||||
[UI_MENU_COOP_AUTO] = "自动",
|
||||
[UI_MENU_COOP_SERVER] = "中继地址",
|
||||
[UI_MENU_COOP_SERVER_DESC] = "连接各玩家游戏的中继服务器:host、host:port 或 [IPv6]:port(未指定时端口为 24680)。"
|
||||
"运行它的人(python tools/coop_relay.py)把地址告诉其他人。日志和系统信息不会显示它。",
|
||||
[UI_MENU_COOP_NONE] = "无",
|
||||
[UI_MENU_COOP_MAKE] = "创建房间",
|
||||
[UI_MENU_COOP_MAKE_DESC] = "创建一个带有新的 18 字符密钥的房间,由你告诉受邀的玩家(口头或私信)。你创建的房间按下方"
|
||||
"规则共享,游戏中也可以修改。",
|
||||
[UI_MENU_COOP_JOIN] = "加入房间",
|
||||
[UI_MENU_COOP_JOIN_DESC] = "加入其他玩家给你密钥的房间。在你看到房间里有谁、共享什么并在此接受之前,房间中的任何内容"
|
||||
"都不会进入你的存档。",
|
||||
[UI_MENU_COOP_NEED_SERVER] = "请先设置中继地址",
|
||||
[UI_MENU_COOP_SECRET] = "房间密钥",
|
||||
[UI_MENU_COOP_SECRET_HINT] = "18 个字符,形如 XXXXXX-XXXXXX-XXXXXX:大小写均可,带不带连字符均可。",
|
||||
[UI_MENU_COOP_SECRET_BAD] = "这不是房间密钥:密钥由 23456789BCDFGHJKMNPRSTVWXYZ 中的 18 个字符组成。",
|
||||
[UI_MENU_COOP_PASTE] = "粘贴", [UI_MENU_COOP_PASTE_EMPTY] = "剪贴板中没有文字。",
|
||||
[UI_MENU_COOP_OK] = "确定", [UI_MENU_COOP_STOP] = "停止",
|
||||
[UI_MENU_COOP_STOP_DESC] = "不再尝试进入房间。",
|
||||
[UI_MENU_COOP_CONNECTING] = "正在连接:%s",
|
||||
[UI_MENU_COOP_RECONNECTING] = "中继没有响应,正在重新进入房间:%s",
|
||||
[UI_MENU_COOP_LEFT] = "不在房间中:%s",
|
||||
[UI_MENU_COOP_NO_ROOM] = "中继上没有使用此密钥的开放房间:请检查密钥,或询问房主房间是否仍开放。",
|
||||
[UI_MENU_COOP_NOT_STARTED] = "合作未能启动,原因见日志。",
|
||||
[UI_MENU_COOP_PLAYERS] = "玩家", [UI_MENU_COOP_YOU] = "你", [UI_MENU_COOP_MAKER] = "房主",
|
||||
[UI_MENU_COOP_HEARD] = "%u 秒前有消息", [UI_MENU_COOP_NOT_HEARD] = "尚无消息", [UI_MENU_COOP_AWAY] = "离开",
|
||||
[UI_MENU_COOP_MEMBER_DESC] = "房间中的玩家。消息:其最近一条用房间密钥封装的消息到达的时间;尚无消息的玩家还没有证明"
|
||||
"自己知道密钥。",
|
||||
[UI_MENU_COOP_REMOVE] = "移除",
|
||||
[UI_MENU_COOP_REMOVE_DESC] = "作为房主,你可以按身份指纹移除玩家:每个游戏都会丢弃该身份并归还它从共用中取走的东西,"
|
||||
"中继会断开该玩家并拒绝其再次进入。知道房间密钥的人可以换一个新身份回来,届时所有人都会"
|
||||
"收到新的提议,可以接受或不接受;要确保安全,请创建新房间。",
|
||||
[UI_MENU_COOP_REMOVE_CONFIRM] = "将 %s 移出房间?",
|
||||
[UI_MENU_COOP_SECRET_DESC] = "任何拥有密钥的人都能加入房间:只通过口头或私信告诉受邀的玩家。只有在你要求时才显示;"
|
||||
"分享屏幕前请将其隐藏。中继永远不会知道它。",
|
||||
[UI_MENU_COOP_SHOW] = "按下以显示", [UI_MENU_COOP_HIDE] = "按下以隐藏",
|
||||
[UI_MENU_COOP_COPY] = "复制密钥",
|
||||
[UI_MENU_COOP_COPY_DESC] = "将房间密钥放入剪贴板,以便粘贴到私信中。",
|
||||
[UI_MENU_COOP_OFFER] = "此房间正等待你的答复",
|
||||
[UI_MENU_COOP_OFFER_WHO] = "房间中:%s。", [UI_MENU_COOP_OFFER_NOBODY] = "暂无其他人",
|
||||
[UI_MENU_COOP_OFFER_SHARED] = "所有人共享:%s。", [UI_MENU_COOP_OFFER_POOLED] = "所有人共用一份:%s。",
|
||||
[UI_MENU_COOP_OFFER_NOTHING] = "规则不共享任何内容。",
|
||||
[UI_MENU_COOP_OFFER_COPY] = "接受之前,房间中的任何内容都不会进入你的存档。接受后,会先把你的整个存档(所有存档位)"
|
||||
"复制到配置文件夹中的 coop-backup/<日期和时间>,之后房间的进度才会到来。",
|
||||
[UI_MENU_COOP_OFFER_TRUST] = "房间中的玩家可以在你的世界里做规则所共享的事(打开宝箱、花掉共用的钥匙),且游戏无法撤销:"
|
||||
"只接受你愿意托付存档的玩家。",
|
||||
[UI_MENU_COOP_ANSWER] = "接受与否",
|
||||
[UI_MENU_COOP_ANSWER_DESC] = "显示提议及“接受”和“暂不”。新玩家或其他规则会产生新的提议,再次等待你的答复。",
|
||||
[UI_MENU_COOP_ACCEPT_CONFIRM] = "接受此房间?", [UI_MENU_COOP_ACCEPT] = "接受", [UI_MENU_COOP_NOT_NOW] = "暂不",
|
||||
[UI_MENU_COOP_ACCEPTED] = "已接受:房间的进度会进入你的存档。你原来的存档在配置文件夹的 coop-backup 中。",
|
||||
[UI_MENU_COOP_COPY_FAILED] = "已接受,但无法复制你的存档,因此不会应用房间中的任何内容;原因见日志。",
|
||||
[UI_MENU_COOP_RULES_ROOM] = "房间规则", [UI_MENU_COOP_RULES_MINE] = "你创建的房间的规则",
|
||||
[UI_MENU_COOP_RULES_UNKNOWN] = "房间规则尚未到达。",
|
||||
[UI_MENU_COOP_RULES_CHANGE] = "修改即是新的提议:其他人在接受之前不会再从房间获取任何内容。",
|
||||
[UI_MENU_COOP_RULES_SET_BY] = "由房主设定", [UI_MENU_COOP_RULE_FOLLOWS] = "随“进度”而定",
|
||||
[UI_MENU_COOP_R_PROGRESS] = "进度", [UI_MENU_COOP_R_ITEMS] = "道具", [UI_MENU_COOP_R_SONGS] = "乐曲",
|
||||
[UI_MENU_COOP_R_QUEST] = "任务道具", [UI_MENU_COOP_R_KEYS] = "小钥匙", [UI_MENU_COOP_R_RUPEES] = "卢比",
|
||||
[UI_MENU_COOP_R_AMMO] = "弹药",
|
||||
[UI_MENU_COOP_R_PROGRESS_DESC] = "剧情、世界和迷宫的标志:事件、对话、宝箱、门、开关、头目、地图和指南针。共享:一名玩家"
|
||||
"做的事会在每个世界中发生。各自:每个世界保留自己的,此时小钥匙也各自独立。",
|
||||
[UI_MENU_COOP_R_ITEMS_DESC] = "装备、关键道具、拥有的瓶子、钱包、袋子和箭筒的容量、魔力槽的大小;数量取最大值。只有在"
|
||||
"“进度”为各自时才能设为各自:在共享的世界里,一名玩家打开的宝箱对其他人是空的。",
|
||||
[UI_MENU_COOP_R_SONGS_DESC] = "学会的乐曲。只有在“进度”为各自时才能设为各自。",
|
||||
[UI_MENU_COOP_R_QUEST_DESC] = "徽章、精灵石、痛苦之石和格鲁德会员证。只有在“进度”为各自时才能设为各自。",
|
||||
[UI_MENU_COOP_R_KEYS_DESC] = "小钥匙,按迷宫计。共用:任何人捡到的钥匙进入该迷宫的共用数量,任何人开门都会用掉一把。"
|
||||
"“进度”为各自时为各自。",
|
||||
[UI_MENU_COOP_R_RUPEES_DESC] = "共用:所有玩家共同存入和花费的一个钱包。各自:每人有自己的。",
|
||||
[UI_MENU_COOP_R_AMMO_DESC] = "炸弹、炸弹老鼠、箭、德库坚果、种子和木棒、魔豆。共用:所有玩家共同增加和消耗的一个数量。",
|
||||
[UI_MENU_COOP_SHARED] = "共享", [UI_MENU_COOP_OWN] = "各自", [UI_MENU_COOP_POOL] = "共用",
|
||||
[UI_MENU_COOP_LEAVE] = "离开房间",
|
||||
[UI_MENU_COOP_LEAVE_DESC] = "离开房间。房间给你存档的内容会保留。",
|
||||
[UI_MENU_COOP_LEAVE_CONFIRM] = "离开房间?它给你存档的内容会保留。",
|
||||
[UI_MENU_COOP_LEAVE_MAKER] = "这个房间是你创建的:你不在时,没人能修改规则或移除玩家;如果房间里没有其他人,它会关闭。",
|
||||
[UI_MENU_COOP_STAY] = "留下",
|
||||
[UI_MENU_COOP_TOAST_JOINED] = "%s 加入了房间", [UI_MENU_COOP_TOAST_LEFT] = "%s 离开了房间",
|
||||
[UI_MENU_COOP_TOAST_OFFER] = "合作房间正在菜单的“合作”页等待你的答复",
|
||||
[UI_MENU_COOP_LOST] = "中继丢失了房间;游戏正在重新进入。",
|
||||
[UI_MENU_COOP_JOIN_LIMIT] = "中继暂时不再接受来自你的网络的加入;游戏会在一分钟后重试。",
|
||||
[UI_MENU_COOP_NOT_IDENTIFIED] = "未表明身份", [UI_MENU_COOP_REMOVED] = "已被房主移除",
|
||||
[UI_MENU_COOP_KEY] = "身份指纹 %s",
|
||||
[UI_MENU_COOP_OFFER_KEY] = "规则由身份指纹为 %s 的玩家签署。",
|
||||
[UI_MENU_COOP_OFFER_COMPARE] = "接受之前,请房主通过语音或聊天把他的身份指纹读给你,并与这里的比对。",
|
||||
[UI_MENU_COOP_MY_KEY] = "你的身份指纹(用于签署此房间的规则):%s。请通过语音或聊天读给其他人,以便他们在接受前比对。",
|
||||
[UI_MENU_COOP_UNIDENTIFIED] = "房间中未确认身份的玩家:%d(尚未表明身份,或有两个身份指纹自称是同一名玩家)。只要他们还在"
|
||||
"房间里,任何人都无法接受此房间:房主可以移除他们,或者大家换到新房间。",
|
||||
[UI_MENU_COOP_DISAGREE] = "玩家们携带的规则由不同的身份签署:接受之前,请向房主确认哪个身份指纹是他的。",
|
||||
[UI_MENU_COOP_NEW_SAVE] = "此房间中正在玩另一个存档:它会得到房间的进度,其中包含上一个存档带来的内容。",
|
||||
[UI_MENU_COOP_WARNINGS] = "与陌生人进入房间之前",
|
||||
[UI_MENU_COOP_WARN_SAVE] = "1. 保留一个可以回退的存档。你接受的任何人都能在你的存档中设置剧情标记,他们接受的人也一样;"
|
||||
"共用中的玩家可以用光一个迷宫的小钥匙。移除玩家不会撤销标记:coop-backup/first-<日期和时间> "
|
||||
"中的副本才能。",
|
||||
[UI_MENU_COOP_WARN_ROOM] = "2. 接受与否由你决定,房间却不由你决定。你接受的玩家会转交他们所接受的玩家的标记,而谁能使用"
|
||||
"共用只由房主决定。如果房间里有你不认识的人,不要接受:离开,并请房主开一个新房间。",
|
||||
[UI_MENU_COOP_WARN_KEY] = "3. 核对房主的身份指纹,并保管好你自己的。把签署规则的身份指纹与房主的比对;绝不要用别人给你的"
|
||||
"设置或脚本启动游戏;绝不要交出你的配置文件夹的副本。",
|
||||
[UI_MENU_COOP_POOLS] = "共用",
|
||||
[UI_MENU_COOP_SPENT] = "超出所带来的部分取走了:%lld 把钥匙、%lld 卢比、%lld 份弹药",
|
||||
[UI_MENU_COOP_NOT_IN_ROOM] = "不在房间中",
|
||||
[UI_MENU_COOP_SPENT_NONE] = "没有人从共用中取走的比带来的多。",
|
||||
[UI_MENU_COOP_SPENT_DESC] = "这个身份从共用中取走的比带来的多。用了别人找到的钥匙的玩家也会列在这里;没人预料到的那个人"
|
||||
"掏空了共用。移除这个身份会在所有游戏中归还它取走的东西,玩家离开后也是如此。请在重置共用之前"
|
||||
"移除它:重置时仍在房间中的玩家会保留已取走的东西。",
|
||||
[UI_MENU_COOP_RESET] = "重置共用",
|
||||
[UI_MENU_COOP_RESET_DESC] = "每个游戏都会带着它为房间中玩家保存的数量重新加入共用。这能恢复被已离开的玩家掏空的共用;"
|
||||
"标记保持不变。掏空了共用且仍在房间中的玩家会保留已取走的东西:先移除,再重置。",
|
||||
[UI_MENU_COOP_RESET_CONFIRM] = "为房间中的所有人重置共用?",
|
||||
[UI_MENU_COOP_REMOVE_KEY_CONFIRM] = "将 %s(身份指纹 %s)移出房间?",
|
||||
[UI_MENU_COOP_NOT_ACCEPTED] = "未接受:房间已变化,或其中有玩家未确认身份。请重新查看提议。",
|
||||
[UI_MENU_COOP_ACCEPTED_AS] = "你曾以“%s”之名接受的身份指纹",
|
||||
[UI_BOOT_TITLE] = "正在准备着色器",
|
||||
[UI_BOOT_STARTING] = "正在启动", [UI_BOOT_SHADERS] = "着色器:%lld / %lld", [UI_BOOT_PIPELINES] = "管线:%lld / %lld",
|
||||
[UI_MENU_CHEATS_REBUILD] = "立即重新构建游戏",
|
||||
|
||||
@@ -270,7 +270,50 @@ 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,
|
||||
UI_MENU_LAST_ID = UI_MENU_SAVE_E_UNSAFE,
|
||||
// the Co-op tab (ui/coop_page.cpp, docs/coop.md)
|
||||
UI_MENU_TAB_COOP,
|
||||
UI_MENU_COOP_ON, UI_MENU_COOP_ON_DESC,
|
||||
UI_MENU_COOP_NAME, UI_MENU_COOP_NAME_DESC, UI_MENU_COOP_AUTO,
|
||||
UI_MENU_COOP_SERVER, UI_MENU_COOP_SERVER_DESC, UI_MENU_COOP_NONE,
|
||||
UI_MENU_COOP_MAKE, UI_MENU_COOP_MAKE_DESC, UI_MENU_COOP_JOIN, UI_MENU_COOP_JOIN_DESC,
|
||||
UI_MENU_COOP_NEED_SERVER, // under Make and Join while no relay is set
|
||||
UI_MENU_COOP_SECRET, UI_MENU_COOP_SECRET_HINT, UI_MENU_COOP_SECRET_BAD, UI_MENU_COOP_PASTE, UI_MENU_COOP_PASTE_EMPTY,
|
||||
UI_MENU_COOP_OK, UI_MENU_COOP_STOP, UI_MENU_COOP_STOP_DESC,
|
||||
UI_MENU_COOP_CONNECTING, UI_MENU_COOP_RECONNECTING, UI_MENU_COOP_LEFT, // "%s": the co-op layer's reason (English)
|
||||
UI_MENU_COOP_NO_ROOM, UI_MENU_COOP_NOT_STARTED,
|
||||
UI_MENU_COOP_PLAYERS, UI_MENU_COOP_YOU, UI_MENU_COOP_MAKER, UI_MENU_COOP_HEARD /* "%u": seconds */,
|
||||
UI_MENU_COOP_NOT_HEARD, UI_MENU_COOP_AWAY, UI_MENU_COOP_MEMBER_DESC,
|
||||
UI_MENU_COOP_REMOVE, UI_MENU_COOP_REMOVE_DESC, UI_MENU_COOP_REMOVE_CONFIRM /* "%s": the player's name */,
|
||||
UI_MENU_COOP_SECRET_DESC, UI_MENU_COOP_SHOW, UI_MENU_COOP_HIDE, UI_MENU_COOP_COPY, UI_MENU_COOP_COPY_DESC,
|
||||
UI_MENU_COOP_OFFER, UI_MENU_COOP_OFFER_WHO /* "%s": names */, UI_MENU_COOP_OFFER_NOBODY,
|
||||
UI_MENU_COOP_OFFER_SHARED, UI_MENU_COOP_OFFER_POOLED /* "%s": rule names */, UI_MENU_COOP_OFFER_NOTHING,
|
||||
UI_MENU_COOP_OFFER_COPY, UI_MENU_COOP_OFFER_TRUST,
|
||||
UI_MENU_COOP_ANSWER, UI_MENU_COOP_ANSWER_DESC, UI_MENU_COOP_ACCEPT_CONFIRM, UI_MENU_COOP_ACCEPT, UI_MENU_COOP_NOT_NOW,
|
||||
UI_MENU_COOP_ACCEPTED, UI_MENU_COOP_COPY_FAILED,
|
||||
UI_MENU_COOP_RULES_ROOM, UI_MENU_COOP_RULES_MINE, UI_MENU_COOP_RULES_UNKNOWN, UI_MENU_COOP_RULES_CHANGE,
|
||||
UI_MENU_COOP_RULES_SET_BY, UI_MENU_COOP_RULE_FOLLOWS,
|
||||
UI_MENU_COOP_R_PROGRESS, UI_MENU_COOP_R_ITEMS, UI_MENU_COOP_R_SONGS, UI_MENU_COOP_R_QUEST, UI_MENU_COOP_R_KEYS,
|
||||
UI_MENU_COOP_R_RUPEES, UI_MENU_COOP_R_AMMO, // in coop_state.h's category order, as are the descriptions
|
||||
UI_MENU_COOP_R_PROGRESS_DESC, UI_MENU_COOP_R_ITEMS_DESC, UI_MENU_COOP_R_SONGS_DESC, UI_MENU_COOP_R_QUEST_DESC,
|
||||
UI_MENU_COOP_R_KEYS_DESC, UI_MENU_COOP_R_RUPEES_DESC, UI_MENU_COOP_R_AMMO_DESC,
|
||||
UI_MENU_COOP_SHARED, UI_MENU_COOP_OWN, UI_MENU_COOP_POOL,
|
||||
UI_MENU_COOP_LEAVE, UI_MENU_COOP_LEAVE_DESC, UI_MENU_COOP_LEAVE_CONFIRM, UI_MENU_COOP_LEAVE_MAKER, UI_MENU_COOP_STAY,
|
||||
UI_MENU_COOP_TOAST_JOINED, UI_MENU_COOP_TOAST_LEFT /* "%s": a name */, UI_MENU_COOP_TOAST_OFFER,
|
||||
// what the hardened layer adds to the Co-op tab: the relay's states, keys and identification, the maker's key, the
|
||||
// three warnings before the first Accept, the pools' contributors and the maker's reset
|
||||
UI_MENU_COOP_LOST, UI_MENU_COOP_JOIN_LIMIT,
|
||||
UI_MENU_COOP_NOT_IDENTIFIED, UI_MENU_COOP_REMOVED, UI_MENU_COOP_KEY /* "%s": a key's fingerprint */,
|
||||
UI_MENU_COOP_OFFER_KEY /* "%s": a key's fingerprint */, UI_MENU_COOP_OFFER_COMPARE,
|
||||
UI_MENU_COOP_MY_KEY /* "%s": a key's fingerprint */,
|
||||
UI_MENU_COOP_UNIDENTIFIED /* "%d": players */, UI_MENU_COOP_DISAGREE, UI_MENU_COOP_NEW_SAVE,
|
||||
UI_MENU_COOP_WARNINGS, UI_MENU_COOP_WARN_SAVE, UI_MENU_COOP_WARN_ROOM, UI_MENU_COOP_WARN_KEY,
|
||||
UI_MENU_COOP_POOLS, UI_MENU_COOP_SPENT /* "%lld": keys, rupees, ammunition */, UI_MENU_COOP_NOT_IN_ROOM,
|
||||
UI_MENU_COOP_SPENT_NONE, UI_MENU_COOP_SPENT_DESC,
|
||||
UI_MENU_COOP_RESET, UI_MENU_COOP_RESET_DESC, UI_MENU_COOP_RESET_CONFIRM,
|
||||
UI_MENU_COOP_REMOVE_KEY_CONFIRM /* "%s": the player's name, "%s": the key's fingerprint */, UI_MENU_COOP_NOT_ACCEPTED,
|
||||
// a key the player accepted, now signed under another name: a new offer (CoopOfferMember.accepted_as)
|
||||
UI_MENU_COOP_ACCEPTED_AS /* "%s": the name it was accepted under */,
|
||||
UI_MENU_LAST_ID = UI_MENU_COOP_ACCEPTED_AS,
|
||||
// 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
|
||||
|
||||
Reference in New Issue
Block a user