mirror of
https://git.triforceproject.com/triforce/source
synced 2026-11-19 16:20:01 -04:00
Triforce v0.2.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
33
host/PROVENANCE.md
Normal file
33
host/PROVENANCE.md
Normal file
@@ -0,0 +1,33 @@
|
||||
# host/: the standalone runtime
|
||||
|
||||
A fork of the Horizon OS layer of NotRexed's a64-kit (`hos/`, TOTKPort commit `e88744a`, 2026-10-31), the runtime
|
||||
that runs Tears of the Kingdom natively. It replaces the Nintendo SDK at the `nn::` boundary: an
|
||||
`HLE(<mangled name>)` function here stands in for that SDK function wherever the game calls it
|
||||
(`nx2/standalone.py` picks them up at lift time). The rest of the SDK runs as lifted code.
|
||||
|
||||
Taken unmodified except as noted:
|
||||
`hos.h`, `hos_main.c`, `hos_mem.c`, `hos_thread.c`, `hos_svc.c`, `hos_hostcall.c`, `nn_os_sync.c`, `nn_fs.c`,
|
||||
`nn_hid.c`, `nn_libc.c`, `nn_diag.c`, `nn_applet.c`, `nn_audio.c`, `nvdrv.c`.
|
||||
|
||||
mkw-recomp's changes:
|
||||
- **The guest window.** It is 64-bit, 512 GB, reserved whole. The image sits at Eden's `0x80000000`, the address the
|
||||
code was lifted for. The heap starts at 64 GB, and address regions grow down from 512 GB (`hos.h`). The runtime
|
||||
commits what it hands out (`hos_commit`), and `mkw_glue.c` commits anything else on first touch. TOTK's whole
|
||||
4 GB window was committed up front.
|
||||
- `hos_main.c`: the image base comes from `gen/hos_image.c`.
|
||||
- `hos_mem.c`: the default memory size is a Switch 2 application's 9809 MB.
|
||||
- `hos_svc.c`: MKW's program id, and the code region at the image base.
|
||||
- **Graphics.** `nvn_native.c` is TOTKPort's native NVN layer for NVN2: the Switch 2 driver's device limits (read by
|
||||
running its nvnDeviceGetInteger under Unicorn), GPU addresses over the 64-bit window (identity below 1 TB, virtual
|
||||
pools above), program builders, native images, sparse tile layouts; procs it lacks log their first call and answer
|
||||
0 (`HOS_NVN_STRICT=1`: stop, as in TOTKPort). `display.c` is TOTKPort's window without its emulated-GPU fallback.
|
||||
The replay was `gpu/render` (see `gpu/PROVENANCE.md`); it is the Vulkan back end in `gpu/vk` now, with `gpu/render`
|
||||
as the fallback (`host/rx_backend.c`). `nn_vi.c` is MKW's own, with the window's frame pacing.
|
||||
- **Virtual cores** (`hos_thread.c`): on by default with six cores; a waiter's request reaches a holder at its next
|
||||
loop header too (`mkw_glue.c` `a64_poll`), and equal-priority holders yield after a 2 ms slice.
|
||||
- **Left out:** files bound to TOTK or its Maxwell GPU: `gpu.c`, `nvn_trace.c`, `hos_prof.c`, `mods.c`, `movie*.c`,
|
||||
`nn_image_debug.c`, `totk_*.c`. `mkw_glue.c` stands in for the hooks the taken files call into them. `mods.c`
|
||||
came back later as Hookshot's `host/mods.c`: the RomFS part of Skybound's loader (`NotRexed/SkyboundTotk`, MIT).
|
||||
|
||||
Licensing follows a64-kit: GPL, through suyu's translator in the lifted code (see
|
||||
`third_party/a64-kit/NOTICE.TOTKPort.md`).
|
||||
324
host/discord_rpc.c
Normal file
324
host/discord_rpc.c
Normal file
@@ -0,0 +1,324 @@
|
||||
/* (hookshot) Discord Rich Presence: "Playing Hookshot" with the time played in the player's Discord status, through the local
|
||||
IPC of a Discord client running on this PC. Nothing leaves the machine but the activity itself, and nothing is sent while the
|
||||
Insert menu's "Discord status" row is off (on by default; it does nothing without a Discord client running).
|
||||
|
||||
Discord shows the *application's* name above the status ("Playing <name>") and its art: the status needs a Discord application
|
||||
of its own (discord.com/developers/applications, named Hookshot, its art uploaded under Rich Presence > Art Assets with the key
|
||||
below). Its Application ID goes into HOOKSHOT_DISCORD_APP_ID_DEFAULT; triforce_options.ini's discord_app_id= or
|
||||
HOS_DISCORD_APP_ID override it. With no id the thread stays idle and says so once in the log.
|
||||
|
||||
One host thread owns the connection. It connects to the first of Discord's discord-ipc-0..9 that completes a handshake and
|
||||
writes the activity again every 60 s: that write is the keep-alive, and one that fails closes the connection and tries again
|
||||
15 s later. Discord clears the status itself when the process ends and the pipe closes. Every answer is read and dropped:
|
||||
unread, they would fill the pipe and block the client.
|
||||
|
||||
The protocol is Discord's documented IPC (discord-rpc's rpc_connection.h): a frame is <opcode u32 LE><length u32 LE><JSON>,
|
||||
Handshake 0, Frame 1, Close 2, Ping 3, Pong 4. The handshake {"v":1,"client_id":...} is answered by a Ready frame; a
|
||||
SET_ACTIVITY frame by a frame; a Ping is echoed as a Pong. */
|
||||
#include "hos_paths.h" /* (first: hos_game_path_a, and windows.h on Windows) */
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <errno.h>
|
||||
#include <poll.h>
|
||||
#include <pthread.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include "../gpu/vk/vk_api.h"
|
||||
|
||||
#define HOOKSHOT_DISCORD_APP_ID_DEFAULT "" /* (Triforce: no Discord application of its own, so no status unless the player names one: upstream Hookshot's id would announce "Playing Hookshot") */
|
||||
#define HOOKSHOT_DISCORD_IMAGE_DEFAULT "hookshot" /* (its large-image art asset key) */
|
||||
|
||||
void hos_log(const char *fmt, ...);
|
||||
int rx_option(int id, int otherwise);
|
||||
const char *hos_version(void); /* hos_main.c */
|
||||
|
||||
enum { OP_HANDSHAKE = 0, OP_FRAME = 1, OP_CLOSE = 2, OP_PING = 3, OP_PONG = 4 };
|
||||
#define ANSWER_CAP 8192
|
||||
|
||||
/* ---- the local connection: a named pipe on Windows, a Unix socket elsewhere ---- */
|
||||
#ifdef _WIN32
|
||||
typedef HANDLE Ipc;
|
||||
#define IPC_NONE INVALID_HANDLE_VALUE
|
||||
static uint64_t now_ms(void) { return GetTickCount64(); }
|
||||
static void sleep_ms(unsigned ms) { Sleep(ms); }
|
||||
static Ipc ipc_connect(int i) {
|
||||
char name[48];
|
||||
snprintf(name, sizeof name, "\\\\.\\pipe\\discord-ipc-%d", i);
|
||||
/* (identification only: another program that made a pipe of this name cannot act as this one) */
|
||||
return CreateFileA(name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION,
|
||||
NULL);
|
||||
}
|
||||
static void ipc_close(Ipc p) { CloseHandle(p); }
|
||||
static int ipc_write(Ipc p, const void *d, size_t n) {
|
||||
DWORD done = 0;
|
||||
return WriteFile(p, d, (DWORD)n, &done, NULL) && done == n;
|
||||
}
|
||||
/* bytes read (0: none came before the deadline), -1 broken */
|
||||
static int ipc_read(Ipc p, void *d, size_t n, uint64_t deadline) {
|
||||
for (;;) {
|
||||
DWORD avail = 0;
|
||||
if (!PeekNamedPipe(p, NULL, 0, NULL, &avail, NULL)) return -1;
|
||||
if (avail) {
|
||||
DWORD got = 0;
|
||||
if (!ReadFile(p, d, (DWORD)(n < avail ? n : avail), &got, NULL)) return -1;
|
||||
return (int)got;
|
||||
}
|
||||
if (now_ms() >= deadline) return 0;
|
||||
Sleep(10);
|
||||
}
|
||||
}
|
||||
static unsigned long process_id(void) { return GetCurrentProcessId(); }
|
||||
#else
|
||||
typedef int Ipc;
|
||||
#define IPC_NONE (-1)
|
||||
static uint64_t now_ms(void) {
|
||||
struct timespec t;
|
||||
clock_gettime(CLOCK_MONOTONIC, &t);
|
||||
return (uint64_t)t.tv_sec * 1000 + (uint64_t)t.tv_nsec / 1000000;
|
||||
}
|
||||
static void sleep_ms(unsigned ms) { usleep(ms * 1000u); }
|
||||
static Ipc ipc_connect(int i) {
|
||||
const char *dir = getenv("XDG_RUNTIME_DIR");
|
||||
if (!dir) dir = getenv("TMPDIR");
|
||||
if (!dir) dir = "/tmp";
|
||||
/* (Flatpak and Snap Discord put theirs one folder down) */
|
||||
const char *subs[] = {"", "app/com.discordapp.Discord/", "snap.discord/"};
|
||||
for (size_t s = 0; s < sizeof subs / sizeof *subs; s++) {
|
||||
struct sockaddr_un a;
|
||||
memset(&a, 0, sizeof a);
|
||||
a.sun_family = AF_UNIX;
|
||||
snprintf(a.sun_path, sizeof a.sun_path, "%s/%sdiscord-ipc-%d", dir, subs[s], i);
|
||||
const int fd = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
if (fd < 0) return IPC_NONE;
|
||||
if (!connect(fd, (struct sockaddr *)&a, sizeof a)) return fd;
|
||||
close(fd);
|
||||
}
|
||||
return IPC_NONE;
|
||||
}
|
||||
static void ipc_close(Ipc p) { close(p); }
|
||||
static int ipc_write(Ipc p, const void *d, size_t n) {
|
||||
const char *c = d;
|
||||
while (n) {
|
||||
const ssize_t w = send(p, c, n, MSG_NOSIGNAL);
|
||||
if (w <= 0) return 0;
|
||||
c += w, n -= (size_t)w;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
static int ipc_read(Ipc p, void *d, size_t n, uint64_t deadline) {
|
||||
const uint64_t t = now_ms();
|
||||
struct pollfd f = {p, POLLIN, 0};
|
||||
const int r = poll(&f, 1, deadline > t ? (int)(deadline - t) : 0);
|
||||
if (r < 0) return errno == EINTR ? 0 : -1;
|
||||
if (!r) return 0;
|
||||
const ssize_t got = recv(p, d, n, 0);
|
||||
return got > 0 ? (int)got : -1;
|
||||
}
|
||||
static unsigned long process_id(void) { return (unsigned long)getpid(); }
|
||||
#endif
|
||||
|
||||
/* ---- settings ---- */
|
||||
static int valid_app_id(const char *s) {
|
||||
const size_t n = strlen(s);
|
||||
if (!n || n > 20) return 0;
|
||||
for (; *s; s++)
|
||||
if (*s < '0' || *s > '9') return 0;
|
||||
return 1;
|
||||
}
|
||||
/* the application id: HOS_DISCORD_APP_ID, then triforce_options.ini's discord_app_id=, then the default */
|
||||
static void read_app_id(char *out, size_t cap) {
|
||||
snprintf(out, cap, "%s", HOOKSHOT_DISCORD_APP_ID_DEFAULT);
|
||||
char path[1024];
|
||||
const DWORD n = hos_game_path_a(path, (DWORD)sizeof path);
|
||||
char *slash = n ? (strrchr(path, '\\') ? strrchr(path, '\\') : strrchr(path, '/')) : NULL;
|
||||
if (slash) {
|
||||
snprintf(slash + 1, (size_t)(path + sizeof path - slash - 1), "triforce_options.ini");
|
||||
FILE *f = fopen(path, "r");
|
||||
if (f) {
|
||||
char line[128];
|
||||
while (fgets(line, sizeof line, f))
|
||||
if (!strncmp(line, "discord_app_id=", 15)) {
|
||||
line[strcspn(line, "\r\n")] = 0;
|
||||
if (valid_app_id(line + 15)) snprintf(out, cap, "%s", line + 15);
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
}
|
||||
const char *e = getenv("HOS_DISCORD_APP_ID");
|
||||
if (e && valid_app_id(e)) snprintf(out, cap, "%s", e);
|
||||
if (*out && !valid_app_id(out)) *out = 0;
|
||||
}
|
||||
|
||||
/* ---- frames ---- */
|
||||
static void le32(uint8_t *at, uint32_t v) { at[0] = (uint8_t)v, at[1] = (uint8_t)(v >> 8), at[2] = (uint8_t)(v >> 16), at[3] = (uint8_t)(v >> 24); }
|
||||
static int write_frame(Ipc p, uint32_t op, const char *json) {
|
||||
uint8_t head[8];
|
||||
le32(head, op), le32(head + 4, (uint32_t)strlen(json));
|
||||
return ipc_write(p, head, sizeof head) && ipc_write(p, json, strlen(json));
|
||||
}
|
||||
/* 1 a whole frame (buf NUL-terminated, a longer payload cut), 0 the deadline passed, -1 broken */
|
||||
static int read_one_frame(Ipc p, uint32_t *op, char *buf, size_t cap, uint64_t deadline) {
|
||||
uint8_t head[8];
|
||||
size_t got = 0;
|
||||
while (got < sizeof head) {
|
||||
const int n = ipc_read(p, head + got, sizeof head - got, deadline);
|
||||
if (n < 0) return -1;
|
||||
if (!n) return 0;
|
||||
got += (size_t)n;
|
||||
}
|
||||
*op = head[0] | head[1] << 8 | head[2] << 16 | (uint32_t)head[3] << 24;
|
||||
const uint32_t len = head[4] | head[5] << 8 | head[6] << 16 | (uint32_t)head[7] << 24;
|
||||
size_t taken = 0, kept = 0;
|
||||
while (taken < len) {
|
||||
char tmp[512];
|
||||
size_t want = len - taken;
|
||||
if (want > sizeof tmp) want = sizeof tmp;
|
||||
const int n = ipc_read(p, tmp, want, deadline);
|
||||
if (n < 0) return -1;
|
||||
if (!n) return 0;
|
||||
for (int i = 0; i < n && kept + 1 < cap; i++) buf[kept++] = tmp[i];
|
||||
taken += (size_t)n;
|
||||
}
|
||||
buf[kept] = 0;
|
||||
return 1;
|
||||
}
|
||||
/* the next frame that is not a Ping (echoed as a Pong); a Close counts as broken */
|
||||
static int read_frame(Ipc p, uint32_t *op, char *buf, size_t cap, unsigned ms) {
|
||||
const uint64_t deadline = now_ms() + ms;
|
||||
for (;;) {
|
||||
const int r = read_one_frame(p, op, buf, cap, deadline);
|
||||
if (r != 1) return r;
|
||||
if (*op == OP_PING) {
|
||||
if (!write_frame(p, OP_PONG, buf)) return -1;
|
||||
continue;
|
||||
}
|
||||
return *op == OP_CLOSE ? -1 : 1;
|
||||
}
|
||||
}
|
||||
static Ipc connect_client(const char *app_id) {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
const Ipc p = ipc_connect(i);
|
||||
if (p == IPC_NONE) continue;
|
||||
char json[96], answer[ANSWER_CAP];
|
||||
snprintf(json, sizeof json, "{\"v\":1,\"client_id\":\"%s\"}", app_id);
|
||||
uint32_t op = 0;
|
||||
if (write_frame(p, OP_HANDSHAKE, json) && read_frame(p, &op, answer, sizeof answer, 2000) == 1 && op == OP_FRAME) return p;
|
||||
ipc_close(p);
|
||||
}
|
||||
return IPC_NONE;
|
||||
}
|
||||
/* the activity: the release in the details, the start of play for the elapsed time, the application's art */
|
||||
static int send_activity(Ipc p, long long started) {
|
||||
static unsigned nonce;
|
||||
char version[48], json[640], answer[ANSWER_CAP];
|
||||
snprintf(version, sizeof version, "%s", hos_version());
|
||||
version[strcspn(version, " +")] = 0; /* ("v2.0.12 (source ...)": the release alone) */
|
||||
snprintf(json, sizeof json,
|
||||
"{\"cmd\":\"SET_ACTIVITY\",\"nonce\":\"%u\",\"args\":{\"pid\":%lu,\"activity\":{\"details\":\"Ocarina of Time\","
|
||||
"\"state\":\"Hookshot %s\",\"timestamps\":{\"start\":%lld},\"assets\":{\"large_image\":\"%s\",\"large_text\":"
|
||||
"\"Hookshot %s\"}}}}",
|
||||
++nonce, process_id(), version, started, HOOKSHOT_DISCORD_IMAGE_DEFAULT, version);
|
||||
if (!write_frame(p, OP_FRAME, json)) return 0;
|
||||
uint32_t op = 0;
|
||||
const int r = read_frame(p, &op, answer, sizeof answer, 2000);
|
||||
static int said;
|
||||
if (r == 1 && !said) { /* (Discord's answer, once: an ERROR event says why it took no status) */
|
||||
said = 1;
|
||||
if (strstr(answer, "\"evt\":\"ERROR\"")) hos_log("discord: the status was refused: %.300s", answer);
|
||||
else hos_log("discord: status set");
|
||||
}
|
||||
return r >= 0;
|
||||
}
|
||||
|
||||
/* ---- the presence thread ---- */
|
||||
static void presence_main(void) {
|
||||
char app_id[24];
|
||||
read_app_id(app_id, sizeof app_id);
|
||||
const long long started = (long long)time(NULL);
|
||||
Ipc ipc = IPC_NONE;
|
||||
uint64_t retry_at = 0, send_at = 0, reread_at = now_ms() + 15000;
|
||||
int said_no_client = 0, said_no_app = 0;
|
||||
for (;;) {
|
||||
sleep_ms(500);
|
||||
if (now_ms() >= reread_at) { /* (an id typed into the options file while the game runs) */
|
||||
char was[24];
|
||||
memcpy(was, app_id, sizeof was);
|
||||
read_app_id(app_id, sizeof app_id);
|
||||
if (strcmp(was, app_id)) {
|
||||
if (ipc != IPC_NONE) ipc_close(ipc), ipc = IPC_NONE;
|
||||
retry_at = 0, said_no_app = 0;
|
||||
}
|
||||
reread_at = now_ms() + 15000;
|
||||
}
|
||||
if (!rx_option(HOS_OPT_DISCORD, 1)) { /* the Insert menu's row, off */
|
||||
if (ipc != IPC_NONE) ipc_close(ipc), ipc = IPC_NONE;
|
||||
continue;
|
||||
}
|
||||
if (!app_id[0]) {
|
||||
if (!said_no_app)
|
||||
hos_log("discord: no application id: discord_app_id= in triforce_options.ini or HOS_DISCORD_APP_ID (the "
|
||||
"Discord application named Hookshot); the status stays off");
|
||||
said_no_app = 1;
|
||||
continue;
|
||||
}
|
||||
if (ipc == IPC_NONE && now_ms() >= retry_at) {
|
||||
ipc = connect_client(app_id);
|
||||
if (ipc == IPC_NONE) {
|
||||
retry_at = now_ms() + 15000;
|
||||
if (!said_no_client) hos_log("discord: no Discord client is running; trying again every 15 s");
|
||||
said_no_client = 1;
|
||||
} else {
|
||||
hos_log("discord: connected (application %s)", app_id);
|
||||
send_at = 0, said_no_client = 0;
|
||||
}
|
||||
}
|
||||
if (ipc != IPC_NONE && now_ms() >= send_at) {
|
||||
if (send_activity(ipc, started)) {
|
||||
send_at = now_ms() + 60000;
|
||||
} else {
|
||||
hos_log("discord: the connection broke; connecting again");
|
||||
ipc_close(ipc), ipc = IPC_NONE;
|
||||
retry_at = now_ms() + 15000;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#ifdef _WIN32
|
||||
static DWORD WINAPI presence_thread(LPVOID arg) {
|
||||
(void)arg;
|
||||
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);
|
||||
presence_main();
|
||||
return 0;
|
||||
}
|
||||
#else
|
||||
static void *presence_thread(void *arg) {
|
||||
(void)arg;
|
||||
presence_main();
|
||||
return NULL;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* hos_main.c, once the game starts (not for --prepare-shaders). HOS_DISCORD=0: no thread at all */
|
||||
void hos_discord_start(void) {
|
||||
const char *e = getenv("HOS_DISCORD");
|
||||
if (e && !atoi(e)) return;
|
||||
#ifdef _WIN32
|
||||
HANDLE t = CreateThread(NULL, 256u << 10, presence_thread, NULL, 0, NULL);
|
||||
if (t) CloseHandle(t);
|
||||
else hos_log("discord: cannot start the presence thread");
|
||||
#else
|
||||
pthread_t t;
|
||||
if (!pthread_create(&t, NULL, presence_thread, NULL)) pthread_detach(t);
|
||||
else hos_log("discord: cannot start the presence thread");
|
||||
#endif
|
||||
}
|
||||
478
host/display.c
Normal file
478
host/display.c
Normal file
@@ -0,0 +1,478 @@
|
||||
/* The game's window (Windows): the renderer's surface (gpu/render/, WebGPU). The native NVN layer (nvn_native.c)
|
||||
presents the game's window textures into it (rx_nvn_present). The title bar carries live numbers.
|
||||
TOTKPort's hos/display.c, without its emulated-GPU fallback (the window buffer read from guest memory): MKW has
|
||||
no emulated GPU, so the renderer is the only way to a picture.
|
||||
HOS_HEADLESS=1: no window (scripted runs; the renderer draws offscreen). Closing the window ends the run.
|
||||
HOS_WINDOW_NOACTIVATE=1: the window opens behind the one in front (test runs do not take the keyboard).
|
||||
HOS_WINDOW_SIZE=<w>x<h>: the client area (default 1280x720 at 96 dpi). F10 or Alt+Enter: fullscreen (F11 is off).
|
||||
Mouse: a click in the window captures the mouse (hidden, kept in the window), Esc or leaving the window releases
|
||||
it (nn_hid.c reads its motion). While the Insert menu is open the mouse is free (the cursor shown, for the menu's
|
||||
clicks: hos_mouse_pointer) and the game gets none of it; the capture it had comes back when the menu closes. The same
|
||||
while one of the game's own menus is open (host/oot_menu.c: hos_mouse_game_menu each frame it runs), its clicks and
|
||||
wheel for that menu (hos_mouse_game_pointer). */
|
||||
#include "hos.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#include "../gpu/render/rx.h"
|
||||
void rx_close_asked(void); /* host/rx_backend.c */
|
||||
#include "../gpu/vk/vk_api.h"
|
||||
|
||||
void hos_relaunch_ask(void); /* (host/hos_relaunch.c) */
|
||||
void hos_window_closed_exit(void);
|
||||
#ifndef WM_DPICHANGED
|
||||
#define WM_DPICHANGED 0x02E0
|
||||
#endif
|
||||
|
||||
volatile LONG64 hos_present_count; /* (nvn_native.c: the game's presents) */
|
||||
static HWND hwnd;
|
||||
static int renderer; /* the renderer presents into the window */
|
||||
|
||||
/* mouse capture: raw motion accumulated here, taken by nn_hid.c */
|
||||
static volatile LONG mouse_dx, mouse_dy;
|
||||
static volatile LONG mouse_captured;
|
||||
static int cursor_hidden;
|
||||
|
||||
int hos_mouse_take(int32_t *dx, int32_t *dy) {
|
||||
*dx = InterlockedExchange(&mouse_dx, 0);
|
||||
*dy = InterlockedExchange(&mouse_dy, 0);
|
||||
return mouse_captured;
|
||||
}
|
||||
|
||||
/* (mouse_native.c) motion taken and not used, put back for the next taker (the player camera's) */
|
||||
void hos_mouse_give_back(int32_t dx, int32_t dy) {
|
||||
InterlockedExchangeAdd(&mouse_dx, dx);
|
||||
InterlockedExchangeAdd(&mouse_dy, dy);
|
||||
}
|
||||
|
||||
/* the free mouse, for the Insert menu (gpu/vk/vk_api.h MkwVkPointer): set on the window's thread, read on the renderer's */
|
||||
static volatile LONG ptr_x, ptr_y, ptr_w, ptr_h, ptr_in, ptr_pressed, ptr_wheel; /* (client pixels; wheel in WHEEL_DELTA units) */
|
||||
static int menu_open, captured_before_menu;
|
||||
/* the game's own menus: open while one of their screens runs with the mouse (stamped each frame on the
|
||||
game's thread), their clicks */
|
||||
static int game_menu_open;
|
||||
static volatile LONG64 game_menu_seen_ns;
|
||||
static volatile LONG gm_pressed, gm_wheel;
|
||||
/* The cursor over the game's menus is hidden until the mouse is used (moved or a button pressed) and again once the
|
||||
pads or the keys are (nn_hid.c: hos_player_input_ns): a player on a controller never sees it, and a mouse at rest
|
||||
takes no part (no pointing or clicks while hidden). The wheel works hidden too, and does not show it: a button held
|
||||
(R, for the item choice) counts as the pad in use, and hid the cursor again at each notch */
|
||||
int64_t hos_player_input_ns(void);
|
||||
static volatile LONG gm_shown, gm_mx = -1, gm_my = -1;
|
||||
static volatile LONG64 gm_mouse_ns;
|
||||
static void gm_mouse_used(void) { InterlockedExchange64(&gm_mouse_ns, (LONG64)hos_now_ns()); InterlockedExchange(&gm_shown, 1); }
|
||||
static int gm_cursor_shown(void) {
|
||||
if (gm_shown && hos_player_input_ns() > InterlockedCompareExchange64(&gm_mouse_ns, 0, 0)) InterlockedExchange(&gm_shown, 0);
|
||||
return (int)gm_shown;
|
||||
}
|
||||
|
||||
int hos_mouse_pointer(MkwVkPointer *out) {
|
||||
memset(out, 0, sizeof *out);
|
||||
if (!hwnd || mouse_captured) return 0;
|
||||
out->x = ptr_x, out->y = ptr_y, out->width = ptr_w, out->height = ptr_h;
|
||||
out->held = ((GetAsyncKeyState(VK_LBUTTON) & 0x8000) ? HOS_MOUSE_LEFT : 0) |
|
||||
((GetAsyncKeyState(VK_RBUTTON) & 0x8000) ? HOS_MOUSE_RIGHT : 0) |
|
||||
((GetAsyncKeyState(VK_MBUTTON) & 0x8000) ? HOS_MOUSE_MIDDLE : 0);
|
||||
out->pressed = (uint32_t)InterlockedExchange(&ptr_pressed, 0);
|
||||
const LONG wheel = InterlockedExchange(&ptr_wheel, 0);
|
||||
out->wheel = wheel / WHEEL_DELTA;
|
||||
if (wheel % WHEEL_DELTA) InterlockedExchangeAdd(&ptr_wheel, wheel % WHEEL_DELTA); /* (a part of a notch: kept) */
|
||||
return ptr_in && GetForegroundWindow() == hwnd && out->width > 0 && out->height > 0;
|
||||
}
|
||||
|
||||
static HANDLE renderer_up;
|
||||
static int fullscreen;
|
||||
static WINDOWPLACEMENT windowed_place;
|
||||
|
||||
static void set_fullscreen(HWND w, int on) {
|
||||
if (on == fullscreen) return;
|
||||
const LONG style = GetWindowLongA(w, GWL_STYLE);
|
||||
if (on) {
|
||||
MONITORINFO mi;
|
||||
mi.cbSize = sizeof mi;
|
||||
windowed_place.length = sizeof windowed_place;
|
||||
if (!GetWindowPlacement(w, &windowed_place) ||
|
||||
!GetMonitorInfoA(MonitorFromWindow(w, MONITOR_DEFAULTTONEAREST), &mi))
|
||||
return;
|
||||
fullscreen = 1;
|
||||
SetWindowLongA(w, GWL_STYLE, style & ~WS_OVERLAPPEDWINDOW);
|
||||
SetWindowPos(w, HWND_TOP, mi.rcMonitor.left, mi.rcMonitor.top, mi.rcMonitor.right - mi.rcMonitor.left,
|
||||
mi.rcMonitor.bottom - mi.rcMonitor.top, SWP_NOOWNERZORDER | SWP_FRAMECHANGED);
|
||||
} else {
|
||||
fullscreen = 0;
|
||||
SetWindowLongA(w, GWL_STYLE, style | WS_OVERLAPPEDWINDOW);
|
||||
SetWindowPlacement(w, &windowed_place);
|
||||
SetWindowPos(w, NULL, 0, 0, 0, 0,
|
||||
SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED);
|
||||
}
|
||||
hos_log("display: %s", on ? "fullscreen" : "windowed");
|
||||
}
|
||||
|
||||
static void dpi_aware_thread(void) {
|
||||
if (getenv("HOS_DPI_UNAWARE")) return;
|
||||
typedef void *(WINAPI * SetCtx)(void *);
|
||||
SetCtx set = (SetCtx)(void *)GetProcAddress(GetModuleHandleA("user32.dll"), "SetThreadDpiAwarenessContext");
|
||||
if (set) set((void *)(intptr_t)-4);
|
||||
}
|
||||
|
||||
static UINT window_dpi(HWND w) {
|
||||
typedef UINT(WINAPI * GetDpi)(HWND);
|
||||
GetDpi get = (GetDpi)(void *)GetProcAddress(GetModuleHandleA("user32.dll"), "GetDpiForWindow");
|
||||
const UINT dpi = get ? get(w) : 96;
|
||||
return dpi ? dpi : 96;
|
||||
}
|
||||
|
||||
static void mouse_capture(HWND w, int on) {
|
||||
if (on == (int)mouse_captured) return;
|
||||
mouse_captured = on;
|
||||
InterlockedExchange(&mouse_dx, 0);
|
||||
InterlockedExchange(&mouse_dy, 0);
|
||||
if (on) {
|
||||
RECT rc;
|
||||
GetClientRect(w, &rc);
|
||||
MapWindowPoints(w, NULL, (POINT *)&rc, 2);
|
||||
ClipCursor(&rc);
|
||||
if (!cursor_hidden) { ShowCursor(FALSE); cursor_hidden = 1; }
|
||||
} else {
|
||||
ClipCursor(NULL);
|
||||
if (cursor_hidden) { ShowCursor(TRUE); cursor_hidden = 0; }
|
||||
}
|
||||
}
|
||||
|
||||
/* the cursor hidden now while it is over the window (not at the next move's WM_SETCURSOR) */
|
||||
static void gm_cursor_off(HWND w) {
|
||||
POINT p;
|
||||
RECT rc;
|
||||
if (GetCursorPos(&p) && ScreenToClient(w, &p) && GetClientRect(w, &rc) && PtInRect(&rc, p)) SetCursor(NULL);
|
||||
}
|
||||
/* a menu opened (the Insert menu or the game's): the mouse let go (its capture kept for later); both closed: the capture
|
||||
back, if the window still has the focus */
|
||||
static void menus_mouse(HWND w, int insert_open, int game_open) {
|
||||
const int was = menu_open || game_menu_open, now = insert_open || game_open, game_was = game_menu_open;
|
||||
menu_open = insert_open, game_menu_open = game_open;
|
||||
/* (hidden till used; a menu back within a second, a moment between its screens, keeps the cursor as it was) */
|
||||
static int64_t game_closed_ns;
|
||||
if (!game_open && game_was) game_closed_ns = hos_now_ns();
|
||||
if (game_open && !game_was && (!game_closed_ns || hos_now_ns() - game_closed_ns > 1000000000LL))
|
||||
InterlockedExchange(&gm_shown, 0), gm_mx = ptr_x, gm_my = ptr_y;
|
||||
if (now && !was) {
|
||||
captured_before_menu = (int)mouse_captured;
|
||||
mouse_capture(w, 0);
|
||||
} else if (!now && was) {
|
||||
if (captured_before_menu && GetForegroundWindow() == w) mouse_capture(w, 1);
|
||||
captured_before_menu = 0;
|
||||
}
|
||||
/* (a game menu opened: its cursor hidden till the mouse is used, at once; the release above showed it) */
|
||||
if (game_open && !game_was && !insert_open) gm_cursor_off(w);
|
||||
InterlockedExchange(&ptr_pressed, 0), InterlockedExchange(&ptr_wheel, 0);
|
||||
InterlockedExchange(&gm_pressed, 0), InterlockedExchange(&gm_wheel, 0);
|
||||
}
|
||||
static void menu_mouse(HWND w, int open) {
|
||||
if (open != menu_open) menus_mouse(w, open, game_menu_open);
|
||||
}
|
||||
|
||||
/* (host/oot_menu.c, the game's thread) one of the game's menus ran this frame */
|
||||
void hos_mouse_game_menu(void) {
|
||||
const LONG64 before = InterlockedExchange64(&game_menu_seen_ns, (LONG64)hos_now_ns());
|
||||
if (!before && hwnd) PostMessageA(hwnd, WM_APP + 10, 1, 0);
|
||||
}
|
||||
/* (host/oot_menu.c, the game's thread) frames go on with none of the game's menus holding the mouse: closed now */
|
||||
void hos_mouse_game_menu_gone(void) {
|
||||
const LONG64 seen = InterlockedCompareExchange64(&game_menu_seen_ns, 0, 0);
|
||||
if (seen && hwnd && InterlockedCompareExchange64(&game_menu_seen_ns, 0, seen) == seen) PostMessageA(hwnd, WM_APP + 11, 0, 0);
|
||||
}
|
||||
/* (host/oot_menu.c, the game's thread) the wheel's notches since the last call, for a screen that takes only the wheel
|
||||
and leaves the mouse as it is (the R button's item choice, in play: the mouse the camera's). Notches count only while
|
||||
such a screen reads them (a call in the last 200 ms): a wheel turned in play does not wait for the next one */
|
||||
static volatile LONG play_wheel;
|
||||
static volatile LONG64 play_wheel_ns;
|
||||
int hos_mouse_wheel_take(void) {
|
||||
InterlockedExchange64(&play_wheel_ns, (LONG64)hos_now_ns());
|
||||
const LONG wl = InterlockedExchange(&play_wheel, 0);
|
||||
if (!hwnd || menu_open || GetForegroundWindow() != hwnd) return 0;
|
||||
if (wl % WHEEL_DELTA) InterlockedExchangeAdd(&play_wheel, wl % WHEEL_DELTA);
|
||||
return wl / WHEEL_DELTA;
|
||||
}
|
||||
/* the free mouse over the game's menus: its position (client pixels) and the window's size, the buttons pressed
|
||||
(HOS_MOUSE_*) and the wheel's notches since the last call. 0 when the Insert menu has it or it is outside the window;
|
||||
2 while the cursor is hidden: the wheel only (no presses; the position is not one to point with) */
|
||||
int hos_mouse_game_pointer(int *x, int *y, int *w, int *h, uint32_t *pressed, int *wheel) {
|
||||
*pressed = 0, *wheel = 0;
|
||||
if (!hwnd || !game_menu_open || menu_open || mouse_captured) return 0;
|
||||
const int shown = gm_cursor_shown();
|
||||
*x = ptr_x, *y = ptr_y, *w = ptr_w, *h = ptr_h;
|
||||
const LONG got = InterlockedExchange(&gm_pressed, 0); /* (hidden: what the buttons did meanwhile is not the menu's) */
|
||||
if (shown) *pressed = (uint32_t)got;
|
||||
const LONG wl = InterlockedExchange(&gm_wheel, 0);
|
||||
*wheel = wl / WHEEL_DELTA;
|
||||
if (wl % WHEEL_DELTA) InterlockedExchangeAdd(&gm_wheel, wl % WHEEL_DELTA);
|
||||
if (!(ptr_in && GetForegroundWindow() == hwnd && *w > 0 && *h > 0)) return 0;
|
||||
return shown ? 1 : 2;
|
||||
}
|
||||
static void game_menu_press(LPARAM lp, LONG bit) {
|
||||
ptr_x = (short)LOWORD(lp), ptr_y = (short)HIWORD(lp), ptr_in = 1;
|
||||
gm_mouse_used();
|
||||
InterlockedOr(&gm_pressed, bit);
|
||||
}
|
||||
static void menu_press(HWND w, LPARAM lp, LONG bit) { /* (a click while the menu is open: the menu's) */
|
||||
ptr_x = (short)LOWORD(lp), ptr_y = (short)HIWORD(lp), ptr_in = 1;
|
||||
InterlockedOr(&ptr_pressed, bit);
|
||||
SetCapture(w); /* (a drag past the window's edge still reaches it) */
|
||||
}
|
||||
|
||||
static LRESULT CALLBACK wndproc(HWND w, UINT msg, WPARAM wp, LPARAM lp) {
|
||||
switch (msg) {
|
||||
case WM_MOUSEMOVE:
|
||||
ptr_x = (short)LOWORD(lp), ptr_y = (short)HIWORD(lp);
|
||||
if (game_menu_open && !menu_open && (ptr_x != gm_mx || ptr_y != gm_my)) { /* (a move: not a repeat at rest) */
|
||||
gm_mx = ptr_x, gm_my = ptr_y;
|
||||
gm_mouse_used();
|
||||
}
|
||||
if (!ptr_in) {
|
||||
TRACKMOUSEEVENT t = {sizeof t, TME_LEAVE, w, 0};
|
||||
TrackMouseEvent(&t);
|
||||
ptr_in = 1;
|
||||
}
|
||||
return 0;
|
||||
case WM_MOUSELEAVE:
|
||||
ptr_in = 0;
|
||||
return 0;
|
||||
case WM_MOUSEWHEEL:
|
||||
if (menu_open) InterlockedExchangeAdd(&ptr_wheel, GET_WHEEL_DELTA_WPARAM(wp));
|
||||
else if (game_menu_open) InterlockedExchangeAdd(&gm_wheel, GET_WHEEL_DELTA_WPARAM(wp)); /* (hidden or not) */
|
||||
else if ((LONG64)hos_now_ns() - InterlockedCompareExchange64(&play_wheel_ns, 0, 0) < 200000000LL)
|
||||
InterlockedExchangeAdd(&play_wheel, GET_WHEEL_DELTA_WPARAM(wp)); /* (a screen that takes the wheel only) */
|
||||
return 0;
|
||||
case WM_RBUTTONDOWN:
|
||||
if (menu_open) menu_press(w, lp, HOS_MOUSE_RIGHT);
|
||||
else if (game_menu_open) game_menu_press(lp, HOS_MOUSE_RIGHT);
|
||||
return 0;
|
||||
case WM_MBUTTONDOWN:
|
||||
if (menu_open) menu_press(w, lp, HOS_MOUSE_MIDDLE);
|
||||
else if (game_menu_open) game_menu_press(lp, HOS_MOUSE_MIDDLE);
|
||||
return 0;
|
||||
case WM_LBUTTONUP:
|
||||
case WM_RBUTTONUP:
|
||||
case WM_MBUTTONUP:
|
||||
if (GetCapture() == w && !(wp & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON))) ReleaseCapture();
|
||||
return 0;
|
||||
case WM_APP + 8: /* (the Insert menu opened or closed: gpu/vk/vk_menu.cpp) */
|
||||
menu_mouse(w, (int)wp);
|
||||
return 0;
|
||||
case WM_APP + 10: /* (a game menu opened: hos_mouse_game_menu) */
|
||||
if (!game_menu_open) menus_mouse(w, menu_open, 1);
|
||||
return 0;
|
||||
case WM_APP + 11: /* (the game's menus closed: hos_mouse_game_menu_gone) */
|
||||
if (game_menu_open) menus_mouse(w, menu_open, 0);
|
||||
return 0;
|
||||
case WM_TIMER: {
|
||||
/* (hookshot, #1532) a controller is not input to Windows: playing with one, the display went off at the power
|
||||
plan's timeout. While the game's window is in front and not minimized, the display's idle timer is reset every
|
||||
30 s (ES_DISPLAY_REQUIRED without ES_CONTINUOUS: nothing is held when the game is left or closed).
|
||||
HOS_KEEP_DISPLAY=0: Windows' timeout as before */
|
||||
static ULONGLONG last_awake;
|
||||
static int keep = -1;
|
||||
if (keep < 0) keep = !getenv("HOS_KEEP_DISPLAY") || atoi(getenv("HOS_KEEP_DISPLAY")) != 0;
|
||||
const ULONGLONG now = GetTickCount64();
|
||||
if (keep && renderer && now - last_awake >= 30000 && GetForegroundWindow() == w && !IsIconic(w)) {
|
||||
last_awake = now;
|
||||
SetThreadExecutionState(ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED);
|
||||
}
|
||||
/* (the game's menus closed: no frame of one for 300 ms) */
|
||||
const LONG64 seen = InterlockedCompareExchange64(&game_menu_seen_ns, 0, 0);
|
||||
if (game_menu_open && seen && (LONG64)hos_now_ns() - seen > 300000000LL &&
|
||||
InterlockedCompareExchange64(&game_menu_seen_ns, 0, seen) == seen)
|
||||
menus_mouse(w, menu_open, 0);
|
||||
if (game_menu_open && !menu_open && !gm_cursor_shown()) gm_cursor_off(w); /* (hidden by the pads or keys: at once) */
|
||||
return 0;
|
||||
}
|
||||
case WM_SYSCOMMAND:
|
||||
if ((wp & 0xFFF0) == SC_SCREENSAVE && !(wp & SCF_ISSECURE) &&
|
||||
renderer && GetForegroundWindow() == w && !IsIconic(w)) {
|
||||
BOOL secure = TRUE; /* unknown or protected policy keeps Windows' normal handling */
|
||||
if (SystemParametersInfoA(SPI_GETSCREENSAVESECURE, 0, &secure, 0) && !secure) return 0;
|
||||
}
|
||||
break;
|
||||
case WM_INPUT: {
|
||||
RAWINPUT ri;
|
||||
UINT size = sizeof ri;
|
||||
if (mouse_captured && GetRawInputData((HRAWINPUT)lp, RID_INPUT, &ri, &size, sizeof(RAWINPUTHEADER)) != (UINT)-1 &&
|
||||
ri.header.dwType == RIM_TYPEMOUSE && !(ri.data.mouse.usFlags & MOUSE_MOVE_ABSOLUTE)) {
|
||||
InterlockedExchangeAdd(&mouse_dx, ri.data.mouse.lLastX);
|
||||
InterlockedExchangeAdd(&mouse_dy, ri.data.mouse.lLastY);
|
||||
}
|
||||
return DefWindowProcA(w, msg, wp, lp);
|
||||
}
|
||||
case WM_LBUTTONDOWN:
|
||||
if (menu_open) menu_press(w, lp, HOS_MOUSE_LEFT);
|
||||
else if (game_menu_open) game_menu_press(lp, HOS_MOUSE_LEFT);
|
||||
else if (renderer && !mouse_captured) mouse_capture(w, 1);
|
||||
return 0;
|
||||
case WM_KEYDOWN: {
|
||||
extern void hos_vk_note_key_press(unsigned key);
|
||||
if (!(lp & (1 << 30))) hos_vk_note_key_press((unsigned)wp);
|
||||
if (wp == VK_ESCAPE) mouse_capture(w, 0);
|
||||
/* (Triforce: F11 does nothing; F10 and Alt+Enter switch fullscreen, below: F10 comes as a system key) */
|
||||
return 0;
|
||||
}
|
||||
case WM_SYSKEYDOWN: /* Alt+Enter and F10, as on Linux (display_sdl.c); other Alt keys (Alt+F4) go on to Windows */
|
||||
if ((wp == VK_RETURN && (lp & (1 << 29))) || wp == VK_F10) {
|
||||
if (!(lp & (1 << 30))) set_fullscreen(w, !fullscreen);
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
case WM_SYSKEYUP: /* (the release of F10: left to Windows it enters the menu loop, and the game seems to freeze until a key) */
|
||||
if (wp == VK_F10) return 0;
|
||||
break;
|
||||
case WM_SYSCHAR: /* (its character: without this Windows beeps, as for an Alt key with no menu) */
|
||||
if (wp == '\r') return 0;
|
||||
break;
|
||||
case WM_APP + 7: /* (the Insert menu's row) */
|
||||
set_fullscreen(w, (int)wp);
|
||||
return 0;
|
||||
case WM_DPICHANGED:
|
||||
if (!fullscreen) {
|
||||
const RECT *s = (const RECT *)lp;
|
||||
SetWindowPos(w, NULL, s->left, s->top, s->right - s->left, s->bottom - s->top,
|
||||
SWP_NOZORDER | SWP_NOACTIVATE);
|
||||
}
|
||||
return 0;
|
||||
case WM_KILLFOCUS:
|
||||
case WM_CANCELMODE:
|
||||
mouse_capture(w, 0);
|
||||
break;
|
||||
case WM_SETCURSOR:
|
||||
if ((mouse_captured || (game_menu_open && !menu_open && !gm_cursor_shown())) && LOWORD(lp) == HTCLIENT) {
|
||||
SetCursor(NULL);
|
||||
return TRUE;
|
||||
}
|
||||
break;
|
||||
case WM_MOVE:
|
||||
if (mouse_captured) { mouse_capture(w, 0); mouse_capture(w, 1); } /* (the clip follows the window) */
|
||||
break;
|
||||
case WM_SIZE:
|
||||
ptr_w = LOWORD(lp), ptr_h = HIWORD(lp);
|
||||
if (mouse_captured) { mouse_capture(w, 0); mouse_capture(w, 1); }
|
||||
if (renderer) rx_resize(LOWORD(lp), HIWORD(lp));
|
||||
return 0;
|
||||
case WM_PAINT:
|
||||
if (renderer) { /* the renderer's surface: nothing to paint */
|
||||
ValidateRect(w, NULL);
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
case WM_ERASEBKGND:
|
||||
return renderer ? 1 : DefWindowProcA(w, msg, wp, lp);
|
||||
case WM_APP + 9: /* (the Insert menu's Restart now: closed as by the player, then started again: host/hos_relaunch.c) */
|
||||
hos_relaunch_ask();
|
||||
/* fall through */
|
||||
case WM_CLOSE:
|
||||
rx_close_asked(); /* (a start still preparing the shaders keeps what it made) */
|
||||
hos_window_closed_exit();
|
||||
return 0;
|
||||
}
|
||||
return DefWindowProcA(w, msg, wp, lp);
|
||||
}
|
||||
|
||||
/* (Triforce) The title bar in Triforce's colours instead of Windows' white one: black, gold title, a dark gold edge (Windows 11's
|
||||
caption colours, DWMWA 34-36), and Windows' dark title bar where those are not there (Windows 10: DWMWA 20, 19 before 2004).
|
||||
dwmapi is loaded here, so nothing changes for a Windows without it */
|
||||
static void theme_caption(HWND w) {
|
||||
HMODULE dwm = LoadLibraryA("dwmapi.dll");
|
||||
typedef HRESULT (WINAPI *set_fn)(HWND, DWORD, LPCVOID, DWORD);
|
||||
set_fn set = dwm ? (set_fn)(void *)GetProcAddress(dwm, "DwmSetWindowAttribute") : NULL;
|
||||
if (!set) return;
|
||||
const BOOL dark = TRUE;
|
||||
if (FAILED(set(w, 20, &dark, sizeof dark))) set(w, 19, &dark, sizeof dark);
|
||||
const COLORREF caption = RGB(11, 10, 9), text = RGB(224, 178, 62), border = RGB(110, 84, 30);
|
||||
set(w, 35, &caption, sizeof caption);
|
||||
set(w, 36, &text, sizeof text);
|
||||
set(w, 34, &border, sizeof border);
|
||||
}
|
||||
|
||||
static void display_start_failed(const char *operation) {
|
||||
const DWORD error = GetLastError();
|
||||
hos_log("display: %s failed (error %lu)", operation, (unsigned long)error);
|
||||
hos_log_flush();
|
||||
ExitProcess(1);
|
||||
}
|
||||
|
||||
static DWORD WINAPI display_main(void *p) {
|
||||
(void)p;
|
||||
{ /* (nothing is typed here. Windows' text services, set up under DefWindowProc as the window was sized, ended the process: a
|
||||
fail-fast in CoreMessaging, called from textinputframework) */
|
||||
HMODULE imm = LoadLibraryExA("imm32.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); /* (hookshot: System32's only) */
|
||||
BOOL (WINAPI *ime_off)(DWORD) = imm ? (BOOL (WINAPI *)(DWORD))GetProcAddress(imm, "ImmDisableIME") : NULL;
|
||||
if (ime_off) ime_off((DWORD)-1);
|
||||
}
|
||||
WNDCLASSA wc;
|
||||
memset(&wc, 0, sizeof wc);
|
||||
wc.lpfnWndProc = wndproc;
|
||||
wc.hInstance = GetModuleHandleA(NULL);
|
||||
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
|
||||
wc.hIcon = LoadIconA(wc.hInstance, MAKEINTRESOURCEA(1)); /* (nx2/make_icon.py; none in a build without the picture) */
|
||||
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
|
||||
wc.lpszClassName = "Triforce";
|
||||
RegisterClassA(&wc);
|
||||
dpi_aware_thread();
|
||||
extern float hos_aspect_ratio;
|
||||
/* (the picture's shape when Monitor's shape set one, wider or narrower than 16:9: 960 x 720 for 4:3, 1720 x 720 for 21:9) */
|
||||
int win_w = hos_aspect_ratio > 0.0f ? (int)(720 * hos_aspect_ratio + 0.5f) : 1280, win_h = 720;
|
||||
if (getenv("HOS_WINDOW_SIZE")) {
|
||||
int w = 0, h = 0;
|
||||
if (sscanf(getenv("HOS_WINDOW_SIZE"), "%dx%d", &w, &h) == 2 && w >= 64 && h >= 64) win_w = w, win_h = h;
|
||||
}
|
||||
RECT r = {0, 0, win_w, win_h};
|
||||
AdjustWindowRect(&r, WS_OVERLAPPEDWINDOW, FALSE);
|
||||
const int noactivate = getenv("HOS_WINDOW_NOACTIVATE") != NULL;
|
||||
hwnd = CreateWindowA("Triforce", HOS_GAME_TITLE, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
|
||||
CW_USEDEFAULT, r.right - r.left, r.bottom - r.top, NULL, NULL, wc.hInstance, NULL);
|
||||
if (!hwnd) display_start_failed("CreateWindowA");
|
||||
theme_caption(hwnd);
|
||||
if (window_dpi(hwnd) != 96) {
|
||||
const UINT dpi = window_dpi(hwnd);
|
||||
RECT s = {0, 0, (LONG)(win_w * dpi / 96), (LONG)(win_h * dpi / 96)};
|
||||
AdjustWindowRect(&s, WS_OVERLAPPEDWINDOW, FALSE);
|
||||
SetWindowPos(hwnd, NULL, 0, 0, s.right - s.left, s.bottom - s.top, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
|
||||
}
|
||||
/* (no activate: shown at the bottom of the z-order, so a game in front keeps its focus) */
|
||||
if (noactivate)
|
||||
SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW);
|
||||
else
|
||||
ShowWindow(hwnd, SW_SHOW);
|
||||
if (getenv("HOS_FULLSCREEN") && atoi(getenv("HOS_FULLSCREEN"))) set_fullscreen(hwnd, 1);
|
||||
RAWINPUTDEVICE rid = {1, 2, 0, hwnd}; /* generic desktop mouse: WM_INPUT while the window is in front */
|
||||
RegisterRawInputDevices(&rid, 1, sizeof rid);
|
||||
renderer = rx_start(hwnd);
|
||||
if (!renderer) hos_log("display: no WebGPU device: the window stays black");
|
||||
SetEvent(renderer_up);
|
||||
SetTimer(hwnd, 1, 250, NULL);
|
||||
MSG m;
|
||||
while (GetMessageA(&m, NULL, 0, 0) > 0) {
|
||||
TranslateMessage(&m);
|
||||
DispatchMessageA(&m);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* (hookshot) The game's first work for the GPU waits for the renderer. It ran beside the renderer's start, and what it submitted while the
|
||||
shaders were being prepared (80 s on a first start) was lost: that run had no ambient light, black foliage and dark characters. The
|
||||
game itself goes on starting as it did: held at the start instead, it left holes in the ground */
|
||||
void hos_renderer_wait(void) {
|
||||
{ const char *e = getenv("HOS_NO_RENDERER_WAIT"); if (e && atoi(e) != 0) return; } /* (=0: the wait, as without it) */ /* (a test: the game's first GPU work no longer waits for the renderer, as before lighting-fix) */
|
||||
if (renderer_up) WaitForSingleObject(renderer_up, INFINITE);
|
||||
}
|
||||
|
||||
void hos_display_start(void) {
|
||||
if (getenv("HOS_HEADLESS")) { /* no window: the renderer still draws, offscreen (screenshots, frame dumps) */
|
||||
rx_start(NULL);
|
||||
return;
|
||||
}
|
||||
renderer_up = CreateEventA(NULL, TRUE, FALSE, NULL);
|
||||
if (!renderer_up) display_start_failed("CreateEventA");
|
||||
HANDLE thread = CreateThread(NULL, 0, display_main, NULL, 0, NULL);
|
||||
if (!thread) display_start_failed("CreateThread");
|
||||
CloseHandle(thread);
|
||||
}
|
||||
150
host/hd_rumble.h
Normal file
150
host/hd_rumble.h
Normal file
@@ -0,0 +1,150 @@
|
||||
/* HD rumble for Nintendo Switch Pro Controllers and Joy-Cons, through SDL's effect call (host/pad_sdl.c).
|
||||
|
||||
The game's vibration values (nn::hid VibrationValue: {amp_low, freq_low, amp_high, freq_high}, amplitudes 0 to 1,
|
||||
frequencies in Hz, one per side of the controller) are what the Switch sends its controllers, so a Switch controller
|
||||
can play them, both bands at their own frequency and on their own side, instead of two motor strengths.
|
||||
SDL's Switch driver (src/joystick/hidapi/SDL_hidapi_switch.c, SDL 3.2 on: HIDAPI_DriverSwitch_SendJoystickEffect)
|
||||
takes a whole rumble output report, 0x10, packet number, then 4 bytes per side, and writes it in place of its own
|
||||
rumble. SDL2's own driver and the other SDL drivers (Switch 2 controllers, the kernel's hid-nintendo, joysticks
|
||||
SDL combined, such as a Joy-Con pair) refuse it: those pads keep the motor path.
|
||||
|
||||
The encoding is the one documented by the community's reverse engineering (Switchbrew's HID "Rumble data" page;
|
||||
dekuNukem's Nintendo_Switch_Reverse_Engineering rumble_data_table.md, written from its formulas and tables):
|
||||
- a frequency's code is round(log2(Hz / 10) * 32); the high band takes code - 0x60 times 4 (0x004 to 0x1FC, 9 bits:
|
||||
81.75 to 1252.57 Hz), the low band code - 0x40 (0x01 to 0x7F: 40.88 to 626.29 Hz);
|
||||
- an amplitude's code, 0 to 100 (0 to 1.003), is round(log2(8.7 a) * 32) from 32 up, round(log2(17 a) * 16) from 16
|
||||
to 31, and below that the table's 2^(1/4) steps (a = 2^(code / 4) / 119.6, code 1 = 0.0078); the high band takes
|
||||
code * 2, the low band code / 2 + 0x40 with the code's odd bit as its 9th bit (0x8000). Codes over 100 are past what
|
||||
the table calls safe for the actuators: 100 is the top, as SDL's own table stops there;
|
||||
- the 4 bytes of a side: high frequency's low 8 bits; high amplitude | the high frequency's 9th bit; low frequency |
|
||||
the low amplitude's 9th bit (0x80); the low amplitude's low 8 bits. Silence is 00 01 40 40 (both bands at 0, at
|
||||
320 and 160 Hz), as SDL sends it.
|
||||
|
||||
Pure (no state, no SDL): tests/test_hd_rumble.py compiles it. */
|
||||
#pragma once
|
||||
#include <math.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
#define HD_RUMBLE_PACKET_SIZE 10 /* (SDL's SwitchCommonOutputPacket_t: type, number, 2 x 4 bytes) */
|
||||
#define HD_RUMBLE_REPORT 0x10 /* (k_eSwitchOutputReportIDs_Rumble) */
|
||||
#define HD_RUMBLE_AMP_TOP 100 /* the amplitude code 1.003 has: the top the table calls safe */
|
||||
#define HD_RUMBLE_GAP_NS 32000000LL /* the least time between two packets (SDL: 30 ms; faster can turn a
|
||||
Bluetooth controller off, or the motors miss them over USB) */
|
||||
#define HD_RUMBLE_REFRESH_NS 40000000LL /* a rumble that goes on is sent again this often (SDL refreshes its own
|
||||
every 50 ms: the controller stops one it is not sent again) */
|
||||
|
||||
/* What kind of Switch controller SDL says a pad is: 0 none of them (the motor path), else the side(s) it has. */
|
||||
enum { HD_RUMBLE_NONE, HD_RUMBLE_PRO, HD_RUMBLE_JOYCON_LEFT, HD_RUMBLE_JOYCON_RIGHT, HD_RUMBLE_JOYCON_PAIR };
|
||||
/* From SDL_GetGamepadType (SDL3: SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO 7, then JOYCON_LEFT, RIGHT, PAIR) or
|
||||
SDL_GameControllerGetType (SDL2: SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO 5, JOYCON_LEFT 11, RIGHT 12, PAIR 13). */
|
||||
static inline int hd_rumble_kind(int sdl_version, int type) {
|
||||
if (sdl_version == 3) return type >= 7 && type <= 10 ? HD_RUMBLE_PRO + (type - 7) : HD_RUMBLE_NONE;
|
||||
if (sdl_version == 2) return type == 5 ? HD_RUMBLE_PRO : type >= 11 && type <= 13 ? HD_RUMBLE_JOYCON_LEFT + (type - 11) : HD_RUMBLE_NONE;
|
||||
return HD_RUMBLE_NONE;
|
||||
}
|
||||
|
||||
/* A frequency's code, round(log2(Hz / 10) * 32), kept to [lo, hi]; a frequency that is not one (0, NaN) gets
|
||||
otherwise. */
|
||||
static inline int hd_rumble_freq_code(float hz, int lo, int hi, int otherwise) {
|
||||
if (!(hz > 0.0f)) return otherwise; /* (also NaN) */
|
||||
const double c = floor(log2((double)hz / 10.0) * 32.0 + 0.5);
|
||||
return c < lo ? lo : c > hi ? hi : (int)c;
|
||||
}
|
||||
/* An amplitude's code, 0 to HD_RUMBLE_AMP_TOP (see above). */
|
||||
static inline int hd_rumble_amp_code(float amp) {
|
||||
if (!(amp > 0.0f)) return 0; /* (also NaN) */
|
||||
double c;
|
||||
if (amp > 0.2275f) c = floor(log2(8.7 * amp) * 32.0 + 0.5); /* (between codes 31 and 32: 0.225, 0.230) */
|
||||
else if (amp > 0.1150f) c = floor(log2(17.0 * amp) * 16.0 + 0.5); /* (15 and 16: 0.112, 0.117) */
|
||||
else if (amp >= 0.0039f) c = floor(4.0 * log2(119.6 * amp) + 0.5); /* (half of code 1's 0.0078: less is 0) */
|
||||
else return 0;
|
||||
if (c < 1) c = 1; /* (code 1, 0.0078, is off the 2^(1/4) steps: the smallest that plays) */
|
||||
return c > HD_RUMBLE_AMP_TOP ? HD_RUMBLE_AMP_TOP : (int)c;
|
||||
}
|
||||
|
||||
/* (issue 263, for HD rumble) The game's amplitudes as a Switch controller is to play them: OoT scales its rumble files
|
||||
by small gains (romfs RSDB/RumbleCall: 0.015 to 0.5, most effects 0.05 to 0.2), so what it asks for is mostly 0.02 to
|
||||
0.1 and played as it is a Pro Controller's actuators hardly move (a heart caught, 0.06 at 55 Hz, is not felt). Each
|
||||
band goes through the same curve as the motors' (nn_hid.c's rumble_motor, from Eden's SDL driver): (a + a^0.35) / 2,
|
||||
which keeps 0 and 1 and the order of the strengths (0.03 -> 0.16, 0.06 -> 0.22, 0.2 -> 0.38, 0.5 -> 0.64); what is
|
||||
below the encoding's smallest step (half of code 1) stays silent. Frequencies are kept. */
|
||||
static inline float hd_rumble_felt_amp(float amp) {
|
||||
if (!(amp >= 0.0039f)) return 0.0f; /* (also NaN) */
|
||||
const float felt = (amp + powf(amp, 0.35f)) * 0.5f;
|
||||
return felt > 1.0f ? 1.0f : felt;
|
||||
}
|
||||
static inline void hd_rumble_felt(const float v[4], float out[4]) {
|
||||
out[0] = hd_rumble_felt_amp(v[0]), out[1] = v[1];
|
||||
out[2] = hd_rumble_felt_amp(v[2]), out[3] = v[3];
|
||||
}
|
||||
|
||||
/* (a single Joy-Con) both sides' values as one: each band at the stronger side's amplitude, with that side's frequency
|
||||
(the left's when they are equal). The game always sees a full Pro Controller and may send an effect to one side only;
|
||||
a lone Joy-Con has one side, and plays what either side asks for, as the motor path's max of the two sides does. */
|
||||
static inline void hd_rumble_merge(const float left[4], const float right[4], float out[4]) {
|
||||
for (int b = 0; b < 4; b += 2) {
|
||||
const int r = right[b] > left[b]; /* (NaN: not stronger, the left kept) */
|
||||
out[b] = r ? right[b] : left[b], out[b + 1] = r ? right[b + 1] : left[b + 1];
|
||||
}
|
||||
}
|
||||
|
||||
/* The silent side, 00 01 40 40. */
|
||||
static inline void hd_rumble_neutral(uint8_t out[4]) {
|
||||
out[0] = 0x00, out[1] = 0x01, out[2] = 0x40, out[3] = 0x40;
|
||||
}
|
||||
/* One side's 4 bytes from the game's value {amp_low, freq_low, amp_high, freq_high}, its amplitudes scaled by percent
|
||||
(100 the game's own, 0 silence). Over 100, both bands get the same factor, the stronger stopping at 1 (as the motors'
|
||||
strength does: the bands keep their balance), and the top stays HD_RUMBLE_AMP_TOP. */
|
||||
static inline void hd_rumble_encode(const float v[4], int percent, uint8_t out[4]) {
|
||||
float scale = percent > 0 ? (float)percent / 100.0f : 0.0f;
|
||||
const float top = v[0] > v[2] ? v[0] : v[2];
|
||||
if (scale > 1.0f && top * scale > 1.0f) scale = top > 1.0f ? 1.0f : 1.0f / top; /* (NaN: not above, kept) */
|
||||
const int la = hd_rumble_amp_code(v[0] * scale), ha = hd_rumble_amp_code(v[2] * scale);
|
||||
if (!la && !ha) {
|
||||
hd_rumble_neutral(out);
|
||||
return;
|
||||
}
|
||||
const int lf = hd_rumble_freq_code(v[1], 0x41, 0xBF, 0x80) - 0x40; /* (160 Hz when it has none) */
|
||||
const int hf = (hd_rumble_freq_code(v[3], 0x61, 0xDF, 0xA0) - 0x60) * 4; /* (320 Hz) */
|
||||
const int ha2 = ha * 2, la9 = ((la & 1) << 15) | (la / 2 + 0x40);
|
||||
out[0] = (uint8_t)(hf & 0xFF);
|
||||
out[1] = (uint8_t)(ha2 | ((hf >> 8) & 0x01));
|
||||
out[2] = (uint8_t)(lf | ((la9 >> 8) & 0x80));
|
||||
out[3] = (uint8_t)(la9 & 0xFF);
|
||||
}
|
||||
|
||||
/* The packet SDL's effect call takes, from the game's left and right sides' bytes: a Pro Controller (and a pair)
|
||||
plays each side on its own; a single Joy-Con plays its own side (SDL's packet has both: it gets it in both). For a
|
||||
single Joy-Con, host/pad_sdl.c passes the two sides merged (hd_rumble_merge) as both. */
|
||||
static inline void hd_rumble_packet(int kind, const uint8_t left[4], const uint8_t right[4], uint8_t out[HD_RUMBLE_PACKET_SIZE]) {
|
||||
out[0] = HD_RUMBLE_REPORT;
|
||||
out[1] = 0; /* (SDL numbers the packets itself) */
|
||||
const uint8_t *l = kind == HD_RUMBLE_JOYCON_RIGHT ? right : left, *r = kind == HD_RUMBLE_JOYCON_LEFT ? left : right;
|
||||
memcpy(out + 2, l, 4);
|
||||
memcpy(out + 6, r, 4);
|
||||
}
|
||||
static inline int hd_rumble_silent(const uint8_t packet[HD_RUMBLE_PACKET_SIZE]) {
|
||||
static const uint8_t n[4] = {0x00, 0x01, 0x40, 0x40};
|
||||
return !memcmp(packet + 2, n, 4) && !memcmp(packet + 6, n, 4);
|
||||
}
|
||||
|
||||
/* Whether a pad's packet goes out now: packet the one the game asks for, sent the last one sent (silence before the
|
||||
first), sent_ns when, ever whether there was one. Never sooner than HD_RUMBLE_GAP_NS after the last; a change goes
|
||||
at once, then the latest when the gap is over (what the game asks for in between is not sent: a newer value takes its
|
||||
place); a rumble that goes on is sent again every HD_RUMBLE_REFRESH_NS; silence that was sent is not sent again. */
|
||||
static inline int hd_rumble_due(const uint8_t packet[HD_RUMBLE_PACKET_SIZE], const uint8_t sent[HD_RUMBLE_PACKET_SIZE],
|
||||
int ever, long long now, long long sent_ns) {
|
||||
if (ever && now - sent_ns < HD_RUMBLE_GAP_NS) return 0;
|
||||
if (memcmp(packet + 2, sent + 2, 8)) return 1;
|
||||
return ever && !hd_rumble_silent(sent) && now - sent_ns >= HD_RUMBLE_REFRESH_NS;
|
||||
}
|
||||
|
||||
/* A pad's HD rumble state, as the poll moves it: unknown until its first packet; on while SDL takes them; off (the
|
||||
motor path, for as long as the pad is open) once SDL refuses one, or when it has no effect call, is no Switch
|
||||
controller, or HOS_HD_RUMBLE=0. */
|
||||
enum { HD_RUMBLE_UNKNOWN, HD_RUMBLE_ON, HD_RUMBLE_OFF };
|
||||
static inline int hd_rumble_start(int kind, int have_call, int env_off) {
|
||||
return kind != HD_RUMBLE_NONE && have_call && !env_off ? HD_RUMBLE_UNKNOWN : HD_RUMBLE_OFF;
|
||||
}
|
||||
static inline int hd_rumble_after_send(int ok) { return ok ? HD_RUMBLE_ON : HD_RUMBLE_OFF; }
|
||||
154
host/hos.h
Normal file
154
host/hos.h
Normal file
@@ -0,0 +1,154 @@
|
||||
/* Horizon OS layer (HLE of the Nintendo SDK at the nn:: boundary) for a64-kit games.
|
||||
|
||||
An import or SDK function the game calls is a C function `void imp_<mangled name>(Ctx *c)` (HLE(...) below):
|
||||
arguments in c->x[0..7], the result in c->x[0]. A symbol with such a definition is hooked both where the game
|
||||
imports it and at the sdk's own definition, so lifted SDK code reaching it lands here too (nx_image.py).
|
||||
Everything without a definition gets a generated stub that logs its first call and returns 0.
|
||||
|
||||
Guest address map (mkw-recomp: the 64-bit window of a 39-bit process, reserved whole and committed as used):
|
||||
0x01000000 - 0x07000000 system region: our own guest objects (main stack, TLS blocks, thread regions)
|
||||
0x80000000 - image end rtld, main, subsdk0, subsdk1, sdk in Eden's layout (hos_image_base, the lift's)
|
||||
0x1000000000 - ... heap (SetMemoryHeapSize), up from 64 GB
|
||||
... - 0x8000000000 address regions (AllocateAddressRegion), down from 512 GB */
|
||||
#ifndef HOS_H
|
||||
#define HOS_H
|
||||
#include "a64.h"
|
||||
#include <stdarg.h>
|
||||
|
||||
#define HLE(sym) void imp_##sym(Ctx *c)
|
||||
/* HOS_GAME_VERSION: the game update the address hooks below are for, from the build (build.py reads the main
|
||||
module's build id). An update moves the game's functions, so a hook compiles the address of the version it is
|
||||
for and the other version's hooks are left out (ENTRY_HOOKs: the address is not in the lift; SPLICE_AFTERs:
|
||||
skipped with a note). */
|
||||
#ifndef HOS_GAME_VERSION
|
||||
#define HOS_GAME_VERSION 100
|
||||
#endif
|
||||
/* ENTRY_HOOK(0x0xxxxxxx) { ... }: runs at the entry of the lifted guest function at that address (8 hex digits),
|
||||
with its arguments in c; return 1 when it handled the call (the function then returns at once, x0 is the result),
|
||||
0 to run the function as usual. build.py splices the call into the lifted code (only that file recompiles). */
|
||||
#define ENTRY_HOOK(addr) int entry_##addr(Ctx *c)
|
||||
#define ENTRY_HOOK_SYM(sym) int entry_sym_##sym(Ctx *c)
|
||||
/* SPLICE_AFTER(0x0xxxxxxx, "text") { ... }: runs inside the lifted guest function at that address, right after the
|
||||
first line of its lifted C that contains the text (a game patch in the middle of a function: c holds the guest
|
||||
registers there). build.py splices the call in and stops the build if the text is not found. One per function. */
|
||||
#define SPLICE_AFTER(addr, anchor) void splice_##addr(Ctx *c)
|
||||
/* SPLICE_AFTER_EACH(0x0xxxxxxx, "text") { ... }: the same after every line of that function with the text */
|
||||
#define SPLICE_AFTER_EACH(addr, anchor) void splice_##addr(Ctx *c)
|
||||
#define ARG(n) (c->x[n])
|
||||
#define RET(v) (c->x[0] = (uint64_t)(v))
|
||||
#define GP(a) ((void *)A64_PTR(a)) /* host pointer of a guest address */
|
||||
#define G64(a) (*(uint64_t *)GP(a))
|
||||
#define G32(a) (*(uint32_t *)GP(a))
|
||||
|
||||
#define HOS_SYSTEM_BASE 0x01000000ULL
|
||||
#define HOS_SYSTEM_END 0x07000000ULL
|
||||
#define HOS_HEAP_BASE 0x1000000000ULL
|
||||
#define HOS_GUEST_SPACE (1ULL << 39)
|
||||
extern const uint64_t hos_image_base, hos_image_end; /* (gen/hos_image.c) */
|
||||
extern const uint64_t hos_program_id; /* (gen/hos_image.c: main.npdm's) */
|
||||
extern const char hos_main_build_id[]; /* (gen/hos_image.c: main's NSO build id, hex) */
|
||||
/* (oot-recomp) MKW's own hooks at fixed guest addresses (its frame pacer in nvn_native.c / nn_vi.c, its idle loop in
|
||||
hos_thread.c) run only when the lifted main is Mario Kart World's: any other game has other code there */
|
||||
int hos_game_is_mkw(void);
|
||||
#define HOS_GAME_TITLE "Triforce"
|
||||
void hos_commit(uint64_t addr, uint64_t size); /* (mkw_glue.c) guest pages made usable by host APIs */
|
||||
#if defined(A64_WRITE_TRACK) && !defined(__EMSCRIPTEN__)
|
||||
void hos_mark_written(const void *p, size_t n); /* (hos_mem.c: guest memory written by host code, native soft watch) */
|
||||
#define HOS_WRITTEN(p, n) hos_mark_written((p), (n))
|
||||
#elif defined(A64_WRITE_TRACK)
|
||||
void web_mark_written(const void *p, size_t n); /* (hos/web/win32.c: guest memory written by host code) */
|
||||
#define HOS_WRITTEN(p, n) web_mark_written((p), (n))
|
||||
#else
|
||||
#define HOS_WRITTEN(p, n) ((void)0)
|
||||
#endif
|
||||
#ifdef A64_MEM_ZERO
|
||||
extern uint64_t hos_space_end; /* web: the guest window ends where the host's own data starts (hos_main.c) */
|
||||
#define HOS_SPACE_END hos_space_end
|
||||
#else
|
||||
#define HOS_SPACE_END 0x8000000000ULL
|
||||
#endif
|
||||
/* (hookshot) host pointer of the n guest bytes at a, NULL unless all of them lie in the guest window. For addresses
|
||||
and sizes host code takes from guest memory or arguments before it reads or writes there: GP alone wraps around
|
||||
to any host address. */
|
||||
static inline void *hos_guest_range(uint64_t a, uint64_t n) {
|
||||
return a < (uint64_t)HOS_SPACE_END && n <= (uint64_t)HOS_SPACE_END - a ? GP(a) : (void *)0;
|
||||
}
|
||||
#define HOS_TICK_HZ 31250000ULL /* (mkw-recomp: the Switch 2 counter; the SDK checks it at init) */
|
||||
|
||||
/* ---- logging: HOS_TRACE=1 logs every HLE call that uses HOS_TRACE_CALL */
|
||||
extern int hos_trace;
|
||||
void hos_log(const char *fmt, ...);
|
||||
void hos_log_flush(void);
|
||||
#define HOS_TRACE_CALL(name) do { if (hos_trace) hos_log("%s(%#llx, %#llx, %#llx, %#llx) lr %#llx", name, \
|
||||
(unsigned long long)c->x[0], (unsigned long long)c->x[1], (unsigned long long)c->x[2], \
|
||||
(unsigned long long)c->x[3], (unsigned long long)c->x[30]); } while (0)
|
||||
void hos_fatal(Ctx *c, const char *fmt, ...);
|
||||
|
||||
/* ---- guest memory (hos_mem.c) */
|
||||
uint64_t hos_sys_alloc(uint64_t size, uint64_t align); /* zeroed, from the system region, never freed */
|
||||
uint64_t hos_region_alloc(uint64_t size, uint64_t align); /* address space above the heap */
|
||||
void hos_region_free(uint64_t addr);
|
||||
void hos_mem_init(uint64_t image_end);
|
||||
extern uint64_t hos_heap_size, hos_heap_used, hos_total_memory, hos_program_size;
|
||||
|
||||
/* ---- threads (hos_thread.c) */
|
||||
typedef struct HosThread HosThread;
|
||||
HosThread *hos_self(void);
|
||||
Ctx *hos_ctx(void);
|
||||
uint64_t hos_thread_guest(HosThread *t); /* its nn::os::ThreadType in guest memory */
|
||||
uint64_t hos_thread_id(HosThread *t);
|
||||
HosThread *hos_thread_of(uint64_t guest_thread_type); /* NULL if unknown */
|
||||
HosThread *hos_thread_create(uint64_t guest_tt, uint64_t entry, uint64_t arg, uint64_t stack, uint64_t stack_size,
|
||||
int priority, int core);
|
||||
void hos_thread_start(HosThread *t);
|
||||
void hos_thread_join(HosThread *t);
|
||||
void hos_thread_destroy(HosThread *t);
|
||||
void hos_thread_set_name(HosThread *t, const char *name);
|
||||
void hos_thread_pin(void *h, const char *name); /* HOS_PIN: host CPU affinity by thread name */
|
||||
int hos_game_cores(void); /* totk_cores.c: HOS_GAME_CORES, or 0 */
|
||||
const char *hos_thread_name(HosThread *t);
|
||||
void hos_thread_affinity(HosThread *t, int ideal, uint64_t mask);
|
||||
uint64_t hos_thread_mask(HosThread *t);
|
||||
int hos_thread_priority(HosThread *t, int set, int value);
|
||||
int hos_thread_core(HosThread *t);
|
||||
int hos_cores(void);
|
||||
/* virtual cores (hos_thread.c, HOS_VCORES=1): a guest thread gives its core up for a block (hos_vcore_away: 1 if it
|
||||
held one) and takes one again after it (hos_vcore_back); checkpoints hand it to a better waiter that asked */
|
||||
int hos_vcores_on(void);
|
||||
int hos_vcore_away(void);
|
||||
void hos_vcore_back(void);
|
||||
void hos_vcore_checkpoint(void);
|
||||
void hos_vcore_yield(void);
|
||||
int hos_cv_sleep(void *cv, void *srw_lock, unsigned ms); /* SleepConditionVariableSRW (exclusive) for guest threads */
|
||||
void hos_thread_boost(int level);
|
||||
void hos_thread_stack(HosThread *t, uint64_t *addr, uint64_t *size);
|
||||
uint64_t *hos_tls_slots(HosThread *t); /* nn::os TLS slot values */
|
||||
#define HOS_TLS_SLOTS 32
|
||||
Ctx *hos_boot_main_thread(uint64_t stack_size); /* the calling host thread becomes the guest main thread */
|
||||
/* the kernel side: Horizon handles and blocking for hos_svc.c's arbitration */
|
||||
uint32_t hos_thread_handle(HosThread *t);
|
||||
HosThread *hos_thread_by_handle(uint32_t h);
|
||||
int hos_thread_prio(HosThread *t);
|
||||
void hos_thread_wait(HosThread *t, int64_t timeout_ns, int *timed_out); /* < 0: forever */
|
||||
void hos_thread_wake(HosThread *t);
|
||||
|
||||
/* ---- for host-side devices: game files by guest path (nn_fs.c), guest events (nn_os_sync.c) */
|
||||
int hos_fs_host_path(const char *guest, char *out, size_t cap);
|
||||
void hos_event_signal(uint64_t guest_event);
|
||||
|
||||
/* ---- videos (movie_mf.c): a video file read as compressed samples or as decoded NV12 frames */
|
||||
typedef struct MovieReader MovieReader;
|
||||
MovieReader *movie_reader_open(const char *host_path, int decoded, int *width, int *height, int64_t *duration_us);
|
||||
/* compressed: the next sample into dst; its size, 0 at the end, -1 on an error or if it does not fit */
|
||||
int movie_reader_sample(MovieReader *r, void *dst, int cap, int64_t *time_us);
|
||||
/* decoded: the next frame as NV12 (width x height luma rows of `width` bytes, then the interleaved chroma rows);
|
||||
1, or 0 at the end */
|
||||
int movie_reader_frame(MovieReader *r, uint8_t *dst, int64_t *time_us);
|
||||
void movie_reader_close(MovieReader *r);
|
||||
uint32_t movie_reader_codec(MovieReader *r); /* the stream's FourCC: 'VP90', 'VP80', 'H264', ... */
|
||||
|
||||
/* ---- time */
|
||||
uint64_t hos_ticks(void);
|
||||
void hos_sleep_ns(int64_t ns);
|
||||
int64_t hos_now_ns(void);
|
||||
#endif
|
||||
132
host/hos_hostcall.c
Normal file
132
host/hos_hostcall.c
Normal file
@@ -0,0 +1,132 @@
|
||||
/* Host calls: guest-callable addresses made at run time, each bound to a host function.
|
||||
|
||||
The lifted code reaches them through indirect calls (blr / br): rt/a64_rt.c asks a64_call_miss for any address
|
||||
that is not a lifted function. Each host call is a 16-byte slot in HOS_HOSTCALL_BASE.. (no memory behind it).
|
||||
Used for APIs that hand out function pointers, NVN above all: every proc nvnDeviceGetProcAddress returns is one. */
|
||||
#include "hos.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
|
||||
#define HOS_HOSTCALL_BASE 0x06000000ULL
|
||||
#define HOS_HOSTCALL_MAX 8192
|
||||
|
||||
typedef void (*HostFn)(Ctx *c, void *user);
|
||||
typedef struct { HostFn fn; void *user; char name[64]; volatile LONG calls; } HostCall;
|
||||
static HostCall calls[HOS_HOSTCALL_MAX];
|
||||
static volatile LONG ncalls;
|
||||
static SRWLOCK lock = SRWLOCK_INIT;
|
||||
|
||||
/* The guest address of a host call named `name` (made on first request, the same address after). */
|
||||
uint64_t hos_hostcall(const char *name, HostFn fn, void *user) {
|
||||
AcquireSRWLockExclusive(&lock);
|
||||
for (LONG i = 0; i < ncalls; i++)
|
||||
if (!strcmp(calls[i].name, name)) { ReleaseSRWLockExclusive(&lock); return HOS_HOSTCALL_BASE + 16ULL * i; }
|
||||
if (ncalls == HOS_HOSTCALL_MAX) hos_fatal(NULL, "out of host calls");
|
||||
LONG i = ncalls++;
|
||||
calls[i].fn = fn;
|
||||
calls[i].user = user;
|
||||
snprintf(calls[i].name, sizeof calls[i].name, "%s", name);
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
return HOS_HOSTCALL_BASE + 16ULL * i;
|
||||
}
|
||||
|
||||
/* (mkw-recomp) the host function and user data behind a host call's address: 0 when it is not one */
|
||||
uint64_t hos_hostcall_target(uint64_t addr, HostFn *fn, void **user) {
|
||||
const uint64_t i = (addr - HOS_HOSTCALL_BASE) / 16;
|
||||
if (addr < HOS_HOSTCALL_BASE || i >= (uint64_t)ncalls) return 0;
|
||||
*fn = calls[i].fn, *user = calls[i].user;
|
||||
return addr;
|
||||
}
|
||||
|
||||
const char *hos_hostcall_name(uint64_t addr) {
|
||||
uint64_t i = (addr - HOS_HOSTCALL_BASE) / 16;
|
||||
return addr >= HOS_HOSTCALL_BASE && i < (uint64_t)ncalls ? calls[i].name : NULL;
|
||||
}
|
||||
|
||||
/* rt/a64_rt.c a64_lookup: a host call without user data as a plain function, called as fn(c) (its user argument, which
|
||||
such handlers do not read, is then whatever the register holds). Not with HOS_HOSTCALL_STATS or tracing (they count
|
||||
in a64_call_miss) or HOS_HOSTCALL_SLOW=1. Not on the web: wasm checks an indirect call's type, and a HostFn
|
||||
(two parameters) called as an A64Fn (one) traps with "function signature mismatch". */
|
||||
A64Fn a64_lookup_host(uint64_t addr) {
|
||||
#ifdef __EMSCRIPTEN__
|
||||
(void)addr;
|
||||
return NULL;
|
||||
#endif
|
||||
if (addr < HOS_HOSTCALL_BASE || (addr - HOS_HOSTCALL_BASE) % 16) return NULL;
|
||||
const uint64_t i = (addr - HOS_HOSTCALL_BASE) / 16;
|
||||
if (i >= (uint64_t)ncalls || calls[i].user) return NULL;
|
||||
static int slow = -1;
|
||||
if (slow < 0) slow = getenv("HOS_HOSTCALL_STATS") != NULL || hos_trace || getenv("HOS_HOSTCALL_SLOW") != NULL;
|
||||
return slow ? NULL : (A64Fn)(void *)calls[i].fn;
|
||||
}
|
||||
|
||||
/* The last host calls, for HOS_HOSTCALL_STATS: what a stalled thread was doing. */
|
||||
#define RING 256
|
||||
typedef struct { uint32_t call; uint32_t thread; uint64_t x[4], lr; } Recent;
|
||||
static Recent ring[RING];
|
||||
static volatile LONG ring_pos;
|
||||
|
||||
void hos_setjmp_return(Ctx *c, uint64_t target); /* hos_setjmp.c: a longjmp's BR to a setjmp site */
|
||||
int a64_call_miss(Ctx *c, uint64_t target) {
|
||||
hos_setjmp_return(c, target); /* (hookshot; does not return when it is one) */
|
||||
if (!target) {
|
||||
/* (hookshot) a callback table entry zeroed at run time: OoT's UpdateTextBoxTextureThread reaches its text release trampoline
|
||||
with a null function pointer at the same cutscene point every session. 0 is never a real function; returning 1 turns the
|
||||
tail call into a plain return. chrispository, Hookshot PR 55 */
|
||||
static volatile LONG logged;
|
||||
if (InterlockedIncrement(&logged) <= 8)
|
||||
hos_log("skipped an indirect call to 0 (lr %#llx, thread %s)", (unsigned long long)c->x[30], hos_thread_name(hos_self()));
|
||||
return 1;
|
||||
}
|
||||
if (target < HOS_HOSTCALL_BASE || (target - HOS_HOSTCALL_BASE) % 16) return 0;
|
||||
uint64_t i = (target - HOS_HOSTCALL_BASE) / 16;
|
||||
if (i >= (uint64_t)ncalls) return 0;
|
||||
HostCall *h = &calls[i];
|
||||
/* (the ring and the counts only for HOS_HOSTCALL_STATS / tracing: every NVN call took two interlocked increments
|
||||
on lines all game threads share) */
|
||||
static int stats = -1;
|
||||
if (stats < 0) stats = getenv("HOS_HOSTCALL_STATS") != NULL || hos_trace;
|
||||
if (!stats) {
|
||||
h->fn(c, h->user);
|
||||
return 1;
|
||||
}
|
||||
Recent *r = &ring[(InterlockedIncrement(&ring_pos) - 1) & (RING - 1)];
|
||||
r->call = (uint32_t)i;
|
||||
r->thread = GetCurrentThreadId();
|
||||
memcpy(r->x, c->x, sizeof r->x);
|
||||
r->lr = c->x[30];
|
||||
LONG n = InterlockedIncrement(&h->calls);
|
||||
if (hos_trace && n <= 3) hos_log("hostcall %s(%#llx, %#llx, %#llx, %#llx)", h->name, (unsigned long long)c->x[0],
|
||||
(unsigned long long)c->x[1], (unsigned long long)c->x[2], (unsigned long long)c->x[3]);
|
||||
h->fn(c, h->user);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Call guest code from inside a host function (an HLE handler), with up to four arguments, on the current guest
|
||||
stack. The guest callee keeps the AArch64 callee-saved registers; LR is restored here. Returns x0. */
|
||||
uint64_t hos_call_guest(Ctx *c, uint64_t fn, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3) {
|
||||
uint64_t lr = c->x[30];
|
||||
c->x[0] = a0; c->x[1] = a1; c->x[2] = a2; c->x[3] = a3;
|
||||
c->x[30] = 0;
|
||||
a64_icall(c, fn);
|
||||
c->x[30] = lr;
|
||||
return c->x[0];
|
||||
}
|
||||
|
||||
/* HOS_HOSTCALL_STATS=1: at exit, how often each host call ran (the NVN surface a game really uses). */
|
||||
void hos_hostcall_stats(void) {
|
||||
if (!getenv("HOS_HOSTCALL_STATS")) return;
|
||||
fprintf(stderr, "[hos] host calls:\n");
|
||||
for (LONG i = 0; i < ncalls; i++) fprintf(stderr, " %10ld %s\n", calls[i].calls, calls[i].name);
|
||||
LONG end = ring_pos, start = end > RING ? end - RING : 0;
|
||||
fprintf(stderr, "[hos] last %ld host calls (oldest first): thread, call(x0, x1, x2, x3) lr\n", end - start);
|
||||
for (LONG k = start; k < end; k++) {
|
||||
Recent *r = &ring[k & (RING - 1)];
|
||||
fprintf(stderr, " %6u %s(%#llx, %#llx, %#llx, %#llx) lr %#llx\n", r->thread, calls[r->call].name,
|
||||
(unsigned long long)r->x[0], (unsigned long long)r->x[1], (unsigned long long)r->x[2],
|
||||
(unsigned long long)r->x[3], (unsigned long long)r->lr);
|
||||
}
|
||||
fflush(stderr);
|
||||
}
|
||||
1588
host/hos_main.c
Normal file
1588
host/hos_main.c
Normal file
File diff suppressed because it is too large
Load Diff
341
host/hos_mem.c
Normal file
341
host/hos_mem.c
Normal file
@@ -0,0 +1,341 @@
|
||||
/* Guest memory map: the system region (our own objects), the heap, address regions.
|
||||
The whole 4 GB window is committed up front (hos_main.c), so "mapping" here is only bookkeeping and zeroing. */
|
||||
#include "hos.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#if defined(_WIN32)
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
static SRWLOCK lock = SRWLOCK_INIT;
|
||||
#define LOCK() AcquireSRWLockExclusive(&lock)
|
||||
#define UNLOCK() ReleaseSRWLockExclusive(&lock)
|
||||
#else
|
||||
#include <pthread.h>
|
||||
#include <sys/mman.h>
|
||||
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
#define LOCK() pthread_mutex_lock(&lock)
|
||||
#define UNLOCK() pthread_mutex_unlock(&lock)
|
||||
#endif
|
||||
|
||||
uint64_t hos_heap_size, hos_heap_used, hos_total_memory, hos_program_size;
|
||||
static uint64_t sys_next = HOS_SYSTEM_BASE;
|
||||
|
||||
/* Address regions are handed out top-down from HOS_SPACE_END; the heap grows up from HOS_HEAP_BASE. */
|
||||
typedef struct { uint64_t addr, size; } Range;
|
||||
static Range *regions;
|
||||
static int nregions, capregions;
|
||||
static uint64_t region_floor = ~0ULL; /* the lowest region (none yet: the window's end) */
|
||||
|
||||
/* Free address space below the heap that regions may also use (web: the window is tight): above the null guard
|
||||
to the system region, and from the image's end to the heap. */
|
||||
static uint64_t low_hole[2][2];
|
||||
|
||||
void hos_mem_init(uint64_t image_end) {
|
||||
hos_program_size = image_end - hos_image_base;
|
||||
hos_commit(HOS_SYSTEM_BASE, HOS_SYSTEM_END - HOS_SYSTEM_BASE);
|
||||
low_hole[0][0] = 0x00100000ULL, low_hole[0][1] = HOS_SYSTEM_BASE;
|
||||
low_hole[1][0] = (image_end + 0xFFFFFULL) & ~0xFFFFFULL, low_hole[1][1] = HOS_HEAP_BASE;
|
||||
/* Retail Switch gives an application 3285 MB. HOS_MEMORY_MB overrides it: TOTK sizes its heap from this
|
||||
(heap = total - used - 1080 MB), which is the lever for fitting the web build into wasm32. */
|
||||
const char *mb = getenv("HOS_MEMORY_MB");
|
||||
#ifdef A64_MEM_ZERO
|
||||
/* (web: TOTK keeps 1080 MB of the total for address regions (its resource memory grows into them) and its heap
|
||||
must stay 2104 MB (a 1902 MB heap: an indirect call into nothing 4 s in), so the window must hold heap +
|
||||
regions; the holes below the heap help) */
|
||||
hos_total_memory = (mb ? strtoull(mb, NULL, 0) : 3285ULL) << 20;
|
||||
hos_log("memory: %llu MB for the game (window %llu MB)", (unsigned long long)(hos_total_memory >> 20),
|
||||
(unsigned long long)(HOS_SPACE_END >> 20));
|
||||
#else
|
||||
/* mkw-recomp: a Switch 2 application gets 9809 MB (Eglantine's KSystemControl, 12 GB arrangement) */
|
||||
hos_total_memory = (mb ? strtoull(mb, NULL, 0) : 9809ULL) << 20;
|
||||
#endif
|
||||
}
|
||||
|
||||
uint64_t hos_region_floor(void) { return region_floor; }
|
||||
|
||||
uint64_t hos_sys_alloc(uint64_t size, uint64_t align) {
|
||||
LOCK();
|
||||
uint64_t a = (sys_next + align - 1) & ~(align - 1);
|
||||
if (a + size > HOS_SYSTEM_END) {
|
||||
UNLOCK();
|
||||
hos_fatal(NULL, "system region exhausted (%#llx bytes asked)", (unsigned long long)size);
|
||||
}
|
||||
sys_next = a + size;
|
||||
UNLOCK();
|
||||
memset(GP(a), 0, size);
|
||||
HOS_WRITTEN(GP(a), size);
|
||||
return a;
|
||||
}
|
||||
|
||||
uint64_t hos_region_alloc(uint64_t size, uint64_t align) {
|
||||
if (align < 0x1000) align = 0x1000;
|
||||
size = (size + 0xFFF) & ~0xFFFULL;
|
||||
LOCK();
|
||||
/* first fit, top-down, between existing regions (kept sorted by address, descending) */
|
||||
uint64_t top = HOS_SPACE_END, found = 0;
|
||||
int at = nregions;
|
||||
for (int i = 0; i <= nregions; i++) {
|
||||
uint64_t bottom = i < nregions ? regions[i].addr + regions[i].size : HOS_HEAP_BASE + hos_heap_size;
|
||||
if (top >= size) {
|
||||
uint64_t a = (top - size) & ~(align - 1);
|
||||
if (a >= bottom && a >= HOS_HEAP_BASE + hos_heap_size) { found = a; at = i; break; }
|
||||
}
|
||||
if (i < nregions) top = regions[i].addr;
|
||||
}
|
||||
if (!found) /* the holes below the heap, top-down, between the regions there (the list is descending) */
|
||||
for (int h = 1; h >= 0 && !found; h--) {
|
||||
uint64_t hi = low_hole[h][1];
|
||||
int i = 0;
|
||||
while (i < nregions && regions[i].addr >= hi) i++;
|
||||
for (;; i++) {
|
||||
const uint64_t lo = i < nregions && regions[i].addr + regions[i].size > low_hole[h][0]
|
||||
? regions[i].addr + regions[i].size : low_hole[h][0];
|
||||
if (hi >= size) {
|
||||
const uint64_t a = (hi - size) & ~(align - 1);
|
||||
if (a >= lo) { found = a; at = i; break; }
|
||||
}
|
||||
if (i >= nregions || regions[i].addr < low_hole[h][0]) break;
|
||||
hi = regions[i].addr;
|
||||
}
|
||||
}
|
||||
if (found) {
|
||||
if (nregions == capregions) {
|
||||
capregions = capregions ? capregions * 2 : 64;
|
||||
regions = (Range *)realloc(regions, capregions * sizeof(Range));
|
||||
}
|
||||
memmove(®ions[at + 1], ®ions[at], (nregions - at) * sizeof(Range));
|
||||
regions[at].addr = found;
|
||||
regions[at].size = size;
|
||||
nregions++;
|
||||
if (found < region_floor && found >= HOS_HEAP_BASE) region_floor = found; /* (not the holes below) */
|
||||
}
|
||||
UNLOCK();
|
||||
if (found) hos_commit(found, size);
|
||||
if (!found) hos_fatal(NULL, "address space exhausted (%#llx bytes asked, heap %#llx)", (unsigned long long)size,
|
||||
(unsigned long long)hos_heap_size);
|
||||
return found;
|
||||
}
|
||||
|
||||
static uint64_t pages_used[(1ULL << 32) / 0x1000 / 64];
|
||||
|
||||
static void pages_mark_used_locked(uint64_t addr, uint64_t size) {
|
||||
for (uint64_t p = addr >> 12; p < (addr + size + 0xFFF) >> 12 && p < (1ULL << 20); p++) pages_used[p >> 6] |= 1ULL << (p & 63);
|
||||
}
|
||||
|
||||
static void discard_pages(uint64_t addr, uint64_t size) {
|
||||
if (!hos_guest_range(addr, size)) return; /* (hookshot: guest pages only; Linux's discard zeroes what it is given) */
|
||||
const uint64_t lo = (addr + 0xFFF) & ~0xFFFULL, hi = (addr + size) & ~0xFFFULL;
|
||||
static int keep = -1;
|
||||
if (keep < 0) keep = getenv("HOS_KEEP_FREED_PAGES") != NULL;
|
||||
if (hi <= lo || keep) return;
|
||||
#if defined(_WIN32) && !defined(__EMSCRIPTEN__)
|
||||
extern int hos_large_pages; /* (hos_main.c: large pages cannot be discarded) */
|
||||
if (hos_large_pages) return;
|
||||
typedef DWORD(WINAPI * DiscardFn)(PVOID, SIZE_T);
|
||||
static DiscardFn discard;
|
||||
static int looked;
|
||||
if (!looked) {
|
||||
looked = 1;
|
||||
discard = (DiscardFn)(void *)GetProcAddress(GetModuleHandleA("kernel32.dll"), "DiscardVirtualMemory");
|
||||
}
|
||||
if (!discard || discard(GP(lo), (SIZE_T)(hi - lo)) != ERROR_SUCCESS)
|
||||
VirtualAlloc(GP(lo), (SIZE_T)(hi - lo), MEM_RESET, PAGE_READWRITE);
|
||||
#elif !defined(__EMSCRIPTEN__)
|
||||
extern int hos_posix_guest_discard(void *p, size_t n); /* (hos_main.c: MADV_REMOVE on the memfd window) */
|
||||
extern int rx_guest_imported(uint64_t lo, uint64_t hi);
|
||||
/* (pages a dma-buf import holds stay where they are, zeroed: a hole punched under one would leave the GPU on
|
||||
the old pages and the game on new ones) */
|
||||
if (rx_guest_imported(lo, hi)) memset(GP(lo), 0, (size_t)(hi - lo));
|
||||
else hos_posix_guest_discard(GP(lo), (size_t)(hi - lo));
|
||||
#endif
|
||||
}
|
||||
|
||||
void hos_region_free(uint64_t addr) {
|
||||
uint64_t freed = 0, freed_size = 0;
|
||||
LOCK();
|
||||
for (int i = 0; i < nregions; i++) {
|
||||
if (regions[i].addr == addr) {
|
||||
pages_mark_used_locked(regions[i].addr, regions[i].size);
|
||||
freed = regions[i].addr;
|
||||
freed_size = regions[i].size;
|
||||
memmove(®ions[i], ®ions[i + 1], (nregions - i - 1) * sizeof(Range));
|
||||
nregions--;
|
||||
break;
|
||||
}
|
||||
}
|
||||
UNLOCK();
|
||||
if (freed_size) discard_pages(freed, freed_size);
|
||||
}
|
||||
|
||||
/* ---- nn::os memory -------------------------------------------------------------------------------------- */
|
||||
|
||||
#if defined(A64_WRITE_TRACK) && !defined(__EMSCRIPTEN__)
|
||||
/* HOS_WRITTEN natively (the soft write watch, rt/a64.h A64_MARK): host code wrote [p, p + n) of guest memory */
|
||||
void hos_mark_written(const void *p, size_t n) {
|
||||
const uintptr_t a = (uintptr_t)p - (uintptr_t)A64_MEM;
|
||||
if (!n || (uintptr_t)p < (uintptr_t)A64_MEM || a >= HOS_GUEST_SPACE) return;
|
||||
for (uintptr_t q = a >> 12; q <= (a + n - 1) >> 12 && q < A64_DIRTY_PAGES; q++)
|
||||
__atomic_store_n(&a64_dirty[q], 1, __ATOMIC_RELEASE);
|
||||
}
|
||||
#endif
|
||||
|
||||
/* (hookshot) a heap of size bytes ends below the address regions and the guest window's end (no wrap-around: the size
|
||||
comes from the game). Also svc SetHeapSize's check (hos_svc.c) */
|
||||
int hos_heap_size_fits(uint64_t size) {
|
||||
const uint64_t limit = region_floor < HOS_SPACE_END ? region_floor : HOS_SPACE_END;
|
||||
return limit >= HOS_HEAP_BASE && size <= limit - HOS_HEAP_BASE;
|
||||
}
|
||||
/* nn::os::SetMemoryHeapSize(unsigned long) -> Result */
|
||||
HLE(_ZN2nn2os17SetMemoryHeapSizeEm) {
|
||||
uint64_t size = ARG(0);
|
||||
HOS_TRACE_CALL("SetMemoryHeapSize");
|
||||
if (!hos_heap_size_fits(size)) {
|
||||
hos_log("SetMemoryHeapSize(%#llx): collides with address regions at %#llx", (unsigned long long)size,
|
||||
(unsigned long long)region_floor);
|
||||
RET(0xCA01); /* svc::ResultOutOfMemory */
|
||||
return;
|
||||
}
|
||||
if (size < hos_heap_size) {
|
||||
memset(GP(HOS_HEAP_BASE + size), 0, hos_heap_size - size);
|
||||
HOS_WRITTEN(GP(HOS_HEAP_BASE + size), hos_heap_size - size);
|
||||
}
|
||||
/* HOS_PREFAULT=1 (experiment): the new heap pages touched now (a zero written to fresh, zero memory), so that the
|
||||
game's first touches while streaming are not page faults (which may hold up the renderer's write-watch scans) */
|
||||
if (size > hos_heap_size && getenv("HOS_PREFAULT")) {
|
||||
const int64_t t0 = hos_now_ns();
|
||||
for (uint64_t a = HOS_HEAP_BASE + hos_heap_size; a < HOS_HEAP_BASE + size; a += 4096) *(volatile uint8_t *)GP(a) = 0;
|
||||
hos_log("heap: %llu MB prefaulted in %.0f ms", (unsigned long long)((size - hos_heap_size) >> 20), (hos_now_ns() - t0) / 1e6);
|
||||
}
|
||||
if (size > hos_heap_size) hos_commit(HOS_HEAP_BASE + hos_heap_size, size - hos_heap_size);
|
||||
hos_heap_size = size;
|
||||
hos_log("heap: %llu MB at %#llx", (unsigned long long)(size >> 20), (unsigned long long)HOS_HEAP_BASE);
|
||||
RET(0);
|
||||
}
|
||||
|
||||
/* nn::os::AllocateMemoryBlock(unsigned long*, unsigned long) -> Result: 2 MB-aligned blocks from the heap */
|
||||
HLE(_ZN2nn2os19AllocateMemoryBlockEPmm) {
|
||||
uint64_t out = ARG(0), size = (ARG(1) + 0x1FFFFF) & ~0x1FFFFFULL;
|
||||
HOS_TRACE_CALL("AllocateMemoryBlock");
|
||||
LOCK();
|
||||
uint64_t a = HOS_HEAP_BASE + hos_heap_used;
|
||||
int ok = hos_heap_used + size <= hos_heap_size;
|
||||
if (ok) hos_heap_used += size;
|
||||
UNLOCK();
|
||||
if (!ok) {
|
||||
hos_log("AllocateMemoryBlock(%#llx): heap exhausted", (unsigned long long)size);
|
||||
RET(0x1A01); /* os::ResultOutOfMemory */
|
||||
return;
|
||||
}
|
||||
G64(out) = a;
|
||||
RET(0);
|
||||
}
|
||||
|
||||
/* nn::os::AllocateAddressRegion(unsigned long*, unsigned long) -> Result */
|
||||
HLE(_ZN2nn2os21AllocateAddressRegionEPmm) {
|
||||
HOS_TRACE_CALL("AllocateAddressRegion");
|
||||
G64(ARG(0)) = hos_region_alloc(ARG(1), 0x10000);
|
||||
RET(0);
|
||||
}
|
||||
|
||||
/* nn::os::FreeAddressRegion(unsigned long) -> Result */
|
||||
HLE(_ZN2nn2os17FreeAddressRegionEm) {
|
||||
HOS_TRACE_CALL("FreeAddressRegion");
|
||||
hos_region_free(ARG(0));
|
||||
RET(0);
|
||||
}
|
||||
|
||||
/* nn::os::AllocateMemoryPages(unsigned long, unsigned long) -> Result: new pages read as zero */
|
||||
HLE(_ZN2nn2os19AllocateMemoryPagesEmm) {
|
||||
HOS_TRACE_CALL("AllocateMemoryPages");
|
||||
const uint64_t a = ARG(0), n = ARG(1), end = a + n;
|
||||
if (!hos_guest_range(a, n)) { /* (hookshot: a range that wrapped around was zeroed whole, past the guest window) */
|
||||
hos_log("AllocateMemoryPages(%#llx, %#llx): outside the guest window", (unsigned long long)a, (unsigned long long)n);
|
||||
RET(0xCA01); /* svc::ResultOutOfMemory */
|
||||
return;
|
||||
}
|
||||
static int zero_all = -1;
|
||||
if (zero_all < 0) zero_all = getenv("HOS_ZERO_ALL_PAGES") != NULL;
|
||||
if (end > (1ULL << 32) && !zero_all) {
|
||||
/* (mkw-recomp) above 4 GB the used-page bitmap does not reach, and zeroing the whole range wiped live data
|
||||
when the game mapped pages over memory it already used (a heap's list lost its links). Horizon's rule
|
||||
instead: only newly mapped pages read as zero. A commit leaves committed pages as they are and gives fresh
|
||||
ones zeroed; FreeMemoryPages decommits. */
|
||||
hos_commit(a, n);
|
||||
} else if (zero_all || end > (1ULL << 32) || end < a) {
|
||||
memset(GP(a), 0, n);
|
||||
} else {
|
||||
uint64_t runs[64][2];
|
||||
int nruns = 0, overflow = 0, in_run = 0;
|
||||
LOCK();
|
||||
for (uint64_t p = a & ~0xFFFULL; p < end; p += 0x1000) {
|
||||
const uint64_t pg = p >> 12, bit = 1ULL << (pg & 63);
|
||||
const int used = (pages_used[pg >> 6] & bit) != 0;
|
||||
pages_used[pg >> 6] |= bit;
|
||||
if (used && !in_run) {
|
||||
if (nruns == 64) overflow = 1;
|
||||
else runs[nruns][0] = p < a ? a : p;
|
||||
in_run = 1;
|
||||
} else if (!used && in_run) {
|
||||
if (nruns < 64) runs[nruns++][1] = p;
|
||||
in_run = 0;
|
||||
}
|
||||
}
|
||||
if (in_run && nruns < 64) runs[nruns++][1] = end;
|
||||
UNLOCK();
|
||||
if (overflow) memset(GP(a), 0, n);
|
||||
else
|
||||
for (int i = 0; i < nruns; i++) memset(GP(runs[i][0]), 0, runs[i][1] - runs[i][0]);
|
||||
}
|
||||
HOS_WRITTEN(GP(a), n);
|
||||
RET(0);
|
||||
}
|
||||
|
||||
/* nn::os::FreeMemoryPages(unsigned long, unsigned long) -> Result */
|
||||
HLE(_ZN2nn2os15FreeMemoryPagesEmm) {
|
||||
HOS_TRACE_CALL("FreeMemoryPages");
|
||||
if (!hos_guest_range(ARG(0), ARG(1))) { /* (hookshot: decommitted or discarded: guest pages only) */
|
||||
hos_log("FreeMemoryPages(%#llx, %#llx): outside the guest window", (unsigned long long)ARG(0), (unsigned long long)ARG(1));
|
||||
RET(0xCA01);
|
||||
return;
|
||||
}
|
||||
if (ARG(0) + ARG(1) > (1ULL << 32)) { /* (mkw-recomp: the pair of AllocateMemoryPages' commit above) */
|
||||
const uint64_t lo = (ARG(0) + 0xFFF) & ~0xFFFULL, hi = (ARG(0) + ARG(1)) & ~0xFFFULL;
|
||||
/* (pages the Vulkan back end imported, as part of a pool's 16 MB chunk, stay committed and are zeroed: the GPU
|
||||
still maps them, and decommitted pages under an import faulted the device. Read as zero, as freed pages) */
|
||||
extern int rx_guest_imported(uint64_t lo, uint64_t hi);
|
||||
if (hi > lo && rx_guest_imported(lo, hi)) memset(GP(lo), 0, (size_t)(hi - lo));
|
||||
#if defined(_WIN32)
|
||||
else if (hi > lo) VirtualFree(GP(lo), (SIZE_T)(hi - lo), MEM_DECOMMIT);
|
||||
#else
|
||||
else if (hi > lo) { /* (linux: kept mapped, the pages read as zero; MADV_REMOVE on the memfd window) */
|
||||
extern int hos_posix_guest_discard(void *p, size_t n);
|
||||
hos_posix_guest_discard(GP(lo), (size_t)(hi - lo));
|
||||
}
|
||||
#endif
|
||||
RET(0);
|
||||
return;
|
||||
}
|
||||
discard_pages(ARG(0), ARG(1));
|
||||
RET(0);
|
||||
}
|
||||
|
||||
/* nn::os::QueryMemoryInfo(nn::os::MemoryInfo*). TOTK reads +0 (total available) and +8 (total used):
|
||||
heap = align_down(total - used, 2 MB) - 0x43800000 (main+0x1131004). */
|
||||
HLE(_ZN2nn2os15QueryMemoryInfoEPNS0_10MemoryInfoE) {
|
||||
uint64_t info = ARG(0);
|
||||
HOS_TRACE_CALL("QueryMemoryInfo");
|
||||
G64(info + 0x00) = hos_total_memory; /* total available */
|
||||
G64(info + 0x08) = hos_program_size + (16ULL << 20); /* total used: program + system */
|
||||
G64(info + 0x10) = hos_heap_size; /* total heap */
|
||||
G64(info + 0x18) = hos_heap_used; /* allocated heap */
|
||||
G64(info + 0x20) = hos_program_size; /* program */
|
||||
G64(info + 0x28) = 0; /* thread stacks */
|
||||
G32(info + 0x30) = 1; /* threads */
|
||||
}
|
||||
|
||||
/* nn::os::SetMemoryAllocatorForThreadLocal runs as the SDK's own code: it stores the game's allocator where
|
||||
nnosAllocateMemoryForThreadLocal finds it, which nnmusl uses for each thread's TLS (hos_thread.c thread_main). */
|
||||
|
||||
/* nn::os::SetDyingMessageRegion(unsigned long, unsigned long) -> Result */
|
||||
HLE(_ZN2nn2os21SetDyingMessageRegionEmm) { RET(0); }
|
||||
262
host/hos_motion.h
Normal file
262
host/hos_motion.h
Normal file
@@ -0,0 +1,262 @@
|
||||
/* (hookshot) A controller's motion sensors as the Switch reports its six-axis state (host/pad_sdl.c fills it from
|
||||
SDL, host/nn_hid.c hands it to the game's GetSixAxisSensorStates). Header-only, no SDL or Windows, so
|
||||
tests/test_motion.py runs it as it is.
|
||||
|
||||
This is Eden's (and yuzu's) motion, the emulators OoT aims right with: SDL's readings turned into the Switch's frame
|
||||
and units, and the state built as the console builds it, so the game gets what it gets on hardware and does its own
|
||||
aiming (it recenters on the camera each time it aims; how the pad is held, in bed or at a desk, does not matter):
|
||||
- acceleration in G and angular velocity in turns a second, in the Switch's frame (Eden's sdl_driver.cpp:
|
||||
x = -X, y = Z, z = -Y for the accelerometer, x = X, y = -Z, z = Y for the gyroscope, SDL's +X right, +Y out of the
|
||||
face buttons, +Z toward the player), so a pad lying face up reads (0, 0, -1) G;
|
||||
- the rotation: the angular velocity summed (turns);
|
||||
- the direction: the pad's orientation as a 3x3 matrix, from Mahony's filter (the gyroscope integrated as a
|
||||
quaternion, pulled toward the measured gravity: kp 0.3, ki 0.005), Eden's motion_input.cpp line for line.
|
||||
The gyroscope's resting rate (its bias) is learned while the pad is still on a table (both sensors steady) and
|
||||
taken off, and rates under 0.007 turns a second count as none, as the console's standard zero-drift mode does (the
|
||||
Motion deadzone row: Low and High are its tight 0.002 and loose 0.01).
|
||||
Motion sensitivity X/Y and Invert motion X/Y scale the angular velocity before it is used: its part about the
|
||||
world's up (the turn, X) and the rest (the tilt, Y). At 100% and not inverted the state is Eden's own. Earlier
|
||||
versions sent a partial state (a yaw rate and a tilt matrix, the rest neutral, spluton's and Link-22's findings in
|
||||
issue 112), and every way the pad could be held at the start needed its own case; the full state needs none.
|
||||
|
||||
The filter, the frame and the orientation matrix follow Eden's src/hid_core/frontend/motion_input.cpp and
|
||||
src/input_common/drivers/sdl_driver.cpp (Copyright 2020 yuzu Emulator Project, GPL-2.0-or-later; Copyright 2026 Eden
|
||||
Emulator Project, GPL-3.0-or-later), as this project is GPL-3.0. */
|
||||
#pragma once
|
||||
#include <math.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
#define HOS_MOTION_G 9.80665f
|
||||
#define HOS_MOTION_TAU 6.28318531f
|
||||
|
||||
typedef struct {
|
||||
float accel[3]; /* G, the Switch's frame */
|
||||
float gyro[3]; /* turns a second */
|
||||
float rotation[3]; /* turns */
|
||||
float direction[9]; /* rows: the orientation */
|
||||
} HosMotionState;
|
||||
|
||||
/* one reading's state as GetSixAxisSensorStates hands it out: n counts the readings, dt_ns is the time since the one
|
||||
before (host/pad_sdl.c keeps the last HOS_MOTION_HISTORY) */
|
||||
typedef struct {
|
||||
HosMotionState st;
|
||||
int64_t n, dt_ns;
|
||||
} HosMotionSample;
|
||||
#define HOS_MOTION_HISTORY 32
|
||||
|
||||
typedef struct {
|
||||
float quat[4]; /* x, y, z, w (Eden's order): the real orientation, Eden's filter on the real rates */
|
||||
float quat_out[4]; /* the orientation handed out: integrated from the rates as Motion sensitivity and Invert
|
||||
motion scale them, with the real filter's drift correction (the same as quat at 100%) */
|
||||
float real_error[3], integral_error[3];
|
||||
float bias[3]; /* turns a second, the Switch's frame */
|
||||
float learned_t; /* seconds of stillness learned from (fast at first, then slowly) */
|
||||
float still_t; /* seconds still */
|
||||
float gmean[3], gvar, avec[3], avar, amean; /* the short window's means and variances (stillness) */
|
||||
int stats_ready, only_accelerometer, reset_counter;
|
||||
float last_accel[3], last_gyro[3], pending_dt;
|
||||
float threshold; /* turns a second, the deadzone (0: HOS_MOTION_THRESHOLD) */
|
||||
float up[3]; /* the world's up in the Switch's frame (from the accelerometer, smoothed: for the split of
|
||||
the angular velocity into turn and tilt) */
|
||||
HosMotionState out;
|
||||
} HosMotion;
|
||||
|
||||
#define HOS_MOTION_STILL_GYRO 0.015f /* rad/s, summed over three axes (about 0.009 on each) */
|
||||
#define HOS_MOTION_STILL_ACCEL 0.0173f /* G, the same way (0.01 on each) */
|
||||
#define HOS_MOTION_STILL_S 0.5f
|
||||
#define HOS_MOTION_WINDOW_S 0.2f
|
||||
#define HOS_MOTION_DT_MAX 0.1f /* (Eden ignores a longer gap) */
|
||||
#define HOS_MOTION_THRESHOLD 0.007f /* turns a second: less is none (the console's standard zero-drift mode) */
|
||||
#define HOS_MOTION_THRESHOLD_TIGHT 0.002f /* (its tight and loose modes: the Motion deadzone row's Low and High) */
|
||||
#define HOS_MOTION_THRESHOLD_LOOSE 0.01f
|
||||
|
||||
static inline void hos_motion_rest(HosMotionState *o) {
|
||||
memset(o, 0, sizeof *o);
|
||||
o->accel[2] = -1;
|
||||
o->direction[0] = o->direction[4] = o->direction[8] = 1;
|
||||
}
|
||||
|
||||
static inline void hos_motion_reset(HosMotion *m) {
|
||||
memset(m, 0, sizeof *m);
|
||||
m->quat[2] = -1; /* (Eden's ResetQuaternion: {0, 0, -1, 0}) */
|
||||
m->quat_out[2] = -1;
|
||||
m->only_accelerometer = 1;
|
||||
m->up[2] = 1;
|
||||
hos_motion_rest(&m->out);
|
||||
}
|
||||
|
||||
static inline float hos_motion_len(const float v[3]) { return sqrtf(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); }
|
||||
|
||||
/* a quaternion (Eden's x, y, z, w) turned at Eden's filter rate rg for period seconds */
|
||||
static inline void hos_motion_integrate(float quat[4], const float rg[3], float period) {
|
||||
float q1 = quat[3], q2 = quat[0], q3 = quat[1], q4 = quat[2];
|
||||
const float gx = rg[1], gy = rg[0], gz = rg[2];
|
||||
const float pa = q2, pb = q3, pc = q4;
|
||||
q1 = q1 + (-q2 * gx - q3 * gy - q4 * gz) * (0.5f * period);
|
||||
q2 = pa + (q1 * gx + pb * gz - pc * gy) * (0.5f * period);
|
||||
q3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * period);
|
||||
q4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * period);
|
||||
const float n = sqrtf(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4);
|
||||
if (n > 0) quat[3] = q1 / n, quat[0] = q2 / n, quat[1] = q3 / n, quat[2] = q4 / n;
|
||||
}
|
||||
static inline void hos_motion_rate(const HosMotion *m, const float gyro[3], float rg[3]) { /* (Eden's swap, rad/s) */
|
||||
rg[0] = gyro[1] * HOS_MOTION_TAU, rg[1] = -gyro[0] * HOS_MOTION_TAU, rg[2] = -gyro[2] * HOS_MOTION_TAU;
|
||||
if (m->only_accelerometer) rg[0] = rg[1] = rg[2] = 0;
|
||||
}
|
||||
|
||||
/* Mahony's filter on the real quaternion, Eden's UpdateOrientation (period: seconds; gain 10: the settling of
|
||||
SetOrientationFromAccelerometer). Returns the feedback it added to the rate, in *corr (rad/s, the filter's frame), so
|
||||
the handed-out orientation can lose the same drift. */
|
||||
static inline void hos_motion_mahony(HosMotion *m, const float accel[3], const float gyro[3], float period, float gain,
|
||||
float corr[3]) {
|
||||
const float q1 = m->quat[3], q2 = m->quat[0], q3 = m->quat[1], q4 = m->quat[2];
|
||||
const float alen = hos_motion_len(accel);
|
||||
float rg[3];
|
||||
hos_motion_rate(m, gyro, rg);
|
||||
if (gain > 1) rg[0] = rg[1] = rg[2] = 0;
|
||||
corr[0] = corr[1] = corr[2] = 0;
|
||||
if ((alen >= 0.75f && alen <= 1.25f) || gain > 1) {
|
||||
const float ax = -accel[0] / alen, ay = accel[1] / alen, az = -accel[2] / alen;
|
||||
const float vx = 2.0f * (q2 * q4 - q1 * q3);
|
||||
const float vy = 2.0f * (q1 * q2 + q3 * q4);
|
||||
const float vz = q1 * q1 - q2 * q2 - q3 * q3 + q4 * q4;
|
||||
const float e[3] = {az * vx - ax * vz, ay * vz - az * vy, ax * vy - ay * vx};
|
||||
memcpy(m->real_error, e, sizeof e);
|
||||
if (gain <= 1 && hos_motion_len(e) >= 0.05f)
|
||||
for (int i = 0; i < 3; i++) m->integral_error[i] += e[i];
|
||||
else if (gain <= 1)
|
||||
memset(m->integral_error, 0, sizeof m->integral_error);
|
||||
const float kp = 0.3f, ki = 0.005f;
|
||||
const float wp = gain > 1 ? 10 : m->only_accelerometer ? 35 : 1, wi = gain > 1 ? 5 : m->only_accelerometer ? 10 : 1;
|
||||
for (int i = 0; i < 3; i++) corr[i] = wp * kp * e[i] + wi * ki * m->integral_error[i];
|
||||
}
|
||||
for (int i = 0; i < 3; i++) rg[i] += corr[i];
|
||||
hos_motion_integrate(m->quat, rg, period);
|
||||
}
|
||||
|
||||
/* the orientation matrix, Eden's GetOrientation (its quaternion's matrix, with its sign changes) */
|
||||
static inline void hos_motion_direction(const float quat[4], float d[9]) {
|
||||
const float x = -quat[1], y = -quat[0], z = -quat[3], w = -quat[2];
|
||||
const float x2 = x * x, y2 = y * y, z2 = z * z, xy = x * y, wz = w * z, xz = x * z, wy = w * y, yz = y * z, wx = w * x;
|
||||
const float mm[9] = {1 - 2 * (y2 + z2), 2 * (xy + wz), 2 * (xz - wy), 2 * (xy - wz), 1 - 2 * (x2 + z2), 2 * (yz + wx),
|
||||
2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (x2 + y2)};
|
||||
d[0] = mm[0], d[1] = mm[1], d[2] = -mm[2];
|
||||
d[3] = mm[3], d[4] = mm[4], d[5] = -mm[5];
|
||||
d[6] = -mm[6], d[7] = -mm[7], d[8] = mm[8];
|
||||
}
|
||||
|
||||
/* One reading: SDL's accelerometer (m/s^2) and gyroscope (rad/s), dt seconds after the last one. sens_h and sens_v
|
||||
scale the turn and the tilt (1: as the pad turns); inv_h and inv_v turn them the other way. Returns 0 for a repeat
|
||||
of the last reading (no new reading: its time goes into the next), 1 otherwise. */
|
||||
static inline int hos_motion_update(HosMotion *m, const float accel_sdl[3], const float gyro_sdl[3], float dt,
|
||||
float sens_h, float sens_v, int inv_h, int inv_v) {
|
||||
if (!(dt >= 0)) dt = 0;
|
||||
if (m->stats_ready && !memcmp(accel_sdl, m->last_accel, sizeof m->last_accel) &&
|
||||
!memcmp(gyro_sdl, m->last_gyro, sizeof m->last_gyro)) {
|
||||
m->pending_dt += dt;
|
||||
return 0;
|
||||
}
|
||||
memcpy(m->last_accel, accel_sdl, sizeof m->last_accel), memcpy(m->last_gyro, gyro_sdl, sizeof m->last_gyro);
|
||||
dt += m->pending_dt, m->pending_dt = 0;
|
||||
/* the Switch's frame and units (Eden's sdl_driver.cpp), clamped as Eden clamps them */
|
||||
float a[3] = {-accel_sdl[0] / HOS_MOTION_G, accel_sdl[2] / HOS_MOTION_G, -accel_sdl[1] / HOS_MOTION_G};
|
||||
float g[3] = {gyro_sdl[0] / HOS_MOTION_TAU, -gyro_sdl[2] / HOS_MOTION_TAU, gyro_sdl[1] / HOS_MOTION_TAU};
|
||||
for (int i = 0; i < 3; i++) {
|
||||
a[i] = a[i] < -7 ? -7 : a[i] > 7 ? 7 : a[i];
|
||||
}
|
||||
const float alen = hos_motion_len(a);
|
||||
/* stillness: the short window's spread of both sensors (rad/s and G, summed over the axes), about 1 G */
|
||||
if (!m->stats_ready) {
|
||||
memcpy(m->gmean, g, sizeof m->gmean), memcpy(m->avec, a, sizeof m->avec);
|
||||
m->gvar = 0.01f, m->avar = 0.01f, m->amean = alen, m->stats_ready = 1;
|
||||
} else if (dt > 0) {
|
||||
const float k = dt / (HOS_MOTION_WINDOW_S + dt);
|
||||
float gv = 0, av = 0;
|
||||
for (int i = 0; i < 3; i++) {
|
||||
const float dg = (g[i] - m->gmean[i]) * HOS_MOTION_TAU, da = a[i] - m->avec[i];
|
||||
m->gmean[i] += (g[i] - m->gmean[i]) * k, m->avec[i] += da * k;
|
||||
gv += dg * dg, av += da * da;
|
||||
}
|
||||
m->gvar += (gv - m->gvar) * k, m->avar += (av - m->avar) * k, m->amean += (alen - m->amean) * k;
|
||||
}
|
||||
const int still = m->gvar < HOS_MOTION_STILL_GYRO * HOS_MOTION_STILL_GYRO &&
|
||||
m->avar < HOS_MOTION_STILL_ACCEL * HOS_MOTION_STILL_ACCEL && m->amean > 0.9f && m->amean < 1.1f;
|
||||
m->still_t = still ? m->still_t + dt : 0;
|
||||
if (m->still_t >= HOS_MOTION_STILL_S && dt > 0) {
|
||||
const float k = dt / ((m->learned_t < 2 ? 0.25f : 3.0f) + dt);
|
||||
for (int i = 0; i < 3; i++) m->bias[i] += (m->gmean[i] - m->bias[i]) * k;
|
||||
m->learned_t += dt;
|
||||
}
|
||||
for (int i = 0; i < 3; i++) {
|
||||
g[i] -= m->bias[i];
|
||||
g[i] = g[i] < -5 ? -5 : g[i] > 5 ? 5 : g[i];
|
||||
}
|
||||
if (hos_motion_len(g) < (m->threshold > 0 ? m->threshold : HOS_MOTION_THRESHOLD)) g[0] = g[1] = g[2] = 0;
|
||||
else m->only_accelerometer = 0;
|
||||
/* the turn and the tilt: the angular velocity's part about the world's up, and the rest, scaled and turned around
|
||||
as the menu says (the up from the accelerometer, smoothed) */
|
||||
if (alen > 0.65f && alen < 1.35f) {
|
||||
const float k = dt / (0.1f + dt);
|
||||
for (int i = 0; i < 3; i++) m->up[i] += (-a[i] / alen - m->up[i]) * k;
|
||||
const float n = hos_motion_len(m->up);
|
||||
if (n > 0.001f) for (int i = 0; i < 3; i++) m->up[i] /= n;
|
||||
}
|
||||
float gs[3]; /* (the scaled rates: what the game is handed; g stays real for the filter) */
|
||||
{
|
||||
const float sh = sens_h * (inv_h ? -1.0f : 1.0f), sv = sens_v * (inv_v ? -1.0f : 1.0f);
|
||||
const float t = g[0] * m->up[0] + g[1] * m->up[1] + g[2] * m->up[2];
|
||||
for (int i = 0; i < 3; i++) gs[i] = sh * t * m->up[i] + sv * (g[i] - t * m->up[i]);
|
||||
}
|
||||
if (dt > HOS_MOTION_DT_MAX) dt = 0; /* (Eden ignores a stall: no rotation, no orientation step) */
|
||||
for (int i = 0; i < 3; i++) m->out.rotation[i] += gs[i] * dt;
|
||||
/* Eden's ResetOrientation: a filter that lost track (its error over 0.1) is set again from the accelerometer once
|
||||
the pad has lain face up and still for 900 readings */
|
||||
if (hos_motion_len(m->real_error) >= 0.1f && !m->only_accelerometer) {
|
||||
if (hos_motion_len(g) < 0.05f && alen > 0.9f && alen < 1.1f && a[2] <= -0.9f) {
|
||||
if (++m->reset_counter > 900) {
|
||||
m->quat[0] = m->quat[1] = m->quat[3] = 0, m->quat[2] = -1;
|
||||
memset(m->integral_error, 0, sizeof m->integral_error);
|
||||
float c[3];
|
||||
for (int it = 0; it < 100 && hos_motion_len(m->real_error) >= 0.01f; it++)
|
||||
hos_motion_mahony(m, a, g, 0.015f, 10, c);
|
||||
memcpy(m->quat_out, m->quat, sizeof m->quat); /* (set again from gravity: the handed-out one too) */
|
||||
m->reset_counter = 0;
|
||||
}
|
||||
} else {
|
||||
m->reset_counter = 0;
|
||||
}
|
||||
}
|
||||
if (dt > 0) {
|
||||
/* the real filter, then the handed-out orientation: the scaled rates plus the real filter's correction, so it
|
||||
loses the gyro's drift but keeps a scaled or inverted move (the gravity pull acts on the real one only;
|
||||
hckrman101). While only the accelerometer has been seen the two settle together. */
|
||||
const int settling = m->only_accelerometer;
|
||||
float c[3], rs[3];
|
||||
hos_motion_mahony(m, a, g, dt, 1, c);
|
||||
if (settling) {
|
||||
memcpy(m->quat_out, m->quat, sizeof m->quat);
|
||||
} else {
|
||||
/* the scaling in the world's frame (hckrman101): the real rate taken to the world by the real orientation,
|
||||
its vertical part (the turn) scaled by sh and the rest (the tilt) by sv, and brought back to the pad by the
|
||||
handed-out one, so a scaled turn while tilted turns quat_out about its own vertical and does not tip it.
|
||||
Both matrices map the world to the pad (their third column is the world's up seen from the pad). */
|
||||
float dr[9], dq[9], w[3], go[3];
|
||||
hos_motion_direction(m->quat, dr);
|
||||
hos_motion_direction(m->quat_out, dq);
|
||||
{
|
||||
const float sh = sens_h * (inv_h ? -1.0f : 1.0f), sv = sens_v * (inv_v ? -1.0f : 1.0f);
|
||||
for (int i = 0; i < 3; i++) w[i] = dr[i] * g[0] + dr[3 + i] * g[1] + dr[6 + i] * g[2]; /* (dr^T g) */
|
||||
w[0] *= sv, w[1] *= sv, w[2] *= sh;
|
||||
for (int i = 0; i < 3; i++) go[i] = dq[3 * i] * w[0] + dq[3 * i + 1] * w[1] + dq[3 * i + 2] * w[2];
|
||||
}
|
||||
hos_motion_rate(m, go, rs);
|
||||
for (int i = 0; i < 3; i++) rs[i] += c[i];
|
||||
hos_motion_integrate(m->quat_out, rs, dt);
|
||||
}
|
||||
}
|
||||
memcpy(m->out.accel, a, sizeof a);
|
||||
memcpy(m->out.gyro, gs, sizeof gs);
|
||||
hos_motion_direction(m->quat_out, m->out.direction);
|
||||
return 1;
|
||||
}
|
||||
81
host/hos_paths.h
Normal file
81
host/hos_paths.h
Normal file
@@ -0,0 +1,81 @@
|
||||
/* The game folder's path, for the files the game keeps there (image.bin, romfs, saves, settings, caches, logs).
|
||||
On Windows the game is bin\Triforce.exe since the launcher came: Triforce.exe in the folder is the launcher (the builder's
|
||||
setup in launch mode), the game and its DLLs are in bin\, the game's files stay in the folder. hos_game_path_a/_w answer as
|
||||
GetModuleFileName(NULL, ...) does, but with the folder's path when the exe is in a "bin" folder beside image.bin, so code that
|
||||
strips the exe's name and adds a file's finds the folder's file. Modules (DLLs) are still loaded from beside the exe itself. */
|
||||
#pragma once
|
||||
#include <string.h>
|
||||
#include <wchar.h>
|
||||
#ifdef _WIN32
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#include <windows.h>
|
||||
|
||||
static inline DWORD hos_game_path_a(char *buf, DWORD size) {
|
||||
DWORD n = GetModuleFileNameA(NULL, buf, size);
|
||||
if (!n || n >= size) return n;
|
||||
char *name = n ? buf + n : buf;
|
||||
while (name > buf && name[-1] != '\\' && name[-1] != '/') name--;
|
||||
if (name - buf < 5) return n;
|
||||
char *dir = name - 1; /* (the separator before the exe's name) */
|
||||
char *bin = dir;
|
||||
while (bin > buf && bin[-1] != '\\' && bin[-1] != '/') bin--;
|
||||
if (dir - bin != 3 || _strnicmp(bin, "bin", 3) != 0) return n;
|
||||
char probe[MAX_PATH + 16];
|
||||
const size_t root = (size_t)(bin - buf); /* (the folder, with its separator) */
|
||||
if (root + 10 >= sizeof probe) return n;
|
||||
memcpy(probe, buf, root);
|
||||
strcpy(probe + root, "image.bin");
|
||||
if (GetFileAttributesA(probe) == INVALID_FILE_ATTRIBUTES) return n;
|
||||
memmove(buf + root, name, strlen(name) + 1); /* (folder\Triforce.exe) */
|
||||
return (DWORD)strlen(buf);
|
||||
}
|
||||
|
||||
static inline DWORD hos_game_path_w(wchar_t *buf, DWORD size) {
|
||||
DWORD n = GetModuleFileNameW(NULL, buf, size);
|
||||
if (!n || n >= size) return n;
|
||||
wchar_t *name = buf + n;
|
||||
while (name > buf && name[-1] != L'\\' && name[-1] != L'/') name--;
|
||||
if (name - buf < 5) return n;
|
||||
wchar_t *dir = name - 1;
|
||||
wchar_t *bin = dir;
|
||||
while (bin > buf && bin[-1] != L'\\' && bin[-1] != L'/') bin--;
|
||||
if (dir - bin != 3 || _wcsnicmp(bin, L"bin", 3) != 0) return n;
|
||||
wchar_t probe[MAX_PATH + 16];
|
||||
const size_t root = (size_t)(bin - buf);
|
||||
if (root + 10 >= sizeof probe / sizeof probe[0]) return n;
|
||||
wmemcpy(probe, buf, root);
|
||||
wcscpy(probe + root, L"image.bin");
|
||||
if (GetFileAttributesW(probe) == INVALID_FILE_ATTRIBUTES) return n;
|
||||
wmemmove(buf + root, name, wcslen(name) + 1);
|
||||
return (DWORD)wcslen(buf);
|
||||
}
|
||||
#else
|
||||
#include <unistd.h>
|
||||
#include <windows.h> /* (linux: host/posix's, for DWORD and GetModuleFileNameA) */
|
||||
/* (Linux) the same bin/ layout when the folder was built by the packaged builder: hookshot in the folder is the
|
||||
launcher script, and the game is bin/hookshot. A development build has no bin/ and this is GetModuleFileName. */
|
||||
static inline DWORD hos_game_path_a(char *buf, DWORD size) {
|
||||
DWORD n = GetModuleFileNameA(NULL, buf, size);
|
||||
if (!n || n >= size) return n;
|
||||
char *name = buf + n;
|
||||
while (name > buf && name[-1] != '/') name--;
|
||||
if (name - buf < 5) return n;
|
||||
char *dir = name - 1;
|
||||
char *bin = dir;
|
||||
while (bin > buf && bin[-1] != '/') bin--;
|
||||
if (dir - bin != 3 || memcmp(bin, "bin", 3) != 0) return n;
|
||||
char probe[MAX_PATH + 16];
|
||||
const size_t root = (size_t)(bin - buf);
|
||||
if (root + 10 >= sizeof probe) return n;
|
||||
memcpy(probe, buf, root);
|
||||
memcpy(probe + root, "image.bin", 10);
|
||||
if (access(probe, F_OK) != 0) return n;
|
||||
memmove(buf + root, name, strlen(name) + 1);
|
||||
return (DWORD)strlen(buf);
|
||||
}
|
||||
#endif
|
||||
95
host/hos_relaunch.c
Normal file
95
host/hos_relaunch.c
Normal file
@@ -0,0 +1,95 @@
|
||||
/* (hookshot) The Insert menu's Restart now (gpu/vk/vk_menu.cpp): it saves its options and asks the window to close for a
|
||||
restart (WM_APP + 9: host/display.c, host/posix/display_sdl.c). The window closes as when the player closes it, and at
|
||||
the very end of that, instead of only exiting, the game is started again:
|
||||
Linux: the process becomes the game again (execve) with the arguments and the environment it started with
|
||||
(/proc/self/cmdline and /proc/self/environ: triforce_env.txt's lines are read again, not kept), so whatever waits
|
||||
for it (the launcher, a stream, a test) still has it. The game is bin/hookshot on disk, never run from inside the
|
||||
AppImage (hookshot-launch starts it with the AppImage's variables taken away), so /proc/self/exe is the game;
|
||||
argv[0] on the PATH if that is gone (the folder built again meanwhile).
|
||||
Windows: a new process of this executable (GetModuleFileNameW) with this one's command line (GetCommandLineW), in
|
||||
the same folder and environment; then this one exits. */
|
||||
#include "hos.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <windows.h>
|
||||
|
||||
static volatile LONG relaunch_asked;
|
||||
|
||||
void hos_relaunch_ask(void) { InterlockedExchange(&relaunch_asked, 1); }
|
||||
|
||||
#ifdef _WIN32
|
||||
static void relaunch(void) {
|
||||
wchar_t exe[MAX_PATH * 4];
|
||||
const DWORD n = GetModuleFileNameW(NULL, exe, MAX_PATH * 4);
|
||||
if (!n || n >= MAX_PATH * 4) {
|
||||
hos_log("restart: this executable's path was not found: the game only exits");
|
||||
return;
|
||||
}
|
||||
const wchar_t *line = GetCommandLineW();
|
||||
const size_t len = wcslen(line);
|
||||
wchar_t *cmd = (wchar_t *)malloc((len + 1) * sizeof *cmd); /* (CreateProcessW may write into it) */
|
||||
if (!cmd) return;
|
||||
memcpy(cmd, line, (len + 1) * sizeof *cmd);
|
||||
STARTUPINFOW si;
|
||||
PROCESS_INFORMATION pi;
|
||||
memset(&si, 0, sizeof si);
|
||||
si.cb = sizeof si;
|
||||
/* (the new process waits for this one to end before it moves triforce_log.txt to .1 and opens its own: this one still
|
||||
has it open until it exits, and a rename of an open file fails on Windows, so the new run overwrote the old run's
|
||||
log. hos_main.c reads HOS_RESTART_OF) */
|
||||
wchar_t pid[16];
|
||||
swprintf(pid, 16, L"%lu", (unsigned long)GetCurrentProcessId());
|
||||
SetEnvironmentVariableW(L"HOS_RESTART_OF", pid);
|
||||
if (CreateProcessW(exe, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
|
||||
CloseHandle(pi.hThread);
|
||||
CloseHandle(pi.hProcess);
|
||||
} else {
|
||||
hos_log("restart: the game could not be started again (error %lu): it only exits", (unsigned long)GetLastError());
|
||||
hos_log_flush();
|
||||
}
|
||||
free(cmd);
|
||||
}
|
||||
#else
|
||||
#include "hos_relaunch.h"
|
||||
#include <dirent.h>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
extern char **environ;
|
||||
|
||||
static void relaunch(void) {
|
||||
HosRelaunch r;
|
||||
if (!hos_relaunch_command("/proc/self/cmdline", "/proc/self/environ", &r)) {
|
||||
hos_log("restart: this process's command was not found: the game only exits");
|
||||
hos_log_flush();
|
||||
return;
|
||||
}
|
||||
/* (every file this process opened closes with it, as at an exit: the new one opens its own) */
|
||||
DIR *d = opendir("/proc/self/fd");
|
||||
if (d) {
|
||||
const int skip = dirfd(d);
|
||||
for (struct dirent *e; (e = readdir(d));) {
|
||||
const int fd = atoi(e->d_name);
|
||||
if (fd > 2 && fd != skip) fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
fflush(NULL);
|
||||
execve("/proc/self/exe", r.argv, r.envp);
|
||||
environ = r.envp; /* (execvp searches the PATH of the environment it is given: the one the game started with) */
|
||||
execvp(r.argv[0], r.argv);
|
||||
hos_log("restart: the game could not be started again: it only exits");
|
||||
hos_log_flush();
|
||||
}
|
||||
#endif
|
||||
|
||||
/* The window was closed (host/display.c's WM_CLOSE, host/posix/display_sdl.c's quit): the game exits, and starts again
|
||||
first when the menu asked for it */
|
||||
void hos_window_closed_exit(void) {
|
||||
const int again = relaunch_asked != 0;
|
||||
hos_log(again ? "display: window closed for a restart (the Insert menu's Restart now)" : "display: window closed, exiting");
|
||||
hos_log_flush();
|
||||
if (again) relaunch();
|
||||
ExitProcess(0);
|
||||
}
|
||||
70
host/hos_relaunch.h
Normal file
70
host/hos_relaunch.h
Normal file
@@ -0,0 +1,70 @@
|
||||
/* (hookshot) The command a restart starts again (host/hos_relaunch.c, the Insert menu's Restart now), as plain C:
|
||||
on Linux the arguments and the environment the process started with, read from /proc/self/cmdline and
|
||||
/proc/self/environ (strings ended by a NUL each). tests/test_menu_restart.py checks it. */
|
||||
#pragma once
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct {
|
||||
char *args, *env; /* (the files' bytes, each string ended by a NUL) */
|
||||
char **argv, **envp; /* (into them, each ended by a NULL) */
|
||||
int argc, envc;
|
||||
} HosRelaunch;
|
||||
|
||||
/* A file's whole contents and one NUL more (a /proc file says it is empty: read until its end). NULL if it cannot be read */
|
||||
static inline char *hos_relaunch_slurp(const char *path, size_t *len) {
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (!f) return NULL;
|
||||
size_t n = 0, cap = 4096;
|
||||
char *b = (char *)malloc(cap + 1);
|
||||
for (size_t got; b && (got = fread(b + n, 1, cap - n, f)) > 0;) {
|
||||
n += got;
|
||||
if (n == cap) {
|
||||
char *more = (char *)realloc(b, cap * 2 + 1);
|
||||
if (!more) free(b);
|
||||
b = more, cap *= 2;
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
if (!b) return NULL;
|
||||
b[n] = 0;
|
||||
*len = n;
|
||||
return b;
|
||||
}
|
||||
|
||||
/* The strings in blob (len bytes, each ended by a NUL; blob[len] is a NUL too, for a last one without its own) as a
|
||||
NULL-ended array: their count, -1 out of memory */
|
||||
static inline int hos_relaunch_split(char *blob, size_t len, char ***out) {
|
||||
int n = 0;
|
||||
for (size_t i = 0; i < len; i++)
|
||||
if (!blob[i] || i + 1 == len) n++;
|
||||
char **v = (char **)malloc(sizeof *v * (size_t)(n + 1));
|
||||
if (!v) return -1;
|
||||
int k = 0;
|
||||
for (size_t i = 0; i < len && k < n;) {
|
||||
v[k++] = blob + i;
|
||||
while (i < len && blob[i]) i++;
|
||||
i++;
|
||||
}
|
||||
v[k] = NULL;
|
||||
*out = v;
|
||||
return k;
|
||||
}
|
||||
|
||||
/* The command from those two files (/proc/self/cmdline, /proc/self/environ): 1, or 0 when either cannot be read or
|
||||
there is no argument (argv[0]) */
|
||||
static inline int hos_relaunch_command(const char *cmdline, const char *environ_file, HosRelaunch *r) {
|
||||
size_t an = 0, en = 0;
|
||||
memset(r, 0, sizeof *r);
|
||||
r->args = hos_relaunch_slurp(cmdline, &an);
|
||||
r->env = hos_relaunch_slurp(environ_file, &en);
|
||||
if (!r->args || !r->env || (r->argc = hos_relaunch_split(r->args, an, &r->argv)) < 1 ||
|
||||
(r->envc = hos_relaunch_split(r->env, en, &r->envp)) < 0) {
|
||||
free(r->args), free(r->env), free(r->argv), free(r->envp);
|
||||
memset(r, 0, sizeof *r);
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
625
host/hos_sdl.c
Normal file
625
host/hos_sdl.c
Normal file
@@ -0,0 +1,625 @@
|
||||
/* SDL3 or SDL2 behind one set of calls (hos_sdl.h). Each call is SDL3's or SDL2's, the same work under other names;
|
||||
SDL3 returns C's bool where SDL2 returned 0 for success or an SDL_bool, and the events and a few structures are laid
|
||||
out differently (both read here at their offsets: SDL_Event is 128 bytes in SDL3, 56 in SDL2). */
|
||||
#include "hos.h"
|
||||
#include "hos_sdl.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
|
||||
static int version; /* 3, 2, or 0 none */
|
||||
static struct {
|
||||
void *InitSubSystem, *SetHint, *GetError;
|
||||
/* window */
|
||||
void *CreateWindow, *SetWindowPosition, *SetWindowFullscreen, *SetRelativeMouseMode, *GetPrimaryDisplay,
|
||||
*GetDesktopDisplayMode, *Vulkan_CreateSurface, *PixelSize, *GetKeyboardState, *GetMouseState, *WaitEventTimeout,
|
||||
*PollEvent, *GetWindowSize, *LoadPNG, *SetWindowIcon, *DestroySurface, *GetWindowDisplay, *GetCurrentDisplayMode;
|
||||
/* sound */
|
||||
void *OpenAudioDevice, *PauseAudioDevice, *OpenAudioDeviceStream, *ResumeAudioStreamDevice, *PutAudioStreamData;
|
||||
/* controllers */
|
||||
void *PadOpen, *PadClose, *PadConnected, *PadsUpdate, *PadButton, *PadAxis, *PadName, *PadRumble;
|
||||
void *PadType, *PadEffect; /* (optional: HD rumble, host/pad_sdl.c) */
|
||||
void *PadHasSensor, *PadSensorEnable, *PadSensorData; /* (motion: optional, NULL in an SDL without them) */
|
||||
void *GetGamepads, *GetGamepadID, *Free; /* (SDL3) */
|
||||
void *NumJoysticks, *IsGameController, *DeviceInstanceID, *GetJoystick, *JoystickInstanceID; /* (SDL2) */
|
||||
} f;
|
||||
#define CALL(type, fn) ((type)f.fn)
|
||||
|
||||
static HMODULE load_one(const char *dll) { /* beside the executable, else the system's */
|
||||
char path[MAX_PATH];
|
||||
DWORD n = GetModuleFileNameA(NULL, path, sizeof path);
|
||||
while (n && path[n - 1] != '\\' && path[n - 1] != '/') n--;
|
||||
snprintf(path + n, sizeof path - n, "%s", dll);
|
||||
HMODULE m = n ? LoadLibraryA(path) : NULL; /* (no folder: a bare name would search the current folder and PATH) */
|
||||
#ifdef _WIN32 /* (hookshot: else the system's, not the current folder's or PATH's) */
|
||||
return m ? m : LoadLibraryExA(dll, NULL, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
|
||||
#else
|
||||
return m ? m : LoadLibraryA(dll);
|
||||
#endif
|
||||
}
|
||||
static int get_all(HMODULE m, int three) {
|
||||
#define GET(field, name) if (!(*(FARPROC *)&f.field = GetProcAddress(m, name))) { hos_log("sdl: SDL%d has no %s", three ? 3 : 2, name); return 0; }
|
||||
#define GET2(field, n3, n2) GET(field, three ? n3 : n2)
|
||||
GET(InitSubSystem, "SDL_InitSubSystem");
|
||||
GET(SetHint, "SDL_SetHint");
|
||||
GET(GetError, "SDL_GetError");
|
||||
GET(CreateWindow, "SDL_CreateWindow");
|
||||
GET(SetWindowFullscreen, "SDL_SetWindowFullscreen");
|
||||
GET2(SetRelativeMouseMode, "SDL_SetWindowRelativeMouseMode", "SDL_SetRelativeMouseMode");
|
||||
GET(GetDesktopDisplayMode, "SDL_GetDesktopDisplayMode");
|
||||
GET(Vulkan_CreateSurface, "SDL_Vulkan_CreateSurface");
|
||||
GET2(PixelSize, "SDL_GetWindowSizeInPixels", "SDL_Vulkan_GetDrawableSize");
|
||||
GET(GetKeyboardState, "SDL_GetKeyboardState");
|
||||
GET(GetMouseState, "SDL_GetMouseState");
|
||||
GET(GetWindowSize, "SDL_GetWindowSize");
|
||||
GET(WaitEventTimeout, "SDL_WaitEventTimeout");
|
||||
GET(PollEvent, "SDL_PollEvent");
|
||||
GET2(PadOpen, "SDL_OpenGamepad", "SDL_GameControllerOpen");
|
||||
GET2(PadClose, "SDL_CloseGamepad", "SDL_GameControllerClose");
|
||||
GET2(PadConnected, "SDL_GamepadConnected", "SDL_GameControllerGetAttached");
|
||||
GET2(PadsUpdate, "SDL_UpdateGamepads", "SDL_GameControllerUpdate");
|
||||
GET2(PadButton, "SDL_GetGamepadButton", "SDL_GameControllerGetButton");
|
||||
GET2(PadAxis, "SDL_GetGamepadAxis", "SDL_GameControllerGetAxis");
|
||||
GET2(PadName, "SDL_GetGamepadName", "SDL_GameControllerName");
|
||||
GET2(PadRumble, "SDL_RumbleGamepad", "SDL_GameControllerRumble");
|
||||
/* (SDL2 2.0.12 and 2.0.16 on, SDL3 3.2 on: without them every pad keeps the motor rumble) */
|
||||
*(FARPROC *)&f.PadType = GetProcAddress(m, three ? "SDL_GetGamepadType" : "SDL_GameControllerGetType");
|
||||
*(FARPROC *)&f.PadEffect = GetProcAddress(m, three ? "SDL_SendGamepadEffect" : "SDL_GameControllerSendEffect");
|
||||
/* (motion sensors: SDL 2.0.14 on and every SDL3; without them the pads still play, with no gyro) */
|
||||
*(FARPROC *)&f.PadHasSensor = GetProcAddress(m, three ? "SDL_GamepadHasSensor" : "SDL_GameControllerHasSensor");
|
||||
*(FARPROC *)&f.PadSensorEnable = GetProcAddress(m, three ? "SDL_SetGamepadSensorEnabled" : "SDL_GameControllerSetSensorEnabled");
|
||||
*(FARPROC *)&f.PadSensorData = GetProcAddress(m, three ? "SDL_GetGamepadSensorData" : "SDL_GameControllerGetSensorData");
|
||||
if (three) {
|
||||
GET(SetWindowPosition, "SDL_SetWindowPosition");
|
||||
GET(GetPrimaryDisplay, "SDL_GetPrimaryDisplay");
|
||||
GET(OpenAudioDeviceStream, "SDL_OpenAudioDeviceStream");
|
||||
GET(ResumeAudioStreamDevice, "SDL_ResumeAudioStreamDevice");
|
||||
GET(PutAudioStreamData, "SDL_PutAudioStreamData");
|
||||
GET(GetGamepads, "SDL_GetGamepads");
|
||||
GET(GetGamepadID, "SDL_GetGamepadID");
|
||||
GET(Free, "SDL_free");
|
||||
*(FARPROC *)&f.LoadPNG = GetProcAddress(m, "SDL_LoadPNG"); /* (3.4 on: the icon, when there) */
|
||||
*(FARPROC *)&f.SetWindowIcon = GetProcAddress(m, "SDL_SetWindowIcon");
|
||||
*(FARPROC *)&f.DestroySurface = GetProcAddress(m, "SDL_DestroySurface");
|
||||
*(FARPROC *)&f.GetWindowDisplay = GetProcAddress(m, "SDL_GetDisplayForWindow"); /* (the refresh: hos_sdl_refresh_mhz) */
|
||||
*(FARPROC *)&f.GetCurrentDisplayMode = GetProcAddress(m, "SDL_GetCurrentDisplayMode");
|
||||
} else {
|
||||
*(FARPROC *)&f.GetWindowDisplay = GetProcAddress(m, "SDL_GetWindowDisplayIndex"); /* (the refresh: hos_sdl_refresh_mhz) */
|
||||
*(FARPROC *)&f.GetCurrentDisplayMode = GetProcAddress(m, "SDL_GetCurrentDisplayMode");
|
||||
GET(OpenAudioDevice, "SDL_OpenAudioDevice");
|
||||
GET(PauseAudioDevice, "SDL_PauseAudioDevice");
|
||||
GET(NumJoysticks, "SDL_NumJoysticks");
|
||||
GET(IsGameController, "SDL_IsGameController");
|
||||
GET(DeviceInstanceID, "SDL_JoystickGetDeviceInstanceID");
|
||||
GET(GetJoystick, "SDL_GameControllerGetJoystick");
|
||||
GET(JoystickInstanceID, "SDL_JoystickInstanceID");
|
||||
}
|
||||
#undef GET2
|
||||
#undef GET
|
||||
return 1;
|
||||
}
|
||||
int hos_sdl_load(void) {
|
||||
static volatile LONG state; /* 0 not tried, 1 loading, 2 done */
|
||||
if (InterlockedCompareExchange(&state, 1, 0) == 0) {
|
||||
const char *want = getenv("HOS_SDL_VERSION");
|
||||
HMODULE m = want && atoi(want) == 2 ? NULL : load_one("SDL3.dll");
|
||||
if (m && get_all(m, 1)) version = 3;
|
||||
else if ((m = load_one("SDL2.dll")) && get_all(m, 0)) version = 2;
|
||||
hos_log(version ? "sdl: SDL%d" : "sdl: no SDL3 or SDL2 found: no window, sound or SDL controllers", version);
|
||||
InterlockedExchange(&state, 2);
|
||||
}
|
||||
while (state != 2) Sleep(0);
|
||||
return version;
|
||||
}
|
||||
|
||||
int hos_sdl_init(uint32_t subsystems) {
|
||||
if (!hos_sdl_load()) return 0;
|
||||
return version == 3 ? CALL(_Bool (*)(uint32_t), InitSubSystem)(subsystems)
|
||||
: CALL(int (*)(uint32_t), InitSubSystem)(subsystems) == 0;
|
||||
}
|
||||
void hos_sdl_hint(const char *name, const char *value) {
|
||||
if (!hos_sdl_load()) return;
|
||||
if (version == 3) CALL(_Bool (*)(const char *, const char *), SetHint)(name, value);
|
||||
else CALL(int (*)(const char *, const char *), SetHint)(name, value);
|
||||
}
|
||||
void hos_sdl_identity(const char *name, const char *app_id) {
|
||||
if (!hos_sdl_load()) return;
|
||||
if (version == 3) {
|
||||
static void *set;
|
||||
if (!set) {
|
||||
HMODULE m = load_one("SDL3.dll"); /* (the one loaded: the same handle back) */
|
||||
set = m ? (void *)GetProcAddress(m, "SDL_SetAppMetadata") : NULL;
|
||||
}
|
||||
if (set) ((_Bool (*)(const char *, const char *, const char *))set)(name, NULL, app_id);
|
||||
return;
|
||||
}
|
||||
hos_sdl_hint("SDL_APP_NAME", name);
|
||||
#ifndef _WIN32 /* (SDL2 reads the window's class from these, not from hints) */
|
||||
setenv("SDL_VIDEO_WAYLAND_WMCLASS", app_id, 0);
|
||||
setenv("SDL_VIDEO_X11_WMCLASS", app_id, 0);
|
||||
#endif
|
||||
}
|
||||
const char *hos_sdl_error(void) { return version ? CALL(const char *(*)(void), GetError)() : "no SDL"; }
|
||||
|
||||
/* ---- the window ---- */
|
||||
enum { WIN_SHOWN2 = 0x4, WIN_RESIZABLE = 0x20, WIN_HIGH_DENSITY = 0x2000, WIN_VULKAN = 0x10000000, CENTRED = 0x2FFF0000 };
|
||||
void *hos_sdl_window(const char *title, int width, int height) {
|
||||
if (version == 2)
|
||||
return CALL(void *(*)(const char *, int, int, int, int, uint32_t), CreateWindow)(
|
||||
title, CENTRED, CENTRED, width, height, WIN_SHOWN2 | WIN_RESIZABLE | WIN_HIGH_DENSITY | WIN_VULKAN);
|
||||
void *w = CALL(void *(*)(const char *, int, int, uint64_t), CreateWindow)(title, width, height,
|
||||
WIN_RESIZABLE | WIN_HIGH_DENSITY | WIN_VULKAN);
|
||||
if (w) CALL(_Bool (*)(void *, int, int), SetWindowPosition)(w, CENTRED, CENTRED);
|
||||
return w;
|
||||
}
|
||||
void hos_sdl_fullscreen(void *window, int on) {
|
||||
if (version == 3) CALL(_Bool (*)(void *, _Bool), SetWindowFullscreen)(window, on != 0);
|
||||
else CALL(int (*)(void *, uint32_t), SetWindowFullscreen)(window, on ? 0x1001 /* FULLSCREEN_DESKTOP */ : 0);
|
||||
}
|
||||
void hos_sdl_relative_mouse(void *window, int on) {
|
||||
if (version == 3) CALL(_Bool (*)(void *, _Bool), SetRelativeMouseMode)(window, on != 0);
|
||||
else CALL(int (*)(int), SetRelativeMouseMode)(on);
|
||||
}
|
||||
int hos_sdl_desktop_size(int *width, int *height) {
|
||||
if (version == 3) { /* (SDL_DisplayMode: displayID, format, w and h at 8 and 12 in screen units, pixel_density at
|
||||
16: in pixels, as SDL2 gave them) */
|
||||
const uint8_t *m = CALL(const uint8_t *(*)(uint32_t), GetDesktopDisplayMode)(CALL(uint32_t (*)(void), GetPrimaryDisplay)());
|
||||
if (!m) return 0;
|
||||
int w, h;
|
||||
float density;
|
||||
memcpy(&w, m + 8, 4), memcpy(&h, m + 12, 4), memcpy(&density, m + 16, 4);
|
||||
if (!(density > 0)) density = 1;
|
||||
*width = (int)(w * density + 0.5f), *height = (int)(h * density + 0.5f);
|
||||
return 1;
|
||||
}
|
||||
struct { uint32_t format; int w, h, refresh_rate; void *driverdata; } m;
|
||||
if (CALL(int (*)(int, void *), GetDesktopDisplayMode)(0, &m)) return 0;
|
||||
*width = m.w, *height = m.h;
|
||||
return 1;
|
||||
}
|
||||
int hos_sdl_refresh_mhz(void *window) {
|
||||
if (!window || !f.GetWindowDisplay || !f.GetCurrentDisplayMode) return 0;
|
||||
float hz = 0;
|
||||
if (version == 3) { /* (SDL_DisplayMode: refresh_rate, a float, at 20) */
|
||||
const uint32_t id = CALL(uint32_t (*)(void *), GetWindowDisplay)(window);
|
||||
const uint8_t *m = id ? CALL(const uint8_t *(*)(uint32_t), GetCurrentDisplayMode)(id) : NULL;
|
||||
if (m) memcpy(&hz, m + 20, 4);
|
||||
} else {
|
||||
const int index = CALL(int (*)(void *), GetWindowDisplay)(window);
|
||||
struct { uint32_t format; int w, h, refresh_rate; void *driverdata; } m;
|
||||
if (index >= 0 && CALL(int (*)(int, void *), GetCurrentDisplayMode)(index, &m) == 0) hz = (float)m.refresh_rate;
|
||||
}
|
||||
return hz > 1 && hz < 1000 ? (int)(hz * 1000 + 0.5f) : 0;
|
||||
}
|
||||
int hos_sdl_vulkan_surface(void *window, void *instance, void *surface_out) {
|
||||
return version == 3 ? CALL(_Bool (*)(void *, void *, const void *, void *), Vulkan_CreateSurface)(window, instance, NULL, surface_out)
|
||||
: CALL(int (*)(void *, void *, void *), Vulkan_CreateSurface)(window, instance, surface_out) != 0;
|
||||
}
|
||||
void hos_sdl_pixel_size(void *window, int *width, int *height) {
|
||||
if (version == 3) CALL(_Bool (*)(void *, int *, int *), PixelSize)(window, width, height);
|
||||
else CALL(void (*)(void *, int *, int *), PixelSize)(window, width, height);
|
||||
}
|
||||
const uint8_t *hos_sdl_keys(int *count) { /* (SDL3's bool and SDL2's Uint8: a byte each) */
|
||||
return CALL(const uint8_t *(*)(int *), GetKeyboardState)(count);
|
||||
}
|
||||
void hos_sdl_icon(void *window, const char *png) {
|
||||
if (version != 3 || !f.LoadPNG || !f.SetWindowIcon || !f.DestroySurface) return;
|
||||
void *icon = CALL(void *(*)(const char *), LoadPNG)(png);
|
||||
if (!icon) return;
|
||||
CALL(_Bool (*)(void *, void *), SetWindowIcon)(window, icon);
|
||||
CALL(void (*)(void *), DestroySurface)(icon);
|
||||
}
|
||||
uint32_t hos_sdl_mouse_buttons(void) {
|
||||
return version == 3 ? CALL(uint32_t (*)(float *, float *), GetMouseState)(NULL, NULL)
|
||||
: CALL(uint32_t (*)(int *, int *), GetMouseState)(NULL, NULL);
|
||||
}
|
||||
void hos_sdl_window_size(void *window, int *width, int *height) {
|
||||
if (version == 3) CALL(_Bool (*)(void *, int *, int *), GetWindowSize)(window, width, height);
|
||||
else CALL(void (*)(void *, int *, int *), GetWindowSize)(window, width, height);
|
||||
}
|
||||
|
||||
/* ---- events ---- */
|
||||
static void read_event(const uint8_t *raw, HosSdlEvent *e) {
|
||||
uint32_t type;
|
||||
memcpy(&type, raw, 4);
|
||||
memset(e, 0, sizeof *e);
|
||||
int32_t i[2];
|
||||
if (version == 3) {
|
||||
switch (type) {
|
||||
case 0x100: e->type = HOS_SDL_EV_QUIT; break;
|
||||
case 0x207: e->type = HOS_SDL_EV_RESIZED; break; /* (PIXEL_SIZE_CHANGED) */
|
||||
case 0x20d: e->type = HOS_SDL_EV_MOUSE_LEAVE; break;
|
||||
case 0x20e: e->type = HOS_SDL_EV_FOCUS_GAINED; break;
|
||||
case 0x20f: e->type = HOS_SDL_EV_FOCUS_LOST; break;
|
||||
case 0x210: e->type = HOS_SDL_EV_CLOSE; break;
|
||||
case 0x300: /* (SDL_KeyboardEvent: scancode at 24, mod at 32, repeat at 37) */
|
||||
e->type = HOS_SDL_EV_KEY_DOWN;
|
||||
memcpy(i, raw + 24, 4), e->scancode = i[0];
|
||||
memcpy(&e->mod, raw + 32, 2), e->repeat = raw[37];
|
||||
break;
|
||||
case 0x20c: e->type = HOS_SDL_EV_MOUSE_ENTER; break;
|
||||
case 0x400: /* (SDL_MouseMotionEvent: x and y at 28 and 32, xrel and yrel at 36 and 40, floats) */
|
||||
e->type = HOS_SDL_EV_MOUSE_MOTION;
|
||||
memcpy(&e->x, raw + 28, 4), memcpy(&e->y, raw + 32, 4);
|
||||
memcpy(&e->dx, raw + 36, 4), memcpy(&e->dy, raw + 40, 4);
|
||||
break;
|
||||
case 0x401:
|
||||
case 0x402: /* (SDL_MouseButtonEvent: button at 24, x and y at 28 and 32, floats) */
|
||||
e->type = type == 0x401 ? HOS_SDL_EV_MOUSE_DOWN : HOS_SDL_EV_MOUSE_UP;
|
||||
e->button = raw[24];
|
||||
memcpy(&e->x, raw + 28, 4), memcpy(&e->y, raw + 32, 4);
|
||||
break;
|
||||
case 0x403: { /* (SDL_MouseWheelEvent: y at 28, a float; direction at 32, 1 flipped) */
|
||||
uint32_t dir;
|
||||
e->type = HOS_SDL_EV_MOUSE_WHEEL;
|
||||
memcpy(&e->wheel, raw + 28, 4), memcpy(&dir, raw + 32, 4);
|
||||
if (dir == 1) e->wheel = -e->wheel;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
switch (type) {
|
||||
case 0x100: e->type = HOS_SDL_EV_QUIT; break;
|
||||
case 0x200: /* (SDL_WindowEvent: what at 12) */
|
||||
e->type = raw[12] == 6 ? HOS_SDL_EV_RESIZED : raw[12] == 10 ? HOS_SDL_EV_MOUSE_ENTER : raw[12] == 11 ? HOS_SDL_EV_MOUSE_LEAVE
|
||||
: raw[12] == 12 ? HOS_SDL_EV_FOCUS_GAINED : raw[12] == 13 ? HOS_SDL_EV_FOCUS_LOST
|
||||
: raw[12] == 14 ? HOS_SDL_EV_CLOSE : HOS_SDL_EV_OTHER;
|
||||
break;
|
||||
case 0x300: /* (SDL_KeyboardEvent: repeat at 13, scancode at 16, mod at 24) */
|
||||
e->type = HOS_SDL_EV_KEY_DOWN;
|
||||
memcpy(i, raw + 16, 4), e->scancode = i[0];
|
||||
memcpy(&e->mod, raw + 24, 2), e->repeat = raw[13];
|
||||
break;
|
||||
case 0x400: /* (SDL_MouseMotionEvent: x and y at 20 and 24, xrel and yrel at 28 and 32, whole pixels) */
|
||||
e->type = HOS_SDL_EV_MOUSE_MOTION;
|
||||
memcpy(i, raw + 20, 8), e->x = (float)i[0], e->y = (float)i[1];
|
||||
memcpy(i, raw + 28, 8), e->dx = (float)i[0], e->dy = (float)i[1];
|
||||
break;
|
||||
case 0x401:
|
||||
case 0x402: /* (SDL_MouseButtonEvent: button at 16, x and y at 20 and 24, whole pixels) */
|
||||
e->type = type == 0x401 ? HOS_SDL_EV_MOUSE_DOWN : HOS_SDL_EV_MOUSE_UP;
|
||||
e->button = raw[16];
|
||||
memcpy(i, raw + 20, 8), e->x = (float)i[0], e->y = (float)i[1];
|
||||
break;
|
||||
case 0x403: { /* (SDL_MouseWheelEvent: y at 20, whole notches; direction at 24, 1 flipped) */
|
||||
uint32_t dir;
|
||||
e->type = HOS_SDL_EV_MOUSE_WHEEL;
|
||||
memcpy(i, raw + 20, 4), memcpy(&dir, raw + 24, 4);
|
||||
e->wheel = (float)(dir == 1 ? -i[0] : i[0]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
int hos_sdl_wait_event(HosSdlEvent *e, int timeout_ms) {
|
||||
_Alignas(8) uint8_t raw[128];
|
||||
const int got = version == 3 ? CALL(_Bool (*)(void *, int32_t), WaitEventTimeout)(raw, timeout_ms)
|
||||
: CALL(int (*)(void *, int), WaitEventTimeout)(raw, timeout_ms) != 0;
|
||||
if (got) read_event(raw, e);
|
||||
return got;
|
||||
}
|
||||
int hos_sdl_poll_event(HosSdlEvent *e) {
|
||||
_Alignas(8) uint8_t raw[128];
|
||||
const int got = version == 3 ? CALL(_Bool (*)(void *), PollEvent)(raw) : CALL(int (*)(void *), PollEvent)(raw) != 0;
|
||||
if (got) read_event(raw, e);
|
||||
return got;
|
||||
}
|
||||
|
||||
/* ---- sound ---- */
|
||||
typedef struct {
|
||||
void (*pull)(void *user, uint8_t *out, int len);
|
||||
void *user;
|
||||
int frame; /* bytes a sample frame (all channels) */
|
||||
} Pull;
|
||||
static void pull3(void *p, void *stream, int want, int total) { /* (SDL3: a stream asks for want more bytes) */
|
||||
(void)total;
|
||||
const Pull *s = (const Pull *)p;
|
||||
uint8_t buf[4096];
|
||||
/* whole sample frames at a time: SDL3 takes no part of one (4096 bytes is not whole 5.1 frames, 12 bytes each:
|
||||
every piece was refused and 5.1 played silence) */
|
||||
const int most = (int)sizeof buf / s->frame * s->frame;
|
||||
for (int n; want > 0; want -= n) {
|
||||
n = want < most ? want : most;
|
||||
s->pull(s->user, buf, n);
|
||||
CALL(_Bool (*)(void *, const void *, int), PutAudioStreamData)(stream, buf, n);
|
||||
}
|
||||
}
|
||||
static void pull2(void *p, uint8_t *out, int len) { /* (SDL2: a device callback fills its buffer) */
|
||||
const Pull *s = (const Pull *)p;
|
||||
s->pull(s->user, out, len);
|
||||
}
|
||||
int hos_sdl_audio_open(int freq, int channels, int s16, void (*pull)(void *user, uint8_t *out, int len), void *user) {
|
||||
if (!hos_sdl_load()) return 0;
|
||||
const uint16_t format = s16 ? 0x8010 /* S16LE */ : 0x8120 /* F32LE */; /* (both's numbers) */
|
||||
const char *env_samples = getenv("SDL_AUDIO_DEVICE_SAMPLE_FRAMES");
|
||||
if (version == 3 && !env_samples) hos_sdl_hint("SDL_AUDIO_DEVICE_SAMPLE_FRAMES", "480"); /* (SDL2's device buffer below) */
|
||||
if (!hos_sdl_init(HOS_SDL_AUDIO)) return 0;
|
||||
Pull *p = (Pull *)calloc(1, sizeof *p);
|
||||
p->pull = pull, p->user = user, p->frame = channels * (s16 ? 2 : 4);
|
||||
if (version == 3) {
|
||||
const struct { uint32_t format; int channels, freq; } spec = {format, channels, freq};
|
||||
void *stream = CALL(void *(*)(uint32_t, const void *, void (*)(void *, void *, int, int), void *), OpenAudioDeviceStream)(
|
||||
0xFFFFFFFFu /* the default output */, &spec, pull3, p);
|
||||
if (stream && CALL(_Bool (*)(void *), ResumeAudioStreamDevice)(stream)) return 1;
|
||||
free(p);
|
||||
return 0;
|
||||
}
|
||||
struct {
|
||||
int freq;
|
||||
uint16_t format;
|
||||
uint8_t channels, silence;
|
||||
uint16_t samples, padding;
|
||||
uint32_t size;
|
||||
void (*callback)(void *, uint8_t *, int);
|
||||
void *userdata;
|
||||
} want, have;
|
||||
memset(&want, 0, sizeof want);
|
||||
want.freq = freq, want.format = format, want.channels = (uint8_t)channels;
|
||||
want.samples = (uint16_t)(env_samples && atoi(env_samples) > 0 ? atoi(env_samples) : 512); /* (SDL2 asks for a power of two) */
|
||||
want.callback = pull2, want.userdata = p;
|
||||
/* (no changes allowed: SDL converts to what the device wants) */
|
||||
const uint32_t dev = CALL(uint32_t (*)(const char *, int, const void *, void *, int), OpenAudioDevice)(NULL, 0, &want, &have, 0);
|
||||
if (!dev) {
|
||||
free(p);
|
||||
return 0;
|
||||
}
|
||||
CALL(void (*)(uint32_t, int), PauseAudioDevice)(dev, 0);
|
||||
return 1;
|
||||
}
|
||||
/* SDL3's format of the default device; SDL2's default audio info (2.24 on: the bundled 2.32 has it). Looked up here,
|
||||
not at load: an SDL without it still plays, in stereo. */
|
||||
int hos_sdl_audio_channels(void) {
|
||||
if (!hos_sdl_load() || !hos_sdl_init(HOS_SDL_AUDIO)) return 2;
|
||||
HMODULE m = load_one(version == 3 ? "SDL3.dll" : "SDL2.dll"); /* (the one loaded: the same handle back) */
|
||||
if (!m) return 2;
|
||||
int n = 0;
|
||||
if (version == 3) {
|
||||
void *get = (void *)GetProcAddress(m, "SDL_GetAudioDeviceFormat");
|
||||
struct { uint32_t format; int channels, freq; } spec = {0, 0, 0};
|
||||
int frames = 0;
|
||||
if (get && ((_Bool (*)(uint32_t, void *, int *))get)(0xFFFFFFFFu /* the default output */, &spec, &frames))
|
||||
n = spec.channels;
|
||||
} else {
|
||||
void *get = (void *)GetProcAddress(m, "SDL_GetDefaultAudioInfo"), *release = (void *)GetProcAddress(m, "SDL_free");
|
||||
struct {
|
||||
int freq;
|
||||
uint16_t format;
|
||||
uint8_t channels, silence;
|
||||
uint16_t samples, padding;
|
||||
uint32_t size;
|
||||
void *callback, *userdata;
|
||||
} spec;
|
||||
memset(&spec, 0, sizeof spec);
|
||||
char *name = NULL;
|
||||
if (get && ((int (*)(char **, void *, int))get)(&name, &spec, 0) == 0) n = spec.channels;
|
||||
if (name && release) ((void (*)(void *))release)(name);
|
||||
}
|
||||
return n > 0 ? n : 2;
|
||||
}
|
||||
|
||||
/* ---- (hookshot) microphones: SDL3's recording devices, or SDL2's capture devices (the Linux AppImage carries SDL2): a
|
||||
stream each opened, in the format asked for, read as the game asks ---- */
|
||||
static struct {
|
||||
void *GetDevices, *DeviceName, *Available, *GetData, *Clear, *Destroy; /* (SDL3) */
|
||||
void *NumDevices, *DeviceName2, *CloseDevice, *LockDevice, *UnlockDevice; /* (SDL2) */
|
||||
int tried, ok;
|
||||
} rec;
|
||||
#define REC_GET(field, name) (*(FARPROC *)&rec.field = GetProcAddress(m, name))
|
||||
static int rec_ready(void) {
|
||||
if (!hos_sdl_load()) return 0;
|
||||
if (!rec.tried) {
|
||||
rec.tried = 1;
|
||||
HMODULE m = load_one(version == 3 ? "SDL3.dll" : "SDL2.dll"); /* (the one loaded: the same handle back) */
|
||||
if (m && version == 3) {
|
||||
REC_GET(GetDevices, "SDL_GetAudioRecordingDevices"), REC_GET(DeviceName, "SDL_GetAudioDeviceName");
|
||||
REC_GET(Available, "SDL_GetAudioStreamAvailable"), REC_GET(GetData, "SDL_GetAudioStreamData");
|
||||
REC_GET(Clear, "SDL_ClearAudioStream"), REC_GET(Destroy, "SDL_DestroyAudioStream");
|
||||
rec.ok = rec.GetDevices && rec.DeviceName && rec.Available && rec.GetData && rec.Clear && rec.Destroy;
|
||||
} else if (m) {
|
||||
REC_GET(NumDevices, "SDL_GetNumAudioDevices"), REC_GET(DeviceName2, "SDL_GetAudioDeviceName");
|
||||
REC_GET(CloseDevice, "SDL_CloseAudioDevice"), REC_GET(LockDevice, "SDL_LockAudioDevice");
|
||||
REC_GET(UnlockDevice, "SDL_UnlockAudioDevice");
|
||||
rec.ok = rec.NumDevices && rec.DeviceName2 && rec.CloseDevice && rec.LockDevice && rec.UnlockDevice;
|
||||
}
|
||||
if (!rec.ok) hos_log("sdl: no recording functions: no microphone");
|
||||
}
|
||||
return rec.ok && hos_sdl_init(HOS_SDL_AUDIO);
|
||||
}
|
||||
#undef REC_GET
|
||||
/* SDL2: the capture callback fills a ring of about a second, the oldest dropped when full; read under the device's lock */
|
||||
typedef struct {
|
||||
uint32_t dev;
|
||||
uint8_t *ring;
|
||||
int cap, start, len;
|
||||
} Mic2;
|
||||
static void mic2_push(void *user, uint8_t *in, int n) { /* (SDL2's audio thread, the device locked) */
|
||||
Mic2 *m = (Mic2 *)user;
|
||||
if (n > m->cap) in += n - m->cap, n = m->cap;
|
||||
const int drop = m->len + n - m->cap;
|
||||
if (drop > 0) m->start = (m->start + drop) % m->cap, m->len -= drop;
|
||||
const int at = (m->start + m->len) % m->cap, first = n < m->cap - at ? n : m->cap - at;
|
||||
memcpy(m->ring + at, in, (size_t)first);
|
||||
memcpy(m->ring, in + first, (size_t)(n - first));
|
||||
m->len += n;
|
||||
}
|
||||
static void mic2_lock(Mic2 *m, int on) { ((void (*)(uint32_t))(on ? rec.LockDevice : rec.UnlockDevice))(m->dev); }
|
||||
|
||||
int hos_sdl_mic_list(uint32_t *ids, char (*names)[128], int max) {
|
||||
if (!rec_ready()) return 0;
|
||||
int n = 0;
|
||||
if (version == 2) { /* (SDL2 names them by index: the id is the index + 1, 0 the default) */
|
||||
const int count = ((int (*)(int))rec.NumDevices)(1);
|
||||
for (int i = 0; i < count && n < max; i++, n++) {
|
||||
const char *name = ((const char *(*)(int, int))rec.DeviceName2)(i, 1);
|
||||
ids[n] = (uint32_t)i + 1;
|
||||
snprintf(names[n], 128, "%s", name ? name : "Microphone");
|
||||
}
|
||||
return n;
|
||||
}
|
||||
int count = 0;
|
||||
uint32_t *all = ((uint32_t *(*)(int *))rec.GetDevices)(&count);
|
||||
for (int i = 0; all && i < count && n < max; i++, n++) {
|
||||
const char *name = ((const char *(*)(uint32_t))rec.DeviceName)(all[i]);
|
||||
ids[n] = all[i];
|
||||
snprintf(names[n], 128, "%s", name ? name : "Microphone");
|
||||
}
|
||||
if (all) CALL(void (*)(void *), Free)(all);
|
||||
return n;
|
||||
}
|
||||
void *hos_sdl_mic_open(uint32_t id, int freq, int channels, uint16_t sdl_format) {
|
||||
if (!rec_ready()) return NULL;
|
||||
if (version == 2) {
|
||||
const int bytes = (sdl_format & 0xFF) / 8 * channels;
|
||||
Mic2 *m = (Mic2 *)calloc(1, sizeof *m);
|
||||
if (!m || !(m->ring = (uint8_t *)malloc((size_t)freq * bytes))) {
|
||||
free(m);
|
||||
return NULL;
|
||||
}
|
||||
m->cap = freq * bytes;
|
||||
struct {
|
||||
int freq;
|
||||
uint16_t format;
|
||||
uint8_t channels, silence;
|
||||
uint16_t samples, padding;
|
||||
uint32_t size;
|
||||
void (*callback)(void *, uint8_t *, int);
|
||||
void *userdata;
|
||||
} want, have;
|
||||
memset(&want, 0, sizeof want);
|
||||
want.freq = freq, want.format = sdl_format, want.channels = (uint8_t)channels, want.samples = 512;
|
||||
want.callback = mic2_push, want.userdata = m;
|
||||
/* (no changes allowed: SDL converts the device's sound to this. SDL2's id is a place in its list, so the caller takes
|
||||
it from a list made just before (host/nn_audio_in.c find_device). SDL2 opens a device by its name: of two with one
|
||||
name it takes the first, whichever was chosen; telling them apart is SDL3's) */
|
||||
const char *name = id ? ((const char *(*)(int, int))rec.DeviceName2)((int)id - 1, 1) : NULL;
|
||||
m->dev = CALL(uint32_t (*)(const char *, int, const void *, void *, int), OpenAudioDevice)(name, 1, &want, &have, 0);
|
||||
if (!m->dev) { /* (the caller says so, once: hos_sdl_error) */
|
||||
free(m->ring), free(m);
|
||||
return NULL;
|
||||
}
|
||||
CALL(void (*)(uint32_t, int), PauseAudioDevice)(m->dev, 0);
|
||||
return m;
|
||||
}
|
||||
const struct { uint32_t format; int channels, freq; } spec = {sdl_format, channels, freq};
|
||||
void *s = CALL(void *(*)(uint32_t, const void *, void *, void *), OpenAudioDeviceStream)(
|
||||
id ? id : 0xFFFFFFFEu /* SDL_AUDIO_DEVICE_DEFAULT_RECORDING */, &spec, NULL, NULL);
|
||||
if (s && !CALL(_Bool (*)(void *), ResumeAudioStreamDevice)(s)) { /* (one that does not start did not open) */
|
||||
((void (*)(void *))rec.Destroy)(s);
|
||||
s = NULL;
|
||||
}
|
||||
return s; /* (none: the caller says so, once: hos_sdl_error) */
|
||||
}
|
||||
int hos_sdl_mic_available(void *mic) {
|
||||
if (!mic || !rec.ok) return 0;
|
||||
if (version == 2) {
|
||||
Mic2 *m = (Mic2 *)mic;
|
||||
mic2_lock(m, 1);
|
||||
const int n = m->len;
|
||||
mic2_lock(m, 0);
|
||||
return n;
|
||||
}
|
||||
return ((int (*)(void *))rec.Available)(mic);
|
||||
}
|
||||
int hos_sdl_mic_read(void *mic, void *dst, int bytes) {
|
||||
if (!mic || !rec.ok || bytes <= 0) return 0;
|
||||
if (version == 2) {
|
||||
Mic2 *m = (Mic2 *)mic;
|
||||
mic2_lock(m, 1);
|
||||
const int n = bytes < m->len ? bytes : m->len, first = n < m->cap - m->start ? n : m->cap - m->start;
|
||||
memcpy(dst, m->ring + m->start, (size_t)first);
|
||||
memcpy((uint8_t *)dst + first, m->ring, (size_t)(n - first));
|
||||
m->start = (m->start + n) % m->cap, m->len -= n;
|
||||
mic2_lock(m, 0);
|
||||
return n;
|
||||
}
|
||||
const int n = ((int (*)(void *, void *, int))rec.GetData)(mic, dst, bytes);
|
||||
return n > 0 ? n : 0;
|
||||
}
|
||||
void hos_sdl_mic_clear(void *mic) {
|
||||
if (!mic || !rec.ok) return;
|
||||
if (version == 2) {
|
||||
Mic2 *m = (Mic2 *)mic;
|
||||
mic2_lock(m, 1);
|
||||
m->start = m->len = 0;
|
||||
mic2_lock(m, 0);
|
||||
return;
|
||||
}
|
||||
((_Bool (*)(void *))rec.Clear)(mic);
|
||||
}
|
||||
void hos_sdl_mic_close(void *mic) {
|
||||
if (!mic || !rec.ok) return;
|
||||
if (version == 2) {
|
||||
Mic2 *m = (Mic2 *)mic;
|
||||
((void (*)(uint32_t))rec.CloseDevice)(m->dev); /* (the callback has stopped when this returns) */
|
||||
free(m->ring), free(m);
|
||||
return;
|
||||
}
|
||||
((void (*)(void *))rec.Destroy)(mic);
|
||||
}
|
||||
|
||||
/* ---- controllers ---- */
|
||||
int hos_sdl_pads_list(int32_t *ids, int *opens, int max) { /* (SDL3 opens by id; SDL2 by device index) */
|
||||
int n = 0;
|
||||
if (version == 3) {
|
||||
int count = 0;
|
||||
uint32_t *got = CALL(uint32_t *(*)(int *), GetGamepads)(&count);
|
||||
for (int i = 0; got && i < count && n < max; i++) ids[n] = (int32_t)got[i], opens[n] = (int)got[i], n++;
|
||||
if (got) CALL(void (*)(void *), Free)(got);
|
||||
return n;
|
||||
}
|
||||
const int nj = CALL(int (*)(void), NumJoysticks)();
|
||||
for (int j = 0; j < nj && n < max; j++)
|
||||
if (CALL(int (*)(int), IsGameController)(j)) ids[n] = CALL(int32_t (*)(int), DeviceInstanceID)(j), opens[n] = j, n++;
|
||||
return n;
|
||||
}
|
||||
void *hos_sdl_pad_open(int what) {
|
||||
return version == 3 ? CALL(void *(*)(uint32_t), PadOpen)((uint32_t)what) : CALL(void *(*)(int), PadOpen)(what);
|
||||
}
|
||||
void hos_sdl_pad_close(void *pad) { CALL(void (*)(void *), PadClose)(pad); }
|
||||
int hos_sdl_pad_connected(void *pad) {
|
||||
return version == 3 ? CALL(_Bool (*)(void *), PadConnected)(pad) : CALL(int (*)(void *), PadConnected)(pad) != 0;
|
||||
}
|
||||
void hos_sdl_pads_update(void) { CALL(void (*)(void), PadsUpdate)(); }
|
||||
int hos_sdl_pad_button(void *pad, int button) {
|
||||
return version == 3 ? CALL(_Bool (*)(void *, int), PadButton)(pad, button)
|
||||
: CALL(uint8_t (*)(void *, int), PadButton)(pad, button) != 0;
|
||||
}
|
||||
int16_t hos_sdl_pad_axis(void *pad, int axis) { return CALL(int16_t (*)(void *, int), PadAxis)(pad, axis); }
|
||||
const char *hos_sdl_pad_name(void *pad) {
|
||||
const char *n = CALL(const char *(*)(void *), PadName)(pad);
|
||||
return n ? n : "?";
|
||||
}
|
||||
int32_t hos_sdl_pad_id(void *pad) {
|
||||
return version == 3 ? (int32_t)CALL(uint32_t (*)(void *), GetGamepadID)(pad)
|
||||
: CALL(int32_t (*)(void *), JoystickInstanceID)(CALL(void *(*)(void *), GetJoystick)(pad));
|
||||
}
|
||||
void hos_sdl_pad_rumble(void *pad, uint16_t low, uint16_t high, uint32_t ms) {
|
||||
if (version == 3) CALL(_Bool (*)(void *, uint16_t, uint16_t, uint32_t), PadRumble)(pad, low, high, ms);
|
||||
else CALL(int (*)(void *, uint16_t, uint16_t, uint32_t), PadRumble)(pad, low, high, ms);
|
||||
}
|
||||
int hos_sdl_pad_type(void *pad) { return f.PadType ? CALL(int (*)(void *), PadType)(pad) : 0; }
|
||||
int hos_sdl_pad_has_effect(void) { return f.PadEffect != NULL; }
|
||||
int hos_sdl_pad_effect(void *pad, const void *data, int size) {
|
||||
if (!f.PadEffect) return 0;
|
||||
if (version == 3) return CALL(_Bool (*)(void *, const void *, int), PadEffect)(pad, data, size);
|
||||
return CALL(int (*)(void *, const void *, int), PadEffect)(pad, data, size) == 0;
|
||||
}
|
||||
/* (motion) type: HOS_SDL_SENSOR_ACCEL or _GYRO, the same numbers in both */
|
||||
int hos_sdl_pad_has_sensor(void *pad, int type) {
|
||||
if (!f.PadHasSensor || !f.PadSensorEnable || !f.PadSensorData) return 0;
|
||||
return version == 3 ? CALL(_Bool (*)(void *, int), PadHasSensor)(pad, type)
|
||||
: CALL(int (*)(void *, int), PadHasSensor)(pad, type) != 0;
|
||||
}
|
||||
int hos_sdl_pad_sensor_enable(void *pad, int type, int on) {
|
||||
if (!f.PadSensorEnable) return 0;
|
||||
return version == 3 ? CALL(_Bool (*)(void *, int, _Bool), PadSensorEnable)(pad, type, on != 0)
|
||||
: CALL(int (*)(void *, int, int), PadSensorEnable)(pad, type, on != 0) == 0;
|
||||
}
|
||||
int hos_sdl_pad_sensor(void *pad, int type, float *data, int n) {
|
||||
if (!f.PadSensorData) return 0;
|
||||
return version == 3 ? CALL(_Bool (*)(void *, int, float *, int), PadSensorData)(pad, type, data, n)
|
||||
: CALL(int (*)(void *, int, float *, int), PadSensorData)(pad, type, data, n) == 0;
|
||||
}
|
||||
#undef CALL
|
||||
86
host/hos_sdl.h
Normal file
86
host/hos_sdl.h
Normal file
@@ -0,0 +1,86 @@
|
||||
/* SDL3 or SDL2 behind one set of calls (host/hos_sdl.c): the window (host/posix/display_sdl.c), the sound
|
||||
(host/posix/win32_posix.c's waveOut) and the controllers (host/pad_sdl.c) call these, whichever SDL loaded. One
|
||||
library for the whole process, loaded at run time: SDL3 beside the executable, else the system's, else SDL2 the same
|
||||
way (SDL3.dll and SDL2.dll; on Linux libSDL3.so.0 and libSDL2-2.0.so.0). HOS_SDL_VERSION=2 takes SDL2 even with an
|
||||
SDL3 there. */
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
|
||||
int hos_sdl_load(void); /* 3 or 2, the SDL loaded (the first call loads it); 0 when there is none */
|
||||
|
||||
enum { HOS_SDL_AUDIO = 0x10, HOS_SDL_VIDEO = 0x20, HOS_SDL_GAMEPAD = 0x2000, HOS_SDL_EVENTS = 0x4000 }; /* (both's) */
|
||||
int hos_sdl_init(uint32_t subsystems); /* 1 when started */
|
||||
void hos_sdl_hint(const char *name, const char *value); /* (a hint the loaded SDL does not know is nothing) */
|
||||
const char *hos_sdl_error(void);
|
||||
/* the app's name and id, before the window and the sound start: Wayland's app_id and X11's WM_CLASS (what the desktop
|
||||
matches the window to its menu entry by, for its icon and name), the name the sound mixer shows */
|
||||
void hos_sdl_identity(const char *name, const char *app_id);
|
||||
|
||||
/* ---- the window: centred, resizable, at the display's pixel density, for Vulkan ---- */
|
||||
void *hos_sdl_window(const char *title, int width, int height);
|
||||
void hos_sdl_fullscreen(void *window, int on); /* (the desktop's mode, borderless) */
|
||||
void hos_sdl_relative_mouse(void *window, int on);
|
||||
int hos_sdl_desktop_size(int *width, int *height);
|
||||
int hos_sdl_refresh_mhz(void *window); /* the refresh rate of the window's display in mHz, 0 when not known (the main thread) */
|
||||
int hos_sdl_vulkan_surface(void *window, void *instance, void *surface_out); /* (VkInstance, VkSurfaceKHR *): 1 if made */
|
||||
void hos_sdl_pixel_size(void *window, int *width, int *height);
|
||||
const uint8_t *hos_sdl_keys(int *count); /* the keyboard by scancode (USB HID usage), 1 a key down */
|
||||
uint32_t hos_sdl_mouse_buttons(void); /* 1 left, 2 middle, 4 right */
|
||||
void hos_sdl_window_size(void *window, int *width, int *height); /* (in the units of the mouse's position, not pixels) */
|
||||
void hos_sdl_icon(void *window, const char *png); /* (SDL 3.4's PNG loader: nothing on SDL2 or an older SDL3) */
|
||||
|
||||
/* ---- events, as the window's loop wants them ---- */
|
||||
enum {
|
||||
HOS_SDL_EV_OTHER, HOS_SDL_EV_QUIT, HOS_SDL_EV_CLOSE, HOS_SDL_EV_RESIZED, HOS_SDL_EV_FOCUS_GAINED,
|
||||
HOS_SDL_EV_FOCUS_LOST, HOS_SDL_EV_MOUSE_LEAVE, HOS_SDL_EV_KEY_DOWN, HOS_SDL_EV_MOUSE_DOWN, HOS_SDL_EV_MOUSE_MOTION,
|
||||
HOS_SDL_EV_MOUSE_UP, HOS_SDL_EV_MOUSE_WHEEL, HOS_SDL_EV_MOUSE_ENTER
|
||||
};
|
||||
typedef struct {
|
||||
int type;
|
||||
int scancode, repeat; /* (key down) */
|
||||
uint16_t mod; /* (key down: 0x300 an Alt key) */
|
||||
float dx, dy; /* (mouse motion, relative) */
|
||||
float x, y; /* (mouse motion, down and up: the cursor in the window, hos_sdl_window_size's units) */
|
||||
int button; /* (mouse down and up: 1 left, 2 middle, 3 right, as SDL numbers them) */
|
||||
float wheel; /* (mouse wheel: notches, up or away from the player positive) */
|
||||
} HosSdlEvent;
|
||||
int hos_sdl_wait_event(HosSdlEvent *e, int timeout_ms); /* 1 when there was one */
|
||||
int hos_sdl_poll_event(HosSdlEvent *e);
|
||||
|
||||
/* ---- sound: the default output, pull() asked for len more bytes as it runs low (s16: 16-bit samples, else float) ---- */
|
||||
int hos_sdl_audio_open(int freq, int channels, int s16, void (*pull)(void *user, uint8_t *out, int len), void *user);
|
||||
int hos_sdl_audio_channels(void); /* the default output's channels (6 for 5.1); 2 when SDL cannot say */
|
||||
|
||||
/* ---- (hookshot) microphones: SDL3's recording devices or SDL2's capture devices, for the game's input streams
|
||||
(host/nn_audio_in.c). The device's sound comes out converted to the format asked for (SDL resamples and mixes the
|
||||
channels down) ---- */
|
||||
int hos_sdl_mic_list(uint32_t *ids, char (*names)[128], int max); /* the recording devices now: their count */
|
||||
void *hos_sdl_mic_open(uint32_t id, int freq, int channels, uint16_t sdl_format); /* id 0: the system's default; NULL
|
||||
(nothing logged): hos_sdl_error */
|
||||
int hos_sdl_mic_available(void *mic); /* bytes ready */
|
||||
int hos_sdl_mic_read(void *mic, void *dst, int bytes); /* bytes read */
|
||||
void hos_sdl_mic_clear(void *mic);
|
||||
void hos_sdl_mic_close(void *mic);
|
||||
|
||||
/* ---- controllers (the button and axis numbers are both's: SDL3's SOUTH, EAST, WEST, NORTH are SDL2's A, B, X, Y) ---- */
|
||||
int hos_sdl_pads_list(int32_t *ids, int *opens, int max); /* the ids of those SDL knows, and what opens each */
|
||||
void *hos_sdl_pad_open(int what);
|
||||
void hos_sdl_pad_close(void *pad);
|
||||
int hos_sdl_pad_connected(void *pad);
|
||||
void hos_sdl_pads_update(void);
|
||||
int hos_sdl_pad_button(void *pad, int button);
|
||||
int16_t hos_sdl_pad_axis(void *pad, int axis);
|
||||
const char *hos_sdl_pad_name(void *pad);
|
||||
int32_t hos_sdl_pad_id(void *pad);
|
||||
void hos_sdl_pad_rumble(void *pad, uint16_t low, uint16_t high, uint32_t ms);
|
||||
/* (HD rumble, host/pad_sdl.c) the pad's SDL_GetGamepadType / SDL_GameControllerGetType, in the loaded SDL's numbers (0
|
||||
unknown, or no such call); whether the SDL has the effect call; a raw effect sent (SDL_SendGamepadEffect /
|
||||
SDL_GameControllerSendEffect): 1 when SDL took it */
|
||||
int hos_sdl_pad_type(void *pad);
|
||||
int hos_sdl_pad_has_effect(void);
|
||||
int hos_sdl_pad_effect(void *pad, const void *data, int size);
|
||||
/* motion sensors (SDL_SENSOR_ACCEL m/s^2, SDL_SENSOR_GYRO rad/s, three values each): 0 when the pad or the SDL has none */
|
||||
enum { HOS_SDL_SENSOR_ACCEL = 1, HOS_SDL_SENSOR_GYRO = 2 };
|
||||
int hos_sdl_pad_has_sensor(void *pad, int type);
|
||||
int hos_sdl_pad_sensor_enable(void *pad, int type, int on); /* 1 when done */
|
||||
int hos_sdl_pad_sensor(void *pad, int type, float *data, int n); /* 1 when read */
|
||||
186
host/hos_setjmp.c
Normal file
186
host/hos_setjmp.c
Normal file
@@ -0,0 +1,186 @@
|
||||
/* (hookshot) setjmp / longjmp in lifted code.
|
||||
|
||||
The guest's __setjmp and longjmp (sdk+0xaec40 / +0xaed50, musl's with pointer-auth hashes) run as lifted code and
|
||||
save and restore the guest registers themselves. What lifting breaks is longjmp's last instruction, BR x30 to the
|
||||
setjmp call's return address: in lifted code that address is the middle of a C function, not an entry, so the
|
||||
indirect jump trapped (OoT's UpdateTextBoxTextureThread, at 0x81681690). And the function that called setjmp may
|
||||
have returned by then: 0x81681670 is a wrapper that returns setjmp's result, which works on the console because
|
||||
its stack frame is still intact when longjmp comes back to it.
|
||||
|
||||
So the lifter (a64_lift.py find_setjmp_owners) makes each setjmp return address an entry, and wraps every call of
|
||||
a function that calls setjmp (its "owner") as
|
||||
|
||||
{ void **sj = recomp_sj_push(c, r0..r3); if (recomp_sj_setjmp(sj) == 0) f_owner(c);
|
||||
else a64_icall(c, recomp_sj_target(sj)); recomp_sj_pop(sj); }
|
||||
|
||||
in the caller's own frame, which is alive while the owner runs and after it returns. A jump that misses
|
||||
(a64_call_miss) to one of a pushed slot's return addresses is a longjmp: the guest registers are restored already
|
||||
(x0 the value, SP and x30 as setjmp saw them), so the newest such slot is taken (slots above it dropped), and
|
||||
recomp_sj_longjmp brings the host back to that caller, which runs the owner's code from the return address: what
|
||||
the owner would have done, ending in its own return to the caller.
|
||||
|
||||
(recomp_sj_setjmp / recomp_sj_longjmp are this file's own, in assembly: every Win64 callee-saved register, xmm6-15
|
||||
with them, and the stack pointer and return address. clang's __builtin_setjmp, which this used first, saves the
|
||||
frame address, which on Win64 sits 128 bytes below the frame pointer clang addresses the frame's spill slots with,
|
||||
and its longjmp set rbp to it: the caller's reloads of c and the slot read garbage, and the text box thread
|
||||
called a stack address after its first longjmp.) */
|
||||
#include "hos.h"
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <windows.h>
|
||||
#include <string.h>
|
||||
|
||||
#define DEPTH 256
|
||||
typedef struct { uint64_t rets[4], target; void *buf[32]; } SjSlot; /* (buf: recomp_sj_setjmp's 248 bytes) */
|
||||
typedef struct { SjSlot slot[DEPTH]; int depth, overflow; } SjStack;
|
||||
static _Thread_local SjStack *stack;
|
||||
|
||||
#ifdef _WIN32
|
||||
/* buf: rbx rbp rdi rsi r12 r13 r14 r15 at 0-56, rsp (after the return) at 64, the return address at 72, xmm6-15 at
|
||||
80-224, mxcsr at 240 and the x87 control word at 244 */
|
||||
__attribute__((naked, returns_twice)) int recomp_sj_setjmp(void **buf) {
|
||||
__asm__ volatile(
|
||||
"movq %rbx, 0(%rcx)\n\t"
|
||||
"movq %rbp, 8(%rcx)\n\t"
|
||||
"movq %rdi, 16(%rcx)\n\t"
|
||||
"movq %rsi, 24(%rcx)\n\t"
|
||||
"movq %r12, 32(%rcx)\n\t"
|
||||
"movq %r13, 40(%rcx)\n\t"
|
||||
"movq %r14, 48(%rcx)\n\t"
|
||||
"movq %r15, 56(%rcx)\n\t"
|
||||
"leaq 8(%rsp), %rdx\n\t"
|
||||
"movq %rdx, 64(%rcx)\n\t"
|
||||
"movq (%rsp), %rdx\n\t"
|
||||
"movq %rdx, 72(%rcx)\n\t"
|
||||
"movdqu %xmm6, 80(%rcx)\n\t"
|
||||
"movdqu %xmm7, 96(%rcx)\n\t"
|
||||
"movdqu %xmm8, 112(%rcx)\n\t"
|
||||
"movdqu %xmm9, 128(%rcx)\n\t"
|
||||
"movdqu %xmm10, 144(%rcx)\n\t"
|
||||
"movdqu %xmm11, 160(%rcx)\n\t"
|
||||
"movdqu %xmm12, 176(%rcx)\n\t"
|
||||
"movdqu %xmm13, 192(%rcx)\n\t"
|
||||
"movdqu %xmm14, 208(%rcx)\n\t"
|
||||
"movdqu %xmm15, 224(%rcx)\n\t"
|
||||
"stmxcsr 240(%rcx)\n\t"
|
||||
"fnstcw 244(%rcx)\n\t"
|
||||
"xorl %eax, %eax\n\t"
|
||||
"ret\n\t");
|
||||
}
|
||||
|
||||
__attribute__((naked, noreturn)) static void recomp_sj_longjmp(void **buf, int value) {
|
||||
__asm__ volatile(
|
||||
"movq 0(%rcx), %rbx\n\t"
|
||||
"movq 8(%rcx), %rbp\n\t"
|
||||
"movq 16(%rcx), %rdi\n\t"
|
||||
"movq 24(%rcx), %rsi\n\t"
|
||||
"movq 32(%rcx), %r12\n\t"
|
||||
"movq 40(%rcx), %r13\n\t"
|
||||
"movq 48(%rcx), %r14\n\t"
|
||||
"movq 56(%rcx), %r15\n\t"
|
||||
"movdqu 80(%rcx), %xmm6\n\t"
|
||||
"movdqu 96(%rcx), %xmm7\n\t"
|
||||
"movdqu 112(%rcx), %xmm8\n\t"
|
||||
"movdqu 128(%rcx), %xmm9\n\t"
|
||||
"movdqu 144(%rcx), %xmm10\n\t"
|
||||
"movdqu 160(%rcx), %xmm11\n\t"
|
||||
"movdqu 176(%rcx), %xmm12\n\t"
|
||||
"movdqu 192(%rcx), %xmm13\n\t"
|
||||
"movdqu 208(%rcx), %xmm14\n\t"
|
||||
"movdqu 224(%rcx), %xmm15\n\t"
|
||||
"ldmxcsr 240(%rcx)\n\t"
|
||||
"fldcw 244(%rcx)\n\t"
|
||||
"movl %edx, %eax\n\t"
|
||||
"testl %eax, %eax\n\t"
|
||||
"jnz 1f\n\t"
|
||||
"incl %eax\n\t"
|
||||
"1:\n\t"
|
||||
"movq 64(%rcx), %rsp\n\t"
|
||||
"jmpq *72(%rcx)\n\t");
|
||||
}
|
||||
|
||||
#else
|
||||
/* (linux) the System V ABI's: the buffer as above, its callee-saved registers only (rbx rbp r12-r15: rdi, rsi and the
|
||||
xmm registers are the caller's to keep there), buf in rdi and the value in esi */
|
||||
__attribute__((naked, returns_twice)) int recomp_sj_setjmp(void **buf) {
|
||||
__asm__ volatile(
|
||||
"movq %rbx, 0(%rdi)\n\t"
|
||||
"movq %rbp, 8(%rdi)\n\t"
|
||||
"movq %r12, 32(%rdi)\n\t"
|
||||
"movq %r13, 40(%rdi)\n\t"
|
||||
"movq %r14, 48(%rdi)\n\t"
|
||||
"movq %r15, 56(%rdi)\n\t"
|
||||
"leaq 8(%rsp), %rdx\n\t"
|
||||
"movq %rdx, 64(%rdi)\n\t"
|
||||
"movq (%rsp), %rdx\n\t"
|
||||
"movq %rdx, 72(%rdi)\n\t"
|
||||
"stmxcsr 240(%rdi)\n\t"
|
||||
"fnstcw 244(%rdi)\n\t"
|
||||
"xorl %eax, %eax\n\t"
|
||||
"ret\n\t");
|
||||
}
|
||||
|
||||
__attribute__((naked, noreturn)) static void recomp_sj_longjmp(void **buf, int value) {
|
||||
__asm__ volatile(
|
||||
"movq 0(%rdi), %rbx\n\t"
|
||||
"movq 8(%rdi), %rbp\n\t"
|
||||
"movq 32(%rdi), %r12\n\t"
|
||||
"movq 40(%rdi), %r13\n\t"
|
||||
"movq 48(%rdi), %r14\n\t"
|
||||
"movq 56(%rdi), %r15\n\t"
|
||||
"ldmxcsr 240(%rdi)\n\t"
|
||||
"fldcw 244(%rdi)\n\t"
|
||||
"movl %esi, %eax\n\t"
|
||||
"testl %eax, %eax\n\t"
|
||||
"jnz 1f\n\t"
|
||||
"incl %eax\n\t"
|
||||
"1:\n\t"
|
||||
"movq 64(%rdi), %rsp\n\t"
|
||||
"jmpq *72(%rdi)\n\t");
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
void **recomp_sj_push(Ctx *c, uint64_t r0, uint64_t r1, uint64_t r2, uint64_t r3) {
|
||||
(void)c;
|
||||
if (!stack) stack = (SjStack *)calloc(1, sizeof *stack);
|
||||
if (stack->depth >= DEPTH) { /* (too deep: the outermost slots go, as they are the least likely targets) */
|
||||
memmove(&stack->slot[0], &stack->slot[1], sizeof stack->slot[0] * (DEPTH - 1));
|
||||
stack->depth = DEPTH - 1;
|
||||
if (!stack->overflow++) hos_log("setjmp: more than %d nested setjmp owners on this thread", DEPTH);
|
||||
}
|
||||
SjSlot *s = &stack->slot[stack->depth++];
|
||||
s->rets[0] = r0, s->rets[1] = r1, s->rets[2] = r2, s->rets[3] = r3, s->target = 0;
|
||||
return s->buf;
|
||||
}
|
||||
|
||||
uint64_t recomp_sj_target(void **buf) { return ((SjSlot *)((char *)buf - offsetof(SjSlot, buf)))->target; }
|
||||
|
||||
void recomp_sj_pop(void **buf) {
|
||||
if (!stack) return;
|
||||
const int i = (int)(((SjSlot *)((char *)buf - offsetof(SjSlot, buf))) - stack->slot);
|
||||
if (i >= 0 && i < DEPTH && i < stack->depth) stack->depth = i;
|
||||
}
|
||||
|
||||
/* a64_call_miss's first question: a longjmp to a pushed setjmp owner? (does not return when it is) */
|
||||
void hos_setjmp_return(Ctx *c, uint64_t target) {
|
||||
if (!stack || !stack->depth || !target) return;
|
||||
for (int i = stack->depth - 1; i >= 0; i--) {
|
||||
SjSlot *s = &stack->slot[i];
|
||||
if (s->rets[0] != target && s->rets[1] != target && s->rets[2] != target && s->rets[3] != target) continue;
|
||||
static volatile LONG logged;
|
||||
if (InterlockedIncrement(&logged) <= 4)
|
||||
hos_log("longjmp to %#llx (value %llu, %d slots above dropped)", (unsigned long long)target,
|
||||
(unsigned long long)c->x[0], stack->depth - 1 - i);
|
||||
s->target = target;
|
||||
stack->depth = i + 1;
|
||||
recomp_sj_longjmp(s->buf, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* ...and every indirect jump's (third_party/a64-kit/rt a64_ijump_hook): the setjmp return addresses are entries too
|
||||
(the callers run them, recomp_sj_target), so the longjmp's BR finds a function there and never missed: it called
|
||||
the owner's code inside longjmp's own frame, which returned into longjmp's caller (0x8168215c, the UDF after OoT's
|
||||
BL longjmp: the text box thread's "branch to a non-function") */
|
||||
void a64_ijump_hook(Ctx *c, uint64_t target) { hos_setjmp_return(c, target); }
|
||||
527
host/hos_svc.c
Normal file
527
host/hos_svc.c
Normal file
@@ -0,0 +1,527 @@
|
||||
/* Horizon supervisor calls that lifted SDK code still makes (the game itself has none; the SDK has ~60 wrappers).
|
||||
The HLE above nn:: should keep most of them from ever running: what reaches here is either trivial
|
||||
(debug output, ticks, info queries) or a sign that an SDK function above it wants an HLE. Unknown ones stop the
|
||||
run with the svc number and the caller, so the log says what to do next. Numbers: switchbrew.org "SVC". */
|
||||
#include "hos.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
|
||||
#define R_OK 0
|
||||
/* (mkw-recomp) the region of GetInfo 29/30: 128 GB at 192 GB, between the heap (up from 64 GB) and the address
|
||||
regions (down from 512 GB); the SDK's VAMM backs pieces of it with MapPhysicalMemory */
|
||||
#define HOS_NX2_REGION_BASE 0x3000000000ULL
|
||||
#define HOS_NX2_REGION_SIZE 0x2000000000ULL
|
||||
#define R_INVALID_ENUM 0xF001 /* svc::ResultInvalidEnumValue */
|
||||
|
||||
static uint64_t get_info(uint32_t id0, uint64_t id1, int *ok) {
|
||||
*ok = 1;
|
||||
switch (id0) {
|
||||
case 0: return (1u << hos_cores()) - 1; /* CoreMask: cores 0 to hos_cores() - 1 */
|
||||
case 1: return 0xFFFFFFFFFFFFFFFFULL; /* PriorityMask */
|
||||
case 2: return HOS_HEAP_BASE; /* AliasRegionAddress */
|
||||
case 3: return HOS_SPACE_END - HOS_HEAP_BASE; /* AliasRegionSize */
|
||||
case 4: return HOS_HEAP_BASE; /* HeapRegionAddress */
|
||||
case 5: return HOS_SPACE_END - HOS_HEAP_BASE; /* HeapRegionSize */
|
||||
case 6: return hos_total_memory; /* TotalMemorySize */
|
||||
case 7: return hos_program_size + hos_heap_size; /* UsedMemorySize */
|
||||
case 8: return 0; /* DebuggerAttached */
|
||||
case 11: return 0x5A3C9E1F0B7D2468ULL ^ (id1 * 0x9E3779B97F4A7C15ULL); /* RandomEntropy */
|
||||
case 12: return 0x08000000ULL; /* AslrRegionAddress */
|
||||
case 13: return HOS_SPACE_END - 0x08000000ULL; /* AslrRegionSize */
|
||||
case 14: return HOS_SYSTEM_BASE; /* StackRegionAddress */
|
||||
case 15: return HOS_SYSTEM_END - HOS_SYSTEM_BASE; /* StackRegionSize */
|
||||
case 16: case 17: return 0; /* SystemResourceSize total / used */
|
||||
case 18: return hos_program_id; /* ProgramId (main.npdm's, gen/hos_image.c) */
|
||||
case 20: { /* UserExceptionContextAddress: (hookshot) OoT's nn::os::SetDyingMessageRegionPrivate writes its
|
||||
dying-message region into it; a zeroed page, made once */
|
||||
static uint64_t ctx_page;
|
||||
if (!ctx_page) ctx_page = hos_sys_alloc(0x1000, 0x1000);
|
||||
return ctx_page;
|
||||
}
|
||||
case 21: return hos_total_memory; /* TotalNonSystemMemorySize */
|
||||
case 22: return hos_program_size + hos_heap_size; /* UsedNonSystemMemorySize */
|
||||
case 23: return 1; /* IsApplication */
|
||||
/* the Switch 2 SDK's (ids from Eglantine's svc_types.h / svc_info.cpp) */
|
||||
case 24: return 256; /* FreeThreadCount */
|
||||
case 28: return 0; /* AliasRegionExtraSize */
|
||||
case 29: return HOS_NX2_REGION_BASE; /* the VAMM region nnosInitialize asks for */
|
||||
case 30: return HOS_NX2_REGION_SIZE;
|
||||
case 31: case 32: return 0; /* remote memory (the graphics stack's): size, used */
|
||||
case 33: return 0x1000; /* the page granule VAMM maps in */
|
||||
case 34: return 0; /* TransferMemoryHint */
|
||||
case 37: case 38: return 0;
|
||||
default: *ok = 0; return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- mutex arbitration and process-wide condition variables -------------------------------------------------
|
||||
Horizon's user-mode mutex: the word holds the owner's handle, bit 30 means "has waiters". A thread that loses the
|
||||
race sets bit 30 and calls ArbitrateLock; the owner's ArbitrateUnlock hands the word straight to the
|
||||
highest-priority waiter. A condition variable wait releases the mutex and sleeps on the key; a signal moves a
|
||||
waiter back to its mutex, or gives it the mutex if free (switchbrew "SVC", libnx mutex.c / condvar.c). */
|
||||
#define HANDLE_WAIT_MASK 0x40000000u
|
||||
#define R_TIMED_OUT 0xEA01
|
||||
|
||||
typedef struct { HosThread *t; uint64_t mutex, key; uint32_t tag; int on_key; } Waiter;
|
||||
static Waiter waiters[1024];
|
||||
static int nwaiters;
|
||||
static SRWLOCK klock = SRWLOCK_INIT;
|
||||
|
||||
static uint32_t word_get(uint64_t a) { return __atomic_load_n((uint32_t *)GP(a), __ATOMIC_SEQ_CST); }
|
||||
static void word_set(uint64_t a, uint32_t v) { __atomic_store_n((uint32_t *)GP(a), v, __ATOMIC_SEQ_CST); }
|
||||
/* User mode changes a mutex word with exclusives (compare-and-swap here) while the kernel holds klock: a kernel
|
||||
read-modify-write of a word user mode may change must be a compare-and-swap too. */
|
||||
static int word_cas(uint64_t a, uint32_t expect, uint32_t v) {
|
||||
return __atomic_compare_exchange_n((uint32_t *)GP(a), &expect, v, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
|
||||
}
|
||||
|
||||
/* The best waiter (lowest priority value, then oldest) for a mutex (on_key 0) or a key (on_key 1). */
|
||||
static int best_waiter(uint64_t addr, int on_key, int *others) {
|
||||
int best = -1;
|
||||
*others = 0;
|
||||
for (int i = 0; i < nwaiters; i++) {
|
||||
Waiter *w = &waiters[i];
|
||||
if (w->on_key != on_key || (on_key ? w->key : w->mutex) != addr) continue;
|
||||
if (best < 0) best = i;
|
||||
else {
|
||||
(*others)++;
|
||||
if (hos_thread_prio(w->t) < hos_thread_prio(waiters[best].t)) best = i;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
static void remove_waiter(int i) { memmove(&waiters[i], &waiters[i + 1], (nwaiters - i - 1) * sizeof *waiters); nwaiters--; }
|
||||
static int find_thread(HosThread *t) {
|
||||
for (int i = 0; i < nwaiters; i++) if (waiters[i].t == t) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Hand a held mutex to its next waiter, or free it. Caller holds klock. */
|
||||
static void release_locked(uint64_t mutex) {
|
||||
int others, i = best_waiter(mutex, 0, &others);
|
||||
if (i < 0) { word_set(mutex, 0); return; }
|
||||
Waiter w = waiters[i];
|
||||
remove_waiter(i);
|
||||
word_set(mutex, w.tag | (others ? HANDLE_WAIT_MASK : 0));
|
||||
hos_thread_wake(w.t);
|
||||
}
|
||||
|
||||
#if (defined(__x86_64__) || defined(_M_X64)) && !defined(__EMSCRIPTEN__)
|
||||
#include <emmintrin.h>
|
||||
static int spin_for_release(uint64_t mutex, uint32_t held) {
|
||||
static int64_t limit = -1;
|
||||
if (limit < 0) {
|
||||
const char *e = getenv("HOS_SPIN_US");
|
||||
limit = (e ? atoll(e) : 20) * 1000;
|
||||
}
|
||||
static int misses[256], tries[256];
|
||||
const unsigned slot = (unsigned)(mutex >> 3 ^ mutex >> 11) & 255;
|
||||
const int m = __atomic_load_n(&misses[slot], __ATOMIC_RELAXED);
|
||||
if (limit <= 0 || (m >= 4 && (__atomic_add_fetch(&tries[slot], 1, __ATOMIC_RELAXED) & 31))) return 0;
|
||||
const int64_t end = hos_now_ns() + limit;
|
||||
for (;;) {
|
||||
for (int i = 0; i < 16; i++) {
|
||||
if (word_get(mutex) != held) {
|
||||
__atomic_store_n(&misses[slot], 0, __ATOMIC_RELAXED);
|
||||
return 1;
|
||||
}
|
||||
_mm_pause();
|
||||
}
|
||||
if (hos_now_ns() >= end) {
|
||||
if (m < 4) __atomic_store_n(&misses[slot], m + 1, __ATOMIC_RELAXED);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
static int spin_for_release(uint64_t mutex, uint32_t held) { (void)mutex; (void)held; return 0; }
|
||||
#endif
|
||||
|
||||
/* svcArbitrateLock(owner handle, mutex address, own tag) */
|
||||
static uint32_t arbitrate_lock(uint32_t owner, uint64_t mutex, uint32_t tag) {
|
||||
HosThread *self = hos_self();
|
||||
if (spin_for_release(mutex, owner | HANDLE_WAIT_MASK)) return 0;
|
||||
AcquireSRWLockExclusive(&klock);
|
||||
if (word_get(mutex) != (owner | HANDLE_WAIT_MASK)) { /* released meanwhile: let user mode retry */
|
||||
ReleaseSRWLockExclusive(&klock);
|
||||
return 0;
|
||||
}
|
||||
if (nwaiters == 1024) hos_fatal(NULL, "kernel: too many waiters");
|
||||
waiters[nwaiters++] = (Waiter){self, mutex, 0, tag, 0};
|
||||
ReleaseSRWLockExclusive(&klock);
|
||||
int to;
|
||||
hos_thread_wait(self, -1, &to); /* woken once release_locked made us the owner */
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* svcArbitrateUnlock(mutex address) */
|
||||
static uint32_t arbitrate_unlock(uint64_t mutex) {
|
||||
AcquireSRWLockExclusive(&klock);
|
||||
release_locked(mutex);
|
||||
ReleaseSRWLockExclusive(&klock);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* svcWaitProcessWideKeyAtomic(mutex address, key address, own tag, timeout ns) */
|
||||
static uint32_t wait_key(uint64_t mutex, uint64_t key, uint32_t tag, int64_t timeout) {
|
||||
HosThread *self = hos_self();
|
||||
AcquireSRWLockExclusive(&klock);
|
||||
/* The key says "a waiter" before the mutex is released (as Horizon's kernel does): user mode signals only when it
|
||||
reads a nonzero key, so a signaller that took the mutex the moment it was free saw 0, skipped the signal, and
|
||||
this thread slept forever (the rare stall while loading: a thread on a key of 1 with its mutex free). */
|
||||
word_set(key, 1);
|
||||
if (nwaiters == 1024) hos_fatal(NULL, "kernel: too many waiters");
|
||||
waiters[nwaiters++] = (Waiter){self, mutex, key, tag, 1};
|
||||
release_locked(mutex);
|
||||
ReleaseSRWLockExclusive(&klock);
|
||||
int to;
|
||||
hos_thread_wait(self, timeout, &to);
|
||||
if (!to) return 0;
|
||||
AcquireSRWLockExclusive(&klock);
|
||||
int i = find_thread(self);
|
||||
if (i >= 0 && waiters[i].on_key) { /* still waiting on the key: a real timeout; user mode relocks */
|
||||
remove_waiter(i);
|
||||
ReleaseSRWLockExclusive(&klock);
|
||||
return R_TIMED_OUT;
|
||||
}
|
||||
ReleaseSRWLockExclusive(&klock);
|
||||
/* signaled meanwhile: either moved to the mutex queue (wait for the hand-over) or already handed the mutex
|
||||
(the wake is pending); both end with one wake-up */
|
||||
hos_thread_wait(self, -1, &to);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* svcSignalProcessWideKey(key address, count): count <= 0 wakes all */
|
||||
static void signal_key(uint64_t key, int32_t count) {
|
||||
AcquireSRWLockExclusive(&klock);
|
||||
for (int n = 0; count <= 0 || n < count; n++) {
|
||||
int others, i = best_waiter(key, 1, &others);
|
||||
if (i < 0) break;
|
||||
Waiter *w = &waiters[i];
|
||||
/* The owner may unlock (owner -> 0) and other threads lock (0 -> them) in user mode meanwhile: a plain store
|
||||
here once left the word naming a thread that had unlocked it (its next Lock aborted: "locked by the
|
||||
current thread"), or gave a free mutex to two threads. */
|
||||
for (;;) {
|
||||
const uint32_t cur = word_get(w->mutex);
|
||||
if (cur == 0) { /* mutex free: it is theirs */
|
||||
if (!word_cas(w->mutex, 0, w->tag)) continue;
|
||||
HosThread *t = w->t;
|
||||
remove_waiter(i);
|
||||
hos_thread_wake(t);
|
||||
} else { /* queue on the mutex */
|
||||
if (!(cur & HANDLE_WAIT_MASK) && !word_cas(w->mutex, cur, cur | HANDLE_WAIT_MASK)) continue;
|
||||
w->on_key = 0;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
int others;
|
||||
if (best_waiter(key, 1, &others) < 0) word_set(key, 0);
|
||||
ReleaseSRWLockExclusive(&klock);
|
||||
}
|
||||
|
||||
/* ---- (hookshot) the address arbiter: svcWaitForAddress / svcSignalToAddress -----------------------------------
|
||||
OoT's SDK (22.2.8) uses them; MKW's never did. Waiters share the table above (on_key 2, key = the address) and klock,
|
||||
so the condition check and the sleep are atomic against a signal, as in Horizon's KAddressArbiter (mesosphere).
|
||||
Wait types: 0 WaitIfLessThan, 1 DecrementAndWaitIfLessThan, 2 WaitIfEqual (32-bit), 3 WaitIfEqual64 (21.0+).
|
||||
Signal types: 0 Signal, 1 SignalAndIncrementIfEqual, 2 SignalAndModifyByWaitingCountIfEqual. */
|
||||
#define R_INVALID_STATE 0xFA01 /* svc::ResultInvalidState: the value did not match */
|
||||
static int addr_waiters(uint64_t addr) {
|
||||
int n = 0;
|
||||
for (int i = 0; i < nwaiters; i++) if (waiters[i].on_key == 2 && waiters[i].key == addr) n++;
|
||||
return n;
|
||||
}
|
||||
static void wake_address_locked(uint64_t addr, int32_t count) {
|
||||
for (int n = 0; count <= 0 || n < count; n++) {
|
||||
int others, i = best_waiter(addr, 2, &others);
|
||||
if (i < 0) break;
|
||||
HosThread *t = waiters[i].t;
|
||||
remove_waiter(i);
|
||||
hos_thread_wake(t);
|
||||
}
|
||||
}
|
||||
static uint32_t wait_address(uint64_t addr, uint32_t type, uint64_t value, int64_t timeout) {
|
||||
HosThread *self = hos_self();
|
||||
AcquireSRWLockExclusive(&klock);
|
||||
int wait;
|
||||
switch (type) {
|
||||
case 0: wait = (int32_t)word_get(addr) < (int32_t)value; break;
|
||||
case 1: {
|
||||
uint32_t cur;
|
||||
for (;;) {
|
||||
cur = word_get(addr);
|
||||
if ((int32_t)cur >= (int32_t)value) { wait = 0; break; }
|
||||
if (word_cas(addr, cur, cur - 1)) { wait = 1; break; }
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 2: wait = (int32_t)word_get(addr) == (int32_t)value; break;
|
||||
case 3: wait = __atomic_load_n((uint64_t *)GP(addr), __ATOMIC_SEQ_CST) == value; break;
|
||||
default:
|
||||
ReleaseSRWLockExclusive(&klock);
|
||||
hos_log("svcWaitForAddress: arbitration type %u", type);
|
||||
return R_INVALID_ENUM;
|
||||
}
|
||||
if (!wait) { ReleaseSRWLockExclusive(&klock); return R_INVALID_STATE; }
|
||||
if (timeout == 0) { ReleaseSRWLockExclusive(&klock); return R_TIMED_OUT; }
|
||||
if (nwaiters == 1024) hos_fatal(NULL, "kernel: too many waiters");
|
||||
waiters[nwaiters++] = (Waiter){self, 0, addr, 0, 2};
|
||||
ReleaseSRWLockExclusive(&klock);
|
||||
int to;
|
||||
hos_thread_wait(self, timeout, &to);
|
||||
if (!to) return 0;
|
||||
AcquireSRWLockExclusive(&klock);
|
||||
int i = find_thread(self);
|
||||
if (i >= 0 && waiters[i].on_key == 2) { /* still queued: a real timeout */
|
||||
remove_waiter(i);
|
||||
ReleaseSRWLockExclusive(&klock);
|
||||
return R_TIMED_OUT;
|
||||
}
|
||||
ReleaseSRWLockExclusive(&klock);
|
||||
hos_thread_wait(self, -1, &to); /* signaled meanwhile: take the pending wake-up */
|
||||
return 0;
|
||||
}
|
||||
static uint32_t signal_address(uint64_t addr, uint32_t type, int32_t value, int32_t count) {
|
||||
AcquireSRWLockExclusive(&klock);
|
||||
uint32_t r = 0;
|
||||
if (type == 1) {
|
||||
if (!word_cas(addr, (uint32_t)value, (uint32_t)value + 1)) r = R_INVALID_STATE;
|
||||
} else if (type == 2) {
|
||||
/* the new value from the number of waiters, as mesosphere's KAddressArbiter computes it */
|
||||
const int n = addr_waiters(addr);
|
||||
int32_t nv;
|
||||
if (count <= 0) nv = n > 0 ? value - 2 : value + 1;
|
||||
else if (n > 0) {
|
||||
const int more = n - 1 < count + 1 ? n - 1 : count + 1; /* the waiters after the first, capped */
|
||||
nv = more == 0 ? value + 1 : more <= count ? value - 1 : value;
|
||||
} else nv = value + 1;
|
||||
if (!word_cas(addr, (uint32_t)value, (uint32_t)nv)) r = R_INVALID_STATE;
|
||||
} else if (type != 0) {
|
||||
ReleaseSRWLockExclusive(&klock);
|
||||
hos_log("svcSignalToAddress: signal type %u", type);
|
||||
return R_INVALID_ENUM;
|
||||
}
|
||||
if (!r) wake_address_locked(addr, count);
|
||||
ReleaseSRWLockExclusive(&klock);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Every thread waiting in the kernel's locks and condition variables, with the words they wait on (printed with the
|
||||
thread stacks at HOS_EXIT_AFTER: who holds what in a hang). */
|
||||
void hos_kernel_dump(void) {
|
||||
AcquireSRWLockExclusive(&klock);
|
||||
hos_log("kernel: %d threads waiting", nwaiters);
|
||||
for (int i = 0; i < nwaiters; i++) {
|
||||
const Waiter *w = &waiters[i];
|
||||
hos_log("kernel: %s (tag %#x) on %s %#llx: mutex %#llx = %#x, key %#llx = %#x", hos_thread_name(w->t), w->tag,
|
||||
w->on_key ? "key" : "mutex", (unsigned long long)(w->on_key ? w->key : w->mutex),
|
||||
(unsigned long long)w->mutex, w->mutex ? word_get(w->mutex) : 0, (unsigned long long)w->key,
|
||||
w->key ? word_get(w->key) : 0);
|
||||
}
|
||||
ReleaseSRWLockExclusive(&klock);
|
||||
void hos_thread_log_handles(void);
|
||||
hos_thread_log_handles();
|
||||
}
|
||||
|
||||
/* svcQueryMemory: MemoryInfo { u64 addr, size; u32 state, attr, perm, ipc_refs, device_refs, pad } */
|
||||
extern const uint64_t hos_image_end;
|
||||
static void query_memory(uint64_t out, uint64_t addr) {
|
||||
uint64_t base = 0, size = 0;
|
||||
uint32_t state = 0, perm = 0; /* Free */
|
||||
uint64_t stack, stack_size;
|
||||
hos_thread_stack(hos_self(), &stack, &stack_size);
|
||||
if (addr >= stack && addr < stack + stack_size) { base = stack; size = stack_size; state = 0x0B; perm = 3; } /* Stack */
|
||||
else if (addr >= hos_image_base && addr < hos_image_end) { base = hos_image_base; size = hos_image_end - base; state = 0x03; perm = 5; } /* Code */
|
||||
else if (addr >= HOS_HEAP_BASE && addr < HOS_HEAP_BASE + hos_heap_size) { base = HOS_HEAP_BASE; size = hos_heap_size; state = 0x05; perm = 3; } /* Normal */
|
||||
else if (addr >= HOS_SYSTEM_BASE && addr < HOS_SYSTEM_END) { base = HOS_SYSTEM_BASE; size = HOS_SYSTEM_END - HOS_SYSTEM_BASE; state = 0x05; perm = 3; }
|
||||
else { base = addr & ~0xFFFULL; size = 0x1000; } /* Free: one page, enough for callers probing an address */
|
||||
memset(GP(out), 0, 0x28);
|
||||
G64(out) = base;
|
||||
G64(out + 8) = size;
|
||||
G32(out + 16) = state;
|
||||
G32(out + 24) = perm;
|
||||
}
|
||||
|
||||
/* A thread handle, with Horizon's pseudo-handle for the current thread. */
|
||||
#define CUR_THREAD 0xFFFF8000u
|
||||
static HosThread *thread_handle(uint32_t h) { return h == CUR_THREAD ? hos_self() : hos_thread_by_handle(h); }
|
||||
|
||||
void a64_svc(Ctx *c, uint32_t imm) {
|
||||
hos_vcore_checkpoint();
|
||||
switch (imm) {
|
||||
case 0x01: { /* SetHeapSize(-, size) -> (result, heap address) */
|
||||
int hos_heap_size_fits(uint64_t size); /* (hookshot, hos_mem.c: the heap stays in the guest window) */
|
||||
if (!hos_heap_size_fits(c->x[1])) {
|
||||
c->x[0] = 0xCA01; /* svc::ResultOutOfMemory */
|
||||
return;
|
||||
}
|
||||
hos_heap_size = c->x[1];
|
||||
c->x[0] = R_OK;
|
||||
c->x[1] = HOS_HEAP_BASE;
|
||||
return;
|
||||
}
|
||||
case 0x02: /* SetMemoryPermission */
|
||||
case 0x03: /* SetMemoryAttribute */
|
||||
case 0x16: /* CloseHandle */
|
||||
case 0x2A: /* FlushEntireDataCache */
|
||||
case 0x2B: /* FlushDataCache */
|
||||
c->x[0] = R_OK;
|
||||
return;
|
||||
case 0x0A: /* ExitThread */
|
||||
hos_vcore_away();
|
||||
ExitThread(0);
|
||||
return;
|
||||
case 0x07: /* ExitProcess */
|
||||
hos_log("svcExitProcess");
|
||||
hos_log_flush();
|
||||
ExitProcess(0);
|
||||
return;
|
||||
case 0x0C: { /* GetThreadPriority(-, handle) -> (result, priority) */
|
||||
HosThread *t = thread_handle((uint32_t)c->x[1]);
|
||||
c->x[1] = t ? (uint32_t)hos_thread_prio(t) : 44;
|
||||
c->x[0] = t ? R_OK : 0xE401; /* svc::ResultInvalidHandle */
|
||||
return;
|
||||
}
|
||||
case 0x0D: { /* SetThreadPriority(handle, priority) */
|
||||
HosThread *t = thread_handle((uint32_t)c->x[0]);
|
||||
if (t) hos_thread_priority(t, 1, (int)c->x[1]);
|
||||
c->x[0] = t ? R_OK : 0xE401;
|
||||
return;
|
||||
}
|
||||
case 0x0E: { /* GetThreadCoreMask(-, -, handle) -> (result, ideal core, affinity mask) */
|
||||
HosThread *t = thread_handle((uint32_t)c->x[2]);
|
||||
c->x[1] = t ? (uint32_t)hos_thread_core(t) : 0;
|
||||
c->x[2] = t && hos_thread_mask(t) ? hos_thread_mask(t) : 0x7;
|
||||
c->x[0] = t ? R_OK : 0xE401;
|
||||
return;
|
||||
}
|
||||
case 0x0F: { /* SetThreadCoreMask(handle, ideal core, mask): -1 keeps the ideal core, -2/-3 defaults */
|
||||
HosThread *t = thread_handle((uint32_t)c->x[0]);
|
||||
if (t) hos_thread_affinity(t, (int)c->x[1], c->x[2]);
|
||||
c->x[0] = t ? R_OK : 0xE401;
|
||||
return;
|
||||
}
|
||||
case 0x24: /* GetProcessId(-, handle) -> (result, id) */
|
||||
c->x[1] = 0x51;
|
||||
c->x[0] = R_OK;
|
||||
return;
|
||||
case 0x06: /* QueryMemory(MemoryInfo* out, -, address) -> (result, page info) */
|
||||
query_memory(c->x[0], c->x[2]);
|
||||
c->x[0] = R_OK;
|
||||
c->x[1] = 0;
|
||||
return;
|
||||
case 0x1A: /* ArbitrateLock(owner handle, mutex, tag) */
|
||||
c->x[0] = arbitrate_lock((uint32_t)c->x[0], c->x[1], (uint32_t)c->x[2]);
|
||||
return;
|
||||
case 0x1B: /* ArbitrateUnlock(mutex) */
|
||||
c->x[0] = arbitrate_unlock(c->x[0]);
|
||||
return;
|
||||
case 0x1C: /* WaitProcessWideKeyAtomic(mutex, key, tag, timeout) */
|
||||
c->x[0] = wait_key(c->x[0], c->x[1], (uint32_t)c->x[2], (int64_t)c->x[3]);
|
||||
return;
|
||||
case 0x34: /* WaitForAddress(address, type, value, timeout) (hookshot) */
|
||||
c->x[0] = wait_address(c->x[0], (uint32_t)c->x[1], c->x[2], (int64_t)c->x[3]);
|
||||
return;
|
||||
case 0x35: /* SignalToAddress(address, type, value, count) (hookshot) */
|
||||
c->x[0] = signal_address(c->x[0], (uint32_t)c->x[1], (int32_t)c->x[2], (int32_t)c->x[3]);
|
||||
return;
|
||||
case 0x1D: /* SignalProcessWideKey(key, count) */
|
||||
signal_key(c->x[0], (int32_t)c->x[1]);
|
||||
return;
|
||||
case 0x0B: { /* SleepThread(ns) */
|
||||
void hos_sleep_logged(int64_t ns, uint64_t lr);
|
||||
hos_sleep_logged((int64_t)c->x[0], c->x[30] | 1);
|
||||
return;
|
||||
}
|
||||
case 0x10: /* GetCurrentProcessorNumber */
|
||||
c->x[0] = (uint32_t)hos_thread_core(hos_self());
|
||||
return;
|
||||
case 0x1E: /* GetSystemTick */
|
||||
c->x[0] = hos_ticks();
|
||||
return;
|
||||
case 0x25: { /* GetThreadId(-, handle) -> (result, id) */
|
||||
HosThread *t = thread_handle((uint32_t)c->x[1]);
|
||||
c->x[1] = hos_thread_id(t ? t : hos_self());
|
||||
c->x[0] = R_OK;
|
||||
return;
|
||||
}
|
||||
case 0x26: { /* Break(reason, info, size) */
|
||||
hos_fatal(c, "svcBreak(reason %#llx, info %#llx, size %#llx)", (unsigned long long)c->x[0],
|
||||
(unsigned long long)c->x[1], (unsigned long long)c->x[2]);
|
||||
return;
|
||||
}
|
||||
case 0x27: { /* OutputDebugString(str, size) */
|
||||
uint64_t n = c->x[1] > 4096 ? 4096 : c->x[1];
|
||||
char buf[4097];
|
||||
memcpy(buf, GP(c->x[0]), n);
|
||||
buf[n] = 0;
|
||||
hos_log("debug: %s", buf);
|
||||
c->x[0] = R_OK;
|
||||
return;
|
||||
}
|
||||
case 0x2C: /* MapPhysicalMemory(address, size) */
|
||||
hos_commit(c->x[0], c->x[1]);
|
||||
if (hos_trace) hos_log("MapPhysicalMemory(%#llx, %#llx)", (unsigned long long)c->x[0], (unsigned long long)c->x[1]);
|
||||
c->x[0] = R_OK;
|
||||
return;
|
||||
case 0x2D: /* UnmapPhysicalMemory(address, size): the pages read as zero if mapped again */
|
||||
if (!hos_guest_range(c->x[0], c->x[1])) { /* (hookshot: guest pages only) */
|
||||
c->x[0] = 0xCA01;
|
||||
return;
|
||||
}
|
||||
{ /* (pages under a Vulkan import stay committed, zeroed: hos_mem.c FreeMemoryPages) */
|
||||
extern int rx_guest_imported(uint64_t lo, uint64_t hi);
|
||||
if (rx_guest_imported(c->x[0], c->x[0] + c->x[1])) memset(GP(c->x[0]), 0, (size_t)c->x[1]);
|
||||
else VirtualFree(GP(c->x[0]), (SIZE_T)c->x[1], MEM_DECOMMIT);
|
||||
}
|
||||
c->x[0] = R_OK;
|
||||
return;
|
||||
case 0x1F: { /* ConnectToNamedPort(-, name) -> (result, session handle): (hookshot) SDK code that resolves a
|
||||
service through "sm:" (nn::sm::Initialize, from nn::nsd's HIPC client in OoT) gets a session
|
||||
whose requests svc 0x21 answers empty, as for any service the runtime does not emulate. */
|
||||
static volatile LONG next = 0;
|
||||
const char *name = c->x[1] ? (const char *)GP(c->x[1]) : "";
|
||||
uint32_t h = 0x7E000000u | (uint32_t)InterlockedIncrement(&next);
|
||||
hos_log("ipc: ConnectToNamedPort(\"%.11s\") -> session %#x (requests answered empty) (lr %#llx)", name, h,
|
||||
(unsigned long long)c->x[30]);
|
||||
c->x[0] = R_OK;
|
||||
c->x[1] = h;
|
||||
return;
|
||||
}
|
||||
case 0x21: { /* SendSyncRequest(session handle): (mkw-recomp) a service the runtime does not emulate. The request
|
||||
is in the thread's IPC buffer (TLS + 0); the answer is a CMIF success with zeroed outputs, as
|
||||
Eglantine's auto-stub does, so a lifted service client sees an empty, successful reply. */
|
||||
uint8_t *tls = (uint8_t *)GP(c->tpidrro_el0);
|
||||
const uint32_t w0 = *(uint32_t *)tls, w1 = *(uint32_t *)(tls + 4);
|
||||
/* the request's CMIF header ('SFCI', version, command id) after the HIPC header, 16-byte aligned */
|
||||
uint32_t cmd = 0;
|
||||
for (int off = 8; off < 0x40; off += 4)
|
||||
if (*(uint32_t *)(tls + off) == 0x49434653u) { cmd = *(uint32_t *)(tls + off + 8); break; }
|
||||
static volatile LONG logged;
|
||||
if (InterlockedIncrement(&logged) <= 64)
|
||||
hos_log("ipc: handle %#x command %u (hipc %08x %08x, lr %#llx): answered empty", (uint32_t)c->x[0], cmd,
|
||||
w0, w1, (unsigned long long)c->x[30]);
|
||||
memset(tls, 0, 0x100);
|
||||
*(uint32_t *)(tls + 0) = 0; /* HIPC: type 0, no descriptors */
|
||||
*(uint32_t *)(tls + 4) = 16; /* 16 raw data words, no handle descriptor */
|
||||
*(uint32_t *)(tls + 16) = 0x4F434653u; /* CMIF response 'SFCO', version 0, result 0 */
|
||||
c->x[0] = R_OK;
|
||||
return;
|
||||
}
|
||||
case 0x29: { /* GetInfo(id0, handle, id1) -> (result, value) */
|
||||
int ok;
|
||||
uint64_t v = get_info((uint32_t)c->x[1], c->x[3], &ok);
|
||||
if (!ok) hos_log("svcGetInfo: unknown id %#x/%#llx (lr %#llx)", (uint32_t)c->x[1],
|
||||
(unsigned long long)c->x[3], (unsigned long long)c->x[30]);
|
||||
c->x[1] = v;
|
||||
c->x[0] = ok ? R_OK : R_INVALID_ENUM;
|
||||
return;
|
||||
}
|
||||
default:
|
||||
hos_fatal(c, "svc %#x not implemented (x0 %#llx x1 %#llx x2 %#llx)", imm, (unsigned long long)c->x[0],
|
||||
(unsigned long long)c->x[1], (unsigned long long)c->x[2]);
|
||||
}
|
||||
}
|
||||
1390
host/hos_thread.c
Normal file
1390
host/hos_thread.c
Normal file
File diff suppressed because it is too large
Load Diff
326
host/hos_update.c
Normal file
326
host/hos_update.c
Normal file
@@ -0,0 +1,326 @@
|
||||
/* (hookshot) The update offer: at start, the latest release on GitHub is asked for (a few seconds at most, nothing when offline), and
|
||||
when it is not the release this game folder was built with, the player is asked whether to update. Yes starts Triforce Setup
|
||||
that made the folder (triforce_version.txt, written by nx2/make_game.py) with --update: it downloads the new release and builds the
|
||||
folder again from the game files the folder keeps, and the game closes. A folder with no triforce_version.txt (built from the
|
||||
repository, or before updates came in) is never asked about. HOOKSHOT_NO_UPDATE_CHECK=1 (triforce_env.txt) turns it off */
|
||||
#if defined(_WIN32) || defined(__linux__)
|
||||
#include <ctype.h>
|
||||
#include <string.h>
|
||||
|
||||
/* a release tag as it may be shown and passed on to the Builder: letters, digits and . _ + - (from the network, or a
|
||||
file of the game folder) */
|
||||
static int safe_tag(const char *s) {
|
||||
size_t n = strlen(s);
|
||||
if (!n || n > 80) return 0;
|
||||
for (size_t i = 0; i < n; i++)
|
||||
if (!isalnum((unsigned char)s[i]) && !strchr("._+-", s[i])) return 0;
|
||||
return 1;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
#include "hos_paths.h"
|
||||
#include <windows.h>
|
||||
#include <winhttp.h>
|
||||
#include <shellapi.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define UPDATE_HOST L"api.github.com"
|
||||
#define UPDATE_PATH L"/repos/ruckus7382sfgsgdf/CBeta0.2/releases?per_page=1" /* (the newest, pre-releases too: /latest skips them) */
|
||||
#define RELEASES_PAGE L"https://github.com/ruckus7382sfgsgdf/CBeta0.2/releases"
|
||||
|
||||
/* (a line "name=value" of a small text file, in UTF-8: its value, trimmed) */
|
||||
static int read_value(const wchar_t *path, const char *name, char *out, size_t cap) {
|
||||
FILE *f = _wfopen(path, L"rb");
|
||||
if (!f) return 0;
|
||||
char line[1024];
|
||||
const size_t n = strlen(name);
|
||||
int found = 0;
|
||||
while (!found && fgets(line, sizeof line, f)) {
|
||||
char *s = line;
|
||||
if ((unsigned char)s[0] == 0xEF && (unsigned char)s[1] == 0xBB && (unsigned char)s[2] == 0xBF) s += 3;
|
||||
if (strncmp(s, name, n) || s[n] != '=') continue;
|
||||
s += n + 1;
|
||||
size_t len = strlen(s);
|
||||
while (len && (s[len - 1] == 10 || s[len - 1] == 13 || s[len - 1] == ' ' || s[len - 1] == 9)) s[--len] = 0;
|
||||
if (len && len < cap) {
|
||||
memcpy(out, s, len + 1);
|
||||
found = 1;
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
return found;
|
||||
}
|
||||
|
||||
/* (the latest release's tag, from GitHub's API: "tag_name":"...") */
|
||||
static int latest_tag(char *tag, size_t cap) {
|
||||
int ok = 0;
|
||||
HINTERNET s = WinHttpOpen(L"Triforce-update-check", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
|
||||
if (!s) return 0;
|
||||
WinHttpSetTimeouts(s, 2500, 2500, 2500, 3000);
|
||||
HINTERNET c = WinHttpConnect(s, UPDATE_HOST, INTERNET_DEFAULT_HTTPS_PORT, 0);
|
||||
HINTERNET r = c ? WinHttpOpenRequest(c, L"GET", UPDATE_PATH, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE) : NULL;
|
||||
if (r && WinHttpSendRequest(r, L"Accept: application/vnd.github+json\r\n", (DWORD)-1, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) &&
|
||||
WinHttpReceiveResponse(r, NULL)) {
|
||||
DWORD status = 0, size = sizeof status;
|
||||
WinHttpQueryHeaders(r, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &size, WINHTTP_NO_HEADER_INDEX);
|
||||
if (status == 200) {
|
||||
const size_t max = 512 << 10;
|
||||
char *body = (char *)malloc(max + 1);
|
||||
size_t have = 0;
|
||||
DWORD got = 0;
|
||||
while (body && have < max && WinHttpReadData(r, body + have, (DWORD)(max - have), &got) && got) have += got;
|
||||
if (body) {
|
||||
body[have] = 0;
|
||||
const char *k = strstr(body, "\"tag_name\"");
|
||||
if (k && (k = strchr(k + 10, '"'))) {
|
||||
const char *e = strchr(++k, '"');
|
||||
if (e && e > k && (size_t)(e - k) < cap) {
|
||||
memcpy(tag, k, (size_t)(e - k));
|
||||
tag[e - k] = 0;
|
||||
ok = safe_tag(tag); /* (hookshot: it goes on the Builder's command line) */
|
||||
}
|
||||
}
|
||||
free(body);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (r) WinHttpCloseHandle(r);
|
||||
if (c) WinHttpCloseHandle(c);
|
||||
WinHttpCloseHandle(s);
|
||||
return ok;
|
||||
}
|
||||
|
||||
void hos_update_check(void) {
|
||||
if (getenv("HOOKSHOT_NO_UPDATE_CHECK") && strcmp(getenv("HOOKSHOT_NO_UPDATE_CHECK"), "0")) return;
|
||||
wchar_t dir[MAX_PATH], file[MAX_PATH + 64];
|
||||
DWORD n = hos_game_path_w(dir, MAX_PATH);
|
||||
if (!n || n >= MAX_PATH) return;
|
||||
while (n && dir[n - 1] != L'\\' && dir[n - 1] != L'/') n--;
|
||||
if (!n) return;
|
||||
dir[n - 1] = 0;
|
||||
char have[128], builder[MAX_PATH * 3], skipped[128] = "", tag[128];
|
||||
_snwprintf(file, MAX_PATH + 64, L"%ls\\triforce_version.txt", dir);
|
||||
if (!read_value(file, "version", have, sizeof have) || !safe_tag(have)) return;
|
||||
_snwprintf(file, MAX_PATH + 64, L"%ls\\user\\triforce_update_skip.txt", dir);
|
||||
read_value(file, "skip", skipped, sizeof skipped);
|
||||
if (!latest_tag(tag, sizeof tag)) {
|
||||
fprintf(stderr, "update: the latest release could not be asked for (offline?)\n");
|
||||
return;
|
||||
}
|
||||
fprintf(stderr, "update: this folder is %s, the latest release is %s\n", have, tag);
|
||||
if (!strcmp(tag, have) || !strcmp(tag, skipped)) return;
|
||||
|
||||
wchar_t wtag[128], whave[128], wbuilder[MAX_PATH], text[2048];
|
||||
MultiByteToWideChar(CP_UTF8, 0, tag, -1, wtag, 128);
|
||||
MultiByteToWideChar(CP_UTF8, 0, have, -1, whave, 128);
|
||||
_snwprintf(file, MAX_PATH + 64, L"%ls\\triforce_version.txt", dir);
|
||||
const int has_builder = read_value(file, "builder", builder, sizeof builder) &&
|
||||
MultiByteToWideChar(CP_UTF8, 0, builder, -1, wbuilder, MAX_PATH) > 0 &&
|
||||
GetFileAttributesW(wbuilder) != INVALID_FILE_ATTRIBUTES;
|
||||
if (has_builder)
|
||||
_snwprintf(text, 2048,
|
||||
L"A new version of Triforce is out: %ls (this game is %ls).\n\n"
|
||||
L"Update now? The game closes, and Triforce Setup downloads the new version and builds this game folder again from the "
|
||||
L"game files it keeps. Only what changed is compiled again, so it usually takes a few minutes. Your saves and settings stay.\n\n"
|
||||
L"Yes: update now\nNo: not now (asked again next time)\nCancel: skip this version",
|
||||
wtag, whave);
|
||||
else
|
||||
_snwprintf(text, 2048,
|
||||
L"A new version of Triforce is out: %ls (this game is %ls).\n\n"
|
||||
L"The Triforce Setup that made this folder was not found, so it can't update by itself. Open the download page?\n\n"
|
||||
L"Yes: open the page\nNo: not now (asked again next time)\nCancel: skip this version",
|
||||
wtag, whave);
|
||||
const int answer = MessageBoxW(NULL, text, L"Triforce update", MB_YESNOCANCEL | MB_ICONINFORMATION | MB_TOPMOST | MB_SETFOREGROUND);
|
||||
if (answer == IDCANCEL) {
|
||||
wchar_t user[MAX_PATH + 16];
|
||||
_snwprintf(user, MAX_PATH + 16, L"%ls\\user", dir);
|
||||
CreateDirectoryW(user, NULL);
|
||||
_snwprintf(file, MAX_PATH + 64, L"%ls\\user\\triforce_update_skip.txt", dir);
|
||||
FILE *f = _wfopen(file, L"wb");
|
||||
if (f) fprintf(f, "skip=%s\n", tag), fclose(f);
|
||||
return;
|
||||
}
|
||||
if (answer != IDYES) return;
|
||||
if (!has_builder) {
|
||||
ShellExecuteW(NULL, L"open", RELEASES_PAGE, NULL, NULL, SW_SHOWNORMAL);
|
||||
return;
|
||||
}
|
||||
/* (the Python builder: builder= is its pythonw.exe, and builder_args= what goes before --update, its start script) */
|
||||
char bargs[1024] = "";
|
||||
wchar_t wbargs[1024] = L"";
|
||||
_snwprintf(file, MAX_PATH + 64, L"%ls\\triforce_version.txt", dir);
|
||||
if (read_value(file, "builder_args", bargs, sizeof bargs)) MultiByteToWideChar(CP_UTF8, 0, bargs, -1, wbargs, 1024);
|
||||
wchar_t args[MAX_PATH + 1280], wdir[MAX_PATH];
|
||||
_snwprintf(args, MAX_PATH + 1280, L"%ls%ls--update \"%ls\" --tag \"%ls\"", wbargs, wbargs[0] ? L" " : L"", dir, wtag);
|
||||
wcsncpy(wdir, wbuilder, MAX_PATH);
|
||||
wdir[MAX_PATH - 1] = 0;
|
||||
wchar_t *slash = wcsrchr(wdir, L'\\');
|
||||
if (slash) *slash = 0;
|
||||
if ((INT_PTR)ShellExecuteW(NULL, L"open", wbuilder, args, slash ? wdir : NULL, SW_SHOWNORMAL) > 32) {
|
||||
void hos_log_flush(void);
|
||||
hos_log_flush(); /* (the lines logged before, queued: host/hos_thread.c log_queue) */
|
||||
fprintf(stderr, "update: Triforce Setup started to update to %s; the game closes\n", tag);
|
||||
fflush(stderr);
|
||||
ExitProcess(0);
|
||||
}
|
||||
MessageBoxW(NULL, L"Triforce Setup could not be started. The game starts as it is.", L"Triforce update", MB_OK | MB_ICONWARNING | MB_TOPMOST);
|
||||
}
|
||||
#elif defined(__linux__)
|
||||
#include "hos_paths.h"
|
||||
#include <ctype.h>
|
||||
#include <sys/stat.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/* (the same offer as Windows, when the player started bin/hookshot itself. The launcher sets HOOKSHOT_NO_UPDATE_CHECK
|
||||
and asks in its own window. curl and zenity do the network and the question; without either, the game just starts) */
|
||||
|
||||
static int read_value(const char *path, const char *name, char *out, size_t cap) {
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (!f) return 0;
|
||||
char line[1024];
|
||||
const size_t n = strlen(name);
|
||||
int found = 0;
|
||||
while (!found && fgets(line, sizeof line, f)) {
|
||||
char *s = line;
|
||||
if (strncmp(s, name, n) || s[n] != '=') continue;
|
||||
s += n + 1;
|
||||
size_t len = strlen(s);
|
||||
while (len && (s[len - 1] == '\n' || s[len - 1] == '\r' || s[len - 1] == ' ')) s[--len] = 0;
|
||||
if (len && len < cap) memcpy(out, s, len + 1), found = 1;
|
||||
}
|
||||
fclose(f);
|
||||
return found;
|
||||
}
|
||||
|
||||
|
||||
static int pipe_tag(const char *cmd, char *tag, size_t cap) {
|
||||
FILE *p = popen(cmd, "r");
|
||||
if (!p) return 0;
|
||||
char buf[8192];
|
||||
size_t n = fread(buf, 1, sizeof buf - 1, p);
|
||||
pclose(p);
|
||||
buf[n] = 0;
|
||||
const char *k = strstr(buf, "\"tag_name\"");
|
||||
if (k && (k = strchr(k + 10, '"'))) {
|
||||
const char *e = strchr(++k, '"');
|
||||
if (e && e > k && (size_t)(e - k) < cap) {
|
||||
memcpy(tag, k, (size_t)(e - k));
|
||||
tag[e - k] = 0;
|
||||
return safe_tag(tag);
|
||||
}
|
||||
}
|
||||
if (!strncmp(buf, "tag ", 4)) {
|
||||
const char *s = buf + 4;
|
||||
size_t len = strcspn(s, "\r\n");
|
||||
if (len && len < cap) {
|
||||
memcpy(tag, s, len);
|
||||
tag[len] = 0;
|
||||
return safe_tag(tag);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int latest_tag(char *tag, size_t cap) {
|
||||
if (pipe_tag("curl -fsSL --max-time 4 --retry 2 -A Triforce-update-check "
|
||||
"-H \"Accept: application/vnd.github+json\" "
|
||||
"https://api.github.com/repos/ruckus7382sfgsgdf/CBeta0.2/releases/latest 2>/dev/null", tag, cap))
|
||||
return 1;
|
||||
return pipe_tag("curl -fsSL --max-time 8 --retry 2 -A Triforce-update-check "
|
||||
"https://github.com/ruckus7382sfgsgdf/CBeta0.2/releases/latest/download/triforce-linux.txt 2>/dev/null", tag, cap);
|
||||
}
|
||||
|
||||
/* the builder an update installed (builder/linux/linux_update.py): <data>/hookshot/builder/versions/<current>/AppRun. The
|
||||
builder= line names the AppImage that built the folder, which the player may have deleted since */
|
||||
static int installed_builder(char *out, size_t cap) {
|
||||
const char *home = getenv("HOOKSHOT_BUILDER_HOME"), *data = getenv("XDG_DATA_HOME"), *user = getenv("HOME");
|
||||
char root[MAX_PATH * 2], path[MAX_PATH * 2 + 64], tag[128];
|
||||
if (home && *home) snprintf(root, sizeof root, "%s/hookshot/builder", home);
|
||||
else if (data && *data) snprintf(root, sizeof root, "%s/hookshot/builder", data);
|
||||
else if (user && *user) snprintf(root, sizeof root, "%s/.local/share/hookshot/builder", user);
|
||||
else return 0;
|
||||
snprintf(path, sizeof path, "%s/current", root);
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (!f) return 0;
|
||||
const int got = fgets(tag, sizeof tag, f) != NULL;
|
||||
fclose(f);
|
||||
if (!got) return 0;
|
||||
tag[strcspn(tag, "\r\n ")] = 0;
|
||||
if (!safe_tag(tag)) return 0;
|
||||
if (snprintf(out, cap, "%s/versions/%s/AppRun", root, tag) >= (int)cap) return 0;
|
||||
return access(out, X_OK) == 0;
|
||||
}
|
||||
|
||||
void hos_update_check(void) {
|
||||
const char *off = getenv("HOOKSHOT_NO_UPDATE_CHECK");
|
||||
if (off && strcmp(off, "0")) return;
|
||||
char path[MAX_PATH + 64], have[128], builder[MAX_PATH * 2], skipped[128] = "", tag[128];
|
||||
DWORD n = hos_game_path_a(path, MAX_PATH);
|
||||
if (!n || n >= MAX_PATH) return;
|
||||
while (n && path[n - 1] != '/') n--;
|
||||
if (!n) return;
|
||||
path[n] = 0;
|
||||
char dir[MAX_PATH];
|
||||
memcpy(dir, path, n);
|
||||
dir[n] = 0;
|
||||
snprintf(path, sizeof path, "%striforce_version.txt", dir);
|
||||
if (!read_value(path, "version", have, sizeof have) || !safe_tag(have)) return;
|
||||
snprintf(path, sizeof path, "%suser/triforce_update_skip.txt", dir);
|
||||
read_value(path, "skip", skipped, sizeof skipped);
|
||||
if (!latest_tag(tag, sizeof tag)) {
|
||||
fprintf(stderr, "update: the latest release could not be asked for (offline?)\n");
|
||||
return;
|
||||
}
|
||||
fprintf(stderr, "update: this folder is %s, the latest release is %s\n", have, tag);
|
||||
if (!strcmp(tag, have) || !strcmp(tag, skipped)) return;
|
||||
snprintf(path, sizeof path, "%striforce_version.txt", dir);
|
||||
const int has_builder = installed_builder(builder, sizeof builder) ||
|
||||
(read_value(path, "builder", builder, sizeof builder) && access(builder, X_OK) == 0);
|
||||
char text[1600], cmd[4096];
|
||||
snprintf(text, sizeof text,
|
||||
has_builder
|
||||
? "A new version of Triforce is out: %s (this game is %s). Update now? The game closes, and Triforce Setup downloads only what changed and builds this folder again. Your saves and settings stay."
|
||||
: "A new version of Triforce is out: %s (this game is %s). The builder that made this folder was not found. Open the download page?",
|
||||
tag, have);
|
||||
snprintf(cmd, sizeof cmd, "zenity --list --title=Triforce --hide-header --column= --text='%s' 'Update now' 'Not now' 'Skip this version'", text);
|
||||
FILE *pick = popen(cmd, "r");
|
||||
if (!pick) return;
|
||||
char answer[64] = "";
|
||||
if (!fgets(answer, sizeof answer, pick)) answer[0] = 0;
|
||||
pclose(pick);
|
||||
if (!strncmp(answer, "Skip", 4)) {
|
||||
snprintf(path, sizeof path, "%suser", dir);
|
||||
mkdir(path, 0755);
|
||||
snprintf(path, sizeof path, "%suser/triforce_update_skip.txt", dir);
|
||||
FILE *f = fopen(path, "wb");
|
||||
if (f) fprintf(f, "skip=%s\n", tag), fclose(f);
|
||||
return;
|
||||
}
|
||||
if (strncmp(answer, "Update", 6)) return;
|
||||
if (!has_builder) {
|
||||
if (fork() == 0) {
|
||||
execlp("xdg-open", "xdg-open", "https://github.com/ruckus7382sfgsgdf/CBeta0.2/releases", (char *)0);
|
||||
_exit(127);
|
||||
}
|
||||
return;
|
||||
}
|
||||
pid_t pid = fork();
|
||||
if (pid == 0) {
|
||||
execl(builder, builder, "--update", dir, "--tag", tag, (char *)0);
|
||||
_exit(127);
|
||||
}
|
||||
if (pid > 0) {
|
||||
fprintf(stderr, "update: Triforce Setup started to update to %s; the game closes\n", tag);
|
||||
fflush(stderr);
|
||||
_exit(0);
|
||||
}
|
||||
}
|
||||
#else
|
||||
void hos_update_check(void) {}
|
||||
#endif
|
||||
249
host/mf_av1.c
Normal file
249
host/mf_av1.c
Normal file
@@ -0,0 +1,249 @@
|
||||
/* (hookshot) An AV1 decoder on Media Foundation, for nn::codec's AV1 decoder (host/nn_video.c).
|
||||
|
||||
OoT's movies (romfs/Movie: the intro, ...) are AV1, and the static FFmpeg the build links has no AV1 decoder (its
|
||||
native one needs a hardware context; dav1d / libaom are not in it). Windows has one: the decoder MFT of the AV1
|
||||
Video Extension (Microsoft.AV1VideoExtension), in hardware on GPUs that decode AV1 and in software otherwise.
|
||||
The game submits AV1 temporal units (low-overhead OBUs, as in MP4/IVF); pictures come out as NV12.
|
||||
|
||||
The API is synchronous and single-stream: mf_av1_decode takes one temporal unit (or NULL at the end, which
|
||||
drains) and calls back once per picture. A hardware MFT is asynchronous; one is used only if no synchronous
|
||||
decoder exists (HOS_AV1_ASYNC=1 to prefer it: untested). HOS_VIDEO_LOG=1 logs the decoder chosen. */
|
||||
#define COBJMACROS
|
||||
#include "hos.h"
|
||||
#include <windows.h>
|
||||
#include <shellapi.h>
|
||||
#include <initguid.h>
|
||||
#include <mfapi.h>
|
||||
#include <mferror.h>
|
||||
#include <mfidl.h>
|
||||
#include <mftransform.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifndef MFVideoFormat_AV1
|
||||
DEFINE_GUID(MFVideoFormat_AV1_local, 0x31305641, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
|
||||
#define MFVideoFormat_AV1 MFVideoFormat_AV1_local
|
||||
#endif
|
||||
|
||||
/* a picture: luma rows and the interleaved chroma rows, both `stride` bytes apart */
|
||||
typedef void (*mf_av1_picture_fn)(void *user, const uint8_t *y, const uint8_t *uv, int w, int h, int stride, int64_t pts);
|
||||
|
||||
typedef struct {
|
||||
IMFTransform *mft;
|
||||
int w, h, stride;
|
||||
int want_w, want_h; /* (the stream's size: the decoder's frames may be padded, 1088 rows for 1080) */
|
||||
int provides_samples;
|
||||
DWORD out_size;
|
||||
} MfAv1;
|
||||
|
||||
static int com_ready(void) {
|
||||
static volatile LONG started;
|
||||
const HRESULT co = CoInitializeEx(NULL, COINIT_MULTITHREADED); /* (per thread; S_FALSE / RPC_E_CHANGED_MODE: fine) */
|
||||
(void)co;
|
||||
if (InterlockedCompareExchange(&started, 1, 0) == 0) {
|
||||
if (FAILED(MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET))) { started = 2; return 0; }
|
||||
}
|
||||
return started == 1;
|
||||
}
|
||||
|
||||
static int set_output_nv12(MfAv1 *m) {
|
||||
for (DWORD i = 0;; i++) {
|
||||
IMFMediaType *t = NULL;
|
||||
if (FAILED(IMFTransform_GetOutputAvailableType(m->mft, 0, i, &t))) return 0;
|
||||
GUID sub;
|
||||
int ok = SUCCEEDED(IMFMediaType_GetGUID(t, &MF_MT_SUBTYPE, &sub)) && IsEqualGUID(&sub, &MFVideoFormat_NV12) &&
|
||||
SUCCEEDED(IMFTransform_SetOutputType(m->mft, 0, t, 0));
|
||||
if (ok) {
|
||||
UINT64 fs = 0;
|
||||
if (SUCCEEDED(IMFMediaType_GetUINT64(t, &MF_MT_FRAME_SIZE, &fs))) m->w = (int)(fs >> 32), m->h = (int)(UINT32)fs;
|
||||
UINT32 st = 0;
|
||||
m->stride = SUCCEEDED(IMFMediaType_GetUINT32(t, &MF_MT_DEFAULT_STRIDE, &st)) ? (int)st : m->w;
|
||||
}
|
||||
IMFMediaType_Release(t);
|
||||
if (ok) break;
|
||||
}
|
||||
MFT_OUTPUT_STREAM_INFO info = {0};
|
||||
if (SUCCEEDED(IMFTransform_GetOutputStreamInfo(m->mft, 0, &info))) {
|
||||
m->provides_samples = (info.dwFlags & (MFT_OUTPUT_STREAM_PROVIDES_SAMPLES | MFT_OUTPUT_STREAM_CAN_PROVIDE_SAMPLES)) != 0;
|
||||
m->out_size = info.cbSize;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* (hookshot) Without the AV1 Video Extension the movies have no decoder: their pictures stay empty, which shows as a green screen, and the
|
||||
intro never ends. Said once, on its own thread (the game goes on), with the way to the Store page. HOS_AV1_MISSING=1: as if it were missing */
|
||||
static DWORD WINAPI av1_missing_notice(LPVOID unused) {
|
||||
(void)unused;
|
||||
if (MessageBoxA(NULL, "Triforce's movies need Microsoft's free AV1 Video Extension, which this PC does not have. Without it they show a green "
|
||||
"screen and the game can stop at a black screen.\n\nOpen its Microsoft Store page now? Install it, then restart the game.",
|
||||
"Triforce", MB_YESNO | MB_ICONINFORMATION | MB_TOPMOST) == IDYES)
|
||||
ShellExecuteA(NULL, "open", "ms-windows-store://pdp/?ProductId=9MVZQVXJBQ9V", NULL, NULL, SW_SHOWNORMAL);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void av1_missing(void) {
|
||||
static LONG told;
|
||||
if (InterlockedExchange(&told, 1)) return;
|
||||
hos_log("video: no AV1 decoder in Media Foundation: the AV1 Video Extension is not installed, movies will not show");
|
||||
CreateThread(NULL, 0, av1_missing_notice, NULL, 0, NULL);
|
||||
}
|
||||
|
||||
void *mf_av1_open(int w, int h) {
|
||||
if (!com_ready()) return NULL;
|
||||
if (getenv("HOS_AV1_MISSING")) { av1_missing(); return NULL; }
|
||||
MFT_REGISTER_TYPE_INFO in = {MFMediaType_Video, MFVideoFormat_AV1};
|
||||
IMFActivate **acts = NULL;
|
||||
UINT32 n = 0;
|
||||
const int prefer_async = getenv("HOS_AV1_ASYNC") != NULL;
|
||||
const UINT32 tries[2] = {prefer_async ? MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_ASYNCMFT : MFT_ENUM_FLAG_SYNCMFT,
|
||||
prefer_async ? MFT_ENUM_FLAG_SYNCMFT : MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_ASYNCMFT};
|
||||
IMFTransform *mft = NULL;
|
||||
for (int k = 0; k < 2 && !mft; k++) {
|
||||
if (FAILED(MFTEnumEx(MFT_CATEGORY_VIDEO_DECODER, tries[k] | MFT_ENUM_FLAG_SORTANDFILTER, &in, NULL, &acts, &n)))
|
||||
continue;
|
||||
for (UINT32 i = 0; i < n && !mft; i++) {
|
||||
if (SUCCEEDED(IMFActivate_ActivateObject(acts[i], &IID_IMFTransform, (void **)&mft))) {
|
||||
WCHAR name[128] = L"?";
|
||||
IMFActivate_GetString(acts[i], &MFT_FRIENDLY_NAME_Attribute, name, 128, NULL);
|
||||
hos_log("video: AV1 on Media Foundation: %ls (%s)", name, k == 0 && !prefer_async ? "synchronous" : "asynchronous");
|
||||
if (tries[k] & MFT_ENUM_FLAG_ASYNCMFT) { /* (an async MFT must be unlocked to be used) */
|
||||
IMFAttributes *a = NULL;
|
||||
if (SUCCEEDED(IMFTransform_GetAttributes(mft, &a)) && a) {
|
||||
IMFAttributes_SetUINT32(a, &MF_TRANSFORM_ASYNC_UNLOCK, TRUE);
|
||||
IMFAttributes_Release(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (UINT32 i = 0; i < n; i++) IMFActivate_Release(acts[i]);
|
||||
CoTaskMemFree(acts);
|
||||
acts = NULL, n = 0;
|
||||
}
|
||||
if (!mft) { av1_missing(); return NULL; }
|
||||
IMFMediaType *t = NULL;
|
||||
MFCreateMediaType(&t);
|
||||
IMFMediaType_SetGUID(t, &MF_MT_MAJOR_TYPE, &MFMediaType_Video);
|
||||
IMFMediaType_SetGUID(t, &MF_MT_SUBTYPE, &MFVideoFormat_AV1);
|
||||
if (w > 0 && h > 0) IMFMediaType_SetUINT64(t, &MF_MT_FRAME_SIZE, ((UINT64)(UINT32)w << 32) | (UINT32)h);
|
||||
const HRESULT hr = IMFTransform_SetInputType(mft, 0, t, 0);
|
||||
IMFMediaType_Release(t);
|
||||
if (FAILED(hr)) { hos_log("video: the AV1 decoder refused its input type (%#lx)", (unsigned long)hr); IMFTransform_Release(mft); return NULL; }
|
||||
MfAv1 *m = (MfAv1 *)calloc(1, sizeof *m);
|
||||
m->mft = mft;
|
||||
m->w = w, m->h = h, m->stride = w;
|
||||
m->want_w = w, m->want_h = h;
|
||||
set_output_nv12(m);
|
||||
IMFTransform_ProcessMessage(mft, MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0);
|
||||
IMFTransform_ProcessMessage(mft, MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0);
|
||||
return m;
|
||||
}
|
||||
|
||||
/* every picture the decoder has ready */
|
||||
static void pull(MfAv1 *m, mf_av1_picture_fn fn, void *user) {
|
||||
for (int guard = 0; guard < 64; guard++) {
|
||||
MFT_OUTPUT_DATA_BUFFER ob = {0};
|
||||
IMFSample *own = NULL;
|
||||
if (!m->provides_samples) {
|
||||
IMFMediaBuffer *b = NULL;
|
||||
const DWORD size = m->out_size ? m->out_size : (DWORD)((size_t)(m->stride > 0 ? m->stride : m->w) * m->h * 3 / 2);
|
||||
if (FAILED(MFCreateSample(&own)) || FAILED(MFCreateMemoryBuffer(size, &b))) { if (own) IMFSample_Release(own); return; }
|
||||
IMFSample_AddBuffer(own, b);
|
||||
IMFMediaBuffer_Release(b);
|
||||
ob.pSample = own;
|
||||
}
|
||||
DWORD status = 0;
|
||||
const HRESULT hr = IMFTransform_ProcessOutput(m->mft, 0, 1, &ob, &status);
|
||||
if (hr == MF_E_TRANSFORM_STREAM_CHANGE) {
|
||||
if (own) IMFSample_Release(own);
|
||||
if (ob.pEvents) IMFCollection_Release(ob.pEvents);
|
||||
set_output_nv12(m);
|
||||
continue;
|
||||
}
|
||||
if (FAILED(hr)) { /* MF_E_TRANSFORM_NEED_MORE_INPUT: all out */
|
||||
if (own) IMFSample_Release(own);
|
||||
if (ob.pEvents) IMFCollection_Release(ob.pEvents);
|
||||
return;
|
||||
}
|
||||
IMFSample *s = ob.pSample;
|
||||
LONGLONG t100 = 0;
|
||||
IMFSample_GetSampleTime(s, &t100);
|
||||
IMFMediaBuffer *b = NULL;
|
||||
if (SUCCEEDED(IMFSample_ConvertToContiguousBuffer(s, &b))) {
|
||||
BYTE *p = NULL;
|
||||
DWORD len = 0;
|
||||
IMFMediaBuffer_GetCurrentLength(b, &len);
|
||||
IMF2DBuffer *b2 = NULL;
|
||||
LONG pitch = 0;
|
||||
const int locked2d = SUCCEEDED(IMFMediaBuffer_QueryInterface(b, &IID_IMF2DBuffer, (void **)&b2)) &&
|
||||
SUCCEEDED(IMF2DBuffer_Lock2D(b2, &p, &pitch));
|
||||
if (!locked2d && SUCCEEDED(IMFMediaBuffer_Lock(b, &p, NULL, &len)))
|
||||
pitch = m->stride > 0 ? m->stride : m->w;
|
||||
if (p && pitch > 0) {
|
||||
/* the chroma plane follows the luma rows the buffer has (the padded height): rows = 1.5 x that */
|
||||
const DWORD rows = len / (DWORD)pitch;
|
||||
const int luma_rows = rows >= (DWORD)m->h * 3 / 2 ? (int)(rows * 2 / 3) : m->h;
|
||||
const int ow = m->want_w > 0 && m->want_w < m->w ? m->want_w : m->w;
|
||||
const int oh = m->want_h > 0 && m->want_h < m->h ? m->want_h : m->h;
|
||||
fn(user, p, p + (size_t)pitch * luma_rows, ow, oh, (int)pitch, (int64_t)t100 * 100);
|
||||
if (locked2d) IMF2DBuffer_Unlock2D(b2);
|
||||
else IMFMediaBuffer_Unlock(b);
|
||||
}
|
||||
if (b2) IMF2DBuffer_Release(b2);
|
||||
IMFMediaBuffer_Release(b);
|
||||
}
|
||||
if (ob.pEvents) IMFCollection_Release(ob.pEvents);
|
||||
IMFSample_Release(s); /* (own, or the decoder's) */
|
||||
}
|
||||
}
|
||||
|
||||
/* one temporal unit (pts in ns), or data NULL: the stream's end (the rest out) */
|
||||
void mf_av1_decode(void *h, const uint8_t *data, size_t n, int64_t pts, mf_av1_picture_fn fn, void *user) {
|
||||
MfAv1 *m = (MfAv1 *)h;
|
||||
if (!m) return;
|
||||
CoInitializeEx(NULL, COINIT_MULTITHREADED);
|
||||
if (!data) {
|
||||
IMFTransform_ProcessMessage(m->mft, MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0);
|
||||
IMFTransform_ProcessMessage(m->mft, MFT_MESSAGE_COMMAND_DRAIN, 0);
|
||||
pull(m, fn, user);
|
||||
IMFTransform_ProcessMessage(m->mft, MFT_MESSAGE_COMMAND_FLUSH, 0);
|
||||
IMFTransform_ProcessMessage(m->mft, MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0);
|
||||
return;
|
||||
}
|
||||
IMFSample *s = NULL;
|
||||
IMFMediaBuffer *b = NULL;
|
||||
if (FAILED(MFCreateSample(&s)) || FAILED(MFCreateMemoryBuffer((DWORD)n, &b))) { if (s) IMFSample_Release(s); return; }
|
||||
BYTE *p = NULL;
|
||||
IMFMediaBuffer_Lock(b, &p, NULL, NULL);
|
||||
memcpy(p, data, n);
|
||||
IMFMediaBuffer_Unlock(b);
|
||||
IMFMediaBuffer_SetCurrentLength(b, (DWORD)n);
|
||||
IMFSample_AddBuffer(s, b);
|
||||
IMFSample_SetSampleTime(s, pts / 100);
|
||||
for (int tries = 0; tries < 2; tries++) {
|
||||
const HRESULT hr = IMFTransform_ProcessInput(m->mft, 0, s, 0);
|
||||
if (hr == MF_E_NOTACCEPTING) { pull(m, fn, user); continue; } /* (full: its pictures out first) */
|
||||
if (FAILED(hr)) {
|
||||
static int logged;
|
||||
if (logged++ < 4) hos_log("video: AV1 decoder ProcessInput failed (%#lx, %zu bytes)", (unsigned long)hr, n);
|
||||
}
|
||||
break;
|
||||
}
|
||||
IMFMediaBuffer_Release(b);
|
||||
IMFSample_Release(s);
|
||||
pull(m, fn, user);
|
||||
}
|
||||
|
||||
void mf_av1_flush(void *h) {
|
||||
MfAv1 *m = (MfAv1 *)h;
|
||||
if (!m) return;
|
||||
IMFTransform_ProcessMessage(m->mft, MFT_MESSAGE_COMMAND_FLUSH, 0);
|
||||
IMFTransform_ProcessMessage(m->mft, MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0);
|
||||
}
|
||||
|
||||
void mf_av1_close(void *h) {
|
||||
MfAv1 *m = (MfAv1 *)h;
|
||||
if (!m) return;
|
||||
IMFTransform_ProcessMessage(m->mft, MFT_MESSAGE_NOTIFY_END_STREAMING, 0);
|
||||
IMFTransform_Release(m->mft);
|
||||
free(m);
|
||||
}
|
||||
40
host/mingw_msvc_shims.c
Normal file
40
host/mingw_msvc_shims.c
Normal file
@@ -0,0 +1,40 @@
|
||||
/* (hookshot) The llvm-mingw build (HOOKSHOT_MINGW, as TotK Recomp builds): the static FFmpeg libraries in the CPM cache were built
|
||||
with Microsoft's compiler and name a few things of its C runtime that the MinGW one does not have: the stack-buffer
|
||||
check (/GS), the float marker and the range-check report. Here they are, as the MSVC runtime defines them. The MSVC build
|
||||
compiles nothing of this file. NVIDIA's NGX library (nvsdk_ngx_s.lib, a build with NVIDIA DLSS) asks for the same: this file
|
||||
is linked into triforce_vk.dll too then, with gpu/vk/vk_ngx_msvc_rt.cpp for its C++ parts. */
|
||||
#if defined(__MINGW32__)
|
||||
#include <windows.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
int _fltused = 0x9875; /* (the value MSVC's runtime gives it: only its presence matters) */
|
||||
|
||||
/* /GS: a cookie in each guarded frame, checked on return. The value is set once at start (a fixed one works too: a mismatch
|
||||
means the stack was overrun, and then the process ends, as with MSVC's runtime) */
|
||||
uintptr_t __security_cookie = (uintptr_t)0x00002B992DDFA232ull;
|
||||
|
||||
__attribute__((constructor)) static void security_cookie_init(void) {
|
||||
LARGE_INTEGER t;
|
||||
QueryPerformanceCounter(&t);
|
||||
uintptr_t c = (uintptr_t)t.QuadPart ^ (uintptr_t)GetCurrentProcessId() ^ ((uintptr_t)GetCurrentThreadId() << 32);
|
||||
c &= 0x0000FFFFFFFFFFFFull; /* (MSVC keeps the top 16 bits clear) */
|
||||
if (c) __security_cookie = c;
|
||||
}
|
||||
|
||||
void __security_check_cookie(uintptr_t cookie) {
|
||||
if (cookie != __security_cookie) __fastfail(2); /* FAST_FAIL_STACK_COOKIE_CHECK_FAILURE */
|
||||
}
|
||||
|
||||
void __report_rangecheckfailure(void) { __fastfail(8); } /* FAST_FAIL_RANGE_CHECK_FAILURE */
|
||||
|
||||
/* MSVC's stack probe for frames over a page: the same contract on x64 as MinGW's ___chkstk_ms (RAX = the size, every page
|
||||
touched, nothing else changed) */
|
||||
__asm__(".text\n.globl __chkstk\n__chkstk:\n jmp ___chkstk_ms\n");
|
||||
|
||||
/* the unwind handler of /GS frames: it checks the frame's cookie, then lets the search go on */
|
||||
EXCEPTION_DISPOSITION __GSHandlerCheck(PEXCEPTION_RECORD record, void *frame, PCONTEXT context, void *dispatcher) {
|
||||
(void)record, (void)frame, (void)context, (void)dispatcher;
|
||||
return ExceptionContinueSearch;
|
||||
}
|
||||
#endif
|
||||
755
host/mkw_glue.c
Normal file
755
host/mkw_glue.c
Normal file
@@ -0,0 +1,755 @@
|
||||
/* mkw-recomp's pieces of the standalone runtime that TOTKPort's hos/ keeps elsewhere: the 64-bit guest window's
|
||||
commit (TOTK commits its whole 4 GB window up front; MKW's 512 GB window is only reserved), and stand-ins for the
|
||||
hooks of files not taken into host/ (the renderer and display, the profiler, mods, TOTK's own patches). */
|
||||
#include "hos.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#ifndef _WIN32
|
||||
#include <dlfcn.h>
|
||||
#include <execinfo.h>
|
||||
#endif
|
||||
|
||||
/* ---- the guest window ---------------------------------------------------------------------------------------
|
||||
The runtime commits what it hands out (image, system region, heap, address regions: hos_commit), because host
|
||||
APIs given guest buffers (ReadFile into a game buffer) fail on reserved pages without raising an exception. A
|
||||
guest or host access to a page nothing committed is committed on first touch, 64 KB at a time, by the handler. */
|
||||
void hos_commit(uint64_t addr, uint64_t size) {
|
||||
if (!size) return;
|
||||
if (!hos_guest_range(addr, size)) { /* (hookshot: guest pages only; the posix layer's commit changes any page's protection) */
|
||||
hos_log("mem: commit of %#llx bytes at %#llx: outside the guest window", (unsigned long long)size, (unsigned long long)addr);
|
||||
return;
|
||||
}
|
||||
const uint64_t lo = addr & ~0xFFFFULL, hi = (addr + size + 0xFFFF) & ~0xFFFFULL;
|
||||
if (!VirtualAlloc(GP(lo), (SIZE_T)(hi - lo), MEM_COMMIT, PAGE_READWRITE)) {
|
||||
const DWORD err = GetLastError();
|
||||
hos_log("mem: commit of %#llx bytes at %#llx failed (error %lu)", (unsigned long long)(hi - lo),
|
||||
(unsigned long long)lo, err);
|
||||
if (err == ERROR_COMMITMENT_LIMIT) { /* (1455: RAM and page file full; the game crashes soon after. Said once, on its own thread) */
|
||||
static volatile LONG said;
|
||||
if (InterlockedExchange(&said, 1) == 0) {
|
||||
hos_log("mem: Windows is out of memory (RAM and page file): close other programs, or let Windows manage the page file size");
|
||||
extern DWORD WINAPI hos_out_of_memory_box(LPVOID);
|
||||
CloseHandle(CreateThread(NULL, 0, hos_out_of_memory_box, NULL, 0, NULL));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DWORD WINAPI hos_out_of_memory_box(LPVOID unused) {
|
||||
(void)unused;
|
||||
MessageBoxA(NULL,
|
||||
"Windows has run out of memory (RAM plus the page file), so Triforce may close.\n\n"
|
||||
"Close other programs, and in Windows' System > About > Advanced system settings > Performance > Advanced > Virtual "
|
||||
"memory, choose \"Automatically manage paging file size\" (or give it at least 16 GB). A lower Quality preset in the "
|
||||
"Insert menu also uses less memory.",
|
||||
"Triforce: out of memory", MB_OK | MB_ICONWARNING | MB_TOPMOST);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static LONG CALLBACK commit_on_touch(EXCEPTION_POINTERS *info) {
|
||||
EXCEPTION_RECORD *rec = info->ExceptionRecord;
|
||||
if (rec->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || rec->NumberParameters < 2) return EXCEPTION_CONTINUE_SEARCH;
|
||||
const uint8_t *p = (const uint8_t *)rec->ExceptionInformation[1];
|
||||
if (p < A64_MEM || p >= A64_MEM + HOS_GUEST_SPACE) return EXCEPTION_CONTINUE_SEARCH;
|
||||
const uint64_t guest = (uint64_t)(p - A64_MEM);
|
||||
if (guest < 0x100000) return EXCEPTION_CONTINUE_SEARCH; /* (a null pointer: the game's own fault) */
|
||||
MEMORY_BASIC_INFORMATION mbi;
|
||||
if (!VirtualQuery(p, &mbi, sizeof mbi) || mbi.State != MEM_RESERVE) return EXCEPTION_CONTINUE_SEARCH;
|
||||
static volatile LONG touched;
|
||||
if (InterlockedIncrement(&touched) <= 16)
|
||||
hos_log("mem: %#llx committed on first touch (nothing handed it out)", (unsigned long long)guest);
|
||||
return VirtualAlloc(GP(guest & ~0xFFFFULL), 0x10000, MEM_COMMIT, PAGE_READWRITE) ? EXCEPTION_CONTINUE_EXECUTION
|
||||
: EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
/* A crash nothing handles: what, where (mkw.exe+offset: nx2/dllmap.py reads mkw.map the same way), and the guest
|
||||
state of the thread, as of its last call out of lifted code, with its frame chain from x29. */
|
||||
static uint64_t peek_guest(uint64_t a) {
|
||||
MEMORY_BASIC_INFORMATION mbi;
|
||||
if (a >= HOS_GUEST_SPACE - 8 || !VirtualQuery(GP(a), &mbi, sizeof mbi) || mbi.State != MEM_COMMIT) return 0;
|
||||
return G64(a);
|
||||
}
|
||||
|
||||
static LONG WINAPI report_crash(EXCEPTION_POINTERS *info) {
|
||||
EXCEPTION_RECORD *rec = info->ExceptionRecord;
|
||||
const uint64_t rip = info->ContextRecord->Rip;
|
||||
HMODULE mod = NULL;
|
||||
char name[MAX_PATH] = "?";
|
||||
if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||
(LPCSTR)rip, &mod))
|
||||
GetModuleFileNameA(mod, name, MAX_PATH);
|
||||
const char *base = strrchr(name, '\\');
|
||||
const uint64_t addr = rec->NumberParameters > 1 ? rec->ExceptionInformation[1] : 0;
|
||||
hos_log("CRASH: exception %#lx (%s %#llx, guest %#llx) at %s+%#llx", rec->ExceptionCode,
|
||||
rec->NumberParameters > 1 && rec->ExceptionInformation[0] == 1 ? "write" : "read",
|
||||
(unsigned long long)addr, (unsigned long long)(addr - (uint64_t)A64_MEM), base ? base + 1 : name,
|
||||
(unsigned long long)(rip - (uint64_t)mod));
|
||||
#ifdef _WIN32
|
||||
{ /* the host stack from the faulting frame (x64 unwind data), as module+offset (nx2/samap.py maps mkw.exe's) */
|
||||
CONTEXT ctx = *info->ContextRecord;
|
||||
char hb[1024];
|
||||
int n = snprintf(hb, sizeof hb, "CRASH: host backtrace:");
|
||||
for (int i = 0; i < 20 && ctx.Rip && n < (int)sizeof hb - 48; i++) {
|
||||
HMODULE m = NULL;
|
||||
char mn[MAX_PATH] = "?";
|
||||
if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||
(LPCSTR)ctx.Rip, &m))
|
||||
GetModuleFileNameA(m, mn, MAX_PATH);
|
||||
const char *mb = strrchr(mn, '\\');
|
||||
n += snprintf(hb + n, sizeof hb - n, " %s+%#llx", mb ? mb + 1 : mn, (unsigned long long)(ctx.Rip - (uint64_t)m));
|
||||
DWORD64 image = 0;
|
||||
PRUNTIME_FUNCTION f = RtlLookupFunctionEntry(ctx.Rip, &image, NULL);
|
||||
if (!f) break;
|
||||
void *handler_data;
|
||||
DWORD64 frame;
|
||||
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, ctx.Rip, f, &ctx, &handler_data, &frame, NULL);
|
||||
}
|
||||
hos_log("%s", hb);
|
||||
}
|
||||
#else
|
||||
{ /* (hookshot) Linux: the host stack as module+offset, from glibc (the frames above the signal's included): the
|
||||
x64 unwind data is Windows' */
|
||||
void *pcs[24];
|
||||
const int got = backtrace(pcs, 24);
|
||||
char hb[1024];
|
||||
int n = snprintf(hb, sizeof hb, "CRASH: host backtrace:");
|
||||
for (int i = 0; i < got && n < (int)sizeof hb - 48; i++) {
|
||||
Dl_info d;
|
||||
const char *mn = "?", *mb;
|
||||
uint64_t off = (uint64_t)(uintptr_t)pcs[i];
|
||||
if (dladdr(pcs[i], &d) && d.dli_fname) mn = d.dli_fname, off -= (uint64_t)(uintptr_t)d.dli_fbase;
|
||||
mb = strrchr(mn, '/');
|
||||
n += snprintf(hb + n, sizeof hb - n, " %s+%#llx", mb ? mb + 1 : mn, (unsigned long long)off);
|
||||
}
|
||||
hos_log("%s", hb);
|
||||
}
|
||||
#endif
|
||||
Ctx *c = hos_ctx();
|
||||
if (c) {
|
||||
hos_log("CRASH: thread %s, sp %#llx", hos_thread_name(hos_self()), (unsigned long long)c->x[31]);
|
||||
for (int i = 0; i < 31; i += 4)
|
||||
hos_log("CRASH: x%-2d %016llx x%-2d %016llx x%-2d %016llx x%-2d %016llx", i,
|
||||
(unsigned long long)c->x[i], i + 1, (unsigned long long)c->x[i + 1], i + 2,
|
||||
(unsigned long long)c->x[i + 2], i + 3, i + 3 < 31 ? (unsigned long long)c->x[i + 3] : 0ULL);
|
||||
char bt[1024];
|
||||
int n = snprintf(bt, sizeof bt, "CRASH: guest backtrace: lr %#llx", (unsigned long long)c->x[30]);
|
||||
uint64_t fp = c->x[29];
|
||||
for (int i = 0; i < 40 && fp && !(fp & 15) && n < (int)sizeof bt - 24; i++) {
|
||||
const uint64_t lr = peek_guest(fp + 8), next = peek_guest(fp);
|
||||
n += snprintf(bt + n, sizeof bt - n, " %#llx", (unsigned long long)lr);
|
||||
if (next <= fp) break;
|
||||
fp = next;
|
||||
}
|
||||
hos_log("%s", bt);
|
||||
/* the memory x0, x1 and x19 point to (the object a crash is usually about) */
|
||||
static const int dumped[] = {0, 1, 19};
|
||||
for (int k = 0; k < 3; k++) {
|
||||
const int r = dumped[k];
|
||||
const uint64_t base = c->x[r];
|
||||
if (base < 0x100000 || !peek_guest(base) && !peek_guest(base + 8) && !peek_guest(base + 0x100)) continue;
|
||||
for (int row = 0; row < 0x120; row += 32)
|
||||
hos_log("CRASH: [x%d+%#05x] %016llx %016llx %016llx %016llx", r, row,
|
||||
(unsigned long long)peek_guest(base + row), (unsigned long long)peek_guest(base + row + 8),
|
||||
(unsigned long long)peek_guest(base + row + 16), (unsigned long long)peek_guest(base + row + 24));
|
||||
}
|
||||
}
|
||||
hos_log_flush();
|
||||
void hos_hostcall_stats(void);
|
||||
hos_hostcall_stats(); /* (HOS_HOSTCALL_STATS=1: the host calls made, and the last 256 of them) */
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
/* (hos_prof.c's, for hos_fatal) the current thread's guest frame chain from x29 */
|
||||
void hos_backtrace(void) {
|
||||
Ctx *c = hos_ctx();
|
||||
if (!c) return;
|
||||
char bt[1024];
|
||||
int n = snprintf(bt, sizeof bt, "guest backtrace: lr %#llx", (unsigned long long)c->x[30]);
|
||||
uint64_t fp = c->x[29];
|
||||
for (int i = 0; i < 40 && fp && !(fp & 15) && n < (int)sizeof bt - 24; i++) {
|
||||
const uint64_t lr = peek_guest(fp + 8), next = peek_guest(fp);
|
||||
n += snprintf(bt + n, sizeof bt - n, " %#llx", (unsigned long long)lr);
|
||||
if (next <= fp) break;
|
||||
fp = next;
|
||||
}
|
||||
fprintf(stderr, "[hos] %s\n", bt);
|
||||
fflush(stderr);
|
||||
}
|
||||
|
||||
/* HOS_STATS_AFTER=<seconds> (with HOS_HOSTCALL_STATS=1): the host call counts and the last calls at that time, for
|
||||
runs that are stopped rather than exit (what a quiet game is doing) */
|
||||
static DWORD WINAPI stats_after(void *p) {
|
||||
Sleep((DWORD)(uintptr_t)p * 1000);
|
||||
void hos_hostcall_stats(void);
|
||||
hos_log("stats: after %u s", (unsigned)(uintptr_t)p);
|
||||
void hos_thread_dump(void);
|
||||
hos_thread_dump();
|
||||
hos_log_flush();
|
||||
hos_hostcall_stats();
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* heap corruption and fail-fast reports go to the process's end without reaching the unhandled filter: reported here
|
||||
first (the backtrace is where the heap noticed, after the bad write) */
|
||||
static LONG CALLBACK report_fatal(EXCEPTION_POINTERS *info) {
|
||||
const DWORD code = info->ExceptionRecord->ExceptionCode;
|
||||
if (code == 0xC0000374 || code == 0xC0000409) report_crash(info);
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
void hos_commit_init(void) {
|
||||
AddVectoredExceptionHandler(1, commit_on_touch);
|
||||
AddVectoredExceptionHandler(0, report_fatal);
|
||||
SetUnhandledExceptionFilter(report_crash);
|
||||
const char *after = getenv("HOS_STATS_AFTER");
|
||||
if (after && atoi(after) > 0) CreateThread(NULL, 0, stats_after, (void *)(uintptr_t)atoi(after), 0, NULL);
|
||||
}
|
||||
|
||||
/* ---- stand-ins --------------------------------------------------------------------------------------------- */
|
||||
/* HOS_PROFILE=<seconds> (in place of TOTKPort's hos_prof.c): every interval, the process's busiest threads and their
|
||||
share of a core (guest threads by their guest names, host threads by their descriptions): which one a frame rate
|
||||
waits for */
|
||||
#ifdef _WIN32
|
||||
#include <tlhelp32.h>
|
||||
int hos_thread_handles(HANDLE *out, const char **names, int max); /* hos_thread.c */
|
||||
static DWORD WINAPI prof_thread(void *p) {
|
||||
const DWORD ms = (DWORD)(uintptr_t)p * 1000;
|
||||
enum { MAXT = 512 };
|
||||
static DWORD ids[MAXT];
|
||||
static uint64_t was[MAXT];
|
||||
int nwas = 0;
|
||||
for (;;) {
|
||||
Sleep(ms);
|
||||
static HANDLE gh[1024];
|
||||
static const char *gn[1024];
|
||||
const int ng = hos_thread_handles(gh, gn, 1024);
|
||||
struct { DWORD id; uint64_t cpu, delta; char name[64]; } cur[MAXT];
|
||||
int n = 0;
|
||||
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
|
||||
THREADENTRY32 te = {sizeof te};
|
||||
for (BOOL ok = Thread32First(snap, &te); ok && n < MAXT; ok = Thread32Next(snap, &te)) {
|
||||
if (te.th32OwnerProcessID != GetCurrentProcessId()) continue;
|
||||
HANDLE h = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, FALSE, te.th32ThreadID);
|
||||
if (!h) continue;
|
||||
FILETIME c0, e0, k, u;
|
||||
if (GetThreadTimes(h, &c0, &e0, &k, &u)) {
|
||||
cur[n].id = te.th32ThreadID;
|
||||
cur[n].cpu = ((uint64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) + ((uint64_t)u.dwHighDateTime << 32 | u.dwLowDateTime);
|
||||
cur[n].delta = cur[n].cpu;
|
||||
for (int i = 0; i < nwas; i++)
|
||||
if (ids[i] == te.th32ThreadID) { cur[n].delta = cur[n].cpu - was[i]; break; }
|
||||
snprintf(cur[n].name, sizeof cur[n].name, "tid %lu", te.th32ThreadID);
|
||||
for (int i = 0; i < ng; i++)
|
||||
if (GetThreadId(gh[i]) == te.th32ThreadID) { snprintf(cur[n].name, sizeof cur[n].name, "%s", gn[i]); break; }
|
||||
if (!strncmp(cur[n].name, "tid ", 4)) {
|
||||
PWSTR d = NULL;
|
||||
if (SUCCEEDED(GetThreadDescription(h, &d)) && d && d[0])
|
||||
WideCharToMultiByte(CP_UTF8, 0, d, -1, cur[n].name, sizeof cur[n].name, NULL, NULL);
|
||||
if (d) LocalFree(d);
|
||||
}
|
||||
n++;
|
||||
}
|
||||
CloseHandle(h);
|
||||
}
|
||||
CloseHandle(snap);
|
||||
for (int i = 0; i < n && i < MAXT; i++) ids[i] = cur[i].id, was[i] = cur[i].cpu;
|
||||
nwas = n;
|
||||
for (int i = 0; i < n; i++) /* (busiest first) */
|
||||
for (int j = i + 1; j < n; j++)
|
||||
if (cur[j].delta > cur[i].delta) { char t[sizeof cur[0]]; memcpy(t, &cur[i], sizeof t); memcpy(&cur[i], &cur[j], sizeof t); memcpy(&cur[j], t, sizeof t); }
|
||||
char line[1024];
|
||||
int len = snprintf(line, sizeof line, "prof: busiest threads (%% of a core):");
|
||||
uint64_t total = 0;
|
||||
for (int i = 0; i < n; i++) total += cur[i].delta;
|
||||
for (int i = 0; i < n && i < 10 && len < (int)sizeof line - 80; i++)
|
||||
len += snprintf(line + len, sizeof line - len, " %s %.0f,", cur[i].name, cur[i].delta / (ms * 100.0));
|
||||
snprintf(line + len, sizeof line - len, " all %.0f", total / (ms * 100.0));
|
||||
hos_log("%s", line);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
/* HOS_SAMPLE=<thread name> (with HOS_PROFILE=<seconds>): that thread's instruction pointer sampled every millisecond;
|
||||
every interval the most frequent places, as module+offset of the leaf and of the first frame in mkw.exe under it
|
||||
(what of ours called into wgpu or the system). nx2/samap.py maps the mkw.exe offsets to functions. */
|
||||
static DWORD WINAPI sample_thread(void *p) {
|
||||
const char *want = (const char *)p;
|
||||
const DWORD ms = (DWORD)atoi(getenv("HOS_PROFILE")) * 1000;
|
||||
HANDLE th = NULL;
|
||||
while (!th) { /* (the renderer's threads start late) */
|
||||
Sleep(1000);
|
||||
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
|
||||
THREADENTRY32 te = {sizeof te};
|
||||
for (BOOL ok = Thread32First(snap, &te); ok && !th; ok = Thread32Next(snap, &te)) {
|
||||
if (te.th32OwnerProcessID != GetCurrentProcessId()) continue;
|
||||
HANDLE h = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);
|
||||
if (!h) continue;
|
||||
PWSTR d = NULL;
|
||||
char name[64] = "";
|
||||
if (SUCCEEDED(GetThreadDescription(h, &d)) && d) WideCharToMultiByte(CP_UTF8, 0, d, -1, name, sizeof name, NULL, NULL);
|
||||
if (d) LocalFree(d);
|
||||
if (strstr(name, want)) th = h;
|
||||
else CloseHandle(h);
|
||||
}
|
||||
CloseHandle(snap);
|
||||
}
|
||||
hos_log("prof: sampling thread \"%s\"", want);
|
||||
const HMODULE exe = GetModuleHandleA(NULL);
|
||||
enum { SLOTS = 4096 };
|
||||
static struct { uint64_t key; uint32_t n; } leaf[SLOTS], ours[SLOTS];
|
||||
static char modname[64][64];
|
||||
static HMODULE mods[64];
|
||||
int nmods = 0;
|
||||
uint32_t total = 0;
|
||||
DWORD last = GetTickCount();
|
||||
/* HOS_SAMPLE_FILE=<path>: every sample's whole stack too, one line of module+offset frames (leaf first), for
|
||||
an offline profile (work/prof.py maps them to functions with the linker maps) */
|
||||
FILE *stacks = getenv("HOS_SAMPLE_FILE") ? fopen(getenv("HOS_SAMPLE_FILE"), "w") : NULL;
|
||||
for (;;) {
|
||||
Sleep(1);
|
||||
if (SuspendThread(th) == (DWORD)-1) return 0; /* (the thread ended) */
|
||||
CONTEXT ctx = {0};
|
||||
ctx.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
|
||||
const BOOL got = GetThreadContext(th, &ctx);
|
||||
uint64_t keys[2] = {0, 0};
|
||||
char stack_line[1024];
|
||||
int stack_len = 0;
|
||||
if (got) {
|
||||
for (int depth = 0; depth < 48 && ctx.Rip; depth++) {
|
||||
HMODULE m = NULL;
|
||||
GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||
(LPCSTR)ctx.Rip, &m);
|
||||
int mi = -1;
|
||||
for (int i = 0; i < nmods; i++) if (mods[i] == m) mi = i;
|
||||
if (mi < 0 && nmods < 64) {
|
||||
mi = nmods++;
|
||||
mods[mi] = m;
|
||||
char path[MAX_PATH] = "?";
|
||||
if (m) GetModuleFileNameA(m, path, MAX_PATH);
|
||||
const char *b = strrchr(path, '\\');
|
||||
snprintf(modname[mi], sizeof modname[mi], "%s", b ? b + 1 : path);
|
||||
}
|
||||
const uint64_t key = (uint64_t)(mi < 0 ? 63 : mi) << 56 | (ctx.Rip - (uint64_t)m);
|
||||
if (stacks && stack_len < (int)sizeof stack_line - 96)
|
||||
stack_len += snprintf(stack_line + stack_len, sizeof stack_line - stack_len, "%s%s+%llx",
|
||||
depth ? ";" : "", mi < 0 ? "?" : modname[mi],
|
||||
(unsigned long long)(ctx.Rip - (uint64_t)m));
|
||||
if (depth == 0) keys[0] = key;
|
||||
if (m == exe && !keys[1]) keys[1] = key;
|
||||
if (m == exe && !stacks) break;
|
||||
DWORD64 image = 0;
|
||||
PRUNTIME_FUNCTION f = RtlLookupFunctionEntry(ctx.Rip, &image, NULL);
|
||||
if (!f) break;
|
||||
void *hd;
|
||||
DWORD64 frame;
|
||||
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, ctx.Rip, f, &ctx, &hd, &frame, NULL);
|
||||
}
|
||||
}
|
||||
ResumeThread(th);
|
||||
if (stacks && got && stack_len) fprintf(stacks, "%s\n", stack_line);
|
||||
if (got) {
|
||||
total++;
|
||||
for (int t = 0; t < 2; t++) {
|
||||
if (!keys[t]) continue;
|
||||
typeof(leaf[0]) *tab = t ? ours : leaf;
|
||||
for (uint32_t s = (uint32_t)(keys[t] * 0x9E3779B97F4A7C15ull >> 52), k = 0; k < SLOTS; k++, s = (s + 1) % SLOTS) {
|
||||
if (tab[s].key == keys[t]) { tab[s].n++; break; }
|
||||
if (!tab[s].key) { tab[s].key = keys[t], tab[s].n = 1; break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (GetTickCount() - last >= ms) {
|
||||
last = GetTickCount();
|
||||
for (int t = 0; t < 2; t++) {
|
||||
typeof(leaf[0]) *tab = t ? ours : leaf;
|
||||
char line[2048];
|
||||
int len = snprintf(line, sizeof line, "prof-sample %s (%u samples):", t ? "ours" : "leaf", total);
|
||||
for (int r = 0; r < 30 && len < (int)sizeof line - 64; r++) {
|
||||
int best = -1;
|
||||
for (int s = 0; s < SLOTS; s++) if (tab[s].n && (best < 0 || tab[s].n > tab[best].n)) best = s;
|
||||
if (best < 0) break;
|
||||
len += snprintf(line + len, sizeof line - len, " %s+%llx %u,", modname[tab[best].key >> 56],
|
||||
(unsigned long long)(tab[best].key & ((1ull << 56) - 1)), tab[best].n);
|
||||
tab[best].n = 0;
|
||||
}
|
||||
hos_log("%s", line);
|
||||
memset(tab, 0, sizeof leaf);
|
||||
}
|
||||
total = 0;
|
||||
if (stacks) fflush(stacks);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* HOS_THREAD_TIMES=<seconds>: every interval, the process's threads that used over 5% of a core, by name, with
|
||||
their share of one core (which thread holds the frame back) */
|
||||
static DWORD WINAPI thread_times_thread(void *p) {
|
||||
const DWORD ms = (DWORD)(uintptr_t)p * 1000;
|
||||
enum { MAX = 512 };
|
||||
static struct { DWORD tid; uint64_t cpu; } last[MAX];
|
||||
int nlast = 0;
|
||||
for (;;) {
|
||||
Sleep(ms);
|
||||
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
|
||||
THREADENTRY32 te = {sizeof te};
|
||||
char line[4096];
|
||||
int n = snprintf(line, sizeof line, "threads in %u s:", (unsigned)(ms / 1000));
|
||||
static struct { DWORD tid; uint64_t cpu; } now[MAX];
|
||||
int nnow = 0;
|
||||
for (BOOL ok = Thread32First(snap, &te); ok; ok = Thread32Next(snap, &te)) {
|
||||
if (te.th32OwnerProcessID != GetCurrentProcessId() || nnow >= MAX) continue;
|
||||
HANDLE h = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, FALSE, te.th32ThreadID);
|
||||
if (!h) continue;
|
||||
FILETIME c, x, k, u;
|
||||
uint64_t cpu = 0;
|
||||
if (GetThreadTimes(h, &c, &x, &k, &u))
|
||||
cpu = (((uint64_t)k.dwHighDateTime << 32) | k.dwLowDateTime) + (((uint64_t)u.dwHighDateTime << 32) | u.dwLowDateTime);
|
||||
uint64_t before = 0;
|
||||
int seen = 0;
|
||||
for (int i = 0; i < nlast; i++)
|
||||
if (last[i].tid == te.th32ThreadID) before = last[i].cpu, seen = 1;
|
||||
now[nnow].tid = te.th32ThreadID, now[nnow].cpu = cpu, nnow++;
|
||||
const double pct = seen ? (double)(cpu - before) / (ms * 10000.0) * 100.0 : 0;
|
||||
if (pct >= 5.0 && n < (int)sizeof line - 96) {
|
||||
PWSTR d = NULL;
|
||||
char name[64] = "?";
|
||||
if (SUCCEEDED(GetThreadDescription(h, &d)) && d && d[0]) WideCharToMultiByte(CP_UTF8, 0, d, -1, name, sizeof name, NULL, NULL);
|
||||
if (d) LocalFree(d);
|
||||
n += snprintf(line + n, sizeof line - n, " %s %.0f%%;", name, pct);
|
||||
}
|
||||
CloseHandle(h);
|
||||
}
|
||||
CloseHandle(snap);
|
||||
memcpy(last, now, sizeof(now[0]) * (size_t)nnow);
|
||||
nlast = nnow;
|
||||
hos_log("prof: %s", line);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* (hookshot) HOS_SAMPLE_ALL=<path> (with HOS_PROFILE): while <path>.go exists, every 2 ms every guest thread and the
|
||||
renderer's threads (descriptions starting "mkw_vk") are sampled at the same instant: one line per thread,
|
||||
"<ms> <name>|<frames>", the frames module+offset leaf first (16 at most). What each thread does while another waits:
|
||||
the frame's critical path (scripts/crit.py) */
|
||||
/* HOS_WATCH=<file> (diagnostic): when <file> exists (up to 4 guest addresses in hex), CPU data breakpoints on them on
|
||||
every guest thread: 4 s on reads and writes, then 4 s on writes; <file>.out gets, by address and the host place of
|
||||
the access, how many; then <file> is renamed <file>.done and the next one may come. */
|
||||
static uint64_t watch_keys[8192];
|
||||
static volatile LONG watch_counts[8192];
|
||||
static volatile LONG watch_phase;
|
||||
static LONG CALLBACK watch_handler(EXCEPTION_POINTERS *e) {
|
||||
if (e->ExceptionRecord->ExceptionCode != EXCEPTION_SINGLE_STEP) return EXCEPTION_CONTINUE_SEARCH;
|
||||
const DWORD64 hit = e->ContextRecord->Dr6 & 15;
|
||||
if (!hit) return EXCEPTION_CONTINUE_SEARCH;
|
||||
int idx = 0;
|
||||
while (!(hit >> idx & 1)) idx++;
|
||||
const uint64_t key = ((uint64_t)(watch_phase & 1) << 62) | ((uint64_t)idx << 58) | (uint64_t)e->ExceptionRecord->ExceptionAddress;
|
||||
for (uint32_t i = (uint32_t)((key >> 2) * 2654435761u) & 8191, n = 0; n < 8192; n++, i = (i + 1) & 8191) {
|
||||
uint64_t k = __atomic_load_n(&watch_keys[i], __ATOMIC_RELAXED);
|
||||
if (!k) {
|
||||
uint64_t expect = 0;
|
||||
if (__atomic_compare_exchange_n(&watch_keys[i], &expect, key, 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED)) k = key;
|
||||
else k = expect;
|
||||
}
|
||||
if (k == key) { InterlockedIncrement(&watch_counts[i]); break; }
|
||||
}
|
||||
e->ContextRecord->Dr6 = 0;
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
static void watch_arm(const uint64_t *addr, int n, int rw) {
|
||||
static HANDLE gh[1024];
|
||||
static const char *gn[1024];
|
||||
const int ng = hos_thread_handles(gh, gn, 1024);
|
||||
for (int i = 0; i < ng; i++) {
|
||||
if (GetThreadId(gh[i]) == GetCurrentThreadId()) continue;
|
||||
if (SuspendThread(gh[i]) == (DWORD)-1) continue;
|
||||
CONTEXT c;
|
||||
memset(&c, 0, sizeof c);
|
||||
c.ContextFlags = CONTEXT_DEBUG_REGISTERS;
|
||||
if (GetThreadContext(gh[i], &c)) {
|
||||
DWORD64 *dr[4] = {&c.Dr0, &c.Dr1, &c.Dr2, &c.Dr3};
|
||||
c.Dr7 = 0;
|
||||
for (int k = 0; k < n && rw; k++) {
|
||||
*dr[k] = (DWORD64)GP(addr[k]);
|
||||
c.Dr7 |= (DWORD64)1 << (k * 2); /* (local enable) */
|
||||
c.Dr7 |= (DWORD64)((rw & 3) | (3 << 2)) << (16 + k * 4); /* (rw, 4 bytes) */
|
||||
}
|
||||
c.Dr6 = 0;
|
||||
SetThreadContext(gh[i], &c);
|
||||
}
|
||||
ResumeThread(gh[i]);
|
||||
}
|
||||
}
|
||||
static DWORD WINAPI watch_thread(void *p) {
|
||||
const char *path = (const char *)p;
|
||||
AddVectoredExceptionHandler(1, watch_handler);
|
||||
for (;;) {
|
||||
Sleep(300);
|
||||
FILE *f = fopen(path, "r");
|
||||
if (!f) continue;
|
||||
uint64_t addr[4];
|
||||
int n = 0;
|
||||
unsigned long long v;
|
||||
while (n < 4 && fscanf(f, "%llx", &v) == 1) addr[n++] = v;
|
||||
fclose(f);
|
||||
memset(watch_keys, 0, sizeof watch_keys);
|
||||
memset((void *)watch_counts, 0, sizeof watch_counts);
|
||||
for (int k = 0; k < n; k++) hos_log("watch: %llx holds %08x", (unsigned long long)addr[k], *(uint32_t *)GP(addr[k]));
|
||||
for (int ph = 0; ph < 2; ph++) {
|
||||
watch_phase = ph;
|
||||
for (int t = 0; t < 4; t++) { /* (threads that started since) */
|
||||
watch_arm(addr, n, ph ? 1 : 3);
|
||||
Sleep(1000);
|
||||
}
|
||||
}
|
||||
watch_arm(addr, 0, 0);
|
||||
char out[MAX_PATH], done[MAX_PATH];
|
||||
snprintf(out, sizeof out, "%s.out", path);
|
||||
snprintf(done, sizeof done, "%s.done", path);
|
||||
f = fopen(out, "a");
|
||||
if (f) {
|
||||
for (int i = 0; i < 8192; i++)
|
||||
if (watch_keys[i]) {
|
||||
const uint64_t k = watch_keys[i], rip = k & ((1ULL << 58) - 1);
|
||||
HMODULE m = NULL;
|
||||
char full[MAX_PATH] = "?";
|
||||
GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCSTR)rip, &m);
|
||||
if (m) GetModuleFileNameA(m, full, sizeof full);
|
||||
const char *name = strrchr(full, 92) ? strrchr(full, 92) + 1 : full;
|
||||
fprintf(f, "%llx %s %s+%llx %ld\n", (unsigned long long)addr[(k >> 58) & 3], k >> 62 & 1 ? "w" : "rw", name,
|
||||
(unsigned long long)(rip - (uint64_t)m), watch_counts[i]);
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
DeleteFileA(done);
|
||||
MoveFileA(path, done);
|
||||
hos_log("watch: done");
|
||||
}
|
||||
}
|
||||
static DWORD WINAPI sample_all_thread(void *p) {
|
||||
const char *path = (const char *)p;
|
||||
char go[MAX_PATH];
|
||||
snprintf(go, sizeof go, "%s.go", path);
|
||||
FILE *out = NULL;
|
||||
static HMODULE mods[64];
|
||||
static char modname[64][64];
|
||||
int nmods = 0;
|
||||
enum { MAXT = 128 };
|
||||
static HANDLE th[MAXT];
|
||||
static char tn[MAXT][64];
|
||||
int nt = 0;
|
||||
int64_t t0 = 0;
|
||||
for (;;) {
|
||||
if (GetFileAttributesA(go) == INVALID_FILE_ATTRIBUTES) {
|
||||
if (out) { fclose(out); out = NULL; hos_log("prof: all-thread sampling stopped"); }
|
||||
Sleep(200);
|
||||
continue;
|
||||
}
|
||||
if (!out) {
|
||||
out = fopen(path, "a");
|
||||
if (!out) { Sleep(1000); continue; }
|
||||
for (int i = 0; i < nt; i++) CloseHandle(th[i]);
|
||||
nt = 0;
|
||||
static HANDLE gh[1024];
|
||||
static const char *gn[1024];
|
||||
const int ng = hos_thread_handles(gh, gn, 1024);
|
||||
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
|
||||
THREADENTRY32 te = {sizeof te};
|
||||
for (BOOL ok = Thread32First(snap, &te); ok && nt < MAXT; ok = Thread32Next(snap, &te)) {
|
||||
if (te.th32OwnerProcessID != GetCurrentProcessId() || te.th32ThreadID == GetCurrentThreadId()) continue;
|
||||
char name[64] = "";
|
||||
for (int i = 0; i < ng; i++)
|
||||
if (GetThreadId(gh[i]) == te.th32ThreadID) { snprintf(name, sizeof name, "%s", gn[i]); break; }
|
||||
HANDLE h = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);
|
||||
if (!h) continue;
|
||||
if (!name[0]) {
|
||||
PWSTR d = NULL;
|
||||
char desc[64] = "";
|
||||
if (SUCCEEDED(GetThreadDescription(h, &d)) && d) WideCharToMultiByte(CP_UTF8, 0, d, -1, desc, sizeof desc, NULL, NULL);
|
||||
if (d) LocalFree(d);
|
||||
if (!strncmp(desc, "mkw_vk", 6)) snprintf(name, sizeof name, "%s", desc);
|
||||
}
|
||||
if (!name[0]) { CloseHandle(h); continue; }
|
||||
for (char *q = name; *q; q++) if (*q == ' ' || *q == '|') *q = '_';
|
||||
th[nt] = h;
|
||||
snprintf(tn[nt], sizeof tn[nt], "%s", name);
|
||||
nt++;
|
||||
}
|
||||
CloseHandle(snap);
|
||||
t0 = hos_now_ns();
|
||||
hos_log("prof: all-thread sampling of %d threads into %s", nt, path);
|
||||
}
|
||||
Sleep(2);
|
||||
const long ms = (long)((hos_now_ns() - t0) / 1000000);
|
||||
for (int i = 0; i < nt; i++) {
|
||||
if (SuspendThread(th[i]) == (DWORD)-1) continue;
|
||||
CONTEXT ctx = {0};
|
||||
ctx.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
|
||||
const BOOL got = GetThreadContext(th[i], &ctx);
|
||||
char line[1024];
|
||||
int len = snprintf(line, sizeof line, "%ld %s|", ms, tn[i]);
|
||||
for (int depth = 0; got && depth < 16 && ctx.Rip && len < (int)sizeof line - 96; depth++) {
|
||||
HMODULE m = NULL;
|
||||
GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||
(LPCSTR)ctx.Rip, &m);
|
||||
int mi = -1;
|
||||
for (int k = 0; k < nmods; k++) if (mods[k] == m) mi = k;
|
||||
if (mi < 0 && nmods < 64) {
|
||||
mi = nmods++;
|
||||
mods[mi] = m;
|
||||
char mp[MAX_PATH] = "?";
|
||||
if (m) GetModuleFileNameA(m, mp, MAX_PATH);
|
||||
const char *b = strrchr(mp, '\\');
|
||||
snprintf(modname[mi], sizeof modname[mi], "%s", b ? b + 1 : mp);
|
||||
}
|
||||
len += snprintf(line + len, sizeof line - len, "%s%s+%llx", depth ? ";" : "", mi < 0 ? "?" : modname[mi],
|
||||
(unsigned long long)(ctx.Rip - (uint64_t)m));
|
||||
DWORD64 image = 0;
|
||||
PRUNTIME_FUNCTION f = RtlLookupFunctionEntry(ctx.Rip, &image, NULL);
|
||||
if (!f) break;
|
||||
void *hd;
|
||||
DWORD64 frame;
|
||||
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, ctx.Rip, f, &ctx, &hd, &frame, NULL);
|
||||
}
|
||||
ResumeThread(th[i]);
|
||||
fprintf(out, "%s\n", line);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void hos_prof_start(void) {
|
||||
const char *tt = getenv("HOS_THREAD_TIMES");
|
||||
if (tt && atoi(tt) > 0) CreateThread(NULL, 0, thread_times_thread, (void *)(uintptr_t)atoi(tt), 0, NULL);
|
||||
const char *e = getenv("HOS_PROFILE");
|
||||
if (e && atoi(e) > 0) CreateThread(NULL, 0, prof_thread, (void *)(uintptr_t)atoi(e), 0, NULL);
|
||||
const char *s = getenv("HOS_SAMPLE");
|
||||
if (e && atoi(e) > 0 && s && *s) CreateThread(NULL, 0, sample_thread, (void *)s, 0, NULL);
|
||||
const char *all = getenv("HOS_SAMPLE_ALL");
|
||||
if (all && *all) CreateThread(NULL, 0, sample_all_thread, (void *)all, 0, NULL);
|
||||
const char *watch = getenv("HOS_WATCH");
|
||||
if (watch && *watch) CreateThread(NULL, 0, watch_thread, (void *)watch, 0, NULL);
|
||||
}
|
||||
#endif /* (linux) host/posix/prof.c */
|
||||
void hos_mem_checkpoint(const char *what) { (void)what; } /* (hos_prof.c: HOS_MEM_TIMELINE) */
|
||||
int hos_game_cores(void) { return 0; } /* (totk_cores.c) */
|
||||
int hos_blank_cached_icon(const char *guest, const char *host) { (void)guest, (void)host; return 0; } /* (TOTK) */
|
||||
int hos_ultrawide_redirect(const char *guest, char *out, size_t cap) { (void)guest, (void)out, (void)cap; return 0; }
|
||||
uint64_t hos_title_input(uint64_t buttons) { return buttons; } /* (totk_title.c) */
|
||||
uint64_t hos_frame_step_buttons(uint64_t buttons) { return buttons; } /* (nn_vi.c) */
|
||||
/* (hookshot) hos_sdl_pads, hos_sdl_rumble: host/pad_sdl.c (from TOTKPort; SDL2.dll beside the exe) */
|
||||
|
||||
/* TOTK's emulated GPU (gpu.c, its Maxwell command processor), which nvdrv.c and the debug commands call into: MKW
|
||||
has none (its NVN2 calls go to nvn_native.c), so a submission is only counted. */
|
||||
int hos_gpu_async(void) { return 0; }
|
||||
void hos_gpu_submit(int channel_fd, const uint64_t *entries, uint32_t n) {
|
||||
static volatile LONG seen;
|
||||
if (InterlockedIncrement(&seen) <= 4) hos_log("gpu: submit of %u entries on channel %d (no GPU yet)", n, channel_fd);
|
||||
(void)entries;
|
||||
}
|
||||
void hos_gpu_queue_submit(int channel_fd, const uint64_t *entries, uint32_t n, int incr_id) {
|
||||
(void)incr_id;
|
||||
hos_gpu_submit(channel_fd, entries, n);
|
||||
}
|
||||
|
||||
/* The loop-header interrupt polls (nx2/poll.py): the virtual cores (HOS_VCORES) ask a thread holding a core a
|
||||
waiter should have to give it up there, so guest code with no nn::os call or SVC in it (a long job) is preempted
|
||||
as Horizon would preempt it. */
|
||||
/* (nx2/rtgen.py) the loop-header poll: the lifted code has cleared c->poll and calls this with no argument, so that the
|
||||
compiler keeps guest registers in host registers across the loop header (a call handed the context could change any
|
||||
of it). The thread's context is the running one's (hos_ctx: a fiber's while it runs one), which is where the kick
|
||||
(hos_thread.c) set the flag; nothing here reads it */
|
||||
void a64_poll_cur(void) {
|
||||
void hos_vcore_checkpoint(void);
|
||||
hos_vcore_checkpoint();
|
||||
}
|
||||
void a64_poll(Ctx *c) { /* (the old form, A64_POLL_CTX builds) */
|
||||
c->poll = 0;
|
||||
a64_poll_cur();
|
||||
}
|
||||
|
||||
/* CNTPCT_EL0 at the Switch 2's 31.25 MHz (rt/a64_rt.c's default counts the Switch 1's 19.2 MHz). The SDK checks
|
||||
nn::os::GetSystemTickFrequency against 31250000 at init and aborts otherwise. */
|
||||
uint64_t a64_cntpct_host(void) {
|
||||
static LARGE_INTEGER base;
|
||||
static uint64_t mult;
|
||||
LARGE_INTEGER now;
|
||||
if (!__atomic_load_n(&mult, __ATOMIC_ACQUIRE)) {
|
||||
LARGE_INTEGER f, b;
|
||||
QueryPerformanceFrequency(&f);
|
||||
QueryPerformanceCounter(&b);
|
||||
base = b;
|
||||
__atomic_store_n(&mult, (HOS_TICK_HZ << 32) / (uint64_t)f.QuadPart, __ATOMIC_RELEASE);
|
||||
}
|
||||
QueryPerformanceCounter(&now);
|
||||
return (uint64_t)(((unsigned __int128)(uint64_t)(now.QuadPart - base.QuadPart) * mult) >> 32);
|
||||
}
|
||||
|
||||
/* ---- what the renderer (gpu/render, TOTKPort's) asks of TOTKPort's hos_prof.c and totk_ultrawide.c ---- */
|
||||
int hos_ab(void) { return 0; } /* (hos_prof.c: A/B measurement phases) */
|
||||
/* (with the renderer's mem: lines) HOS_MEM_MAP=1: how much of the guest window is committed, and its resident part */
|
||||
void hos_memory_map_log(void) {
|
||||
static int on = -1;
|
||||
if (on < 0) on = getenv("HOS_MEM_MAP") != NULL;
|
||||
if (!on) return;
|
||||
uint64_t committed = 0, regions = 0;
|
||||
for (uint64_t a = 0; a < HOS_GUEST_SPACE;) {
|
||||
MEMORY_BASIC_INFORMATION m;
|
||||
if (!VirtualQuery(GP(a), &m, sizeof m)) break;
|
||||
const uint64_t end = (uint64_t)((uint8_t *)m.BaseAddress + m.RegionSize - (uint8_t *)GP(0));
|
||||
if (m.State == MEM_COMMIT) committed += m.RegionSize, regions++;
|
||||
a = end > a ? end : a + 0x1000;
|
||||
}
|
||||
hos_log("mem: guest window %llu MB committed in %llu regions", (unsigned long long)(committed >> 20),
|
||||
(unsigned long long)regions);
|
||||
/* the rest of the address space: private memory by allocation, the largest */
|
||||
struct { uint64_t base, bytes; } top[8] = {{0}};
|
||||
uint64_t other = 0, cur_base = 0, cur = 0;
|
||||
const uint64_t g0 = (uint64_t)(uintptr_t)GP(0), g1 = g0 + HOS_GUEST_SPACE;
|
||||
for (uint64_t a = 0x10000; a < 0x7FFFFFFF0000ull;) {
|
||||
MEMORY_BASIC_INFORMATION m;
|
||||
if (!VirtualQuery((void *)(uintptr_t)a, &m, sizeof m)) break;
|
||||
const uint64_t base = (uint64_t)(uintptr_t)m.AllocationBase, end = (uint64_t)(uintptr_t)m.BaseAddress + m.RegionSize;
|
||||
if (base != cur_base) {
|
||||
for (int k = 0; k < 8 && cur; k++)
|
||||
if (cur > top[k].bytes) {
|
||||
memmove(&top[k + 1], &top[k], (size_t)(7 - k) * sizeof top[0]);
|
||||
top[k].base = cur_base, top[k].bytes = cur;
|
||||
break;
|
||||
}
|
||||
cur_base = base, cur = 0;
|
||||
}
|
||||
if (m.State == MEM_COMMIT && m.Type == MEM_PRIVATE && (a < g0 || a >= g1)) other += m.RegionSize, cur += m.RegionSize;
|
||||
a = end > a ? end : a + 0x1000;
|
||||
}
|
||||
hos_log("mem: private outside the guest window %llu MB; largest: %llx %llu MB, %llx %llu MB, %llx %llu MB, %llx %llu "
|
||||
"MB, %llx %llu MB, %llx %llu MB", (unsigned long long)(other >> 20), (unsigned long long)top[0].base,
|
||||
(unsigned long long)(top[0].bytes >> 20), (unsigned long long)top[1].base, (unsigned long long)(top[1].bytes >> 20),
|
||||
(unsigned long long)top[2].base, (unsigned long long)(top[2].bytes >> 20), (unsigned long long)top[3].base,
|
||||
(unsigned long long)(top[3].bytes >> 20), (unsigned long long)top[4].base, (unsigned long long)(top[4].bytes >> 20),
|
||||
(unsigned long long)top[5].base, (unsigned long long)(top[5].bytes >> 20));
|
||||
}
|
||||
void hos_ultrawide_apply(void) {} /* (totk_ultrawide.c) */
|
||||
float hos_view_aspect; /* (totk_ultrawide.c: 0, the game's own 16:9) */
|
||||
void hos_host_thread_register_self(const char *name) { /* (hos_prof.c: names for its stats; here the thread's description) */
|
||||
wchar_t w[64];
|
||||
if (MultiByteToWideChar(CP_UTF8, 0, name, -1, w, 64)) SetThreadDescription(GetCurrentThread(), w);
|
||||
}
|
||||
void hos_process_memory(uint64_t *private_bytes, uint64_t *working_set) {
|
||||
typedef struct {
|
||||
DWORD cb, PageFaultCount;
|
||||
SIZE_T PeakWorkingSetSize, WorkingSetSize, QuotaPeakPagedPoolUsage, QuotaPagedPoolUsage,
|
||||
QuotaPeakNonPagedPoolUsage, QuotaNonPagedPoolUsage, PagefileUsage, PeakPagefileUsage, PrivateUsage;
|
||||
} Counters;
|
||||
typedef BOOL(WINAPI * Fn)(HANDLE, Counters *, DWORD);
|
||||
static Fn fn;
|
||||
if (!fn) fn = (Fn)(void *)GetProcAddress(GetModuleHandleA("kernel32.dll"), "K32GetProcessMemoryInfo");
|
||||
Counters m;
|
||||
memset(&m, 0, sizeof m);
|
||||
m.cb = sizeof m;
|
||||
if (!fn || !fn(GetCurrentProcess(), &m, sizeof m)) memset(&m, 0, sizeof m);
|
||||
*private_bytes = m.PrivateUsage;
|
||||
*working_set = m.WorkingSetSize;
|
||||
}
|
||||
234
host/mods.c
Normal file
234
host/mods.c
Normal file
@@ -0,0 +1,234 @@
|
||||
/* Mods, in the layout emulators use, so RomFS mods made for them work as they are:
|
||||
<mods>/<name>/romfs/... files that replace (or add to) the game's RomFS
|
||||
<mods> is the "mods" folder beside the executable, or HOS_MODS=<dir>. A mod may sit deeper, as emulators keep them
|
||||
(<mods>/contents/<title id>/<name>/romfs): any folder holding a romfs or exefs folder is a mod. Folders whose names
|
||||
start with '-' or '_' are left out (off). When two mods have the same file, the one whose path sorts last wins (name
|
||||
them 01-..., 02-... to order them).
|
||||
Every mod file is indexed once at the start (no disk lookups per open); nn_fs.c asks hos_mods_romfs for each rom:
|
||||
path and lists a folder's mod-only entries with the game's own (hos_mods_dir_extras). HOS_FS_OVERLAY (nn_fs.c) is
|
||||
looked at after this, so a test overlay wins over mods.
|
||||
exefs patches (.pchtxt, .ips) are not applied: the code is compiled ahead of time from the original instructions, and
|
||||
the game folder has no module map (image.json) to place data patches with. A mod's exefs folder is logged as left out.
|
||||
From Skybound's loader (NotRexed/SkyboundTotk a64-kit/hos/mods.c, MIT): its RomFS part. */
|
||||
#include "hos.h"
|
||||
#include "hos_paths.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <ctype.h>
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
|
||||
typedef struct { char *key; char *host; uint64_t size; int is_dir, logged; } Entry; /* key: romfs path, lower case, '/' */
|
||||
static Entry *table;
|
||||
static size_t table_cap, table_n;
|
||||
|
||||
static uint64_t hash_str(const char *s) {
|
||||
uint64_t h = 0xcbf29ce484222325ull;
|
||||
for (; *s; s++) h = (h ^ (uint8_t)*s) * 0x100000001b3ull;
|
||||
return h;
|
||||
}
|
||||
static void lower_slash(char *s) {
|
||||
for (; *s; s++) *s = *s == '\\' ? '/' : (char)tolower((unsigned char)*s);
|
||||
}
|
||||
static const char *last_sep(const char *s) { /* (a host path: '\' on Windows, '/' from host/posix) */
|
||||
const char *b = strrchr(s, '\\'), *f = strrchr(s, '/');
|
||||
return b > f ? b : f;
|
||||
}
|
||||
static Entry *find(const char *key) {
|
||||
if (!table_cap) return NULL;
|
||||
for (size_t i = hash_str(key) & (table_cap - 1);; i = (i + 1) & (table_cap - 1)) {
|
||||
if (!table[i].key) return NULL;
|
||||
if (!strcmp(table[i].key, key)) return &table[i];
|
||||
}
|
||||
}
|
||||
static void put(const char *key, const char *host, uint64_t size, int is_dir) {
|
||||
if ((table_n + 1) * 2 > table_cap) { /* (grow: rehash) */
|
||||
Entry *old = table;
|
||||
const size_t old_cap = table_cap;
|
||||
table_cap = table_cap ? table_cap * 2 : 1024;
|
||||
table = (Entry *)calloc(table_cap, sizeof *table);
|
||||
table_n = 0;
|
||||
for (size_t i = 0; i < old_cap; i++)
|
||||
if (old[i].key) {
|
||||
size_t j = hash_str(old[i].key) & (table_cap - 1);
|
||||
while (table[j].key) j = (j + 1) & (table_cap - 1);
|
||||
table[j] = old[i];
|
||||
table_n++;
|
||||
}
|
||||
free(old);
|
||||
}
|
||||
size_t i = hash_str(key) & (table_cap - 1);
|
||||
while (table[i].key && strcmp(table[i].key, key)) i = (i + 1) & (table_cap - 1);
|
||||
if (!table[i].key) table[i].key = _strdup(key), table_n++;
|
||||
else free(table[i].host);
|
||||
table[i].host = _strdup(host);
|
||||
table[i].size = size;
|
||||
table[i].is_dir = is_dir;
|
||||
}
|
||||
|
||||
/* a mod's romfs folder, recursively: rel is the path inside the RomFS so far ("" at its root) */
|
||||
static int index_romfs(const char *host_dir, const char *rel, int depth) {
|
||||
if (depth > 32) return 0; /* (hookshot: no RomFS is this deep) */
|
||||
if (!depth) { /* (hookshot) the romfs folder itself a link (to / in a mod's archive): the walk covered the whole disk */
|
||||
const DWORD at = GetFileAttributesA(host_dir);
|
||||
if (at != INVALID_FILE_ATTRIBUTES && (at & FILE_ATTRIBUTE_REPARSE_POINT)) {
|
||||
hos_log("mods: %s is a link to a folder: left out", host_dir);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
char pat[MAX_PATH];
|
||||
snprintf(pat, sizeof pat, "%s\\*", host_dir);
|
||||
WIN32_FIND_DATAA fd;
|
||||
HANDLE f = FindFirstFileA(pat, &fd);
|
||||
if (f == INVALID_HANDLE_VALUE) return 0;
|
||||
int files = 0;
|
||||
do {
|
||||
if (!strcmp(fd.cFileName, ".") || !strcmp(fd.cFileName, "..")) continue;
|
||||
char host[MAX_PATH], key[MAX_PATH];
|
||||
snprintf(host, sizeof host, "%s\\%s", host_dir, fd.cFileName);
|
||||
/* (hookshot) a link to a folder is not followed (two links back up made the walk endless); links to files are
|
||||
(mod managers place files as links) */
|
||||
if ((fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) && (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
|
||||
hos_log("mods: %s is a link to a folder: left out", host);
|
||||
continue;
|
||||
}
|
||||
snprintf(key, sizeof key, "%s%s%s", rel, *rel ? "/" : "", fd.cFileName);
|
||||
lower_slash(key);
|
||||
const int is_dir = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
|
||||
put(key, host, ((uint64_t)fd.nFileSizeHigh << 32) | fd.nFileSizeLow, is_dir);
|
||||
if (is_dir) {
|
||||
char sub_rel[MAX_PATH];
|
||||
snprintf(sub_rel, sizeof sub_rel, "%s%s%s", rel, *rel ? "/" : "", fd.cFileName);
|
||||
files += index_romfs(host, sub_rel, depth + 1);
|
||||
} else {
|
||||
files++;
|
||||
}
|
||||
} while (FindNextFileA(f, &fd));
|
||||
FindClose(f);
|
||||
return files;
|
||||
}
|
||||
|
||||
/* the mod folders under root, sorted (a mod: a folder holding romfs or exefs) */
|
||||
typedef struct { char path[MAX_PATH]; char name[MAX_PATH]; } Mod;
|
||||
static Mod *mods;
|
||||
static int nmods, cap_mods;
|
||||
static void find_mods(const char *dir, const char *name, int depth) {
|
||||
char probe[MAX_PATH];
|
||||
snprintf(probe, sizeof probe, "%s\\romfs", dir);
|
||||
const int has_romfs = GetFileAttributesA(probe) != INVALID_FILE_ATTRIBUTES;
|
||||
snprintf(probe, sizeof probe, "%s\\exefs", dir);
|
||||
const int has_exefs = GetFileAttributesA(probe) != INVALID_FILE_ATTRIBUTES;
|
||||
if ((has_romfs || has_exefs) && depth > 0) {
|
||||
if (nmods == cap_mods) mods = (Mod *)realloc(mods, sizeof *mods * (size_t)(cap_mods = cap_mods ? cap_mods * 2 : 16));
|
||||
snprintf(mods[nmods].path, MAX_PATH, "%s", dir);
|
||||
snprintf(mods[nmods].name, MAX_PATH, "%s", name);
|
||||
nmods++;
|
||||
return;
|
||||
}
|
||||
if (depth >= 4) return;
|
||||
char pat[MAX_PATH];
|
||||
snprintf(pat, sizeof pat, "%s\\*", dir);
|
||||
WIN32_FIND_DATAA fd;
|
||||
HANDLE f = FindFirstFileA(pat, &fd);
|
||||
if (f == INVALID_HANDLE_VALUE) return;
|
||||
do {
|
||||
if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || fd.cFileName[0] == '.') continue;
|
||||
if (fd.cFileName[0] == '-' || fd.cFileName[0] == '_') {
|
||||
hos_log("mods: %s\\%s is off (its name starts with %c)", dir, fd.cFileName, fd.cFileName[0]);
|
||||
continue;
|
||||
}
|
||||
char sub[MAX_PATH], sub_name[MAX_PATH];
|
||||
snprintf(sub, sizeof sub, "%s\\%s", dir, fd.cFileName);
|
||||
snprintf(sub_name, sizeof sub_name, "%s%s%s", name, *name ? "/" : "", fd.cFileName);
|
||||
find_mods(sub, sub_name, depth + 1);
|
||||
} while (FindNextFileA(f, &fd));
|
||||
FindClose(f);
|
||||
}
|
||||
static int mod_cmp(const void *a, const void *b) { return _stricmp(((const Mod *)a)->name, ((const Mod *)b)->name); }
|
||||
|
||||
/* hos_main.c, once the image is loaded (image_path: kept for exefs patches, which are not applied here) */
|
||||
void hos_mods_init(const char *image_path) {
|
||||
(void)image_path;
|
||||
char root[MAX_PATH];
|
||||
if (getenv("HOS_MODS")) {
|
||||
snprintf(root, sizeof root, "%s", getenv("HOS_MODS"));
|
||||
} else {
|
||||
hos_game_path_a(root, sizeof root);
|
||||
char *slash = (char *)last_sep(root);
|
||||
if (!slash) return;
|
||||
snprintf(slash + 1, sizeof root - (size_t)(slash + 1 - root), "mods");
|
||||
}
|
||||
if (GetFileAttributesA(root) == INVALID_FILE_ATTRIBUTES) return;
|
||||
find_mods(root, "", 0);
|
||||
if (!nmods) {
|
||||
hos_log("mods: none in %s (a mod: <name>\\romfs)", root);
|
||||
return;
|
||||
}
|
||||
qsort(mods, (size_t)nmods, sizeof *mods, mod_cmp);
|
||||
for (int i = 0; i < nmods; i++) {
|
||||
char dir[MAX_PATH];
|
||||
snprintf(dir, sizeof dir, "%s\\romfs", mods[i].path);
|
||||
const int files = index_romfs(dir, "", 0);
|
||||
snprintf(dir, sizeof dir, "%s\\exefs", mods[i].path);
|
||||
if (GetFileAttributesA(dir) != INVALID_FILE_ATTRIBUTES)
|
||||
hos_log("mods: %s: exefs patches are left out (the code is compiled ahead of time)", mods[i].name);
|
||||
hos_log("mods: %s: %d RomFS files", mods[i].name, files);
|
||||
}
|
||||
hos_log("mods: %d mods from %s: %zu RomFS entries", nmods, root, table_n);
|
||||
}
|
||||
|
||||
/* nn_fs.c: the mod file for a RomFS path ("UI/x.zs", no mount, no leading slash), or 0 */
|
||||
int hos_mods_romfs(const char *rel, char *out, size_t cap) {
|
||||
char key[MAX_PATH];
|
||||
snprintf(key, sizeof key, "%s", rel);
|
||||
lower_slash(key);
|
||||
int hos_prompts_romfs(const char *key, char *out, size_t cap); /* prompts.c: the button prompts, where no mod has the file */
|
||||
Entry *e = table_n ? find(key) : NULL;
|
||||
if (!e || e->is_dir) return hos_prompts_romfs(key, out, cap);
|
||||
snprintf(out, cap, "%s", e->host);
|
||||
static volatile LONG logged;
|
||||
if (!e->logged && InterlockedIncrement(&logged) <= 200) hos_log("mods: %s <- %s", rel, e->host);
|
||||
e->logged = 1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* prompts.c: 1 when a mod has a file whose key (lower case, '/') starts with prefix and ends with suffix */
|
||||
int hos_mods_has(const char *prefix, const char *suffix) {
|
||||
const size_t pn = strlen(prefix), sn = strlen(suffix);
|
||||
for (size_t i = 0; i < table_cap; i++) {
|
||||
const char *k = table[i].key;
|
||||
const size_t kn = k ? strlen(k) : 0;
|
||||
if (k && !table[i].is_dir && kn >= pn + sn && !strncmp(k, prefix, pn) && !strcmp(k + kn - sn, suffix)) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* nn_fs.c, listing a RomFS folder: fn(arg, name, is_dir, size) for each mod entry directly in it that the game's own
|
||||
folder (base_dir, a host path; may not exist) does not have. Returns how many. */
|
||||
int hos_mods_dir_extras(const char *rel, const char *base_dir, void (*fn)(void *, const char *, int, uint64_t),
|
||||
void *arg) {
|
||||
if (!table_n) return 0;
|
||||
char prefix[MAX_PATH];
|
||||
snprintf(prefix, sizeof prefix, "%s", rel);
|
||||
lower_slash(prefix);
|
||||
size_t pn = strlen(prefix);
|
||||
while (pn && prefix[pn - 1] == '/') prefix[--pn] = 0;
|
||||
int n = 0;
|
||||
for (size_t i = 0; i < table_cap; i++) {
|
||||
const Entry *e = &table[i];
|
||||
if (!e->key) continue;
|
||||
const char *k = e->key;
|
||||
if (pn && (strncmp(k, prefix, pn) || k[pn] != '/')) continue;
|
||||
const char *name = pn ? k + pn + 1 : k;
|
||||
if (!*name || strchr(name, '/')) continue; /* (deeper) */
|
||||
const char *real = last_sep(e->host); /* (the name as the mod spells it) */
|
||||
real = real ? real + 1 : e->host;
|
||||
char base[MAX_PATH];
|
||||
snprintf(base, sizeof base, "%s\\%s", base_dir, real);
|
||||
if (GetFileAttributesA(base) != INVALID_FILE_ATTRIBUTES) continue;
|
||||
fn(arg, real, e->is_dir, e->size);
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
120
host/mouse_native.c
Normal file
120
host/mouse_native.c
Normal file
@@ -0,0 +1,120 @@
|
||||
/* (hookshot) Native mouse look (the Insert menu's "Mouse camera", off by default; HOS_MOUSE_NATIVE=1 or 0 overrides it):
|
||||
the captured mouse turns the player camera's own yaw and pitch, in degrees, with no dead zone, no response curve, no
|
||||
smoothing and no top speed, in place of the mouse as the right stick (nn_hid.c's mouse_stick).
|
||||
|
||||
Where the angles are: the player camera's update, f_80644c80 (a virtual method, the camera in x0), calls
|
||||
hos_mouse_camera first (nx2/oot_patches.py, patch_mouse_camera), on the game's thread, once a frame while that camera
|
||||
runs. The camera holds its pitch limits at +0x178 ({-85, 89} in the field), its pitch at +0x18c and its yaw at +0x1a4.
|
||||
The game turns them by the right stick in f_80649c10 (yaw, wrapped at 180) and f_8064b770 (pitch, within the limits),
|
||||
which f_80644c80 calls only while the stick is out of its dead zone (found with hardware write watchpoints on the two
|
||||
angles in Kokiri Forest). Yaw falls as the view turns right and pitch rises as it tilts down.
|
||||
|
||||
The camera's state at +0x204 is 3 while it follows Link by itself, and then it eases the pitch back to its rest over a
|
||||
couple of seconds; the right stick makes it 4 (the player's), where a pitch stays where it was put. The mouse leaves the
|
||||
state as it is: written there from here the game puts it back and the angles with it the next frame. So a pitch the
|
||||
mouse chose eases back as one the game chose does, while yaw stays.
|
||||
|
||||
The motion is added before the camera reads its input, so the game's own collision, lock-on and scripted cameras still
|
||||
follow. While the hook has run in the last 150 ms the mouse's motion is the camera's (hos_mouse_native gives 1: the
|
||||
right stick is left alone); otherwise (the pause menu, cutscenes with another camera, a build the patch did not find
|
||||
its place in) it is the right stick as before.
|
||||
|
||||
The sensitivity is the mouse's (the menu's Mouse sensitivity, - and =): 0.1 degrees a count at 1. HOS_MOUSE_INVERT_Y=1
|
||||
or the menu's Invert mouse vertical flips up and down. */
|
||||
#include "hos.h"
|
||||
#include <math.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
|
||||
int hos_mouse_take(int32_t *dx, int32_t *dy); /* display.c */
|
||||
void hos_mouse_give_back(int32_t dx, int32_t dy); /* display.c */
|
||||
int rx_option(int id, int otherwise);
|
||||
extern double hos_mouse_sens;
|
||||
|
||||
enum { LIMITS_AT = 0x178, PITCH_AT = 0x18c, YAW_AT = 0x1a4, STATE_AT = 0x204 };
|
||||
#define LIVE_NS 150000000LL /* (the hook ran this recently: the camera takes the mouse) */
|
||||
#define DEG_PER_COUNT 0.1
|
||||
|
||||
static volatile LONG64 last_hook_ns;
|
||||
static volatile LONG64 last_camera;
|
||||
static long long applied, cameras_seen;
|
||||
|
||||
static float getf(uint64_t a) { float f; memcpy(&f, GP(a), 4); return f; }
|
||||
static void putf(uint64_t a, float f) { memcpy(GP(a), &f, 4); }
|
||||
|
||||
/* the menu's Mouse camera (option 6), or HOS_MOUSE_NATIVE */
|
||||
static int native_on(void) {
|
||||
static const char *env;
|
||||
static int looked;
|
||||
if (!looked) looked = 1, env = getenv("HOS_MOUSE_NATIVE");
|
||||
return env ? atoi(env) != 0 : rx_option(6, 0);
|
||||
}
|
||||
|
||||
static int invert_y(void) {
|
||||
static int env = -1;
|
||||
if (env < 0) env = getenv("HOS_MOUSE_INVERT_Y") != NULL;
|
||||
return env || rx_option(8, 0); /* (the menu's Invert mouse vertical) */
|
||||
}
|
||||
|
||||
/* a camera's angles as the game keeps them: limits in order within +-90, angles finite */
|
||||
static int looks_like_camera(uint64_t cam) {
|
||||
const float lo = getf(cam + LIMITS_AT), hi = getf(cam + LIMITS_AT + 4), p = getf(cam + PITCH_AT), y = getf(cam + YAW_AT);
|
||||
return isfinite(lo) && isfinite(hi) && lo < hi && lo >= -90.0f && hi <= 90.0f && isfinite(p) && isfinite(y) &&
|
||||
fabsf(y) <= 360.0f;
|
||||
}
|
||||
|
||||
/* f_80644c80's first line (nx2/oot_patches.py): cam is the player camera, the game's thread */
|
||||
void hos_mouse_camera(uint64_t cam) {
|
||||
if (!cam || !native_on() || !looks_like_camera(cam)) return;
|
||||
/* Only while it is the view: following Link (3) or turned by the player (4). Aiming the slingshot in first person
|
||||
leaves this camera updating with its state 0 while another one draws (traced at Hyrule Castle); shops are reported
|
||||
the same. In any other state the mouse is the right stick, which those views turn by (the hook counts as not
|
||||
run, so hos_mouse_native gives -1) */
|
||||
uint32_t state;
|
||||
memcpy(&state, GP(cam + STATE_AT), 4);
|
||||
if (state != 3 && state != 4) {
|
||||
/* (at once: the stick takes the next motion, not one burst once the 150 ms run out) */
|
||||
InterlockedExchange64(&last_hook_ns, 0);
|
||||
/* (each state seen leaving the mouse to the stick, once: what another view, Z-targeting, climbing or swimming,
|
||||
is, to add here if one of them should turn with the mouse) */
|
||||
static uint32_t said[8];
|
||||
static int nsaid;
|
||||
int seen = 0;
|
||||
for (int i = 0; i < nsaid; i++) seen |= said[i] == state;
|
||||
if (!seen && nsaid < 8) {
|
||||
said[nsaid++] = state;
|
||||
hos_log("mouse native: camera state %u: the mouse is the right stick", state);
|
||||
}
|
||||
return;
|
||||
}
|
||||
InterlockedExchange64(&last_hook_ns, hos_now_ns());
|
||||
if (InterlockedExchange64(&last_camera, (LONG64)cam) != (LONG64)cam && cameras_seen++ < 8)
|
||||
hos_log("mouse native: the player camera at %#llx turns with the mouse", (unsigned long long)cam);
|
||||
int32_t dx, dy;
|
||||
if (!hos_mouse_take(&dx, &dy) || (!dx && !dy)) return;
|
||||
const double k = DEG_PER_COUNT * hos_mouse_sens;
|
||||
float y = getf(cam + YAW_AT) - (float)(dx * k), p = getf(cam + PITCH_AT) + (float)((invert_y() ? -dy : dy) * k);
|
||||
const float lo = getf(cam + LIMITS_AT), hi = getf(cam + LIMITS_AT + 4);
|
||||
while (y > 180.0f) y -= 360.0f;
|
||||
while (y < -180.0f) y += 360.0f;
|
||||
if (p < lo) p = lo;
|
||||
if (p > hi) p = hi;
|
||||
putf(cam + YAW_AT, y), putf(cam + PITCH_AT, p);
|
||||
if ((++applied & 4095) == 1)
|
||||
hos_log("mouse native: %lld moves applied; pitch %.2f yaw %.2f", applied, p, y);
|
||||
}
|
||||
|
||||
/* With each read of the controller (nn_hid.c, the game's threads): 0 if the mouse is not captured, 1 if the camera takes
|
||||
its motion (hos_mouse_camera), -1 if no player camera runs now (the right stick takes it) */
|
||||
int hos_mouse_native(void) {
|
||||
static int said;
|
||||
if (!said) said = 1, hos_log("mouse native: on (the menu's Mouse camera, or HOS_MOUSE_NATIVE)");
|
||||
if (hos_now_ns() - InterlockedCompareExchange64(&last_hook_ns, 0, 0) >= LIVE_NS) return -1;
|
||||
int32_t dx, dy;
|
||||
const int captured = hos_mouse_take(&dx, &dy); /* (only to know the capture: the motion is the camera's) */
|
||||
if (dx || dy) hos_mouse_give_back(dx, dy);
|
||||
return captured ? 1 : 0;
|
||||
}
|
||||
15
host/msvc_oldnames.c
Normal file
15
host/msvc_oldnames.c
Normal file
@@ -0,0 +1,15 @@
|
||||
/* (hookshot, issue 439) oldnames.lib is the aliases from the C runtime's pre-2015 (non-underscore) names to its current ones.
|
||||
clang asks for it as a default library for the MSVC target, but recent Windows SDKs no longer ship it (an older SDK has it
|
||||
in ucrt\x64; Visual Studio has its own copy in its lib folder), so a link whose library paths reach neither failed after
|
||||
the whole game had been compiled. toolchain.native_link() no longer asks for it, and this file holds the aliases the
|
||||
prebuilt static FFmpeg libraries (the CPM cache, built with Microsoft's compiler) still need: avutil's log.o isatty, its
|
||||
file.o close, and avcodec's/avutil's file_open.o fdopen and tempnam. The MinGW and POSIX builds compile nothing of it,
|
||||
their C library has these names itself. */
|
||||
#if defined(_MSC_VER) && !defined(__MINGW32__)
|
||||
#pragma comment(linker, "/alternatename:close=_close")
|
||||
#pragma comment(linker, "/alternatename:fdopen=_fdopen")
|
||||
#pragma comment(linker, "/alternatename:isatty=_isatty")
|
||||
#pragma comment(linker, "/alternatename:tempnam=_tempnam")
|
||||
#else
|
||||
typedef int msvc_oldnames_unused; /* (a translation unit with something in it) */
|
||||
#endif
|
||||
406
host/nn_applet.c
Normal file
406
host/nn_applet.c
Normal file
@@ -0,0 +1,406 @@
|
||||
/* nn::oe (applet), nn::account, nn::time, nn::pl, nn::err: what a game asks the system about itself.
|
||||
The answers describe a docked console in English (HOS_LANGUAGE / language.txt: another language) with one user,
|
||||
"Player". */
|
||||
#include "hos.h"
|
||||
#include "hos_paths.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <windows.h> /* (the exe's folder; the browser build: the Microsoft C runtime's time functions) */
|
||||
|
||||
static int64_t boot_ns;
|
||||
|
||||
/* ---- nn::oe ------------------------------------------------------------------------------------------------- */
|
||||
HLE(_ZN2nn2oe10InitializeEv) { if (!boot_ns) boot_ns = hos_now_ns(); }
|
||||
HLE(_ZN2nn2oe17FinishStartupLogoEv) { hos_log("oe: startup logo finished"); }
|
||||
/* GetDesiredLanguage() -> settings::LanguageCode (char[8]) by value: the language the game shows. HOS_LANGUAGE, or language.txt
|
||||
beside the exe: its first line that is not blank or a comment. The file is written on the first start, with the choices: the 16
|
||||
languages in romfs/Mals. After SkyboundTotk PR 16 by sardigital. */
|
||||
static const struct { const char *code, *name; } languages[] = {
|
||||
{"en-US", "English (US)"}, {"en-GB", "English (UK)"}, {"fr", "French (France)"}, {"fr-CA", "French (Canada)"},
|
||||
{"de", "German"}, {"it", "Italian"}, {"es", "Spanish (Spain)"}, {"es-419", "Spanish (Latin America)"},
|
||||
{"pt-BR", "Portuguese (Brazil)"}, {"nl", "Dutch"}, {"pl", "Polish"}, {"ru", "Russian"},
|
||||
{"ja", "Japanese"}, {"ko", "Korean"}, {"zh-Hans", "Chinese (Simplified)"}, {"zh-Hant", "Chinese (Traditional)"},
|
||||
};
|
||||
static const char *desired_language(void) {
|
||||
static char lang[8];
|
||||
if (lang[0]) return lang;
|
||||
char want[32] = "";
|
||||
const char *from = "the default";
|
||||
if (getenv("HOS_LANGUAGE")) {
|
||||
snprintf(want, sizeof want, "%s", getenv("HOS_LANGUAGE"));
|
||||
from = "HOS_LANGUAGE";
|
||||
} else {
|
||||
char path[300] = "language.txt";
|
||||
#if !defined(__EMSCRIPTEN__) /* (linux too: host/posix) */
|
||||
DWORD n = hos_game_path_a(path, 260);
|
||||
while (n > 0 && path[n - 1] != 92 && path[n - 1] != 47) n--;
|
||||
snprintf(path + n, sizeof path - n, "language.txt");
|
||||
#endif
|
||||
FILE *f = fopen(path, "r");
|
||||
if (f) {
|
||||
char line[80];
|
||||
int whole = 1; /* (the first line is longer than this: its second piece, "ave, and start...", was taken for the code) */
|
||||
while (fgets(line, sizeof line, f)) {
|
||||
const int starts = whole;
|
||||
whole = strchr(line, 10) != NULL;
|
||||
if (!starts) continue;
|
||||
const char *p = line;
|
||||
if ((unsigned char)p[0] == 0xEF && (unsigned char)p[1] == 0xBB && (unsigned char)p[2] == 0xBF) p += 3; /* (a BOM: Notepad's UTF-8) */
|
||||
while (*p == ' ' || *p == '\t') p++;
|
||||
if (*p == '#' || *p == '\r' || *p == '\n' || !*p) continue;
|
||||
/* (only a code the game has: a stray line was taken before, and the game stayed in English, Hookshot issue 75) */
|
||||
char code[32];
|
||||
snprintf(code, sizeof code, "%s", p);
|
||||
code[strcspn(code, " \t\r\n")] = 0;
|
||||
int known = 0;
|
||||
for (size_t i = 0; i < sizeof languages / sizeof *languages; i++)
|
||||
if (!_stricmp(code, languages[i].code)) snprintf(code, sizeof code, "%s", languages[i].code), known = 1;
|
||||
if (!known) continue;
|
||||
snprintf(want, sizeof want, "%s", code);
|
||||
from = "language.txt";
|
||||
break;
|
||||
}
|
||||
fclose(f);
|
||||
} else if ((f = fopen(path, "w")) != NULL) {
|
||||
fputs("# The game's language. Change the line below to one of the codes listed here, save, and start the game again.\n\nen-US\n\n", f);
|
||||
for (size_t i = 0; i < sizeof languages / sizeof *languages; i++) fprintf(f, "# %-8s %s\n", languages[i].code, languages[i].name);
|
||||
fclose(f);
|
||||
}
|
||||
}
|
||||
want[strcspn(want, " \t\r\n")] = 0;
|
||||
snprintf(lang, sizeof lang, "en-US");
|
||||
int found = 0;
|
||||
for (size_t i = 0; want[0] && i < sizeof languages / sizeof *languages; i++)
|
||||
if (!_stricmp(want, languages[i].code)) snprintf(lang, sizeof lang, "%s", languages[i].code), found = 1; /* (HOS_LANGUAGE=pt-br too, as language.txt) */
|
||||
if (want[0] && !found) hos_log("oe: language \"%s\" (%s) is not one the game has: English (US)", want, from);
|
||||
else hos_log("oe: language %s (%s)", lang, from);
|
||||
return lang;
|
||||
}
|
||||
HLE(_ZN2nn2oe18GetDesiredLanguageEv) {
|
||||
uint64_t v = 0;
|
||||
memcpy(&v, desired_language(), strlen(desired_language()));
|
||||
RET(v);
|
||||
}
|
||||
/* HOS_HANDHELD=1: handheld (the 1080p screen: 1080p output and the game's handheld resolutions) instead of docked
|
||||
(MKW docked composes 3840 x 2160) */
|
||||
int hos_ini_option(const char *key, int otherwise);
|
||||
#define ini_option hos_ini_option
|
||||
int hos_ini_option(const char *key, int otherwise) { /* (hookshot: the Insert menu's choice, gpu/vk/vk_menu.cpp; nn_vi.c reads it too) */
|
||||
char path[MAX_PATH];
|
||||
const DWORD n = hos_game_path_a(path, MAX_PATH);
|
||||
char *slash = n ? (strrchr(path, 92) ? strrchr(path, 92) : strrchr(path, 47)) : NULL; /* (linux: '/'; the game folder's, not bin\\'s) */
|
||||
if (!slash) return otherwise;
|
||||
snprintf(slash + 1, (size_t)(path + MAX_PATH - slash - 1), "triforce_options.ini");
|
||||
FILE *f = fopen(path, "r");
|
||||
if (!f) return otherwise;
|
||||
char line[80];
|
||||
const size_t len = strlen(key);
|
||||
while (fgets(line, sizeof line, f))
|
||||
if (!strncmp(line, key, len) && line[len] == '=') otherwise = atoi(line + len + 1);
|
||||
fclose(f);
|
||||
return otherwise;
|
||||
}
|
||||
static int handheld(void) {
|
||||
static int v = -1;
|
||||
if (v < 0) v = getenv("HOS_HANDHELD") ? atoi(getenv("HOS_HANDHELD")) != 0 : ini_option("handheld_profile", 0) != 0;
|
||||
return v;
|
||||
}
|
||||
/* (hookshot) The Insert menu's Output resolution (output_res=, HOS_OUTPUT_RES over it), docked only: 0 the game's 2048 x 1152,
|
||||
1 2560 x 1440, 2 3840 x 2160, 3 1920 x 1080, 4 5120 x 1440, 5 5120 x 2880. The game's frame is its display size (2560 x 1440 as shipped;
|
||||
nx2/oot_patches.py apply_output_size asks hos_output_size) times its graphics scale (GetCurrentGraphicsScale: 0 x1, 1 x0.8,
|
||||
2 x0.667). Here it saw scale 1 (x0 left at the call before's answer), so 2048 x 1152; each explicit size uses x1. */
|
||||
static int output_mode(void) {
|
||||
static int v = -1;
|
||||
if (v < 0) {
|
||||
static const char *const names[] = {"2048x1152 (the game's)", "2560x1440", "3840x2160", "1920x1080", "5120x1440", "5120x2880"};
|
||||
v = getenv("HOS_OUTPUT_RES") ? atoi(getenv("HOS_OUTPUT_RES")) : ini_option("output_res", 0);
|
||||
if ((unsigned)v >= sizeof names / sizeof *names || handheld()) v = 0;
|
||||
hos_log("oe: output resolution %s", names[v]);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
uint32_t hos_output_size(int height) {
|
||||
switch (output_mode()) {
|
||||
case 2: return height ? 2160 : 3840;
|
||||
case 3: return height ? 1080 : 1920;
|
||||
case 4: return height ? 1440 : 5120;
|
||||
case 5: return height ? 2880 : 5120;
|
||||
default: return height ? 1440 : 2560;
|
||||
}
|
||||
}
|
||||
/* (hookshot) The render targets' GPU pool (nx2/oot_patches.py), 0x13100000 bytes as shipped, for 2560 x 1440: a 3840x2160 3D at
|
||||
the 4K output ran out of it. Scaled with the output's pixels, or the widescreen picture's when it has more (host/hos_main.c:
|
||||
hos_wide_out, the output's height at the screen's shape: 7680 x 2160 for a 32:9 screen at the 4K output, twice the pixels the pool
|
||||
was scaled for, and the game crashed as Kokiri Forest loaded, a null pointer or "texture handle ids -1", issue 1031);
|
||||
Castle Town's guard-house conversation/camera test crashed with 305 MB at 2560 x 1440 and passed with 512 MB.
|
||||
Keep at least 512 MB by default; larger scaled pools and an explicit HOS_RT_POOL_MB=<MB> still win. The 5120 x 2880 output's
|
||||
pool is kept to 900 MB: scaled, it is 1220 MB, and 1220 and 1000 MB both failed the game's own reservation at boot; at 900
|
||||
MB it boots and plays with the 3D at the full 5120 x 2880. Every other output keeps its whole scaled pool. */
|
||||
uint64_t hos_rt_pool_size(uint64_t game) {
|
||||
const char *e = getenv("HOS_RT_POOL_MB");
|
||||
extern volatile uint64_t hos_wide_out;
|
||||
const uint64_t wide = hos_wide_out, wide_px = (wide >> 32) * (wide & 0xffffffffULL);
|
||||
uint64_t px = (uint64_t)hos_output_size(0) * hos_output_size(1);
|
||||
if (wide_px > px) px = wide_px;
|
||||
const uint64_t scaled = px > 2560 * 1440 ? (game * px / (2560 * 1440) + 0xfffff) & ~0xfffffULL : game;
|
||||
const uint64_t minimum = 512ULL << 20, five_k = 900ULL << 20;
|
||||
const int is_five_k = hos_output_size(0) == 5120 && hos_output_size(1) == 2880;
|
||||
const uint64_t v = e ? strtoull(e, NULL, 0) << 20 : scaled < minimum ? minimum : is_five_k && scaled > five_k ? five_k : scaled;
|
||||
static int logged;
|
||||
if (!logged++) hos_log("applet: render target pool %llu MB (the game's %llu MB)", (unsigned long long)(v >> 20), (unsigned long long)(game >> 20));
|
||||
return v;
|
||||
}
|
||||
HLE(_ZN2nn2oe16GetOperationModeEv) { RET(handheld() ? 0 : 1); } /* OperationMode_Handheld / _Console (docked) */
|
||||
HLE(_ZN2nn2oe18GetPerformanceModeEv) { RET(handheld() ? 0 : 1); } /* PerformanceMode_Normal / _Boost (docked) */
|
||||
HLE(_ZN2nn2oe20GetCurrentFocusStateEv) { RET(1); } /* FocusState_InFocus */
|
||||
HLE(_ZN2nn2oe25GetProgramTotalActiveTimeEv) { RET(hos_now_ns() - boot_ns); }
|
||||
HLE(_ZN2nn2oe24GetExpectedVolumeBalanceEPfS1_) {
|
||||
float one = 1.0f;
|
||||
memcpy(GP(ARG(0)), &one, 4);
|
||||
memcpy(GP(ARG(1)), &one, 4);
|
||||
}
|
||||
HLE(_ZN2nn2oe24SetExpectedVolumeBalanceEff) {}
|
||||
HLE(_ZN2nn2oe15SetCpuBoostModeENS0_12CpuBoostModeE) {}
|
||||
HLE(_ZN2nn2oe20SetFocusHandlingModeENS0_17FocusHandlingModeE) {}
|
||||
HLE(_ZN2nn2oe27SetPerformanceConfigurationENS0_15PerformanceModeEi) {}
|
||||
HLE(_ZN2nn2oe42SetOperationModeChangedNotificationEnabledEb) {}
|
||||
HLE(_ZN2nn2oe44SetPerformanceModeChangedNotificationEnabledEb) {}
|
||||
HLE(_ZN2nn2oe28SetResumeNotificationEnabledEb) {}
|
||||
HLE(_ZN2nn2oe38SetUserInactivityDetectionTimeExtendedEb) {}
|
||||
/* No system notifications ever arrive: TryPop says none, Pop waits forever (as it would on a quiet console). */
|
||||
HLE(_ZN2nn2oe25TryPopNotificationMessageEPj) { RET(0); }
|
||||
HLE(_ZN2nn2oe22PopNotificationMessageEv) { for (;;) hos_sleep_ns(1000000000LL); }
|
||||
|
||||
/* ---- nn::account: one user ------------------------------------------------------------------------------------ */
|
||||
static const uint64_t user_uid[2] = {0x0000000000000001ULL, 0x5a3c9e1f0b7d2468ULL};
|
||||
HLE(_ZN2nn7account10InitializeEv) {}
|
||||
/* TryOpenPreselectedUser(UserHandle*) -> bool. A handle is three words; ours carries the uid. */
|
||||
HLE(_ZN2nn7account22TryOpenPreselectedUserEPNS0_10UserHandleE) {
|
||||
G64(ARG(0)) = user_uid[0];
|
||||
G64(ARG(0) + 8) = user_uid[1];
|
||||
G64(ARG(0) + 16) = 1;
|
||||
RET(1);
|
||||
}
|
||||
HLE(_ZN2nn7account9CloseUserERKNS0_10UserHandleE) {}
|
||||
/* GetUserId(Uid*, UserHandle const&) -> Result */
|
||||
HLE(_ZN2nn7account9GetUserIdEPNS0_3UidERKNS0_10UserHandleE) {
|
||||
G64(ARG(0)) = user_uid[0];
|
||||
G64(ARG(0) + 8) = user_uid[1];
|
||||
RET(0);
|
||||
}
|
||||
/* GetNickname(Nickname*, Uid const&) -> Result: Nickname is char[33] */
|
||||
HLE(_ZN2nn7account11GetNicknameEPNS0_8NicknameERKNS0_3UidE) {
|
||||
memset(GP(ARG(0)), 0, 33);
|
||||
memcpy(GP(ARG(0)), "Player", 6);
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn7account16GetUserExistenceEPbRKNS0_3UidE) {
|
||||
*(uint8_t *)GP(ARG(0)) = G64(ARG(1)) == user_uid[0] && G64(ARG(1) + 8) == user_uid[1];
|
||||
RET(0);
|
||||
}
|
||||
|
||||
/* ---- nn::time: the host clock --------------------------------------------------------------------------------- */
|
||||
HLE(_ZN2nn4time10InitializeEv) { RET(0); }
|
||||
HLE(_ZN2nn4time8FinalizeEv) { RET(0); }
|
||||
HLE(_ZN2nn4time13IsInitializedEv) { RET(1); }
|
||||
/* HOS_FIXED_TIME=<POSIX seconds>: the clock starts there at boot (runs that can be compared: what the title shows
|
||||
follows the time) */
|
||||
static uint64_t now_posix(void) {
|
||||
static int64_t fixed = -1;
|
||||
if (fixed < 0) fixed = getenv("HOS_FIXED_TIME") ? _atoi64(getenv("HOS_FIXED_TIME")) : 0;
|
||||
return fixed ? (uint64_t)(fixed + hos_now_ns() / 1000000000LL) : (uint64_t)time(NULL);
|
||||
}
|
||||
HLE(_ZN2nn4time23StandardUserSystemClock14GetCurrentTimeEPNS0_9PosixTimeE) { G64(ARG(0)) = now_posix(); RET(0); }
|
||||
HLE(_ZN2nn4time26StandardNetworkSystemClock14GetCurrentTimeEPNS0_9PosixTimeE) { G64(ARG(0)) = now_posix(); RET(0); }
|
||||
/* StandardSteadyClock::now() -> time_point (std::chrono, rep int64, period seconds): one register, x0.
|
||||
(hookshot) It was a 24-byte SteadyClockTimePoint written through x8; OoT reads x0 and leaves x8 unset (it was 0:
|
||||
the write faulted at guest 0). MKW does not import it. */
|
||||
HLE(_ZN2nn4time19StandardSteadyClock3nowEv) { RET((uint64_t)(hos_now_ns() / 1000000000LL)); }
|
||||
|
||||
/* (hookshot) nn::socket::detail::Poll(pollfd* fds, unsigned long n, int timeout_ms): offline, no descriptor is ever
|
||||
ready. OoT's gRPC poll engine (nn.npln.GrpcDispatcher) calls it through a function pointer, past the socket
|
||||
imports the runtime stubs, and the SDK's own Poll aborted on the uninitialized socket layer. It waits out the
|
||||
timeout (an infinite one in 50 ms steps, which the poll loop takes as a spurious wake) and reports a timeout. */
|
||||
static void socket_poll(Ctx *c) {
|
||||
const uint64_t fds = ARG(0), n = ARG(1);
|
||||
const int timeout = (int)ARG(2);
|
||||
for (uint64_t i = 0; fds && i < n && i < 4096; i++) *(uint16_t *)GP(fds + 8 * i + 6) = 0; /* revents */
|
||||
if (timeout != 0) {
|
||||
const int away = hos_vcore_away();
|
||||
hos_sleep_ns((int64_t)(timeout < 0 || timeout > 50 ? 50 : timeout) * 1000000);
|
||||
if (away) hos_vcore_back();
|
||||
}
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn6socket6detail4PollEP6pollfdmi) { socket_poll(c); }
|
||||
HLE(_ZN2nn6socket6detail4PollEPNS0_6PollFdEmi) { socket_poll(c); }
|
||||
|
||||
/* (hookshot) nn::account::EnsureNetworkServiceAccountIdTokenCacheAsync(AsyncContext*, UserHandle const&): offline,
|
||||
so no network service account. The generic stub's 0 said the task started, and OoT's npln worker (main
|
||||
0x8214eac0) then waited on the AsyncContext nothing had set up. This failure (account module 124, description
|
||||
280) takes the game's error branch right after the call. */
|
||||
HLE(_ZN2nn7account44EnsureNetworkServiceAccountIdTokenCacheAsyncEPNS0_12AsyncContextERKNS0_10UserHandleE) {
|
||||
RET(124 | (280 << 9));
|
||||
}
|
||||
|
||||
/* (hookshot) nn::nsd::GetEnvironmentIdentifier(EnvironmentIdentifier* out): char[8]; retail units say "lp1".
|
||||
OoT (main 0x8243f490) only checks for a "t-" test prefix. Left to the SDK it asks the nsd service over HIPC. */
|
||||
HLE(_ZN2nn3nsd24GetEnvironmentIdentifierEPNS0_21EnvironmentIdentifierE) {
|
||||
if (ARG(0)) { memset(GP(ARG(0)), 0, 8); memcpy(GP(ARG(0)), "lp1", 3); }
|
||||
}
|
||||
|
||||
static void calendar(uint64_t out, uint64_t info, int64_t posix, int local) {
|
||||
time_t t = (time_t)posix;
|
||||
struct tm tmv = {0}; /* (hookshot: a time the C library cannot convert left it as the stack had it) */
|
||||
if (local) localtime_s(&tmv, &t); else gmtime_s(&tmv, &t);
|
||||
/* CalendarTime { s16 year; s8 month, day, hour, minute, second; pad } */
|
||||
uint8_t ct[8] = {0};
|
||||
int16_t year = (int16_t)(tmv.tm_year + 1900);
|
||||
memcpy(ct, &year, 2);
|
||||
ct[2] = (uint8_t)(tmv.tm_mon + 1); ct[3] = (uint8_t)tmv.tm_mday; ct[4] = (uint8_t)tmv.tm_hour;
|
||||
ct[5] = (uint8_t)tmv.tm_min; ct[6] = (uint8_t)tmv.tm_sec;
|
||||
memcpy(GP(out), ct, 8);
|
||||
if (info) { /* CalendarAdditionalInfo { s32 dayOfWeek, dayOfYear; char tz[8]; s32 isDst; s32 utcOffset } */
|
||||
memset(GP(info), 0, 0x18);
|
||||
G32(info) = (uint32_t)tmv.tm_wday;
|
||||
G32(info + 4) = (uint32_t)tmv.tm_yday;
|
||||
memcpy(GP(info + 8), "UTC", 3);
|
||||
}
|
||||
}
|
||||
/* ToCalendarTime(CalendarTime*, CalendarAdditionalInfo*, PosixTime const&) -> Result */
|
||||
HLE(_ZN2nn4time14ToCalendarTimeEPNS0_12CalendarTimeEPNS0_22CalendarAdditionalInfoERKNS0_9PosixTimeE) {
|
||||
calendar(ARG(0), ARG(1), (int64_t)G64(ARG(2)), 1);
|
||||
RET(0);
|
||||
}
|
||||
/* ToCalendarTimeInUtc(PosixTime const&) -> CalendarTime (8 bytes, in x0) */
|
||||
HLE(_ZN2nn4time19ToCalendarTimeInUtcERKNS0_9PosixTimeE) {
|
||||
static _Thread_local uint64_t tmp;
|
||||
if (!tmp) tmp = hos_sys_alloc(8, 8);
|
||||
calendar(tmp, 0, (int64_t)G64(ARG(0)), 0);
|
||||
RET(G64(tmp));
|
||||
}
|
||||
/* ToPosixTimeFromUtc(CalendarTime const&) -> PosixTime */
|
||||
HLE(_ZN2nn4time18ToPosixTimeFromUtcERKNS0_12CalendarTimeE) {
|
||||
uint8_t ct[8];
|
||||
memcpy(ct, GP(ARG(0)), 8);
|
||||
struct tm tmv = {0};
|
||||
int16_t year;
|
||||
memcpy(&year, ct, 2);
|
||||
tmv.tm_year = year - 1900; tmv.tm_mon = ct[2] - 1; tmv.tm_mday = ct[3];
|
||||
tmv.tm_hour = ct[4]; tmv.tm_min = ct[5]; tmv.tm_sec = ct[6];
|
||||
RET((uint64_t)_mkgmtime(&tmv));
|
||||
}
|
||||
/* ClockSnapshot: an opaque 0xD0-byte record; ours holds the POSIX time at +0 */
|
||||
HLE(_ZN2nn4time13ClockSnapshotC1Ev) { memset(GP(ARG(0)), 0, 0xD0); }
|
||||
HLE(_ZN2nn4time13ClockSnapshot29CreateWithStandardSystemClockEPS1_) {
|
||||
memset(GP(ARG(0)), 0, 0xD0);
|
||||
G64(ARG(0)) = now_posix();
|
||||
RET(0);
|
||||
}
|
||||
/* CalculateSpanBetween(TimeSpan*, ClockSnapshot const& a, ClockSnapshot const& b) -> Result */
|
||||
HLE(_ZN2nn4time20CalculateSpanBetweenEPNS_8TimeSpanERKNS0_13ClockSnapshotES5_) {
|
||||
G64(ARG(0)) = (uint64_t)(((int64_t)G64(ARG(2)) - (int64_t)G64(ARG(1))) * 1000000000LL);
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn4time48CalculateStandardUserSystemClockDifferenceByUserERKNS0_13ClockSnapshotES3_) { RET(0); }
|
||||
|
||||
/* ---- nn::pl: system shared fonts. We have none; report an empty one, loaded. ------------------------------------ */
|
||||
static uint64_t empty_font;
|
||||
HLE(_ZN2nn2pl22GetSharedFontLoadStateENS0_14SharedFontTypeE) { RET(1); } /* SharedFontLoadState_Loaded */
|
||||
HLE(_ZN2nn2pl20GetSharedFontAddressENS0_14SharedFontTypeE) {
|
||||
if (!empty_font) empty_font = hos_sys_alloc(0x1000, 0x1000);
|
||||
RET(empty_font);
|
||||
}
|
||||
HLE(_ZN2nn2pl17GetSharedFontSizeENS0_14SharedFontTypeE) { RET(0); }
|
||||
|
||||
/* ---- nn::err ------------------------------------------------------------------------------------------------- */
|
||||
HLE(_ZN2nn3err9ShowErrorENS_6ResultE) { hos_log("err: the game shows error %#x (module %u, description %u)", (uint32_t)ARG(0),
|
||||
(uint32_t)ARG(0) & 0x1FF, ((uint32_t)ARG(0) >> 9) & 0x1FFF); }
|
||||
|
||||
/* ---- nn::prepo: play reports. The PlayReport builder (Add*, SetEventId) is the SDK's own code; saving one would
|
||||
send it to the prepo service. Reports are dropped. ---------------------------------------------------------- */
|
||||
HLE(_ZN2nn5prepo10PlayReport4SaveEv) { RET(0); }
|
||||
HLE(_ZN2nn5prepo10PlayReport4SaveERKNS_7account3UidE) { RET(0); }
|
||||
/* (hookshot) PlayReport::Send(Uid const&), SDK 22's: kept nowhere, as Save. Left to the SDK it opened the prepo
|
||||
service through sm: and aborted on the empty reply (OoT's PlayReporter thread, ~5 minutes into a game). */
|
||||
HLE(_ZN2nn5prepo10PlayReport4SendERKNS_7account3UidE) { RET(0); }
|
||||
/* (hookshot) prepo::AsyncContext: the report "sent" at once. GetCompletionEvent(SystemEvent* out) gives an event
|
||||
already signaled (the SDK's own aborted on the context the empty IPC reply left), GetResult success. */
|
||||
void hos_system_event_init(uint64_t key, int autoclear); /* nn_os_sync.c */
|
||||
void hos_system_event_signal(uint64_t key);
|
||||
HLE(_ZN2nn5prepo12AsyncContext18GetCompletionEventEPNS_2os11SystemEventE) {
|
||||
if (ARG(1)) {
|
||||
hos_system_event_init(ARG(1), 0);
|
||||
hos_system_event_signal(ARG(1));
|
||||
}
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn5prepo12AsyncContext9GetResultEv) { RET(0); }
|
||||
HLE(_ZN2nn5prepo12AsyncContextD1Ev) {}
|
||||
|
||||
/* ---- (mkw-recomp) MKW's account and oe calls TOTK never made: the one user, offline ------------------------- */
|
||||
/* ListAllUsers(int* count, Uid* out, int max) -> Result */
|
||||
HLE(_ZN2nn7account12ListAllUsersEPiPNS0_3UidEi) {
|
||||
const int n = (int)ARG(2) > 0 ? 1 : 0;
|
||||
if (n && ARG(1)) {
|
||||
G64(ARG(1)) = user_uid[0];
|
||||
G64(ARG(1) + 8) = user_uid[1];
|
||||
}
|
||||
if (ARG(0)) G32(ARG(0)) = (uint32_t)n;
|
||||
RET(0);
|
||||
}
|
||||
/* OpenUser(UserHandle*, Uid const&) -> Result */
|
||||
HLE(_ZN2nn7account8OpenUserEPNS0_10UserHandleERKNS0_3UidE) {
|
||||
G64(ARG(0)) = G64(ARG(1));
|
||||
G64(ARG(0) + 8) = G64(ARG(1) + 8);
|
||||
G64(ARG(0) + 16) = 0;
|
||||
RET(0);
|
||||
}
|
||||
/* the network service account: not available (the game stays offline) */
|
||||
HLE(_ZN2nn7account32IsNetworkServiceAccountAvailableEPbRKNS0_10UserHandleE) {
|
||||
*(uint8_t *)GP(ARG(0)) = 0;
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn7account36EnsureNetworkServiceAccountAvailableERKNS0_10UserHandleE) { RET(0x7C7C); } /* (an account error) */
|
||||
HLE(_ZN2nn7account26GetNetworkServiceAccountIdEPNS0_23NetworkServiceAccountIdERKNS0_10UserHandleE) {
|
||||
G64(ARG(0)) = 0;
|
||||
RET(0x7C7C);
|
||||
}
|
||||
/* nn::oe::GetCurrentGraphicsScale() -> float (docked/handheld render scale): 1.0 */
|
||||
HLE(_ZN2nn2oe23GetCurrentGraphicsScaleEv) {
|
||||
/* (hookshot) HOS_GRAPHICS_SCALE=<f>: another scale, a test of whether the game sizes its picture by it (4K, issue 68) */
|
||||
static float scale = 0;
|
||||
static volatile LONG told;
|
||||
if (scale == 0) scale = getenv("HOS_GRAPHICS_SCALE") ? (float)atof(getenv("HOS_GRAPHICS_SCALE")) : 1.0f;
|
||||
if (scale <= 0) scale = 1.0f;
|
||||
if (InterlockedIncrement(&told) <= 3) hos_log("oe: GetCurrentGraphicsScale -> %.2f", scale);
|
||||
const float one = scale;
|
||||
uint32_t bits;
|
||||
memcpy(&bits, &one, 4);
|
||||
c->vreg[0][0] = bits, c->vreg[0][1] = 0;
|
||||
c->x[0] = output_mode() ? 0 : 1; /* (the scale enum the game reads, w0: x1 for a chosen output, x0.8 as before) */
|
||||
}
|
||||
HLE(_ZN2nn2oe42SetGraphicsScaleChangedNotificationEnabledEb) {}
|
||||
HLE(_ZN2nn2oe31EnterExitRequestHandlingSectionEv) {}
|
||||
HLE(_ZN2nn2oe31LeaveExitRequestHandlingSectionEv) {}
|
||||
HLE(_ZN2nn2oe15EnableRecordingEv) {}
|
||||
HLE(_ZN2nn2oe16DisableRecordingEv) {}
|
||||
HLE(_ZN2nn2oe16EnableScreenShotEv) {}
|
||||
HLE(_ZN2nn2oe17DisableScreenShotEv) {}
|
||||
/* GetDisplayVersion(DisplayVersion*): a 16-byte string */
|
||||
HLE(_ZN2nn2oe17GetDisplayVersionEPNS0_14DisplayVersionE) {
|
||||
memset(GP(ARG(0)), 0, 16);
|
||||
memcpy(GP(ARG(0)), "1.8.0", 5);
|
||||
}
|
||||
/* nn::camera::sdk::CreateCameraContext(gsdrv::UniqueNativeHandle*) -> Result: no camera (GameChat's video), so the
|
||||
game does not open the camera service through a handle it never got */
|
||||
HLE(_ZN2nn6camera3sdk19CreateCameraContextEPNS_5gsdrv18UniqueNativeHandleE) {
|
||||
/* the game aborts unless this succeeds: a session handle that hos_svc.c's SendSyncRequest answers generically */
|
||||
if (ARG(0)) G32(ARG(0)) = 0xC0FE0001u;
|
||||
RET(0);
|
||||
}
|
||||
/* StandardNetworkSystemClock::IsAccuracySufficient(): offline, so no (the lifted SDK version aborted, with no time
|
||||
service session) */
|
||||
HLE(_ZN2nn4time26StandardNetworkSystemClock20IsAccuracySufficientEv) { RET(0); }
|
||||
1640
host/nn_audio.c
Normal file
1640
host/nn_audio.c
Normal file
File diff suppressed because it is too large
Load Diff
505
host/nn_audio_in.c
Normal file
505
host/nn_audio_in.c
Normal file
@@ -0,0 +1,505 @@
|
||||
/* (hookshot) nn::audio's input streams: the microphone, as the ocarina's "play with your voice / an instrument" option uses it.
|
||||
|
||||
The game lists the virtual input devices once at its start (ListVirtualInputDevices) and opens two input streams only if
|
||||
there is one: one on the default virtual device, one on the "true raw" one (GetTrueRawAudioInputDevice), both 48 kHz,
|
||||
mono, 16-bit (its StreamFormat: {PcmInt16, 1 channel, 48000}). With the ocarina's microphone mode on it starts them
|
||||
(StartInputStream when GetInputStreamState is not 2), reads up to 256 frames a frame (GetInputStreamFilledFrameCount,
|
||||
ReadInputStream) and works the notes out itself. Without these the stubs listed no device: the game never opened a
|
||||
stream, and the ocarina never heard anything.
|
||||
|
||||
Here there is always one device of each kind (as on the console, whose microphone is always there). The started streams
|
||||
of one format share a source: one microphone opened once, through SDL3, or SDL2 as the Linux AppImage carries
|
||||
(host/hos_sdl.c), converted to that format; what it records goes to each stream's own buffer, the newest capacity's
|
||||
worth kept. Which one is the Insert menu's choice (gpu/vk/vk_menu.cpp, Gameplay: Microphone), told by hos_mic_select:
|
||||
off, the system's default, or a microphone by its name. One that is not there, does not open, stops sending, or is no
|
||||
longer listed (pulled out: looked for every 5 s, as one pulled out can go on sending zeros): the default stands in for
|
||||
it (silence when there is none either) and it is tried again, found by its name in a list made then (it may come back
|
||||
under another id), after 3 s, then twice as long each time up to a minute; once it gives sound again the waits start
|
||||
over. Off, or no SDL: silence at the stream's rate, so the game's reads go on as they
|
||||
would. A change in the menu takes effect at the next read. HOS_MIC_LOG=1: a line a second while a stream runs (its
|
||||
frames and level). */
|
||||
#include "hos.h"
|
||||
#include "hos_sdl.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
|
||||
#define MIC_MAGIC 0x4D494349u /* "MICI": the high word of our handle in the game's InputStreamType */
|
||||
#define MAX_STREAMS 4
|
||||
#define MAX_DEVICES 16
|
||||
#define QUIET_NS 2000000000LL /* a microphone that gives nothing this long is taken as gone */
|
||||
#define RETRY_NS 3000000000LL /* a chosen microphone that is not there: tried again after this, */
|
||||
#define RETRY_MAX_NS 60000000000LL /* twice as long each time up to this */
|
||||
#define CHECK_NS 5000000000LL /* an open microphone looked for in a list made now this often (one pulled out may go on
|
||||
sending zeros: SDL3 on Windows) */
|
||||
enum { STATE_STOPPED = 1, STATE_STARTED = 2 }; /* (the game starts a stream whose state is not 2, stops one whose is) */
|
||||
/* nn::audio::SampleFormat */
|
||||
enum { FMT_PCM8 = 1, FMT_PCM16 = 2, FMT_PCM24 = 3, FMT_PCM32 = 4, FMT_FLOAT = 5 };
|
||||
|
||||
typedef struct {
|
||||
int used, users; /* (users: the started streams reading it) */
|
||||
int format, channels, rate, frame_bytes;
|
||||
long gen; /* the menu's choice it follows (sel_gen) */
|
||||
int mode; /* 0 off, 1 the system's default, 2 the microphone named want */
|
||||
char want[128];
|
||||
uint32_t want_id; /* (its id when chosen or last opened, 0 unknown: of two with one name, the one chosen) */
|
||||
void *mic; /* the SDL device, NULL: silence */
|
||||
int standin; /* (mic is the default, standing in for want) */
|
||||
int64_t heard_ns; /* (the last time the microphone gave anything) */
|
||||
int64_t check_ns; /* (when the wanted one, open, is next looked for in a fresh list) */
|
||||
int64_t retry_ns, retry_wait; /* (the wanted microphone not open: when to try again, and the wait after that) */
|
||||
int64_t silence_from_ns, silence_made; /* (silence: counted from here, frames of it made) */
|
||||
int failures; /* (in a row, since it last gave sound: logged at the first) */
|
||||
} Source;
|
||||
|
||||
typedef struct {
|
||||
int used, started, raw;
|
||||
int format, channels, rate, frame_bytes, capacity; /* (capacity: frames the stream holds, the open's last argument) */
|
||||
int source; /* the source it reads while started (-1 none) */
|
||||
uint8_t *ring; /* what was recorded for it and not read: capacity's worth at most, the oldest dropped */
|
||||
int ring_start, ring_len;
|
||||
int64_t frames_read, log_next_ns;
|
||||
int peak; /* (the loudest sample since the last log line, 16-bit) */
|
||||
} InStream;
|
||||
|
||||
static InStream streams[MAX_STREAMS];
|
||||
static Source sources[MAX_STREAMS];
|
||||
static SRWLOCK lock = SRWLOCK_INIT; /* the streams and the sources (the game's threads) */
|
||||
static SRWLOCK list_lock = SRWLOCK_INIT; /* the device list (the menu's thread too): never held while listing them */
|
||||
static uint32_t dev_ids[MAX_DEVICES];
|
||||
static char dev_names[MAX_DEVICES][128];
|
||||
static int dev_count = -1; /* (-1: not listed yet) */
|
||||
static long sel_gen = 1; /* the menu's choice (hos_mic_select), under list_lock: */
|
||||
static int sel_mode = 1; /* (before the menu says: the system's default) */
|
||||
static char sel_name[128];
|
||||
static int sel_index = -1;
|
||||
static int log_on = -1;
|
||||
|
||||
/* ---- the devices, for the menu (gpu/vk/vk_api.h: MkwVkHost mic_count, mic_name) ---- */
|
||||
int hos_mic_count(void) { /* (lists them again: a microphone plugged in since shows; SDL asked without a lock held) */
|
||||
uint32_t ids[MAX_DEVICES];
|
||||
char names[MAX_DEVICES][128];
|
||||
const int n = hos_sdl_mic_list(ids, names, MAX_DEVICES);
|
||||
AcquireSRWLockExclusive(&list_lock);
|
||||
memcpy(dev_ids, ids, sizeof ids), memcpy(dev_names, names, sizeof names), dev_count = n;
|
||||
ReleaseSRWLockExclusive(&list_lock);
|
||||
return n;
|
||||
}
|
||||
const char *hos_mic_name(int index) {
|
||||
static char name[128];
|
||||
AcquireSRWLockShared(&list_lock);
|
||||
snprintf(name, sizeof name, "%s", index >= 0 && index < dev_count ? dev_names[index] : "");
|
||||
ReleaseSRWLockShared(&list_lock);
|
||||
return name;
|
||||
}
|
||||
void hos_mic_select(int mode, const char *name, int index) { /* (the row's choice: taken at the streams' next read) */
|
||||
AcquireSRWLockExclusive(&list_lock);
|
||||
sel_mode = mode, sel_index = index, sel_gen++;
|
||||
snprintf(sel_name, sizeof sel_name, "%s", name ? name : "");
|
||||
ReleaseSRWLockExclusive(&list_lock);
|
||||
}
|
||||
|
||||
/* ---- the sources: one microphone (or silence) for the started streams of one format ---- */
|
||||
static uint16_t sdl_format(int f) { /* (SDL_AudioFormat: little-endian, signed) */
|
||||
return f == FMT_PCM8 ? 0x8008 : f == FMT_PCM32 ? 0x8020 : f == FMT_FLOAT ? 0x8120 : 0x8010;
|
||||
}
|
||||
static int sample_bytes(int f) { return f == FMT_PCM8 ? 1 : f == FMT_PCM16 ? 2 : f == FMT_PCM24 ? 3 : 4; }
|
||||
|
||||
static void push(InStream *s, const uint8_t *in, int n) { /* (into the stream's ring: the oldest dropped when full) */
|
||||
const int cap = s->capacity * s->frame_bytes;
|
||||
if (n > cap) { /* (the newest capacity's worth) */
|
||||
if (in) in += n - cap;
|
||||
n = cap;
|
||||
}
|
||||
const int drop = s->ring_len + n - cap;
|
||||
if (drop > 0) s->ring_start = (s->ring_start + drop) % cap, s->ring_len -= drop;
|
||||
const int at = (s->ring_start + s->ring_len) % cap, first = n < cap - at ? n : cap - at;
|
||||
if (in) memcpy(s->ring + at, in, (size_t)first), memcpy(s->ring, in + first, (size_t)(n - first));
|
||||
else memset(s->ring + at, 0, (size_t)first), memset(s->ring, 0, (size_t)(n - first)); /* (silence) */
|
||||
s->ring_len += n;
|
||||
}
|
||||
static void push_all(const Source *src, const uint8_t *in, int n) {
|
||||
for (int i = 0; i < MAX_STREAMS; i++)
|
||||
if (streams[i].used && streams[i].started && &sources[streams[i].source] == src) push(&streams[i], in, n);
|
||||
}
|
||||
|
||||
/* a device's name is the wanted one: the same, or its start when the wanted one is the menu's kept name (cut at kMicNameKept
|
||||
bytes, 60, at a character's start: 57 to 60 bytes; gpu/vk/vk_menu.cpp mic_key) */
|
||||
static int same_name(const char *name, const char *want) {
|
||||
const size_t n = strlen(want);
|
||||
return !strcmp(name, want) || (n >= 57 && !strncmp(name, want, n));
|
||||
}
|
||||
/* the SDL id of the wanted microphone in a list: the one it was chosen or last opened as while a device of its name has that
|
||||
id, else the first of its name */
|
||||
static int pick(const uint32_t *ids, char (*names)[128], int n, const Source *src, uint32_t *id) {
|
||||
int first = -1;
|
||||
for (int i = 0; i < n; i++)
|
||||
if (same_name(names[i], src->want)) {
|
||||
if (src->want_id && ids[i] == src->want_id) return *id = ids[i], 1;
|
||||
if (first < 0) first = i;
|
||||
}
|
||||
if (first >= 0) *id = ids[first];
|
||||
return first >= 0;
|
||||
}
|
||||
/* always in a list made now: a microphone plugged in again has another id, and SDL2's ids are places in its list, which move
|
||||
as devices come and go (the menu's list can be hours old) */
|
||||
static int find_device(const Source *src, uint32_t *id) {
|
||||
uint32_t ids[MAX_DEVICES];
|
||||
char names[MAX_DEVICES][128];
|
||||
const int n = hos_sdl_mic_list(ids, names, MAX_DEVICES);
|
||||
return pick(ids, names, n, src, id);
|
||||
}
|
||||
static const char *wanted(const Source *src) { return src->mode == 2 ? src->want : "the default microphone"; }
|
||||
static void close_mic(Source *src, int64_t now) {
|
||||
if (src->mic) {
|
||||
hos_sdl_mic_close(src->mic);
|
||||
src->silence_from_ns = now, src->silence_made = 0; /* (silence from here) */
|
||||
}
|
||||
src->mic = NULL, src->standin = 0;
|
||||
}
|
||||
static void use(Source *src, void *mic, int standin, int64_t now) { /* (a microphone opened: in place of the one before) */
|
||||
close_mic(src, now);
|
||||
src->mic = mic, src->standin = standin, src->heard_ns = now;
|
||||
}
|
||||
/* the wanted microphone could not be had: said once until it gives sound again, tried again later, each wait twice the last */
|
||||
static void missed(Source *src, int64_t now, const char *why) {
|
||||
if (!src->failures++)
|
||||
hos_log("audio in: %s %s: %s, tried again from time to time", wanted(src), why,
|
||||
src->standin ? "the default microphone stands in" : "silence");
|
||||
src->retry_ns = now + src->retry_wait;
|
||||
src->retry_wait = src->retry_wait * 2 < RETRY_MAX_NS ? src->retry_wait * 2 : RETRY_MAX_NS;
|
||||
}
|
||||
static void stand_in(Source *src, int64_t now) { /* (the default, while the wanted one cannot be had) */
|
||||
if (src->standin) return;
|
||||
void *standin = hos_sdl_mic_open(0, src->rate, src->channels, sdl_format(src->format));
|
||||
if (standin) use(src, standin, 1, now);
|
||||
else close_mic(src, now);
|
||||
}
|
||||
/* the wanted microphone, open, is gone (pulled out, stalled): the default stands in for a named one, tried again later */
|
||||
static void lost(Source *src, int64_t now, const char *why) {
|
||||
close_mic(src, now);
|
||||
if (src->mode == 2) stand_in(src, now);
|
||||
missed(src, now, why);
|
||||
}
|
||||
/* the wanted microphone opened; a named one that cannot be: the default stands in */
|
||||
static void connect(Source *src) {
|
||||
const int64_t now = hos_now_ns();
|
||||
if (src->mode <= 0) {
|
||||
close_mic(src, now);
|
||||
return;
|
||||
}
|
||||
uint32_t id = 0; /* (the system's default) */
|
||||
void *mic = NULL;
|
||||
const int found = src->mode == 1 || find_device(src, &id);
|
||||
if (found) mic = hos_sdl_mic_open(id, src->rate, src->channels, sdl_format(src->format));
|
||||
if (mic) {
|
||||
if (!src->failures) hos_log("audio in: %s open (%d Hz, %d channel%s)", wanted(src), src->rate, src->channels,
|
||||
src->channels == 1 ? "" : "s");
|
||||
use(src, mic, 0, now);
|
||||
if (src->mode == 2) src->want_id = id; /* (under the id it has now: the menu's next word of it is the same choice) */
|
||||
src->check_ns = now + CHECK_NS;
|
||||
return;
|
||||
}
|
||||
if (src->mode == 2) stand_in(src, now);
|
||||
else close_mic(src, now);
|
||||
missed(src, now, found ? "did not open" : "is not plugged in");
|
||||
if (src->failures == 1 && found) hos_log("audio in: (%s)", hos_sdl_error());
|
||||
}
|
||||
/* the menu's choice now: opened again only when it is another microphone */
|
||||
static void choose(Source *src) {
|
||||
AcquireSRWLockShared(&list_lock);
|
||||
const long gen = sel_gen;
|
||||
const int mode = sel_mode, listed = mode == 2 && sel_index >= 0 && sel_index < dev_count && same_name(dev_names[sel_index], sel_name);
|
||||
char want[128];
|
||||
snprintf(want, sizeof want, "%s", listed ? dev_names[sel_index] : mode == 2 ? sel_name : ""); /* (the whole name when listed) */
|
||||
const uint32_t want_id = listed ? dev_ids[sel_index] : 0;
|
||||
ReleaseSRWLockShared(&list_lock);
|
||||
if (gen == src->gen) return;
|
||||
const int same = src->gen && mode == src->mode && (same_name(want, src->want) || same_name(src->want, want)) &&
|
||||
(!want_id || want_id == src->want_id);
|
||||
src->gen = gen;
|
||||
if (same) {
|
||||
if (strlen(want) > strlen(src->want)) snprintf(src->want, sizeof src->want, "%s", want);
|
||||
if (mode == 2 && sel_index < 0 && src->mic && !src->standin) src->check_ns = 0; /* (the menu sees it unplugged: look now) */
|
||||
return;
|
||||
}
|
||||
src->mode = mode, src->want_id = want_id;
|
||||
snprintf(src->want, sizeof src->want, "%s", want);
|
||||
src->failures = 0, src->retry_wait = RETRY_NS;
|
||||
if (mode <= 0) hos_log("audio in: the microphone is off in the menu: silence");
|
||||
connect(src);
|
||||
}
|
||||
/* what the source has recorded since, into its streams: the microphone's, or silence at the rate when there is none */
|
||||
static void pump(Source *src) {
|
||||
const int64_t now = hos_now_ns();
|
||||
if (src->mode > 0 && (!src->mic || src->standin) && now >= src->retry_ns) connect(src); /* (the wanted one again) */
|
||||
if (src->mode == 2 && src->mic && !src->standin && now >= src->check_ns) { /* (still plugged in?) */
|
||||
uint32_t id;
|
||||
src->check_ns = now + CHECK_NS;
|
||||
if (!find_device(src, &id)) lost(src, now, "was unplugged");
|
||||
}
|
||||
if (src->mic) {
|
||||
int most = 0; /* (the largest stream's capacity: more than that backlog is dropped before it reaches them) */
|
||||
for (int i = 0; i < MAX_STREAMS; i++)
|
||||
if (streams[i].used && streams[i].started && &sources[streams[i].source] == src) {
|
||||
const int bytes = streams[i].capacity * streams[i].frame_bytes;
|
||||
if (bytes > most) most = bytes;
|
||||
}
|
||||
uint8_t buf[4096];
|
||||
const int chunk = (int)sizeof buf - (int)sizeof buf % src->frame_bytes;
|
||||
int heard = 0, avail = hos_sdl_mic_available(src->mic);
|
||||
for (int drop = avail - most; drop > 0;) { /* (the game stopped reading a while) */
|
||||
const int got = hos_sdl_mic_read(src->mic, buf, drop < chunk ? drop - drop % src->frame_bytes : chunk);
|
||||
if (got <= 0) break;
|
||||
drop -= got, avail -= got, heard = 1;
|
||||
}
|
||||
while (avail > 0) {
|
||||
const int got = hos_sdl_mic_read(src->mic, buf, avail < chunk ? avail - avail % src->frame_bytes : chunk);
|
||||
if (got <= 0) break;
|
||||
push_all(src, buf, got), heard = 1;
|
||||
avail -= got;
|
||||
}
|
||||
if (heard) {
|
||||
src->heard_ns = now;
|
||||
if (src->failures && !src->standin) { /* (the wanted one gives sound again: the waits start over) */
|
||||
hos_log("audio in: %s is back", wanted(src));
|
||||
src->failures = 0, src->retry_wait = RETRY_NS;
|
||||
}
|
||||
} else if (now - src->heard_ns > QUIET_NS) { /* (pulled out, or its driver stopped) */
|
||||
if (src->standin) close_mic(src, now); /* (the stand-in gone quiet too: silence until the next try) */
|
||||
else lost(src, now, "stopped sending");
|
||||
}
|
||||
return;
|
||||
}
|
||||
const int64_t since = now - src->silence_from_ns; /* (in seconds and the rest: no overflow however long) */
|
||||
int64_t due = since / 1000000000LL * src->rate + since % 1000000000LL * src->rate / 1000000000LL - src->silence_made;
|
||||
src->silence_made += due;
|
||||
if (src->silence_made >= src->rate) { /* (whole seconds into the start: no overflow however long it stays silent) */
|
||||
const int64_t secs = src->silence_made / src->rate;
|
||||
src->silence_from_ns += secs * 1000000000LL, src->silence_made -= secs * src->rate;
|
||||
}
|
||||
if (due > src->rate) due = src->rate; /* (more than a second is past every stream's capacity anyway) */
|
||||
if (due > 0) push_all(src, NULL, (int)due * src->frame_bytes);
|
||||
}
|
||||
static void pump_all(void) {
|
||||
for (int i = 0; i < MAX_STREAMS; i++)
|
||||
if (sources[i].used) {
|
||||
choose(&sources[i]);
|
||||
pump(&sources[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the streams ---- */
|
||||
static InStream *stream_of(uint64_t obj) {
|
||||
if (!obj) return NULL;
|
||||
const uint64_t h = G64(obj);
|
||||
const int i = (int)(h & 0xFFFF) - 1;
|
||||
if ((uint32_t)(h >> 32) != MIC_MAGIC || i < 0 || i >= MAX_STREAMS || !streams[i].used) return NULL;
|
||||
return &streams[i];
|
||||
}
|
||||
static void attach(InStream *s) { /* (the source of its format, made when there is none) */
|
||||
int free_at = -1;
|
||||
for (int i = 0; i < MAX_STREAMS; i++) {
|
||||
const Source *src = &sources[i];
|
||||
if (src->used && src->format == s->format && src->channels == s->channels && src->rate == s->rate) {
|
||||
s->source = i, sources[i].users++;
|
||||
return;
|
||||
}
|
||||
if (!src->used && free_at < 0) free_at = i;
|
||||
}
|
||||
Source *src = &sources[free_at]; /* (as many sources as streams: one is free) */
|
||||
memset(src, 0, sizeof *src);
|
||||
src->used = 1, src->users = 1, src->silence_from_ns = hos_now_ns(), src->retry_wait = RETRY_NS;
|
||||
src->format = s->format, src->channels = s->channels, src->rate = s->rate, src->frame_bytes = s->frame_bytes;
|
||||
s->source = free_at;
|
||||
choose(src);
|
||||
}
|
||||
static void detach(InStream *s) {
|
||||
if (s->source < 0) return;
|
||||
Source *src = &sources[s->source];
|
||||
s->source = -1;
|
||||
if (--src->users > 0) return;
|
||||
close_mic(src, hos_now_ns());
|
||||
memset(src, 0, sizeof *src);
|
||||
}
|
||||
static void note_read(InStream *s, const uint8_t *p, int frames) {
|
||||
s->frames_read += frames;
|
||||
if (log_on < 0) log_on = getenv("HOS_MIC_LOG") != NULL;
|
||||
if (!log_on) return;
|
||||
if (s->format == FMT_PCM16)
|
||||
for (int i = 0; i < frames * s->channels; i++) {
|
||||
int v = ((const int16_t *)p)[i];
|
||||
if (v < 0) v = -v;
|
||||
if (v > s->peak) s->peak = v;
|
||||
}
|
||||
const int64_t now = hos_now_ns();
|
||||
if (now >= s->log_next_ns) {
|
||||
hos_log("audio in: stream %d: %lld frames read, peak %d of 32767 in the last second", (int)(s - streams),
|
||||
(long long)s->frames_read, s->peak);
|
||||
s->peak = 0, s->log_next_ns = now + 1000000000LL;
|
||||
}
|
||||
}
|
||||
|
||||
/* ListVirtualInputDevices(AudioDeviceName *names, int count): one (256 bytes, a name) */
|
||||
HLE(_ZN2nn5audio23ListVirtualInputDevicesEPNS0_15AudioDeviceNameEi) {
|
||||
if ((int)ARG(1) <= 0 || !ARG(0)) { RET(0); return; }
|
||||
memset(GP(ARG(0)), 0, 256);
|
||||
memcpy(GP(ARG(0)), "MainAudioIn", 11);
|
||||
RET(1);
|
||||
}
|
||||
HLE(_ZN2nn5audio28GetDefaultVirtualInputDeviceEPNS0_15AudioDeviceNameE) {
|
||||
if (ARG(0)) memset(GP(ARG(0)), 0, 256), memcpy(GP(ARG(0)), "MainAudioIn", 11);
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn5audio26GetTrueRawAudioInputDeviceEPNS0_15AudioDeviceNameE) {
|
||||
if (ARG(0)) memset(GP(ARG(0)), 0, 256), memcpy(GP(ARG(0)), "RawAudioIn", 10);
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn5audio41IsVirtualInputDeviceStreamFormatSupportedERKNS0_15AudioDeviceNameERKNS0_12StreamFormatE) { RET(1); }
|
||||
|
||||
/* OpenInputStream(InputStreamType *, void *work, size_t, const AudioDeviceName &, const StreamFormat &, int frames).
|
||||
StreamFormat: {SampleFormat, channel count, sample rate} (the game's: {2, 1, 48000}). (The overload with an
|
||||
os::SystemEvent is not here: OoT does not import it, and a stub of it logs its first call, where an event never signalled
|
||||
could leave a waiter blocked) */
|
||||
HLE(_ZN2nn5audio15OpenInputStreamEPNS0_15InputStreamTypeEPvmRKNS0_15AudioDeviceNameERKNS0_12StreamFormatEi) {
|
||||
const uint64_t obj = ARG(0), name = ARG(3), format = ARG(4);
|
||||
const int frames = (int)ARG(5);
|
||||
AcquireSRWLockExclusive(&lock);
|
||||
int i = 0;
|
||||
while (i < MAX_STREAMS && streams[i].used) i++;
|
||||
if (!obj || !format || i == MAX_STREAMS) {
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
hos_log("audio in: an input stream did not open (%s)", i == MAX_STREAMS ? "too many" : "no stream or format");
|
||||
RET(0x1F3); /* (a failure: the game leaves the stream alone) */
|
||||
return;
|
||||
}
|
||||
InStream *s = &streams[i];
|
||||
memset(s, 0, sizeof *s);
|
||||
s->format = (int)G32(format), s->channels = (int)G32(format + 4), s->rate = (int)G32(format + 8);
|
||||
if (s->format < FMT_PCM8 || s->format > FMT_FLOAT || s->format == FMT_PCM24) s->format = FMT_PCM16;
|
||||
if (s->channels < 1 || s->channels > 8) s->channels = 1;
|
||||
if (s->rate < 8000 || s->rate > 192000) s->rate = 48000;
|
||||
s->frame_bytes = sample_bytes(s->format) * s->channels;
|
||||
/* (hookshot) at most 10 s: the ring's byte offsets are ints (a larger frame count from the game overflowed them) */
|
||||
s->capacity = frames > 0 && frames <= s->rate * 10 ? frames : frames > 0 ? s->rate * 10 : s->rate / 10;
|
||||
s->ring = (uint8_t *)malloc((size_t)s->capacity * s->frame_bytes);
|
||||
if (!s->ring) {
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
RET(0x1F3);
|
||||
return;
|
||||
}
|
||||
s->used = 1, s->source = -1;
|
||||
s->raw = name && !memcmp(GP(name), "RawAudioIn", 10);
|
||||
G64(obj) = (uint64_t)MIC_MAGIC << 32 | (uint64_t)(i + 1);
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
hos_log("audio in: stream %d opened%s: format %d, %d channel%s, %d Hz, %d frames", i, s->raw ? " (raw)" : "", s->format,
|
||||
s->channels, s->channels == 1 ? "" : "s", s->rate, s->capacity);
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn5audio16CloseInputStreamEPNS0_15InputStreamTypeE) {
|
||||
AcquireSRWLockExclusive(&lock);
|
||||
InStream *s = stream_of(ARG(0));
|
||||
if (s) {
|
||||
if (s->started) detach(s);
|
||||
free(s->ring);
|
||||
memset(s, 0, sizeof *s);
|
||||
G64(ARG(0)) = 0;
|
||||
}
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
}
|
||||
HLE(_ZN2nn5audio16StartInputStreamEPNS0_15InputStreamTypeE) {
|
||||
AcquireSRWLockExclusive(&lock);
|
||||
InStream *s = stream_of(ARG(0));
|
||||
if (s && !s->started) {
|
||||
s->started = 1, s->ring_start = s->ring_len = 0;
|
||||
attach(s);
|
||||
}
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
RET(s ? 0 : 0x1F3);
|
||||
}
|
||||
HLE(_ZN2nn5audio15StopInputStreamEPNS0_15InputStreamTypeE) {
|
||||
AcquireSRWLockExclusive(&lock);
|
||||
InStream *s = stream_of(ARG(0));
|
||||
if (s && s->started) {
|
||||
s->started = 0;
|
||||
detach(s);
|
||||
hos_log("audio in: stream %d stopped (%lld frames read)", (int)(s - streams), (long long)s->frames_read);
|
||||
}
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn5audio16PurgeInputStreamEPNS0_15InputStreamTypeE) { /* (what was recorded and not read: gone) */
|
||||
AcquireSRWLockExclusive(&lock);
|
||||
InStream *s = stream_of(ARG(0));
|
||||
if (s) {
|
||||
if (s->started) pump_all(); /* (what the source had for it so far goes too) */
|
||||
s->ring_start = s->ring_len = 0;
|
||||
}
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn5audio19GetInputStreamStateEPKNS0_15InputStreamTypeE) {
|
||||
AcquireSRWLockExclusive(&lock);
|
||||
InStream *s = stream_of(ARG(0));
|
||||
RET(s && s->started ? STATE_STARTED : STATE_STOPPED);
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
}
|
||||
static int filled(InStream *s) {
|
||||
if (!s->started) return 0;
|
||||
pump_all();
|
||||
return s->ring_len / s->frame_bytes;
|
||||
}
|
||||
HLE(_ZN2nn5audio30GetInputStreamFilledFrameCountEPKNS0_15InputStreamTypeE) {
|
||||
AcquireSRWLockExclusive(&lock);
|
||||
InStream *s = stream_of(ARG(0));
|
||||
RET(s ? filled(s) : 0);
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
}
|
||||
HLE(_ZN2nn5audio28GetInputStreamFreeFrameCountEPKNS0_15InputStreamTypeE) {
|
||||
AcquireSRWLockExclusive(&lock);
|
||||
InStream *s = stream_of(ARG(0));
|
||||
RET(s ? s->capacity - filled(s) : 0);
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
}
|
||||
HLE(_ZN2nn5audio32GetInputStreamCapacityFrameCountEPKNS0_15InputStreamTypeE) {
|
||||
AcquireSRWLockExclusive(&lock);
|
||||
InStream *s = stream_of(ARG(0));
|
||||
RET(s ? s->capacity : 0);
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
}
|
||||
/* ReadInputStream(InputStreamType *, void *buffer, int frames): the frames read */
|
||||
HLE(_ZN2nn5audio15ReadInputStreamEPNS0_15InputStreamTypeEPvi) {
|
||||
AcquireSRWLockExclusive(&lock);
|
||||
InStream *s = stream_of(ARG(0));
|
||||
int frames = 0;
|
||||
if (s && ARG(1) && (int)ARG(2) > 0) {
|
||||
const int have = filled(s);
|
||||
frames = (int)ARG(2) < have ? (int)ARG(2) : have;
|
||||
const int cap = s->capacity * s->frame_bytes, n = frames * s->frame_bytes;
|
||||
uint8_t *dst = (uint8_t *)hos_guest_range(ARG(1), (uint64_t)n); /* (hookshot: only into guest memory) */
|
||||
if (!dst) frames = 0;
|
||||
else {
|
||||
const int first = n < cap - s->ring_start ? n : cap - s->ring_start;
|
||||
memcpy(dst, s->ring + s->ring_start, (size_t)first);
|
||||
memcpy(dst + first, s->ring, (size_t)(n - first));
|
||||
s->ring_start = (s->ring_start + n) % cap, s->ring_len -= n;
|
||||
HOS_WRITTEN(dst, (size_t)n);
|
||||
note_read(s, dst, frames);
|
||||
}
|
||||
}
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
RET(frames);
|
||||
}
|
||||
/* GetInputStreamStatistics(InputStreamType *, bool reset): a structure returned through x8; the game checks its second
|
||||
64-bit word (frames lost?) against 1. Nothing lost */
|
||||
HLE(_ZN2nn5audio24GetInputStreamStatisticsEPNS0_15InputStreamTypeEb) {
|
||||
if (c->x[8]) memset(GP(c->x[8]), 0, 16);
|
||||
}
|
||||
HLE(_ZN2nn5audio18SetInputStreamGainEPNS0_15InputStreamTypeEfNS_8TimeSpanE) { (void)c; } /* (the device's level as the system has it) */
|
||||
HLE(_ZN2nn5audio18GetInputStreamGainEPKNS0_15InputStreamTypeE) {
|
||||
const float one = 1.0f;
|
||||
c->vreg[0][0] = c->vreg[0][1] = 0;
|
||||
memcpy(&c->vreg[0][0], &one, 4);
|
||||
}
|
||||
126
host/nn_codec.c
Normal file
126
host/nn_codec.c
Normal file
@@ -0,0 +1,126 @@
|
||||
/* nn::codec: the hardware Opus decoder, on libopus (third_party/opus).
|
||||
|
||||
Input packets come as on the hardware decoder: an 8-byte header {u32 big-endian payload size, u32 big-endian
|
||||
final range} then the Opus packet. DecodeOpusInterleavedWithHardware decodes one packet into interleaved
|
||||
16-bit PCM and says how many bytes it consumed (header + payload) and how many samples (per channel) it made.
|
||||
Each HardwareOpusDecoderType gets our handle in its first 8 bytes. */
|
||||
#include "hos.h"
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <opus.h>
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
|
||||
#define CODEC_MAGIC 0x4F505553u /* 'OPUS' */
|
||||
#define MAX_DECODERS 64
|
||||
|
||||
typedef struct {
|
||||
OpusDecoder *dec;
|
||||
int rate, channels;
|
||||
} Dec;
|
||||
static Dec decs[MAX_DECODERS];
|
||||
static volatile LONG decs_lock;
|
||||
|
||||
static void dlock(void) { while (InterlockedExchange(&decs_lock, 1)) hos_sleep_ns(1000); }
|
||||
static void dunlock(void) { InterlockedExchange(&decs_lock, 0); }
|
||||
|
||||
static Dec *dec_of(uint64_t obj) {
|
||||
if (!obj) return NULL;
|
||||
const uint64_t h = G64(obj);
|
||||
if ((uint32_t)(h >> 32) != CODEC_MAGIC) return NULL;
|
||||
const uint32_t i = (uint32_t)h;
|
||||
return i < MAX_DECODERS && decs[i].dec ? &decs[i] : NULL;
|
||||
}
|
||||
static uint32_t be32(const uint8_t *p) { return (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3]; }
|
||||
|
||||
/* GetHardwareOpusDecoderWorkBufferSize(int sampleRate, int channelCount, ...): the game allocates it; we keep our
|
||||
state on the host */
|
||||
HLE(_ZN2nn5codec36GetHardwareOpusDecoderWorkBufferSizeEiii) { RET(0x1000); }
|
||||
|
||||
/* InitializeHardwareOpusDecoder(HardwareOpusDecoderType*, int sampleRate, int channelCount, void* workBuffer,
|
||||
size_t workBufferSize, int option) -> Result */
|
||||
HLE(_ZN2nn5codec29InitializeHardwareOpusDecoderEPNS0_23HardwareOpusDecoderTypeEiiPvmi) {
|
||||
const int rate = (int)ARG(1), channels = (int)ARG(2);
|
||||
int err = 0;
|
||||
OpusDecoder *d = opus_decoder_create(rate, channels, &err);
|
||||
if (!d || err != OPUS_OK) {
|
||||
hos_log("codec: Opus decoder %d Hz %d channels not created (%d)", rate, channels, err);
|
||||
RET(0x1F0); /* (any failure result) */
|
||||
return;
|
||||
}
|
||||
dlock();
|
||||
int i = 0;
|
||||
while (i < MAX_DECODERS && decs[i].dec) i++;
|
||||
if (i == MAX_DECODERS) {
|
||||
dunlock();
|
||||
opus_decoder_destroy(d);
|
||||
RET(0x1F0);
|
||||
return;
|
||||
}
|
||||
decs[i].dec = d;
|
||||
decs[i].rate = rate;
|
||||
decs[i].channels = channels;
|
||||
G64(ARG(0)) = (uint64_t)CODEC_MAGIC << 32 | (uint32_t)i;
|
||||
dunlock();
|
||||
static int logged;
|
||||
if (logged++ < 8) hos_log("codec: Opus decoder %d: %d Hz, %d channels", i, rate, channels);
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn5codec27FinalizeHardwareOpusDecoderEPNS0_23HardwareOpusDecoderTypeE) {
|
||||
dlock();
|
||||
Dec *d = dec_of(ARG(0));
|
||||
if (d) {
|
||||
opus_decoder_destroy(d->dec);
|
||||
d->dec = NULL;
|
||||
G64(ARG(0)) = 0;
|
||||
}
|
||||
dunlock();
|
||||
}
|
||||
HLE(_ZN2nn5codec24ResetHardwareOpusDecoderEPNS0_23HardwareOpusDecoderTypeE) {
|
||||
Dec *d = dec_of(ARG(0));
|
||||
if (d) opus_decoder_ctl(d->dec, OPUS_RESET_STATE);
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn5codec32GetHardwareOpusDecoderSampleRateEPKNS0_23HardwareOpusDecoderTypeE) {
|
||||
Dec *d = dec_of(ARG(0));
|
||||
RET(d ? d->rate : 48000);
|
||||
}
|
||||
HLE(_ZN2nn5codec34GetHardwareOpusDecoderChannelCountEPKNS0_23HardwareOpusDecoderTypeE) {
|
||||
Dec *d = dec_of(ARG(0));
|
||||
RET(d ? d->channels : 2);
|
||||
}
|
||||
|
||||
/* GetOpusPacketSize(const uint8* data, size_t size): the size of the packet the header describes, header included */
|
||||
HLE(_ZN2nn5codec17GetOpusPacketSizeEPKhm) {
|
||||
const uint8_t *p = (const uint8_t *)GP(ARG(0));
|
||||
const uint64_t size = ARG(1);
|
||||
const uint64_t r = size >= 8 ? 8 + (uint64_t)be32(p) : 0;
|
||||
static int logged;
|
||||
if (logged++ < 6) hos_log("codec: GetOpusPacketSize(%#llx, %llu): header %08x %08x -> %llu", (unsigned long long)ARG(0),
|
||||
(unsigned long long)size, be32(p), be32(p + 4), (unsigned long long)r);
|
||||
RET(r);
|
||||
}
|
||||
|
||||
/* DecodeOpusInterleavedWithHardware(HardwareOpusDecoderType*, size_t* consumed, int* sampleCount, int16* out,
|
||||
size_t outSize, const void* in, size_t inSize) -> Result */
|
||||
HLE(_ZN2nn5codec33DecodeOpusInterleavedWithHardwareEPNS0_23HardwareOpusDecoderTypeEPmPiPsmPKvm) {
|
||||
Dec *d = dec_of(ARG(0));
|
||||
const uint64_t out_size = ARG(4), in_size = ARG(6);
|
||||
/* (hookshot) both buffers in guest memory, and the frame count an int (a 64-bit size was cut to any int) */
|
||||
const uint8_t *in = (const uint8_t *)hos_guest_range(ARG(5), in_size);
|
||||
if (!d || in_size < 8 || !in) { RET(0x1F0); return; }
|
||||
const uint32_t len = be32(in);
|
||||
if (len > in_size - 8) { RET(0x1F0); return; }
|
||||
const uint64_t room = out_size / (2 * (uint64_t)d->channels);
|
||||
const int frames = room < 5760 ? (int)room : 5760; /* (Opus' longest packet: 120 ms at 48 kHz) */
|
||||
opus_int16 *out = (opus_int16 *)hos_guest_range(ARG(3), (uint64_t)frames * 2 * (uint64_t)d->channels);
|
||||
if (!out) { RET(0x1F0); return; }
|
||||
const int n = opus_decode(d->dec, in + 8, (opus_int32)len, out, frames, 0);
|
||||
static int logged;
|
||||
if (logged++ < 6)
|
||||
hos_log("codec: decode %u bytes (of %llu) -> %d samples (room for %d)", len, (unsigned long long)in_size, n, frames);
|
||||
if (n < 0) { RET(0x1F0); return; }
|
||||
if (ARG(1)) G64(ARG(1)) = 8 + (uint64_t)len;
|
||||
if (ARG(2)) G32(ARG(2)) = (uint32_t)n;
|
||||
RET(0);
|
||||
}
|
||||
22
host/nn_diag.c
Normal file
22
host/nn_diag.c
Normal file
@@ -0,0 +1,22 @@
|
||||
/* nn::diag: the game's own log lines and aborts. */
|
||||
#include "hos.h"
|
||||
#include <stdio.h>
|
||||
|
||||
/* nn::diag::detail::PutImpl(LogMetaData const&, char const* text, unsigned long length) */
|
||||
HLE(_ZN2nn4diag6detail7PutImplERKNS0_11LogMetaDataEPKcm) {
|
||||
uint64_t n = ARG(2) > 4000 ? 4000 : ARG(2);
|
||||
char buf[4001];
|
||||
memcpy(buf, GP(ARG(1)), n);
|
||||
buf[n] = 0;
|
||||
while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = 0;
|
||||
hos_log("game: %s", buf);
|
||||
}
|
||||
|
||||
/* nn::diag::detail::AbortImpl() */
|
||||
HLE(_ZN2nn4diag6detail9AbortImplEv) { hos_fatal(c, "the game aborted (nn::diag::detail::AbortImpl)"); }
|
||||
|
||||
/* nn::detail::UnexpectedDefaultImpl(): a switch reached a case the SDK says cannot happen */
|
||||
HLE(_ZN2nn6detail21UnexpectedDefaultImplEv) { hos_fatal(c, "nn::detail::UnexpectedDefaultImpl"); }
|
||||
|
||||
/* nn::diag::GetBacktrace(unsigned long*, int) -> int: none */
|
||||
HLE(_ZN2nn4diag12GetBacktraceEPmi) { RET(0); }
|
||||
652
host/nn_fs.c
Normal file
652
host/nn_fs.c
Normal file
@@ -0,0 +1,652 @@
|
||||
/* nn::fs: mounts map to host folders.
|
||||
rom: the game's RomFS (extracted by tools/nx.py romfs), read-only
|
||||
save: <user>/save/<uid> (MountSaveData / MountSaveDataReadOnly)
|
||||
cache: <user>/cache/<index> (MountCacheStorage)
|
||||
temp: <user>/temp (MountTemporaryStorage)
|
||||
hos_romfs_dir and hos_user_dir are set by hos_main.c. Reads are positional (ReadFile with an offset), so any number
|
||||
of guest threads can read one file at once. Results: switchbrew "Error codes" (module 2 = fs). */
|
||||
#include "hos.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
|
||||
/* (hookshot, #1468) A game folder whose deepest file passes 260 characters (MAX_PATH: "E:\Games\...\romfs\Event\EventSetting\
|
||||
Ev..." at 262) is read too. The host paths here are up to HOS_FS_PATH bytes, and on Windows each file call goes through
|
||||
its wide function: the path converted from the game's UTF-8 strings and, when it is
|
||||
long and absolute, given the extended-length prefix \\?\ (with its / made \), which Windows takes without its long-paths
|
||||
setting. Short paths are as they were. */
|
||||
#define HOS_FS_PATH 1024
|
||||
#ifdef _WIN32
|
||||
static const wchar_t *fs_wide(const char *p, wchar_t *w, size_t cap) {
|
||||
const size_t n = strlen(p);
|
||||
const int already = p[0] == '\\' && p[1] == '\\' && p[2] == '?';
|
||||
const int unc = !already && p[0] == '\\' && p[1] == '\\';
|
||||
const int drive = p[0] && p[1] == ':' && (p[2] == '\\' || p[2] == '/');
|
||||
const int extended = !already && n >= 240 && (drive || unc);
|
||||
size_t at = 0;
|
||||
if (extended) {
|
||||
wcscpy(w, unc ? L"\\\\?\\UNC" : L"\\\\?\\");
|
||||
at = wcslen(w);
|
||||
if (unc) p++; /* (\\server\share -> \\?\UNC\server\share) */
|
||||
}
|
||||
if (MultiByteToWideChar(CP_UTF8, 0, p, -1, w + at, (int)(cap - at)) <= 0) w[0] = 0;
|
||||
if (extended)
|
||||
for (wchar_t *q = w; *q; q++)
|
||||
if (*q == L'/') *q = L'\\';
|
||||
return w;
|
||||
}
|
||||
#define FS_W(p) fs_wide((p), (wchar_t[HOS_FS_PATH + 8]){0}, HOS_FS_PATH + 8)
|
||||
static void fs_find_data(const WIN32_FIND_DATAW *w, WIN32_FIND_DATAA *a) {
|
||||
a->dwFileAttributes = w->dwFileAttributes;
|
||||
a->ftCreationTime = w->ftCreationTime, a->ftLastAccessTime = w->ftLastAccessTime, a->ftLastWriteTime = w->ftLastWriteTime;
|
||||
a->nFileSizeHigh = w->nFileSizeHigh, a->nFileSizeLow = w->nFileSizeLow;
|
||||
a->dwReserved0 = w->dwReserved0, a->dwReserved1 = w->dwReserved1;
|
||||
if (WideCharToMultiByte(CP_UTF8, 0, w->cFileName, -1, a->cFileName, (int)sizeof a->cFileName, NULL, NULL) <= 0) a->cFileName[0] = 0;
|
||||
if (WideCharToMultiByte(CP_UTF8, 0, w->cAlternateFileName, -1, a->cAlternateFileName, (int)sizeof a->cAlternateFileName, NULL,
|
||||
NULL) <= 0)
|
||||
a->cAlternateFileName[0] = 0;
|
||||
}
|
||||
static HANDLE fs_CreateFile(const char *p, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES sa, DWORD how, DWORD flags, HANDLE t) {
|
||||
return CreateFileW(FS_W(p), access, share, sa, how, flags, t);
|
||||
}
|
||||
static DWORD fs_GetFileAttributes(const char *p) { return GetFileAttributesW(FS_W(p)); }
|
||||
static BOOL fs_CreateDirectory(const char *p, LPSECURITY_ATTRIBUTES sa) { return CreateDirectoryW(FS_W(p), sa); }
|
||||
static BOOL fs_DeleteFile(const char *p) { return DeleteFileW(FS_W(p)); }
|
||||
static BOOL fs_RemoveDirectory(const char *p) { return RemoveDirectoryW(FS_W(p)); }
|
||||
static BOOL fs_MoveFileEx(const char *a, const char *b, DWORD flags) { return MoveFileExW(FS_W(a), FS_W(b), flags); }
|
||||
static HANDLE fs_FindFirstFile(const char *p, WIN32_FIND_DATAA *fd) {
|
||||
WIN32_FIND_DATAW w;
|
||||
const HANDLE h = FindFirstFileW(FS_W(p), &w);
|
||||
if (h != INVALID_HANDLE_VALUE) fs_find_data(&w, fd);
|
||||
return h;
|
||||
}
|
||||
static BOOL fs_FindNextFile(HANDLE h, WIN32_FIND_DATAA *fd) {
|
||||
WIN32_FIND_DATAW w;
|
||||
if (!FindNextFileW(h, &w)) return FALSE;
|
||||
fs_find_data(&w, fd);
|
||||
return TRUE;
|
||||
}
|
||||
#define CreateFileA fs_CreateFile
|
||||
#define GetFileAttributesA fs_GetFileAttributes
|
||||
#define CreateDirectoryA fs_CreateDirectory
|
||||
#define DeleteFileA fs_DeleteFile
|
||||
#define RemoveDirectoryA fs_RemoveDirectory
|
||||
#define MoveFileExA fs_MoveFileEx
|
||||
#define FindFirstFileA fs_FindFirstFile
|
||||
#define FindNextFileA fs_FindNextFile
|
||||
#endif
|
||||
|
||||
const char *hos_romfs_dir, *hos_user_dir;
|
||||
|
||||
#define R_PATH_NOT_FOUND 0x202 /* fs::ResultPathNotFound */
|
||||
#define R_PATH_EXISTS 0x402 /* fs::ResultPathAlreadyExists */
|
||||
#define R_NOT_MOUNTED 0xCA02 /* fs::ResultInvalidMountName-ish: no such mount */
|
||||
#define R_TARGET_NOT_FOUND 0x7D402 /* fs::ResultTargetNotFound (save data) */
|
||||
|
||||
#define FS_PATH_MAX 0x302 /* (nn::fs paths: 0x300 bytes and the NUL; DirectoryEntry's name is 0x301) */
|
||||
|
||||
typedef struct { char name[32]; char root[HOS_FS_PATH]; int writable; } Mount;
|
||||
static Mount mounts[16];
|
||||
static int nmounts;
|
||||
static SRWLOCK mount_lock = SRWLOCK_INIT;
|
||||
|
||||
static int mount(const char *name, const char *root, int writable) { /* 0: the table is full (16 mounts) */
|
||||
AcquireSRWLockExclusive(&mount_lock);
|
||||
int i;
|
||||
for (i = 0; i < nmounts && strcmp(mounts[i].name, name); i++) {}
|
||||
if (i == nmounts) { /* (hookshot: a 17th name was written past the table) */
|
||||
if (nmounts == 16) {
|
||||
ReleaseSRWLockExclusive(&mount_lock);
|
||||
hos_log("fs: %s: not mounted (16 mounts already)", name);
|
||||
return 0;
|
||||
}
|
||||
nmounts++;
|
||||
}
|
||||
snprintf(mounts[i].name, sizeof mounts[i].name, "%s", name);
|
||||
snprintf(mounts[i].root, sizeof mounts[i].root, "%s", root);
|
||||
mounts[i].writable = writable;
|
||||
ReleaseSRWLockExclusive(&mount_lock);
|
||||
if (writable) CreateDirectoryA(root, NULL);
|
||||
hos_log("fs: mounted %s: -> %s", name, root);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int hos_mods_romfs(const char *rel, char *out, size_t cap); /* mods.c */
|
||||
int hos_mods_dir_extras(const char *rel, const char *base_dir, void (*fn)(void *, const char *, int, uint64_t), void *arg);
|
||||
|
||||
/* (hookshot) a guest path below its mount stays below it on the host: no "." or ".." part, no \\ or : (a drive or a
|
||||
Windows stream), no control characters; on Windows also no part ending in a dot or a space (Windows drops them) and
|
||||
no device name (CON, NUL, COM1, COM\u00b9, "NUL .txt"...) */
|
||||
static int guest_path_ok(const char *rest) {
|
||||
#ifdef _WIN32
|
||||
static const char *const devices[] = {"CON", "PRN", "AUX", "NUL", "COM", "LPT", "CONIN$", "CONOUT$", "CLOCK$"};
|
||||
#endif
|
||||
for (const char *p = rest; *p;) {
|
||||
const char *e = strchr(p, '/');
|
||||
const size_t n = e ? (size_t)(e - p) : strlen(p);
|
||||
if ((n == 1 && p[0] == '.') || (n == 2 && p[0] == '.' && p[1] == '.')) return 0;
|
||||
for (size_t i = 0; i < n; i++)
|
||||
if ((unsigned char)p[i] < 32 || p[i] == '\\' || p[i] == ':') return 0;
|
||||
#ifdef _WIN32
|
||||
if (n && (p[n - 1] == '.' || p[n - 1] == ' ')) return 0;
|
||||
for (size_t d = 0; d < sizeof devices / sizeof *devices; d++) {
|
||||
const size_t k = strlen(devices[d]);
|
||||
if (n < k || _strnicmp(p, devices[d], k)) continue;
|
||||
const char *after = p + k;
|
||||
if (k == 3 && (!strcmp(devices[d], "COM") || !strcmp(devices[d], "LPT"))) {
|
||||
/* (a digit, or a superscript 1, 2 or 3 in UTF-8, the game's code page: Windows takes those too) */
|
||||
if (after < p + n && *after >= '0' && *after <= '9') after++;
|
||||
else if (after + 1 < p + n && (unsigned char)after[0] == 0xC2 &&
|
||||
((unsigned char)after[1] == 0xB9 || (unsigned char)after[1] == 0xB2 || (unsigned char)after[1] == 0xB3))
|
||||
after += 2;
|
||||
else continue;
|
||||
}
|
||||
while (after < p + n && *after == ' ') after++; /* ("NUL .txt" is NUL too) */
|
||||
if (after == p + n || *after == '.') return 0;
|
||||
}
|
||||
#endif
|
||||
p += n;
|
||||
while (*p == '/') p++;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* "mount:/a/b" -> host path (a mod's file instead of the RomFS one, when a mod has it: mods.c). Returns 0 if the mount
|
||||
is unknown, or the path leaves it (guest_path_ok). */
|
||||
static int host_path(const char *guest_mem, char *out, size_t cap, int *writable) {
|
||||
/* (hookshot) one copy of the path, read once: another guest thread may change guest memory between the check and
|
||||
the use */
|
||||
char guest[FS_PATH_MAX];
|
||||
if ((size_t)snprintf(guest, sizeof guest, "%s", guest_mem) >= sizeof guest) return 0;
|
||||
const char *colon = strchr(guest, ':');
|
||||
if (!colon) return 0;
|
||||
size_t n = (size_t)(colon - guest);
|
||||
int ok = 0;
|
||||
AcquireSRWLockShared(&mount_lock);
|
||||
for (int i = 0; i < nmounts; i++) {
|
||||
if (strlen(mounts[i].name) == n && !strncmp(mounts[i].name, guest, n)) {
|
||||
const char *rest = colon + 1;
|
||||
while (*rest == '/') rest++;
|
||||
if (!guest_path_ok(rest)) break;
|
||||
if (mounts[i].writable || !hos_mods_romfs(rest, out, cap))
|
||||
if ((size_t)snprintf(out, cap, "%s/%s", mounts[i].root, rest) >= cap) break; /* (cut short: not this path) */
|
||||
if (writable) *writable = mounts[i].writable;
|
||||
ok = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
ReleaseSRWLockShared(&mount_lock);
|
||||
for (char *p = out; ok && *p; p++) if (*p == '/') *p = '\\';
|
||||
return ok;
|
||||
}
|
||||
|
||||
/* For other OS layer parts that open game files themselves (videos): "mount:/a/b" -> host path, 0 if unknown. */
|
||||
int hos_fs_host_path(const char *guest, char *out, size_t cap) { return host_path(guest, out, cap, NULL); }
|
||||
|
||||
/* (hookshot) a guest string: "" unless it lies in guest memory and ends within FS_PATH_MAX bytes */
|
||||
static const char *gstr(uint64_t a) {
|
||||
if (!a || a >= (uint64_t)HOS_SPACE_END) return "";
|
||||
const uint64_t room = (uint64_t)HOS_SPACE_END - a;
|
||||
const char *s = (const char *)GP(a);
|
||||
const size_t max = room < FS_PATH_MAX ? (size_t)room : FS_PATH_MAX;
|
||||
return strnlen(s, max) < max ? s : "";
|
||||
}
|
||||
|
||||
static void make_dirs(const char *path) { /* every parent of path */
|
||||
char tmp[HOS_FS_PATH];
|
||||
snprintf(tmp, sizeof tmp, "%s", path);
|
||||
for (char *p = tmp + 3; *p; p++)
|
||||
if (*p == '\\') { *p = 0; CreateDirectoryA(tmp, NULL); *p = '\\'; }
|
||||
}
|
||||
|
||||
/* ---- handles: a FileHandle / DirectoryHandle is one pointer-sized value; ours are table indices + 1 ----------- */
|
||||
typedef struct { char name[HOS_FS_PATH]; int is_dir; uint64_t size; } ExtraEntry; /* (a listed folder's mod-only entries) */
|
||||
typedef struct {
|
||||
HANDLE h; int writable; HANDLE find; WIN32_FIND_DATAA fd; int find_done, is_dir; char path[HOS_FS_PATH];
|
||||
ExtraEntry *extras; int nextras, extra_pos;
|
||||
} Handle;
|
||||
static Handle *handles[4096];
|
||||
static SRWLOCK handle_lock = SRWLOCK_INIT;
|
||||
|
||||
static uint64_t new_handle(Handle *h) {
|
||||
AcquireSRWLockExclusive(&handle_lock);
|
||||
for (int i = 0; i < 4096; i++)
|
||||
if (!handles[i]) { handles[i] = h; ReleaseSRWLockExclusive(&handle_lock); return (uint64_t)i + 1; }
|
||||
ReleaseSRWLockExclusive(&handle_lock);
|
||||
hos_fatal(NULL, "fs: out of handles");
|
||||
return 0;
|
||||
}
|
||||
static Handle *get_handle(Ctx *c, uint64_t id) {
|
||||
Handle *h = id && id <= 4096 ? handles[id - 1] : NULL;
|
||||
if (!h) hos_fatal(c, "fs: bad handle %#llx", (unsigned long long)id);
|
||||
return h;
|
||||
}
|
||||
static void free_handle(uint64_t id) {
|
||||
AcquireSRWLockExclusive(&handle_lock);
|
||||
if (id && id <= 4096) handles[id - 1] = NULL;
|
||||
ReleaseSRWLockExclusive(&handle_lock);
|
||||
}
|
||||
|
||||
/* ---- mounts --------------------------------------------------------------------------------------------------- */
|
||||
HLE(_ZN2nn2fs22QueryMountRomCacheSizeEPm) { G64(ARG(0)) = 0x10000; RET(0); }
|
||||
HLE(_ZN2nn2fs8MountRomEPKcPvm) {
|
||||
if (!hos_romfs_dir) hos_fatal(c, "fs: MountRom but no RomFS folder given (--romfs)");
|
||||
RET(mount(gstr(ARG(0)), hos_romfs_dir, 0) ? 0 : R_NOT_MOUNTED);
|
||||
}
|
||||
/* (hookshot) MountRom(char const* name): the cacheless overload OoT uses (SDK 22). Left to the SDK it opens the
|
||||
file-system proxy over IPC and aborts on the empty reply. */
|
||||
HLE(_ZN2nn2fs8MountRomEPKc) {
|
||||
if (!hos_romfs_dir) hos_fatal(c, "fs: MountRom but no RomFS folder given (--romfs)");
|
||||
RET(mount(gstr(ARG(0)), hos_romfs_dir, 0) ? 0 : R_NOT_MOUNTED);
|
||||
}
|
||||
|
||||
static int user_mount(const char *name, const char *sub) {
|
||||
char root[HOS_FS_PATH];
|
||||
snprintf(root, sizeof root, "%s\\%s", hos_user_dir, sub);
|
||||
make_dirs(root);
|
||||
CreateDirectoryA(root, NULL);
|
||||
return mount(name, root, 1);
|
||||
}
|
||||
|
||||
/* nn::fs::IsSaveDataExisting(ApplicationId, account::Uid const&) -> bool */
|
||||
HLE(_ZN2nn2fs18IsSaveDataExistingENS_13ApplicationIdERKNS_7account3UidE) {
|
||||
char root[HOS_FS_PATH];
|
||||
snprintf(root, sizeof root, "%s\\save\\%016llx%016llx", hos_user_dir, (unsigned long long)G64(ARG(1) + 8),
|
||||
(unsigned long long)G64(ARG(1)));
|
||||
RET(GetFileAttributesA(root) != INVALID_FILE_ATTRIBUTES);
|
||||
}
|
||||
/* MountSaveData(char const*, account::Uid const&) */
|
||||
HLE(_ZN2nn2fs13MountSaveDataEPKcRKNS_7account3UidE) {
|
||||
char sub[64];
|
||||
snprintf(sub, sizeof sub, "save\\%016llx%016llx", (unsigned long long)G64(ARG(1) + 8), (unsigned long long)G64(ARG(1)));
|
||||
RET(user_mount(gstr(ARG(0)), sub) ? 0 : R_NOT_MOUNTED);
|
||||
}
|
||||
/* MountSaveDataReadOnly(char const*, ApplicationId, account::Uid const&) */
|
||||
HLE(_ZN2nn2fs21MountSaveDataReadOnlyEPKcNS_13ApplicationIdERKNS_7account3UidE) {
|
||||
char sub[64];
|
||||
snprintf(sub, sizeof sub, "save\\%016llx%016llx", (unsigned long long)G64(ARG(2) + 8), (unsigned long long)G64(ARG(2)));
|
||||
RET(user_mount(gstr(ARG(0)), sub) ? 0 : R_NOT_MOUNTED);
|
||||
}
|
||||
HLE(_ZN2nn2fs21MountTemporaryStorageEPKc) { RET(user_mount(gstr(ARG(0)), "temp") ? 0 : R_NOT_MOUNTED); }
|
||||
/* MountCacheStorage(char const*, int index) */
|
||||
HLE(_ZN2nn2fs17MountCacheStorageEPKci) {
|
||||
char sub[32];
|
||||
snprintf(sub, sizeof sub, "cache\\%d", (int)ARG(1));
|
||||
RET(user_mount(gstr(ARG(0)), sub) ? 0 : R_NOT_MOUNTED);
|
||||
}
|
||||
/* CreateCacheStorage(int index, long size, long journal) */
|
||||
HLE(_ZN2nn2fs18CreateCacheStorageEill) {
|
||||
char root[HOS_FS_PATH];
|
||||
snprintf(root, sizeof root, "%s\\cache\\%d\\", hos_user_dir, (int)ARG(0));
|
||||
make_dirs(root);
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn2fs18DeleteCacheStorageEi) { RET(0); }
|
||||
/* The cache-storage list: report the indices that exist on disk. Handle: one value; info: {s32 index, pad[0x1C]} */
|
||||
static int cache_list_pos;
|
||||
HLE(_ZN2nn2fs20OpenCacheStorageListEPNS0_22CacheStorageListHandleE) { G64(ARG(0)) = 1; cache_list_pos = 0; RET(0); }
|
||||
HLE(_ZN2nn2fs20ReadCacheStorageListEPiPNS0_16CacheStorageInfoENS0_22CacheStorageListHandleEi) {
|
||||
int n = 0, max = (int)ARG(3);
|
||||
for (; cache_list_pos < 16 && n < max; cache_list_pos++) {
|
||||
char root[HOS_FS_PATH];
|
||||
snprintf(root, sizeof root, "%s\\cache\\%d", hos_user_dir, cache_list_pos);
|
||||
if (GetFileAttributesA(root) != INVALID_FILE_ATTRIBUTES) {
|
||||
memset(GP(ARG(1) + 0x20 * n), 0, 0x20);
|
||||
G32(ARG(1) + 0x20 * n) = (uint32_t)cache_list_pos;
|
||||
n++;
|
||||
}
|
||||
}
|
||||
G32(ARG(0)) = (uint32_t)n;
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn2fs21CloseCacheStorageListENS0_22CacheStorageListHandleE) {}
|
||||
HLE(_ZN2nn2fs7UnmountEPKc) {
|
||||
AcquireSRWLockExclusive(&mount_lock);
|
||||
for (int i = 0; i < nmounts; i++)
|
||||
if (!strcmp(mounts[i].name, gstr(ARG(0)))) { mounts[i] = mounts[--nmounts]; break; }
|
||||
ReleaseSRWLockExclusive(&mount_lock);
|
||||
}
|
||||
HLE(_ZN2nn2fs6CommitEPKc) { RET(0); }
|
||||
HLE(_ZN2nn2fs26SetPriorityOnCurrentThreadENS0_8PriorityE) {}
|
||||
|
||||
/* ---- files ---------------------------------------------------------------------------------------------------- */
|
||||
int hos_blank_cached_icon(const char *guest, const char *host); /* (totk_icon_cache.c: TOTK's fused weapon icons) */
|
||||
/* HOS_FS_TRACE=1: every file opened (or not found) is logged */
|
||||
static int fs_trace(void) {
|
||||
static int on = -1;
|
||||
if (on < 0) on = getenv("HOS_FS_TRACE") != NULL;
|
||||
return on;
|
||||
}
|
||||
/* OpenFile(FileHandle*, char const* path, int mode): mode bit 0 read, bit 1 write, bit 2 append */
|
||||
HLE(_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci) {
|
||||
char path[HOS_FS_PATH];
|
||||
int writable = 0;
|
||||
const char *g = gstr(ARG(1));
|
||||
if (!host_path(g, path, sizeof path, &writable)) { hos_log("fs: OpenFile(%s): unknown mount", g); RET(R_PATH_NOT_FOUND); return; }
|
||||
int want_write = (ARG(2) & 6) != 0;
|
||||
if (want_write && !writable) { RET(R_PATH_NOT_FOUND); return; }
|
||||
/* (mkw-recomp) HOS_NO_MOVIES=1: MKW's WebM movies (cup openings, billboards, emblems) are not found, and the
|
||||
game goes on without them (decoded by nn_video.c otherwise) */
|
||||
if (!want_write && getenv("HOS_NO_MOVIES")) {
|
||||
const size_t n = strlen(g);
|
||||
if (n > 5 && !_stricmp(g + n - 5, ".webm")) {
|
||||
static int logged;
|
||||
if (!logged++) hos_log("fs: OpenFile(%s): movies are left out (HOS_NO_MOVIES)", g);
|
||||
RET(R_PATH_NOT_FOUND);
|
||||
return;
|
||||
}
|
||||
}
|
||||
{ int hos_ultrawide_redirect(const char *guest, char *out, size_t cap); /* (totk_ultrawide_ui.c: the HUD) */
|
||||
char alt[HOS_FS_PATH];
|
||||
if (!want_write && hos_ultrawide_redirect(g, alt, sizeof alt)) snprintf(path, sizeof path, "%s", alt); }
|
||||
if (!want_write && hos_blank_cached_icon(g, path)) { RET(R_PATH_NOT_FOUND); return; }
|
||||
{ /* HOS_FS_OVERLAY=<folder> (a test): a file of the game's data found there is read in place of the game's own */
|
||||
const char *ov = getenv("HOS_FS_OVERLAY");
|
||||
const char *rel = !want_write && ov ? strstr(g, ":/") : NULL;
|
||||
if (rel) {
|
||||
char alt[HOS_FS_PATH];
|
||||
snprintf(alt, sizeof alt, "%s/%s", ov, rel + 2);
|
||||
if (GetFileAttributesA(alt) != INVALID_FILE_ATTRIBUTES) {
|
||||
hos_log("fs: OpenFile(%s): from the overlay", g);
|
||||
snprintf(path, sizeof path, "%s", alt);
|
||||
}
|
||||
}
|
||||
}
|
||||
/* (mkw-recomp 16bc3bc: the host's file calls block, so the virtual core goes to another thread meanwhile, as
|
||||
Horizon would run another while this one waits for the file system. OoT's ARes loaders held it up to 250 ms) */
|
||||
const int away = hos_vcore_away();
|
||||
HANDLE h = CreateFileA(path, GENERIC_READ | (want_write ? GENERIC_WRITE : 0), FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
|
||||
if (away) hos_vcore_back();
|
||||
if (h == INVALID_HANDLE_VALUE) {
|
||||
if (hos_trace || fs_trace()) hos_log("fs: OpenFile(%s): not found", g);
|
||||
RET(R_PATH_NOT_FOUND);
|
||||
return;
|
||||
}
|
||||
Handle *fh = (Handle *)calloc(1, sizeof *fh);
|
||||
fh->h = h;
|
||||
fh->writable = want_write;
|
||||
snprintf(fh->path, sizeof fh->path, "%s", g);
|
||||
G64(ARG(0)) = new_handle(fh);
|
||||
if (hos_trace || fs_trace()) hos_log("fs: OpenFile(%s)", g);
|
||||
RET(0);
|
||||
}
|
||||
|
||||
static uint64_t read_at(Ctx *c, uint64_t id, int64_t off, uint64_t buf, uint64_t size) {
|
||||
Handle *fh = get_handle(c, id);
|
||||
uint64_t done = 0;
|
||||
if (!hos_guest_range(buf, size)) return 0; /* (hookshot: the file's bytes go into guest memory only) */
|
||||
static int64_t delay_ns = -1, delay_after_ns; /* HOS_FS_DELAY_MS=<ms>[,<after s>] (experiment): slower reads */
|
||||
if (delay_ns < 0) {
|
||||
const char *e = getenv("HOS_FS_DELAY_MS");
|
||||
delay_ns = e ? (int64_t)(atof(e) * 1e6) : 0;
|
||||
const char *a = e ? strchr(e, ',') : NULL;
|
||||
delay_after_ns = hos_now_ns() + (a ? (int64_t)(atof(a + 1) * 1e9) : 0);
|
||||
}
|
||||
if (delay_ns && hos_now_ns() >= delay_after_ns) {
|
||||
if (fs_trace()) hos_log("fs: read %s at %lld, %llu bytes", fh->path, (long long)off, (unsigned long long)size);
|
||||
hos_sleep_ns(delay_ns);
|
||||
}
|
||||
const int away = hos_vcore_away(); /* (as OpenFile: no core held through the read) */
|
||||
while (done < size) {
|
||||
OVERLAPPED ov = {0};
|
||||
int64_t o = off + (int64_t)done;
|
||||
ov.Offset = (DWORD)o;
|
||||
ov.OffsetHigh = (DWORD)(o >> 32);
|
||||
DWORD chunk = (DWORD)(size - done > 0x40000000 ? 0x40000000 : size - done), got = 0;
|
||||
if (!ReadFile(fh->h, GP(buf + done), chunk, &got, &ov) || !got) break;
|
||||
done += got;
|
||||
}
|
||||
if (away) hos_vcore_back();
|
||||
HOS_WRITTEN(GP(buf), (size_t)done); /* (into guest memory: the GPU may read it) */
|
||||
{ /* HOS_FS_WATCH=<lo hex>:<hi hex> (debugging): reads into that guest range, with the file */
|
||||
static int on = -1;
|
||||
static unsigned long long wlo, whi;
|
||||
if (on < 0) on = getenv("HOS_FS_WATCH") && sscanf(getenv("HOS_FS_WATCH"), "%llx:%llx", &wlo, &whi) == 2;
|
||||
if (on && buf < whi && buf + done > wlo)
|
||||
hos_log("fs: read into watched memory: %s at %lld, %llu bytes to %#llx", fh->path, (long long)off,
|
||||
(unsigned long long)done, (unsigned long long)buf);
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
/* ReadFile(FileHandle, long offset, void* buf, unsigned long size) -> Result (must read it all) */
|
||||
HLE(_ZN2nn2fs8ReadFileENS0_10FileHandleElPvm) {
|
||||
uint64_t n = read_at(c, ARG(0), (int64_t)ARG(1), ARG(2), ARG(3));
|
||||
RET(n == ARG(3) ? 0 : 0x2EE202); /* fs::ResultOutOfRange */
|
||||
}
|
||||
/* ReadFile(unsigned long* read, FileHandle, long offset, void* buf, unsigned long size[, ReadOption const&]) */
|
||||
HLE(_ZN2nn2fs8ReadFileEPmNS0_10FileHandleElPvm) {
|
||||
G64(ARG(0)) = read_at(c, ARG(1), (int64_t)ARG(2), ARG(3), ARG(4));
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn2fs8ReadFileEPmNS0_10FileHandleElPvmRKNS0_10ReadOptionE) {
|
||||
G64(ARG(0)) = read_at(c, ARG(1), (int64_t)ARG(2), ARG(3), ARG(4));
|
||||
RET(0);
|
||||
}
|
||||
/* GetFileSize(long*, FileHandle) */
|
||||
HLE(_ZN2nn2fs11GetFileSizeEPlNS0_10FileHandleE) {
|
||||
LARGE_INTEGER sz = {0}; /* (hookshot: a folder's handle has no size: 0, not the host stack's bytes) */
|
||||
GetFileSizeEx(get_handle(c, ARG(1))->h, &sz);
|
||||
G64(ARG(0)) = (uint64_t)sz.QuadPart;
|
||||
RET(0);
|
||||
}
|
||||
/* WriteFile(FileHandle, long offset, void const* buf, unsigned long size, WriteOption const&) */
|
||||
HLE(_ZN2nn2fs9WriteFileENS0_10FileHandleElPKvmRKNS0_11WriteOptionE) {
|
||||
Handle *fh = get_handle(c, ARG(0));
|
||||
OVERLAPPED ov = {0};
|
||||
ov.Offset = (DWORD)ARG(1);
|
||||
ov.OffsetHigh = (DWORD)(ARG(1) >> 32);
|
||||
DWORD put = 0;
|
||||
/* (hookshot) from guest memory only, and the whole size: a DWORD cut wrote less than asked and said so */
|
||||
if (ARG(3) <= 0xFFFFFFFFu && hos_guest_range(ARG(2), ARG(3))) WriteFile(fh->h, GP(ARG(2)), (DWORD)ARG(3), &put, &ov);
|
||||
RET(put == ARG(3) ? 0 : 0x2EE202);
|
||||
}
|
||||
HLE(_ZN2nn2fs11SetFileSizeENS0_10FileHandleEl) {
|
||||
Handle *fh = get_handle(c, ARG(0));
|
||||
LARGE_INTEGER sz;
|
||||
sz.QuadPart = (LONGLONG)ARG(1);
|
||||
SetFilePointerEx(fh->h, sz, NULL, FILE_BEGIN);
|
||||
SetEndOfFile(fh->h);
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn2fs9FlushFileENS0_10FileHandleE) { FlushFileBuffers(get_handle(c, ARG(0))->h); RET(0); }
|
||||
HLE(_ZN2nn2fs9CloseFileENS0_10FileHandleE) {
|
||||
Handle *fh = get_handle(c, ARG(0));
|
||||
CloseHandle(fh->h);
|
||||
free_handle(ARG(0));
|
||||
free(fh);
|
||||
}
|
||||
|
||||
/* CreateFile(char const*, long size) */
|
||||
HLE(_ZN2nn2fs10CreateFileEPKcl) {
|
||||
char path[HOS_FS_PATH];
|
||||
int writable = 0;
|
||||
if (!host_path(gstr(ARG(0)), path, sizeof path, &writable) || !writable) { RET(R_PATH_NOT_FOUND); return; }
|
||||
make_dirs(path);
|
||||
HANDLE h = CreateFileA(path, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
|
||||
if (h == INVALID_HANDLE_VALUE) { RET(GetLastError() == ERROR_FILE_EXISTS ? R_PATH_EXISTS : R_PATH_NOT_FOUND); return; }
|
||||
LARGE_INTEGER sz;
|
||||
sz.QuadPart = (LONGLONG)ARG(1);
|
||||
SetFilePointerEx(h, sz, NULL, FILE_BEGIN);
|
||||
SetEndOfFile(h);
|
||||
CloseHandle(h);
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn2fs10DeleteFileEPKc) {
|
||||
char path[HOS_FS_PATH];
|
||||
int writable = 0;
|
||||
if (!host_path(gstr(ARG(0)), path, sizeof path, &writable) || !writable || !DeleteFileA(path)) { RET(R_PATH_NOT_FOUND); return; }
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn2fs15CreateDirectoryEPKc) {
|
||||
char path[HOS_FS_PATH];
|
||||
int writable = 0;
|
||||
if (!host_path(gstr(ARG(0)), path, sizeof path, &writable) || !writable) { RET(R_PATH_NOT_FOUND); return; }
|
||||
make_dirs(path);
|
||||
RET(CreateDirectoryA(path, NULL) ? 0 : GetLastError() == ERROR_ALREADY_EXISTS ? R_PATH_EXISTS : R_PATH_NOT_FOUND);
|
||||
}
|
||||
static void delete_tree(const char *dir) {
|
||||
char pat[HOS_FS_PATH];
|
||||
WIN32_FIND_DATAA fd;
|
||||
snprintf(pat, sizeof pat, "%s\\*", dir);
|
||||
HANDLE f = FindFirstFileA(pat, &fd);
|
||||
if (f != INVALID_HANDLE_VALUE) {
|
||||
do {
|
||||
if (!strcmp(fd.cFileName, ".") || !strcmp(fd.cFileName, "..")) continue;
|
||||
char sub[HOS_FS_PATH];
|
||||
snprintf(sub, sizeof sub, "%s\\%s", dir, fd.cFileName);
|
||||
/* (hookshot) a link (a symbolic link, a junction) goes itself: never what it points to */
|
||||
if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { if (!DeleteFileA(sub)) RemoveDirectoryA(sub); }
|
||||
else if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) delete_tree(sub);
|
||||
else DeleteFileA(sub);
|
||||
} while (FindNextFileA(f, &fd));
|
||||
FindClose(f);
|
||||
}
|
||||
RemoveDirectoryA(dir);
|
||||
}
|
||||
HLE(_ZN2nn2fs26DeleteDirectoryRecursivelyEPKc) {
|
||||
char path[HOS_FS_PATH];
|
||||
int writable = 0;
|
||||
if (!host_path(gstr(ARG(0)), path, sizeof path, &writable) || !writable) { RET(R_PATH_NOT_FOUND); return; }
|
||||
/* (hookshot) the folder named itself a link: the link goes, never what it points to (as for the links inside) */
|
||||
const DWORD at = GetFileAttributesA(path);
|
||||
if (at != INVALID_FILE_ATTRIBUTES && (at & FILE_ATTRIBUTE_REPARSE_POINT)) {
|
||||
if (!DeleteFileA(path)) RemoveDirectoryA(path);
|
||||
RET(0);
|
||||
return;
|
||||
}
|
||||
delete_tree(path);
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn2fs10RenameFileEPKcS2_) {
|
||||
char a[HOS_FS_PATH], b[HOS_FS_PATH];
|
||||
int w1 = 0, w2 = 0;
|
||||
if (!host_path(gstr(ARG(0)), a, sizeof a, &w1) || !host_path(gstr(ARG(1)), b, sizeof b, &w2) || !w1 || !w2) { RET(R_PATH_NOT_FOUND); return; }
|
||||
RET(MoveFileExA(a, b, MOVEFILE_REPLACE_EXISTING) ? 0 : R_PATH_NOT_FOUND);
|
||||
}
|
||||
/* a RomFS folder that only mods have: rom:/x -> some mod entry lies under x */
|
||||
static void count_extra(void *arg, const char *name, int is_dir, uint64_t size) { (void)name, (void)is_dir, (void)size; ++*(int *)arg; }
|
||||
static const char *rom_rel(const char *guest) { /* the path inside the RomFS mount, or NULL */
|
||||
const char *colon = strchr(guest, ':');
|
||||
if (!colon || !hos_romfs_dir) return NULL;
|
||||
char root[HOS_FS_PATH];
|
||||
if (!host_path(guest, root, sizeof root, NULL)) return NULL;
|
||||
AcquireSRWLockShared(&mount_lock);
|
||||
int rom = 0;
|
||||
for (int i = 0; i < nmounts; i++)
|
||||
if (strlen(mounts[i].name) == (size_t)(colon - guest) && !strncmp(mounts[i].name, guest, (size_t)(colon - guest)))
|
||||
rom = !mounts[i].writable && !strcmp(mounts[i].root, hos_romfs_dir);
|
||||
ReleaseSRWLockShared(&mount_lock);
|
||||
if (!rom) return NULL;
|
||||
const char *rest = colon + 1;
|
||||
while (*rest == '/') rest++;
|
||||
return rest;
|
||||
}
|
||||
static int is_mod_dir(const char *guest) {
|
||||
const char *rel = rom_rel(guest);
|
||||
int n = 0;
|
||||
if (rel) hos_mods_dir_extras(rel, "<", count_extra, &n); /* ("<": no such folder: every entry counts) */
|
||||
return n > 0;
|
||||
}
|
||||
|
||||
/* GetEntryType(DirectoryEntryType*, char const*): 0 directory, 1 file */
|
||||
HLE(_ZN2nn2fs12GetEntryTypeEPNS0_18DirectoryEntryTypeEPKc) {
|
||||
char path[HOS_FS_PATH];
|
||||
if (!host_path(gstr(ARG(1)), path, sizeof path, NULL)) { RET(R_PATH_NOT_FOUND); return; }
|
||||
hos_blank_cached_icon(gstr(ARG(1)), path);
|
||||
DWORD at = GetFileAttributesA(path);
|
||||
if (at == INVALID_FILE_ATTRIBUTES && is_mod_dir(gstr(ARG(1)))) at = FILE_ATTRIBUTE_DIRECTORY; /* (only in mods) */
|
||||
if (fs_trace())
|
||||
hos_log("fs: GetEntryType(%s): %s", gstr(ARG(1)), at == INVALID_FILE_ATTRIBUTES ? "not found"
|
||||
: (at & FILE_ATTRIBUTE_DIRECTORY) ? "directory" : "file");
|
||||
if (at == INVALID_FILE_ATTRIBUTES) { RET(R_PATH_NOT_FOUND); return; }
|
||||
G32(ARG(0)) = (at & FILE_ATTRIBUTE_DIRECTORY) ? 0 : 1;
|
||||
RET(0);
|
||||
}
|
||||
|
||||
/* ---- directories: DirectoryEntry = { char name[0x301]; pad[3]; s8 type at 0x304 (0 directory, 1 file); pad[3]; s64 size at 0x308 } ---- */
|
||||
static void add_extra(void *arg, const char *name, int is_dir, uint64_t size) {
|
||||
Handle *dh = (Handle *)arg;
|
||||
if (!(dh->nextras & 15)) dh->extras = (ExtraEntry *)realloc(dh->extras, sizeof *dh->extras * (size_t)(dh->nextras + 16));
|
||||
ExtraEntry *e = &dh->extras[dh->nextras++];
|
||||
snprintf(e->name, sizeof e->name, "%s", name);
|
||||
e->is_dir = is_dir, e->size = size;
|
||||
}
|
||||
HLE(_ZN2nn2fs13OpenDirectoryEPNS0_15DirectoryHandleEPKci) {
|
||||
char path[HOS_FS_PATH], pat[HOS_FS_PATH];
|
||||
if (!host_path(gstr(ARG(1)), path, sizeof path, NULL)) { RET(R_PATH_NOT_FOUND); return; }
|
||||
snprintf(pat, sizeof pat, "%s\\*", path);
|
||||
Handle *dh = (Handle *)calloc(1, sizeof *dh);
|
||||
dh->is_dir = (int)ARG(2); /* mode: 1 directories, 2 files, 3 both */
|
||||
snprintf(dh->path, sizeof dh->path, "%s", pat); /* (for GetDirectoryEntryCount) */
|
||||
dh->find = FindFirstFileA(pat, &dh->fd);
|
||||
if (dh->find == INVALID_HANDLE_VALUE) dh->find_done = 1;
|
||||
if (rom_rel(gstr(ARG(1)))) hos_mods_dir_extras(rom_rel(gstr(ARG(1))), path, add_extra, dh);
|
||||
if (fs_trace())
|
||||
hos_log("fs: OpenDirectory(%s, mode %d)%s, %d entries from mods", gstr(ARG(1)), (int)ARG(2),
|
||||
dh->find == INVALID_HANDLE_VALUE ? ": not found" : "", dh->nextras);
|
||||
if (dh->find == INVALID_HANDLE_VALUE && !dh->nextras) { free(dh); RET(R_PATH_NOT_FOUND); return; }
|
||||
G64(ARG(0)) = new_handle(dh);
|
||||
RET(0);
|
||||
}
|
||||
/* ReadDirectory(long* count, DirectoryEntry* entries, DirectoryHandle, long max) */
|
||||
HLE(_ZN2nn2fs13ReadDirectoryEPlPNS0_14DirectoryEntryENS0_15DirectoryHandleEl) {
|
||||
Handle *dh = get_handle(c, ARG(2));
|
||||
int64_t n = 0, max = (int64_t)ARG(3);
|
||||
while (n < max && !dh->find_done) {
|
||||
WIN32_FIND_DATAA *fd = &dh->fd;
|
||||
int isdir = (fd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
|
||||
int want = (isdir && (dh->is_dir & 1)) || (!isdir && (dh->is_dir & 2));
|
||||
if (strcmp(fd->cFileName, ".") && strcmp(fd->cFileName, "..") && want) {
|
||||
uint64_t e = ARG(1) + 0x310 * n;
|
||||
memset(GP(e), 0, 0x310);
|
||||
snprintf((char *)GP(e), 0x301, "%s", fd->cFileName);
|
||||
*(uint8_t *)GP(e + 0x304) = isdir ? 0 : 1;
|
||||
G64(e + 0x308) = ((uint64_t)fd->nFileSizeHigh << 32) | fd->nFileSizeLow;
|
||||
n++;
|
||||
}
|
||||
if (!FindNextFileA(dh->find, &dh->fd)) dh->find_done = 1;
|
||||
}
|
||||
while (n < max && dh->find_done && dh->extra_pos < dh->nextras) { /* then the mods' own entries */
|
||||
const ExtraEntry *x = &dh->extras[dh->extra_pos++];
|
||||
if (!((x->is_dir && (dh->is_dir & 1)) || (!x->is_dir && (dh->is_dir & 2)))) continue;
|
||||
uint64_t e = ARG(1) + 0x310 * n;
|
||||
memset(GP(e), 0, 0x310);
|
||||
snprintf((char *)GP(e), 0x301, "%s", x->name);
|
||||
*(uint8_t *)GP(e + 0x304) = x->is_dir ? 0 : 1;
|
||||
G64(e + 0x308) = x->size;
|
||||
n++;
|
||||
}
|
||||
G64(ARG(0)) = (uint64_t)n;
|
||||
RET(0);
|
||||
}
|
||||
/* (hookshot) GetDirectoryEntryCount(long* count, DirectoryHandle): every entry the open mode lists, read or not */
|
||||
HLE(_ZN2nn2fs22GetDirectoryEntryCountEPlNS0_15DirectoryHandleE) {
|
||||
Handle *dh = get_handle(c, ARG(1));
|
||||
int64_t n = 0;
|
||||
WIN32_FIND_DATAA fd;
|
||||
HANDLE f = dh->path[0] ? FindFirstFileA(dh->path, &fd) : INVALID_HANDLE_VALUE;
|
||||
if (f != INVALID_HANDLE_VALUE) {
|
||||
do {
|
||||
int isdir = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
|
||||
if (strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..") &&
|
||||
((isdir && (dh->is_dir & 1)) || (!isdir && (dh->is_dir & 2))))
|
||||
n++;
|
||||
} while (FindNextFileA(f, &fd));
|
||||
FindClose(f);
|
||||
}
|
||||
for (int i = 0; i < dh->nextras; i++)
|
||||
n += (dh->extras[i].is_dir && (dh->is_dir & 1)) || (!dh->extras[i].is_dir && (dh->is_dir & 2));
|
||||
G64(ARG(0)) = (uint64_t)n;
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn2fs14CloseDirectoryENS0_15DirectoryHandleE) {
|
||||
Handle *dh = get_handle(c, ARG(0));
|
||||
if (dh->find != INVALID_HANDLE_VALUE) FindClose(dh->find);
|
||||
free_handle(ARG(0));
|
||||
free(dh->extras);
|
||||
free(dh);
|
||||
}
|
||||
38
host/nn_gs.c
Normal file
38
host/nn_gs.c
Normal file
@@ -0,0 +1,38 @@
|
||||
/* nn::gs::sdk: the Switch 2 graphics system the game boots before NVN (native memory, native windows and their
|
||||
buffers, presentation). On hardware it talks to the graphics server (nn::gsv over nn::am's graphics supervisor
|
||||
handle); natively it is the boundary the NVN2 layer will take over. For now: booted as a no-op, so the rest of
|
||||
the game's start can run headless. */
|
||||
#include "hos.h"
|
||||
#include <string.h>
|
||||
|
||||
/* nn::gs::sdk::BootGraphicsSystem(void* memory, unsigned long size): the graphics stack's working memory */
|
||||
HLE(_ZN2nn2gs3sdk18BootGraphicsSystemEPvm) {
|
||||
hos_log("gs: BootGraphicsSystem(%#llx, %#llx): no graphics server yet (headless)", (unsigned long long)ARG(0),
|
||||
(unsigned long long)ARG(1));
|
||||
RET(0);
|
||||
}
|
||||
|
||||
/* nn::gs::sdk::CheckGraphicsSystemInitialized(char const* who, unsigned long length) */
|
||||
HLE(_ZN2nn2gs3sdk30CheckGraphicsSystemInitializedEPKcm) { RET(1); }
|
||||
|
||||
/* nv::GetGraphicsMemoryInfo(nv::MemoryInfo*): the GPU driver's memory statistics, from the nvdrv service the native
|
||||
build does not have (its lock is never set up). Zeros, as the SDK reports with no driver attached. */
|
||||
HLE(_ZN2nv21GetGraphicsMemoryInfoEPNS_10MemoryInfoE) { memset(GP(ARG(0)), 0, 0x40); }
|
||||
|
||||
/* Native syncs (GPU fences between the graphics server, the video decoders and the game): the native NVN layer and
|
||||
nn_video.c complete their work in order, so every one is reached, except the one nn_video.c gives a buffer an idle
|
||||
video decoder will never fill (hos_video_sync_reached). MKW's movie library asserts TryWaitNativeSync on each
|
||||
decoded frame before it takes it. WaitNativeSync does not block even on that one: nothing would ever reach it. */
|
||||
int hos_video_sync_reached(uint64_t handle);
|
||||
HLE(_ZN2nn2gs14WaitNativeSyncERKNS0_16NativeSyncHandleE) { RET(0); }
|
||||
HLE(_ZN2nn2gs17TryWaitNativeSyncERKNS0_16NativeSyncHandleE) { RET(hos_video_sync_reached(G64(ARG(0)))); }
|
||||
HLE(_ZN2nn2gs19TimedWaitNativeSyncERKNS0_16NativeSyncHandleENS_8TimeSpanE) {
|
||||
const uint64_t handle = G64(ARG(0));
|
||||
int64_t left = (int64_t)ARG(1);
|
||||
int reached;
|
||||
while (!(reached = hos_video_sync_reached(handle)) && left > 0) {
|
||||
hos_sleep_ns(left < 1000000 ? left : 1000000);
|
||||
left -= 1000000;
|
||||
}
|
||||
RET(reached);
|
||||
}
|
||||
1151
host/nn_hid.c
Normal file
1151
host/nn_hid.c
Normal file
File diff suppressed because it is too large
Load Diff
84
host/nn_libc.c
Normal file
84
host/nn_libc.c
Normal file
@@ -0,0 +1,84 @@
|
||||
#include "hos.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static int guest_libc(void) {
|
||||
static int v = -1;
|
||||
if (v < 0) v = getenv("HOS_GUEST_LIBC") != NULL;
|
||||
return v;
|
||||
}
|
||||
|
||||
#if defined(RX_WEB_MT) && RX_WEB_MT
|
||||
void rx_wait_writebacks_reading(const void *p, uint64_t n); /* gpu/render/rx_nvn.h */
|
||||
#define WAIT_WRITEBACKS(p, n) rx_wait_writebacks_reading(p, n)
|
||||
#else
|
||||
#define WAIT_WRITEBACKS(p, n) ((void)0)
|
||||
#endif
|
||||
|
||||
ENTRY_HOOK_SYM(memcpy) {
|
||||
if (guest_libc()) return 0;
|
||||
const uint64_t n = ARG(2);
|
||||
if (!hos_guest_range(ARG(0), n) || !hos_guest_range(ARG(1), n)) return 0; /* (hookshot: past the guest window, the game's own copy) */
|
||||
if (n) {
|
||||
WAIT_WRITEBACKS(GP(ARG(1)), n); /* (TOTK copies some rendered maps with the CPU) */
|
||||
memmove(GP(ARG(0)), GP(ARG(1)), (size_t)n);
|
||||
HOS_WRITTEN(GP(ARG(0)), (size_t)n);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
ENTRY_HOOK_SYM(memmove) {
|
||||
if (guest_libc()) return 0;
|
||||
const uint64_t n = ARG(2);
|
||||
if (!hos_guest_range(ARG(0), n) || !hos_guest_range(ARG(1), n)) return 0; /* (hookshot: past the guest window, the game's own copy) */
|
||||
if (n) {
|
||||
WAIT_WRITEBACKS(GP(ARG(1)), n);
|
||||
memmove(GP(ARG(0)), GP(ARG(1)), (size_t)n);
|
||||
HOS_WRITTEN(GP(ARG(0)), (size_t)n);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
ENTRY_HOOK_SYM(memset) {
|
||||
if (guest_libc()) return 0;
|
||||
const uint64_t n = ARG(2);
|
||||
if (!hos_guest_range(ARG(0), n)) return 0; /* (hookshot: past the guest window, the game's own copy) */
|
||||
if (n) {
|
||||
memset(GP(ARG(0)), (int)(uint8_t)ARG(1), (size_t)n);
|
||||
HOS_WRITTEN(GP(ARG(0)), (size_t)n);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
ENTRY_HOOK_SYM(memcmp) {
|
||||
if (guest_libc()) return 0;
|
||||
const uint8_t *a = (const uint8_t *)GP(ARG(0)), *b = (const uint8_t *)GP(ARG(1));
|
||||
const size_t n = (size_t)ARG(2);
|
||||
int r = 0;
|
||||
if (n && memcmp(a, b, n)) {
|
||||
size_t i = 0;
|
||||
while (a[i] == b[i]) i++;
|
||||
r = (int)a[i] - (int)b[i];
|
||||
}
|
||||
RET((uint64_t)(int64_t)r);
|
||||
return 1;
|
||||
}
|
||||
|
||||
ENTRY_HOOK_SYM(strlen) {
|
||||
if (guest_libc()) return 0;
|
||||
RET(strlen((const char *)GP(ARG(0))));
|
||||
return 1;
|
||||
}
|
||||
|
||||
ENTRY_HOOK_SYM(strcmp) {
|
||||
if (guest_libc()) return 0;
|
||||
const uint8_t *a = (const uint8_t *)GP(ARG(0)), *b = (const uint8_t *)GP(ARG(1));
|
||||
int r = 0;
|
||||
if (strcmp((const char *)a, (const char *)b)) {
|
||||
size_t i = 0;
|
||||
while (a[i] && a[i] == b[i]) i++;
|
||||
r = (int)a[i] - (int)b[i];
|
||||
}
|
||||
RET((uint64_t)(int64_t)r);
|
||||
return 1;
|
||||
}
|
||||
1284
host/nn_os_sync.c
Normal file
1284
host/nn_os_sync.c
Normal file
File diff suppressed because it is too large
Load Diff
52
host/nn_syncpt.c
Normal file
52
host/nn_syncpt.c
Normal file
@@ -0,0 +1,52 @@
|
||||
/* nn::syncpt::sdk: GPU sync points (the console's host1x syncpoints) and the events that wait for them. The SDK and
|
||||
the game's movie library import them from a system library the image does not carry, so their calls went to
|
||||
address 0. There is no GPU timeline here to wait on (the native NVN layer completes work in order), so every sync
|
||||
point counts as reached: a sync point event is a system event, signaled when it is requested. */
|
||||
#include "hos.h"
|
||||
|
||||
void hos_system_event_init(uint64_t key, int autoclear); /* nn_os_sync.c */
|
||||
void hos_system_event_signal(uint64_t key);
|
||||
void imp__ZN2nn2os25InitializeMultiWaitHolderEPNS0_19MultiWaitHolderTypeEPNS0_15SystemEventTypeE(Ctx *c);
|
||||
|
||||
HLE(_ZN2nn6syncpt17GetLibraryVersionEv) { RET(1); }
|
||||
HLE(_ZN2nn6syncpt3sdk12InitializeExEPvmNS1_14LibraryOptionsE) { RET(0); }
|
||||
|
||||
/* sync points: reached */
|
||||
HLE(_ZN2nn6syncpt3sdk13WaitSyncPointERKNS1_15SyncPointHandleE) { RET(0); }
|
||||
HLE(_ZN2nn6syncpt3sdk16TryWaitSyncPointERKNS1_15SyncPointHandleE) { RET(1); }
|
||||
HLE(_ZN2nn6syncpt3sdk18TimedWaitSyncPointERKNS1_15SyncPointHandleENS_8TimeSpanE) { RET(1); }
|
||||
|
||||
/* sync point events: system events (the object's storage is the game's) */
|
||||
HLE(_ZN2nn6syncpt3sdk20CreateSyncPointEventEPNS1_18SyncPointEventTypeE) {
|
||||
hos_system_event_init(ARG(0), 0);
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn6syncpt3sdk21DestroySyncPointEventEPNS1_18SyncPointEventTypeE) {}
|
||||
/* (hookshot) except for the handle nn_video.c gives a buffer an idle video decoder will not fill: its event is
|
||||
signalled at the next submission (hos_video_sync_defer). A cancelled event is cleared, as a new request starts over:
|
||||
left signalled, the request after it was signalled already, whatever its handle. */
|
||||
int hos_video_sync_defer(uint64_t event, uint64_t handle);
|
||||
void hos_video_sync_cancel(uint64_t event);
|
||||
int hos_video_sync_waiting(uint64_t event);
|
||||
void imp__ZN2nn2os16ClearSystemEventEPNS0_15SystemEventTypeE(Ctx *c);
|
||||
HLE(_ZN2nn6syncpt3sdk21RequestSyncPointEventEPNS1_18SyncPointEventTypeERKNS1_15SyncPointHandleE) {
|
||||
if (!hos_video_sync_defer(ARG(0), ARG(1) ? G64(ARG(1)) : 0)) hos_system_event_signal(ARG(0));
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn6syncpt3sdk20CancelSyncPointEventEPNS1_18SyncPointEventTypeE) {
|
||||
hos_video_sync_cancel(ARG(0));
|
||||
imp__ZN2nn2os16ClearSystemEventEPNS0_15SystemEventTypeE(c); /* (ARG(0): the same event) */
|
||||
}
|
||||
HLE(_ZN2nn6syncpt3sdk21TryWaitSyncPointEventEPKNS1_18SyncPointEventTypeE) { RET(!hos_video_sync_waiting(ARG(0))); }
|
||||
/* InitializeMultiWaitHolder(holder, SyncPointEventType*): as for a system event */
|
||||
HLE(_ZN2nn6syncpt3sdk25InitializeMultiWaitHolderEPNS_2os19MultiWaitHolderTypeEPNS1_18SyncPointEventTypeE) {
|
||||
imp__ZN2nn2os25InitializeMultiWaitHolderEPNS0_19MultiWaitHolderTypeEPNS0_15SystemEventTypeE(c);
|
||||
}
|
||||
|
||||
/* conversions between sync point handles, NvRm fences and native sync handles: a handle holds nothing to convert */
|
||||
HLE(_ZN2nn6syncpt3sdk32MakeNvRmFenceFromSyncPointHandleEPjS2_RKNS1_15SyncPointHandleE) {
|
||||
if (ARG(0)) G32(ARG(0)) = 0;
|
||||
if (ARG(1)) G32(ARG(1)) = 0;
|
||||
}
|
||||
HLE(_ZN2nn6syncpt3sdk32MakeSyncPointHandleFromNvRmFenceEjj) { RET(0); }
|
||||
HLE(_ZN2nn6syncpt3sdk39MakeNativeSyncHandleFromSyncPointHandleERKNS1_15SyncPointHandleE) { RET(0); }
|
||||
463
host/nn_vi.c
Normal file
463
host/nn_vi.c
Normal file
@@ -0,0 +1,463 @@
|
||||
/* nn::vi for MKW (TOTKPort's nn_vi.c is bound to its renderer and TOTK's frame pacing): the default display, one
|
||||
layer, and the display's vsync event, signaled at 60 Hz by a host thread. HDR and VRR are reported unsupported,
|
||||
so the game takes its SDR path. Frames are paced at the native NVN layer's window acquire (the end of this file). */
|
||||
#include "hos.h"
|
||||
#include "../gpu/vk/vk_api.h" /* (HOS_OPT_HDR_*: the Insert menu's HDR, answered by the renderer) */
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
void hos_system_event_init(uint64_t key, int autoclear); /* nn_os_sync.c */
|
||||
void hos_system_event_signal(uint64_t key);
|
||||
|
||||
static uint64_t display, layer;
|
||||
static uint64_t vsync_events[8];
|
||||
static volatile LONG nvsync;
|
||||
static HANDLE vsync_thread;
|
||||
|
||||
static int fps_max(void); /* (below: HOS_FPS_MAX) */
|
||||
static DWORD WINAPI vsync_main(void *p) {
|
||||
(void)p;
|
||||
const int64_t period = 1000000000LL / fps_max();
|
||||
int64_t next = hos_now_ns() + period;
|
||||
for (;;) {
|
||||
const int64_t now = hos_now_ns();
|
||||
if (next > now) hos_sleep_ns(next - now);
|
||||
next += period;
|
||||
if (next < hos_now_ns()) next = hos_now_ns() + period; /* (fell behind: no burst of vsyncs) */
|
||||
for (LONG i = 0; i < nvsync; i++) hos_system_event_signal(vsync_events[i]);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* nn::vi::Initialize() */
|
||||
HLE(_ZN2nn2vi10InitializeEv) {}
|
||||
|
||||
/* nn::vi::OpenDefaultDisplay(nn::vi::Display**) -> Result */
|
||||
HLE(_ZN2nn2vi18OpenDefaultDisplayEPPNS0_7DisplayE) {
|
||||
if (!display) display = hos_sys_alloc(0x100, 16);
|
||||
G64(ARG(0)) = display;
|
||||
RET(0);
|
||||
}
|
||||
|
||||
/* nn::vi::CreateLayer(nn::vi::Layer**, nn::vi::Display*) -> Result */
|
||||
HLE(_ZN2nn2vi11CreateLayerEPPNS0_5LayerEPNS0_7DisplayE) {
|
||||
if (!layer) layer = hos_sys_alloc(0x100, 16);
|
||||
G64(ARG(0)) = layer;
|
||||
RET(0);
|
||||
}
|
||||
|
||||
/* nn::vi::GetDisplayVsyncEvent(nn::os::SystemEventType*, nn::vi::Display*) -> Result */
|
||||
HLE(_ZN2nn2vi20GetDisplayVsyncEventEPNS_2os15SystemEventTypeEPNS0_7DisplayE) {
|
||||
hos_system_event_init(ARG(0), 1);
|
||||
{ /* (hookshot) under a lock: two threads checked the count at once and wrote past the table */
|
||||
static SRWLOCK vsync_lock = SRWLOCK_INIT;
|
||||
AcquireSRWLockExclusive(&vsync_lock);
|
||||
if (nvsync < (LONG)(sizeof vsync_events / sizeof vsync_events[0])) {
|
||||
vsync_events[nvsync] = ARG(0);
|
||||
InterlockedIncrement(&nvsync);
|
||||
}
|
||||
ReleaseSRWLockExclusive(&vsync_lock);
|
||||
}
|
||||
if (!vsync_thread) vsync_thread = CreateThread(NULL, 0, vsync_main, NULL, 0, NULL);
|
||||
RET(0);
|
||||
}
|
||||
|
||||
/* nn::vi::QueryDisplayHdrStatus(bool* on, HdrOutputFormat*, unsigned short* max nits, Display const*) -> Result */
|
||||
/* (hookshot) the Insert menu's HDR set to Native on an HDR10 swapchain: an HDR10 display (format 1, which makes the game present PQ
|
||||
codes in 10 bits) of the menu's peak; otherwise SDR, as a desktop window is */
|
||||
HLE(_ZN2nn2vi21QueryDisplayHdrStatusEPbPNS0_15HdrOutputFormatEPtPKNS0_7DisplayE) {
|
||||
const int native = rx_option(HOS_OPT_HDR_NATIVE, 0);
|
||||
*(uint8_t *)GP(ARG(0)) = (uint8_t)native;
|
||||
if (ARG(1)) G32(ARG(1)) = native ? 1 : 0;
|
||||
if (ARG(2)) *(uint16_t *)GP(ARG(2)) = native ? (uint16_t)rx_option(HOS_OPT_HDR_PEAK, 1000) : 0;
|
||||
static int logged = -1;
|
||||
if (logged != native) logged = native, hos_log("vi: QueryDisplayHdrStatus -> %s", native ? "HDR10 (the game's native HDR)" : "SDR");
|
||||
RET(0);
|
||||
}
|
||||
/* nn::vi::QueryDisplayHdrPaperWhite(unsigned short*, Display const*) -> Result */
|
||||
HLE(_ZN2nn2vi25QueryDisplayHdrPaperWhiteEPtPKNS0_7DisplayE) {
|
||||
*(uint16_t *)GP(ARG(0)) = rx_option(HOS_OPT_HDR_NATIVE, 0) ? (uint16_t)rx_option(HOS_OPT_HDR_WHITE, 203) : 203;
|
||||
RET(0);
|
||||
}
|
||||
/* nn::vi::QueryDisplayVrrSupported(bool*, Display const*) -> Result */
|
||||
HLE(_ZN2nn2vi24QueryDisplayVrrSupportedEPbPKNS0_7DisplayE) {
|
||||
*(uint8_t *)GP(ARG(0)) = 0;
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn2vi23SetDisplayVrrCapabilityEPNS0_7DisplayEb) { RET(0); }
|
||||
HLE(_ZN2nn2vi28SetLayerExtendedSwapIntervalEPNS0_5LayerEii) { RET(0); }
|
||||
HLE(_ZN2nn2vi30ClearLayerExtendedSwapIntervalEPNS0_5LayerE) { RET(0); }
|
||||
|
||||
/* nn::vi::GetNativeWindow(void**, nn::vi::Layer*) -> Result: a window object (NVN builds its window on it; the
|
||||
native NVN layer only keeps the pointer) */
|
||||
HLE(_ZN2nn2vi15GetNativeWindowEPPvPNS0_5LayerE) {
|
||||
static uint64_t window;
|
||||
if (!window) window = hos_sys_alloc(0x100, 16);
|
||||
G64(ARG(0)) = window;
|
||||
hos_log("vi: GetNativeWindow -> %#llx", (unsigned long long)window);
|
||||
RET(0);
|
||||
}
|
||||
|
||||
/* ---- frame pacing for the native NVN layer's window (nvn_native.c) ----
|
||||
The game acquires a window texture before each frame and presents it after; on the console the acquire blocks
|
||||
while every texture waits for the display. Here the acquire waits for the frame's display time: the present
|
||||
interval's vsyncs (1: 60 fps, 2: 30) after the last present, so the game runs at the display's rate.
|
||||
HOS_NO_PACING=1: as fast as it can. */
|
||||
static volatile int present_interval = 1;
|
||||
/* (hookshot) HOS_FPS_MAX=<61-240>: the frame rate cap past the console's 60 (opt-in, a test): the display pacing's interval, the game's
|
||||
own limiter (+0xfc) and the vsync event go up to it, and the game's time step is the frames' own time (realtime_step), so the game is
|
||||
not sped up. Unset or 60: 60, as on the console */
|
||||
int hos_ini_option(const char *key, int otherwise); /* (nn_applet.c) */
|
||||
static int fps_max(void) {
|
||||
static int v = -1;
|
||||
if (v < 0) {
|
||||
/* (the Insert menu's Frame rate cap, frame_rate_cap=: 0 the console's 60, then 90, 120, 144, 165, 240; HOS_FPS_MAX over it) */
|
||||
static const int caps[] = {60, 90, 120, 144, 165, 240};
|
||||
const int i = hos_ini_option("frame_rate_cap", 0);
|
||||
const char *e = getenv("HOS_FPS_MAX");
|
||||
const int want = e ? atoi(e) : caps[i >= 0 && i < 6 ? i : 0];
|
||||
v = want > 60 ? (want > 240 ? 240 : want) : 60;
|
||||
if (v > 60) hos_log("vi: frame rate cap %d: pacing, the game's limiter and its time step follow it", v);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
static int64_t next_frame_at, window_start, frames_in_window;
|
||||
static volatile LONG64 presents;
|
||||
int hos_vi_native_interval(Ctx *c, int requested) {
|
||||
(void)c;
|
||||
/* (hookshot) OoT's frame-rate controller asks for 2, 3 or 4 vsyncs a frame whenever one runs long (480 changes a minute
|
||||
in Kokiri): paced to them, frames snapped to 33, 50 and 67 ms, the stutter, and the frame rate sat far under what the
|
||||
PC managed. With game time following the clock (the Insert menu's Real time, realtime_step), a frame is shown as soon
|
||||
as it is ready, 60 at most; the game still reads back its own interval. HOS_GAME_INTERVAL=1, or Game speed Per frame:
|
||||
paced to the game's interval, as before */
|
||||
static int game_interval = -1;
|
||||
if (game_interval < 0) game_interval = getenv("HOS_GAME_INTERVAL") && atoi(getenv("HOS_GAME_INTERVAL")) != 0;
|
||||
int rx_option(int id, int otherwise);
|
||||
const int clamped = requested < 1 ? 1 : requested > 4 ? 4 : requested;
|
||||
present_interval = game_interval || !rx_option(0, 1) ? clamped : 1;
|
||||
return requested;
|
||||
}
|
||||
/* (hookshot) The window's textures as the console's display queue has them: each present is shown at its display
|
||||
time, the later of its present and one interval after the frame shown before it, and a texture is free again once
|
||||
the frame presented after it is shown. The acquire of a frame waits for its texture: with `active` textures, the
|
||||
texture of the frame `active` back, freed when the frame after that one is shown. With three (OoT) a frame slower
|
||||
than the display waits for nothing and a fast one is held to the display's rate, two frames queued at most;
|
||||
the acquire waited for one interval after the last present before (two textures' behaviour), which held every
|
||||
frame over 16.7 ms to the next vsync step (gameplay at 27 ms frames, 5 ms of them in this sleep). HOS_VI_DOUBLE=1:
|
||||
that behaviour */
|
||||
static int64_t shown_at[16];
|
||||
static volatile LONG64 shown_count;
|
||||
void hos_vi_native_acquire(int active) {
|
||||
static int no_pacing = -1, double_buffered = -1;
|
||||
if (no_pacing < 0) no_pacing = getenv("HOS_NO_PACING") != NULL;
|
||||
if (double_buffered < 0) double_buffered = getenv("HOS_VI_DOUBLE") != NULL;
|
||||
if (no_pacing || !next_frame_at) return;
|
||||
int64_t until = next_frame_at;
|
||||
if (!double_buffered && active >= 2) {
|
||||
const int64_t n = shown_count, frame = n - active + 1; /* (the frame whose showing frees this texture) */
|
||||
until = frame >= 0 && frame < n ? shown_at[frame & 15] : 0;
|
||||
}
|
||||
const int64_t now = hos_now_ns();
|
||||
if (until > now) hos_sleep_ns(until - now);
|
||||
}
|
||||
/* (mkw-recomp) MKW's frame pacer (0x806bcbb0, x19 when it sets the interval: nvn_native.c): its measured frame time
|
||||
(+0x128, ticks), its running excess (+0x218) and interval (+0x214), logged with the frame rate */
|
||||
volatile uint64_t hos_mkw_pacer;
|
||||
/* HOS_SCAN_DT=<file prefix> (diagnostic): writes every float in guest memory between ~0.015 and ~0.04, with its
|
||||
address, four times 300 presents apart: the game's frame step is either one exact 1/60 or follows the frames */
|
||||
static void scan_dt(long long presents) {
|
||||
static long long first; static const char *prefix; static int scans, read_env;
|
||||
if (!read_env) read_env = 1, prefix = getenv("HOS_SCAN_DT");
|
||||
if (!prefix) return;
|
||||
if (!first) { /* (once <prefix>go exists) */
|
||||
if (presents % 60) return;
|
||||
char go[512];
|
||||
snprintf(go, sizeof go, "%sgo", prefix);
|
||||
FILE *g = fopen(go, "r");
|
||||
if (!g) return;
|
||||
fclose(g);
|
||||
first = presents;
|
||||
}
|
||||
if (presents < first + scans * 300 || scans >= 4) return;
|
||||
char name[512];
|
||||
snprintf(name, sizeof name, "%s%d.txt", prefix, scans++);
|
||||
FILE *f = fopen(name, "w");
|
||||
if (!f) return;
|
||||
size_t hits = 0;
|
||||
for (uint64_t a = 0x80000000ULL; a < 0x2000000000ULL && hits < 4000000;) {
|
||||
MEMORY_BASIC_INFORMATION m;
|
||||
if (!VirtualQuery(GP(a), &m, sizeof m)) break;
|
||||
const uint64_t size = m.RegionSize;
|
||||
if (m.State == MEM_COMMIT && (m.Protect & PAGE_READWRITE)) {
|
||||
const uint32_t *w = (const uint32_t *)m.BaseAddress;
|
||||
for (size_t i = 0; i < size / 4; i++)
|
||||
if (w[i] >= 0x3c800000 && w[i] <= 0x3d230000) {
|
||||
fprintf(f, "%llx %08x\n", (unsigned long long)((uint8_t *)&w[i] - (uint8_t *)GP(0)), w[i]);
|
||||
if (++hits >= 4000000) break;
|
||||
}
|
||||
}
|
||||
a = (uint64_t)((uint8_t *)m.BaseAddress - (uint8_t *)GP(0)) + size;
|
||||
}
|
||||
fclose(f);
|
||||
hos_log("vi: scan %s: %zu floats", name, hits);
|
||||
}
|
||||
/* (hookshot) Game time follows the clock. The engine steps every frame by ratio = 60 / <the graphics module's nominal fps,
|
||||
an int at +0x2c8> (main+0x6e6cc4, f_83b6e300 makes seconds = ratio / 60 and the rest), so at 50 fps the game ran at 83%
|
||||
speed: walking the same 8 s at 52 and 33 fps went as far as those rates. Each present writes the rate of the last 5
|
||||
display intervals there, the rounding error carried to the next frame so that no time is lost; a step is at most
|
||||
1/15 s, as TotK Recomp's frame_rate.c (slower frames slow the game down, as on the console), at least 1/60 s (the game's
|
||||
own limit holds it at 60). HOS_REALTIME_STEP=0: the shipping whole steps. */
|
||||
extern volatile uint64_t hos_gfx_module;
|
||||
volatile int hos_fixed_resolution = 0; /* (the lifted code reads these: nx2/oot_patches.py) */
|
||||
volatile uint32_t hos_fixed_scale_bits = 0x3f800000; /* (HOS_RES_SCALE: the fixed path's scale) */
|
||||
volatile int hos_dynres_runs = 0; /* (the dynamic path's frames: it fills fields the 3D reads, +8 +16 +168) */
|
||||
volatile float hos_text_scale = 1.0f; /* (the letters' clock of a text pane, f_80b1e140: nx2/oot_patches.py) */
|
||||
/* The Insert menu's Text speed (0 Normal, 1 2x, 2 4x, 3 Instant), HOS_TEXT_SPEED=<0..3> over it: what the time of a letter
|
||||
animation's step is multiplied by. Instant: the page at once, as the game's own skip on A */
|
||||
static float text_scale(const char *env, int menu) {
|
||||
const int v = env && *env ? atoi(env) : menu;
|
||||
return v == 1 ? 2.0f : v == 2 ? 4.0f : v >= 3 ? 1e6f : 1.0f;
|
||||
}
|
||||
volatile uint64_t hos_step_probe = 0; /* (f_80706be0's object, set by the lifted code when the frame-time hook is in this build; its
|
||||
+0xd58 is the game clock in 1/60 s: nx2/oot_patches.py) */
|
||||
volatile uint32_t hos_frame_seconds_bits = 0; /* (the frame's seconds as a float's bits for that hook, 0: the game's own step) */
|
||||
volatile uint64_t hos_res_module = 0; /* (f_831f3200's object, whose +0xe5c is the 3D's scale: nx2/oot_patches.py) */
|
||||
static void realtime_step(int64_t now) {
|
||||
int rx_option(int id, int otherwise);
|
||||
/* (Resolution 100% from the start once came out black (the dynamic block's fields unset), so the dynamic path ran 30
|
||||
frames first. Those frames left the 3D at the controller's size, 60% of 1440p (1536x864, then the game's network to
|
||||
2048x1152), whatever the fixed scale said. 11-08: from the first frame, as EvilOOT's Max Resolution patch, the 3D
|
||||
draws at the full 2560x1440, no network pass, not black, same fps; tree edges 23.4 -> 36.1 at the rock) */
|
||||
{ /* (Evil Hookshot, HOS_FIXED_FROM=<n>: the dynamic path's frames before the fixed one, 0 by default = EvilOOT's
|
||||
built-in patch, the fixed path from the first frame) */
|
||||
static int from = -1;
|
||||
if (from < 0) from = getenv("HOS_FIXED_FROM") ? atoi(getenv("HOS_FIXED_FROM")) : 0;
|
||||
/* (HOS_RES_PULSE=<frame>: Auto for 240 frames from that frame, then back: the menu's Auto -> 100% in a lab run) */
|
||||
static long long frame, pulse = -2;
|
||||
if (pulse == -2) pulse = getenv("HOS_RES_PULSE") ? atoll(getenv("HOS_RES_PULSE")) : -1;
|
||||
frame++;
|
||||
const int pulsed = pulse >= 0 && frame >= pulse && frame < pulse + 240;
|
||||
if (pulse >= 0 && (frame == pulse || frame == pulse + 240)) hos_log("vi: resolution pulse: %s at frame %lld", pulsed ? "Auto" : "back to fixed", frame);
|
||||
/* (the menu's Resolution is read once, at the start: switching to Auto in game ran the dynamic path, whose size the
|
||||
game keeps elsewhere, and 100% after it stayed at that size; putting the resolution object back did not undo it.
|
||||
Read when the renderer answers: before, rx_option gives its fallback) */
|
||||
static int dyn_at_start = -1;
|
||||
if (dyn_at_start < 0) dyn_at_start = rx_option(2, -1);
|
||||
hos_fixed_resolution = !pulsed && dyn_at_start == 0 && hos_dynres_runs >= from;
|
||||
}
|
||||
{ /* (Evil Hookshot, HOS_RES_LOG=1: the resolution switch's state every 600 frames) */
|
||||
static int on = -1;
|
||||
static long long n;
|
||||
if (on < 0) on = getenv("HOS_RES_LOG") != NULL;
|
||||
if (on && !(n++ % 600))
|
||||
hos_log("vi: resolution: menu dynamic %d, scale %d/10000, fixed %d, dynamic path runs %d, scale bits %08x", rx_option(2, -1),
|
||||
rx_option(3, -1), hos_fixed_resolution, hos_dynres_runs, (unsigned)hos_fixed_scale_bits);
|
||||
}
|
||||
{
|
||||
static const char *env;
|
||||
static int looked;
|
||||
if (!looked) looked = 1, env = getenv("HOS_TEXT_SPEED");
|
||||
hos_text_scale = text_scale(env, rx_option(5, 0));
|
||||
}
|
||||
{ /* (the Insert menu's Resolution: the fixed path's scale in 1/10000, read once at the start as the mode above;
|
||||
HOS_RES_SCALE below stays over it) */
|
||||
static int scale = -1;
|
||||
if (scale < 0) scale = rx_option(3, -1);
|
||||
if (scale > 0 && !getenv("HOS_RES_SCALE")) {
|
||||
const float v = scale / 10000.0f;
|
||||
memcpy((void *)&hos_fixed_scale_bits, &v, 4);
|
||||
}
|
||||
}
|
||||
{
|
||||
static int read_scale;
|
||||
if (!read_scale) {
|
||||
read_scale = 1;
|
||||
if (getenv("HOS_RES_SCALE")) { float v = (float)atof(getenv("HOS_RES_SCALE")); memcpy((void *)&hos_fixed_scale_bits, &v, 4); }
|
||||
}
|
||||
}
|
||||
{ /* HOS_RES_LOG=1: the 3D's scale every 300 presents. +0xe20: flags (bit 3: 0.75, bit 4: 0.5 in place of the scale),
|
||||
+0xe2c bit 3: recompute asked, +0xe50/+0xe54/+0xe58: the sizes the scale is taken against, +0xe5c: the scale */
|
||||
static int on = -1;
|
||||
static long long n;
|
||||
if (on < 0) on = getenv("HOS_RES_LOG") != NULL;
|
||||
const uint64_t m = hos_res_module;
|
||||
if (on && m && !(n++ % 300)) {
|
||||
float f[4], s;
|
||||
memcpy(f, GP(m + 0xe50), sizeof f);
|
||||
memcpy(&s, (const void *)&hos_fixed_scale_bits, 4);
|
||||
hos_log("vi: res: fixed %d (scale %.3f), +0xe20 %llx, +0xe2c %x, +0xe50 %.0f %.0f %.0f, 3D scale %.3f", hos_fixed_resolution, s,
|
||||
(unsigned long long)*(uint64_t *)GP(m + 0xe20), *(uint32_t *)GP(m + 0xe2c), f[0], f[1], f[2], f[3]);
|
||||
}
|
||||
}
|
||||
const uint64_t mod = hos_gfx_module;
|
||||
if (!mod) return;
|
||||
{ /* (hookshot) The frame limiter (f_8042cd20 sleeps to 1 / +0xfc). The engine's adaptive controller writes +0xfc when
|
||||
variable refresh is on (+0x231, f_804fc0f0), any rate from 40 up. HOS_FPS_TARGET=<fps>: that rate kept, 0: left alone;
|
||||
HOS_FPS_LOG=1: what the game asks for, every 300 presents */
|
||||
static int target = -1, log_on = -1;
|
||||
static long long n;
|
||||
if (target < 0) target = getenv("HOS_FPS_TARGET") ? atoi(getenv("HOS_FPS_TARGET")) : 0, log_on = getenv("HOS_FPS_LOG") != NULL;
|
||||
int *limit = (int *)GP(mod + 0xfc);
|
||||
if (log_on && !(n++ % 300))
|
||||
hos_log("vi: frame limiter %d, vrr %d %d, nominal %d, controller +0x58.. %d %d %d %d", *limit, *(uint8_t *)GP(mod + 0x231),
|
||||
*(uint8_t *)GP(mod + 0x232), *(int *)GP(mod + 0x2c8), *(int *)GP(mod + 0x270 + 0x58), *(int *)GP(mod + 0x270 + 0x28),
|
||||
*(int *)GP(mod + 0x270 + 0x2c), *(int *)GP(mod + 0x270 + 0x30));
|
||||
if (log_on && !((n - 1) % 300) && hos_step_probe) { /* (game speed: the game clock's 1/60 s units a second of wall time, 60.0 at speed 1) */
|
||||
static double clock_before;
|
||||
static int64_t at_before;
|
||||
double game_clock;
|
||||
memcpy(&game_clock, GP(hos_step_probe + 0xd58), 8);
|
||||
if (at_before && now > at_before) {
|
||||
const double rate = (game_clock - clock_before) * 1e9 / (double)(now - at_before);
|
||||
hos_log("vi: game clock %.1f: %.2f a second of wall time (speed %.3f) at %.1f fps", game_clock, rate, rate / 60.0,
|
||||
300e9 / (double)(now - at_before));
|
||||
}
|
||||
clock_before = game_clock, at_before = now;
|
||||
}
|
||||
if (target && *limit > 0 && *limit < target) *limit = target;
|
||||
if (fps_max() > 60 && *limit > 0 && *limit < fps_max()) *limit = fps_max();
|
||||
}
|
||||
/* (the Insert menu's Game speed "per frame": a frame is a 60th of a second of game time. Not past 60 fps: the game would run
|
||||
faster than real time, so a cap above 60 keeps the real-time step whatever that row says) */
|
||||
if (!rx_option(0, 1) && fps_max() <= 60) {
|
||||
int *slot = (int *)GP(mod + 0x2c8);
|
||||
if (*slot >= 15 && *slot <= 60) *slot = 60;
|
||||
return;
|
||||
}
|
||||
static int64_t last;
|
||||
static double samples[5], carry;
|
||||
static unsigned count, next;
|
||||
static long long steps;
|
||||
const double dt = (now - last) / 1e9;
|
||||
last = now;
|
||||
if (dt <= 0 || dt > 0.25) { count = next = 0; carry = 0; return; } /* (a load: the average starts again) */
|
||||
/* (HOS_REALTIME_WINDOW=<1-5>: frames averaged for the step; 1: each step the last frame's own time) */
|
||||
static int window = -1;
|
||||
if (window < 0) {
|
||||
window = getenv("HOS_REALTIME_WINDOW") ? atoi(getenv("HOS_REALTIME_WINDOW")) : 5;
|
||||
window = window < 1 ? 1 : window > 5 ? 5 : window;
|
||||
}
|
||||
samples[next++ % window] = dt;
|
||||
if (count < (unsigned)window) count++;
|
||||
double sum = 0;
|
||||
for (unsigned i = 0; i < count; i++) sum += samples[i];
|
||||
/* (hookshot) A cap above 60: the engine's own rate is 60 / <whole display intervals>, and its controller puts 60 back over a
|
||||
higher +0x2c8 before the step is made from it, so every frame still stepped 1/60 s and the game ran fps / 60 times too fast.
|
||||
The step is then the frames' own time at the two places the engine makes it (nx2/oot_patches.py, hos_frame_seconds_bits):
|
||||
this same average, at most 1/15 s as below and at least 1/240 s, and the rate under it stays the engine's, 60 at most.
|
||||
HOS_FPS_STEP=0, or a lift without the hook (hos_step_probe unset): the rate up to the cap, as before */
|
||||
static int timed_step = -1;
|
||||
if (timed_step < 0) timed_step = !(getenv("HOS_FPS_STEP") && !atoi(getenv("HOS_FPS_STEP")));
|
||||
const int timed = fps_max() > 60 && timed_step && hos_step_probe;
|
||||
if (timed) {
|
||||
const double secs = sum / count;
|
||||
const float f = (float)(secs > 4.0 / 60.0 ? 4.0 / 60.0 : secs < 1.0 / 240.0 ? 1.0 / 240.0 : secs);
|
||||
uint32_t bits;
|
||||
memcpy(&bits, &f, 4);
|
||||
hos_frame_seconds_bits = bits;
|
||||
} else {
|
||||
hos_frame_seconds_bits = 0;
|
||||
}
|
||||
const int top = timed ? 60 : fps_max();
|
||||
double ratio = sum / count * 60.0 + carry;
|
||||
const double least = 60.0 / top;
|
||||
ratio = ratio < least ? least : ratio > 4.0 ? 4.0 : ratio;
|
||||
int fps = (int)(60.0 / ratio + 0.5);
|
||||
fps = fps < 15 ? 15 : fps > top ? top : fps;
|
||||
int *slot = (int *)GP(mod + 0x2c8);
|
||||
if (*slot < 15 || *slot > fps_max()) {
|
||||
static int logged;
|
||||
if (!logged++) hos_log("vi: the graphics module's frame rate reads %d: no real-time step", *slot);
|
||||
return;
|
||||
}
|
||||
carry = ratio - 60.0 / fps;
|
||||
carry = carry > 0.5 ? 0.5 : carry < -0.5 ? -0.5 : carry;
|
||||
*slot = fps;
|
||||
if (!(steps++ % 3000)) hos_log("vi: real-time step on: ratio %.3f, game's frame rate %d", ratio, fps);
|
||||
}
|
||||
/* HOS_PRESENT_TRACE=<csv>: native game present-call returns, not GPU completion or display times.
|
||||
Uses the existing frame ID/clock; a forced stop can lose the last second of buffered present records. */
|
||||
static void present_trace(int64_t frame, int64_t now) {
|
||||
static FILE *file;
|
||||
static char buffer[64 * 1024];
|
||||
static int looked;
|
||||
static int64_t last, flushed;
|
||||
if (!looked) {
|
||||
const char *path = getenv("HOS_PRESENT_TRACE");
|
||||
looked = 1;
|
||||
if (path && *path) {
|
||||
file = fopen(path, "w");
|
||||
if (!file) hos_log("vi: could not open present trace %s", path);
|
||||
}
|
||||
if (file) {
|
||||
setvbuf(file, buffer, _IOFBF, sizeof buffer);
|
||||
fputs("frame,return_ns,interval_ns\n", file);
|
||||
flushed = now;
|
||||
}
|
||||
}
|
||||
if (!file) return;
|
||||
fprintf(file, "%lld,%lld,%lld\n", (long long)frame, (long long)now, (long long)(frame > 1 ? now - last : 0));
|
||||
last = now;
|
||||
if (now - flushed >= 1000000000LL) {
|
||||
fflush(file);
|
||||
flushed = now;
|
||||
}
|
||||
}
|
||||
void hos_vi_native_presented(void) {
|
||||
static long long scan_n;
|
||||
scan_dt(++scan_n);
|
||||
{ /* HOS_FRAME_SLEEP_MS (diagnostic): slower frames, for game speed against frame rate */
|
||||
static int ms = -1;
|
||||
if (ms < 0) ms = getenv("HOS_FRAME_SLEEP_MS") ? atoi(getenv("HOS_FRAME_SLEEP_MS")) : 0;
|
||||
if (ms) hos_sleep_ns(ms * 1000000LL);
|
||||
}
|
||||
const int64_t period = 1000000000LL / fps_max() * present_interval, now = hos_now_ns();
|
||||
realtime_step(now);
|
||||
/* (behind by more than a frame: the next one is paced from now, with no burst to catch up) */
|
||||
next_frame_at = next_frame_at && now - next_frame_at < period ? next_frame_at + period : now + period;
|
||||
{ /* (the display queue: this frame is shown one interval after the last, or now when the display waits) */
|
||||
const int64_t n = shown_count, last = n ? shown_at[(n - 1) & 15] : 0;
|
||||
shown_at[n & 15] = last + period > now ? last + period : now;
|
||||
shown_count = n + 1;
|
||||
}
|
||||
const int64_t n = InterlockedIncrement64(&presents);
|
||||
present_trace(n, now);
|
||||
{ /* HOS_MKW_INTERVAL=<0|1|2>: the interval MKW's pacer is held at, through its own override (+0x210, any
|
||||
non-zero value is used as the interval): 1 (the default): a steady 60 fps; 2: 30; 0: the game's choice,
|
||||
which with frames between 16.7 and 33 ms swings between the two (25-27 fps, stutters). Its timing counts
|
||||
vsyncs, so an interval the renderer cannot keep slows the game down rather than dropping frames */
|
||||
static int forced = -1;
|
||||
if (forced < 0) forced = getenv("HOS_MKW_INTERVAL") ? atoi(getenv("HOS_MKW_INTERVAL")) : 1;
|
||||
if (hos_mkw_pacer && forced >= 0 && forced <= 2) G32(hos_mkw_pacer + 0x210) = (uint32_t)forced;
|
||||
}
|
||||
if (!window_start) window_start = now;
|
||||
frames_in_window++;
|
||||
/* (present-to-present intervals of the window, in buckets: which frames miss their vsync) */
|
||||
static int64_t last_present;
|
||||
static int hist[6];
|
||||
if (last_present) {
|
||||
const int64_t d = now - last_present;
|
||||
hist[d < 15500000 ? 0 : d < 17800000 ? 1 : d < 22000000 ? 2 : d < 30000000 ? 3 : d < 40000000 ? 4 : 5]++;
|
||||
}
|
||||
last_present = now;
|
||||
if (now - window_start >= 5000000000LL) {
|
||||
hos_log("vi: %lld frames presented (%.1f fps over the last %.1f s, interval %d)", (long long)n,
|
||||
frames_in_window * 1e9 / (double)(now - window_start), (now - window_start) / 1e9, present_interval);
|
||||
hos_log("vi: present intervals: <15.5 ms %d, 15.5-17.8 %d, 17.8-22 %d, 22-30 %d, 30-40 %d, over 40 %d", hist[0],
|
||||
hist[1], hist[2], hist[3], hist[4], hist[5]);
|
||||
memset(hist, 0, sizeof hist);
|
||||
window_start = now, frames_in_window = 0;
|
||||
const uint64_t pacer = hos_mkw_pacer, freq = pacer ? G64(0x837de940) : 0; /* (MKW only: nvn_native.c) */
|
||||
if (pacer && freq)
|
||||
hos_log("vi: the game's pacer: frame work %.1f ms, excess %.1f ms, interval %d",
|
||||
(double)(int64_t)G64(pacer + 0x128) * 1e3 / (double)freq,
|
||||
(double)(int64_t)G64(pacer + 0x218) * 1e3 / (double)freq, (int)G32(pacer + 0x214)),
|
||||
hos_log("vi: pacer raw: now %llx f0 %llx 128 %llx e8 %llx 50 %x 210 %x 22c %x freq %llu", (unsigned long long)hos_ticks(),
|
||||
(unsigned long long)G64(pacer + 0xf0), (unsigned long long)G64(pacer + 0x128),
|
||||
(unsigned long long)G64(pacer + 0xe8), G32(pacer + 0x50), G32(pacer + 0x210), *(const uint8_t *)GP(pacer + 0x22c),
|
||||
(unsigned long long)freq);
|
||||
}
|
||||
}
|
||||
788
host/nn_video.c
Normal file
788
host/nn_video.c
Normal file
@@ -0,0 +1,788 @@
|
||||
/* nn::codec's hardware video decoders (VP8/VP9 here) and their image pools, on FFmpeg's libavcodec (the static
|
||||
libraries in Eglantine's package cache: work/eg/.cache/cpm/ffmpeg). MKW's movie library (subsdk0, movie::) plays
|
||||
its WebM movies through them: the cup openings, the courses' billboards, the emblems.
|
||||
|
||||
How the library uses them (subsdk0, movie::detail::VideoDecoderBuffer): each picture buffer is an image pool of
|
||||
one image, sized by MakeDecodeImagePreference + CalculateDecoderImagePoolBuffer, registered with the decoder by
|
||||
index (RegisterXDecoderBuffer). It submits each compressed frame (SubmitXDecoderInputBuffer), takes finished
|
||||
pictures by buffer index (AcquireXDecoderOutputBuffer, GetXDecoderOutputBufferProperties), reads them back to
|
||||
its own memory as RGBA or NV12 (ReadDecoderOutputImageRgba / Nv12) and gives the buffer back (Release).
|
||||
|
||||
Here a submission is decoded at once; a finished picture waits in a queue until an Acquire puts it in the first
|
||||
free registered buffer (host memory: the pool's guest memory is not used). The video service itself (nn::gsv) is
|
||||
not emulated: nn::codec::video::Initialize does nothing. */
|
||||
#include "hos.h"
|
||||
#include <limits.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#ifdef _WIN32
|
||||
#include <shellapi.h>
|
||||
#endif
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libswscale/swscale.h>
|
||||
|
||||
#define RESULT_NO_OUTPUT 0x2a1ca /* (a failure: "no picture yet"; the library polls again) */
|
||||
#define POOL_MAGIC 0x4c4f4f50u /* 'POOL' */
|
||||
#define DEC_MAGIC 0x43454456u /* 'VDEC' */
|
||||
#define PREF_MAGIC 0x46455250u /* 'PREF' */
|
||||
#define MAX_SLOTS 16
|
||||
#define MAX_QUEUE 8
|
||||
|
||||
static int video_log(void) { /* HOS_VIDEO_LOG=1: submissions and acquisitions */
|
||||
static int on = -1;
|
||||
if (on < 0) on = getenv("HOS_VIDEO_LOG") != NULL;
|
||||
return on;
|
||||
}
|
||||
|
||||
void hos_system_event_init(uint64_t key, int autoclear); /* nn_os_sync.c */
|
||||
void hos_system_event_signal(uint64_t key);
|
||||
|
||||
/* an image pool: its pictures, w x h, as RGBA and as NV12 (both kept: the reader asks for either) */
|
||||
typedef struct {
|
||||
int w, h, format, count;
|
||||
uint8_t *rgba, *nv12;
|
||||
uint64_t mem, mem_size; /* (hookshot) the pool's guest memory: where the hardware decoder writes its pictures */
|
||||
int rgba_stale; /* (hookshot) its NV12 picture not converted to RGBA yet (pool_rgba, when it is asked for) */
|
||||
int read_by_api; /* (hookshot) read through ReadDecoderOutputImage*: no copy into its memory (dec_acquire) */
|
||||
struct SwsContext *sws; /* (that conversion's) */
|
||||
} Pool;
|
||||
/* the preference MakeDecodeImagePreference returns (the caller's buffer is larger: only these fields are ours) */
|
||||
typedef struct { uint32_t magic; uint16_t w, h; uint32_t format, tiling; } Pref;
|
||||
|
||||
/* (rgba NULL: a picture decoded as NV12 is kept as that alone; its pool makes the RGBA if a reader wants it) */
|
||||
typedef struct { uint8_t *rgba, *nv12; int w, h; int64_t pts; int last; } Picture;
|
||||
/* a submission waiting to be decoded (pkt NULL: the stream's end) */
|
||||
typedef struct Pending { AVPacket *pkt; struct Pending *next; } Pending;
|
||||
#ifdef _WIN32
|
||||
/* (hookshot, issue 380) once, when Windows has no AV1 decoder: OoT's movies are AV1, and Windows decodes it only with
|
||||
Microsoft's free "AV1 Video Extension" (preinstalled on most PCs, not all). Yes opens its Store page */
|
||||
static DWORD WINAPI av1_notice(LPVOID unused) {
|
||||
(void)unused;
|
||||
if (MessageBoxA(NULL, "The game's movies need Microsoft's free \"AV1 Video Extension\", which this PC doesn't have, so they "
|
||||
"show black (the sound plays).\n\nOpen its page in the Microsoft Store now? Install it, then start the game again.",
|
||||
"Triforce", MB_YESNO | MB_ICONINFORMATION | MB_SETFOREGROUND) == IDYES)
|
||||
ShellExecuteA(NULL, "open", "ms-windows-store://pdp/?ProductId=9MVZQVXJBQ9V", NULL, NULL, SW_SHOWNORMAL);
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
/* (hookshot) host/mf_av1.c: AV1 on Media Foundation, as the static FFmpeg has no AV1 decoder */
|
||||
typedef void (*mf_av1_picture_fn)(void *user, const uint8_t *y, const uint8_t *uv, int w, int h, int stride, int64_t pts);
|
||||
void *mf_av1_open(int w, int h);
|
||||
void mf_av1_decode(void *m, const uint8_t *data, size_t n, int64_t pts, mf_av1_picture_fn fn, void *user);
|
||||
void mf_av1_flush(void *m);
|
||||
void mf_av1_close(void *m);
|
||||
|
||||
typedef struct {
|
||||
AVCodecContext *ctx;
|
||||
void *mf; /* (hookshot) an AV1 decoder on Media Foundation instead of ctx */
|
||||
AVPacket *pkt;
|
||||
AVFrame *frame;
|
||||
struct SwsContext *sws;
|
||||
int sws_w, sws_h, sws_fmt;
|
||||
uint64_t slots[MAX_SLOTS]; /* registered pools (guest pointers), by buffer index */
|
||||
int busy[MAX_SLOTS]; /* acquired, not released */
|
||||
int64_t slot_pts[MAX_SLOTS];
|
||||
int slot_last[MAX_SLOTS]; /* the stream's last picture (the submission marked last, all decoded) */
|
||||
Picture queue[MAX_QUEUE];
|
||||
int qhead, qn;
|
||||
int eos; /* the last submission is in and decoded: an empty queue is the end */
|
||||
Pending *phead, *ptail; /* submissions not decoded yet, oldest first */
|
||||
int64_t submits, acquires;
|
||||
int clock_set; /* (hookshot) the movie's clock: the picture at clock_pts was due at clock_ns */
|
||||
int64_t clock_ns, clock_pts;
|
||||
int64_t last_pts; /* the pts of the last picture handed out */
|
||||
int64_t log_submits; /* (HOS_VIDEO_LOG) submissions still to log, after a flush or the end */
|
||||
SRWLOCK lock;
|
||||
} Dec;
|
||||
|
||||
/* (hookshot) the host objects of the game's pool and decoder objects, by the guest object's address: kept here, not in
|
||||
the guest object (guest memory). Few at a time (a movie's decoder and its pools). */
|
||||
typedef struct { uint64_t obj; uint32_t magic; void *p; } HostObj;
|
||||
static HostObj *host_objs;
|
||||
static size_t nhost_objs, cap_host_objs;
|
||||
static SRWLOCK host_objs_lock = SRWLOCK_INIT;
|
||||
static void *host_of(uint64_t obj, uint32_t magic) {
|
||||
void *p = NULL;
|
||||
if (!obj) return NULL;
|
||||
AcquireSRWLockShared(&host_objs_lock);
|
||||
for (size_t i = 0; i < nhost_objs; i++)
|
||||
if (host_objs[i].obj == obj && host_objs[i].magic == magic) p = host_objs[i].p;
|
||||
ReleaseSRWLockShared(&host_objs_lock);
|
||||
return p;
|
||||
}
|
||||
static void set_host(uint64_t obj, uint32_t magic, void *p) {
|
||||
if (!obj) return;
|
||||
AcquireSRWLockExclusive(&host_objs_lock);
|
||||
size_t i = 0;
|
||||
while (i < nhost_objs && host_objs[i].obj != obj) i++;
|
||||
if (!p) {
|
||||
if (i < nhost_objs) host_objs[i] = host_objs[--nhost_objs];
|
||||
} else {
|
||||
if (i == nhost_objs) {
|
||||
if (nhost_objs == cap_host_objs) {
|
||||
cap_host_objs = cap_host_objs ? cap_host_objs * 2 : 16;
|
||||
host_objs = (HostObj *)realloc(host_objs, cap_host_objs * sizeof *host_objs);
|
||||
if (!host_objs) hos_fatal(NULL, "video: out of memory");
|
||||
}
|
||||
nhost_objs++;
|
||||
}
|
||||
host_objs[i] = (HostObj){obj, magic, p};
|
||||
}
|
||||
ReleaseSRWLockExclusive(&host_objs_lock);
|
||||
}
|
||||
|
||||
/* ---- the service ---- */
|
||||
HLE(_ZN2nn5codec5video10InitializeEv) {
|
||||
static int logged;
|
||||
if (!logged++) hos_log("video: nn::codec::video on libavcodec");
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn5codec5video8FinalizeEv) { RET(0); }
|
||||
|
||||
/* ---- image pools ---- */
|
||||
/* MakeDecodeImagePreference(u16 w, u16 h, OutputFormat, TilingMode) -> the preference (returned through x8) */
|
||||
HLE(_ZN2nn5codec25MakeDecodeImagePreferenceEttNS0_24VideoDecoderOutputFormatENS0_15ImageTilingModeE) {
|
||||
const uint64_t out = c->x[8];
|
||||
Pref p = {PREF_MAGIC, (uint16_t)ARG(0), (uint16_t)ARG(1), (uint32_t)ARG(2), (uint32_t)ARG(3)};
|
||||
if (out) memcpy(GP(out), &p, sizeof p);
|
||||
RET(out);
|
||||
}
|
||||
/* CalculateDecoderImagePoolBuffer(u64* size, u64* alignment, Preference const&, u32 count) */
|
||||
HLE(_ZN2nn5codec31CalculateDecoderImagePoolBufferEPmS1_RKNS0_27VideoDecoderImagePreferenceEj) {
|
||||
const Pref *p = (const Pref *)GP(ARG(2));
|
||||
const uint64_t one = p->magic == PREF_MAGIC ? (uint64_t)p->w * p->h * 4 : 0x400000;
|
||||
if (ARG(0)) G64(ARG(0)) = ((one * (uint32_t)ARG(3)) + 0xFFF) & ~0xFFFull;
|
||||
if (ARG(1)) G64(ARG(1)) = 0x1000;
|
||||
RET(0);
|
||||
}
|
||||
/* InitializeDecoderImagePool(pool, void* memory, size, Preference const&, u32 count) */
|
||||
HLE(_ZN2nn5codec26InitializeDecoderImagePoolEPNS0_25VideoDecoderImagePoolTypeEPvmRKNS0_27VideoDecoderImagePreferenceEj) {
|
||||
const Pref *p = (const Pref *)GP(ARG(3));
|
||||
Pool *o = (Pool *)calloc(1, sizeof *o);
|
||||
if (!o) hos_fatal(NULL, "video: out of memory for an image pool");
|
||||
o->w = p->magic == PREF_MAGIC && p->w ? p->w : 1280, o->h = p->magic == PREF_MAGIC && p->h ? p->h : 720;
|
||||
o->format = p->magic == PREF_MAGIC ? (int)p->format : 2;
|
||||
o->count = (int)ARG(4) > 0 ? (int)ARG(4) : 1;
|
||||
o->rgba = (uint8_t *)calloc((size_t)o->count, (size_t)o->w * o->h * 4);
|
||||
/* (hookshot, issue 342: an allocation that failed went on as a NULL picture, and the movie thread read address 0) */
|
||||
o->nv12 = (uint8_t *)calloc((size_t)o->count, (size_t)o->w * o->h * 3 / 2);
|
||||
/* (hookshot) video black, not zeros. A buffer the game takes before the decoder's first picture is shown as it is
|
||||
(dec_acquire: "nothing decoded, the buffer again", up to ~100 ms into a movie's start), and NV12 zeros are bright
|
||||
green (luma 0 with no chroma): one green frame at each scene change that opens a movie. Luma 16, chroma 128 is
|
||||
black; the RGBA opaque black */
|
||||
if (o->nv12) {
|
||||
for (int i = 0; i < o->count; i++) {
|
||||
uint8_t *img = o->nv12 + (size_t)i * o->w * o->h * 3 / 2;
|
||||
memset(img, 0x10, (size_t)o->w * o->h);
|
||||
memset(img + (size_t)o->w * o->h, 0x80, (size_t)o->w * o->h / 2);
|
||||
}
|
||||
}
|
||||
if (o->rgba)
|
||||
for (size_t k = 3; k < (size_t)o->count * o->w * o->h * 4; k += 4) o->rgba[k] = 0xff;
|
||||
o->mem = ARG(1), o->mem_size = ARG(2);
|
||||
if (video_log())
|
||||
hos_log("video: image pool %#llx: %dx%d format %d, %d images, memory %#llx+%#llx", (unsigned long long)ARG(0),
|
||||
o->w, o->h, o->format, o->count, (unsigned long long)o->mem, (unsigned long long)o->mem_size);
|
||||
set_host(ARG(0), POOL_MAGIC, o);
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn5codec24FinalizeDecoderImagePoolEPNS0_25VideoDecoderImagePoolTypeE) {
|
||||
Pool *o = (Pool *)host_of(ARG(0), POOL_MAGIC);
|
||||
if (o && o->sws) sws_freeContext(o->sws);
|
||||
if (o) free(o->rgba), free(o->nv12), free(o);
|
||||
set_host(ARG(0), POOL_MAGIC, NULL);
|
||||
}
|
||||
/* (hookshot) the pool's picture as RGBA, from its NV12, if it was not made yet. Each 1080p frame of OoT's movies was
|
||||
converted on the movie thread, in plain C, though OoT reads only the NV12: nearly half that thread's time, which put the
|
||||
picture behind the sound */
|
||||
static SRWLOCK pool_rgba_lock = SRWLOCK_INIT;
|
||||
static void pool_rgba(Pool *o) {
|
||||
AcquireSRWLockExclusive(&pool_rgba_lock);
|
||||
if (o->rgba_stale && o->rgba && o->nv12) {
|
||||
if (!o->sws)
|
||||
o->sws = sws_getContext(o->w, o->h, AV_PIX_FMT_NV12, o->w, o->h, AV_PIX_FMT_RGBA, SWS_BILINEAR, NULL, NULL, NULL);
|
||||
const uint8_t *src[4] = {o->nv12, o->nv12 + (size_t)o->w * o->h, NULL, NULL};
|
||||
const int src_stride[4] = {o->w, o->w, 0, 0};
|
||||
uint8_t *dst[4] = {o->rgba, NULL, NULL, NULL};
|
||||
int dst_stride[4] = {o->w * 4, 0, 0, 0};
|
||||
if (o->sws) sws_scale(o->sws, src, src_stride, 0, o->h, dst, dst_stride);
|
||||
o->rgba_stale = 0;
|
||||
}
|
||||
ReleaseSRWLockExclusive(&pool_rgba_lock);
|
||||
}
|
||||
/* ReadDecoderOutputImageRgba(pool, u32 index, u16 x, u16 y, u16 w, u16 h, void* dst, size_t stride, size_t size) */
|
||||
HLE(_ZN2nn5codec26ReadDecoderOutputImageRgbaEPKNS0_25VideoDecoderImagePoolTypeEjttttPvmm) {
|
||||
Pool *o = (Pool *)host_of(ARG(0), POOL_MAGIC);
|
||||
const uint32_t i = (uint32_t)ARG(1), x = (uint16_t)ARG(2), y = (uint16_t)ARG(3), w = (uint16_t)ARG(4), h = (uint16_t)ARG(5);
|
||||
const uint64_t dst = ARG(6), stride = ARG(7) ? ARG(7) : (uint64_t)w * 4;
|
||||
{ /* (hookshot, HOS_VIDEO_LOG) the first reads, with where they go */
|
||||
static volatile LONG n;
|
||||
if (video_log() && InterlockedIncrement(&n) <= 4)
|
||||
hos_log("video: ReadDecoderOutputImageRgba(pool %s, index %u, %u,%u %ux%u, dst %#llx stride %llu)",
|
||||
o ? "ok" : "unknown", i, x, y, w, h, (unsigned long long)dst, (unsigned long long)stride);
|
||||
}
|
||||
if (!o || !o->rgba || i >= (uint32_t)o->count || !dst || x >= (uint32_t)o->w) { RET(0); return; }
|
||||
o->read_by_api = 1;
|
||||
if (i == 0 && o->rgba_stale) pool_rgba(o);
|
||||
const uint8_t *src = o->rgba + (size_t)i * o->w * o->h * 4;
|
||||
const uint32_t cw = x + w <= (uint32_t)o->w ? w : o->w - x;
|
||||
for (uint32_t r = 0; r < h && y + r < (uint32_t)o->h; r++) {
|
||||
void *row = hos_guest_range(dst + r * stride, (size_t)cw * 4); /* (hookshot: only into guest memory) */
|
||||
if (row) memcpy(row, src + ((size_t)(y + r) * o->w + x) * 4, (size_t)cw * 4);
|
||||
}
|
||||
HOS_WRITTEN(GP(dst), (size_t)(h ? h - 1 : 0) * stride + (size_t)cw * 4); /* (the game may give it to the GPU) */
|
||||
RET(0);
|
||||
}
|
||||
/* ReadDecoderOutputImageNv12(pool, u32 index, u16 x, u16 y, u16 w, u16 h, void* y_dst, size_t y_stride, [stack:]
|
||||
size_t y_size, void* uv_dst, size_t uv_stride, size_t uv_size) */
|
||||
HLE(_ZN2nn5codec26ReadDecoderOutputImageNv12EPKNS0_25VideoDecoderImagePoolTypeEjttttPvmmS4_mm) {
|
||||
Pool *o = (Pool *)host_of(ARG(0), POOL_MAGIC);
|
||||
const uint32_t i = (uint32_t)ARG(1), x = (uint16_t)ARG(2), y = (uint16_t)ARG(3), w = (uint16_t)ARG(4), h = (uint16_t)ARG(5);
|
||||
const uint64_t ydst = ARG(6), ystride = ARG(7) ? ARG(7) : w;
|
||||
const uint64_t uvdst = G64(c->x[31] + 8), uvstride = G64(c->x[31] + 16) ? G64(c->x[31] + 16) : w;
|
||||
{ /* (HOS_VIDEO_LOG) each new destination, with the pool and image */
|
||||
static uint64_t seen[32];
|
||||
static volatile LONG nseen;
|
||||
int k;
|
||||
for (k = 0; k < nseen && seen[k] != ydst; k++) {}
|
||||
if (video_log() && k == nseen && nseen < 32) {
|
||||
seen[InterlockedIncrement(&nseen) - 1] = ydst;
|
||||
hos_log("video: ReadDecoderOutputImageNv12(pool %#llx %s, index %u, %u,%u %ux%u, y %#llx/%llu, uv %#llx/%llu) "
|
||||
"lr %#llx", (unsigned long long)ARG(0), o ? "ok" : "unknown", i, x, y, w, h, (unsigned long long)ydst,
|
||||
(unsigned long long)ystride, (unsigned long long)uvdst, (unsigned long long)uvstride,
|
||||
(unsigned long long)c->x[30]);
|
||||
}
|
||||
}
|
||||
/* (hookshot) and no NV12 when its allocation failed: o->nv12 + offset was then any host address, copied to the game */
|
||||
if (!o || !o->nv12 || i >= (uint32_t)o->count || x >= (uint32_t)o->w) { RET(0); return; }
|
||||
o->read_by_api = 1;
|
||||
const uint8_t *yp = o->nv12 + (size_t)i * o->w * o->h * 3 / 2, *uvp = yp + (size_t)o->w * o->h;
|
||||
const uint32_t cw = x + w <= (uint32_t)o->w ? w : o->w - x;
|
||||
for (uint32_t r = 0; ydst && r < h && y + r < (uint32_t)o->h; r++) {
|
||||
void *row = hos_guest_range(ydst + r * ystride, cw); /* (hookshot: only into guest memory) */
|
||||
if (row) memcpy(row, yp + (size_t)(y + r) * o->w + x, cw);
|
||||
}
|
||||
for (uint32_t r = 0; uvdst && r < h / 2 && y / 2 + r < (uint32_t)o->h / 2; r++) {
|
||||
void *row = hos_guest_range(uvdst + r * uvstride, cw);
|
||||
if (row) memcpy(row, uvp + (size_t)(y / 2 + r) * o->w + (x & ~1u), cw);
|
||||
}
|
||||
if (ydst) HOS_WRITTEN(GP(ydst), (size_t)(h ? h - 1 : 0) * ystride + cw);
|
||||
if (uvdst) HOS_WRITTEN(GP(uvdst), (size_t)(h / 2 ? h / 2 - 1 : 0) * uvstride + cw);
|
||||
RET(0);
|
||||
}
|
||||
|
||||
/* ---- decoders ---- */
|
||||
static void dec_init_sized(Ctx *c, enum AVCodecID id, const char *what, int w, int h);
|
||||
static void dec_init(Ctx *c, enum AVCodecID id, const char *what) { dec_init_sized(c, id, what, 0, 0); }
|
||||
static void dec_init_sized(Ctx *c, enum AVCodecID id, const char *what, int w, int h) {
|
||||
const AVCodec *codec = NULL;
|
||||
#ifndef _WIN32 /* (linux) FFmpeg's own AV1 decoder needs a hardware context, and there is no Media Foundation to fall
|
||||
back on: dav1d, else libaom, by name */
|
||||
if (id == AV_CODEC_ID_AV1) codec = avcodec_find_decoder_by_name("libdav1d");
|
||||
if (!codec && id == AV_CODEC_ID_AV1) codec = avcodec_find_decoder_by_name("libaom-av1");
|
||||
#endif
|
||||
if (!codec) codec = avcodec_find_decoder(id);
|
||||
Dec *d = (Dec *)calloc(1, sizeof *d);
|
||||
InitializeSRWLock(&d->lock);
|
||||
if (codec) {
|
||||
d->ctx = avcodec_alloc_context3(codec);
|
||||
d->ctx->thread_count = id == AV_CODEC_ID_AV1 ? 4 : 2; /* (1080p AV1 in software) */
|
||||
if (avcodec_open2(d->ctx, codec, NULL) < 0) avcodec_free_context(&d->ctx);
|
||||
}
|
||||
if (!d->ctx && id == AV_CODEC_ID_AV1) d->mf = mf_av1_open(w, h);
|
||||
#ifdef _WIN32
|
||||
if (!d->ctx && !d->mf && id == AV_CODEC_ID_AV1) { /* (issue 380: no AV1 decoder in Windows: the movies were black, with sound) */
|
||||
static volatile LONG told;
|
||||
if (!InterlockedExchange(&told, 1)) {
|
||||
hos_log("video: no AV1 decoder: install Microsoft's free AV1 Video Extension for the movies");
|
||||
if (!getenv("HOS_HEADLESS") && !getenv("HOOKSHOT_NO_AV1_NOTICE"))
|
||||
CreateThread(NULL, 0, av1_notice, NULL, 0, NULL);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
d->pkt = av_packet_alloc();
|
||||
d->frame = av_frame_alloc();
|
||||
set_host(ARG(0), DEC_MAGIC, d);
|
||||
static int logged;
|
||||
if (logged++ < 4)
|
||||
hos_log("video: %s decoder %s (%dx%d)", what, d->ctx ? "ready" : d->mf ? "ready on Media Foundation" :
|
||||
"not available in this FFmpeg", w, h);
|
||||
RET(0);
|
||||
}
|
||||
static void picture_free(Picture *p) {
|
||||
free(p->rgba), free(p->nv12);
|
||||
memset(p, 0, sizeof *p);
|
||||
}
|
||||
static void pending_free(Dec *d) {
|
||||
while (d->phead) {
|
||||
Pending *n = d->phead;
|
||||
d->phead = n->next;
|
||||
av_packet_free(&n->pkt);
|
||||
free(n);
|
||||
}
|
||||
d->ptail = NULL;
|
||||
}
|
||||
static void dec_finalize(Ctx *c) {
|
||||
Dec *d = (Dec *)host_of(ARG(0), DEC_MAGIC);
|
||||
if (!d) return;
|
||||
pending_free(d);
|
||||
for (int i = 0; i < d->qn; i++) picture_free(&d->queue[(d->qhead + i) % MAX_QUEUE]);
|
||||
if (d->sws) sws_freeContext(d->sws);
|
||||
avcodec_free_context(&d->ctx);
|
||||
mf_av1_close(d->mf);
|
||||
av_packet_free(&d->pkt);
|
||||
av_frame_free(&d->frame);
|
||||
free(d);
|
||||
set_host(ARG(0), DEC_MAGIC, NULL);
|
||||
}
|
||||
/* a decoded frame into the queue, as RGBA and NV12 (the oldest dropped when the reader falls behind) */
|
||||
static void queue_frame(Dec *d, const AVFrame *f) {
|
||||
const int w = f->width, h = f->height;
|
||||
if (w <= 0 || h <= 0) return;
|
||||
if (f->format != AV_PIX_FMT_NV12 && (!d->sws || d->sws_w != w || d->sws_h != h || d->sws_fmt != f->format)) {
|
||||
if (d->sws) sws_freeContext(d->sws);
|
||||
d->sws = sws_getContext(w, h, (enum AVPixelFormat)f->format, w, h, AV_PIX_FMT_RGBA, SWS_BILINEAR, NULL, NULL, NULL);
|
||||
d->sws_w = w, d->sws_h = h, d->sws_fmt = f->format;
|
||||
}
|
||||
Picture p = {0};
|
||||
p.w = w, p.h = h, p.pts = f->pts;
|
||||
const int nv12 = f->format == AV_PIX_FMT_NV12; /* (hookshot: Media Foundation's pictures, kept as NV12 alone) */
|
||||
p.rgba = nv12 ? NULL : (uint8_t *)malloc((size_t)w * h * 4);
|
||||
p.nv12 = nv12 ? (uint8_t *)malloc((size_t)w * h * 3 / 2) : (uint8_t *)calloc(1, (size_t)w * h * 3 / 2);
|
||||
if (!p.nv12 || (!nv12 && !p.rgba)) { /* (out of memory: this frame is dropped, not written through NULL; issue 342) */
|
||||
static volatile LONG told;
|
||||
if (InterlockedIncrement(&told) <= 4) hos_log("video: no memory for a %dx%d frame: dropped", w, h);
|
||||
free(p.rgba), free(p.nv12);
|
||||
return;
|
||||
}
|
||||
uint8_t *dst[4] = {p.rgba, NULL, NULL, NULL};
|
||||
int dst_stride[4] = {w * 4, 0, 0, 0};
|
||||
if (d->sws && p.rgba) sws_scale(d->sws, (const uint8_t *const *)f->data, f->linesize, 0, h, dst, dst_stride);
|
||||
if (nv12) {
|
||||
for (int y = 0; y < h; y++) memcpy(p.nv12 + (size_t)y * w, f->data[0] + (size_t)y * f->linesize[0], (size_t)w);
|
||||
for (int y = 0; y < h / 2; y++)
|
||||
memcpy(p.nv12 + (size_t)w * h + (size_t)y * w, f->data[1] + (size_t)y * f->linesize[1], (size_t)w);
|
||||
} else if (f->format == AV_PIX_FMT_YUV420P || f->format == AV_PIX_FMT_YUVA420P) { /* (planar 4:2:0 -> NV12) */
|
||||
for (int y = 0; y < h; y++) memcpy(p.nv12 + (size_t)y * w, f->data[0] + (size_t)y * f->linesize[0], (size_t)w);
|
||||
uint8_t *uv = p.nv12 + (size_t)w * h;
|
||||
for (int y = 0; y < h / 2; y++)
|
||||
for (int x = 0; x < w / 2; x++) {
|
||||
uv[(size_t)y * w + 2 * x] = f->data[1][(size_t)y * f->linesize[1] + x];
|
||||
uv[(size_t)y * w + 2 * x + 1] = f->data[2][(size_t)y * f->linesize[2] + x];
|
||||
}
|
||||
}
|
||||
if (d->qn == MAX_QUEUE) {
|
||||
picture_free(&d->queue[d->qhead]);
|
||||
d->qhead = (d->qhead + 1) % MAX_QUEUE, d->qn--;
|
||||
}
|
||||
d->queue[(d->qhead + d->qn) % MAX_QUEUE] = p;
|
||||
d->qn++;
|
||||
}
|
||||
static void mf_picture(void *user, const uint8_t *y, const uint8_t *uv, int w, int h, int stride, int64_t pts) {
|
||||
AVFrame f;
|
||||
memset(&f, 0, sizeof f);
|
||||
f.width = w, f.height = h, f.format = AV_PIX_FMT_NV12, f.pts = pts;
|
||||
f.data[0] = (uint8_t *)y, f.data[1] = (uint8_t *)uv;
|
||||
f.linesize[0] = f.linesize[1] = stride;
|
||||
queue_frame((Dec *)user, &f);
|
||||
}
|
||||
static void drain(Dec *d) {
|
||||
while (avcodec_receive_frame(d->ctx, d->frame) == 0) {
|
||||
queue_frame(d, d->frame);
|
||||
av_frame_unref(d->frame);
|
||||
}
|
||||
}
|
||||
/* the oldest submissions decoded until a picture comes out (or none are left). The stream's end is taken as soon as
|
||||
it is next, pictures queued or not: the last picture decoded must carry the last flag, as the hardware's does. Media
|
||||
Foundation's decoder holds nothing back, so waiting for an empty queue gave the flag only to a buffer handed out
|
||||
again, with an older picture's pts, after the real last one went out unmarked */
|
||||
static void decode_next(Dec *d);
|
||||
static void decode_pending(Dec *d) {
|
||||
while (d->phead && (!d->qn || !d->phead->pkt)) decode_next(d);
|
||||
}
|
||||
/* one submission decoded (its pictures into the queue, if any) */
|
||||
static void decode_next(Dec *d) {
|
||||
if (d->phead) {
|
||||
Pending *n = d->phead;
|
||||
d->phead = n->next;
|
||||
if (!d->phead) d->ptail = NULL;
|
||||
if (d->mf) { /* (hookshot) */
|
||||
if (n->pkt) {
|
||||
d->eos = 0;
|
||||
mf_av1_decode(d->mf, n->pkt->data, (size_t)n->pkt->size, n->pkt->pts, mf_picture, d);
|
||||
av_packet_free(&n->pkt);
|
||||
} else {
|
||||
mf_av1_decode(d->mf, NULL, 0, 0, mf_picture, d);
|
||||
d->eos = 1;
|
||||
d->log_submits = 8; /* (data after the end: a restart, worth seeing) */
|
||||
if (d->qn) d->queue[(d->qhead + d->qn - 1) % MAX_QUEUE].last = 1;
|
||||
}
|
||||
} else if (n->pkt) {
|
||||
d->eos = 0;
|
||||
if (avcodec_send_packet(d->ctx, n->pkt) == AVERROR(EAGAIN)) { /* (full: its pictures out first) */
|
||||
drain(d);
|
||||
avcodec_send_packet(d->ctx, n->pkt);
|
||||
}
|
||||
drain(d);
|
||||
av_packet_free(&n->pkt);
|
||||
} else { /* (the end: the rest out, the last picture marked) */
|
||||
avcodec_send_packet(d->ctx, NULL);
|
||||
drain(d);
|
||||
d->eos = 1;
|
||||
d->log_submits = 8;
|
||||
if (d->qn) d->queue[(d->qhead + d->qn - 1) % MAX_QUEUE].last = 1;
|
||||
avcodec_flush_buffers(d->ctx); /* (a stream after it starts again) */
|
||||
}
|
||||
free(n);
|
||||
}
|
||||
}
|
||||
static void pending_push(Dec *d, AVPacket *pkt) {
|
||||
Pending *n = (Pending *)calloc(1, sizeof *n);
|
||||
n->pkt = pkt;
|
||||
if (d->ptail) d->ptail->next = n;
|
||||
else d->phead = n;
|
||||
d->ptail = n;
|
||||
}
|
||||
/* SubmitXDecoderInputBuffer(u64* id, decoder, data, size, TimeSpan pts, bool last): kept, decoded when a picture is
|
||||
acquired (the library submits a whole movie at once: its pictures decoded then would not fit any queue) */
|
||||
static volatile LONG64 submissions;
|
||||
|
||||
/* (hookshot) A buffer handed out with nothing decoded into it, by a decoder with nothing left to decode, gets a sync
|
||||
handle that is not reached until something is submitted again (anywhere: the count is global). Every other buffer's
|
||||
is 0, reached. The hardware's is a fence the decoder signals once the picture is in the buffer, so an idle decoder's
|
||||
never is; the movie library's VideoDecoder::Flush recycles buffers until it finds one not reached, and with all of
|
||||
them reached it never returned: the movie never stopped, and the game sat on a black screen after its intro.
|
||||
The library also waits for the handle as a sync point event (VideoDecoderEventManager::SetFence), and the callback
|
||||
that event runs aborts unless TryWaitNativeSync says reached: an event for a handle not reached is signalled at the
|
||||
next submission, not when it is requested (hos_video_sync_defer, from nn_syncpt.c). */
|
||||
#define SYNC_IDLE_TAG 0x5ec0000000000000ull
|
||||
#define SYNC_IDLE_MASK 0x0000ffffffffffffull
|
||||
int hos_video_sync_reached(uint64_t handle) { /* (nn_gs.c: TryWaitNativeSync, TimedWaitNativeSync) */
|
||||
if ((handle & ~SYNC_IDLE_MASK) != SYNC_IDLE_TAG) return 1;
|
||||
return (handle & SYNC_IDLE_MASK) != ((uint64_t)InterlockedCompareExchange64(&submissions, 0, 0) & SYNC_IDLE_MASK);
|
||||
}
|
||||
|
||||
static SRWLOCK waiter_lock = SRWLOCK_INIT;
|
||||
static uint64_t waiters[32]; /* sync point events (their guest addresses) waiting for the next submission */
|
||||
static int nwaiters;
|
||||
|
||||
/* RequestSyncPointEvent(event, handle): 1 when the event waits for the next submission, 0 when it is due now */
|
||||
int hos_video_sync_defer(uint64_t event, uint64_t handle) {
|
||||
AcquireSRWLockExclusive(&waiter_lock); /* (checked under the lock submitted() takes: no submission slips between) */
|
||||
int deferred = !hos_video_sync_reached(handle);
|
||||
if (deferred) {
|
||||
int i = 0;
|
||||
while (i < nwaiters && waiters[i] != event) i++;
|
||||
if (i == nwaiters && nwaiters < (int)(sizeof waiters / sizeof waiters[0])) waiters[nwaiters++] = event;
|
||||
else if (i == nwaiters) deferred = 0; /* (full: signalled now, as before) */
|
||||
}
|
||||
ReleaseSRWLockExclusive(&waiter_lock);
|
||||
return deferred;
|
||||
}
|
||||
|
||||
/* CancelSyncPointEvent(event) */
|
||||
void hos_video_sync_cancel(uint64_t event) {
|
||||
AcquireSRWLockExclusive(&waiter_lock);
|
||||
for (int i = 0; i < nwaiters; i++)
|
||||
if (waiters[i] == event) { waiters[i] = waiters[--nwaiters]; break; }
|
||||
ReleaseSRWLockExclusive(&waiter_lock);
|
||||
}
|
||||
|
||||
int hos_video_sync_waiting(uint64_t event) { /* TryWaitSyncPointEvent(event): 1 while it waits for a submission */
|
||||
AcquireSRWLockExclusive(&waiter_lock);
|
||||
int i = 0;
|
||||
while (i < nwaiters && waiters[i] != event) i++;
|
||||
const int waiting = i < nwaiters;
|
||||
ReleaseSRWLockExclusive(&waiter_lock);
|
||||
return waiting;
|
||||
}
|
||||
|
||||
void hos_system_event_signal(uint64_t key);
|
||||
static uint64_t submitted(void) { /* a submission: every handle given out before it is reached */
|
||||
uint64_t due[32];
|
||||
AcquireSRWLockExclusive(&waiter_lock);
|
||||
const uint64_t id = (uint64_t)InterlockedIncrement64(&submissions);
|
||||
const int n = nwaiters;
|
||||
memcpy(due, waiters, sizeof due);
|
||||
nwaiters = 0;
|
||||
ReleaseSRWLockExclusive(&waiter_lock);
|
||||
for (int i = 0; i < n; i++) hos_system_event_signal(due[i]);
|
||||
return id;
|
||||
}
|
||||
|
||||
static void dec_submit(Ctx *c) {
|
||||
Dec *d = (Dec *)host_of(ARG(1), DEC_MAGIC);
|
||||
const uint64_t id = submitted();
|
||||
if (ARG(0)) G64(ARG(0)) = id;
|
||||
if (!d || (!d->ctx && !d->mf)) { RET(0); return; }
|
||||
AcquireSRWLockExclusive(&d->lock);
|
||||
/* (hookshot) the size is 64-bit: one past what an AVPacket holds was cut to a small packet and copied in whole; and
|
||||
the data must lie in guest memory */
|
||||
const void *data = ARG(2) && ARG(3) && ARG(3) <= INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE ? hos_guest_range(ARG(2), ARG(3)) : NULL;
|
||||
if (ARG(2) && ARG(3) && !data) hos_log("video: submit of %#llx bytes at %#llx left out", (unsigned long long)ARG(3),
|
||||
(unsigned long long)ARG(2));
|
||||
if (data) {
|
||||
AVPacket *pkt = av_packet_alloc();
|
||||
if (pkt && av_new_packet(pkt, (int)ARG(3)) == 0) {
|
||||
memcpy(pkt->data, data, (size_t)ARG(3));
|
||||
pkt->pts = (int64_t)ARG(4);
|
||||
pending_push(d, pkt);
|
||||
} else {
|
||||
av_packet_free(&pkt);
|
||||
}
|
||||
}
|
||||
d->submits++;
|
||||
if (ARG(5) & 1) pending_push(d, NULL);
|
||||
const int logged_one = d->log_submits > 0;
|
||||
if (logged_one) d->log_submits--;
|
||||
if (video_log() && (d->submits <= 8 || (ARG(5) & 1) || logged_one))
|
||||
hos_log("video: submit %lld (%llu bytes, pts %lld%s)", (long long)d->submits, (unsigned long long)ARG(3),
|
||||
(long long)ARG(4), (ARG(5) & 1) ? ", last" : "");
|
||||
ReleaseSRWLockExclusive(&d->lock);
|
||||
RET(0);
|
||||
}
|
||||
static void dec_flush(Ctx *c, const char *what) {
|
||||
Dec *d = (Dec *)host_of(ARG(0), DEC_MAGIC);
|
||||
if (d && (d->ctx || d->mf)) {
|
||||
AcquireSRWLockExclusive(&d->lock);
|
||||
if (video_log())
|
||||
hos_log("video: %s after %lld submits and %lld acquires (%d queued, %s, lr %#llx)", what, (long long)d->submits,
|
||||
(long long)d->acquires, d->qn, d->eos ? "at the end" : d->phead ? "submissions left" : "none left",
|
||||
(unsigned long long)c->x[30]);
|
||||
d->log_submits = 8;
|
||||
if (d->ctx) avcodec_flush_buffers(d->ctx);
|
||||
else mf_av1_flush(d->mf);
|
||||
pending_free(d);
|
||||
for (int i = 0; i < d->qn; i++) picture_free(&d->queue[(d->qhead + i) % MAX_QUEUE]);
|
||||
d->qhead = d->qn = 0;
|
||||
d->eos = 0;
|
||||
d->clock_set = 0;
|
||||
for (int i = 0; i < MAX_SLOTS; i++) d->slot_last[i] = 0;
|
||||
ReleaseSRWLockExclusive(&d->lock);
|
||||
}
|
||||
RET(0);
|
||||
}
|
||||
/* RegisterXDecoderBuffer(decoder, u32 index, pool, u32 image) / UnregisterXDecoderBuffer(decoder, u32 index) */
|
||||
static void dec_register(Ctx *c) {
|
||||
Dec *d = (Dec *)host_of(ARG(0), DEC_MAGIC);
|
||||
if (d && (uint32_t)ARG(1) < MAX_SLOTS) d->slots[(uint32_t)ARG(1)] = ARG(2), d->busy[(uint32_t)ARG(1)] = 0;
|
||||
RET(0);
|
||||
}
|
||||
static void dec_unregister(Ctx *c) {
|
||||
Dec *d = (Dec *)host_of(ARG(0), DEC_MAGIC);
|
||||
if (d && (uint32_t)ARG(1) < MAX_SLOTS) d->slots[(uint32_t)ARG(1)] = 0;
|
||||
RET(0);
|
||||
}
|
||||
/* AcquireXDecoderOutputBuffer(u32* index, NativeSyncHandle*, decoder): the oldest picture into a free buffer */
|
||||
static void dec_acquire(Ctx *c) {
|
||||
Dec *d = (Dec *)host_of(ARG(2), DEC_MAGIC);
|
||||
if (ARG(1)) G64(ARG(1)) = 0;
|
||||
if (!d) { RET(RESULT_NO_OUTPUT); return; }
|
||||
/* (the library aborts on any failure here: the hardware call waits for a picture. Up to ~100 ms for one decoded
|
||||
by another thread's submission; then a free buffer as it was, so the caller is never refused) */
|
||||
AcquireSRWLockExclusive(&d->lock);
|
||||
decode_pending(d);
|
||||
for (int tries = 0; !d->qn && !d->eos && tries < 50; tries++) {
|
||||
ReleaseSRWLockExclusive(&d->lock);
|
||||
hos_sleep_ns(2000000);
|
||||
AcquireSRWLockExclusive(&d->lock);
|
||||
decode_pending(d);
|
||||
}
|
||||
int slot = -1;
|
||||
for (int i = 0; i < MAX_SLOTS && slot < 0; i++)
|
||||
if (d->slots[i] && !d->busy[i] && host_of(d->slots[i], POOL_MAGIC)) slot = i;
|
||||
if (slot < 0) {
|
||||
ReleaseSRWLockExclusive(&d->lock);
|
||||
RET(RESULT_NO_OUTPUT);
|
||||
return;
|
||||
}
|
||||
d->acquires++;
|
||||
if (!d->qn) { /* (nothing decoded: the buffer's last picture again; after the last submission, as the last) */
|
||||
d->busy[slot] = 1;
|
||||
if (d->eos) d->slot_last[slot] = 1, d->slot_pts[slot] = d->last_pts; /* (the end at the last picture's time) */
|
||||
const int idle = !d->eos && !d->phead; /* (nothing will come into this buffer: its sync is not reached) */
|
||||
if (idle && ARG(1))
|
||||
G64(ARG(1)) = SYNC_IDLE_TAG | ((uint64_t)InterlockedCompareExchange64(&submissions, 0, 0) & SYNC_IDLE_MASK);
|
||||
if (video_log()) hos_log("video: acquire %lld: nothing decoded%s, buffer %d again", (long long)d->acquires,
|
||||
d->eos ? " (the end)" : idle ? " (idle: its sync not reached)" : "", slot);
|
||||
else if (d->acquires == 1 && !d->eos) /* (the start: the frame shows the buffer as it was, black since the pool's fill) */
|
||||
hos_log("video: the first buffer went out before the first picture was decoded (shown black)");
|
||||
ReleaseSRWLockExclusive(&d->lock);
|
||||
if (ARG(0)) G32(ARG(0)) = (uint32_t)slot;
|
||||
RET(0);
|
||||
return;
|
||||
}
|
||||
{ /* (hookshot) The game takes one picture a frame, and the sound plays on: under 60 fps the movie fell behind its
|
||||
sound (the intro "slow motion, audio ahead", issues 146 and 179). Pictures behind the movie's clock are skipped:
|
||||
the next ones decoded, as the whole movie is submitted at once. HOS_VIDEO_NO_CATCHUP=1: as before */
|
||||
static int off = -1;
|
||||
if (off < 0) off = getenv("HOS_VIDEO_NO_CATCHUP") != NULL;
|
||||
const int64_t now = hos_now_ns(), late = 25000000; /* (a frame and a half at 60 fps) */
|
||||
Picture *h = &d->queue[d->qhead];
|
||||
if (!d->clock_set || h->pts < d->clock_pts) d->clock_set = 1, d->clock_ns = now, d->clock_pts = h->pts; /* (a start, a loop) */
|
||||
int skipped = 0;
|
||||
for (int guard = 0; !off && guard < 600 && !d->queue[d->qhead].last; guard++) {
|
||||
const int64_t due = d->clock_pts + (now - d->clock_ns);
|
||||
if (d->queue[d->qhead].pts + late >= due) break;
|
||||
if (d->qn < 2) {
|
||||
if (!d->phead) break;
|
||||
decode_next(d);
|
||||
continue;
|
||||
}
|
||||
picture_free(&d->queue[d->qhead]);
|
||||
d->qhead = (d->qhead + 1) % MAX_QUEUE, d->qn--;
|
||||
skipped++;
|
||||
}
|
||||
if (skipped && video_log()) hos_log("video: %d pictures skipped to catch up with the movie's clock", skipped);
|
||||
}
|
||||
Picture *p = &d->queue[d->qhead];
|
||||
Pool *o = (Pool *)host_of(d->slots[slot], POOL_MAGIC);
|
||||
/* (the picture at the pool's size: rows and columns past either are left out) */
|
||||
const int ok = o->nv12 != NULL && p->nv12 != NULL; /* (an allocation that failed: nothing copied; issue 342) */
|
||||
const int w = !ok ? 0 : p->w < o->w ? p->w : o->w, h = !ok ? 0 : p->h < o->h ? p->h : o->h;
|
||||
for (int y = 0; y < h; y++) {
|
||||
if (p->rgba && o->rgba) memcpy(o->rgba + (size_t)y * o->w * 4, p->rgba + (size_t)y * p->w * 4, (size_t)w * 4);
|
||||
memcpy(o->nv12 + (size_t)y * o->w, p->nv12 + (size_t)y * p->w, (size_t)w);
|
||||
}
|
||||
for (int y = 0; y < h / 2; y++)
|
||||
memcpy(o->nv12 + (size_t)o->w * o->h + (size_t)y * o->w, p->nv12 + (size_t)p->w * p->h + (size_t)y * p->w,
|
||||
(size_t)w);
|
||||
o->rgba_stale = !p->rgba;
|
||||
/* (hookshot) and into the pool's guest memory, as the hardware decoder leaves it (NV12, pitch = width, chroma right
|
||||
after the luma rows; RGBA when the memory has room for it and the pool's format is not NV12's). Not once the
|
||||
game reads the pool through ReadDecoderOutputImageNv12 / Rgba, as OoT's movie library does: its pools are
|
||||
format 3, so each 1080p picture was made RGBA and copied there for nothing (the movie is the same without it) */
|
||||
if (o->mem && o->mem_size && !o->read_by_api) {
|
||||
const size_t nv12_size = (size_t)o->w * o->h * 3 / 2, rgba_size = (size_t)o->w * o->h * 4;
|
||||
const int rgba = o->format != 0 && o->mem_size >= rgba_size; /* (VideoDecoderOutputFormat 0: NV12) */
|
||||
const size_t need = rgba ? rgba_size : nv12_size;
|
||||
void *to = hos_guest_range(o->mem, need); /* (hookshot: only into guest memory) */
|
||||
if (o->mem_size >= need && ok && to && (rgba ? o->rgba != NULL : 1)) {
|
||||
if (rgba && o->rgba_stale) pool_rgba(o);
|
||||
memcpy(to, rgba ? o->rgba : o->nv12, need);
|
||||
HOS_WRITTEN(to, need);
|
||||
}
|
||||
}
|
||||
d->slot_pts[slot] = d->last_pts = p->pts;
|
||||
d->slot_last[slot] = p->last;
|
||||
d->busy[slot] = 1;
|
||||
{ /* (hookshot) HOS_VIDEO_LOG: the picture's time against this decoder's movie clock, to see it fall behind the sound */
|
||||
if (video_log() && d->acquires % 60 == 0) {
|
||||
const int64_t now = hos_now_ns();
|
||||
hos_log("video: acquire %lld: picture at %.2f s, wall clock %.2f s (behind by %.2f s), %d decoded ahead", (long long)d->acquires,
|
||||
(double)(p->pts - d->clock_pts) / 1e9, (double)(now - d->clock_ns) / 1e9,
|
||||
(double)(now - d->clock_ns - (p->pts - d->clock_pts)) / 1e9, d->qn);
|
||||
}
|
||||
}
|
||||
if (video_log() && (d->acquires <= 8 || p->last || d->acquires % 300 == 0)) {
|
||||
uint64_t sum = 0, n = 0; /* (the picture's mean luma and RGB, sampled: a black or garbage decode shows) */
|
||||
uint64_t rgb[3] = {0, 0, 0};
|
||||
for (int y = 0; y < p->h; y += 37)
|
||||
for (int x = 0; x < p->w; x += 41, n++) {
|
||||
sum += p->nv12[(size_t)y * p->w + x];
|
||||
for (int k = 0; k < 3 && p->rgba; k++) rgb[k] += p->rgba[((size_t)y * p->w + x) * 4 + k];
|
||||
}
|
||||
hos_log("video: acquire %lld: %dx%d pts %lld%s into buffer %d (mean Y %llu, RGB %llu %llu %llu)",
|
||||
(long long)d->acquires, p->w, p->h, (long long)p->pts, p->last ? " (last)" : "", slot,
|
||||
(unsigned long long)(n ? sum / n : 0), (unsigned long long)(n ? rgb[0] / n : 0),
|
||||
(unsigned long long)(n ? rgb[1] / n : 0), (unsigned long long)(n ? rgb[2] / n : 0));
|
||||
}
|
||||
picture_free(p);
|
||||
d->qhead = (d->qhead + 1) % MAX_QUEUE, d->qn--;
|
||||
ReleaseSRWLockExclusive(&d->lock);
|
||||
if (ARG(0)) G32(ARG(0)) = (uint32_t)slot;
|
||||
RET(0);
|
||||
}
|
||||
/* ReleaseXDecoderOutputBuffer(decoder, u32 index, NativeSyncHandle) */
|
||||
static void dec_release(Ctx *c) {
|
||||
Dec *d = (Dec *)host_of(ARG(0), DEC_MAGIC);
|
||||
if (d && (uint32_t)ARG(1) < MAX_SLOTS) d->busy[(uint32_t)ARG(1)] = 0;
|
||||
RET(0);
|
||||
}
|
||||
/* GetXDecoderOutputBufferProperties(u16* w, u16* h, u16* display w, u16* display h, TimeSpan* pts, bool* last,
|
||||
decoder, u32 index) */
|
||||
static void dec_properties(Ctx *c) {
|
||||
Dec *d = (Dec *)host_of(ARG(6), DEC_MAGIC);
|
||||
const uint32_t i = (uint32_t)ARG(7);
|
||||
const Pool *o = d && i < MAX_SLOTS ? (const Pool *)host_of(d->slots[i], POOL_MAGIC) : NULL;
|
||||
const uint16_t w = o ? (uint16_t)o->w : 0, h = o ? (uint16_t)o->h : 0;
|
||||
if (ARG(0)) *(uint16_t *)GP(ARG(0)) = w;
|
||||
if (ARG(1)) *(uint16_t *)GP(ARG(1)) = h;
|
||||
if (ARG(2)) *(uint16_t *)GP(ARG(2)) = w;
|
||||
if (ARG(3)) *(uint16_t *)GP(ARG(3)) = h;
|
||||
if (ARG(4)) G64(ARG(4)) = d && i < MAX_SLOTS ? (uint64_t)d->slot_pts[i] : 0;
|
||||
if (ARG(5)) *(uint8_t *)GP(ARG(5)) = d && i < MAX_SLOTS ? (uint8_t)d->slot_last[i] : 0;
|
||||
{ /* (HOS_VIDEO_LOG) the first times the game is told a picture is the last */
|
||||
static volatile LONG n;
|
||||
if (video_log() && d && i < MAX_SLOTS && d->slot_last[i] && InterlockedIncrement(&n) <= 8)
|
||||
hos_log("video: properties of buffer %u: the last picture, pts %lld (lr %#llx)", i, (long long)d->slot_pts[i],
|
||||
(unsigned long long)c->x[30]);
|
||||
}
|
||||
RET(0);
|
||||
}
|
||||
static uint64_t ready_event(void) {
|
||||
static uint64_t event;
|
||||
if (!event) {
|
||||
event = hos_sys_alloc(0x40, 16);
|
||||
hos_system_event_init(event, 0);
|
||||
hos_system_event_signal(event);
|
||||
}
|
||||
return event;
|
||||
}
|
||||
|
||||
/* VP9 */
|
||||
HLE(_ZN2nn5codec36InitializeVp9DecoderByTransferMemoryEPNS0_14Vp9DecoderTypeEPvmmttjNS0_23VideoDecoderInputFormatENS0_24VideoDecoderOutputFormatENS0_22VideoDecoderOutputModeE) { dec_init(c, AV_CODEC_ID_VP9, "VP9"); }
|
||||
HLE(_ZN2nn5codec34InitializeVp9DecoderByRemoteMemoryEPNS0_14Vp9DecoderTypeEmttjNS0_23VideoDecoderInputFormatENS0_24VideoDecoderOutputFormatENS0_22VideoDecoderOutputModeE) { dec_init(c, AV_CODEC_ID_VP9, "VP9"); }
|
||||
HLE(_ZN2nn5codec18FinalizeVp9DecoderEPNS0_14Vp9DecoderTypeE) { dec_finalize(c); }
|
||||
HLE(_ZN2nn5codec24RegisterVp9DecoderBufferEPNS0_14Vp9DecoderTypeEjPNS0_25VideoDecoderImagePoolTypeEj) { dec_register(c); }
|
||||
HLE(_ZN2nn5codec26UnregisterVp9DecoderBufferEPNS0_14Vp9DecoderTypeEj) { dec_unregister(c); }
|
||||
HLE(_ZN2nn5codec15StartVp9DecoderEPNS0_14Vp9DecoderTypeE) { RET(0); }
|
||||
HLE(_ZN2nn5codec14StopVp9DecoderEPNS0_14Vp9DecoderTypeE) { dec_flush(c, "Stop"); }
|
||||
HLE(_ZN2nn5codec15FlushVp9DecoderEPNS0_14Vp9DecoderTypeE) { dec_flush(c, "Flush"); }
|
||||
HLE(_ZN2nn5codec33GetVp9DecoderSubmissionReadyEventEPNS0_14Vp9DecoderTypeE) { RET(ready_event()); }
|
||||
HLE(_ZN2nn5codec27SubmitVp9DecoderInputBufferEPmPNS0_14Vp9DecoderTypeEPKvmNS_8TimeSpanEb) { dec_submit(c); }
|
||||
HLE(_ZN2nn5codec36SubmitEncryptedVp9DecoderInputBufferEPmPNS0_14Vp9DecoderTypeEPKNS0_18EncryptionPropertyEPKvmNS_8TimeSpanEb) {
|
||||
const uint64_t id = submitted();
|
||||
if (ARG(0)) G64(ARG(0)) = id;
|
||||
RET(0);
|
||||
}
|
||||
HLE(_ZN2nn5codec29AcquireVp9DecoderOutputBufferEPjPNS_2gs16NativeSyncHandleEPNS0_14Vp9DecoderTypeE) { dec_acquire(c); }
|
||||
HLE(_ZN2nn5codec29ReleaseVp9DecoderOutputBufferEPNS0_14Vp9DecoderTypeEjNS_2gs16NativeSyncHandleE) { dec_release(c); }
|
||||
HLE(_ZN2nn5codec35GetVp9DecoderOutputBufferPropertiesEPtS1_S1_S1_PNS_8TimeSpanEPbPNS0_14Vp9DecoderTypeEj) { dec_properties(c); }
|
||||
|
||||
/* (hookshot) AV1: OoT's movies. FFmpeg's AV1 decoder if the build has one, else Media Foundation (host/mf_av1.c).
|
||||
Initialize...ByTransferMemory(decoder, memory, size, ?, u16 width, u16 height, ...), ...ByRemoteMemory(decoder,
|
||||
size, u16 width, u16 height, ...) */
|
||||
HLE(_ZN2nn5codec36InitializeAv1DecoderByTransferMemoryEPNS0_14Av1DecoderTypeEPvmmttjNS0_23VideoDecoderInputFormatENS0_24VideoDecoderOutputFormatENS0_22VideoDecoderOutputModeE) {
|
||||
dec_init_sized(c, AV_CODEC_ID_AV1, "AV1", (int)(uint16_t)ARG(4), (int)(uint16_t)ARG(5));
|
||||
}
|
||||
HLE(_ZN2nn5codec34InitializeAv1DecoderByRemoteMemoryEPNS0_14Av1DecoderTypeEmttjNS0_23VideoDecoderInputFormatENS0_24VideoDecoderOutputFormatENS0_22VideoDecoderOutputModeE) {
|
||||
dec_init_sized(c, AV_CODEC_ID_AV1, "AV1", (int)(uint16_t)ARG(2), (int)(uint16_t)ARG(3));
|
||||
}
|
||||
HLE(_ZN2nn5codec18FinalizeAv1DecoderEPNS0_14Av1DecoderTypeE) { dec_finalize(c); }
|
||||
HLE(_ZN2nn5codec24RegisterAv1DecoderBufferEPNS0_14Av1DecoderTypeEjPNS0_25VideoDecoderImagePoolTypeEj) { dec_register(c); }
|
||||
HLE(_ZN2nn5codec15StartAv1DecoderEPNS0_14Av1DecoderTypeE) { RET(0); }
|
||||
HLE(_ZN2nn5codec14StopAv1DecoderEPNS0_14Av1DecoderTypeE) { dec_flush(c, "Stop"); }
|
||||
HLE(_ZN2nn5codec15FlushAv1DecoderEPNS0_14Av1DecoderTypeE) { dec_flush(c, "Flush"); }
|
||||
HLE(_ZN2nn5codec33GetAv1DecoderSubmissionReadyEventEPNS0_14Av1DecoderTypeE) { RET(ready_event()); }
|
||||
HLE(_ZN2nn5codec27SubmitAv1DecoderInputBufferEPmPNS0_14Av1DecoderTypeEPKvmNS_8TimeSpanEb) { dec_submit(c); }
|
||||
HLE(_ZN2nn5codec29AcquireAv1DecoderOutputBufferEPjPNS_2gs16NativeSyncHandleEPNS0_14Av1DecoderTypeE) { dec_acquire(c); }
|
||||
HLE(_ZN2nn5codec29ReleaseAv1DecoderOutputBufferEPNS0_14Av1DecoderTypeEjNS_2gs16NativeSyncHandleE) { dec_release(c); }
|
||||
HLE(_ZN2nn5codec35GetAv1DecoderOutputBufferPropertiesEPtS1_S1_S1_PNS_8TimeSpanEPbPNS0_14Av1DecoderTypeEj) { dec_properties(c); }
|
||||
|
||||
/* VP8 */
|
||||
HLE(_ZN2nn5codec36InitializeVp8DecoderByTransferMemoryEPNS0_14Vp8DecoderTypeEPvmmttjNS0_23VideoDecoderInputFormatENS0_24VideoDecoderOutputFormatENS0_22VideoDecoderOutputModeE) { dec_init(c, AV_CODEC_ID_VP8, "VP8"); }
|
||||
HLE(_ZN2nn5codec34InitializeVp8DecoderByRemoteMemoryEPNS0_14Vp8DecoderTypeEmttjNS0_23VideoDecoderInputFormatENS0_24VideoDecoderOutputFormatENS0_22VideoDecoderOutputModeE) { dec_init(c, AV_CODEC_ID_VP8, "VP8"); }
|
||||
HLE(_ZN2nn5codec18FinalizeVp8DecoderEPNS0_14Vp8DecoderTypeE) { dec_finalize(c); }
|
||||
HLE(_ZN2nn5codec24RegisterVp8DecoderBufferEPNS0_14Vp8DecoderTypeEjPNS0_25VideoDecoderImagePoolTypeEj) { dec_register(c); }
|
||||
HLE(_ZN2nn5codec26UnregisterVp8DecoderBufferEPNS0_14Vp8DecoderTypeEj) { dec_unregister(c); }
|
||||
HLE(_ZN2nn5codec15StartVp8DecoderEPNS0_14Vp8DecoderTypeE) { RET(0); }
|
||||
HLE(_ZN2nn5codec14StopVp8DecoderEPNS0_14Vp8DecoderTypeE) { dec_flush(c, "Stop"); }
|
||||
HLE(_ZN2nn5codec15FlushVp8DecoderEPNS0_14Vp8DecoderTypeE) { dec_flush(c, "Flush"); }
|
||||
HLE(_ZN2nn5codec33GetVp8DecoderSubmissionReadyEventEPNS0_14Vp8DecoderTypeE) { RET(ready_event()); }
|
||||
HLE(_ZN2nn5codec27SubmitVp8DecoderInputBufferEPmPNS0_14Vp8DecoderTypeEPKvmNS_8TimeSpanEb) { dec_submit(c); }
|
||||
HLE(_ZN2nn5codec29AcquireVp8DecoderOutputBufferEPjPNS_2gs16NativeSyncHandleEPNS0_14Vp8DecoderTypeE) { dec_acquire(c); }
|
||||
HLE(_ZN2nn5codec29ReleaseVp8DecoderOutputBufferEPNS0_14Vp8DecoderTypeEjNS_2gs16NativeSyncHandleE) { dec_release(c); }
|
||||
HLE(_ZN2nn5codec35GetVp8DecoderOutputBufferPropertiesEPtS1_S1_S1_PNS_8TimeSpanEPbPNS0_14Vp8DecoderTypeEj) { dec_properties(c); }
|
||||
662
host/nvdrv.c
Normal file
662
host/nvdrv.c
Normal file
@@ -0,0 +1,662 @@
|
||||
/* nvdrv: NVIDIA's kernel-driver interface, below the real NVN driver.
|
||||
|
||||
The NVN driver and NVIDIA's resource manager (NvRm*) are lifted SDK code and run unchanged. They reach the GPU only
|
||||
through the exported NvOs layer: NvOsDrvOpen / NvOsDrvIoctl{,2,3} / NvOsDrvClose / NvOsDrvMapSharedMem /
|
||||
NvOsDrvQueryEvent, which on hardware talk to the nvdrv service. Those are hooked here and emulate the devices:
|
||||
|
||||
/dev/nvmap memory handles; the backing memory is the game's own (guest addresses)
|
||||
/dev/nvhost-as-gpu the GPU's virtual address space: GPU VA -> guest address mappings
|
||||
/dev/nvhost-gpu channels: GPFIFO submissions run on the GPU (hos/gpu.c) as they are made, so a
|
||||
submission's fence has passed by the time the ioctl returns
|
||||
/dev/nvhost-ctrl sync points and their events
|
||||
/dev/nvhost-ctrl-gpu Tegra X1 (GM20B) characteristics, zcull/zbc, TPC masks, GPU time
|
||||
|
||||
Ioctl numbers are Linux-style: nr bits 0-7, group 8-15, size 16-29, direction 30-31. Structures and values follow
|
||||
suyu's nvdrv (src/core/hle/service/nvdrv, GPL-2.0-or-later) and switchbrew "NV services". */
|
||||
#include "hos.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
|
||||
void hos_system_event_init(uint64_t key, int autoclear);
|
||||
void hos_system_event_signal(uint64_t key);
|
||||
|
||||
enum { NV_OK = 0, NV_NOT_IMPLEMENTED = 1, NV_NOT_SUPPORTED = 2, NV_BAD_PARAMETER = 4, NV_TIMEOUT = 5,
|
||||
NV_INSUFFICIENT_MEMORY = 6, NV_BAD_VALUE = 0xB, NV_CONFIG_NOT_FOUND = 0x30006 };
|
||||
enum { DEV_NONE, DEV_NVMAP, DEV_AS_GPU, DEV_GPU, DEV_CTRL, DEV_CTRL_GPU, DEV_OTHER };
|
||||
|
||||
static SRWLOCK lock = SRWLOCK_INIT;
|
||||
#define LOCK() AcquireSRWLockExclusive(&lock)
|
||||
#define UNLOCK() ReleaseSRWLockExclusive(&lock)
|
||||
|
||||
/* ---- file descriptors ---------------------------------------------------------------------------------------- */
|
||||
typedef struct { int type; char path[48]; int syncpt; } Fd; /* syncpt: a channel's sync point */
|
||||
static Fd fds[256];
|
||||
|
||||
static const struct { const char *path; int type; } devices[] = {
|
||||
{"/dev/nvmap", DEV_NVMAP}, {"/dev/nvhost-as-gpu", DEV_AS_GPU}, {"/dev/nvhost-gpu", DEV_GPU},
|
||||
{"/dev/nvhost-ctrl", DEV_CTRL}, {"/dev/nvhost-ctrl-gpu", DEV_CTRL_GPU}, {"/dev/nvhost-nvdec", DEV_OTHER},
|
||||
{"/dev/nvhost-vic", DEV_OTHER}, {"/dev/nvhost-nvjpg", DEV_OTHER}, {"/dev/nvdisp-disp0", DEV_OTHER},
|
||||
{"/dev/nvdisp-disp1", DEV_OTHER}, {"/dev/nvhost-display", DEV_OTHER}, {"/dev/nvhost-prof-gpu", DEV_OTHER},
|
||||
{"/dev/nvhost-dbg-gpu", DEV_OTHER}, {"/dev/nvsched-ctrl", DEV_OTHER}};
|
||||
|
||||
/* ---- sync points: 192 counters. syncpt is the value the GPU reached, syncpt_max the value the work submitted so far
|
||||
will reach (the fences handed out). With the GPU thread (default; HOS_GPU_SYNC=1: synchronous, they move together)
|
||||
submissions run on it (hos/gpu.c) and sync points advance when they finish; waits block, and events are signalled
|
||||
then. ------------------------------------------------------------------------------------------------------- */
|
||||
#define SYNCPTS 192
|
||||
static volatile uint32_t syncpt[SYNCPTS], syncpt_max[SYNCPTS];
|
||||
static SRWLOCK sync_lock = SRWLOCK_INIT;
|
||||
static CONDITION_VARIABLE sync_cv = CONDITION_VARIABLE_INIT;
|
||||
int hos_gpu_async(void); /* gpu.c */
|
||||
static uint64_t ctrl_events[64]; /* user event id -> the SystemEventType the game queried for it */
|
||||
static uint8_t ctrl_early[64]; /* a fence on that event passed before the game queried the event: signal it then */
|
||||
/* event waits that had not passed: signal the slot's event when the sync point reaches the value */
|
||||
static struct { int used; uint32_t slot, id, value; } pending[512];
|
||||
static int sync_trace = -1; /* HOS_SYNC_TRACE=1: log fences and sync point waits */
|
||||
#define SYNC_LOG(...) do { if (sync_trace < 0) sync_trace = getenv("HOS_SYNC_TRACE") != NULL; if (sync_trace) hos_log(__VA_ARGS__); } while (0)
|
||||
static int next_syncpt = 24; /* low ids belong to the system */
|
||||
|
||||
/* ---- nvmap handles ---------------------------------------------------------------------------------------------- */
|
||||
typedef struct { uint32_t size, align, flags, kind, id; uint64_t address; int used, allocated; } Handle;
|
||||
static Handle handles[8192];
|
||||
static uint32_t next_id = 1;
|
||||
|
||||
static Handle *handle(uint32_t h) { return h && h < 8192 && handles[h].used ? &handles[h] : NULL; }
|
||||
/* Guest address of an nvmap handle's memory (0 if none): the display reads window buffers through it. */
|
||||
uint64_t hos_nvmap_address(uint32_t h) { Handle *x = handle(h); return x ? x->address : 0; }
|
||||
|
||||
/* ---- the GPU address space: mappings GPU VA -> guest address, sorted by VA ------------------------------------ */
|
||||
typedef struct { uint64_t va, size, guest; } Map;
|
||||
static Map *maps;
|
||||
static int nmaps, capmaps;
|
||||
static uint64_t va_next = 0x400000000ULL, va_end = 1ULL << 40; /* 40-bit GPU VA, as GM20B reports */
|
||||
|
||||
static int map_trace = -1; /* HOS_MAP_TRACE=1: log every GPU mapping change */
|
||||
#define MAP_LOG(...) do { if (map_trace < 0) map_trace = getenv("HOS_MAP_TRACE") != NULL; if (map_trace) hos_log(__VA_ARGS__); } while (0)
|
||||
|
||||
/* index of the last mapping starting at or below va, or -1 */
|
||||
static int map_floor(uint64_t va) {
|
||||
int lo = 0, hi = nmaps - 1;
|
||||
while (lo <= hi) {
|
||||
int mid = (lo + hi) / 2;
|
||||
if (maps[mid].va <= va) lo = mid + 1;
|
||||
else hi = mid - 1;
|
||||
}
|
||||
return hi;
|
||||
}
|
||||
/* a new mapping replaces whatever started inside its range (a remap of the same VA, sparse rebinding) */
|
||||
static volatile LONG maps_changed = 1; /* the mappings changed since hos_gpu_guest_ranges last merged them */
|
||||
volatile LONG maps_generation = 1; /* bumped by every change (hos_gpu_ptr's per-thread cache, the renderer's gpu_read) */
|
||||
static void map_add(uint64_t va, uint64_t size, uint64_t guest) {
|
||||
maps_changed = 1;
|
||||
InterlockedIncrement(&maps_generation);
|
||||
MAP_LOG("nvdrv: map GPU %#llx..%#llx -> %#llx", (unsigned long long)va, (unsigned long long)(va + size),
|
||||
(unsigned long long)guest);
|
||||
int i = map_floor(va);
|
||||
if (i >= 0 && maps[i].va == va) { maps[i].size = size; maps[i].guest = guest; return; }
|
||||
int at = i + 1, end = at;
|
||||
while (end < nmaps && maps[end].va < va + size) end++;
|
||||
if (end > at) { memmove(&maps[at], &maps[end], (nmaps - end) * sizeof *maps); nmaps -= end - at; }
|
||||
if (nmaps == capmaps) {
|
||||
capmaps = capmaps ? capmaps * 2 : 256;
|
||||
maps = (Map *)realloc(maps, capmaps * sizeof *maps);
|
||||
}
|
||||
memmove(&maps[at + 1], &maps[at], (nmaps - at) * sizeof *maps);
|
||||
maps[at] = (Map){va, size, guest};
|
||||
nmaps++;
|
||||
}
|
||||
static void map_remove(uint64_t va) {
|
||||
maps_changed = 1;
|
||||
InterlockedIncrement(&maps_generation);
|
||||
MAP_LOG("nvdrv: unmap GPU %#llx", (unsigned long long)va);
|
||||
int i = map_floor(va);
|
||||
if (i >= 0 && maps[i].va == va) { memmove(&maps[i], &maps[i + 1], (nmaps - i - 1) * sizeof *maps); nmaps--; }
|
||||
}
|
||||
static uint64_t va_alloc(uint64_t size, uint64_t align) {
|
||||
if (align < 0x10000) align = 0x10000;
|
||||
uint64_t va = (va_next + align - 1) & ~(align - 1);
|
||||
va_next = va + ((size + 0xFFFF) & ~0xFFFFULL);
|
||||
return va;
|
||||
}
|
||||
|
||||
/* (mkw-recomp) The memory pools one by one, as {guest start, size} pairs (at most max; the count is returned), and a
|
||||
number that changes with them: the Vulkan back end imports each pool as host memory (gpu/vk/vk_memory.cpp) */
|
||||
int hos_gpu_pools(uint64_t (*out)[2], int max) {
|
||||
LOCK();
|
||||
int n = 0;
|
||||
for (int i = 0; i < nmaps && n < max; i++)
|
||||
if (maps[i].va == maps[i].guest) out[n][0] = maps[i].guest, out[n][1] = maps[i].size, n++;
|
||||
UNLOCK();
|
||||
return n;
|
||||
}
|
||||
uint32_t hos_gpu_maps_generation(void) { return (uint32_t)maps_generation; }
|
||||
|
||||
/* The native NVN layer's memory pools (GPU address = guest address): mapped here only for the renderer's change
|
||||
tracking (hos_gpu_ptr resolves native addresses itself) */
|
||||
/* (and, for the change tracking, a list of their own counted by range: in the GPU mappings, keyed by start, a pool made
|
||||
over another's memory replaced its entry or dropped the ones inside it, and the old pool's finalize then removed the
|
||||
new one's. The CPU's writes to such a pool were never collected again: MK World's font cache kept the glyphs it had
|
||||
first, the menus lost letters. The mappings stay as they were for the pools' imports, hos_gpu_pools) */
|
||||
typedef struct { uint64_t lo, hi; int n; } Tracked;
|
||||
static Tracked *tracked;
|
||||
static int ntracked, captracked;
|
||||
void hos_gpu_track(uint64_t guest, uint64_t size, int on) {
|
||||
const uint64_t lo = guest & ~0xFFFULL, hi = (guest + size + 0xFFF) & ~0xFFFULL;
|
||||
LOCK();
|
||||
if (on) map_add(guest, size, guest);
|
||||
else map_remove(guest);
|
||||
int i = 0;
|
||||
while (i < ntracked && (tracked[i].lo != lo || tracked[i].hi != hi)) i++;
|
||||
if (on) {
|
||||
if (i < ntracked) tracked[i].n++;
|
||||
else {
|
||||
if (ntracked == captracked) {
|
||||
captracked = captracked ? captracked * 2 : 256;
|
||||
tracked = (Tracked *)realloc(tracked, (size_t)captracked * sizeof *tracked);
|
||||
}
|
||||
tracked[ntracked++] = (Tracked){lo, hi, 1};
|
||||
}
|
||||
} else if (i < ntracked && --tracked[i].n <= 0) {
|
||||
tracked[i] = tracked[--ntracked];
|
||||
}
|
||||
maps_changed = 1;
|
||||
InterlockedIncrement(&maps_generation);
|
||||
UNLOCK();
|
||||
}
|
||||
|
||||
/* The guest memory the GPU can reach (every mapping's guest range, merged, page aligned), for the renderer's change
|
||||
tracking: GetWriteWatch over the whole guest arena cost ~2.5 ms a call, and the GPU only reads these. Returns
|
||||
the number of ranges (at most max) written to out as {start, end} pairs. */
|
||||
static int cmp_range(const void *a, const void *b) {
|
||||
const uint64_t x = ((const uint64_t *)a)[0], y = ((const uint64_t *)b)[0];
|
||||
return x < y ? -1 : x > y;
|
||||
}
|
||||
int hos_gpu_guest_ranges(uint64_t (*out)[2], int max) {
|
||||
static uint64_t (*merged)[2];
|
||||
static int nmerged, capmerged;
|
||||
LOCK();
|
||||
if (maps_changed) {
|
||||
maps_changed = 0;
|
||||
const int nall = nmaps + ntracked; /* (the GPU mappings and the native NVN pools) */
|
||||
if (capmerged < nall) {
|
||||
capmerged = nall + 64;
|
||||
merged = (uint64_t (*)[2])realloc(merged, (size_t)capmerged * sizeof *merged);
|
||||
}
|
||||
for (int i = 0; i < nmaps; i++) {
|
||||
merged[i][0] = maps[i].guest & ~0xFFFULL;
|
||||
merged[i][1] = (maps[i].guest + maps[i].size + 0xFFF) & ~0xFFFULL;
|
||||
}
|
||||
for (int i = 0; i < ntracked; i++) merged[nmaps + i][0] = tracked[i].lo, merged[nmaps + i][1] = tracked[i].hi;
|
||||
qsort(merged, (size_t)nall, sizeof *merged, cmp_range);
|
||||
nmerged = 0;
|
||||
/* ranges less than 16 MB apart are one: a GetWriteWatch call costs about what 16 MB of range does, and
|
||||
TOTK maps ~4000 pieces */
|
||||
for (int i = 0; i < nall; i++) {
|
||||
if (nmerged && merged[i][0] <= merged[nmerged - 1][1] + (16ULL << 20)) {
|
||||
if (merged[i][1] > merged[nmerged - 1][1]) merged[nmerged - 1][1] = merged[i][1];
|
||||
} else {
|
||||
merged[nmerged][0] = merged[i][0];
|
||||
merged[nmerged][1] = merged[i][1];
|
||||
nmerged++;
|
||||
}
|
||||
}
|
||||
}
|
||||
int n = nmerged < max ? nmerged : max;
|
||||
memcpy(out, merged, (size_t)n * sizeof *merged);
|
||||
UNLOCK();
|
||||
return n;
|
||||
}
|
||||
|
||||
/* GPU VA -> guest address. Returns 0 if unmapped. */
|
||||
uint8_t *hos_gpu_ptr(uint64_t va, uint64_t *avail);
|
||||
uint64_t nvn_gpu_guest(uint64_t gpu);
|
||||
int nvn_native_on(void);
|
||||
uint64_t hos_guest_size(void);
|
||||
uint64_t hos_gpu_translate(uint64_t va) {
|
||||
static int native = -1;
|
||||
if (native < 0) native = nvn_native_on();
|
||||
if (native) { /* (no contiguity asked: the guest address alone) */
|
||||
const uint64_t g = nvn_gpu_guest(va);
|
||||
return g < hos_guest_size() ? g : 0;
|
||||
}
|
||||
uint64_t avail;
|
||||
uint8_t *p = hos_gpu_ptr(va, &avail);
|
||||
/* (unsigned: a pointer difference is 32-bit and signed in wasm, where the guest window passes 2 GB) */
|
||||
return p ? (uint64_t)((uintptr_t)p - (uintptr_t)GP(0)) : 0;
|
||||
}
|
||||
/* GPU VA -> host pointer, and how many bytes from there stay inside the mapping. NULL if unmapped. The renderer and
|
||||
the command processor ask tens of thousands of times a frame, nearly always for a mapping they just used: each
|
||||
thread keeps its last few mappings, good while no mapping changed. */
|
||||
uint64_t hos_guest_size(void);
|
||||
int nvn_native_on(void); /* hos/nvn_native.c */
|
||||
uint64_t nvn_gpu_guest(uint64_t gpu);
|
||||
uint64_t nvn_gpu_contiguous(uint64_t gpu, uint64_t n);
|
||||
uint8_t *hos_gpu_ptr(uint64_t va, uint64_t *avail) {
|
||||
/* the native NVN layer (HOS_NVN_NATIVE=1): a GPU address is the guest address (virtual pools: through their page
|
||||
tables), with no GPU address space of its own */
|
||||
static int native = -1;
|
||||
if (native < 0) native = nvn_native_on();
|
||||
if (native) {
|
||||
const uint64_t g = nvn_gpu_guest(va);
|
||||
if (!g || g >= hos_guest_size()) return NULL;
|
||||
*avail = va < hos_guest_size() ? hos_guest_size() - g : nvn_gpu_contiguous(va, 1ull << 30); /* (mkw-recomp: the
|
||||
identity range is the whole 512 GB window) */
|
||||
return (uint8_t *)GP(g);
|
||||
}
|
||||
/* direct-mapped by 64 KB page (a draw touches more mappings than a short list holds: constant buffers in several
|
||||
pools, the header pools, vertex data; a miss is a locked search over ~4000 mappings) */
|
||||
static _Thread_local struct { uint64_t lo, hi, guest; LONG generation; } recent[1024];
|
||||
const LONG generation = maps_generation;
|
||||
const unsigned k = (unsigned)(va >> 16) & 1023;
|
||||
if (recent[k].generation == generation && va >= recent[k].lo && va < recent[k].hi) { /* (most calls) */
|
||||
*avail = recent[k].hi - va;
|
||||
return (uint8_t *)GP(recent[k].guest + (va - recent[k].lo));
|
||||
}
|
||||
AcquireSRWLockShared(&lock);
|
||||
int i = map_floor(va);
|
||||
uint8_t *p = NULL;
|
||||
if (i >= 0 && va < maps[i].va + maps[i].size) {
|
||||
*avail = maps[i].va + maps[i].size - va;
|
||||
p = (uint8_t *)GP(maps[i].guest + (va - maps[i].va));
|
||||
recent[k].lo = maps[i].va;
|
||||
recent[k].hi = maps[i].va + maps[i].size;
|
||||
recent[k].guest = maps[i].guest;
|
||||
recent[k].generation = generation;
|
||||
}
|
||||
ReleaseSRWLockShared(&lock);
|
||||
return p;
|
||||
}
|
||||
|
||||
/* The GPU (hos/gpu.c) executes every GPFIFO submission: entries are { u64: GPU VA of a command list (bits 0-39),
|
||||
words (42-62) }. */
|
||||
void hos_gpu_submit(int channel_fd, const uint64_t *entries, uint32_t n);
|
||||
/* the same on the GPU thread (HOS_GPU_ASYNC): then two increments of sync point incr_id (unless -1) */
|
||||
void hos_gpu_queue_submit(int channel_fd, const uint64_t *entries, uint32_t n, int incr_id);
|
||||
void hos_gpu_syncpt_incr(uint32_t id) {
|
||||
id %= SYNCPTS;
|
||||
AcquireSRWLockExclusive(&sync_lock);
|
||||
uint32_t v = InterlockedIncrement((volatile LONG *)&syncpt[id]);
|
||||
if ((int32_t)(syncpt_max[id] - v) < 0) syncpt_max[id] = v; /* increments the kernel did not hand out */
|
||||
for (int i = 0; i < 512; i++)
|
||||
if (pending[i].used && pending[i].id == id && (int32_t)(v - pending[i].value) >= 0) {
|
||||
pending[i].used = 0;
|
||||
/* (the driver may register a wait before it queries the event: the signal must not be lost, or it
|
||||
waits forever: the rare stall while loading) */
|
||||
if (ctrl_events[pending[i].slot & 63]) hos_system_event_signal(ctrl_events[pending[i].slot & 63]);
|
||||
else ctrl_early[pending[i].slot & 63] = 1;
|
||||
}
|
||||
ReleaseSRWLockExclusive(&sync_lock);
|
||||
WakeAllConditionVariable(&sync_cv);
|
||||
}
|
||||
|
||||
/* Blocks until sync point id reaches value or timeout_ms passes (-1: forever). 1 when it did. */
|
||||
static int syncpt_wait(uint32_t id, uint32_t value, int32_t timeout_ms) {
|
||||
id %= SYNCPTS;
|
||||
int64_t end = timeout_ms < 0 ? INT64_MAX : hos_now_ns() + (int64_t)timeout_ms * 1000000;
|
||||
AcquireSRWLockExclusive(&sync_lock);
|
||||
for (;;) {
|
||||
if ((int32_t)(syncpt[id] - value) >= 0) break;
|
||||
int64_t left = end - hos_now_ns();
|
||||
if (left <= 0) {
|
||||
ReleaseSRWLockExclusive(&sync_lock);
|
||||
return 0;
|
||||
}
|
||||
hos_cv_sleep(&sync_cv, &sync_lock, timeout_ms < 0 ? 100 : (DWORD)(left / 1000000 + 1));
|
||||
}
|
||||
ReleaseSRWLockExclusive(&sync_lock);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* ---- per-device ioctls ------------------------------------------------------------------------------------------ */
|
||||
static uint32_t ioctl_nvmap(uint32_t nr, uint64_t p) {
|
||||
switch (nr) {
|
||||
case 0x01: { /* CREATE {u32 size; u32 handle out} */
|
||||
LOCK();
|
||||
uint32_t h = 1;
|
||||
while (h < 8192 && handles[h].used) h++;
|
||||
if (h == 8192) { UNLOCK(); return NV_INSUFFICIENT_MEMORY; }
|
||||
handles[h] = (Handle){G32(p), 0x1000, 0, 0, next_id++, 0, 1, 0};
|
||||
UNLOCK();
|
||||
G32(p + 4) = h;
|
||||
return NV_OK;
|
||||
}
|
||||
case 0x03: { /* FROM_ID {u32 id; u32 handle out} */
|
||||
uint32_t id = G32(p);
|
||||
for (uint32_t h = 1; h < 8192; h++)
|
||||
if (handles[h].used && handles[h].id == id) { G32(p + 4) = h; return NV_OK; }
|
||||
return NV_BAD_VALUE;
|
||||
}
|
||||
case 0x04: { /* ALLOC {u32 handle, heap_mask, flags, align; u8 kind; pad[7]; u64 address} */
|
||||
Handle *h = handle(G32(p));
|
||||
if (!h) return NV_BAD_VALUE;
|
||||
h->flags = G32(p + 8);
|
||||
h->align = G32(p + 12) ? G32(p + 12) : 0x1000;
|
||||
h->kind = *(uint8_t *)GP(p + 16);
|
||||
h->address = G64(p + 24);
|
||||
h->allocated = 1;
|
||||
return NV_OK;
|
||||
}
|
||||
case 0x05: { /* FREE {u32 handle; pad; u64 address out; u32 size out; u32 flags out} */
|
||||
Handle *h = handle(G32(p));
|
||||
if (!h) return NV_BAD_VALUE;
|
||||
G64(p + 8) = h->address;
|
||||
G32(p + 16) = h->size;
|
||||
G32(p + 20) = h->flags;
|
||||
h->used = 0;
|
||||
return NV_OK;
|
||||
}
|
||||
case 0x09: { /* PARAM {u32 handle, param; u32 result} */
|
||||
Handle *h = handle(G32(p));
|
||||
if (!h) return NV_BAD_VALUE;
|
||||
switch (G32(p + 4)) {
|
||||
case 1: G32(p + 8) = h->size; break;
|
||||
case 2: G32(p + 8) = h->align; break;
|
||||
case 3: G32(p + 8) = (uint32_t)h->address; break;
|
||||
case 4: G32(p + 8) = h->allocated ? 0x40000000 : 0; break; /* heap: IOVMM */
|
||||
case 5: G32(p + 8) = h->kind; break;
|
||||
case 6: G32(p + 8) = 0; break;
|
||||
default: return NV_BAD_PARAMETER;
|
||||
}
|
||||
return NV_OK;
|
||||
}
|
||||
case 0x0E: { /* GET_ID {u32 id out; u32 handle} */
|
||||
Handle *h = handle(G32(p + 4));
|
||||
if (!h) return NV_BAD_VALUE;
|
||||
G32(p) = h->id;
|
||||
return NV_OK;
|
||||
}
|
||||
}
|
||||
return NV_NOT_IMPLEMENTED;
|
||||
}
|
||||
|
||||
static uint32_t ioctl_as_gpu(uint32_t nr, uint64_t p, uint64_t size) {
|
||||
switch (nr) {
|
||||
case 0x01: return NV_OK; /* BIND_CHANNEL {s32 fd} */
|
||||
case 0x09: { /* ALLOC_AS_EX {flags, as_fd, big_page_size, reserved; u64 va_start, va_end, va_split} */
|
||||
MAP_LOG("nvdrv: alloc as ex flags %#x big page size %#x va %#llx..%#llx split %#llx", G32(p), G32(p + 8),
|
||||
(unsigned long long)G64(p + 16), (unsigned long long)G64(p + 24), (unsigned long long)G64(p + 32));
|
||||
if (G64(p + 16)) va_next = G64(p + 16);
|
||||
if (G64(p + 24)) va_end = G64(p + 24);
|
||||
return NV_OK;
|
||||
}
|
||||
case 0x02: { /* ALLOC_SPACE {u32 pages, page_size, flags; pad; u64 offset|align} */
|
||||
uint64_t sz = (uint64_t)G32(p) * G32(p + 4);
|
||||
uint32_t flags = G32(p + 8);
|
||||
MAP_LOG("nvdrv: alloc space %#llx bytes flags %#x at %#llx", (unsigned long long)sz, flags,
|
||||
(unsigned long long)G64(p + 16));
|
||||
if (flags & 1) return NV_OK; /* fixed offset: the VA is already chosen */
|
||||
LOCK();
|
||||
G64(p + 16) = va_alloc(sz, G64(p + 16) ? G64(p + 16) : G32(p + 4));
|
||||
UNLOCK();
|
||||
return NV_OK;
|
||||
}
|
||||
case 0x03: return NV_OK; /* FREE_SPACE */
|
||||
case 0x05: { /* UNMAP_BUFFER {s64 offset} */
|
||||
LOCK();
|
||||
map_remove(G64(p));
|
||||
UNLOCK();
|
||||
return NV_OK;
|
||||
}
|
||||
case 0x06: { /* MAP_BUFFER_EX {flags, kind, handle, page_size; s64 buffer_offset; u64 size; s64 offset} */
|
||||
uint32_t flags = G32(p);
|
||||
if (flags & 0x100) { /* REMAP: a range of an existing mapping gets another kind (NVN does this for compressed
|
||||
depth textures: refused, nvnTextureInitialize fails and the game draws its rain
|
||||
occlusion depth to GPU address 0). The memory behind it stays: just check it */
|
||||
const uint64_t va = G64(p + 32);
|
||||
LOCK();
|
||||
const int i = map_floor(va);
|
||||
const int ok = i >= 0 && va + G64(p + 16) + G64(p + 24) <= maps[i].va + maps[i].size;
|
||||
UNLOCK();
|
||||
MAP_LOG("nvdrv: remap GPU %#llx +%#llx size %#llx kind %#x: %s", (unsigned long long)va,
|
||||
(unsigned long long)G64(p + 16), (unsigned long long)G64(p + 24), G32(p + 4), ok ? "ok" : "no mapping");
|
||||
return ok ? NV_OK : NV_BAD_VALUE;
|
||||
}
|
||||
Handle *h = handle(G32(p + 8));
|
||||
if (!h) return NV_BAD_VALUE;
|
||||
uint64_t off = G64(p + 16), sz = G64(p + 24);
|
||||
if (!sz) sz = h->size - off;
|
||||
LOCK();
|
||||
uint64_t va = (flags & 1) ? G64(p + 32) : va_alloc(sz, G32(p + 12) ? G32(p + 12) : 0x10000);
|
||||
MAP_LOG("nvdrv: map buffer ex flags %#x kind %#x handle align %#x page size %#x size %#llx -> %#llx", flags,
|
||||
G32(p + 4), h->align, G32(p + 12), (unsigned long long)sz, (unsigned long long)va);
|
||||
map_add(va, sz, h->address + off);
|
||||
UNLOCK();
|
||||
G64(p + 32) = va;
|
||||
return NV_OK;
|
||||
}
|
||||
case 0x08: { /* GET_VA_REGIONS {u64 buf; u32 buf_size; u32 reserved; VaRegion[2]} */
|
||||
G32(p + 8) = 2 * 0x18;
|
||||
uint64_t r = p + 16;
|
||||
G64(r) = 0x04000000ULL; G32(r + 8) = 0x1000; G32(r + 12) = 0; G64(r + 16) = 0x3FBFFULL; /* small pages */
|
||||
r += 0x18;
|
||||
G64(r) = 0x400000000ULL; G32(r + 8) = 0x10000; G32(r + 12) = 0; G64(r + 16) = 0x1BFFFF0ULL; /* big pages */
|
||||
return NV_OK;
|
||||
}
|
||||
case 0x14: { /* REMAP: an array of {u16 flags, kind; u32 handle, handle_offset_bp, as_offset_bp, big_pages} */
|
||||
for (uint64_t e = p; e + 20 <= p + size; e += 20) {
|
||||
Handle *h = handle(G32(e + 4));
|
||||
uint64_t bp = 0x10000;
|
||||
uint64_t va = (uint64_t)G32(e + 12) * bp, sz = (uint64_t)G32(e + 16) * bp;
|
||||
LOCK();
|
||||
if (h) map_add(va, sz, h->address + (uint64_t)G32(e + 8) * bp);
|
||||
else map_remove(va); /* handle 0: unmap (sparse) */
|
||||
UNLOCK();
|
||||
}
|
||||
return NV_OK;
|
||||
}
|
||||
}
|
||||
return NV_NOT_IMPLEMENTED;
|
||||
}
|
||||
|
||||
static uint32_t ioctl_gpu(int fd, uint32_t group, uint32_t nr, uint64_t p, uint64_t size, uint64_t in2, uint64_t in2size) {
|
||||
if (group == 0x00 && nr == 0x03) { G32(p + 4) = 0; return NV_OK; } /* GET_WAITBASE */
|
||||
if (group == 0x47 && (nr == 0x14 || nr == 0x15)) return NV_OK; /* SET/GET_CLIENT_DATA */
|
||||
if (group != 0x48) return NV_NOT_IMPLEMENTED;
|
||||
switch (nr) {
|
||||
case 0x01: case 0x03: case 0x0B: case 0x0C: case 0x0D: case 0x1D:
|
||||
return NV_OK; /* SET_NVMAP_FD, SET_TIMEOUT, ZCULL_BIND, SET_ERROR_NOTIFIER, SET_PRIORITY, SET_TIMESLICE */
|
||||
case 0x17: /* GET_ERROR_NOTIFICATION {u64 timestamp; u32 info32; u16 info16; u16 status}: no error */
|
||||
memset(GP(p), 0, 16);
|
||||
return NV_OK;
|
||||
case 0x09: /* ALLOC_OBJ_CTX {u32 class, flags; u64 obj_id out} */
|
||||
G64(p + 8) = G32(p);
|
||||
return NV_OK;
|
||||
case 0x18: case 0x1A: { /* ALLOC_GPFIFO_EX(2) {u32 entries, jobs, flags; NvFence out; reserved} */
|
||||
LOCK();
|
||||
if (!fds[fd].syncpt) { /* (hookshot: ids are used again after the last one; they index syncpt[] and syncpt_max[]) */
|
||||
fds[fd].syncpt = next_syncpt++;
|
||||
if (next_syncpt >= SYNCPTS) next_syncpt = 24;
|
||||
}
|
||||
UNLOCK();
|
||||
G32(p + 12) = (uint32_t)fds[fd].syncpt;
|
||||
if ((int32_t)(syncpt_max[fds[fd].syncpt] - syncpt[fds[fd].syncpt]) < 0)
|
||||
syncpt_max[fds[fd].syncpt] = syncpt[fds[fd].syncpt];
|
||||
G32(p + 16) = syncpt[fds[fd].syncpt];
|
||||
SYNC_LOG("nvdrv: channel fd %d gets sync point %d (value %u)", fd, fds[fd].syncpt, syncpt[fds[fd].syncpt]);
|
||||
return NV_OK;
|
||||
}
|
||||
case 0x08: case 0x1B: { /* SUBMIT_GPFIFO {u64 address; u32 num_entries; u32 flags; NvFence fence} + entries */
|
||||
uint32_t n = G32(p + 8), flags = G32(p + 12);
|
||||
uint64_t entries = in2 && in2size >= (uint64_t)n * 8 ? in2 : p + 24; /* Ioctl2: inline; else after it */
|
||||
(void)size;
|
||||
if (!hos_guest_range(entries, (uint64_t)n * 8)) return NV_BAD_PARAMETER; /* (hookshot) */
|
||||
int sp = fds[fd].syncpt;
|
||||
/* add_increment (bit 1): the kernel appends two sync point increments after the work (suyu's
|
||||
BuildIncrementCommandList): the fence is the value they reach */
|
||||
uint32_t v;
|
||||
if (hos_gpu_async()) {
|
||||
AcquireSRWLockExclusive(&sync_lock);
|
||||
if (flags & 2) syncpt_max[sp] += 2;
|
||||
v = syncpt_max[sp];
|
||||
ReleaseSRWLockExclusive(&sync_lock);
|
||||
hos_gpu_queue_submit(fd, (const uint64_t *)GP(entries), n, (flags & 2) ? sp : -1);
|
||||
} else {
|
||||
hos_gpu_submit(fd, (const uint64_t *)GP(entries), n);
|
||||
if (flags & 2) { hos_gpu_syncpt_incr(sp); hos_gpu_syncpt_incr(sp); }
|
||||
v = syncpt[sp];
|
||||
}
|
||||
SYNC_LOG("nvdrv: submit %u entries flags %#x fence in {%u, %u} -> {%d, %u}", n, flags, G32(p + 16), G32(p + 20),
|
||||
sp, v);
|
||||
G32(p + 16) = (uint32_t)sp;
|
||||
G32(p + 20) = v;
|
||||
return NV_OK;
|
||||
}
|
||||
}
|
||||
return NV_NOT_IMPLEMENTED;
|
||||
}
|
||||
|
||||
static uint32_t ioctl_ctrl(uint32_t nr, uint64_t p) {
|
||||
switch (nr) {
|
||||
case 0x14: /* SYNCPT_READ {id; value out} */
|
||||
G32(p + 4) = syncpt[G32(p) % SYNCPTS];
|
||||
SYNC_LOG("nvdrv: syncpt read id %u: %u", G32(p), G32(p + 4));
|
||||
return NV_OK;
|
||||
case 0x15: /* SYNCPT_INCR {id} */
|
||||
hos_gpu_syncpt_incr(G32(p));
|
||||
SYNC_LOG("nvdrv: syncpt incr id %u (CPU): %u", G32(p), syncpt[G32(p) % SYNCPTS]);
|
||||
return NV_OK;
|
||||
case 0x16: case 0x19: { /* SYNCPT_WAIT(EX) {id, thresh, timeout[, value]} */
|
||||
int ok = syncpt_wait(G32(p), G32(p + 4), (int32_t)G32(p + 8));
|
||||
uint32_t v = syncpt[G32(p) % SYNCPTS];
|
||||
SYNC_LOG("nvdrv: syncpt wait id %u thresh %u timeout %d: value %u", G32(p), G32(p + 4), (int)G32(p + 8), v);
|
||||
if (nr == 0x19) G32(p + 12) = v;
|
||||
return ok ? NV_OK : NV_TIMEOUT;
|
||||
}
|
||||
case 0x1B: return NV_CONFIG_NOT_FOUND; /* GET_CONFIG */
|
||||
case 0x1C: return NV_OK; /* CLEAR_EVENT_WAIT */
|
||||
case 0x1D: case 0x1E: { /* EVENT_WAIT(_ASYNC) {NvFence fence; u32 timeout; u32 value in/out} */
|
||||
uint32_t id = G32(p) % SYNCPTS, thresh = G32(p + 4);
|
||||
SYNC_LOG("nvdrv: event wait%s id %u thresh %u timeout %d: value %u", nr == 0x1E ? " async" : "", id, thresh,
|
||||
(int)G32(p + 8), syncpt[id]);
|
||||
if ((int32_t)(syncpt[id] - thresh) >= 0) {
|
||||
G32(p + 12) = syncpt[id];
|
||||
return NV_OK;
|
||||
}
|
||||
if (hos_gpu_async()) { /* the event (the value's slot) is signalled when the sync point gets there */
|
||||
AcquireSRWLockExclusive(&sync_lock);
|
||||
int done = (int32_t)(syncpt[id] - thresh) >= 0;
|
||||
int i = 0;
|
||||
for (; i < 512 && !done; i++)
|
||||
if (!pending[i].used) {
|
||||
pending[i].used = 1;
|
||||
pending[i].slot = G32(p + 12) & 0xFFFF;
|
||||
pending[i].id = id;
|
||||
pending[i].value = thresh;
|
||||
break;
|
||||
}
|
||||
if (i == 512) hos_log("nvdrv: event wait table full: a fence wait is lost");
|
||||
ReleaseSRWLockExclusive(&sync_lock);
|
||||
if (done) {
|
||||
G32(p + 12) = syncpt[id];
|
||||
return NV_OK;
|
||||
}
|
||||
}
|
||||
/* synchronous GPU: work finishes at submission, so a fence still ahead was never submitted */
|
||||
return NV_TIMEOUT;
|
||||
}
|
||||
case 0x1F: case 0x20: case 0x21: return NV_OK; /* EVENT_REGISTER / UNREGISTER(_BATCH) */
|
||||
}
|
||||
return NV_NOT_IMPLEMENTED;
|
||||
}
|
||||
|
||||
static uint32_t ioctl_ctrl_gpu(uint32_t nr, uint64_t p, uint64_t out2, uint64_t out2size) {
|
||||
switch (nr) {
|
||||
case 0x01: G32(p) = 1; return NV_OK; /* ZCULL_GET_CTX_SIZE */
|
||||
case 0x02: { /* ZCULL_GET_INFO */
|
||||
static const uint32_t v[10] = {0x20, 0x20, 0x400, 0x800, 0x20, 0x20, 0xC0, 0x20, 0x40, 0x10};
|
||||
memcpy(GP(p), v, sizeof v);
|
||||
return NV_OK;
|
||||
}
|
||||
case 0x03: case 0x04: case 0x07: return NV_OK; /* ZBC_SET_TABLE, ZBC_QUERY_TABLE, FLUSH_L2 */
|
||||
case 0x05: { /* GET_CHARACTERISTICS {u64 buf_size; u64 buf_addr; characteristics[0xA0]} (Ioctl3: into out2) */
|
||||
uint32_t c[40] = {0};
|
||||
uint64_t q;
|
||||
c[0] = 0x120; c[1] = 0xB; c[2] = 0xA1; c[3] = 1; /* GM20B, rev A1, 1 GPC */
|
||||
q = 0x40000; memcpy(&c[4], &q, 8); /* L2 256 KB */
|
||||
c[8] = 2; c[9] = 0x20; c[10] = 0x20000; c[11] = 0x20000; c[12] = 0x1B; c[13] = 0x30000; c[14] = 1;
|
||||
c[15] = 0x503; c[16] = 0x503; c[17] = 0x80; c[18] = 0x28;
|
||||
q = 0x55; memcpy(&c[20], &q, 8);
|
||||
c[22] = 0x902D; c[23] = 0xB197; c[24] = 0xB1C0; c[25] = 0xB06F; c[26] = 0xA140; c[27] = 0xB0B5;
|
||||
c[28] = 1; c[29] = 0; c[30] = 2; c[31] = 1; c[32] = 0; c[33] = 1; c[34] = 0x21D70; c[35] = 0;
|
||||
q = 0x6230326D67ULL; memcpy(&c[36], &q, 8); /* "gm20b" */
|
||||
G64(p) = 0xA0;
|
||||
memcpy(GP(out2 && out2size >= 0xA0 ? out2 : p + 16), c, 0xA0);
|
||||
return NV_OK;
|
||||
}
|
||||
case 0x06: { /* GET_TPC_MASKS {u32 size; pad; u64 addr; u32 tpc_mask; pad} */
|
||||
G32(p + 16) = 0x3;
|
||||
if (out2 && out2size >= 4) G32(out2) = 0x3;
|
||||
return NV_OK;
|
||||
}
|
||||
case 0x14: G32(p) = 0x07; G32(p + 4) = 0x01; return NV_OK; /* ZBC_GET_ACTIVE_SLOT_MASK */
|
||||
case 0x15: G32(p) = 0; return NV_OK; /* PMU_GET_GPU_LOAD */
|
||||
case 0x1C: G64(p) = (uint64_t)hos_now_ns(); return NV_OK; /* GET_GPU_TIME */
|
||||
}
|
||||
return NV_NOT_IMPLEMENTED;
|
||||
}
|
||||
|
||||
static uint32_t ioctl(Ctx *c, int fd, uint32_t cmd, uint64_t buf, uint64_t x2, uint64_t x2size) {
|
||||
if (fd < 0 || fd >= 256 || !fds[fd].type) return NV_BAD_PARAMETER;
|
||||
uint32_t nr = cmd & 0xFF, group = (cmd >> 8) & 0xFF;
|
||||
uint64_t size = (cmd >> 16) & 0x3FFF;
|
||||
uint32_t r;
|
||||
/* (hookshot) the argument buffers lie in guest memory (the handlers read fixed fields up to 0x100 past the start) */
|
||||
if (!hos_guest_range(buf, size + 0x100) || (x2 && !hos_guest_range(x2, x2size))) return NV_BAD_PARAMETER;
|
||||
switch (fds[fd].type) {
|
||||
case DEV_NVMAP: r = ioctl_nvmap(nr, buf); break;
|
||||
case DEV_AS_GPU: r = ioctl_as_gpu(nr, buf, size); break;
|
||||
case DEV_GPU: r = ioctl_gpu(fd, group, nr, buf, size, x2, x2size); break;
|
||||
case DEV_CTRL: r = ioctl_ctrl(nr, buf); break;
|
||||
case DEV_CTRL_GPU: r = ioctl_ctrl_gpu(nr, buf, x2, x2size); break;
|
||||
default: r = NV_NOT_IMPLEMENTED;
|
||||
}
|
||||
if (r == NV_NOT_IMPLEMENTED || hos_trace)
|
||||
hos_log("nvdrv %s ioctl %#x (group %#x nr %#x size %#llx) -> %#x", fds[fd].path, cmd, group, nr,
|
||||
(unsigned long long)size, r);
|
||||
(void)c;
|
||||
return r;
|
||||
}
|
||||
|
||||
/* ---- the NvOs layer ----------------------------------------------------------------------------------------------- */
|
||||
/* NvOsDrvOpen(char const* path) -> fd, or -1 */
|
||||
HLE(NvOsDrvOpen) {
|
||||
const char *path = ARG(0) ? (const char *)GP(ARG(0)) : "";
|
||||
int type = 0;
|
||||
for (unsigned i = 0; i < sizeof devices / sizeof *devices; i++)
|
||||
if (!strcmp(devices[i].path, path)) type = devices[i].type;
|
||||
if (!type) { hos_log("nvdrv: open %s: unknown device", path); RET(-1); return; }
|
||||
LOCK();
|
||||
int fd = 1;
|
||||
while (fd < 256 && fds[fd].type) fd++;
|
||||
if (fd < 256) {
|
||||
fds[fd] = (Fd){type, "", 0};
|
||||
snprintf(fds[fd].path, sizeof fds[fd].path, "%s", path);
|
||||
}
|
||||
UNLOCK();
|
||||
if (hos_trace) hos_log("nvdrv: open %s -> %d", path, fd);
|
||||
RET(fd < 256 ? fd : -1);
|
||||
}
|
||||
HLE(NvOsDrvClose) { int fd = (int)ARG(0); if (fd > 0 && fd < 256) fds[fd].type = 0; RET(0); }
|
||||
/* NvOsDrvIoctl(int fd, u32 cmd, void* buf) */
|
||||
HLE(NvOsDrvIoctl) { RET(ioctl(c, (int)ARG(0), (uint32_t)ARG(1), ARG(2), 0, 0)); }
|
||||
/* NvOsDrvIoctl2(int fd, u32 cmd, void* buf, ?, void const* in2, size in2) */
|
||||
HLE(NvOsDrvIoctl2) { RET(ioctl(c, (int)ARG(0), (uint32_t)ARG(1), ARG(2), ARG(4), ARG(5))); }
|
||||
/* NvOsDrvIoctl3(int fd, u32 cmd, void* buf, ?, void* out2, size out2) */
|
||||
HLE(NvOsDrvIoctl3) { RET(ioctl(c, (int)ARG(0), (uint32_t)ARG(1), ARG(2), ARG(4), ARG(5))); }
|
||||
/* NvOsDrvMapSharedMem(int fd, handle, size) */
|
||||
HLE(NvOsDrvMapSharedMem) { RET(0); }
|
||||
/* NvOsDrvQueryEvent(int fd, u32 event id, os::SystemEventType*) */
|
||||
HLE(_Z17NvOsDrvQueryEventijPN2nn2os15SystemEventTypeE) {
|
||||
SYNC_LOG("nvdrv: query event fd %d id %#x", (int)ARG(0), (uint32_t)ARG(1));
|
||||
hos_system_event_init(ARG(2), 1);
|
||||
uint32_t id = (uint32_t)ARG(1) & 63;
|
||||
AcquireSRWLockExclusive(&sync_lock);
|
||||
ctrl_events[id] = ARG(2);
|
||||
const int early = ctrl_early[id];
|
||||
ctrl_early[id] = 0;
|
||||
ReleaseSRWLockExclusive(&sync_lock);
|
||||
if (early || !hos_gpu_async()) hos_system_event_signal(ARG(2)); /* (a synchronous GPU never lags) */
|
||||
RET(0);
|
||||
}
|
||||
186
host/nvn_layout.c
Normal file
186
host/nvn_layout.c
Normal file
@@ -0,0 +1,186 @@
|
||||
/* NVN texture storage: size, alignment and level offsets of the Tegra X1 block-linear layout (the native NVN layer,
|
||||
gpu/render/rx_nvn.h). The game allocates texture storage by these numbers and copies its packaged (pre-tiled) data
|
||||
into it, so they must be the real driver's.
|
||||
From the NVN layer of d2r-mobile / MacNativeGames (jhaizhou, MIT), itself based on deko3d source/dk_image.cpp
|
||||
(zlib license, Copyright (C) 2018-2020 fincs; altered: the NVN SDK's integer rounding for the automatic block height,
|
||||
packaged layouts, MINIMAL_LAYOUT). One GOB = 64 bytes x 8 rows = 512 bytes; the block height (tileH, in GOBs) is
|
||||
picked from height x 1.5; levels are added up in whole blocks. A packaged texture's 8 layout bytes: byte 0's low
|
||||
nibble = log2 of the block height, its high nibble = log2 of the block depth (3D). CUBEMAP_ARRAY depth already counts
|
||||
layer-faces (a multiple of 6), and linear textures are sized in pixel rows, block-compressed ones too (MacNativeGames
|
||||
3c482a7, found against the original driver under emulation: nxnative PR 11). */
|
||||
#include "../gpu/render/rx_nvn.h"
|
||||
#include <stdatomic.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct { uint8_t bpb, bw, bh; } fmt_t; // Bytes per block, block width, block height (for uncompressed formats block width and height = 1)
|
||||
|
||||
static fmt_t fmt_of(int f) {
|
||||
static const uint8_t astc[14][2] = {{4,4},{5,4},{5,5},{6,5},{6,6},{8,5},{8,6},{8,8},{10,5},{10,6},{10,8},{10,10},{12,10},{12,12}};
|
||||
if (f >= 0x79 && f <= 0x94) { int k = (f - 0x79) % 14; return (fmt_t){16, astc[k][0], astc[k][1]}; }
|
||||
if (f >= 0x41 && f <= 0x50) { // DXT / RGTC / BPTC: 4×4 blocks
|
||||
int b8 = (f <= 0x42) || (f == 0x45 || f == 0x46) || (f == 0x49 || f == 0x4A);
|
||||
return (fmt_t){b8 ? 8 : 16, 4, 4};
|
||||
}
|
||||
static const struct { uint8_t lo, hi, bpb; } r[] = {
|
||||
{0x01,0x04,1},{0x05,0x09,2},{0x0A,0x0C,4},{0x0D,0x10,2},{0x11,0x15,4},{0x16,0x18,8},
|
||||
{0x19,0x1C,3},{0x1D,0x21,6},{0x22,0x24,12},{0x25,0x28,4},{0x29,0x2D,8},{0x2E,0x30,16},
|
||||
{0x31,0x31,1},{0x32,0x32,2},{0x33,0x35,4},{0x36,0x36,8},{0x37,0x38,4},{0x39,0x3C,2},{0x3D,0x40,4},
|
||||
{0x51,0x52,1},{0x53,0x54,2},{0x55,0x56,4},{0x57,0x58,2},{0x59,0x5A,4},{0x5B,0x5C,8},
|
||||
{0x5D,0x5E,3},{0x5F,0x60,6},{0x61,0x62,12},{0x63,0x64,4},{0x65,0x66,8},{0x67,0x68,16},
|
||||
{0x69,0x6C,4},{0x6D,0x70,4},{0x71,0x75,8},{0x76,0x78,16},{0x95,0x98,2},{0x99,0x9C,4},
|
||||
};
|
||||
for (unsigned i = 0; i < sizeof r / sizeof *r; i++)
|
||||
if (f >= r[i].lo && f <= r[i].hi) return (fmt_t){r[i].bpb, 1, 1};
|
||||
return (fmt_t){0, 1, 1};
|
||||
}
|
||||
|
||||
int nvn_fmt_bpb(int f, int *bw, int *bh) { fmt_t t = fmt_of(f); if (bw) *bw = t.bw; if (bh) *bh = t.bh; return t.bpb; }
|
||||
|
||||
/* (hookshot) 64-bit: a width from the game times the samples and the bytes per block wrapped in 32 bits, and a 512-byte
|
||||
size was given for a texture the renderer then made 4 GB wide */
|
||||
static uint64_t mip(uint64_t s, unsigned l) { s = l < 64 ? s >> l : 0; return s ? s : 1; }
|
||||
static uint64_t blk(uint64_t s, uint32_t b) { return (s + b - 1) / b; }
|
||||
static unsigned pick_tile(uint32_t gobs) { return gobs >= 16 ? 4 : gobs >= 8 ? 3 : gobs >= 4 ? 2 : gobs >= 2 ? 1 : 0; }
|
||||
static unsigned adj_tile(unsigned shift, uint32_t unit, uint32_t dim) {
|
||||
if (!shift) return 0;
|
||||
uint32_t x = unit << (shift - 1);
|
||||
if (x >= dim) while (--shift) { x >>= 1; if (x < dim) break; }
|
||||
return shift;
|
||||
}
|
||||
|
||||
// target: NVNtextureTarget; the number of dims and whether it is layered are determined by target
|
||||
static void shape(const nvn_texdesc *d, unsigned *dpl, int *layered, uint32_t *w, uint32_t *h, uint32_t *z) {
|
||||
*w = d->width; *h = d->height; *z = d->depth; *layered = 0;
|
||||
switch (d->target) {
|
||||
case 0: *dpl = 1; *h = 1; *z = 1; break; // 1D
|
||||
case 3: *dpl = 1; *z = d->height; *h = 1; *layered = 1; break; // 1D_ARRAY (layer count is in height)
|
||||
case 2: *dpl = 3; break; // 3D
|
||||
case 4: case 6: *dpl = 2; *layered = 1; break; // 2D_ARRAY / MS_ARRAY
|
||||
case 8: *dpl = 2; *z = 6; *layered = 1; break; // CUBEMAP
|
||||
case 9: *dpl = 2; *layered = 1; break; // CUBEMAP_ARRAY: depth already counts layer-faces
|
||||
default: *dpl = 2; *z = 1; break; // 2D / MS / RECTANGLE
|
||||
}
|
||||
if (*z == 0) *z = 1;
|
||||
}
|
||||
|
||||
static void samples_xy(int s, uint32_t *sx, uint32_t *sy) {
|
||||
*sx = *sy = 1;
|
||||
if (s == 2) *sx = 2; else if (s == 4) *sx = *sy = 2; else if (s == 8) { *sx = 4; *sy = 2; }
|
||||
}
|
||||
|
||||
static uint64_t level_offset(const nvn_texdesc *d, unsigned level, unsigned dpl, uint32_t w, uint32_t h, uint32_t z,
|
||||
unsigned tileH, unsigned tileD, fmt_t t) {
|
||||
uint32_t sx, sy; samples_xy(d->samples, &sx, &sy);
|
||||
uint64_t off = 0;
|
||||
if (level > 32) level = 32; /* (hookshot: past 32 every level is 1x1; a level count from the game looped for minutes) */
|
||||
for (unsigned i = 0; i < level; i++) {
|
||||
uint64_t lw = blk(mip((uint64_t)w * sx, i), t.bw);
|
||||
uint64_t lh = dpl >= 2 ? blk(mip((uint64_t)h * sy, i), t.bh) : 1;
|
||||
uint64_t ld = dpl >= 3 ? mip(z, i) : 1;
|
||||
uint64_t lwb = lw * t.bpb;
|
||||
unsigned th = adj_tile(tileH, 8, lh > 0xFFFFFFFFu ? 0xFFFFFFFFu : (uint32_t)lh);
|
||||
unsigned td = adj_tile(tileD, 1, ld > 0xFFFFFFFFu ? 0xFFFFFFFFu : (uint32_t)ld);
|
||||
uint64_t wg = (lwb + 63) / 64, hg = (lh + 7) / 8;
|
||||
uint64_t wt = wg, ht = (hg + (1u << th) - 1) >> th, dt = (ld + (1u << td) - 1) >> td;
|
||||
off += (uint64_t)wt * ht * dt << (9 + th + td);
|
||||
}
|
||||
return off;
|
||||
}
|
||||
|
||||
/* NVN v55 sdk+0x4429c8 compares the default footprint against one-GOB tiles
|
||||
for MINIMAL_LAYOUT. Keep the default if equal; otherwise use tile H=D=0.
|
||||
Packaged layouts override this choice. Layout cannot be switched on live
|
||||
resources: the startup-only knob is a negative control for fresh sessions. */
|
||||
static int minimal_layout_on(void) {
|
||||
static _Atomic int enabled = -1;
|
||||
int value = atomic_load(&enabled);
|
||||
if (value < 0) { const char *e = getenv("TOTK_MINIMAL_LAYOUT"); value = !(e && !strcmp(e, "0")); atomic_store(&enabled, value); }
|
||||
return value;
|
||||
}
|
||||
static uint64_t layer_bytes(const nvn_texdesc *d, unsigned dpl, int layered,
|
||||
uint32_t w, uint32_t h, uint32_t z, unsigned tileH, unsigned tileD, fmt_t t) {
|
||||
uint64_t ls = level_offset(d, d->levels ? d->levels : 1, dpl, w, h, z, tileH, tileD, t);
|
||||
if (layered) {
|
||||
uint32_t hh = blk(h, t.bh); unsigned th = tileH, td = tileD;
|
||||
while (th && hh <= (8u << (th - 1))) th--;
|
||||
while (td && z <= (1u << (td - 1))) td--;
|
||||
uint64_t align = 1ull << (th + td + 9);
|
||||
ls = (ls + align - 1) & ~(align - 1);
|
||||
}
|
||||
return ls;
|
||||
}
|
||||
|
||||
void nvn_tex_layout(const nvn_texdesc *d, nvn_texlayout *o) {
|
||||
fmt_t t = fmt_of(d->format);
|
||||
unsigned dpl; int layered; uint32_t w, h, z;
|
||||
shape(d, &dpl, &layered, &w, &h, &z);
|
||||
uint32_t sx, sy; samples_xy(d->samples, &sx, &sy);
|
||||
o->bpb = t.bpb; o->tileH = o->tileD = 0; o->layers = layered ? z : 1;
|
||||
if (!t.bpb) { o->size = 0; o->align = 512; o->layer_size = 0; return; }
|
||||
if (d->target == 10) { // BUFFER
|
||||
o->layer_size = o->size = (uint64_t)t.bpb * d->width;
|
||||
o->align = t.bpb == 12 ? 4 : t.bpb; return;
|
||||
}
|
||||
if (nvn_tex_is_linear(d)) { // Pitch storage: explicit stride, otherwise 32-byte (LINEAR) / 128-byte (LINEAR_RENDER_TARGET) alignment
|
||||
o->align = (d->flags & 0x40) ? 128 : 32;
|
||||
uint32_t stride = nvn_tex_linear_stride(d);
|
||||
o->layer_size = o->size = (uint64_t)stride * h; // (the driver counts pixel rows, block-compressed formats too)
|
||||
return;
|
||||
}
|
||||
unsigned tileH = 0, tileD = 0;
|
||||
/* NVN truncates height*1.5 to whole GOB rows before choosing the power of
|
||||
two. Rounding up here changes e.g. 40 BC rows from H2 to H3 even when
|
||||
the total allocation size is unchanged, so padding becomes black texels. */
|
||||
if (d->pkg_block_h) { // packaged byte 0: low nibble block height, high nibble block depth
|
||||
const unsigned pl = (unsigned)(d->pkg_block_h - 1) & 0xFF;
|
||||
/* (hookshot) at most 32 GOBs high and deep, the hardware's largest blocks: the game's nibble went up to 15, and
|
||||
the renderer's scratch for one level grew with 512 << (tileH + tileD) */
|
||||
if (dpl >= 2) tileH = (pl & 0xF) > 5 ? 5 : pl & 0xF;
|
||||
if (dpl == 3) tileD = (pl >> 4) > 5 ? 5 : pl >> 4;
|
||||
} else if (dpl == 2) {
|
||||
const uint64_t ah = blk((uint64_t)h * sy, t.bh), gobs = (ah + ah / 2) / 8;
|
||||
tileH = pick_tile(gobs > 0xFFFFFFFFu ? 0xFFFFFFFFu : (uint32_t)gobs);
|
||||
}
|
||||
else if (dpl == 3) tileD = pick_tile(z + z / 2);
|
||||
uint64_t ls = layer_bytes(d, dpl, layered, w, h, z, tileH, tileD, t);
|
||||
if ((d->flags & 0x200) && !d->pkg_block_h && minimal_layout_on()) {
|
||||
uint64_t minimal = layer_bytes(d, dpl, layered, w, h, z, 0, 0, t);
|
||||
if (minimal != ls) { tileH = tileD = 0; ls = minimal; }
|
||||
}
|
||||
o->tileH = tileH; o->tileD = tileD;
|
||||
o->layer_size = ls;
|
||||
o->size = layered ? ls * z : ls;
|
||||
o->align = 512;
|
||||
}
|
||||
|
||||
uint64_t nvn_tex_level_offset(const nvn_texdesc *d, unsigned level) {
|
||||
fmt_t t = fmt_of(d->format);
|
||||
unsigned dpl; int layered; uint32_t w, h, z;
|
||||
shape(d, &dpl, &layered, &w, &h, &z);
|
||||
if (!t.bpb || nvn_tex_is_linear(d) || d->target == 10) return 0;
|
||||
nvn_texlayout L; nvn_tex_layout(d, &L);
|
||||
return level_offset(d, level, dpl, w, h, z, L.tileH, L.tileD, t);
|
||||
}
|
||||
|
||||
void nvn_tex_level_tiles(const nvn_texdesc *d, unsigned level, unsigned *tileH, unsigned *tileD) {
|
||||
fmt_t t = fmt_of(d->format);
|
||||
unsigned dpl; int layered; uint32_t w, h, z;
|
||||
shape(d, &dpl, &layered, &w, &h, &z);
|
||||
uint32_t sx, sy; samples_xy(d->samples, &sx, &sy);
|
||||
nvn_texlayout L; nvn_tex_layout(d, &L);
|
||||
const uint64_t lh = dpl >= 2 ? blk(mip((uint64_t)h * sy, level), t.bh) : 1;
|
||||
const uint64_t ld = dpl >= 3 ? mip(z, level) : 1;
|
||||
*tileH = adj_tile(L.tileH, 8, lh > 0xFFFFFFFFu ? 0xFFFFFFFFu : (uint32_t)lh);
|
||||
*tileD = adj_tile(L.tileD, 1, ld > 0xFFFFFFFFu ? 0xFFFFFFFFu : (uint32_t)ld);
|
||||
}
|
||||
|
||||
uint32_t nvn_tex_linear_stride(const nvn_texdesc *d) {
|
||||
if (d->stride) return d->stride;
|
||||
int bw, bh;
|
||||
int bpb = nvn_fmt_bpb(d->format, &bw, &bh);
|
||||
uint32_t align = (d->flags & 0x40) ? 128 : 32;
|
||||
/* (hookshot) 64-bit, as the layout: a width near 2^32 wrapped to a small stride */
|
||||
const uint64_t s = (((uint64_t)d->width + bw - 1) / bw * bpb + align - 1) & ~(uint64_t)(align - 1);
|
||||
return s > 0xFFFFFFFFu ? 0xFFFFFFFFu & ~(align - 1) : (uint32_t)s;
|
||||
}
|
||||
3204
host/nvn_native.c
Normal file
3204
host/nvn_native.c
Normal file
File diff suppressed because it is too large
Load Diff
842
host/oot_menu.c
Normal file
842
host/oot_menu.c
Normal file
@@ -0,0 +1,842 @@
|
||||
/* The mouse in the game's own menus: the title and its lists, the pause menu, the panel of
|
||||
Key Items, Threads of Time and the Map, the options, the save files' dialogs. The mouse frees itself over them
|
||||
(display.c), points at their buttons (the focus as the pad moves it), clicks them (A), backs out (the right button:
|
||||
B) and scrolls their lists. nx2/oot_patches.py has two of the game's functions call here first (the supported build
|
||||
only):
|
||||
- f_802ed660 (in the pause menu's vtable at 0x84c0bc18), the pause menu's handler of a pane getting the focus: it
|
||||
matches the pane's name against the pages (PaItemMenu_00, PaEquipmentMenu_00, PaCollectMenu_00, PaSystemMenu_00)
|
||||
and hands the pane to the page (f_802ebd20 on the Items page: the info panel). The pause menu's page, for its tabs.
|
||||
- f_802f1380, every menu screen's update (each frame, before its UI controller at +56 runs the buttons' requests):
|
||||
the screens are tracked, and the mouse is for the one in front (hos_oot_menu_tick).
|
||||
The focus setter is f_8088ffc0(screen, button, flag), as the game's screens call it (f_80795090): it finds the button's
|
||||
entry in the screen's list (+136 the head, +144 the first, +156 the entry's offset from its node; entry+24 the button)
|
||||
and hands it to the focus manager (*(screen+32)+96, its vtable +48), when the manager takes the player's input.
|
||||
HOS_MENU_TRACE=1: the focus changes, the screens and what the mouse does logged. */
|
||||
#include "hos.h"
|
||||
#if defined(_WIN32)
|
||||
#include <windows.h>
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "../gpu/vk/vk_api.h" /* (HOS_MOUSE_*) */
|
||||
|
||||
/* A guest read, of the pointers the game's objects hold: inside the guest's space (below 1 MB: a null pointer's), it is
|
||||
read as the lifted code reads it; a page there not committed yet is committed on the touch (mkw_glue.c
|
||||
commit_on_touch), so a stray pointer costs a page, not a fault. Not ReadProcessMemory: a call into the kernel each,
|
||||
hundreds a frame */
|
||||
static int peek(uint64_t a, void *dst, size_t n) {
|
||||
if (a < 0x100000 || a >= HOS_GUEST_SPACE || n > HOS_GUEST_SPACE - a) return 0;
|
||||
memcpy(dst, GP(a), n);
|
||||
return 1;
|
||||
}
|
||||
static uint64_t peek64(uint64_t a) {
|
||||
uint64_t v = 0;
|
||||
return peek(a, &v, 8) ? v : 0;
|
||||
}
|
||||
/* a printable C string at a (else "-") */
|
||||
static const char *text_at(uint64_t a, char *buf, size_t cap) {
|
||||
if (!peek(a, buf, cap - 1)) return "-";
|
||||
buf[cap - 1] = 0;
|
||||
for (size_t i = 0; buf[i]; i++)
|
||||
if ((unsigned char)buf[i] < 32 || (unsigned char)buf[i] > 126) return i > 2 ? (buf[i] = 0, buf) : "-";
|
||||
return buf[0] ? buf : "-";
|
||||
}
|
||||
|
||||
static int trace = -1;
|
||||
/* (the screen f_802ed660 ran for: written under mouse_lock, read by every screen's update under seen_lock or none,
|
||||
so read and written whole) */
|
||||
static volatile LONG64 pause_screen;
|
||||
static uint64_t pause_screen_now(void) { return (uint64_t)InterlockedCompareExchange64(&pause_screen, 0, 0); }
|
||||
static uint64_t focus_page; /* (the focused pane's page object: a change is a page switch) */
|
||||
static volatile LONG ticks; /* (the pause menu's updates since its focus came: for the trace only) */
|
||||
static int tab_goal = -1, tab_pages, tab_from = -9; /* (a clicked tab: the page to step to, and how many the menu has) */
|
||||
static int64_t goal_ns;
|
||||
static uint64_t focused_button; /* (the last pane f_802ed660 was handed) */
|
||||
static uint64_t asked; /* (the button the mouse asked the focus for, until it has it) */
|
||||
static int page_now = -1; /* (the shown page: 0 Collection, 1 Equipment, 2 Items, 3 System; L and R step through them) */
|
||||
|
||||
/* the screen's list of entries: fn(entry, button) for each, at most max */
|
||||
static int each_entry(uint64_t screen, int max, void (*fn)(int i, uint64_t entry, uint64_t button, void *arg), void *arg) {
|
||||
const uint64_t head = screen + 136;
|
||||
int32_t off = 0;
|
||||
peek(screen + 156, &off, 4);
|
||||
uint64_t node = peek64(screen + 144);
|
||||
int i = 0;
|
||||
for (; node && node != head && i < max; i++) {
|
||||
const uint64_t entry = node - (uint64_t)(int64_t)off;
|
||||
if (fn) fn(i, entry, peek64(entry + 24), arg);
|
||||
node = peek64(node + 8);
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
/* the game's focus setter on a button (on the game's thread, at a screen's update) */
|
||||
static int set_focus(Ctx *c, uint64_t screen, uint64_t button) {
|
||||
A64Fn fn = a64_lookup(0x8088ffc0ULL);
|
||||
if (!fn) return -1;
|
||||
const Ctx saved = *c;
|
||||
c->x[0] = screen, c->x[1] = button, c->x[2] = 0;
|
||||
c->x[30] = 0;
|
||||
fn(c);
|
||||
const int r = (int)(c->x[0] & 1);
|
||||
*c = saved;
|
||||
return r;
|
||||
}
|
||||
|
||||
/* A call of a guest function from the host, on the game's thread (x0, x1 in; x0 out, s0 and s1 too: a position) */
|
||||
static uint64_t guest_call(Ctx *c, uint64_t fn_addr, uint64_t a0, uint64_t a1, float *s0, float *s1) {
|
||||
A64Fn fn = a64_lookup(fn_addr);
|
||||
if (!fn) return 0;
|
||||
const Ctx saved = *c;
|
||||
c->x[0] = a0, c->x[1] = a1, c->x[30] = 0;
|
||||
fn(c);
|
||||
const uint64_t r = c->x[0];
|
||||
if (s0) memcpy(s0, &c->vreg[0][0], 4);
|
||||
if (s1) memcpy(s1, &c->vreg[1][0], 4);
|
||||
*c = saved;
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Key Items' items where the page shows them, as the page finds them to place its cursor (f_833fdaa0): the item
|
||||
database (**0x84c9e0d0), its lists 4 and 3 (f_80a8f690: +8 the count, +16 the entries); an entry's key (f_8002a520,
|
||||
f_80d666a0(.., 0), f_8002a4c0: a string, its text first) and its pane's name (f_80a963c0: its text first); the pane in
|
||||
the screen's layout (f_8078e2b0(*(screen+40), name)) and its position (f_8078fcb0). fn(key, x, y) for each */
|
||||
static int item_panes(Ctx *c, uint64_t screen, void (*fn)(const char *key, float x, float y, void *arg), void *arg) {
|
||||
const uint64_t db = peek64(peek64(0x84c9e0d0ULL)), layout = peek64(screen + 40);
|
||||
if (!db || !layout) return 0;
|
||||
int n = 0;
|
||||
for (int which = 4; which >= 3; which--) {
|
||||
const uint64_t list = guest_call(c, 0x80a8f690ULL, db, (uint64_t)which, NULL, NULL);
|
||||
int32_t count = 0;
|
||||
peek(list + 8, &count, 4);
|
||||
const uint64_t entries = peek64(list + 16);
|
||||
for (int i = 0; i < count && i < 32; i++) {
|
||||
const uint64_t e = peek64(entries + 8ull * (unsigned)i);
|
||||
if (!e) continue;
|
||||
uint64_t k = guest_call(c, 0x8002a520ULL, e, 0, NULL, NULL);
|
||||
k = guest_call(c, 0x80d666a0ULL, k, 0, NULL, NULL);
|
||||
k = guest_call(c, 0x8002a4c0ULL, k, 0, NULL, NULL);
|
||||
char key[40];
|
||||
if (!k || !peek(peek64(k), key, sizeof key - 1)) continue;
|
||||
key[sizeof key - 1] = 0;
|
||||
const uint64_t named = guest_call(c, 0x80a963c0ULL, e, 0, NULL, NULL);
|
||||
const uint64_t pane = named ? guest_call(c, 0x8078e2b0ULL, layout, peek64(named), NULL, NULL) : 0;
|
||||
float x = 0, y = 0;
|
||||
if (!pane) continue;
|
||||
guest_call(c, 0x8078fcb0ULL, pane, 0, &x, &y);
|
||||
if (x == x && y == y) fn(key, x, y, arg), n++;
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/* Key Items' setter: the item's key into the page's key buffer (*(screen+760), its room at +768) and the page's refresh
|
||||
f_833fda00(screen, screen+760) (the cursor's key and the item's name and description; the page's update places the
|
||||
cursor from the key next frame), as the page does when it opens. Only while the page browses (+840: 0; 1 its
|
||||
details shown) */
|
||||
static int set_item_key(Ctx *c, uint64_t screen, const char *key) {
|
||||
const uint64_t buf = peek64(screen + 760);
|
||||
int32_t room = 0, mode = 1;
|
||||
peek(screen + 768, &room, 4);
|
||||
peek(screen + 840, &mode, 4);
|
||||
const size_t n = strlen(key);
|
||||
A64Fn fn = a64_lookup(0x833fda00ULL);
|
||||
if (!fn || !buf || buf + n + 1 > HOS_GUEST_SPACE || room <= (int32_t)n || mode != 0) return 0;
|
||||
memcpy(GP(buf), key, n + 1);
|
||||
const Ctx saved = *c;
|
||||
c->x[0] = screen, c->x[1] = screen + 760, c->x[30] = 0;
|
||||
fn(c);
|
||||
*c = saved;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static SRWLOCK mouse_lock;
|
||||
static volatile DWORD mouse_owner;
|
||||
/* A focus change the hook could not hand over at once (mouse_lock busy: mouse_tick holds it on another of the game's
|
||||
threads, across its calls into the game): kept, the latest only, for mouse_tick to take. The hook never waits for
|
||||
mouse_lock, as that thread's game code might wait on this one. pending_lock is held only to copy these words */
|
||||
static SRWLOCK pending_lock = SRWLOCK_INIT;
|
||||
static struct { uint64_t screen, pane, lr; int set; } pending;
|
||||
static void focus_locked(uint64_t screen, uint64_t pane, uint64_t lr);
|
||||
void hos_oot_menu_focus(Ctx *c, uint64_t screen, uint64_t pane, uint64_t lr) {
|
||||
(void)c;
|
||||
if (trace < 0) trace = getenv("HOS_MENU_TRACE") != NULL;
|
||||
if (mouse_owner == GetCurrentThreadId()) { /* (inside mouse_tick's setter, on its thread: the lock is this thread's) */
|
||||
focus_locked(screen, pane, lr);
|
||||
return;
|
||||
}
|
||||
const int mine = TryAcquireSRWLockExclusive(&mouse_lock);
|
||||
AcquireSRWLockExclusive(&pending_lock);
|
||||
pending.screen = screen, pending.pane = pane, pending.lr = lr, pending.set = !mine; /* (a newer one than any kept) */
|
||||
ReleaseSRWLockExclusive(&pending_lock);
|
||||
if (!mine) return;
|
||||
focus_locked(screen, pane, lr);
|
||||
ReleaseSRWLockExclusive(&mouse_lock);
|
||||
}
|
||||
/* (mouse_tick, under mouse_lock) the focus change kept for it, if any */
|
||||
static void focus_pending(void) {
|
||||
AcquireSRWLockExclusive(&pending_lock);
|
||||
const int set = pending.set;
|
||||
const uint64_t screen = pending.screen, pane = pending.pane, lr = pending.lr;
|
||||
pending.set = 0;
|
||||
ReleaseSRWLockExclusive(&pending_lock);
|
||||
if (set) focus_locked(screen, pane, lr);
|
||||
}
|
||||
static void focus_locked(uint64_t screen, uint64_t pane, uint64_t lr) {
|
||||
if (screen != pause_screen_now()) InterlockedExchange64(&pause_screen, (LONG64)screen), InterlockedExchange(&ticks, 0);
|
||||
uint8_t flags = 0;
|
||||
peek(pane + 65, &flags, 1);
|
||||
const uint64_t at = (flags & 0x20) ? peek64(pane + 32) + 48 : pane + 32;
|
||||
const uint64_t obj = peek64(at);
|
||||
focus_page = obj;
|
||||
focused_button = pane, asked = 0;
|
||||
/* (f_807923a0's name: obj+128 -> +248 -> +24) */
|
||||
char a[96], b[64];
|
||||
{
|
||||
static const char *const pages[] = {"PaCollectMenu_00", "PaEquipmentMenu_00", "PaItemMenu_00", "PaSystemMenu_00"};
|
||||
const char *page = text_at(peek64(peek64(peek64(obj + 128) + 248) + 24), a, sizeof a);
|
||||
for (int i = 0; i < 4; i++)
|
||||
if (!strcmp(page, pages[i])) page_now = i;
|
||||
}
|
||||
if (!trace) return;
|
||||
hos_log("menu: focus (caller %#llx, tick %u) screen %#llx pane %#llx %s page %#llx %s; owner screen %#llx",
|
||||
(unsigned long long)lr, (unsigned)ticks, (unsigned long long)screen, (unsigned long long)pane,
|
||||
text_at(peek64(pane + 0x18), b, sizeof b), (unsigned long long)obj,
|
||||
text_at(peek64(peek64(peek64(obj + 128) + 248) + 24), a, sizeof a),
|
||||
(unsigned long long)peek64(peek64(pane + 32) + 40));
|
||||
}
|
||||
|
||||
/* ---- the mouse. The layout's units: 3840 x 2160, the origin at the screen's centre, y up; the window shows it fit
|
||||
(the larger of the two scales) and centred */
|
||||
void hos_mouse_game_menu(void); /* (display.c) */
|
||||
void hos_mouse_game_menu_gone(void);
|
||||
int hos_mouse_game_pointer(int *x, int *y, int *w, int *h, uint32_t *pressed, int *wheel);
|
||||
void hos_hid_tap(const char *press); /* (nn_hid.c) */
|
||||
void hos_hid_stick(int lx, int ly, int rx, int ry, int hold_ms);
|
||||
void hos_hid_drag(int dx, int dy, int right); /* (nn_hid.c: as the camera's mouse; the left stick or the right) */
|
||||
/* The panel of Key Items, Threads of Time and Map (Minus opens it; L to the left, R to the right; pages 0, 1, 2), as
|
||||
the screens told apart by vtable: Key Items' screen 0x84c07798 and Threads of Time's
|
||||
0x84c04a18 (its list of threads: N_SlideList_00, the framework's buttons) each run only while their page is shown;
|
||||
the Map page has no screen of its own: the panel's frame 0x84c08aa0 runs alone (it runs under the pause menu too).
|
||||
The mouse is the page's while it is shown (no focused button on Key Items or the Map: the stones, the floors and the
|
||||
world map are not the framework's buttons). 0x84c08300, its 30 Pa_MelodyIcon_00, is the game's HUD of songs */
|
||||
#define PANEL_FRAME_VTABLE 0x84c08aa0ULL
|
||||
static volatile int map_page; /* (hos_oot_menu_tick: the frame runs, and neither other page nor the pause menu) */
|
||||
static int panel_page_vt(uint64_t vt) {
|
||||
return vt == 0x84c07798ULL ? 0 : vt == 0x84c04a18ULL ? 1 : vt == PANEL_FRAME_VTABLE && map_page ? 2 : -1;
|
||||
}
|
||||
static int panel_page(uint64_t screen) { return panel_page_vt(peek64(screen)); }
|
||||
/* The game's HUD screen (0x84c08300, the songs' icons; it runs through the play) holds the map page's floors (a
|
||||
search of memory, in Lord Jabu-Jabu's Belly): +0x1368 the floor chosen (2F 1, 1F 0, B1 -1), +0x136c how
|
||||
many floors, +0x1370 the lowest; the top is the lowest + the count - 1. Kept as the screens are seen */
|
||||
#define HUD_SCREEN_VTABLE 0x84c08300ULL
|
||||
/* (Triforce) The game's own Options screen (the layout SystemOption_00; the title's Options and the pause menu's are the one
|
||||
screen), by its vtable (HOS_MENU_TRACE in a headless run, 2026-11-10: the screen of 15 entries that starts to run when
|
||||
Options is chosen, from the title and from the pause menu alike, and stops with Back; L and R do nothing on it). While
|
||||
it runs the renderer is told each frame (rx_option_set HOS_OPT_GAME_OPTIONS): the menu draws its tabs over this
|
||||
screen's header, the game's own list the first of them (gpu/vk/vk_menu.cpp), and nn_hid.c passes Back on when one of
|
||||
our tabs is left with it. HOS_OPTIONS_TABS=0 keeps the renderer untold */
|
||||
#define OPTIONS_SCREEN_VTABLE 0x84c0f108ULL
|
||||
static volatile LONG64 options_seen_ns;
|
||||
void rx_option_set(int id, int value); /* rx_backend.c */
|
||||
int hos_oot_options_front(void) {
|
||||
const LONG64 t = InterlockedCompareExchange64(&options_seen_ns, 0, 0);
|
||||
return t && (LONG64)hos_now_ns() - t < 200000000LL;
|
||||
}
|
||||
static volatile uint64_t hud_screen;
|
||||
static int map_floors(int *cur, int *top, int *bottom) {
|
||||
int32_t f[3];
|
||||
if (!hud_screen || !peek(hud_screen + 0x1368, f, sizeof f) || f[1] < 1 || f[1] > 12) return 0;
|
||||
*cur = f[0], *bottom = f[2], *top = f[2] + f[1] - 1;
|
||||
return *cur >= *bottom && *cur <= *top;
|
||||
}
|
||||
|
||||
typedef struct { float x0, y0, x1, y1; } Rect;
|
||||
/* (Key Items' items, in their grid's order: item_found puts the page's own positions of them in) */
|
||||
static const char *const item_keys[9] = {"Item_Medal_Shadow", "Item_Medal_Light", "Item_Medal_Forest", "Item_Stone_Forest",
|
||||
"Item_Stone_Fire", "Item_Stone_Water", "Item_Medal_Spirit", "Item_Medal_Water",
|
||||
"Item_Medal_Fire"};
|
||||
static void item_found(const char *key, float x, float y, void *arg) {
|
||||
struct { int *found; float *x, *y; } *a = arg;
|
||||
for (int i = 0; i < 9; i++) {
|
||||
/* (the game's strings hold a length: the text need not end in a NUL, so the key's end is where a name's can't go) */
|
||||
const size_t n = strlen(item_keys[i]);
|
||||
const char after = key[n];
|
||||
if (!strncmp(key, item_keys[i], n) && !isalnum((unsigned char)after) && after != '_')
|
||||
*a->found |= 1 << i, a->x[i] = x, a->y[i] = y;
|
||||
}
|
||||
}
|
||||
/* a button's rectangle in the layout's units (0 when it has none or is hidden) */
|
||||
static int button_rect(uint64_t button, Rect *r);
|
||||
|
||||
typedef struct { float x, y; uint64_t hit; float area; int n; uint64_t button[128]; Rect rect[128]; } Hit;
|
||||
static void shown_entry(int i, uint64_t entry, uint64_t button, void *arg) {
|
||||
(void)i, (void)entry;
|
||||
Hit *h = arg;
|
||||
if (h->n < 128 && button_rect(button, &h->rect[h->n])) h->button[h->n++] = button;
|
||||
}
|
||||
|
||||
/* The boxes as the mouse takes them, from the game's: a box under 100 x 100 (the title's: 60 x 60, a cursor's mark at the
|
||||
middle of a line of text) made 1100 wide; then boxes one above the other (centres less than 60 apart across) grown to
|
||||
meet halfway across a gap under 240, and the column's ends by as much as the gap they have (no dead lines between
|
||||
the rows of a list, and its first and last rows as tall as the others) */
|
||||
static void list_boxes(Hit *h) {
|
||||
for (int i = 0; i < h->n; i++) {
|
||||
Rect *r = &h->rect[i];
|
||||
if (r->x1 - r->x0 < 100 && r->y1 - r->y0 < 100) {
|
||||
const float cx = (r->x0 + r->x1) / 2;
|
||||
r->x0 = cx - 550, r->x1 = cx + 550;
|
||||
}
|
||||
}
|
||||
Rect out[128];
|
||||
for (int i = 0; i < h->n; i++) {
|
||||
const Rect *r = &h->rect[i];
|
||||
const float cx = (r->x0 + r->x1) / 2;
|
||||
float above = -1, below = -1; /* (the gaps to the nearest box above and below in the column) */
|
||||
for (int j = 0; j < h->n; j++) {
|
||||
const Rect *o = &h->rect[j];
|
||||
const float ox = (o->x0 + o->x1) / 2;
|
||||
if (j == i || ox - cx > 60 || cx - ox > 60) continue;
|
||||
const float up = o->y0 - r->y1, down = r->y0 - o->y1;
|
||||
if (up >= 0 && up < 240 && (above < 0 || up < above)) above = up;
|
||||
if (down >= 0 && down < 240 && (below < 0 || down < below)) below = down;
|
||||
}
|
||||
out[i] = *r;
|
||||
if (above >= 0) out[i].y1 += above / 2;
|
||||
if (below >= 0) out[i].y0 -= below / 2;
|
||||
if (above >= 0 && below < 0) out[i].y0 -= above / 2; /* (an end of the column) */
|
||||
if (below >= 0 && above < 0) out[i].y1 += below / 2;
|
||||
}
|
||||
memcpy(h->rect, out, (size_t)h->n * sizeof *out);
|
||||
}
|
||||
|
||||
static void hit_test(uint64_t screen, Hit *h) {
|
||||
h->n = 0, h->hit = 0;
|
||||
each_entry(screen, 400, shown_entry, h);
|
||||
list_boxes(h);
|
||||
if (h->y > -1080 && h->y < -960 && h->x >= 1600 && h->x < 1900) return; /* (the "Back" prompt's: no button's) */
|
||||
for (int i = 0; i < h->n; i++) {
|
||||
const Rect *r = &h->rect[i];
|
||||
if (h->x < r->x0 || h->x > r->x1 || h->y < r->y0 || h->y > r->y1) continue;
|
||||
const float area = (r->x1 - r->x0) * (r->y1 - r->y0);
|
||||
if (!h->hit || area < h->area) h->hit = h->button[i], h->area = area; /* (the smallest: a slot inside a panel) */
|
||||
}
|
||||
}
|
||||
|
||||
/* The tab bar across the top (no buttons of the screen's list: the pages' names and the L and R signs), in the layout's
|
||||
units, measured from the menu as shown (the Items page): the names centred at about -696, -228, 240, 708 (468 apart),
|
||||
L at -1002 and R at 1014; the boxes meet halfway between */
|
||||
enum { TAB_L = 4, TAB_R = 5 };
|
||||
static int tab_at(float x, float y) {
|
||||
if (y < 900 || y > 1080) return -1;
|
||||
if (x >= -1100 && x < -926) return TAB_L;
|
||||
if (x >= -926 && x < 942) return x < -462 ? 0 : x < 6 ? 1 : x < 474 ? 2 : 3;
|
||||
if (x >= 942 && x <= 1100) return TAB_R;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static void focus_entry(int i, uint64_t entry, uint64_t button, void *arg); /* (below: a focused button shown) */
|
||||
|
||||
/* The mouse's state below is one, and the screens' updates run on several of the game's threads: one at a time (a
|
||||
frame the lock is busy is passed, not waited for); the focus hook's writes take it too */
|
||||
static SRWLOCK mouse_lock = SRWLOCK_INIT;
|
||||
static void mouse_tick_locked(Ctx *c, uint64_t screen);
|
||||
/* (mouse_owner: the thread in mouse_tick: the game's focus handler may run inside its setter) */
|
||||
static void mouse_tick(Ctx *c, uint64_t screen) {
|
||||
if (!TryAcquireSRWLockExclusive(&mouse_lock)) return;
|
||||
mouse_owner = GetCurrentThreadId();
|
||||
focus_pending();
|
||||
mouse_tick_locked(c, screen);
|
||||
mouse_owner = 0;
|
||||
ReleaseSRWLockExclusive(&mouse_lock);
|
||||
}
|
||||
/* The R button's item choice (0x84c0d430, N_SlideList_00: a carousel of the items in a row, shown while R is held in
|
||||
play, turned by the D-pad's or the left stick's left and right, not wrapping; its items move from one end to the
|
||||
other as it turns, so no row stays the next). The mouse stays the camera's (the menu does not free it: no cursor, no
|
||||
pointing); the wheel turns it (hos_mouse_wheel_take, captured or not): the D-pad's right (the wheel down) or left, a
|
||||
notch each. Each press after the last one queued has been let go (60 ms down, 60 up: a notch the next frame would
|
||||
otherwise press while the last is held, and the game sees one press), at most 0.72 s ahead, so the row stops soon
|
||||
after the wheel */
|
||||
#define ITEM_CHOICE_VTABLE 0x84c0d430ULL
|
||||
int hos_mouse_wheel_take(void); /* (display.c) */
|
||||
static void item_choice_tick(void) {
|
||||
static int64_t dpad_free_ns; /* (when the last press queued here has been let go) */
|
||||
const int wheel = hos_mouse_wheel_take();
|
||||
if (!wheel) return;
|
||||
const int64_t now = hos_now_ns();
|
||||
const int k = wheel < 0 ? -wheel : wheel;
|
||||
char taps[128];
|
||||
int n = 0;
|
||||
if (dpad_free_ns < now) dpad_free_ns = now;
|
||||
for (int i = 0; i < k && i < 6 && dpad_free_ns - now < 720000000; i++) {
|
||||
n += snprintf(taps + n, sizeof taps - (size_t)n, "%s%.3f:%s/60", n ? "," : "", (double)(dpad_free_ns - now) / 1e9,
|
||||
wheel < 0 ? "RIGHT" : "LEFT");
|
||||
dpad_free_ns += 120000000;
|
||||
}
|
||||
if (n) hos_hid_tap(taps);
|
||||
if (trace) hos_log("menu: wheel %d: the item choice turned %s", wheel, wheel < 0 ? "right" : "left");
|
||||
}
|
||||
|
||||
static void mouse_tick_locked(Ctx *c, uint64_t screen) {
|
||||
if (peek64(screen) == ITEM_CHOICE_VTABLE) {
|
||||
item_choice_tick();
|
||||
return;
|
||||
}
|
||||
hos_mouse_game_menu();
|
||||
int px, py, w, h, wheel;
|
||||
uint32_t pressed;
|
||||
const int got = hos_mouse_game_pointer(&px, &py, &w, &h, &pressed, &wheel);
|
||||
if (!got) return;
|
||||
const int hidden = got == 2; /* (the cursor hidden while the pad is in use: the wheel only, no pointing) */
|
||||
const int pause = screen == pause_screen_now();
|
||||
const float scale = 3840.0f / (float)w > 2160.0f / (float)h ? 3840.0f / (float)w : 2160.0f / (float)h;
|
||||
static Hit hit;
|
||||
hit.x = (float)(px - w / 2) * scale, hit.y = (float)(h / 2 - py) * scale, hit.hit = 0;
|
||||
static int last_x = -1, last_y = -1;
|
||||
int moved = !hidden && (px != last_x || py != last_y);
|
||||
if (!hidden) last_x = px, last_y = py;
|
||||
/* The panel's pages: the left button dragged pans the map and the tapestry (the left stick, against the drag: the
|
||||
picture follows the mouse) and turns Key Items' stone (the right stick, with the drag), as the camera's mouse
|
||||
turns it (hos_hid_drag); pressed and let go without a drag it is a click, at its release. The middle button is Y
|
||||
on the map (the world map and back). The wheel off a list zooms (the right stick up or down, 0.12 s a notch:
|
||||
the world map's two steps) */
|
||||
const int page = panel_page(screen), map = page == 2, keys = page == 0;
|
||||
/* The pause menu's Items page: the chosen item's model at the right, turned left and right by the right stick (as
|
||||
Key Items' stones are): a drag there turns it, off the buttons; the page's slots at the left (to x about 100),
|
||||
the tabs above (y 900), the prompts below (-960) */
|
||||
const int item_model = pause && page_now == 2, pan = page >= 0 || item_model;
|
||||
static int ldown, ldrag, lx0, ly0, llx, lly;
|
||||
if (pan) {
|
||||
const int held = (GetAsyncKeyState(VK_LBUTTON) & 0x8000) != 0;
|
||||
const int was_down = ldown;
|
||||
int grab = !item_model;
|
||||
if (item_model && (pressed & HOS_MOUSE_LEFT) && !ldown && hit.x > 300 && hit.x < 1900 && hit.y > -900 && hit.y < 880) {
|
||||
hit_test(screen, &hit);
|
||||
grab = !hit.hit;
|
||||
}
|
||||
if ((pressed & HOS_MOUSE_LEFT) && !ldown && grab) ldown = 1, ldrag = 0, lx0 = llx = px, ly0 = lly = py;
|
||||
if (ldown) pressed &= ~(uint32_t)HOS_MOUSE_LEFT; /* (a click is at the release) */
|
||||
if (ldown && held) {
|
||||
if (!ldrag && (px - lx0 > 6 || lx0 - px > 6 || py - ly0 > 6 || ly0 - py > 6)) {
|
||||
ldrag = 1;
|
||||
if (trace) hos_log("menu: drag from (%d, %d)", lx0, ly0);
|
||||
}
|
||||
if (ldrag && (px != llx || py != lly)) { /* (against the drag: the picture follows the mouse) */
|
||||
if (keys) hos_hid_drag(px - llx, -(py - lly), 1);
|
||||
else if (item_model) hos_hid_drag(px - llx, 0, 1); /* (left and right only) */
|
||||
else hos_hid_drag(-(px - llx), py - lly, 0);
|
||||
static int64_t logged;
|
||||
if (trace && hos_now_ns() - logged > 250000000)
|
||||
logged = hos_now_ns(), hos_log("menu: drag: %d, %d pixels", px - llx, py - lly);
|
||||
}
|
||||
llx = px, lly = py;
|
||||
} else if (ldown && was_down) {
|
||||
if (!ldrag) { /* (a click: where it was pressed) */
|
||||
pressed |= HOS_MOUSE_LEFT;
|
||||
px = lx0, py = ly0;
|
||||
hit.x = (float)(px - w / 2) * scale, hit.y = (float)(h / 2 - py) * scale;
|
||||
}
|
||||
if (trace) hos_log("menu: left button up: %s", ldrag ? "the drag's end" : "a click");
|
||||
ldown = 0;
|
||||
}
|
||||
if (map && (pressed & HOS_MOUSE_MIDDLE)) hos_hid_tap("0:Y/80");
|
||||
if (ldown) moved = 0; /* (no hover while dragging) */
|
||||
}
|
||||
/* the wheel: the pause menu's pages (L, R). Elsewhere it scrolls a list: the focus to the row shown last that way
|
||||
(the lowest for down), then the pad's down (up) a notch each, which moves the list on by a row as at its end;
|
||||
then the focus back to the row the mouse is over */
|
||||
static int64_t refocus_ns;
|
||||
static uint64_t scroll_row; /* (the row the wheel gave the focus, out of view) */
|
||||
static float scroll_lo, scroll_hi;
|
||||
const int64_t now = hos_now_ns();
|
||||
if (wheel) {
|
||||
char taps[128];
|
||||
int n = 0;
|
||||
const int k = wheel < 0 ? -wheel : wheel;
|
||||
float at = 0;
|
||||
int list = !keys, pan_off = keys; /* (the wheel scrolls a list, or turns the pages; nothing on Key Items) */
|
||||
/* The Map page, anywhere: a dungeon's floors (the pad's up and down, a notch each) and the world map's zoom (the
|
||||
right stick, below): each view takes its own and lets the other be (the world map has nothing on the pad's up
|
||||
and down). The view shown is not known */
|
||||
if (map) {
|
||||
const char *dir = wheel > 0 ? "UP" : "DOWN";
|
||||
for (int i = 0; i < k && i < 4; i++)
|
||||
n += snprintf(taps + n, sizeof taps - (size_t)n, "%s%.2f:%s/75", n ? "," : "", i * 0.25, dir);
|
||||
if (trace) hos_log("menu: map wheel %d: the floors (%s) and the zoom", wheel, dir);
|
||||
list = 0;
|
||||
}
|
||||
if ((map || page == 1) && !pan_off) { /* (off the list, or no row of it focused: the world map's, the tapestry's: the zoom) */
|
||||
int focused = 0;
|
||||
each_entry(screen, 400, focus_entry, &focused);
|
||||
/* (Threads of Time: its list focused, the wheel scrolls it wherever the mouse is; the tapestry shown (the
|
||||
list without a focused row) zooms. The map: the list's rows under the mouse scroll it, else the zoom) */
|
||||
if (focused && page != 1) hit_test(screen, &hit);
|
||||
if (!focused || (page != 1 && !hit.hit)) {
|
||||
hos_hid_stick(0, 0, 0, wheel > 0 ? 32767 : -32767, 120 * (k < 6 ? k : 6)), list = 0;
|
||||
if (trace) hos_log("menu: map wheel %d: the zoom (right stick %s for %d ms)", wheel, wheel > 0 ? "up" : "down", 120 * (k < 6 ? k : 6));
|
||||
}
|
||||
hit.hit = 0;
|
||||
}
|
||||
if (list && !pause) {
|
||||
/* A list's rows in their order down the screen. The wheel's target is the row the pad's down would bring
|
||||
in from the lowest row shown (up: the highest), a notch each: the first rows off the screen that way (a
|
||||
scrolled list lays out all its items, or keeps a spare row for the next). Given the focus, the list
|
||||
scrolls it in, without the pad's sound; the focus goes back to the row under the mouse once the list has
|
||||
moved. With no row off the screen that way (a short list: a dungeon's floors, or a list's end) the focus
|
||||
steps from the focused row to the next, and stays */
|
||||
hit_test(screen, &hit);
|
||||
int order[128], n_rows = 0, at_focus = -1;
|
||||
for (int i = 0; i < hit.n; i++) {
|
||||
int j = n_rows++;
|
||||
const float cy = (hit.rect[i].y0 + hit.rect[i].y1) / 2;
|
||||
while (j > 0 && (hit.rect[order[j - 1]].y0 + hit.rect[order[j - 1]].y1) / 2 < cy) order[j] = order[j - 1], j--;
|
||||
order[j] = i;
|
||||
}
|
||||
for (int j = 0; j < n_rows; j++) {
|
||||
uint8_t st = 0;
|
||||
peek(hit.button[order[j]] + 56, &st, 1);
|
||||
if (st && at_focus < 0) at_focus = j;
|
||||
}
|
||||
const int step = wheel < 0 ? 1 : -1, want = (k < 3 ? k : 3) * step;
|
||||
/* (the rows in view: the screen's height, or Threads of Time's list frame, y -756 to 594 (from the page as
|
||||
shown): the game takes a row as shown once its centre is in it, and scrolls a focused row only that far) */
|
||||
const int threads = peek64(screen) == 0x84c04a18ULL;
|
||||
const float view_lo = threads ? -760.0f : -1080.0f, view_hi = threads ? 598.0f : 1080.0f;
|
||||
int first = -1, last = -1; /* (the rows shown: their first and last in the order) */
|
||||
for (int j = 0; j < n_rows; j++) {
|
||||
const float cy = (hit.rect[order[j]].y0 + hit.rect[order[j]].y1) / 2;
|
||||
if (cy >= view_lo && cy <= view_hi) last = j, first = first < 0 ? j : first;
|
||||
}
|
||||
int to = -1;
|
||||
if (first >= 0 && step > 0 && last + 1 < n_rows) to = last + want < n_rows ? last + want : n_rows - 1;
|
||||
else if (first >= 0 && step < 0 && first > 0) to = first + want >= 0 ? first + want : 0;
|
||||
else if (at_focus >= 0) {
|
||||
to = at_focus + want;
|
||||
if (to >= n_rows) to = n_rows - 1;
|
||||
if (to < 0) to = 0;
|
||||
}
|
||||
if (to >= 0 && to != at_focus) {
|
||||
const Rect *r = &hit.rect[order[to]];
|
||||
const float cy = (r->y0 + r->y1) / 2;
|
||||
set_focus(c, screen, hit.button[order[to]]);
|
||||
if (trace) hos_log("menu: wheel %d: the focus from row %d to %d of %d (y %.0f)%s", wheel, at_focus, to, n_rows, cy,
|
||||
cy < view_lo || cy > view_hi ? ", out of view: the list moves" : "");
|
||||
if (cy < view_lo || cy > view_hi) /* (then the row under the mouse, once the list has brought it into view) */
|
||||
refocus_ns = now + 1200000000, scroll_row = hit.button[order[to]], scroll_lo = view_lo, scroll_hi = view_hi, asked = 0;
|
||||
else asked = hit.button[order[to]]; /* (the hover leaves it be until the mouse moves on) */
|
||||
}
|
||||
hit.hit = 0;
|
||||
list = 0; /* (no pad presses) */
|
||||
}
|
||||
for (int i = 0; list && i < k && i < 6; i++)
|
||||
n += snprintf(taps + n, sizeof taps - (size_t)n, "%s%.2f:%s/60", n ? "," : "", at + i * 0.12,
|
||||
pause ? (wheel > 0 ? "L" : "R") : (wheel > 0 ? "UP" : "DOWN"));
|
||||
if (n) hos_hid_tap(taps);
|
||||
}
|
||||
/* (the list has moved under the mouse: the row the wheel gave the focus is in view, as the list scrolls at its own
|
||||
pace; at most 1.2 s on. Taken back sooner, the scroll stopped short of it) */
|
||||
if (refocus_ns && scroll_row) {
|
||||
Rect r;
|
||||
const float cy = button_rect(scroll_row, &r) ? (r.y0 + r.y1) / 2 : 0;
|
||||
if (cy >= scroll_lo && cy <= scroll_hi) refocus_ns = now;
|
||||
}
|
||||
if (refocus_ns && now >= refocus_ns) refocus_ns = 0, scroll_row = 0, moved = 1, asked = 0;
|
||||
if (moved || (pressed & HOS_MOUSE_LEFT)) hit_test(screen, &hit);
|
||||
else hit.hit = 0;
|
||||
/* hover: the focus to the button under the mouse, only as it moves (the pad keeps the focus it moved) */
|
||||
int just = 0;
|
||||
uint8_t state = 0;
|
||||
if (hit.hit) peek(hit.hit + 56, &state, 1); /* (0: not focused) */
|
||||
if (hit.hit && hit.hit != focused_button && hit.hit != asked && !state) {
|
||||
asked = hit.hit, just = 1;
|
||||
const int r = set_focus(c, screen, hit.hit);
|
||||
if (trace) {
|
||||
char name[64];
|
||||
hos_log("menu: mouse (%.0f, %.0f): the focus to %s (%d) on screen %#llx", hit.x, hit.y,
|
||||
text_at(peek64(hit.hit + 0x18), name, sizeof name), r, (unsigned long long)screen);
|
||||
}
|
||||
}
|
||||
/* a click on the tabs: L or R pressed as many times as the pages between (one at a time, as the pages slide) */
|
||||
if (pause && (pressed & HOS_MOUSE_LEFT) && !hit.hit) {
|
||||
const int tab = tab_at(hit.x, hit.y);
|
||||
if (tab == TAB_L || tab == TAB_R) hos_hid_tap(tab == TAB_L ? "0:L/120" : "0:R/120");
|
||||
else if (tab >= 0 && page_now >= 0 && tab != page_now) tab_goal = tab, tab_pages = 4, goal_ns = now, tab_from = -9;
|
||||
if (trace && tab != -1) hos_log("menu: mouse (%.0f, %.0f): tab %d from page %d", hit.x, hit.y, tab, page_now);
|
||||
}
|
||||
/* A tab clicked (the pause menu's, the panel's): L or R one at a time toward it, the next once the page has come and
|
||||
settled (0.25 s: a press while a page slides in is lost); given up after 4 s */
|
||||
{
|
||||
static int last_cur = -9;
|
||||
static int64_t arrive_ns;
|
||||
const int cur = pause ? page_now : page;
|
||||
if (cur != last_cur) last_cur = cur, arrive_ns = now;
|
||||
if (tab_goal >= 0 && (cur < 0 || now - goal_ns > 4000000000LL)) tab_goal = -1;
|
||||
if (tab_goal >= 0) {
|
||||
if (cur == tab_goal) tab_goal = -1;
|
||||
else if (cur != tab_from && now - arrive_ns > 250000000) {
|
||||
const int d = tab_goal - cur;
|
||||
if (tab_pages == 4) hos_hid_tap(d < 0 ? "0:L/120" : "0:R/120");
|
||||
else hos_hid_tap(d < 0 ? "0:L/75" : "0:R/75"); /* (the panel: 75 ms, not into the next page) */
|
||||
if (trace) hos_log("menu: tab: page %d toward %d: %s", cur, tab_goal, d < 0 ? "L" : "R");
|
||||
tab_from = cur;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Key Items: the stones and the medallions (not the framework's buttons). The item chosen is the page's own key of
|
||||
it, a string at *(screen+760) (Item_Medal_Fire, Item_Stone_Water, ...; an empty slot has its key too). The page
|
||||
moves its choice with the left stick (A and D on the keyboard) on a 3 x 3 grid:
|
||||
Item_Medal_Shadow Item_Medal_Light Item_Medal_Forest
|
||||
Item_Stone_Forest Item_Stone_Fire Item_Stone_Water
|
||||
Item_Medal_Spirit Item_Medal_Water Item_Medal_Fire
|
||||
and a press off the grid's edge leaves the page (to the pause menu). With the medallions (an adult's page) the
|
||||
items sit in a ring round the stones; without (a child's) only the stones are shown, further apart. The key is
|
||||
the page's whole choice: each frame its update places the cursor from it, and its stick only works out the next
|
||||
key and copies it in. So the mouse moved onto an item sets that item's key and calls the page's own refresh
|
||||
(set_item_key: as the page does when it opens), silently; a click on an item is Details (A) for it, once it is
|
||||
the one chosen (given up after 2 s). Positions: the item's centre in the layout's units, from the pages as
|
||||
shown (1280 x 720 screenshots) */
|
||||
if (keys) {
|
||||
static const struct { const char *key; int row, col; float x, y, cx; } items[] = {
|
||||
{"Item_Medal_Shadow", 0, 0, -750, 294, 0}, {"Item_Medal_Light", 0, 1, 0, 660, 0}, {"Item_Medal_Forest", 0, 2, 744, 294, 0},
|
||||
{"Item_Stone_Forest", 1, 0, -429, -24, -640}, {"Item_Stone_Fire", 1, 1, 0, -15, 0}, {"Item_Stone_Water", 1, 2, 429, -6, 650},
|
||||
{"Item_Medal_Spirit", 2, 0, -756, -354, 0}, {"Item_Medal_Water", 2, 1, 0, -714, 0}, {"Item_Medal_Fire", 2, 2, 759, -354, 0}};
|
||||
enum { N_ITEMS = (int)(sizeof items / sizeof *items) };
|
||||
static int adult; /* (the ring is shown; worked out again when the page has been away) */
|
||||
static int64_t keys_ns;
|
||||
static float px_[N_ITEMS], py_[N_ITEMS];
|
||||
static int found; /* (the items' panes the game found) */
|
||||
if (now - keys_ns > 1000000000) {
|
||||
/* The page shown anew: the layout from the items' panes, found as the page finds them to place its glow;
|
||||
the Emerald's x tells them apart (a child's wider row: about -680, the ring's -430). The panes' positions
|
||||
are their parent's, about 200 below the items as drawn: the hit boxes stay those measured above */
|
||||
adult = 0, found = 0;
|
||||
struct { int *found; float *x, *y; } at_ = {&found, px_, py_};
|
||||
item_panes(c, screen, item_found, &at_);
|
||||
if (found & (1 << 3)) adult = px_[3] > -540.0f;
|
||||
if (trace) {
|
||||
char line[600];
|
||||
int n = snprintf(line, sizeof line, "menu: Key Items' panes (%s):", adult ? "the ring" : "the stones' row");
|
||||
for (int i = 0; i < N_ITEMS && n < (int)sizeof line - 40; i++)
|
||||
n += found & (1 << i) ? snprintf(line + n, sizeof line - (size_t)n, " %s %.0f,%.0f", items[i].key + 5, px_[i], py_[i])
|
||||
: snprintf(line + n, sizeof line - (size_t)n, " %s -", items[i].key + 5);
|
||||
hos_log("%s", line);
|
||||
}
|
||||
}
|
||||
keys_ns = now;
|
||||
static int64_t click_ns;
|
||||
static int click_item = -1;
|
||||
char key[40] = "";
|
||||
int at = -1, want = -1;
|
||||
{
|
||||
const uint64_t p = peek64(screen + 760);
|
||||
if (p && peek(p, key, sizeof key - 1)) key[sizeof key - 1] = 0;
|
||||
for (int i = 0; i < N_ITEMS; i++)
|
||||
if (!strcmp(key, items[i].key)) at = i;
|
||||
if (at >= 0 && items[at].row != 1) adult = 1;
|
||||
}
|
||||
float best = 0;
|
||||
for (int i = 0; i < N_ITEMS; i++) {
|
||||
if (!adult && items[i].row != 1) continue; /* (a child's page: the stones alone) */
|
||||
const float ix = adult || !items[i].cx ? items[i].x : items[i].cx, iy = items[i].y, r = adult ? 190.0f : 240.0f;
|
||||
const float dx = hit.x - ix, dy = hit.y - iy, d = dx * dx + dy * dy;
|
||||
if (d < r * r && (want < 0 || d < best)) want = i, best = d;
|
||||
}
|
||||
if ((pressed & HOS_MOUSE_LEFT) && want >= 0) {
|
||||
click_item = want, click_ns = now;
|
||||
pressed &= ~(uint32_t)HOS_MOUSE_LEFT; /* (a click on an item is this, not the tabs' or the prompts') */
|
||||
}
|
||||
if (click_item >= 0 && now - click_ns > 2000000000LL) click_item = -1;
|
||||
if (click_item >= 0 && at == click_item) {
|
||||
hos_hid_tap("0:A/75");
|
||||
if (trace) hos_log("menu: Key Items: %s clicked: A", key);
|
||||
click_item = -1;
|
||||
}
|
||||
/* (the mouse moved onto an item, or clicked one: the stick may move the choice away while the mouse rests) */
|
||||
const int to = click_item >= 0 ? click_item : moved && !ldown ? want : -1;
|
||||
if (to >= 0 && at >= 0 && to != at) {
|
||||
const int r = set_item_key(c, screen, items[to].key);
|
||||
if (trace) hos_log("menu: Key Items: %s chosen, the mouse over %s: set %s", key, items[to].key, r ? "" : "(not now)");
|
||||
}
|
||||
}
|
||||
/* The map's page (no buttons of the screen's list for these; in the layout's units, from its screens as shown,
|
||||
measured): the prompts at the bottom right ("World Map" / "Current Location" with Y, "Back" with B) and the tab
|
||||
bar of its panel (Key Items, Threads of Time, Map; L and R): the map's screen has the mouse while the Map page
|
||||
is shown, so a tab is that many pages from it */
|
||||
if (page >= 0 && (pressed & HOS_MOUSE_LEFT) && !hit.hit) {
|
||||
char tap[256] = "";
|
||||
if (hit.y > -1080 && hit.y < -960) { /* (the Y prompt: World Map / Current Location, See Tapestry) */
|
||||
if (page >= 1 && hit.x > 1040 && hit.x < 1570) strcpy(tap, "0:Y/75");
|
||||
} else if (map && hit.x > 1400 && hit.x < 1880 && hit.y > -960 && hit.y < -560) {
|
||||
strcpy(tap, "0:Y/75"); /* (an area's map, not a dungeon's: its World Map picture and prompt above Back) */
|
||||
} else if (map && hit.x > -1850 && hit.x < -1200 && hit.y < 700 && hit.y > -1000) {
|
||||
/* A dungeon's floors (not the framework's buttons): the rows 142 apart, the list centred at y -119 (from the
|
||||
screens as shown: Lord Jabu-Jabu's 3 floors' top row at y 23; the Water Temple's 4 sit half a row higher):
|
||||
the floor of the row clicked, and the pad's up or down as many times as it is from the floor chosen
|
||||
(map_floors). A row past the last floor is the last */
|
||||
int cur, top, bottom;
|
||||
if (map_floors(&cur, &top, &bottom)) {
|
||||
const float top_y = -119.0f + (float)(top - bottom) * 71.0f;
|
||||
int row = (int)((top_y - hit.y) / 142.0f + 0.5f);
|
||||
if (row < 0) row = 0;
|
||||
int want = top - row;
|
||||
if (want < bottom) want = bottom;
|
||||
const int steps = want - cur;
|
||||
for (int i = 0, n = 0; i < (steps < 0 ? -steps : steps) && n < (int)sizeof tap - 16; i++)
|
||||
n += snprintf(tap + n, sizeof tap - (size_t)n, "%s%.2f:%s/60", n ? "," : "", i * 0.15, steps > 0 ? "UP" : "DOWN");
|
||||
if (trace) hos_log("menu: map floors %d..%d, floor %d; row %d clicked: floor %d", bottom, top, cur, row, want);
|
||||
}
|
||||
} else if (hit.y > 900 && hit.y < 1080) { /* (the tabs: Key Items, Threads of Time, Map; L and R) */
|
||||
if (hit.x >= -1100 && hit.x < -850) strcpy(tap, "0:L/75");
|
||||
else if (hit.x >= 850 && hit.x < 1100) strcpy(tap, "0:R/75");
|
||||
else { /* (L to the left, R to the right: stepped toward it, above) */
|
||||
const int to = hit.x >= -850 && hit.x < -300 ? 0 : hit.x >= -300 && hit.x < 345 ? 1 : hit.x >= 345 && hit.x < 850 ? 2 : page;
|
||||
if (to != page) tab_goal = to, tab_pages = 3, goal_ns = now, tab_from = -9;
|
||||
}
|
||||
}
|
||||
if (tap[0]) hos_hid_tap(tap);
|
||||
if (trace) hos_log("menu: panel page %d click (%.0f, %.0f): %s", page, hit.x, hit.y, tap[0] ? tap : "-");
|
||||
}
|
||||
/* The "Back" prompt at the bottom right (B), on every screen with one (the title's load list, the pause menu, the
|
||||
map; in the layout's units, measured from their screens): a click there off the buttons */
|
||||
if ((pressed & HOS_MOUSE_LEFT) && !hit.hit && hit.y > -1080 && hit.y < -960 && hit.x >= 1600 && hit.x < 1900) {
|
||||
hos_hid_tap("0:B/80");
|
||||
if (trace) hos_log("menu: the Back prompt clicked (%.0f, %.0f)", hit.x, hit.y);
|
||||
}
|
||||
/* a click: the button under it decided (A: after the focus has landed, at the next update, when it moved it), the
|
||||
right button back (B) */
|
||||
if ((pressed & HOS_MOUSE_LEFT) && hit.hit) hos_hid_tap(just || hit.hit == asked ? "0.05:A/80" : "0:A/80");
|
||||
if (pressed & HOS_MOUSE_RIGHT) hos_hid_tap("0:B/80");
|
||||
}
|
||||
|
||||
/* The button's boxes (button+0x58, 0xb0 apart). The first is its hit box: its global matrix at +0x28 (3 x 4, by column:
|
||||
the translation at +0x4c, +0x50; the layout's units, moving with a page as it slides; all 0 while its page is not shown)
|
||||
and its rectangle at +0x84 (x, y, w, h, about the box's origin). The second is centred on the slot's picture (its
|
||||
translation at +0xfc, +0x100; its own rectangle a fixed 700 x 700). A few slots' hit boxes cover only a side of the
|
||||
picture (Pa_ItemIcon_05: 100 wide on the right of a slot 260 wide, its centre 80 to the right of the picture's): such
|
||||
a box is mirrored about the picture's centre and both taken */
|
||||
static int button_rect(uint64_t button, Rect *r) {
|
||||
float m[12], b[4], c[2];
|
||||
const uint64_t box = peek64(button + 0x58);
|
||||
if (!peek(box + 0x28, m, sizeof m) || !peek(box + 0x84, b, sizeof b)) return 0;
|
||||
const float sx = m[0], sy = m[4], tx = m[9], ty = m[10];
|
||||
if (!(sx > 1e-3f) || !(sy > 1e-3f) || !(b[2] > 0) || !(b[3] > 0)) return 0;
|
||||
r->x0 = tx + sx * b[0], r->x1 = tx + sx * (b[0] + b[2]);
|
||||
r->y0 = ty + sy * b[1], r->y1 = ty + sy * (b[1] + b[3]);
|
||||
float s2;
|
||||
if (peek(box + 0xd8, &s2, 4) && s2 > 1e-3f && peek(box + 0xfc, c, sizeof c)) {
|
||||
const float w = r->x1 - r->x0, h = r->y1 - r->y0, cx = (r->x0 + r->x1) / 2, cy = (r->y0 + r->y1) / 2;
|
||||
if (c[0] - cx < w && cx - c[0] < w && c[1] - cy < h && cy - c[1] < h) { /* (the picture's centre near the box) */
|
||||
const float x0 = 2 * c[0] - r->x1, x1 = 2 * c[0] - r->x0, y0 = 2 * c[1] - r->y1, y1 = 2 * c[1] - r->y0;
|
||||
if (x0 < r->x0) r->x0 = x0;
|
||||
if (x1 > r->x1) r->x1 = x1;
|
||||
if (y0 < r->y0) r->y0 = y0;
|
||||
if (y1 > r->y1) r->y1 = y1;
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* ---- The screens f_802f1380 runs for (the HUD's, the menus', the title's: each frame each). The mouse is for the one
|
||||
in front: of those that ran in the last 100 ms with a focused button shown (or one gone for under 0.5 s: the map's
|
||||
list loses it for 6 to 24 frames as it moves), the one that came last (a dialog over the menu that opened it). Whether a screen has a focused button is looked at 10 times a second (each look reads its list) */
|
||||
typedef struct { uint64_t screen, vt; int64_t first_ns, seen_ns, lost_ns; int focus, running; unsigned n; } Seen;
|
||||
static Seen seen[24];
|
||||
static SRWLOCK seen_lock = SRWLOCK_INIT; /* (the screens' updates run on several of the game's threads at once) */
|
||||
|
||||
static void focus_entry(int i, uint64_t entry, uint64_t button, void *arg) {
|
||||
(void)i, (void)entry;
|
||||
uint8_t state = 0;
|
||||
Rect r;
|
||||
if (!*(int *)arg && peek(button + 56, &state, 1) && state && button_rect(button, &r)) *(int *)arg = 1;
|
||||
}
|
||||
static Seen *screen_seen(uint64_t screen, int64_t now) {
|
||||
Seen *free_one = NULL;
|
||||
for (int i = 0; i < (int)(sizeof seen / sizeof *seen); i++) {
|
||||
if (seen[i].screen == screen) return &seen[i];
|
||||
if (!free_one || seen[i].seen_ns < free_one->seen_ns) free_one = &seen[i]; /* (the one gone longest) */
|
||||
}
|
||||
memset(free_one, 0, sizeof *free_one);
|
||||
free_one->screen = screen, free_one->first_ns = now, free_one->vt = peek64(screen);
|
||||
if (free_one->vt == HUD_SCREEN_VTABLE) hud_screen = screen;
|
||||
if (trace) {
|
||||
const uint64_t mgr = peek64(peek64(screen + 32) + 96);
|
||||
hos_log("menu: a screen: %#llx (vtable %#llx) entries %d, focus manager %#llx%s", (unsigned long long)screen,
|
||||
(unsigned long long)peek64(screen), each_entry(screen, 400, NULL, NULL), (unsigned long long)mgr,
|
||||
screen == pause_screen_now() ? " (the pause menu)" : "");
|
||||
}
|
||||
return free_one;
|
||||
}
|
||||
|
||||
void hos_oot_menu_tick(Ctx *c, uint64_t screen) {
|
||||
if (!screen) return;
|
||||
if (trace < 0) trace = getenv("HOS_MENU_TRACE") != NULL;
|
||||
const int64_t now = hos_now_ns();
|
||||
AcquireSRWLockExclusive(&seen_lock);
|
||||
Seen *me = screen_seen(screen, now);
|
||||
if (!me->running) {
|
||||
me->running = 1;
|
||||
if (trace) hos_log("menu: screen %#llx (vtable %#llx) runs", (unsigned long long)screen, (unsigned long long)peek64(screen));
|
||||
}
|
||||
me->seen_ns = now;
|
||||
/* (Triforce: the game's Options screen runs: the renderer's tabs over its header. Its vtable as it is now, not me->vt:
|
||||
a screen's memory is another screen's later, the Load list ran at the Options' address in the traced run) */
|
||||
if (peek64(screen) == OPTIONS_SCREEN_VTABLE) {
|
||||
static int tabs = -1;
|
||||
if (tabs < 0) {
|
||||
const char *e = getenv("HOS_OPTIONS_TABS");
|
||||
tabs = !(e && *e == '0');
|
||||
}
|
||||
InterlockedExchange64(&options_seen_ns, (LONG64)now);
|
||||
if (tabs) rx_option_set(HOS_OPT_GAME_OPTIONS, 1);
|
||||
}
|
||||
for (int i = 0; i < (int)(sizeof seen / sizeof *seen); i++) /* (a screen with no update for 200 ms has stopped) */
|
||||
if (seen[i].running && now - seen[i].seen_ns > 200000000) {
|
||||
seen[i].running = 0;
|
||||
if (trace) hos_log("menu: screen %#llx stopped", (unsigned long long)seen[i].screen);
|
||||
}
|
||||
if (me->n++ % 6 == 0) {
|
||||
const int had = me->focus;
|
||||
me->focus = 0;
|
||||
if (peek64(peek64(screen + 32) + 96)) each_entry(screen, 400, focus_entry, &me->focus);
|
||||
if (had && !me->focus) me->lost_ns = now;
|
||||
if (trace && me->focus != had)
|
||||
hos_log("menu: screen %#llx %s a focused button (%u frames in)", (unsigned long long)screen,
|
||||
me->focus ? "has" : "no longer has", me->n);
|
||||
}
|
||||
{ /* (the Map page: the panel's frame running alone) */
|
||||
int frame = 0, other = 0;
|
||||
for (int i = 0; i < (int)(sizeof seen / sizeof *seen); i++) {
|
||||
if (!seen[i].screen || !seen[i].running) continue;
|
||||
if (seen[i].vt == PANEL_FRAME_VTABLE) frame = 1;
|
||||
if (seen[i].vt == 0x84c07798ULL || seen[i].vt == 0x84c04a18ULL || seen[i].screen == pause_screen_now()) other = 1;
|
||||
}
|
||||
const int was = map_page;
|
||||
map_page = frame && !other;
|
||||
if (trace && map_page != was) hos_log("menu: the panel's Map page %s", map_page ? "shown" : "gone");
|
||||
}
|
||||
const Seen *front = NULL;
|
||||
for (int i = 0; i < (int)(sizeof seen / sizeof *seen); i++)
|
||||
if (seen[i].screen && (seen[i].focus || now - seen[i].lost_ns < 500000000 || panel_page_vt(seen[i].vt) >= 0) &&
|
||||
seen[i].running && now - seen[i].seen_ns < 100000000 &&
|
||||
(!front || seen[i].first_ns > front->first_ns)) /* (its focus gone for under 0.5 s: a list's moment between rows) */
|
||||
front = &seen[i];
|
||||
static uint64_t front_was;
|
||||
if (trace && front && front->screen != front_was) hos_log("menu: the mouse is for screen %#llx", (unsigned long long)front->screen);
|
||||
front_was = front ? front->screen : 0;
|
||||
const int mine = front == me;
|
||||
/* (no screen has held the mouse for 50 ms of frames, the HUD's among them in play: the game's menus have closed,
|
||||
and the window gives the camera its mouse back now, not after display.c's 300 ms) */
|
||||
static int64_t none_since;
|
||||
const int gone = !front && none_since && now - none_since > 50000000;
|
||||
none_since = front ? 0 : none_since ? none_since : now;
|
||||
ReleaseSRWLockExclusive(&seen_lock);
|
||||
if (gone) hos_mouse_game_menu_gone();
|
||||
if (mine) mouse_tick(c, screen);
|
||||
if (screen == pause_screen_now()) InterlockedIncrement(&ticks);
|
||||
}
|
||||
#else
|
||||
void hos_oot_menu_focus(Ctx *c, uint64_t screen, uint64_t pane, uint64_t lr) { (void)c, (void)screen, (void)pane, (void)lr; }
|
||||
void hos_oot_menu_tick(Ctx *c, uint64_t screen) { (void)c, (void)screen; }
|
||||
int hos_oot_options_front(void) { return 0; }
|
||||
#endif
|
||||
487
host/pad_sdl.c
Normal file
487
host/pad_sdl.c
Normal file
@@ -0,0 +1,487 @@
|
||||
/* Game controllers through SDL (host/hos_sdl.c: SDL3, else SDL2, third_party/sdl2/SDL2.dll; zlib license, loaded at
|
||||
run time): DualSense, DualShock 4, Switch Pro, Xbox and most other pads, over USB or Bluetooth. XInput alone sees
|
||||
only Xbox-style pads.
|
||||
|
||||
A thread of its own (on Linux the window's, which runs SDL there too) opens every controller SDL knows (and ones
|
||||
plugged in later), polls them every 4 ms and keeps
|
||||
the merged state; nn_hid.c ORs it into the input with XInput, keyboard and mouse. Without SDL nothing
|
||||
changes. HOS_NO_SDL=1 leaves SDL out. The inputs go by position (HOS_PAD_*, SDL's own order: the bottom face button
|
||||
first, cross on a DualSense, A on an Xbox pad); nn_hid.c's controls make them the Switch's buttons.
|
||||
|
||||
(hookshot) Motion: with the Insert menu's Motion controls on (the default), the open pad with a gyroscope and an
|
||||
accelerometer (Switch Pro and pads in Switch mode, DualSense, DualShock 4, others) that was used last has them read
|
||||
each poll and turned into the six-axis state OoT aims with (host/hos_motion.h), which nn_hid.c's
|
||||
GetSixAxisSensorStates gives the game; Motion sensitivity X/Y and Invert motion X/Y apply there. Off, or with no such pad, the game sees the pad
|
||||
lying still, as before. */
|
||||
#include "hos.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#include "hos_sdl.h"
|
||||
#include "hd_rumble.h"
|
||||
#include "hos_motion.h"
|
||||
#include "../gpu/vk/vk_api.h" /* (HOS_PAD_*) */
|
||||
|
||||
void hos_host_thread_register_self(const char *name); /* hos_prof.c */
|
||||
|
||||
/* (BTN_A ... BTN_RIGHT are HOS_PAD_SOUTH ... HOS_PAD_RIGHT) */
|
||||
enum { BTN_A, BTN_B, BTN_X, BTN_Y, BTN_BACK, BTN_GUIDE, BTN_START, BTN_LSTICK, BTN_RSTICK, BTN_LSHOULDER, BTN_RSHOULDER,
|
||||
BTN_UP, BTN_DOWN, BTN_LEFT, BTN_RIGHT, BTN_MISC1, BTN_N = 21 };
|
||||
enum { AX_LX, AX_LY, AX_RX, AX_RY, AX_LT, AX_RT };
|
||||
|
||||
#define MAX_PADS 8
|
||||
/* (motion: whether it has the sensors, whether they are on, when to try again after they would not turn on; used_ns:
|
||||
its last button or stick change; serial: which opening this is, so a pad reconnecting into the slot is a new one;
|
||||
bias: its gyroscope's learned resting rate, kept while another pad has motion) */
|
||||
static struct {
|
||||
void *gc;
|
||||
int32_t id;
|
||||
uint16_t rumble_lo, rumble_hi;
|
||||
int64_t rumble_ns;
|
||||
uint8_t hd, hd_kind, hd_ever; /* HD rumble (hd_rumble.h): HD_RUMBLE_UNKNOWN / ON / OFF, the pad's kind, sent once */
|
||||
uint8_t hd_sent[HD_RUMBLE_PACKET_SIZE];
|
||||
int64_t hd_ns;
|
||||
int motion, motion_on;
|
||||
int64_t motion_retry_ns, used_ns;
|
||||
uint64_t input_sig;
|
||||
unsigned rested; /* (hookshot) the sticks' axes seen at rest since it was opened, a bit each: only those steer */
|
||||
signed char held[4]; /* (the way each axis was last held, -1, 0 or 1: one held the other way has passed its rest) */
|
||||
uint32_t serial;
|
||||
float bias[3], bias_t;
|
||||
int has_bias;
|
||||
} pads[MAX_PADS];
|
||||
static uint32_t pads_opened;
|
||||
static SRWLOCK state_lock = SRWLOCK_INIT;
|
||||
static uint64_t state_buttons;
|
||||
static int32_t state_stick[4];
|
||||
static int state_count;
|
||||
static char state_name[128]; /* the first controller's name (host/prompts.c: the button prompts' Auto) */
|
||||
static volatile LONG rumble_low, rumble_high; /* 0..65535, set by the vibration HLE */
|
||||
/* the game's own vibration values per side (0 left, 1 right: {amp_low, freq_low, amp_high, freq_high}), for the pads
|
||||
that play HD rumble; silence until the game sends one */
|
||||
static SRWLOCK hd_lock = SRWLOCK_INIT;
|
||||
static float hd_values[2][4] = {{0.0f, 160.0f, 0.0f, 320.0f}, {0.0f, 160.0f, 0.0f, 320.0f}};
|
||||
/* (motion) the pad read and its filter (the polling thread's own), then what the game is handed (under state_lock): the
|
||||
last HOS_MOTION_HISTORY readings, newest at motion_hist[motion_head]; gyro_status for the menu */
|
||||
static HosMotion motion;
|
||||
static int64_t motion_ns, motion_reading_ns, motion_log_ns, motion_readings, motion_start_ns;
|
||||
static int motion_warned;
|
||||
static int motion_pad = -1;
|
||||
static uint32_t motion_serial;
|
||||
static HosMotionSample motion_hist[HOS_MOTION_HISTORY];
|
||||
static int motion_head, motion_count, motion_live;
|
||||
static volatile LONG gyro_status; /* 0 no controller, 1 controllers but none with a gyro, 2 one with a gyro */
|
||||
|
||||
int32_t hos_stick_axis(int16_t v, int zone); /* nn_hid.c: the menu's Stick dead zone, as XInput's pads */
|
||||
|
||||
static int32_t stick_value(int16_t v, int flip, int zone) {
|
||||
const int32_t a = hos_stick_axis(v, zone);
|
||||
return flip ? -a : a;
|
||||
}
|
||||
|
||||
/* SDL's controller support started; 0 when it could not be */
|
||||
static int pads_start(void) {
|
||||
/* poll in the background, whatever window is in front (nn_hid.c decides when input counts) */
|
||||
hos_sdl_hint("SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS", "1");
|
||||
/* (SDL2: PlayStation pads' rumble asked for; SDL3 turns it on when a rumble is first sent) */
|
||||
hos_sdl_hint("SDL_JOYSTICK_HIDAPI_PS5_RUMBLE", "1");
|
||||
hos_sdl_hint("SDL_JOYSTICK_HIDAPI_PS4_RUMBLE", "1");
|
||||
/* (the map below is by position; SDL2 reports Nintendo pads by their labels unless told not to, which put a Switch Pro
|
||||
Controller's A, on the right, at the bottom button's place: A acted as B and X as Y: SkyboundTotk issue 12. SDL3's
|
||||
are by position always) */
|
||||
hos_sdl_hint("SDL_GAMECONTROLLER_USE_BUTTON_LABELS", "0");
|
||||
/* (with no window nothing reads SDL's quit event: SDL's own SIGINT/SIGTERM handlers turned a timeout's or a service
|
||||
manager's SIGTERM into that event, and the run went on until SIGKILL. Without them the signals end it as usual) */
|
||||
if (getenv("HOS_HEADLESS")) hos_sdl_hint("SDL_NO_SIGNAL_HANDLERS", "1");
|
||||
if (!hos_sdl_init(HOS_SDL_GAMEPAD)) {
|
||||
hos_log("hid: SDL could not start its controller support: %s", hos_sdl_error());
|
||||
return 0;
|
||||
}
|
||||
hos_log("hid: SDL controller support ready (DualSense, DualShock 4, Switch Pro, Xbox and others)");
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* SDL_GameControllerRumble runs only for the duration it is given, then stops, and a repeat of the same numbers was
|
||||
skipped. A rumble the game holds, and one that was already playing when this controller opened, never reached it. */
|
||||
static int rumble_due(unsigned lo, unsigned hi, unsigned sent_lo, unsigned sent_hi, long long now, long long sent_ns) {
|
||||
if (lo != sent_lo || hi != sent_hi) return 1;
|
||||
if ((lo || hi) && now - sent_ns >= 500000000LL) return 1; /* (half of the 1 s effect, so it does not lapse) */
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* The Insert menu's Rumble strength (percent; 0 Off) on the motors' 0..65535, heavy and light together: up to 100 each
|
||||
motor is scaled on its own (100 sends them as they are); above, when the stronger would pass the motor's top, both
|
||||
are scaled by the same factor so that it just reaches it, keeping the balance between the motors that the frequency
|
||||
split chose. Off stops a rumble that is playing (the poll sends the change). */
|
||||
static void rumble_strength(unsigned heavy, unsigned light, int percent, uint16_t out[2]) {
|
||||
if (percent <= 0) {
|
||||
out[0] = out[1] = 0;
|
||||
return;
|
||||
}
|
||||
unsigned long long h = (unsigned long long)heavy * (unsigned)percent / 100u;
|
||||
unsigned long long l = (unsigned long long)light * (unsigned)percent / 100u;
|
||||
if (h > 0xFFFFu || l > 0xFFFFu) { /* (from the motors' own values: the same factor for both, the stronger at the top) */
|
||||
const unsigned long long top = heavy > light ? heavy : light;
|
||||
h = heavy * 0xFFFFull / top;
|
||||
l = light * 0xFFFFull / top;
|
||||
}
|
||||
out[0] = (uint16_t)h;
|
||||
out[1] = (uint16_t)l;
|
||||
}
|
||||
|
||||
/* A pad SDL just opened: HD rumble when it is a Switch Pro Controller or a Joy-Con and the SDL has the effect call
|
||||
(HOS_HD_RUMBLE=0: never); whether SDL's driver takes it shows with the first packet. */
|
||||
static void hd_open(int i, void *gc) {
|
||||
static int env_off = -1;
|
||||
if (env_off < 0) {
|
||||
const char *e = getenv("HOS_HD_RUMBLE");
|
||||
env_off = e && !strcmp(e, "0");
|
||||
}
|
||||
pads[i].hd_kind = (uint8_t)hd_rumble_kind(hos_sdl_load(), hos_sdl_pad_type(gc));
|
||||
pads[i].hd = (uint8_t)hd_rumble_start(pads[i].hd_kind, hos_sdl_pad_has_effect(), env_off);
|
||||
pads[i].hd_ever = 0;
|
||||
pads[i].hd_ns = 0;
|
||||
const uint8_t n[4] = {0x00, 0x01, 0x40, 0x40};
|
||||
hd_rumble_packet(HD_RUMBLE_PRO, n, n, pads[i].hd_sent);
|
||||
}
|
||||
|
||||
/* A pad's HD rumble, each poll: its packet when due (hd_rumble_due). 1 when the pad plays HD rumble (the motor rumble
|
||||
is not sent to it); 0 when it does not, or SDL just refused it (then it gets the motor rumble from now on). side:
|
||||
the left side's bytes, the right's, and both merged (for a single Joy-Con, which has only one). */
|
||||
static int hd_poll(int i, const uint8_t side[3][4], long long now) {
|
||||
if (pads[i].hd == HD_RUMBLE_OFF) return 0;
|
||||
uint8_t packet[HD_RUMBLE_PACKET_SIZE];
|
||||
const int single = pads[i].hd_kind == HD_RUMBLE_JOYCON_LEFT || pads[i].hd_kind == HD_RUMBLE_JOYCON_RIGHT;
|
||||
hd_rumble_packet(pads[i].hd_kind, single ? side[2] : side[0], single ? side[2] : side[1], packet);
|
||||
if (!hd_rumble_due(packet, pads[i].hd_sent, pads[i].hd_ever, now, pads[i].hd_ns)) return 1;
|
||||
const int was = pads[i].hd;
|
||||
pads[i].hd = (uint8_t)hd_rumble_after_send(hos_sdl_pad_effect(pads[i].gc, packet, sizeof packet));
|
||||
if (pads[i].hd == HD_RUMBLE_OFF) { /* (refused: HD rumble off for this pad until it is closed and opened again.
|
||||
SDL3 queues the write, so false means the driver does not support the effect,
|
||||
not a write that failed once) */
|
||||
hos_log("hid: \"%s\" did not take HD rumble (%s): its rumble goes to its motors", hos_sdl_pad_name(pads[i].gc),
|
||||
hos_sdl_error());
|
||||
pads[i].rumble_lo = pads[i].rumble_hi = 0; /* (the motor path sends what is playing at once) */
|
||||
pads[i].rumble_ns = 0;
|
||||
return 0;
|
||||
}
|
||||
if (was == HD_RUMBLE_UNKNOWN) hos_log("hid: HD rumble on \"%s\"", hos_sdl_pad_name(pads[i].gc));
|
||||
memcpy(pads[i].hd_sent, packet, sizeof packet);
|
||||
pads[i].hd_ns = now;
|
||||
pads[i].hd_ever = 1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* (motion) the sensors on while Motion controls is on (HOS_OPT_GYRO, on without the menu), off otherwise; the pad with
|
||||
them that was used last read into the filter. count: the pads open */
|
||||
static void motion_poll(int64_t now, int count) {
|
||||
int rx_option(int id, int otherwise);
|
||||
static int debug = -1; /* (HOS_MOTION_DEBUG, read once) */
|
||||
if (debug < 0) debug = getenv("HOS_MOTION_DEBUG") != NULL;
|
||||
const int want = rx_option(HOS_OPT_GYRO, 1) != 0;
|
||||
int pick = -1, any = 0;
|
||||
for (int i = 0; i < MAX_PADS; i++) {
|
||||
if (!pads[i].gc || !pads[i].motion) continue;
|
||||
any = 1;
|
||||
if (pads[i].motion_on != want && now >= pads[i].motion_retry_ns) {
|
||||
const int ok = hos_sdl_pad_sensor_enable(pads[i].gc, HOS_SDL_SENSOR_ACCEL, want) &
|
||||
hos_sdl_pad_sensor_enable(pads[i].gc, HOS_SDL_SENSOR_GYRO, want);
|
||||
if (want && !ok) { /* (both off again, and another try in two seconds: a pad over Bluetooth may still be
|
||||
starting) */
|
||||
hos_sdl_pad_sensor_enable(pads[i].gc, HOS_SDL_SENSOR_ACCEL, 0);
|
||||
hos_sdl_pad_sensor_enable(pads[i].gc, HOS_SDL_SENSOR_GYRO, 0);
|
||||
pads[i].motion_on = 0;
|
||||
if (!pads[i].motion_retry_ns)
|
||||
hos_log("hid: \"%s\": its motion sensors could not be turned on yet, trying again",
|
||||
hos_sdl_pad_name(pads[i].gc));
|
||||
pads[i].motion_retry_ns = now + 2000000000LL;
|
||||
} else {
|
||||
pads[i].motion_on = want;
|
||||
pads[i].motion_retry_ns = 0;
|
||||
}
|
||||
}
|
||||
if (want && pads[i].motion_on && (pick < 0 || pads[i].used_ns > pads[pick].used_ns)) pick = i;
|
||||
}
|
||||
InterlockedExchange(&gyro_status, any ? 2 : count ? 1 : 0);
|
||||
float a[3], g[3];
|
||||
const int read = pick >= 0 && hos_sdl_pad_sensor(pads[pick].gc, HOS_SDL_SENSOR_ACCEL, a, 3) &&
|
||||
hos_sdl_pad_sensor(pads[pick].gc, HOS_SDL_SENSOR_GYRO, g, 3);
|
||||
/* (the pad that had motion keeps what its filter learned of its gyroscope's bias, for when it has motion again) */
|
||||
if (motion_pad >= 0 && (!read || pick != motion_pad) && pads[motion_pad].gc && pads[motion_pad].serial == motion_serial &&
|
||||
motion.learned_t > 0) {
|
||||
memcpy(pads[motion_pad].bias, motion.bias, sizeof motion.bias);
|
||||
pads[motion_pad].bias_t = motion.learned_t, pads[motion_pad].has_bias = 1;
|
||||
}
|
||||
if (!read) {
|
||||
motion_pad = -1;
|
||||
AcquireSRWLockExclusive(&state_lock);
|
||||
motion_live = 0, motion_count = 0;
|
||||
ReleaseSRWLockExclusive(&state_lock);
|
||||
return;
|
||||
}
|
||||
int fresh = 0;
|
||||
if (pick != motion_pad || pads[pick].serial != motion_serial) { /* (another pad, or one reconnected: a fresh filter) */
|
||||
hos_motion_reset(&motion);
|
||||
if (pads[pick].has_bias)
|
||||
memcpy(motion.bias, pads[pick].bias, sizeof motion.bias), motion.learned_t = pads[pick].bias_t;
|
||||
motion_pad = pick, motion_serial = pads[pick].serial, motion_ns = now;
|
||||
fresh = 1;
|
||||
motion_start_ns = now, motion_warned = 0;
|
||||
hos_log("hid: motion controls from \"%s\"", hos_sdl_pad_name(pads[pick].gc));
|
||||
}
|
||||
/* the filter runs outside the lock (the game's input calls take it); a repeat of the last reading is no reading */
|
||||
const int64_t dt_ns = now - motion_ns;
|
||||
motion_ns = now;
|
||||
{ /* (the Motion deadzone row: the console's tight, standard and loose zero-drift thresholds, turns a second) */
|
||||
static const float zone[3] = {HOS_MOTION_THRESHOLD_TIGHT, HOS_MOTION_THRESHOLD, HOS_MOTION_THRESHOLD_LOOSE};
|
||||
const int z = rx_option(HOS_OPT_GYRO_DEADZONE, 1);
|
||||
motion.threshold = zone[z < 0 ? 0 : z > 2 ? 2 : z];
|
||||
}
|
||||
if (!hos_motion_update(&motion, a, g, (float)(dt_ns / 1e9), rx_option(HOS_OPT_GYRO_SENS_X, 100) / 100.0f,
|
||||
rx_option(HOS_OPT_GYRO_SENS_Y, 100) / 100.0f, rx_option(HOS_OPT_GYRO_INV_X, 0),
|
||||
rx_option(HOS_OPT_GYRO_INV_Y, 0)) && !fresh)
|
||||
return;
|
||||
if (!motion_warned && motion.learned_t <= 0 && now - motion_start_ns > 30000000000LL) {
|
||||
motion_warned = 1; /* (a pad noisier than the stillness test allows: its drift is never taken off) */
|
||||
hos_log("hid: motion: \"%s\" has not been set down yet, so its gyroscope's drift is not learned: set it on a "
|
||||
"table for a second (if it is on a table and this stays, its sensor may be noisier than the stillness "
|
||||
"test allows)", hos_sdl_pad_name(pads[pick].gc));
|
||||
}
|
||||
if (debug && now >= motion_log_ns) { /* (twice a second: what the game gets) */
|
||||
motion_log_ns = now + 500000000LL;
|
||||
hos_log("hid: motion: accel (%+.2f, %+.2f, %+.2f) G, gyro (%+.3f, %+.3f, %+.3f) turns/s, direction rows "
|
||||
"(%+.2f %+.2f %+.2f / %+.2f %+.2f %+.2f / %+.2f %+.2f %+.2f), bias (%+.4f, %+.4f, %+.4f)", motion.out.accel[0],
|
||||
motion.out.accel[1], motion.out.accel[2], motion.out.gyro[0], motion.out.gyro[1], motion.out.gyro[2],
|
||||
motion.out.direction[0], motion.out.direction[1], motion.out.direction[2], motion.out.direction[3],
|
||||
motion.out.direction[4], motion.out.direction[5], motion.out.direction[6], motion.out.direction[7],
|
||||
motion.out.direction[8], motion.bias[0], motion.bias[1], motion.bias[2]);
|
||||
}
|
||||
HosMotionSample r;
|
||||
r.st = motion.out;
|
||||
r.n = ++motion_readings;
|
||||
/* (the time since the reading before, capped as the filter caps it: a stalled pad's next reading is no jump) */
|
||||
r.dt_ns = fresh ? 5000000 : now - motion_reading_ns;
|
||||
if (r.dt_ns > (int64_t)(HOS_MOTION_DT_MAX * 1e9)) r.dt_ns = (int64_t)(HOS_MOTION_DT_MAX * 1e9);
|
||||
motion_reading_ns = now;
|
||||
AcquireSRWLockExclusive(&state_lock);
|
||||
motion_head = (motion_head + 1) % HOS_MOTION_HISTORY;
|
||||
motion_hist[motion_head] = r;
|
||||
if (fresh) motion_count = 0;
|
||||
if (motion_count < HOS_MOTION_HISTORY) motion_count++;
|
||||
motion_live = 1;
|
||||
ReleaseSRWLockExclusive(&state_lock);
|
||||
}
|
||||
|
||||
/* one poll: controllers plugged in or gone (each second), then every open one's buttons, sticks and rumble */
|
||||
static void pads_poll(void) {
|
||||
static int64_t next_scan = 0;
|
||||
hos_sdl_pads_update();
|
||||
const int64_t now = hos_now_ns();
|
||||
if (now >= next_scan) { /* new controllers (and ones that went away) */
|
||||
next_scan = now + 1000000000LL;
|
||||
for (int i = 0; i < MAX_PADS; i++)
|
||||
if (pads[i].gc && !hos_sdl_pad_connected(pads[i].gc)) {
|
||||
hos_log("hid: controller \"%s\" disconnected (SDL)", hos_sdl_pad_name(pads[i].gc));
|
||||
hos_sdl_pad_close(pads[i].gc);
|
||||
pads[i].gc = NULL;
|
||||
pads[i].rumble_lo = pads[i].rumble_hi = 0;
|
||||
pads[i].rumble_ns = 0;
|
||||
pads[i].motion = pads[i].motion_on = 0;
|
||||
}
|
||||
int32_t ids[32];
|
||||
int opens[32];
|
||||
const int nj = hos_sdl_pads_list(ids, opens, 32);
|
||||
for (int j = 0; j < nj; j++) {
|
||||
const int32_t id = ids[j];
|
||||
int have = 0, slot = -1;
|
||||
for (int i = 0; i < MAX_PADS; i++) {
|
||||
if (pads[i].gc && pads[i].id == id) have = 1;
|
||||
if (!pads[i].gc && slot < 0) slot = i;
|
||||
}
|
||||
if (have || slot < 0) continue;
|
||||
void *gc = hos_sdl_pad_open(opens[j]);
|
||||
if (!gc) continue;
|
||||
pads[slot].gc = gc;
|
||||
pads[slot].id = hos_sdl_pad_id(gc);
|
||||
pads[slot].rumble_lo = pads[slot].rumble_hi = 0;
|
||||
pads[slot].rumble_ns = 0;
|
||||
hd_open(slot, gc);
|
||||
pads[slot].motion = hos_sdl_pad_has_sensor(gc, HOS_SDL_SENSOR_GYRO) && hos_sdl_pad_has_sensor(gc, HOS_SDL_SENSOR_ACCEL);
|
||||
pads[slot].motion_on = 0;
|
||||
pads[slot].motion_retry_ns = 0;
|
||||
pads[slot].used_ns = now, pads[slot].input_sig = 0; /* (just connected: the one about to be used) */
|
||||
pads[slot].rested = 0;
|
||||
memset(pads[slot].held, 0, sizeof pads[slot].held);
|
||||
pads[slot].serial = ++pads_opened;
|
||||
pads[slot].has_bias = 0;
|
||||
hos_log("hid: controller \"%s\" connected (SDL)%s", hos_sdl_pad_name(gc),
|
||||
pads[slot].motion ? ", with a gyroscope" : "");
|
||||
}
|
||||
}
|
||||
uint64_t b = 0;
|
||||
int32_t s[4] = {0};
|
||||
int count = 0;
|
||||
int rx_option(int id, int otherwise);
|
||||
const int strength = rx_option(9, 100); /* (the menu's Rumble strength: the motors' and HD rumble's) */
|
||||
uint16_t motors[2];
|
||||
rumble_strength((uint16_t)rumble_low, (uint16_t)rumble_high, strength, motors);
|
||||
const uint16_t lo = motors[0], hi = motors[1];
|
||||
uint8_t side[3][4]; /* (the HD rumble pads': each side's bytes, then both merged for a single Joy-Con) */
|
||||
{
|
||||
float hv[2][4], felt[3][4];
|
||||
AcquireSRWLockShared(&hd_lock);
|
||||
memcpy(hv, hd_values, sizeof hv);
|
||||
ReleaseSRWLockShared(&hd_lock);
|
||||
hd_rumble_felt(hv[0], felt[0]); /* (the game's small amplitudes, as the motors get them) */
|
||||
hd_rumble_felt(hv[1], felt[1]);
|
||||
hd_rumble_encode(felt[0], strength, side[0]);
|
||||
hd_rumble_encode(felt[1], strength, side[1]);
|
||||
hd_rumble_merge(felt[0], felt[1], felt[2]);
|
||||
hd_rumble_encode(felt[2], strength, side[2]);
|
||||
}
|
||||
for (int i = 0; i < MAX_PADS; i++) {
|
||||
void *gc = pads[i].gc;
|
||||
if (!gc) continue;
|
||||
count++;
|
||||
for (int k = BTN_A; k <= BTN_RIGHT; k++) /* (SDL3's gamepad buttons are in SDL2's order) */
|
||||
if (hos_sdl_pad_button(gc, k)) b |= 1ULL << k;
|
||||
if (hos_sdl_pad_axis(gc, AX_LT) > 8000) b |= 1ULL << HOS_PAD_LTRIGGER;
|
||||
if (hos_sdl_pad_axis(gc, AX_RT) > 8000) b |= 1ULL << HOS_PAD_RTRIGGER;
|
||||
const int inv_x = rx_option(16, 0);
|
||||
const int inv_y = rx_option(17, 0);
|
||||
const int z = rx_option(11, 0); /* (the menu's Stick dead zone: nn_hid.c's hos_stick_axis) */
|
||||
int32_t v[4] = {stick_value(hos_sdl_pad_axis(gc, AX_LX), 0, z),
|
||||
stick_value(hos_sdl_pad_axis(gc, AX_LY), 1, z),
|
||||
stick_value(hos_sdl_pad_axis(gc, AX_RX), inv_x, z),
|
||||
stick_value(hos_sdl_pad_axis(gc, AX_RY), inv_y ? 0 : 1, z)};
|
||||
/* (hookshot) An axis steers once it has been seen at rest (inside the dead zone) since the pad was opened. The sticks are
|
||||
the strongest of all the pads', so a device whose axis reads held for good (a mapping that puts a trigger or an
|
||||
unused axis on a stick, a second virtual pad) turned the camera or walked Link in circles on its own, with the
|
||||
player's pad at rest (#1673: Xbox 360 pad, CachyOS; #1661: GameSir 2 Lite, wired). A real stick rests at the start. */
|
||||
/* (a worn stick resting just past a small dead zone counts once it is pushed the other way: it went past its rest) */
|
||||
for (int k = 0; k < 4; k++) {
|
||||
const signed char way = (signed char)(v[k] > 0 ? 1 : v[k] < 0 ? -1 : 0);
|
||||
if (!way || (pads[i].held[k] && way != pads[i].held[k])) pads[i].rested |= 1u << k;
|
||||
pads[i].held[k] = way;
|
||||
if (!(pads[i].rested >> k & 1)) v[k] = 0;
|
||||
}
|
||||
for (int k = 0; k < 4; k++)
|
||||
if ((v[k] < 0 ? -v[k] : v[k]) > (s[k] < 0 ? -s[k] : s[k])) s[k] = v[k];
|
||||
{ /* (motion: the pad last used; a stick counts by which way it is pushed, not by how far) */
|
||||
uint64_t sig = 0;
|
||||
for (int k = BTN_A; k <= BTN_RIGHT; k++)
|
||||
if (hos_sdl_pad_button(gc, k)) sig |= 1ULL << k;
|
||||
for (int k = 0; k < 4; k++) sig |= (uint64_t)(v[k] > 0 ? 1 : v[k] < 0 ? 2 : 0) << (32 + 2 * k);
|
||||
if (sig != pads[i].input_sig) pads[i].input_sig = sig, pads[i].used_ns = now;
|
||||
}
|
||||
if (hd_poll(i, side, now)) continue;
|
||||
if (rumble_due(lo, hi, pads[i].rumble_lo, pads[i].rumble_hi, now, pads[i].rumble_ns)) {
|
||||
hos_sdl_pad_rumble(gc, lo, hi, lo || hi ? 1000 : 0);
|
||||
pads[i].rumble_lo = lo;
|
||||
pads[i].rumble_hi = hi;
|
||||
pads[i].rumble_ns = now;
|
||||
}
|
||||
}
|
||||
motion_poll(now, count);
|
||||
AcquireSRWLockExclusive(&state_lock);
|
||||
state_buttons = b;
|
||||
memcpy(state_stick, s, sizeof s);
|
||||
state_count = count;
|
||||
state_name[0] = 0;
|
||||
for (int i = 0; i < MAX_PADS; i++)
|
||||
if (pads[i].gc) {
|
||||
const char *name = hos_sdl_pad_name(pads[i].gc);
|
||||
snprintf(state_name, sizeof state_name, "%s", name ? name : "");
|
||||
break;
|
||||
}
|
||||
ReleaseSRWLockExclusive(&state_lock);
|
||||
}
|
||||
|
||||
static DWORD WINAPI pad_main(void *arg) {
|
||||
(void)arg;
|
||||
hos_host_thread_register_self("gamepads (SDL)");
|
||||
if (!pads_start()) return 0;
|
||||
for (;;) {
|
||||
pads_poll();
|
||||
Sleep(4);
|
||||
}
|
||||
}
|
||||
#ifndef _WIN32
|
||||
int hos_display_owns_sdl(void); /* host/posix/display_sdl.c */
|
||||
/* (linux) SDL also runs the window (host/posix/display_sdl.c), and its event queue is not for two threads. Polled
|
||||
from the window's thread, between its events. Two threads pumping it corrupted the heap once a controller was
|
||||
attached. */
|
||||
static volatile LONG pads_loaded;
|
||||
void hos_sdl_pads_pump(void) {
|
||||
static int state; /* 0 not started, 1 polling, -1 not available */
|
||||
if (!state && pads_loaded) state = pads_start() ? 1 : -1;
|
||||
if (state > 0) pads_poll();
|
||||
}
|
||||
#endif
|
||||
|
||||
/* The controllers' merged state (nn_hid.c): ORs their inputs in (1 << HOS_PAD_*), keeps the larger stick
|
||||
deflections; returns how many controllers SDL has open. Starts the SDL thread on the first call. */
|
||||
int hos_sdl_pads(uint64_t *buttons, int32_t stick[4]) {
|
||||
static volatile LONG started;
|
||||
if (!started && !InterlockedExchange(&started, 1)) {
|
||||
if (getenv("HOS_NO_SDL")) return 0;
|
||||
if (!hos_sdl_load()) {
|
||||
hos_log("hid: no SDL beside the exe or on the system: only XInput controllers (Xbox pads) work");
|
||||
return 0;
|
||||
}
|
||||
#ifdef _WIN32
|
||||
CreateThread(NULL, 0, pad_main, NULL, 0, NULL);
|
||||
#else
|
||||
if (hos_display_owns_sdl())
|
||||
InterlockedExchange(&pads_loaded, 1); /* (the window's thread polls: hos_sdl_pads_pump) */
|
||||
else
|
||||
CreateThread(NULL, 0, pad_main, NULL, 0, NULL); /* (no window: nothing else pumps SDL) */
|
||||
#endif
|
||||
}
|
||||
AcquireSRWLockShared(&state_lock);
|
||||
const int n = state_count;
|
||||
*buttons |= state_buttons;
|
||||
for (int k = 0; k < 4; k++)
|
||||
if ((state_stick[k] < 0 ? -state_stick[k] : state_stick[k]) > (stick[k] < 0 ? -stick[k] : stick[k]))
|
||||
stick[k] = state_stick[k];
|
||||
ReleaseSRWLockShared(&state_lock);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* (motion) the latest readings for nn_hid.c's GetSixAxisSensorStates, newest first: up to max, how many there are; 0
|
||||
when there are none (Motion controls off, or no pad with a gyroscope) */
|
||||
int hos_sdl_motion_history(HosMotionSample *out, int max) {
|
||||
AcquireSRWLockShared(&state_lock);
|
||||
const int n = !motion_live ? 0 : motion_count < max ? motion_count : max;
|
||||
for (int i = 0; i < n; i++) out[i] = motion_hist[(motion_head - i + HOS_MOTION_HISTORY) % HOS_MOTION_HISTORY];
|
||||
ReleaseSRWLockShared(&state_lock);
|
||||
return n;
|
||||
}
|
||||
/* (the Insert menu's Motion controls row) 0 no controller, 1 controllers with no gyroscope, 2 one with a gyroscope */
|
||||
int hos_sdl_gyro_status(void) { return (int)gyro_status; }
|
||||
/* The first open controller's name into out ("" with none) */
|
||||
void hos_sdl_pad_first_name(char *out, size_t cap) {
|
||||
AcquireSRWLockShared(&state_lock);
|
||||
snprintf(out, cap, "%s", state_name);
|
||||
ReleaseSRWLockShared(&state_lock);
|
||||
}
|
||||
|
||||
/* Vibration from the game (0..1 amplitudes of the low and high bands), for the pads that rumble. */
|
||||
void hos_sdl_rumble(float low, float high) {
|
||||
if (low < 0) low = 0;
|
||||
if (low > 1) low = 1;
|
||||
if (high < 0) high = 0;
|
||||
if (high > 1) high = 1;
|
||||
InterlockedExchange(&rumble_low, (LONG)(low * 65535));
|
||||
InterlockedExchange(&rumble_high, (LONG)(high * 65535));
|
||||
}
|
||||
|
||||
/* The game's own vibration value for one side (0 left, 1 right; {amp_low, freq_low, amp_high, freq_high}), for the
|
||||
pads that play HD rumble (hd_rumble.h); nn_hid.c's vibration_send, beside hos_sdl_rumble. */
|
||||
void hos_sdl_rumble_hd(int side, const float value[4]) {
|
||||
AcquireSRWLockExclusive(&hd_lock);
|
||||
memcpy(hd_values[side & 1], value, sizeof hd_values[0]);
|
||||
ReleaseSRWLockExclusive(&hd_lock);
|
||||
}
|
||||
89
host/pgo_rt.c
Normal file
89
host/pgo_rt.c
Normal file
@@ -0,0 +1,89 @@
|
||||
/* (hookshot) Profile-guided builds (RX_PGO=gen, nx2/build.py): what clang's -fprofile-instr-generate needs, in place of compiler-rt's
|
||||
profile library, which this toolchain lacks. The counters sit in sections .lprfc/.lprfd/.lprfn; this writes them in LLVM's raw
|
||||
format for llvm-profdata.
|
||||
HOS_PGO=<path>: every 500 ms, if <path>.reset exists the counters are cleared, and if <path>.dump exists they are written to <path>;
|
||||
each file is deleted when done. So a run can leave out the loading. */
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <windows.h>
|
||||
|
||||
int __llvm_profile_runtime = 0;
|
||||
|
||||
#pragma section(".lprfc$A", read, write)
|
||||
#pragma section(".lprfc$Z", read, write)
|
||||
#pragma section(".lprfd$A", read, write)
|
||||
#pragma section(".lprfd$Z", read, write)
|
||||
#pragma section(".lprfn$A", read)
|
||||
#pragma section(".lprfn$Z", read)
|
||||
__declspec(allocate(".lprfc$A")) __attribute__((used, aligned(8))) char pgo_cnt_a[8] = {0};
|
||||
__declspec(allocate(".lprfc$Z")) __attribute__((used, aligned(8))) char pgo_cnt_z[8] = {0};
|
||||
__declspec(allocate(".lprfd$A")) __attribute__((used, aligned(8))) char pgo_dat_a[72] = {0};
|
||||
__declspec(allocate(".lprfd$Z")) __attribute__((used, aligned(8))) char pgo_dat_z[72] = {0};
|
||||
__declspec(allocate(".lprfn$A")) __attribute__((used)) const char pgo_nam_a[1] = {0};
|
||||
__declspec(allocate(".lprfn$Z")) __attribute__((used)) const char pgo_nam_z[1] = {0};
|
||||
|
||||
enum { DATA_SIZE = 72 };
|
||||
|
||||
static void pgo_write(const char *path) {
|
||||
const char *cb = pgo_cnt_a + 8, *ce = pgo_cnt_z, *db = pgo_dat_a + DATA_SIZE, *de = pgo_dat_z, *nb = pgo_nam_a + 1, *ne = pgo_nam_z;
|
||||
const uint64_t ndata = (uint64_t)(de - db) / DATA_SIZE, ncnt = (uint64_t)(ce - cb) / 8, nnames = (uint64_t)(ne - nb);
|
||||
const uint64_t header[] = {
|
||||
0xff6c70726f667281ULL, /* magic: \xfflprofr\x81 */
|
||||
11, /* (the format llvm-profdata 24 reads) */
|
||||
0, /* binary ids */
|
||||
ndata, 0, ncnt, 0,
|
||||
0, 0, /* bitmap */
|
||||
0, 0, 0, /* uniform counters */
|
||||
nnames,
|
||||
(uint64_t)(uintptr_t)cb - (uint64_t)(uintptr_t)db, /* CountersDelta */
|
||||
(uint64_t)0, /* BitmapDelta */
|
||||
(uint64_t)(uintptr_t)nb, /* NamesDelta */
|
||||
0, 0, /* vtables */
|
||||
2, /* ValueKindLast (IPVK_Last) */
|
||||
};
|
||||
FILE *f = fopen(path, "wb");
|
||||
if (!f) return;
|
||||
fwrite(header, sizeof header, 1, f);
|
||||
/* (the records' pointers to their counters are 32 bits in a COFF image, the rest zero, and the counters come first: negative) */
|
||||
char *copy = malloc((size_t)(de - db));
|
||||
memcpy(copy, db, (size_t)(de - db));
|
||||
for (uint64_t i = 0; i < ndata; i++) {
|
||||
int32_t rel;
|
||||
memcpy(&rel, copy + i * DATA_SIZE + 16, 4);
|
||||
const int64_t wide = rel;
|
||||
memcpy(copy + i * DATA_SIZE + 16, &wide, 8);
|
||||
}
|
||||
fwrite(copy, 1, (size_t)(de - db), f);
|
||||
free(copy);
|
||||
fwrite(cb, 1, (size_t)(ce - cb), f);
|
||||
fwrite(nb, 1, (size_t)nnames, f);
|
||||
static const char zero[8];
|
||||
fwrite(zero, 1, (size_t)(-(int64_t)nnames & 7), f);
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
static DWORD WINAPI pgo_thread(void *arg) {
|
||||
const char *path = arg;
|
||||
char dump[MAX_PATH], reset[MAX_PATH];
|
||||
snprintf(dump, sizeof dump, "%s.dump", path);
|
||||
snprintf(reset, sizeof reset, "%s.reset", path);
|
||||
for (;;) {
|
||||
Sleep(500);
|
||||
if (GetFileAttributesA(reset) != INVALID_FILE_ATTRIBUTES) {
|
||||
memset(pgo_cnt_a + 8, 0, (size_t)(pgo_cnt_z - (pgo_cnt_a + 8)));
|
||||
DeleteFileA(reset);
|
||||
}
|
||||
if (GetFileAttributesA(dump) != INVALID_FILE_ATTRIBUTES) {
|
||||
pgo_write(path);
|
||||
DeleteFileA(dump);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void pgo_start(void) {
|
||||
const char *e = getenv("HOS_PGO");
|
||||
if (e) CreateThread(NULL, 0, pgo_thread, _strdup(e), 0, NULL);
|
||||
}
|
||||
2
host/posix/direct.h
Normal file
2
host/posix/direct.h
Normal file
@@ -0,0 +1,2 @@
|
||||
/* (linux) direct.h: _mkdir is in windows.h here */
|
||||
#include <windows.h>
|
||||
343
host/posix/display_sdl.c
Normal file
343
host/posix/display_sdl.c
Normal file
@@ -0,0 +1,343 @@
|
||||
/* (linux) The game's window on SDL (host/hos_sdl.c: SDL3, Wayland when there is one, else X11; or SDL2): what
|
||||
host/display.c is on Windows. The window lives on the process's main thread, as SDL wants it (hos_main.c runs the
|
||||
game on a thread of its own on Linux); the Vulkan back end makes its surface through SDL (gpu/vk/vk_api.h
|
||||
MkwVkWindow), on a thread of its own so the window keeps answering while the shaders are prepared.
|
||||
|
||||
The keyboard's state goes to hos_posix_keys (GetAsyncKeyState, for nn_hid.c and the Insert menu), the window's focus
|
||||
and the screen's size to hos_posix_window (GetForegroundWindow, GetSystemMetrics).
|
||||
HOS_HEADLESS=1: no window. HOS_WINDOW_SIZE=<w>x<h>: its size (default 1280x720). F10 or Alt+Enter: fullscreen (HOS_FULLSCREEN=1 to
|
||||
start so). Mouse: a click in the window captures it (relative motion, for nn_hid.c), Esc or leaving releases it.
|
||||
While the Insert menu is open the mouse is free (the cursor shown, for the menu's clicks: hos_mouse_pointer) and
|
||||
the game gets none of it; the capture it had comes back when the menu closes. */
|
||||
#include "../hos.h"
|
||||
#include "../hos_sdl.h"
|
||||
|
||||
/* (the window's app id: the applications menu's entry names it as its StartupWMClass, builder/linux/hookshot_builder.py) */
|
||||
#define HOS_APP_ID "io.github.NotRexed.Hookshot"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <windows.h>
|
||||
#include "../../gpu/vk/vk_api.h"
|
||||
|
||||
int rx_start(void *hwnd);
|
||||
void rx_resize(int width, int height);
|
||||
void rx_close_asked(void);
|
||||
void hos_sdl_pads_pump(void); /* host/pad_sdl.c: controllers, on this thread, as SDL's queue wants */
|
||||
void hos_relaunch_ask(void); /* (host/hos_relaunch.c: the Insert menu's Restart now) */
|
||||
void hos_window_closed_exit(void);
|
||||
|
||||
volatile LONG64 hos_present_count; /* (nvn_native.c: the game's presents) */
|
||||
__attribute__((visibility("default"))) volatile uint8_t hos_posix_keys[256];
|
||||
__attribute__((visibility("default"))) volatile int hos_posix_window[4]; /* focused, screen width, screen height, fullscreen */
|
||||
|
||||
static volatile LONG mouse_dx, mouse_dy, mouse_captured;
|
||||
int hos_mouse_take(int32_t *dx, int32_t *dy) {
|
||||
*dx = InterlockedExchange(&mouse_dx, 0);
|
||||
*dy = InterlockedExchange(&mouse_dy, 0);
|
||||
return mouse_captured;
|
||||
}
|
||||
|
||||
/* (mouse_native.c) motion taken and not used, put back for the next taker (the player camera's) */
|
||||
void hos_mouse_give_back(int32_t dx, int32_t dy) {
|
||||
InterlockedExchangeAdd(&mouse_dx, dx);
|
||||
InterlockedExchangeAdd(&mouse_dy, dy);
|
||||
}
|
||||
|
||||
/* ---- the free mouse, for the Insert menu (gpu/vk/vk_api.h MkwVkPointer): set on the main thread, read on the renderer's ---- */
|
||||
static volatile LONG ptr_x, ptr_y, ptr_in, ptr_held, ptr_pressed, ptr_wheel; /* (x, y in window units; wheel in 1/120 notches) */
|
||||
static volatile int menu_open; /* (WM_APP + 8: the menu's state, as the window last heard it) */
|
||||
static void *window;
|
||||
int hos_mouse_pointer(MkwVkPointer *out) {
|
||||
memset(out, 0, sizeof *out);
|
||||
if (!window || mouse_captured) return 0;
|
||||
int ww = 0, wh = 0, pw = 0, ph = 0;
|
||||
hos_sdl_window_size(window, &ww, &wh); /* (SDL's position is in the window's units: scaled to its pixels) */
|
||||
hos_sdl_pixel_size(window, &pw, &ph);
|
||||
if (ww <= 0 || wh <= 0 || pw <= 0 || ph <= 0) return 0;
|
||||
out->x = (int32_t)((int64_t)ptr_x * pw / ww), out->y = (int32_t)((int64_t)ptr_y * ph / wh);
|
||||
out->width = pw, out->height = ph;
|
||||
out->held = (uint32_t)ptr_held;
|
||||
out->pressed = (uint32_t)InterlockedExchange(&ptr_pressed, 0);
|
||||
const LONG wheel = InterlockedExchange(&ptr_wheel, 0);
|
||||
out->wheel = wheel / 120;
|
||||
if (wheel % 120) InterlockedExchangeAdd(&ptr_wheel, wheel % 120); /* (a part of a notch: kept for the next) */
|
||||
return ptr_in && hos_posix_window[0];
|
||||
}
|
||||
static uint32_t sdl_button_bit(int b) { return b == 1 ? HOS_MOUSE_LEFT : b == 3 ? HOS_MOUSE_RIGHT : b == 2 ? HOS_MOUSE_MIDDLE : 0; }
|
||||
|
||||
/* ---- keys: SDL's scancodes (USB HID usages) as Windows' virtual keys ---- */
|
||||
static void keys_update(void) {
|
||||
int n = 0;
|
||||
const uint8_t *k = hos_sdl_keys(&n);
|
||||
uint8_t v[256];
|
||||
memset(v, 0, sizeof v);
|
||||
if (k && hos_posix_window[0]) {
|
||||
#define K(sc) ((sc) < n && k[sc])
|
||||
for (int i = 0; i < 26; i++) v['A' + i] = K(4 + i);
|
||||
for (int i = 0; i < 9; i++) v['1' + i] = K(30 + i);
|
||||
v['0'] = K(39);
|
||||
v[VK_RETURN] = K(40) || K(88), v[VK_ESCAPE] = K(41), v[VK_BACK] = K(42), v[VK_TAB] = K(43), v[VK_SPACE] = K(44);
|
||||
v[VK_OEM_MINUS] = K(45), v[VK_OEM_PLUS] = K(46), v[VK_OEM_1] = K(51), v[VK_OEM_3] = K(53);
|
||||
v[VK_OEM_COMMA] = K(54), v[VK_OEM_PERIOD] = K(55), v[VK_OEM_2] = K(56), v[VK_CAPITAL] = K(57);
|
||||
v[VK_OEM_4] = K(47), v[VK_OEM_6] = K(48), v[VK_OEM_5] = K(49), v[VK_OEM_7] = K(52); /* ([ ] \ ') */
|
||||
for (int i = 0; i < 12; i++) v[VK_F1 + i] = K(58 + i);
|
||||
v[VK_PAUSE] = K(72), v[VK_INSERT] = K(73), v[VK_HOME] = K(74), v[VK_PRIOR] = K(75), v[VK_DELETE] = K(76);
|
||||
v[VK_END] = K(77), v[VK_NEXT] = K(78), v[VK_RIGHT] = K(79), v[VK_LEFT] = K(80), v[VK_DOWN] = K(81), v[VK_UP] = K(82);
|
||||
v[VK_DIVIDE] = K(84), v[VK_MULTIPLY] = K(85), v[VK_SUBTRACT] = K(86), v[VK_ADD] = K(87);
|
||||
for (int i = 0; i < 9; i++) v[VK_NUMPAD0 + 1 + i] = K(89 + i);
|
||||
v[VK_NUMPAD0] = K(98), v[VK_DECIMAL] = K(99);
|
||||
v[VK_LCONTROL] = K(224), v[VK_LSHIFT] = K(225), v[VK_LMENU] = K(226);
|
||||
v[VK_RCONTROL] = K(228), v[VK_RSHIFT] = K(229), v[VK_RMENU] = K(230);
|
||||
#undef K
|
||||
v[VK_CONTROL] = v[VK_LCONTROL] || v[VK_RCONTROL];
|
||||
v[VK_SHIFT] = v[VK_LSHIFT] || v[VK_RSHIFT];
|
||||
v[VK_MENU] = v[VK_LMENU] || v[VK_RMENU];
|
||||
const uint32_t b = hos_sdl_mouse_buttons();
|
||||
v[VK_LBUTTON] = (b & 1) != 0, v[VK_MBUTTON] = (b & 2) != 0, v[VK_RBUTTON] = (b & 4) != 0;
|
||||
}
|
||||
for (int i = 0; i < 256; i++) hos_posix_keys[i] = v[i];
|
||||
}
|
||||
|
||||
/* ---- the window ---- */
|
||||
static volatile int renderer; /* the renderer presents into the window */
|
||||
static HANDLE renderer_up; /* (set once rx_start has returned, ready or not: hos_renderer_wait) */
|
||||
static int fullscreen;
|
||||
|
||||
static int create_surface(void *w, void *instance, void *surface) { return hos_sdl_vulkan_surface(w, instance, surface); }
|
||||
static void drawable_size(void *w, int *width, int *height) { hos_sdl_pixel_size(w, width, height); }
|
||||
/* (SDL's display calls belong on this thread: the loop asks every second, the renderer reads what it found) */
|
||||
static volatile int refresh_now;
|
||||
static int refresh_mhz(void *w) { (void)w; return __atomic_load_n(&refresh_now, __ATOMIC_RELAXED); }
|
||||
static MkwVkWindow vk_window = {MKWVK_WINDOW_VERSION, create_surface, drawable_size, NULL, refresh_mhz};
|
||||
|
||||
static void mouse_capture(int on) {
|
||||
if (on == (int)mouse_captured) return;
|
||||
mouse_captured = on;
|
||||
InterlockedExchange(&mouse_dx, 0);
|
||||
InterlockedExchange(&mouse_dy, 0);
|
||||
hos_sdl_relative_mouse(window, on);
|
||||
}
|
||||
static void set_fullscreen(int on) {
|
||||
if (on == fullscreen) return;
|
||||
fullscreen = on;
|
||||
hos_posix_window[3] = on;
|
||||
hos_sdl_fullscreen(window, on);
|
||||
hos_log("display: %s", on ? "fullscreen" : "windowed");
|
||||
}
|
||||
|
||||
static DWORD WINAPI renderer_main(void *p) {
|
||||
(void)p;
|
||||
const int ok = rx_start(&vk_window);
|
||||
if (!ok) hos_log("display: the renderer did not start: the window stays black");
|
||||
renderer = ok;
|
||||
if (ok) { /* (a size change while it started) */
|
||||
int w = 0, h = 0;
|
||||
hos_sdl_pixel_size(window, &w, &h);
|
||||
if (w > 0 && h > 0) rx_resize(w, h);
|
||||
}
|
||||
SetEvent(renderer_up);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* (hookshot) host/display.c's: the game's first work for the GPU waits for the renderer (nvn_native.c), so nothing it submits while
|
||||
the shaders are prepared is lost. Without a window the renderer starts on the game's own thread, before this is asked */
|
||||
void hos_renderer_wait(void) {
|
||||
{ const char *e = getenv("HOS_NO_RENDERER_WAIT"); if (e && atoi(e) != 0) return; }
|
||||
if (renderer_up) WaitForSingleObject(renderer_up, INFINITE);
|
||||
}
|
||||
|
||||
static volatile int start_asked;
|
||||
static volatile int fullscreen_asked = -1; /* (the Insert menu's row, from the renderer's thread: applied on this one) */
|
||||
static volatile int menu_asked = -1; /* (the Insert menu opened or closed, likewise) */
|
||||
static volatile int restart_asked; /* (the Insert menu's Restart now: the window closes as by the player) */
|
||||
static volatile int close_asked; /* (the Insert menu's Quit: likewise, without the relaunch) */
|
||||
|
||||
/* PostMessageA to the window (host/posix/win32_posix.c): WM_APP + 7, the Insert menu's Fullscreen row, WM_APP + 8 the
|
||||
menu opened or closed, WM_APP + 9 its Restart now, WM_CLOSE its Quit (host/display.c's) */
|
||||
__attribute__((visibility("default"))) void hos_posix_post_message(uint32_t msg, uintptr_t wp, intptr_t lp) {
|
||||
(void)lp;
|
||||
if (msg == WM_APP + 7) __atomic_store_n(&fullscreen_asked, wp ? 1 : 0, __ATOMIC_RELEASE);
|
||||
if (msg == WM_APP + 8) __atomic_store_n(&menu_asked, wp ? 1 : 0, __ATOMIC_RELEASE);
|
||||
if (msg == WM_APP + 9) __atomic_store_n(&restart_asked, 1, __ATOMIC_RELEASE);
|
||||
if (msg == WM_CLOSE) __atomic_store_n(&close_asked, 1, __ATOMIC_RELEASE);
|
||||
}
|
||||
/* the menu opened: the mouse let go (its capture kept for later); closed: the capture back, if the window still has the focus */
|
||||
static int captured_before_menu;
|
||||
static void menu_mouse(int open) {
|
||||
if (open == menu_open) return;
|
||||
menu_open = open;
|
||||
if (open) {
|
||||
captured_before_menu = (int)mouse_captured;
|
||||
mouse_capture(0);
|
||||
InterlockedExchange(&ptr_pressed, 0), InterlockedExchange(&ptr_wheel, 0);
|
||||
} else {
|
||||
if (captured_before_menu && hos_posix_window[0]) mouse_capture(1);
|
||||
captured_before_menu = 0;
|
||||
}
|
||||
}
|
||||
static int sdl_ready;
|
||||
int hos_display_owns_sdl(void) { return sdl_ready; } /* (controllers stay on this thread while it runs SDL) */
|
||||
|
||||
/* main(), before the game: SDL's video on this, the main, thread; the screen's size for GetSystemMetrics.
|
||||
Returns 1 when ready, 0 for explicit headless, -1 for startup failure. */
|
||||
int hos_display_init(void) {
|
||||
if (getenv("HOS_HEADLESS")) return 0;
|
||||
if (!hos_sdl_load()) {
|
||||
hos_log("display: no SDL: no window");
|
||||
fprintf(stderr, "display: no SDL: no window\n");
|
||||
return -1;
|
||||
}
|
||||
hos_sdl_identity("Triforce", HOS_APP_ID);
|
||||
hos_sdl_hint("SDL_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR", "0");
|
||||
hos_sdl_hint("SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS", "1");
|
||||
/* (bundled SDL tries x11 before wayland. NVIDIA's X11 surface has no mailbox, and an immediate
|
||||
present then drops vblank for every output. Wayland has mailbox. SDL_VIDEODRIVER (SDL3: SDL_VIDEO_DRIVER) still wins.
|
||||
Under gamescope (XDG_CURRENT_DESKTOP names it: Steam Deck game mode) SDL keeps its own order.) */
|
||||
const char* desktop = getenv("XDG_CURRENT_DESKTOP");
|
||||
const int gamescope = desktop && strstr(desktop, "gamescope");
|
||||
if (!getenv("SDL_VIDEODRIVER") && !getenv("SDL_VIDEO_DRIVER") && !gamescope)
|
||||
hos_sdl_hint(hos_sdl_load() == 3 ? "SDL_VIDEO_DRIVER" : "SDL_VIDEODRIVER", "wayland,x11");
|
||||
if (!hos_sdl_init(HOS_SDL_VIDEO | HOS_SDL_EVENTS)) {
|
||||
hos_log("display: SDL_Init: %s: no window", hos_sdl_error());
|
||||
fprintf(stderr, "display: SDL_Init: %s: no window\n", hos_sdl_error());
|
||||
return -1;
|
||||
}
|
||||
int w, h;
|
||||
if (hos_sdl_desktop_size(&w, &h)) hos_posix_window[1] = w, hos_posix_window[2] = h;
|
||||
sdl_ready = 1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* the game's thread, when NVN is up (hos_main.c): the window is made on the main thread, which waits for this */
|
||||
void hos_display_start(void) {
|
||||
if (getenv("HOS_HEADLESS") || !sdl_ready) { /* no window: the renderer still draws, offscreen (screenshots) */
|
||||
rx_start(NULL);
|
||||
return;
|
||||
}
|
||||
renderer_up = CreateEventA(NULL, TRUE, FALSE, NULL);
|
||||
__atomic_store_n(&start_asked, 1, __ATOMIC_RELEASE);
|
||||
}
|
||||
|
||||
/* the main thread's loop, until the process ends: the window once asked for, then its events */
|
||||
void hos_display_loop(void) {
|
||||
if (!sdl_ready) {
|
||||
for (;;) Sleep(1000);
|
||||
}
|
||||
HosSdlEvent e;
|
||||
while (!__atomic_load_n(&start_asked, __ATOMIC_ACQUIRE)) hos_sdl_wait_event(&e, 10); /* (nothing to show yet) */
|
||||
extern float hos_aspect_ratio;
|
||||
/* (the picture's shape when Monitor's shape set one, wider or narrower than 16:9: 960 x 720 for 4:3, 1720 x 720 for 21:9) */
|
||||
int win_w = hos_aspect_ratio > 0.0f ? (int)(720 * hos_aspect_ratio + 0.5f) : 1280, win_h = 720;
|
||||
if (getenv("HOS_WINDOW_SIZE")) {
|
||||
int w = 0, h = 0;
|
||||
if (sscanf(getenv("HOS_WINDOW_SIZE"), "%dx%d", &w, &h) == 2 && w >= 64 && h >= 64) win_w = w, win_h = h;
|
||||
}
|
||||
window = hos_sdl_window(HOS_GAME_TITLE, win_w, win_h);
|
||||
if (!window) {
|
||||
hos_log("display: SDL_CreateWindow: %s: no window", hos_sdl_error());
|
||||
fprintf(stderr, "display: SDL_CreateWindow: %s: no window\n", hos_sdl_error());
|
||||
hos_log_flush();
|
||||
ExitProcess(1);
|
||||
}
|
||||
vk_window.window = window;
|
||||
hos_posix_window[0] = 1;
|
||||
{ /* the window's icon: hookshot.png beside the game (make_game.py puts it there), for X11 and the compositors that
|
||||
take one from the window; the others find it through the menu entry */
|
||||
char png[MAX_PATH];
|
||||
DWORD n = GetModuleFileNameA(NULL, png, MAX_PATH);
|
||||
while (n && png[n - 1] != '/') n--;
|
||||
snprintf(png + n, sizeof png - n, "triforce.png");
|
||||
hos_sdl_icon(window, png);
|
||||
}
|
||||
if (getenv("HOS_FULLSCREEN") && atoi(getenv("HOS_FULLSCREEN"))) set_fullscreen(1);
|
||||
__atomic_store_n(&refresh_now, hos_sdl_refresh_mhz(window), __ATOMIC_RELAXED);
|
||||
CloseHandle(CreateThread(NULL, 0, renderer_main, NULL, 0, NULL));
|
||||
DWORD refresh_asked = GetTickCount();
|
||||
for (;;) {
|
||||
hos_sdl_pads_pump();
|
||||
if (GetTickCount() - refresh_asked >= 1000) { /* (the window may have moved to another display) */
|
||||
refresh_asked = GetTickCount();
|
||||
__atomic_store_n(&refresh_now, hos_sdl_refresh_mhz(window), __ATOMIC_RELAXED);
|
||||
}
|
||||
if (hos_sdl_wait_event(&e, 4)) {
|
||||
do {
|
||||
switch (e.type) {
|
||||
case HOS_SDL_EV_QUIT:
|
||||
case HOS_SDL_EV_CLOSE:
|
||||
rx_close_asked(); /* (a start still preparing the shaders keeps what it made) */
|
||||
hos_window_closed_exit();
|
||||
case HOS_SDL_EV_RESIZED:
|
||||
if (renderer) {
|
||||
int w = 0, h = 0;
|
||||
hos_sdl_pixel_size(window, &w, &h);
|
||||
rx_resize(w, h);
|
||||
}
|
||||
break;
|
||||
case HOS_SDL_EV_FOCUS_GAINED:
|
||||
hos_posix_window[0] = 1;
|
||||
break;
|
||||
case HOS_SDL_EV_FOCUS_LOST:
|
||||
hos_posix_window[0] = 0;
|
||||
mouse_capture(0);
|
||||
ptr_in = 0, ptr_held = 0;
|
||||
break;
|
||||
case HOS_SDL_EV_MOUSE_LEAVE:
|
||||
/* (Wayland: turning the relative mode on sends a leave in the same millisecond (Mutter), and
|
||||
releasing here dropped the capture before the first motion: the mouse turned nothing and its
|
||||
buttons did nothing. The capture goes with the window's focus, not with the pointer: Windows
|
||||
releases on WM_KILLFOCUS alone, host/display.c.) */
|
||||
ptr_in = 0;
|
||||
break;
|
||||
case HOS_SDL_EV_MOUSE_ENTER:
|
||||
ptr_in = 1;
|
||||
break;
|
||||
case HOS_SDL_EV_KEY_DOWN: {
|
||||
const int scancode = e.scancode, mod = e.mod;
|
||||
if (e.scancode == 41) mouse_capture(0); /* Esc */
|
||||
if (!e.repeat && ((scancode == 67 && !(mod & 0x0FC3)) || (scancode == 40 && (mod & 0x300)))) set_fullscreen(!fullscreen); /* F10, Alt+Enter (Triforce: F11 is off) */
|
||||
break;
|
||||
}
|
||||
case HOS_SDL_EV_MOUSE_DOWN:
|
||||
ptr_x = (LONG)e.x, ptr_y = (LONG)e.y, ptr_in = 1;
|
||||
InterlockedOr(&ptr_held, (LONG)sdl_button_bit(e.button));
|
||||
if (menu_open) InterlockedOr(&ptr_pressed, (LONG)sdl_button_bit(e.button)); /* (the menu's click) */
|
||||
else if (renderer && !mouse_captured) mouse_capture(1);
|
||||
break;
|
||||
case HOS_SDL_EV_MOUSE_UP:
|
||||
ptr_x = (LONG)e.x, ptr_y = (LONG)e.y;
|
||||
InterlockedAnd(&ptr_held, ~(LONG)sdl_button_bit(e.button));
|
||||
break;
|
||||
case HOS_SDL_EV_MOUSE_WHEEL:
|
||||
if (menu_open) InterlockedExchangeAdd(&ptr_wheel, (LONG)(e.wheel * 120));
|
||||
break;
|
||||
case HOS_SDL_EV_MOUSE_MOTION:
|
||||
if (!mouse_captured) ptr_x = (LONG)e.x, ptr_y = (LONG)e.y, ptr_in = 1;
|
||||
if (mouse_captured) { /* (SDL3's motion comes in fractions of a pixel: the remainders kept for the next) */
|
||||
static float rx, ry;
|
||||
rx += e.dx, ry += e.dy;
|
||||
const LONG dx = (LONG)rx, dy = (LONG)ry;
|
||||
rx -= (float)dx, ry -= (float)dy;
|
||||
InterlockedExchangeAdd(&mouse_dx, dx);
|
||||
InterlockedExchangeAdd(&mouse_dy, dy);
|
||||
}
|
||||
break;
|
||||
}
|
||||
} while (hos_sdl_poll_event(&e));
|
||||
}
|
||||
const int asked = __atomic_exchange_n(&fullscreen_asked, -1, __ATOMIC_ACQ_REL);
|
||||
if (asked >= 0) set_fullscreen(asked);
|
||||
const int menu = __atomic_exchange_n(&menu_asked, -1, __ATOMIC_ACQ_REL);
|
||||
if (menu >= 0) menu_mouse(menu);
|
||||
if (__atomic_load_n(&restart_asked, __ATOMIC_ACQUIRE)) {
|
||||
hos_relaunch_ask();
|
||||
rx_close_asked();
|
||||
hos_window_closed_exit();
|
||||
}
|
||||
if (__atomic_load_n(&close_asked, __ATOMIC_ACQUIRE)) {
|
||||
rx_close_asked();
|
||||
hos_window_closed_exit();
|
||||
}
|
||||
keys_update();
|
||||
}
|
||||
}
|
||||
3
host/posix/io.h
Normal file
3
host/posix/io.h
Normal file
@@ -0,0 +1,3 @@
|
||||
/* (linux) io.h: POSIX has these in unistd.h */
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
50
host/posix/linux_stubs.c
Normal file
50
host/posix/linux_stubs.c
Normal file
@@ -0,0 +1,50 @@
|
||||
/* (linux) What the Windows build has and Linux does without:
|
||||
|
||||
- Media Foundation's AV1 decoder (host/mf_av1.c): FFmpeg decodes AV1 itself here, with dav1d (host/nn_video.c asks
|
||||
FFmpeg first), so these are never reached with a dav1d build; without one, AV1 movies are skipped.
|
||||
- The WebGPU renderer (gpu/render, wgr_*): the Vulkan back end is the only renderer on Linux. Should it not start,
|
||||
these leave the window black, as a WebGPU renderer without a device does. */
|
||||
#include "../hos.h"
|
||||
#include "../../gpu/vk/vk_api.h"
|
||||
|
||||
typedef void (*mf_av1_picture_fn)(void *user, const uint8_t *y, const uint8_t *uv, int w, int h, int stride, int64_t pts);
|
||||
void *mf_av1_open(int w, int h) { (void)w, (void)h; return NULL; }
|
||||
void mf_av1_decode(void *m, const uint8_t *data, size_t n, int64_t pts, mf_av1_picture_fn fn, void *user) {
|
||||
(void)m, (void)data, (void)n, (void)pts, (void)fn, (void)user;
|
||||
}
|
||||
void mf_av1_flush(void *m) { (void)m; }
|
||||
void mf_av1_close(void *m) { (void)m; }
|
||||
|
||||
int wgr_start(void *hwnd) { (void)hwnd; hos_log("rx: no WebGPU renderer in the Linux build: nothing is drawn"); return 0; }
|
||||
void wgr_resize(int width, int height) { (void)width, (void)height; }
|
||||
const char *wgr_describe(void) { return "none"; }
|
||||
void wgr_stats(int64_t *draws, int64_t *skipped, int64_t *pipelines) { *draws = *skipped = *pipelines = 0; }
|
||||
void wgr_nvn_submit(const uint64_t *handles, int n) { (void)handles, (void)n; }
|
||||
uint64_t wgr_nvn_fence(void) { return 0; }
|
||||
uint64_t wgr_nvn_pushed(void) { return 0; }
|
||||
uint64_t wgr_nvn_replayed(void) { return 0; }
|
||||
int wgr_nvn_wait(uint64_t fence, uint64_t timeout_ns) { (void)fence, (void)timeout_ns; return 1; }
|
||||
void wgr_wait_writebacks_reading(const void *p, uint64_t n) { (void)p, (void)n; }
|
||||
void wgr_nvn_finish(void) {}
|
||||
void wgr_nvn_present(const nvn_tex *t, const int crop[4]) { (void)t, (void)crop; }
|
||||
void wgr_nvn_register_texture(int id, const nvn_tex *t, const nvn_view *v) { (void)id, (void)t, (void)v; }
|
||||
void wgr_nvn_register_sampler(int id, const nvn_samp_par *p) { (void)id, (void)p; }
|
||||
void wgr_nvn_set_texture_pool_size(int n) { (void)n; }
|
||||
void wgr_nvn_texture_released(const nvn_tex *t) { (void)t; }
|
||||
void wgr_nvn_program_released(const nvn_prog *p) { (void)p; }
|
||||
void wgr_nvn_read_texels(const nvn_tex *t, unsigned level, unsigned layer0, const NVNcopyRegion *r, uint8_t *dst,
|
||||
uint64_t row, uint64_t img) {
|
||||
(void)t, (void)level, (void)layer0, (void)r, (void)dst, (void)row, (void)img;
|
||||
}
|
||||
void wgr_nvn_write_texels(const nvn_tex *t, unsigned level, unsigned layer0, const NVNcopyRegion *r, const uint8_t *src,
|
||||
uint64_t row, uint64_t img) {
|
||||
(void)t, (void)level, (void)layer0, (void)r, (void)src, (void)row, (void)img;
|
||||
}
|
||||
void wgr_nvn_invalidate(uint64_t gpu, uint64_t size) { (void)gpu, (void)size; }
|
||||
/* (gpu/render/rx_core.cpp's, for the soft write watch's other consumer) */
|
||||
uint32_t *rx_collect_written(int64_t *count) { *count = -1; return NULL; }
|
||||
/* (gpu/render's debugging commands: host/nn_hid.c's live input "!dump", "!shots", "!rdoc", "!flasharm") */
|
||||
void rx_request_frame_dump(void) { hos_log("rx: frame dumps are the WebGPU renderer's: not in the Linux build"); }
|
||||
void rx_set_screenshot_ms(int64_t ms) { (void)ms; hos_log("rx: !shots is the WebGPU renderer's: RX_VK_SHOTS instead"); }
|
||||
void rx_request_rdoc_capture(int frames) { (void)frames; }
|
||||
void rx_flash_dark_arm(void) {}
|
||||
42
host/posix/mmsystem.h
Normal file
42
host/posix/mmsystem.h
Normal file
@@ -0,0 +1,42 @@
|
||||
/* (linux) waveOut, the audio renderer's output (host/nn_audio.c), on SDL's audio (win32_posix.c): the blocks written
|
||||
play in order and are marked WHDR_DONE as the device takes them, as on Windows. */
|
||||
#ifndef HOOKSHOT_POSIX_MMSYSTEM_H
|
||||
#define HOOKSHOT_POSIX_MMSYSTEM_H
|
||||
#include <windows.h>
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
typedef UINT MMRESULT;
|
||||
typedef void *HWAVEOUT;
|
||||
#define MMSYSERR_NOERROR 0
|
||||
#define MMSYSERR_ERROR 1
|
||||
#define WAVE_MAPPER ((UINT)-1)
|
||||
#define WAVE_FORMAT_PCM 1
|
||||
#define CALLBACK_NULL 0
|
||||
#define WHDR_DONE 0x1
|
||||
#define WHDR_PREPARED 0x2
|
||||
#define WHDR_INQUEUE 0x10
|
||||
typedef struct {
|
||||
WORD wFormatTag, nChannels;
|
||||
DWORD nSamplesPerSec, nAvgBytesPerSec;
|
||||
WORD nBlockAlign, wBitsPerSample, cbSize;
|
||||
} WAVEFORMATEX;
|
||||
typedef struct wavehdr_tag {
|
||||
LPSTR lpData;
|
||||
DWORD dwBufferLength, dwBytesRecorded;
|
||||
DWORD_PTR dwUser;
|
||||
volatile DWORD dwFlags;
|
||||
DWORD dwLoops;
|
||||
struct wavehdr_tag *lpNext;
|
||||
DWORD_PTR reserved;
|
||||
} WAVEHDR;
|
||||
MMRESULT waveOutOpen(HWAVEOUT *out, UINT device, const WAVEFORMATEX *f, DWORD_PTR cb, DWORD_PTR inst, DWORD flags);
|
||||
MMRESULT waveOutPrepareHeader(HWAVEOUT w, WAVEHDR *h, UINT size);
|
||||
MMRESULT waveOutUnprepareHeader(HWAVEOUT w, WAVEHDR *h, UINT size);
|
||||
MMRESULT waveOutWrite(HWAVEOUT w, WAVEHDR *h, UINT size);
|
||||
MMRESULT waveOutReset(HWAVEOUT w);
|
||||
MMRESULT waveOutClose(HWAVEOUT w);
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
507
host/posix/prof.c
Normal file
507
host/posix/prof.c
Normal file
@@ -0,0 +1,507 @@
|
||||
/* (linux) host/mkw_glue.c's profilers, with the same variables and the same lines in the log and files:
|
||||
HOS_PROFILE=<seconds> (the busiest threads), HOS_THREAD_TIMES=<seconds> (threads over 5% of a core), HOS_SAMPLE=<thread
|
||||
name> + HOS_SAMPLE_FILE (one thread's stacks every millisecond), HOS_SAMPLE_ALL=<path> (every guest thread and the
|
||||
renderer's at once, every 2 ms, while <path>.go exists) and HOS_WATCH=<file> (data breakpoints on guest addresses).
|
||||
Windows reads other threads with SuspendThread + GetThreadContext + RtlVirtualUnwind and sets debug registers; here:
|
||||
- CPU time per thread from /proc/self/task/<tid>/schedstat (stat's utime + stime without schedstats);
|
||||
- a thread's stack from inside it: SAMPLE_SIG sent to it with tgkill, its handler takes the interrupted rip from the
|
||||
signal's context and unwinds from there with libgcc's unwinder (the .eh_frame clang writes), the sampler waits;
|
||||
- breakpoints with perf_event_open (PERF_TYPE_BREAKPOINT, sigtrap=1: a SIGTRAP in the thread that touched the
|
||||
address, si_code TRAP_PERF), allowed on our own threads at the default perf_event_paranoid (2).
|
||||
Frames are written as <module>+<offset from its load base>: hookshot and triforce_vk.so,
|
||||
offsets as in their linker maps (position-independent, based at 0). */
|
||||
#include "../hos.h"
|
||||
#include <dirent.h>
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <linux/hw_breakpoint.h>
|
||||
#include <linux/perf_event.h>
|
||||
#include <sched.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <time.h>
|
||||
#include <ucontext.h>
|
||||
#include <unistd.h>
|
||||
#include <unwind.h>
|
||||
#include <windows.h>
|
||||
#ifndef TRAP_PERF /* (the kernel's since 5.13; glibc names it from 2.36) */
|
||||
#define TRAP_PERF 6
|
||||
#endif
|
||||
|
||||
int hos_thread_handles(HANDLE *out, const char **names, int max); /* hos_thread.c */
|
||||
void hos_prof_start(void);
|
||||
|
||||
/* ---- the process's threads: id, CPU time, name (the guest thread's, else the thread's own: SetThreadDescription) ---- */
|
||||
typedef struct { int tid; uint64_t cpu_ns; char name[64]; int guest; } Task;
|
||||
|
||||
static uint64_t task_cpu_ns(int tid) {
|
||||
char p[64];
|
||||
unsigned long long ns = 0, ut = 0, st = 0;
|
||||
snprintf(p, sizeof p, "/proc/self/task/%d/schedstat", tid);
|
||||
FILE *f = fopen(p, "r");
|
||||
if (f) {
|
||||
const int got = fscanf(f, "%llu", &ns);
|
||||
fclose(f);
|
||||
if (got == 1) return ns;
|
||||
}
|
||||
snprintf(p, sizeof p, "/proc/self/task/%d/stat", tid);
|
||||
f = fopen(p, "r");
|
||||
if (!f) return 0;
|
||||
char line[1024];
|
||||
const char *s = fgets(line, sizeof line, f) ? strrchr(line, ')') : NULL;
|
||||
fclose(f);
|
||||
/* (after "(comm)": state is field 3, utime 14, stime 15) */
|
||||
if (!s || sscanf(s + 1, " %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu", &ut, &st) != 2) return 0;
|
||||
return (ut + st) * (1000000000ull / (unsigned long long)sysconf(_SC_CLK_TCK));
|
||||
}
|
||||
static void task_comm(int tid, char *out, size_t cap) {
|
||||
char p[64];
|
||||
snprintf(p, sizeof p, "/proc/self/task/%d/comm", tid);
|
||||
out[0] = 0;
|
||||
FILE *f = fopen(p, "r");
|
||||
if (!f) return;
|
||||
if (fgets(out, (int)cap, f)) out[strcspn(out, "\n")] = 0;
|
||||
fclose(f);
|
||||
}
|
||||
static int tasks(Task *out, int max) {
|
||||
static HANDLE gh[1024];
|
||||
static const char *gn[1024];
|
||||
const int ng = hos_thread_handles(gh, gn, 1024);
|
||||
static int gtid[1024];
|
||||
for (int i = 0; i < ng; i++) gtid[i] = (int)GetThreadId(gh[i]);
|
||||
int n = 0;
|
||||
DIR *d = opendir("/proc/self/task");
|
||||
if (!d) return 0;
|
||||
for (struct dirent *e; (e = readdir(d)) && n < max;) {
|
||||
const int tid = atoi(e->d_name);
|
||||
if (tid <= 0) continue;
|
||||
Task *t = &out[n++];
|
||||
t->tid = tid;
|
||||
t->cpu_ns = task_cpu_ns(tid);
|
||||
t->guest = 0;
|
||||
t->name[0] = 0;
|
||||
for (int i = 0; i < ng; i++)
|
||||
if (gtid[i] == tid) { snprintf(t->name, sizeof t->name, "%s", gn[i]); t->guest = 1; break; }
|
||||
if (!t->name[0]) task_comm(tid, t->name, sizeof t->name);
|
||||
if (!t->name[0]) snprintf(t->name, sizeof t->name, "tid %d", tid);
|
||||
}
|
||||
closedir(d);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* HOS_PROFILE=<seconds>: every interval, the busiest threads and their share of a core */
|
||||
static DWORD WINAPI prof_thread(void *p) {
|
||||
const DWORD ms = (DWORD)(uintptr_t)p * 1000;
|
||||
enum { MAXT = 512 };
|
||||
static int ids[MAXT];
|
||||
static uint64_t was[MAXT];
|
||||
int nwas = 0;
|
||||
for (;;) {
|
||||
Sleep(ms);
|
||||
static Task cur[MAXT];
|
||||
static uint64_t delta[MAXT];
|
||||
const int n = tasks(cur, MAXT);
|
||||
for (int i = 0; i < n; i++) {
|
||||
delta[i] = cur[i].cpu_ns;
|
||||
for (int k = 0; k < nwas; k++)
|
||||
if (ids[k] == cur[i].tid) { delta[i] = cur[i].cpu_ns - was[k]; break; }
|
||||
}
|
||||
for (int i = 0; i < n; i++) ids[i] = cur[i].tid, was[i] = cur[i].cpu_ns;
|
||||
nwas = n;
|
||||
for (int i = 0; i < n; i++) /* (busiest first) */
|
||||
for (int j = i + 1; j < n; j++)
|
||||
if (delta[j] > delta[i]) {
|
||||
Task t = cur[i]; cur[i] = cur[j]; cur[j] = t;
|
||||
const uint64_t d = delta[i]; delta[i] = delta[j]; delta[j] = d;
|
||||
}
|
||||
char line[1024];
|
||||
int len = snprintf(line, sizeof line, "prof: busiest threads (%% of a core):");
|
||||
uint64_t total = 0;
|
||||
for (int i = 0; i < n; i++) total += delta[i];
|
||||
for (int i = 0; i < n && i < 10 && len < (int)sizeof line - 80; i++)
|
||||
len += snprintf(line + len, sizeof line - len, " %s %.0f,", cur[i].name, delta[i] / (ms * 10000.0));
|
||||
snprintf(line + len, sizeof line - len, " all %.0f", total / (ms * 10000.0));
|
||||
hos_log("%s", line);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* HOS_THREAD_TIMES=<seconds>: every interval, the threads that used over 5% of a core */
|
||||
static DWORD WINAPI thread_times_thread(void *p) {
|
||||
const DWORD ms = (DWORD)(uintptr_t)p * 1000;
|
||||
enum { MAXT = 512 };
|
||||
static struct { int tid; uint64_t cpu; } last[MAXT];
|
||||
int nlast = 0;
|
||||
for (;;) {
|
||||
Sleep(ms);
|
||||
static Task now[MAXT];
|
||||
const int n = tasks(now, MAXT);
|
||||
char line[4096];
|
||||
int len = snprintf(line, sizeof line, "threads in %u s:", (unsigned)(ms / 1000));
|
||||
for (int i = 0; i < n; i++) {
|
||||
uint64_t before = 0;
|
||||
int seen = 0;
|
||||
for (int k = 0; k < nlast; k++)
|
||||
if (last[k].tid == now[i].tid) before = last[k].cpu, seen = 1;
|
||||
const double pct = seen ? (double)(now[i].cpu_ns - before) / (ms * 1e6) * 100.0 : 0;
|
||||
if (pct >= 5.0 && len < (int)sizeof line - 96) len += snprintf(line + len, sizeof line - len, " %s %.0f%%;", now[i].name, pct);
|
||||
}
|
||||
for (int i = 0; i < n; i++) last[i].tid = now[i].tid, last[i].cpu = now[i].cpu_ns;
|
||||
nlast = n;
|
||||
hos_log("prof: %s", line);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ---- one thread's stack, taken inside it ---- */
|
||||
#define SAMPLE_SIG (SIGRTMIN + 3)
|
||||
enum { DEPTH = 48 };
|
||||
static volatile int sample_tid;
|
||||
static volatile int sample_done;
|
||||
static uintptr_t sample_pcs[DEPTH];
|
||||
static int sample_n;
|
||||
|
||||
typedef struct { uintptr_t *pcs; int n, max; uintptr_t rip; int found; } Walk;
|
||||
static _Unwind_Reason_Code walk_step(struct _Unwind_Context *uc, void *p) {
|
||||
Walk *w = (Walk *)p;
|
||||
int before = 0;
|
||||
const uintptr_t ip = (uintptr_t)_Unwind_GetIPInfo(uc, &before);
|
||||
if (!w->found) { /* (the handler's frames and the signal's trampoline, up to the interrupted frame: frame 0) */
|
||||
if (ip == w->rip) w->found = 1;
|
||||
return _URC_NO_REASON;
|
||||
}
|
||||
if (w->n >= w->max || !ip) return _URC_END_OF_STACK;
|
||||
w->pcs[w->n++] = ip; /* (return addresses, as the Windows sampler writes them) */
|
||||
return _URC_NO_REASON;
|
||||
}
|
||||
static void on_sample(int sig, siginfo_t *si, void *uctx) {
|
||||
(void)sig, (void)si;
|
||||
const int saved = errno;
|
||||
if ((int)syscall(SYS_gettid) == sample_tid) {
|
||||
const ucontext_t *u = (const ucontext_t *)uctx;
|
||||
const uintptr_t rip = (uintptr_t)u->uc_mcontext.gregs[REG_RIP];
|
||||
Walk w = {sample_pcs + 1, 0, DEPTH - 1, rip, 0};
|
||||
sample_pcs[0] = rip;
|
||||
_Unwind_Backtrace(walk_step, &w);
|
||||
sample_n = 1 + w.n;
|
||||
__atomic_store_n(&sample_done, 1, __ATOMIC_RELEASE);
|
||||
}
|
||||
errno = saved;
|
||||
}
|
||||
static void sampling_init(void) {
|
||||
static int done;
|
||||
if (done++) return;
|
||||
struct sigaction sa;
|
||||
memset(&sa, 0, sizeof sa);
|
||||
sa.sa_sigaction = on_sample;
|
||||
sa.sa_flags = SA_SIGINFO | SA_RESTART | SA_ONSTACK;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sigaction(SAMPLE_SIG, &sa, NULL);
|
||||
Walk w = {sample_pcs, 0, 1, 0, 1};
|
||||
_Unwind_Backtrace(walk_step, &w); /* (the unwinder's first use loads and sets up: not in a handler) */
|
||||
}
|
||||
/* the thread's frames, leaf first, into pcs; 0 when it did not answer within 50 ms or has ended */
|
||||
static int sample_one(int tid, uintptr_t *pcs, int max) {
|
||||
__atomic_store_n(&sample_done, 0, __ATOMIC_RELAXED);
|
||||
__atomic_store_n(&sample_tid, tid, __ATOMIC_RELEASE);
|
||||
if (syscall(SYS_tgkill, getpid(), tid, SAMPLE_SIG)) { sample_tid = 0; return -1; }
|
||||
const int64_t until = hos_now_ns() + 50000000;
|
||||
while (!__atomic_load_n(&sample_done, __ATOMIC_ACQUIRE)) {
|
||||
if (hos_now_ns() > until) { __atomic_store_n(&sample_tid, 0, __ATOMIC_RELEASE); return 0; }
|
||||
sched_yield();
|
||||
}
|
||||
sample_tid = 0;
|
||||
const int n = sample_n < max ? sample_n : max;
|
||||
memcpy(pcs, sample_pcs, sizeof *pcs * (size_t)n);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* a code address as module + offset: the module's file name and load base (dladdr) */
|
||||
typedef struct { uintptr_t base; char name[64]; } Module;
|
||||
static Module mods[64];
|
||||
static int nmods;
|
||||
static int module_of(uintptr_t pc, uintptr_t *base) {
|
||||
Dl_info d;
|
||||
if (!dladdr((void *)pc, &d) || !d.dli_fbase) { *base = 0; return -1; }
|
||||
*base = (uintptr_t)d.dli_fbase;
|
||||
for (int i = 0; i < nmods; i++)
|
||||
if (mods[i].base == *base) return i;
|
||||
if (nmods >= 64) return -1;
|
||||
const char *n = d.dli_fname && d.dli_fname[0] ? d.dli_fname : "hookshot";
|
||||
const char *b = strrchr(n, '/');
|
||||
mods[nmods].base = *base;
|
||||
snprintf(mods[nmods].name, sizeof mods[nmods].name, "%s", b ? b + 1 : n);
|
||||
return nmods++;
|
||||
}
|
||||
static uintptr_t exe_base(void) {
|
||||
uintptr_t base = 0;
|
||||
module_of((uintptr_t)&hos_prof_start, &base);
|
||||
return base;
|
||||
}
|
||||
|
||||
/* HOS_SAMPLE=<thread name> (with HOS_PROFILE=<seconds>): that thread sampled every millisecond; every interval its
|
||||
most frequent places, as module+offset of the leaf and of the first frame in the runtime under it. HOS_SAMPLE_FILE:
|
||||
every sample's whole stack too, a line of frames leaf first (scripts/prof.py) */
|
||||
static DWORD WINAPI sample_thread(void *p) {
|
||||
const char *want = (const char *)p;
|
||||
const DWORD ms = (DWORD)atoi(getenv("HOS_PROFILE")) * 1000;
|
||||
sampling_init();
|
||||
int tid = 0;
|
||||
while (!tid) { /* (the renderer's threads start late) */
|
||||
Sleep(1000);
|
||||
static Task all[512];
|
||||
const int n = tasks(all, 512);
|
||||
for (int i = 0; i < n && !tid; i++)
|
||||
if (strstr(all[i].name, want)) tid = all[i].tid;
|
||||
}
|
||||
hos_log("prof: sampling thread \"%s\"", want);
|
||||
const uintptr_t exe = exe_base();
|
||||
enum { SLOTS = 4096 };
|
||||
static struct { uint64_t key; uint32_t n; } leaf[SLOTS], ours[SLOTS];
|
||||
uint32_t total = 0;
|
||||
DWORD last = GetTickCount();
|
||||
FILE *stacks = getenv("HOS_SAMPLE_FILE") ? fopen(getenv("HOS_SAMPLE_FILE"), "w") : NULL;
|
||||
for (;;) {
|
||||
Sleep(1);
|
||||
uintptr_t pcs[DEPTH];
|
||||
const int n = sample_one(tid, pcs, DEPTH);
|
||||
if (n < 0) return 0; /* (the thread ended) */
|
||||
uint64_t keys[2] = {0, 0};
|
||||
char stack_line[1024];
|
||||
int stack_len = 0;
|
||||
for (int depth = 0; depth < n; depth++) {
|
||||
uintptr_t base;
|
||||
const int mi = module_of(pcs[depth], &base);
|
||||
const uint64_t key = (uint64_t)(mi < 0 ? 63 : mi) << 56 | (pcs[depth] - base);
|
||||
if (stacks && stack_len < (int)sizeof stack_line - 96)
|
||||
stack_len += snprintf(stack_line + stack_len, sizeof stack_line - stack_len, "%s%s+%llx", depth ? ";" : "",
|
||||
mi < 0 ? "?" : mods[mi].name, (unsigned long long)(pcs[depth] - base));
|
||||
if (depth == 0) keys[0] = key;
|
||||
if (base == exe && !keys[1]) keys[1] = key;
|
||||
if (base == exe && !stacks) break;
|
||||
}
|
||||
if (stacks && stack_len) fprintf(stacks, "%s\n", stack_line);
|
||||
if (n > 0) {
|
||||
total++;
|
||||
for (int t = 0; t < 2; t++) {
|
||||
if (!keys[t]) continue;
|
||||
typeof(leaf[0]) *tab = t ? ours : leaf;
|
||||
for (uint32_t s = (uint32_t)(keys[t] * 0x9E3779B97F4A7C15ull >> 52), k = 0; k < SLOTS; k++, s = (s + 1) % SLOTS) {
|
||||
if (tab[s].key == keys[t]) { tab[s].n++; break; }
|
||||
if (!tab[s].key) { tab[s].key = keys[t], tab[s].n = 1; break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (GetTickCount() - last >= ms) {
|
||||
last = GetTickCount();
|
||||
for (int t = 0; t < 2; t++) {
|
||||
typeof(leaf[0]) *tab = t ? ours : leaf;
|
||||
char line[2048];
|
||||
int len = snprintf(line, sizeof line, "prof-sample %s (%u samples):", t ? "ours" : "leaf", total);
|
||||
for (int r = 0; r < 30 && len < (int)sizeof line - 64; r++) {
|
||||
int best = -1;
|
||||
for (int s = 0; s < SLOTS; s++) if (tab[s].n && (best < 0 || tab[s].n > tab[best].n)) best = s;
|
||||
if (best < 0) break;
|
||||
const int mi = (int)(tab[best].key >> 56);
|
||||
len += snprintf(line + len, sizeof line - len, " %s+%llx %u,", mi < nmods ? mods[mi].name : "?",
|
||||
(unsigned long long)(tab[best].key & ((1ull << 56) - 1)), tab[best].n);
|
||||
tab[best].n = 0;
|
||||
}
|
||||
hos_log("%s", line);
|
||||
memset(tab, 0, sizeof leaf);
|
||||
}
|
||||
total = 0;
|
||||
if (stacks) fflush(stacks);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* HOS_SAMPLE_ALL=<path> (with HOS_PROFILE): while <path>.go exists, every 2 ms every guest thread and the renderer's
|
||||
threads (names starting "mkw_vk") sampled one after another: a line per thread, "<ms> <name>|<frames>", 16 frames
|
||||
at most (scripts/crit.py, scripts/hotlist.py) */
|
||||
static DWORD WINAPI sample_all_thread(void *p) {
|
||||
const char *path = (const char *)p;
|
||||
char go[MAX_PATH];
|
||||
snprintf(go, sizeof go, "%s.go", path);
|
||||
sampling_init();
|
||||
FILE *out = NULL;
|
||||
enum { MAXT = 128 };
|
||||
static int th[MAXT];
|
||||
static char tn[MAXT][64];
|
||||
int nt = 0;
|
||||
int64_t t0 = 0;
|
||||
const int self = (int)syscall(SYS_gettid);
|
||||
for (;;) {
|
||||
if (access(go, F_OK)) {
|
||||
if (out) { fclose(out); out = NULL; hos_log("prof: all-thread sampling stopped"); }
|
||||
Sleep(200);
|
||||
continue;
|
||||
}
|
||||
if (!out) {
|
||||
out = fopen(path, "a");
|
||||
if (!out) { Sleep(1000); continue; }
|
||||
static Task all[512];
|
||||
const int n = tasks(all, 512);
|
||||
nt = 0;
|
||||
for (int i = 0; i < n && nt < MAXT; i++) {
|
||||
if (all[i].tid == self || (!all[i].guest && strncmp(all[i].name, "mkw_vk", 6))) continue;
|
||||
th[nt] = all[i].tid;
|
||||
snprintf(tn[nt], sizeof tn[nt], "%s", all[i].name);
|
||||
for (char *q = tn[nt]; *q; q++) if (*q == ' ' || *q == '|') *q = '_';
|
||||
nt++;
|
||||
}
|
||||
t0 = hos_now_ns();
|
||||
hos_log("prof: all-thread sampling of %d threads into %s", nt, path);
|
||||
}
|
||||
Sleep(2);
|
||||
const long ms = (long)((hos_now_ns() - t0) / 1000000);
|
||||
for (int i = 0; i < nt; i++) {
|
||||
uintptr_t pcs[16];
|
||||
const int n = sample_one(th[i], pcs, 16);
|
||||
if (n < 0) continue;
|
||||
char line[1024];
|
||||
int len = snprintf(line, sizeof line, "%ld %s|", ms, tn[i]);
|
||||
for (int depth = 0; depth < n && len < (int)sizeof line - 96; depth++) {
|
||||
uintptr_t base;
|
||||
const int mi = module_of(pcs[depth], &base);
|
||||
len += snprintf(line + len, sizeof line - len, "%s%s+%llx", depth ? ";" : "", mi < 0 ? "?" : mods[mi].name,
|
||||
(unsigned long long)(pcs[depth] - base));
|
||||
}
|
||||
fprintf(out, "%s\n", line);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* HOS_WATCH=<file> (diagnostic): when <file> exists (up to 4 guest addresses in hex), data breakpoints on them on every
|
||||
guest thread: 4 s on reads and writes, then 4 s on writes; <file>.out gets, by address and the host place of the
|
||||
access, how many; then <file> is renamed <file>.done and the next one may come. */
|
||||
static uint64_t watch_keys[8192];
|
||||
static volatile LONG watch_counts[8192];
|
||||
static volatile LONG watch_phase;
|
||||
static struct sigaction watch_prev;
|
||||
static void on_watch(int sig, siginfo_t *si, void *uctx) {
|
||||
if (si->si_code != TRAP_PERF) { /* (a breakpoint of the game's or a debugger's: host/linux/win32.c's handlers) */
|
||||
if (watch_prev.sa_flags & SA_SIGINFO) watch_prev.sa_sigaction(sig, si, uctx);
|
||||
else if (watch_prev.sa_handler != SIG_DFL && watch_prev.sa_handler != SIG_IGN) watch_prev.sa_handler(sig);
|
||||
else { signal(sig, SIG_DFL); raise(sig); }
|
||||
return;
|
||||
}
|
||||
/* (si_perf_data, the event's sig_data: the watch's index. glibc's siginfo_t has no name for it: the kernel puts it
|
||||
after si_addr, at 24) */
|
||||
const unsigned long idx = *(const unsigned long *)((const char *)si + 24) & 3;
|
||||
const uint64_t rip = (uint64_t)((const ucontext_t *)uctx)->uc_mcontext.gregs[REG_RIP];
|
||||
const uint64_t key = ((uint64_t)(watch_phase & 1) << 62) | ((uint64_t)idx << 58) | rip;
|
||||
for (uint32_t i = (uint32_t)((key >> 2) * 2654435761u) & 8191, n = 0; n < 8192; n++, i = (i + 1) & 8191) {
|
||||
uint64_t k = __atomic_load_n(&watch_keys[i], __ATOMIC_RELAXED);
|
||||
if (!k) {
|
||||
uint64_t expect = 0;
|
||||
if (__atomic_compare_exchange_n(&watch_keys[i], &expect, key, 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED)) k = key;
|
||||
else k = expect;
|
||||
}
|
||||
if (k == key) { InterlockedIncrement(&watch_counts[i]); break; }
|
||||
}
|
||||
}
|
||||
enum { WATCH_FDS = 1024 * 4 };
|
||||
static int watch_fd[WATCH_FDS];
|
||||
static int nwatch_fd;
|
||||
static void watch_arm(const uint64_t *addr, int n, int rw) {
|
||||
for (int i = 0; i < nwatch_fd; i++) close(watch_fd[i]);
|
||||
nwatch_fd = 0;
|
||||
if (!rw) return;
|
||||
static HANDLE gh[1024];
|
||||
static const char *gn[1024];
|
||||
const int ng = hos_thread_handles(gh, gn, 1024);
|
||||
int failed = 0, err = 0;
|
||||
for (int t = 0; t < ng; t++) {
|
||||
const int tid = (int)GetThreadId(gh[t]);
|
||||
if (!tid || tid == (int)GetCurrentThreadId()) continue;
|
||||
for (int k = 0; k < n && nwatch_fd < WATCH_FDS; k++) {
|
||||
struct perf_event_attr a;
|
||||
memset(&a, 0, sizeof a);
|
||||
a.type = PERF_TYPE_BREAKPOINT;
|
||||
a.size = sizeof a;
|
||||
a.bp_type = rw == 1 ? HW_BREAKPOINT_W : HW_BREAKPOINT_RW;
|
||||
a.bp_addr = (uint64_t)(uintptr_t)GP(addr[k]);
|
||||
a.bp_len = HW_BREAKPOINT_LEN_4;
|
||||
a.sample_period = 1;
|
||||
a.exclude_kernel = 1;
|
||||
a.exclude_hv = 1;
|
||||
a.sigtrap = 1;
|
||||
a.remove_on_exec = 1;
|
||||
a.sig_data = (uint64_t)k;
|
||||
const int fd = (int)syscall(SYS_perf_event_open, &a, tid, -1, -1, PERF_FLAG_FD_CLOEXEC);
|
||||
if (fd >= 0) watch_fd[nwatch_fd++] = fd;
|
||||
else failed++, err = errno;
|
||||
}
|
||||
}
|
||||
if (failed) hos_log("watch: %d breakpoints not set (perf_event_open: %s; /proc/sys/kernel/perf_event_paranoid)", failed, strerror(err));
|
||||
}
|
||||
static DWORD WINAPI watch_thread(void *p) {
|
||||
const char *path = (const char *)p;
|
||||
struct sigaction sa;
|
||||
memset(&sa, 0, sizeof sa);
|
||||
sa.sa_sigaction = on_watch;
|
||||
sa.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_NODEFER;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
for (;;) {
|
||||
Sleep(300);
|
||||
FILE *f = fopen(path, "r");
|
||||
if (!f) continue;
|
||||
uint64_t addr[4];
|
||||
int n = 0;
|
||||
unsigned long long v;
|
||||
while (n < 4 && fscanf(f, "%llx", &v) == 1) addr[n++] = v;
|
||||
fclose(f);
|
||||
struct sigaction cur; /* (ours ahead of win32.c's, which it calls for every other SIGTRAP) */
|
||||
sigaction(SIGTRAP, NULL, &cur);
|
||||
if (cur.sa_sigaction != on_watch) sigaction(SIGTRAP, &sa, &watch_prev);
|
||||
memset(watch_keys, 0, sizeof watch_keys);
|
||||
memset((void *)watch_counts, 0, sizeof watch_counts);
|
||||
for (int k = 0; k < n; k++) hos_log("watch: %llx holds %08x", (unsigned long long)addr[k], *(uint32_t *)GP(addr[k]));
|
||||
for (int ph = 0; ph < 2; ph++) {
|
||||
watch_phase = ph;
|
||||
for (int t = 0; t < 4; t++) { /* (threads that started since) */
|
||||
watch_arm(addr, n, ph ? 1 : 3);
|
||||
Sleep(1000);
|
||||
}
|
||||
}
|
||||
watch_arm(addr, 0, 0);
|
||||
char out[MAX_PATH], done[MAX_PATH];
|
||||
snprintf(out, sizeof out, "%s.out", path);
|
||||
snprintf(done, sizeof done, "%s.done", path);
|
||||
f = fopen(out, "a");
|
||||
if (f) {
|
||||
for (int i = 0; i < 8192; i++)
|
||||
if (watch_keys[i]) {
|
||||
const uint64_t k = watch_keys[i], rip = k & ((1ULL << 58) - 1);
|
||||
uintptr_t base;
|
||||
const int mi = module_of((uintptr_t)rip, &base);
|
||||
fprintf(f, "%llx %s %s+%llx %ld\n", (unsigned long long)addr[(k >> 58) & 3], k >> 62 & 1 ? "w" : "rw",
|
||||
mi < 0 ? "?" : mods[mi].name, (unsigned long long)(rip - base), (long)watch_counts[i]);
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
unlink(done);
|
||||
rename(path, done);
|
||||
hos_log("watch: done");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void hos_prof_start(void) {
|
||||
const char *tt = getenv("HOS_THREAD_TIMES");
|
||||
if (tt && atoi(tt) > 0) CreateThread(NULL, 0, thread_times_thread, (void *)(uintptr_t)atoi(tt), 0, NULL);
|
||||
const char *e = getenv("HOS_PROFILE");
|
||||
if (e && atoi(e) > 0) CreateThread(NULL, 0, prof_thread, (void *)(uintptr_t)atoi(e), 0, NULL);
|
||||
const char *s = getenv("HOS_SAMPLE");
|
||||
if (e && atoi(e) > 0 && s && *s) CreateThread(NULL, 0, sample_thread, (void *)s, 0, NULL);
|
||||
const char *all = getenv("HOS_SAMPLE_ALL");
|
||||
if (all && *all) CreateThread(NULL, 0, sample_all_thread, (void *)all, 0, NULL);
|
||||
const char *watch = getenv("HOS_WATCH");
|
||||
if (watch && *watch) CreateThread(NULL, 0, watch_thread, (void *)watch, 0, NULL);
|
||||
}
|
||||
35
host/posix/psapi.h
Normal file
35
host/posix/psapi.h
Normal file
@@ -0,0 +1,35 @@
|
||||
/* (linux) psapi: the process's memory counters, from /proc/self/status (the working set is the resident set, private
|
||||
memory the anonymous part of it), for the back end's memory log lines */
|
||||
#ifndef HOOKSHOT_POSIX_PSAPI_H
|
||||
#define HOOKSHOT_POSIX_PSAPI_H
|
||||
#include <windows.h>
|
||||
typedef struct {
|
||||
DWORD cb, PageFaultCount;
|
||||
SIZE_T PeakWorkingSetSize, WorkingSetSize, QuotaPeakPagedPoolUsage, QuotaPagedPoolUsage, QuotaPeakNonPagedPoolUsage,
|
||||
QuotaNonPagedPoolUsage, PagefileUsage, PeakPagefileUsage;
|
||||
} PROCESS_MEMORY_COUNTERS;
|
||||
typedef struct {
|
||||
DWORD cb, PageFaultCount;
|
||||
SIZE_T PeakWorkingSetSize, WorkingSetSize, QuotaPeakPagedPoolUsage, QuotaPagedPoolUsage, QuotaPeakNonPagedPoolUsage,
|
||||
QuotaNonPagedPoolUsage, PagefileUsage, PeakPagefileUsage, PrivateUsage;
|
||||
} PROCESS_MEMORY_COUNTERS_EX;
|
||||
static inline BOOL K32GetProcessMemoryInfo(HANDLE p, PROCESS_MEMORY_COUNTERS *out, DWORD cb) {
|
||||
(void)p;
|
||||
FILE *f = fopen("/proc/self/status", "r");
|
||||
if (!f) return FALSE;
|
||||
SIZE_T rss = 0, hwm = 0, anon = 0;
|
||||
char line[256];
|
||||
while (fgets(line, sizeof line, f)) {
|
||||
unsigned long long kb;
|
||||
if (sscanf(line, "VmRSS: %llu", &kb) == 1) rss = (SIZE_T)kb << 10;
|
||||
else if (sscanf(line, "VmHWM: %llu", &kb) == 1) hwm = (SIZE_T)kb << 10;
|
||||
else if (sscanf(line, "RssAnon: %llu", &kb) == 1) anon = (SIZE_T)kb << 10;
|
||||
}
|
||||
fclose(f);
|
||||
memset(out, 0, cb);
|
||||
out->cb = cb, out->WorkingSetSize = rss, out->PeakWorkingSetSize = hwm, out->PagefileUsage = anon;
|
||||
if (cb >= sizeof(PROCESS_MEMORY_COUNTERS_EX)) ((PROCESS_MEMORY_COUNTERS_EX *)out)->PrivateUsage = anon;
|
||||
return TRUE;
|
||||
}
|
||||
#define GetProcessMemoryInfo K32GetProcessMemoryInfo
|
||||
#endif
|
||||
15
host/posix/tlhelp32.h
Normal file
15
host/posix/tlhelp32.h
Normal file
@@ -0,0 +1,15 @@
|
||||
/* (linux) Tool Help: the thread snapshots the profiler and the stall reports walk. There is no snapshot here
|
||||
(CreateToolhelp32Snapshot fails), so those debugging aids find no threads. */
|
||||
#ifndef HOOKSHOT_POSIX_TLHELP32_H
|
||||
#define HOOKSHOT_POSIX_TLHELP32_H
|
||||
#include <windows.h>
|
||||
#define TH32CS_SNAPTHREAD 0x4
|
||||
typedef struct {
|
||||
DWORD dwSize, cntUsage, th32ThreadID, th32OwnerProcessID;
|
||||
LONG tpBasePri, tpDeltaPri;
|
||||
DWORD dwFlags;
|
||||
} THREADENTRY32;
|
||||
static inline HANDLE CreateToolhelp32Snapshot(DWORD flags, DWORD pid) { (void)flags, (void)pid; return INVALID_HANDLE_VALUE; }
|
||||
static inline BOOL Thread32First(HANDLE s, THREADENTRY32 *te) { (void)s, (void)te; return FALSE; }
|
||||
static inline BOOL Thread32Next(HANDLE s, THREADENTRY32 *te) { (void)s, (void)te; return FALSE; }
|
||||
#endif
|
||||
1320
host/posix/win32_posix.c
Normal file
1320
host/posix/win32_posix.c
Normal file
File diff suppressed because it is too large
Load Diff
562
host/posix/windows.h
Normal file
562
host/posix/windows.h
Normal file
@@ -0,0 +1,562 @@
|
||||
/* (linux) The part of the Win32 API Hookshot's runtime and Vulkan back end use, on POSIX: host/posix is on the include
|
||||
path of Linux builds only (nx2/build.py), so `#include <windows.h>` finds this file and the Windows code paths stay
|
||||
as they are. Implemented in win32_posix.c (threads, events, fibers, files, memory, modules, exceptions, waveOut) and
|
||||
display_sdl.c (the window, keyboard, mouse).
|
||||
|
||||
Not a general emulation: what is here is what the code calls, with the behaviour it relies on. Handles are
|
||||
pointers to objects of this file's own (threads, events, timers, files, find searches); the guest window is one
|
||||
mapping (hos_main.c), so committing memory is a no-op and decommitting zeroes it. */
|
||||
#ifndef HOOKSHOT_POSIX_WINDOWS_H
|
||||
#define HOOKSHOT_POSIX_WINDOWS_H
|
||||
#ifndef _GNU_SOURCE
|
||||
#define _GNU_SOURCE
|
||||
#endif
|
||||
#include <errno.h>
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include <wchar.h>
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* ---- types ---- */
|
||||
typedef int BOOL;
|
||||
typedef unsigned char BYTE;
|
||||
typedef uint16_t WORD;
|
||||
typedef uint32_t DWORD;
|
||||
typedef int32_t LONG;
|
||||
typedef uint32_t ULONG;
|
||||
typedef int64_t LONG64, LONGLONG;
|
||||
typedef uint64_t ULONG64, ULONGLONG, DWORD64, DWORDLONG;
|
||||
typedef uintptr_t DWORD_PTR, ULONG_PTR, UINT_PTR, WPARAM;
|
||||
typedef intptr_t LONG_PTR, INT_PTR, LPARAM, LRESULT;
|
||||
typedef size_t SIZE_T;
|
||||
typedef unsigned int UINT;
|
||||
typedef int INT;
|
||||
typedef short SHORT;
|
||||
typedef unsigned short USHORT;
|
||||
typedef char CHAR;
|
||||
typedef wchar_t WCHAR;
|
||||
typedef void *HANDLE, *HMODULE, *HINSTANCE, *HWND, *HDC, *HGDIOBJ, *HBITMAP, *HFONT, *HBRUSH, *HICON, *HCURSOR, *HKEY;
|
||||
typedef void *PVOID, *LPVOID;
|
||||
typedef const void *LPCVOID;
|
||||
typedef char *LPSTR;
|
||||
typedef const char *LPCSTR;
|
||||
typedef wchar_t *PWSTR, *LPWSTR;
|
||||
typedef const wchar_t *PCWSTR, *LPCWSTR;
|
||||
typedef DWORD *LPDWORD;
|
||||
typedef LONG HRESULT;
|
||||
typedef DWORD COLORREF;
|
||||
typedef void (*FARPROC)(void);
|
||||
typedef union { struct { DWORD LowPart; LONG HighPart; } u; int64_t QuadPart; } LARGE_INTEGER;
|
||||
typedef struct { DWORD dwLowDateTime, dwHighDateTime; } FILETIME;
|
||||
typedef struct { LONG left, top, right, bottom; } RECT;
|
||||
typedef struct { LONG x, y; } POINT;
|
||||
typedef struct { LONG cx, cy; } SIZE;
|
||||
|
||||
#define WINAPI
|
||||
#define CALLBACK
|
||||
#define APIENTRY
|
||||
#define WINAPIV
|
||||
#ifndef TRUE
|
||||
#define TRUE 1
|
||||
#define FALSE 0
|
||||
#endif
|
||||
#ifndef MAX_PATH
|
||||
#define MAX_PATH 4096
|
||||
#endif
|
||||
#define INFINITE 0xFFFFFFFFu
|
||||
#define S_OK 0
|
||||
#define S_FALSE 1
|
||||
#define SUCCEEDED(hr) ((HRESULT)(hr) >= 0)
|
||||
#define FAILED(hr) ((HRESULT)(hr) < 0)
|
||||
#define INVALID_HANDLE_VALUE ((HANDLE)(intptr_t)-1)
|
||||
#define LOWORD(l) ((WORD)((uintptr_t)(l) & 0xffff))
|
||||
#define HIWORD(l) ((WORD)(((uintptr_t)(l) >> 16) & 0xffff))
|
||||
#define RGB(r, g, b) ((COLORREF)(((BYTE)(r) | ((WORD)((BYTE)(g)) << 8)) | (((DWORD)(BYTE)(b)) << 16)))
|
||||
#define UNREFERENCED_PARAMETER(x) ((void)(x))
|
||||
#define __declspec(x) HOOKSHOT_DECLSPEC_##x
|
||||
#define HOOKSHOT_DECLSPEC_dllexport __attribute__((visibility("default")))
|
||||
#define HOOKSHOT_DECLSPEC_dllimport
|
||||
#define HOOKSHOT_DECLSPEC_noinline __attribute__((noinline))
|
||||
#define HOOKSHOT_DECLSPEC_thread __thread
|
||||
#define _stricmp strcasecmp
|
||||
#define _strnicmp strncasecmp
|
||||
#define _strdup strdup
|
||||
#define _fseeki64 fseeko
|
||||
#define _ftelli64 ftello
|
||||
#define _mkdir(p) mkdir((p), 0755)
|
||||
#define _getpid getpid
|
||||
#define _countof(a) (sizeof(a) / sizeof((a)[0]))
|
||||
#define _environ environ
|
||||
#define _fileno fileno
|
||||
#define _chsize_s(fd, size) ftruncate((fd), (off_t)(size))
|
||||
#define _atoi64 atoll
|
||||
#define _mkgmtime timegm
|
||||
/* (MSVC's argument order: the result first; 0 on success) */
|
||||
static inline int gmtime_s(struct tm *out, const time_t *t) { return gmtime_r(t, out) ? 0 : EINVAL; }
|
||||
static inline int localtime_s(struct tm *out, const time_t *t) { return localtime_r(t, out) ? 0 : EINVAL; }
|
||||
|
||||
/* ---- errors (GetLastError: errno mapped to the codes the callers test) ---- */
|
||||
#define ERROR_SUCCESS 0L
|
||||
#define ERROR_FILE_NOT_FOUND 2L
|
||||
#define ERROR_PATH_NOT_FOUND 3L
|
||||
#define ERROR_ACCESS_DENIED 5L
|
||||
#define ERROR_INVALID_HANDLE 6L
|
||||
#define ERROR_NOT_ENOUGH_MEMORY 8L
|
||||
#define ERROR_NO_MORE_FILES 18L
|
||||
#define ERROR_HANDLE_EOF 38L
|
||||
#define ERROR_NOT_SUPPORTED 50L
|
||||
#define ERROR_FILE_EXISTS 80L
|
||||
#define ERROR_INVALID_PARAMETER 87L
|
||||
#define ERROR_ALREADY_EXISTS 183L
|
||||
#define ERROR_COMMITMENT_LIMIT 1455L
|
||||
#define ERROR_NOT_ALL_ASSIGNED 1300L
|
||||
#define ERROR_TIMEOUT 1460L
|
||||
#define ERROR_DEVICE_NOT_CONNECTED 1167L
|
||||
DWORD GetLastError(void);
|
||||
void SetLastError(DWORD e);
|
||||
|
||||
/* ---- atomics (type-generic, as MSVC's are per width) ---- */
|
||||
#define InterlockedIncrement(p) __atomic_add_fetch((p), 1, __ATOMIC_SEQ_CST)
|
||||
#define InterlockedDecrement(p) __atomic_sub_fetch((p), 1, __ATOMIC_SEQ_CST)
|
||||
#define InterlockedIncrement64 InterlockedIncrement
|
||||
#define InterlockedDecrement64 InterlockedDecrement
|
||||
#define InterlockedExchange(p, v) __atomic_exchange_n((p), (v), __ATOMIC_SEQ_CST)
|
||||
#define InterlockedExchange64 InterlockedExchange
|
||||
#define InterlockedExchangePointer InterlockedExchange
|
||||
#define InterlockedExchangeAdd(p, v) __atomic_fetch_add((p), (v), __ATOMIC_SEQ_CST)
|
||||
#define InterlockedExchangeAdd64 InterlockedExchangeAdd
|
||||
#define InterlockedAdd(p, v) __atomic_add_fetch((p), (v), __ATOMIC_SEQ_CST)
|
||||
#define InterlockedAdd64 InterlockedAdd
|
||||
#define InterlockedOr(p, v) __atomic_fetch_or((p), (v), __ATOMIC_SEQ_CST)
|
||||
#define InterlockedAnd(p, v) __atomic_fetch_and((p), (v), __ATOMIC_SEQ_CST)
|
||||
#define InterlockedOr64 InterlockedOr
|
||||
#define InterlockedAnd64 InterlockedAnd
|
||||
#define InterlockedCompareExchange(p, x, c) __sync_val_compare_and_swap((p), (c), (x))
|
||||
#define InterlockedCompareExchange64 InterlockedCompareExchange
|
||||
#define InterlockedCompareExchangePointer InterlockedCompareExchange
|
||||
#define MemoryBarrier() __atomic_thread_fence(__ATOMIC_SEQ_CST)
|
||||
#define _ReadWriteBarrier() __atomic_signal_fence(__ATOMIC_SEQ_CST)
|
||||
#define YieldProcessor() __builtin_ia32_pause()
|
||||
|
||||
/* ---- locks: SRW locks are POSIX rwlocks (zero-initialised is valid, as on Windows); condition variables a futex
|
||||
word, so they wait with either an SRW lock or a critical section ---- */
|
||||
typedef pthread_rwlock_t SRWLOCK, *PSRWLOCK;
|
||||
#define SRWLOCK_INIT PTHREAD_RWLOCK_INITIALIZER
|
||||
typedef struct { volatile uint32_t seq; } CONDITION_VARIABLE, *PCONDITION_VARIABLE;
|
||||
#define CONDITION_VARIABLE_INIT {0}
|
||||
#define CONDITION_VARIABLE_LOCKMODE_SHARED 0x1
|
||||
typedef pthread_mutex_t CRITICAL_SECTION, *LPCRITICAL_SECTION;
|
||||
static inline void InitializeSRWLock(SRWLOCK *l) { pthread_rwlock_init(l, NULL); }
|
||||
static inline void AcquireSRWLockExclusive(SRWLOCK *l) { pthread_rwlock_wrlock(l); }
|
||||
static inline void ReleaseSRWLockExclusive(SRWLOCK *l) { pthread_rwlock_unlock(l); }
|
||||
static inline void AcquireSRWLockShared(SRWLOCK *l) { pthread_rwlock_rdlock(l); }
|
||||
static inline void ReleaseSRWLockShared(SRWLOCK *l) { pthread_rwlock_unlock(l); }
|
||||
static inline BOOL TryAcquireSRWLockExclusive(SRWLOCK *l) { return pthread_rwlock_trywrlock(l) == 0; }
|
||||
static inline BOOL TryAcquireSRWLockShared(SRWLOCK *l) { return pthread_rwlock_tryrdlock(l) == 0; }
|
||||
void InitializeCriticalSection(CRITICAL_SECTION *cs);
|
||||
static inline BOOL InitializeCriticalSectionAndSpinCount(CRITICAL_SECTION *cs, DWORD n) { (void)n; InitializeCriticalSection(cs); return TRUE; }
|
||||
static inline void EnterCriticalSection(CRITICAL_SECTION *cs) { pthread_mutex_lock(cs); }
|
||||
static inline void LeaveCriticalSection(CRITICAL_SECTION *cs) { pthread_mutex_unlock(cs); }
|
||||
static inline BOOL TryEnterCriticalSection(CRITICAL_SECTION *cs) { return pthread_mutex_trylock(cs) == 0; }
|
||||
static inline void DeleteCriticalSection(CRITICAL_SECTION *cs) { pthread_mutex_destroy(cs); }
|
||||
static inline void InitializeConditionVariable(CONDITION_VARIABLE *cv) { cv->seq = 0; }
|
||||
void WakeConditionVariable(CONDITION_VARIABLE *cv);
|
||||
void WakeAllConditionVariable(CONDITION_VARIABLE *cv);
|
||||
BOOL SleepConditionVariableSRW(CONDITION_VARIABLE *cv, SRWLOCK *l, DWORD ms, ULONG flags);
|
||||
BOOL SleepConditionVariableCS(CONDITION_VARIABLE *cv, CRITICAL_SECTION *cs, DWORD ms);
|
||||
BOOL WaitOnAddress(volatile void *addr, void *compare, SIZE_T size, DWORD ms);
|
||||
void WakeByAddressSingle(void *addr);
|
||||
void WakeByAddressAll(void *addr);
|
||||
|
||||
/* ---- time ---- */
|
||||
static inline BOOL QueryPerformanceFrequency(LARGE_INTEGER *f) { f->QuadPart = 1000000000LL; return TRUE; }
|
||||
static inline BOOL QueryPerformanceCounter(LARGE_INTEGER *c) {
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
c->QuadPart = (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
|
||||
return TRUE;
|
||||
}
|
||||
static inline ULONGLONG GetTickCount64(void) {
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (ULONGLONG)ts.tv_sec * 1000 + (ULONGLONG)ts.tv_nsec / 1000000;
|
||||
}
|
||||
static inline DWORD GetTickCount(void) { return (DWORD)GetTickCount64(); }
|
||||
void Sleep(DWORD ms);
|
||||
static inline BOOL SwitchToThread(void) { return sched_yield() == 0; }
|
||||
static inline UINT timeBeginPeriod(UINT p) { (void)p; return 0; }
|
||||
static inline UINT timeEndPeriod(UINT p) { (void)p; return 0; }
|
||||
void GetSystemTimeAsFileTime(FILETIME *ft);
|
||||
#define CREATE_WAITABLE_TIMER_HIGH_RESOLUTION 0x2
|
||||
#define TIMER_ALL_ACCESS 0x1F0003
|
||||
HANDLE CreateWaitableTimerExW(void *attr, LPCWSTR name, DWORD flags, DWORD access);
|
||||
BOOL SetWaitableTimerEx(HANDLE t, const LARGE_INTEGER *due, LONG period, void *fn, void *arg, void *ctx, ULONG delay);
|
||||
|
||||
/* ---- handles, threads, events ---- */
|
||||
typedef DWORD (*LPTHREAD_START_ROUTINE)(void *);
|
||||
#define WAIT_OBJECT_0 0u
|
||||
#define WAIT_ABANDONED 0x80u
|
||||
#define WAIT_TIMEOUT 258u
|
||||
#define WAIT_FAILED 0xFFFFFFFFu
|
||||
#define STILL_ACTIVE 259
|
||||
#define CREATE_SUSPENDED 0x4
|
||||
#define STACK_SIZE_PARAM_IS_A_RESERVATION 0x10000
|
||||
#define THREAD_PRIORITY_IDLE -15
|
||||
#define THREAD_PRIORITY_LOWEST -2
|
||||
#define THREAD_PRIORITY_BELOW_NORMAL -1
|
||||
#define THREAD_PRIORITY_NORMAL 0
|
||||
#define THREAD_PRIORITY_ABOVE_NORMAL 1
|
||||
#define THREAD_PRIORITY_HIGHEST 2
|
||||
#define THREAD_PRIORITY_TIME_CRITICAL 15
|
||||
#define DUPLICATE_SAME_ACCESS 0x2
|
||||
#define THREAD_ALL_ACCESS 0x1FFFFF
|
||||
#define THREAD_QUERY_INFORMATION 0x40
|
||||
#define THREAD_QUERY_LIMITED_INFORMATION 0x800
|
||||
#define THREAD_SUSPEND_RESUME 0x2
|
||||
#define THREAD_GET_CONTEXT 0x8
|
||||
#define THREAD_SET_CONTEXT 0x10
|
||||
#define SYNCHRONIZE 0x100000
|
||||
#define EVENT_ALL_ACCESS 0x1F0003
|
||||
HANDLE CreateThread(void *attr, SIZE_T stack, LPTHREAD_START_ROUTINE fn, void *arg, DWORD flags, DWORD *id);
|
||||
HANDLE GetCurrentThread(void);
|
||||
static inline HANDLE GetCurrentProcess(void) { return (HANDLE)(intptr_t)-1; }
|
||||
static inline DWORD GetCurrentProcessId(void) { return (DWORD)getpid(); }
|
||||
DWORD GetCurrentThreadId(void);
|
||||
DWORD GetThreadId(HANDLE t);
|
||||
DWORD GetProcessId(HANDLE p);
|
||||
HANDLE OpenThread(DWORD access, BOOL inherit, DWORD id);
|
||||
BOOL DuplicateHandle(HANDLE sp, HANDLE src, HANDLE tp, HANDLE *out, DWORD access, BOOL inherit, DWORD options);
|
||||
BOOL CloseHandle(HANDLE h);
|
||||
BOOL SetThreadPriority(HANDLE t, int p);
|
||||
int GetThreadPriority(HANDLE t);
|
||||
DWORD_PTR SetThreadAffinityMask(HANDLE t, DWORD_PTR mask);
|
||||
BOOL GetProcessAffinityMask(HANDLE p, DWORD_PTR *proc, DWORD_PTR *sys);
|
||||
HRESULT SetThreadDescription(HANDLE t, PCWSTR name);
|
||||
HRESULT GetThreadDescription(HANDLE t, PWSTR *name);
|
||||
BOOL GetThreadTimes(HANDLE t, FILETIME *create, FILETIME *exit, FILETIME *kernel, FILETIME *user);
|
||||
DWORD SuspendThread(HANDLE t);
|
||||
DWORD ResumeThread(HANDLE t);
|
||||
BOOL GetExitCodeThread(HANDLE t, DWORD *code);
|
||||
__attribute__((noreturn)) void ExitThread(DWORD code);
|
||||
__attribute__((noreturn)) void ExitProcess(UINT code);
|
||||
BOOL TerminateProcess(HANDLE p, UINT code);
|
||||
HANDLE CreateEventA(void *attr, BOOL manual, BOOL initial, LPCSTR name);
|
||||
#define CreateEvent CreateEventA
|
||||
BOOL SetEvent(HANDLE e);
|
||||
BOOL ResetEvent(HANDLE e);
|
||||
HANDLE CreateSemaphoreA(void *attr, LONG initial, LONG max, LPCSTR name);
|
||||
BOOL ReleaseSemaphore(HANDLE s, LONG n, LONG *prev);
|
||||
DWORD WaitForSingleObject(HANDLE h, DWORD ms);
|
||||
DWORD WaitForMultipleObjects(DWORD n, const HANDLE *hs, BOOL all, DWORD ms);
|
||||
void *LocalFree(void *p);
|
||||
|
||||
/* fibers: ucontext, each on its own stack */
|
||||
#define FIBER_FLAG_FLOAT_SWITCH 0x1
|
||||
typedef void (*LPFIBER_START_ROUTINE)(void *);
|
||||
void *ConvertThreadToFiberEx(void *param, DWORD flags);
|
||||
void *ConvertThreadToFiber(void *param);
|
||||
BOOL ConvertFiberToThread(void);
|
||||
void *CreateFiberEx(SIZE_T commit, SIZE_T reserve, DWORD flags, LPFIBER_START_ROUTINE fn, void *param);
|
||||
void *CreateFiber(SIZE_T stack, LPFIBER_START_ROUTINE fn, void *param);
|
||||
void SwitchToFiber(void *fiber);
|
||||
void DeleteFiber(void *fiber);
|
||||
void *GetCurrentFiber(void);
|
||||
void *GetFiberData(void);
|
||||
|
||||
/* processors */
|
||||
typedef enum { RelationProcessorCore = 0, RelationNumaNode = 1, RelationCache = 2, RelationProcessorPackage = 3 } LOGICAL_PROCESSOR_RELATIONSHIP;
|
||||
typedef struct {
|
||||
ULONG_PTR ProcessorMask;
|
||||
LOGICAL_PROCESSOR_RELATIONSHIP Relationship;
|
||||
union { struct { BYTE Flags; } ProcessorCore; ULONGLONG Reserved[2]; };
|
||||
} SYSTEM_LOGICAL_PROCESSOR_INFORMATION, *PSYSTEM_LOGICAL_PROCESSOR_INFORMATION;
|
||||
BOOL GetLogicalProcessorInformation(SYSTEM_LOGICAL_PROCESSOR_INFORMATION *info, DWORD *len);
|
||||
typedef struct {
|
||||
WORD wProcessorArchitecture, wReserved;
|
||||
DWORD dwPageSize;
|
||||
void *lpMinimumApplicationAddress, *lpMaximumApplicationAddress;
|
||||
DWORD_PTR dwActiveProcessorMask;
|
||||
DWORD dwNumberOfProcessors, dwProcessorType, dwAllocationGranularity;
|
||||
WORD wProcessorLevel, wProcessorRevision;
|
||||
} SYSTEM_INFO;
|
||||
void GetSystemInfo(SYSTEM_INFO *si);
|
||||
|
||||
/* ---- strings ---- */
|
||||
#define CP_ACP 0
|
||||
#define CP_UTF8 65001
|
||||
int MultiByteToWideChar(UINT cp, DWORD flags, LPCSTR s, int n, LPWSTR w, int cap);
|
||||
int WideCharToMultiByte(UINT cp, DWORD flags, LPCWSTR w, int n, LPSTR s, int cap, LPCSTR def, BOOL *used);
|
||||
void OutputDebugStringA(LPCSTR s);
|
||||
#define OutputDebugString OutputDebugStringA
|
||||
|
||||
/* ---- memory ---- */
|
||||
#define MEM_COMMIT 0x1000
|
||||
#define MEM_RESERVE 0x2000
|
||||
#define MEM_DECOMMIT 0x4000
|
||||
#define MEM_RELEASE 0x8000
|
||||
#define MEM_FREE 0x10000
|
||||
#define MEM_PRIVATE 0x20000
|
||||
#define MEM_MAPPED 0x40000
|
||||
#define MEM_IMAGE 0x1000000
|
||||
#define MEM_RESET 0x80000
|
||||
#define MEM_WRITE_WATCH 0x200000
|
||||
#define MEM_LARGE_PAGES 0x20000000
|
||||
#define PAGE_NOACCESS 0x01
|
||||
#define PAGE_READONLY 0x02
|
||||
#define PAGE_READWRITE 0x04
|
||||
#define PAGE_EXECUTE 0x10
|
||||
#define PAGE_EXECUTE_READ 0x20
|
||||
#define PAGE_EXECUTE_READWRITE 0x40
|
||||
#define PAGE_WRITECOPY 0x08
|
||||
#define PAGE_GUARD 0x100
|
||||
typedef struct {
|
||||
void *BaseAddress, *AllocationBase;
|
||||
DWORD AllocationProtect;
|
||||
SIZE_T RegionSize;
|
||||
DWORD State, Protect, Type;
|
||||
} MEMORY_BASIC_INFORMATION, *PMEMORY_BASIC_INFORMATION;
|
||||
void *VirtualAlloc(void *addr, SIZE_T size, DWORD type, DWORD protect);
|
||||
BOOL VirtualFree(void *addr, SIZE_T size, DWORD type);
|
||||
BOOL VirtualProtect(void *addr, SIZE_T size, DWORD protect, DWORD *old);
|
||||
SIZE_T VirtualQuery(const void *addr, MEMORY_BASIC_INFORMATION *mbi, SIZE_T size);
|
||||
static inline SIZE_T GetLargePageMinimum(void) { return 0; }
|
||||
|
||||
/* ---- modules: dlopen; ".dll" names map to the shared libraries (win32_posix.c) ---- */
|
||||
#define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 0x2
|
||||
#define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 0x4
|
||||
HMODULE LoadLibraryA(LPCSTR name);
|
||||
#define LoadLibrary LoadLibraryA
|
||||
BOOL FreeLibrary(HMODULE m);
|
||||
FARPROC GetProcAddress(HMODULE m, LPCSTR name);
|
||||
HMODULE GetModuleHandleA(LPCSTR name);
|
||||
BOOL GetModuleHandleExA(DWORD flags, LPCSTR name, HMODULE *out);
|
||||
DWORD GetModuleFileNameA(HMODULE m, LPSTR out, DWORD cap);
|
||||
BOOL SetCurrentDirectoryA(LPCSTR dir);
|
||||
DWORD GetCurrentDirectoryA(DWORD cap, LPSTR out);
|
||||
|
||||
/* ---- files: paths may use '\' (it is made '/') ---- */
|
||||
#define GENERIC_READ 0x80000000u
|
||||
#define GENERIC_WRITE 0x40000000u
|
||||
#define FILE_SHARE_READ 0x1
|
||||
#define FILE_SHARE_WRITE 0x2
|
||||
#define FILE_SHARE_DELETE 0x4
|
||||
#define CREATE_NEW 1
|
||||
#define CREATE_ALWAYS 2
|
||||
#define OPEN_EXISTING 3
|
||||
#define OPEN_ALWAYS 4
|
||||
#define TRUNCATE_EXISTING 5
|
||||
#define FILE_ATTRIBUTE_READONLY 0x1
|
||||
#define FILE_ATTRIBUTE_HIDDEN 0x2
|
||||
#define FILE_ATTRIBUTE_DIRECTORY 0x10
|
||||
#define FILE_ATTRIBUTE_NORMAL 0x80
|
||||
#define FILE_ATTRIBUTE_REPARSE_POINT 0x400 /* (a symbolic link: find_next sets it) */
|
||||
#define FILE_FLAG_SEQUENTIAL_SCAN 0x08000000
|
||||
#define FILE_FLAG_RANDOM_ACCESS 0x10000000
|
||||
#define FILE_FLAG_OVERLAPPED 0x40000000
|
||||
#define FILE_FLAG_NO_BUFFERING 0x20000000
|
||||
#define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
|
||||
#define INVALID_FILE_SIZE ((DWORD)0xFFFFFFFF)
|
||||
#define FILE_BEGIN 0
|
||||
#define FILE_CURRENT 1
|
||||
#define FILE_END 2
|
||||
#define MOVEFILE_REPLACE_EXISTING 0x1
|
||||
#define MOVEFILE_COPY_ALLOWED 0x2
|
||||
#define MOVEFILE_WRITE_THROUGH 0x8
|
||||
#define STD_INPUT_HANDLE ((DWORD)-10)
|
||||
#define STD_OUTPUT_HANDLE ((DWORD)-11)
|
||||
#define STD_ERROR_HANDLE ((DWORD)-12)
|
||||
#define FILE_TYPE_UNKNOWN 0
|
||||
#define FILE_TYPE_DISK 1
|
||||
#define FILE_TYPE_CHAR 2
|
||||
#define FILE_TYPE_PIPE 3
|
||||
typedef struct {
|
||||
ULONG_PTR Internal, InternalHigh;
|
||||
union { struct { DWORD Offset, OffsetHigh; }; PVOID Pointer; };
|
||||
HANDLE hEvent;
|
||||
} OVERLAPPED, *LPOVERLAPPED;
|
||||
typedef struct {
|
||||
DWORD dwFileAttributes;
|
||||
FILETIME ftCreationTime, ftLastAccessTime, ftLastWriteTime;
|
||||
DWORD nFileSizeHigh, nFileSizeLow, dwReserved0, dwReserved1;
|
||||
CHAR cFileName[MAX_PATH];
|
||||
CHAR cAlternateFileName[14];
|
||||
} WIN32_FIND_DATAA, *LPWIN32_FIND_DATAA;
|
||||
HANDLE CreateFileA(LPCSTR path, DWORD access, DWORD share, void *attr, DWORD disposition, DWORD flags, HANDLE tmpl);
|
||||
#define CreateFile CreateFileA
|
||||
BOOL ReadFile(HANDLE h, void *buf, DWORD n, DWORD *got, OVERLAPPED *ov);
|
||||
BOOL WriteFile(HANDLE h, const void *buf, DWORD n, DWORD *put, OVERLAPPED *ov);
|
||||
BOOL SetFilePointerEx(HANDLE h, LARGE_INTEGER dist, LARGE_INTEGER *pos, DWORD method);
|
||||
BOOL GetFileSizeEx(HANDLE h, LARGE_INTEGER *size);
|
||||
DWORD GetFileSize(HANDLE h, DWORD *high);
|
||||
BOOL SetEndOfFile(HANDLE h);
|
||||
BOOL FlushFileBuffers(HANDLE h);
|
||||
DWORD GetFileType(HANDLE h);
|
||||
HANDLE GetStdHandle(DWORD which);
|
||||
BOOL GetConsoleMode(HANDLE h, DWORD *mode);
|
||||
DWORD GetFileAttributesA(LPCSTR path);
|
||||
#define GetFileAttributes GetFileAttributesA
|
||||
BOOL CreateDirectoryA(LPCSTR path, void *attr);
|
||||
BOOL RemoveDirectoryA(LPCSTR path);
|
||||
BOOL DeleteFileA(LPCSTR path);
|
||||
BOOL MoveFileA(LPCSTR from, LPCSTR to);
|
||||
BOOL MoveFileExA(LPCSTR from, LPCSTR to, DWORD flags);
|
||||
BOOL CopyFileA(LPCSTR from, LPCSTR to, BOOL fail_if_exists);
|
||||
HANDLE FindFirstFileA(LPCSTR pattern, WIN32_FIND_DATAA *fd);
|
||||
BOOL FindNextFileA(HANDLE h, WIN32_FIND_DATAA *fd);
|
||||
BOOL FindClose(HANDLE h);
|
||||
static inline BOOL AllocConsole(void) { return FALSE; }
|
||||
static inline BOOL FreeConsole(void) { return TRUE; }
|
||||
static inline BOOL SetConsoleTitleA(LPCSTR t) { (void)t; return TRUE; }
|
||||
|
||||
/* ---- exceptions: vectored handlers and the unhandled filter on SIGSEGV / SIGBUS / SIGILL / SIGFPE ---- */
|
||||
#define EXCEPTION_ACCESS_VIOLATION 0xC0000005u
|
||||
#define EXCEPTION_ILLEGAL_INSTRUCTION 0xC000001Du
|
||||
#define EXCEPTION_INT_DIVIDE_BY_ZERO 0xC0000094u
|
||||
#define EXCEPTION_STACK_OVERFLOW 0xC00000FDu
|
||||
#define EXCEPTION_BREAKPOINT 0x80000003u
|
||||
#define EXCEPTION_IN_PAGE_ERROR 0xC0000006u
|
||||
#define EXCEPTION_CONTINUE_EXECUTION (-1)
|
||||
#define EXCEPTION_CONTINUE_SEARCH 0
|
||||
#define EXCEPTION_EXECUTE_HANDLER 1
|
||||
#define EXCEPTION_MAXIMUM_PARAMETERS 15
|
||||
typedef struct _EXCEPTION_RECORD {
|
||||
DWORD ExceptionCode, ExceptionFlags;
|
||||
struct _EXCEPTION_RECORD *ExceptionRecord;
|
||||
void *ExceptionAddress;
|
||||
DWORD NumberParameters;
|
||||
ULONG_PTR ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS];
|
||||
} EXCEPTION_RECORD, *PEXCEPTION_RECORD;
|
||||
typedef struct {
|
||||
DWORD64 Rax, Rcx, Rdx, Rbx, Rsp, Rbp, Rsi, Rdi, R8, R9, R10, R11, R12, R13, R14, R15, Rip;
|
||||
DWORD EFlags, ContextFlags;
|
||||
DWORD64 Dr0, Dr1, Dr2, Dr3, Dr6, Dr7; /* (no thread's context is read or set here: GetThreadContext fails) */
|
||||
} CONTEXT, *PCONTEXT;
|
||||
#define EXCEPTION_SINGLE_STEP 0x80000004u
|
||||
#define CONTEXT_DEBUG_REGISTERS 0x100010
|
||||
#define CONTEXT_FULL 0x10000B
|
||||
#define CONTEXT_CONTROL 0x100001
|
||||
#define CONTEXT_INTEGER 0x100002
|
||||
typedef struct { EXCEPTION_RECORD *ExceptionRecord; CONTEXT *ContextRecord; } EXCEPTION_POINTERS, *PEXCEPTION_POINTERS;
|
||||
typedef LONG (*PVECTORED_EXCEPTION_HANDLER)(EXCEPTION_POINTERS *);
|
||||
typedef LONG (*LPTOP_LEVEL_EXCEPTION_FILTER)(EXCEPTION_POINTERS *);
|
||||
void *AddVectoredExceptionHandler(ULONG first, PVECTORED_EXCEPTION_HANDLER h);
|
||||
ULONG RemoveVectoredExceptionHandler(void *h);
|
||||
LPTOP_LEVEL_EXCEPTION_FILTER SetUnhandledExceptionFilter(LPTOP_LEVEL_EXCEPTION_FILTER f);
|
||||
BOOL GetThreadContext(HANDLE t, CONTEXT *c);
|
||||
BOOL SetThreadContext(HANDLE t, const CONTEXT *c);
|
||||
/* (no SEH unwind tables: the host backtraces of crash reports stop at the faulting frame) */
|
||||
typedef struct { DWORD BeginAddress, EndAddress, UnwindData; } RUNTIME_FUNCTION, *PRUNTIME_FUNCTION;
|
||||
#define UNW_FLAG_NHANDLER 0
|
||||
static inline PRUNTIME_FUNCTION RtlLookupFunctionEntry(DWORD64 pc, DWORD64 *base, void *table) { (void)pc, (void)table; *base = 0; return NULL; }
|
||||
static inline void *RtlVirtualUnwind(DWORD type, DWORD64 base, DWORD64 pc, PRUNTIME_FUNCTION f, CONTEXT *c, void **hd,
|
||||
DWORD64 *frame, void *ptrs) {
|
||||
(void)type, (void)base, (void)pc, (void)f, (void)c, (void)hd, (void)frame, (void)ptrs;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* ---- the window, keyboard and screen (display_sdl.c) ---- */
|
||||
#define VK_LBUTTON 0x01
|
||||
#define VK_RBUTTON 0x02
|
||||
#define VK_MBUTTON 0x04
|
||||
#define VK_BACK 0x08
|
||||
#define VK_TAB 0x09
|
||||
#define VK_RETURN 0x0D
|
||||
#define VK_SHIFT 0x10
|
||||
#define VK_CONTROL 0x11
|
||||
#define VK_MENU 0x12
|
||||
#define VK_PAUSE 0x13
|
||||
#define VK_CAPITAL 0x14
|
||||
#define VK_ESCAPE 0x1B
|
||||
#define VK_SPACE 0x20
|
||||
#define VK_PRIOR 0x21
|
||||
#define VK_NEXT 0x22
|
||||
#define VK_END 0x23
|
||||
#define VK_HOME 0x24
|
||||
#define VK_LEFT 0x25
|
||||
#define VK_UP 0x26
|
||||
#define VK_RIGHT 0x27
|
||||
#define VK_DOWN 0x28
|
||||
#define VK_INSERT 0x2D
|
||||
#define VK_DELETE 0x2E
|
||||
#define VK_NUMPAD0 0x60
|
||||
#define VK_MULTIPLY 0x6A
|
||||
#define VK_ADD 0x6B
|
||||
#define VK_SUBTRACT 0x6D
|
||||
#define VK_DECIMAL 0x6E
|
||||
#define VK_DIVIDE 0x6F
|
||||
#define VK_F1 0x70
|
||||
#define VK_F2 0x71
|
||||
#define VK_F3 0x72
|
||||
#define VK_F4 0x73
|
||||
#define VK_F5 0x74
|
||||
#define VK_F6 0x75
|
||||
#define VK_F7 0x76
|
||||
#define VK_F8 0x77
|
||||
#define VK_F9 0x78
|
||||
#define VK_F10 0x79
|
||||
#define VK_F11 0x7A
|
||||
#define VK_F12 0x7B
|
||||
#define VK_LSHIFT 0xA0
|
||||
#define VK_RSHIFT 0xA1
|
||||
#define VK_LCONTROL 0xA2
|
||||
#define VK_RCONTROL 0xA3
|
||||
#define VK_LMENU 0xA4
|
||||
#define VK_RMENU 0xA5
|
||||
#define VK_OEM_1 0xBA
|
||||
#define VK_OEM_PLUS 0xBB
|
||||
#define VK_OEM_COMMA 0xBC
|
||||
#define VK_OEM_MINUS 0xBD
|
||||
#define VK_OEM_PERIOD 0xBE
|
||||
#define VK_OEM_2 0xBF
|
||||
#define VK_OEM_3 0xC0
|
||||
#define VK_OEM_4 0xDB
|
||||
#define VK_OEM_5 0xDC
|
||||
#define VK_OEM_6 0xDD
|
||||
#define VK_OEM_7 0xDE
|
||||
/* the window's key state: 0x8000 while down (display_sdl.c fills it; the Vulkan back end reads the executable's) */
|
||||
SHORT GetAsyncKeyState(int vk);
|
||||
SHORT GetKeyState(int vk);
|
||||
#define SM_CXSCREEN 0
|
||||
#define SM_CYSCREEN 1
|
||||
int GetSystemMetrics(int index);
|
||||
HWND GetForegroundWindow(void);
|
||||
#define GWL_STYLE (-16)
|
||||
#define GWL_EXSTYLE (-20)
|
||||
#define WS_EX_TOOLWINDOW 0x80
|
||||
#define WS_EX_NOACTIVATE 0x08000000
|
||||
static inline LONG_PTR GetWindowLongPtrA(HWND w, int i) { (void)w, (void)i; return 0; }
|
||||
/* (the Insert menu's Fullscreen row, gpu/vk/vk_menu.cpp: WM_APP + 7 to the window sets it, GWL_STYLE without WS_CAPTION reads it) */
|
||||
#define WM_CLOSE 0x0010
|
||||
#define WM_APP 0x8000
|
||||
#define WS_CAPTION 0x00C00000L
|
||||
BOOL PostMessageA(HWND w, UINT msg, WPARAM wp, LPARAM lp);
|
||||
LONG GetWindowLongA(HWND w, int index);
|
||||
static inline int GetClassNameA(HWND w, LPSTR s, int n) { (void)w; if (n > 0) s[0] = 0; return 0; }
|
||||
DWORD GetWindowThreadProcessId(HWND w, DWORD *pid);
|
||||
int MessageBoxA(HWND w, LPCSTR text, LPCSTR caption, UINT type);
|
||||
#define MB_OK 0
|
||||
#define MB_ICONERROR 0x10
|
||||
#define MessageBox MessageBoxA
|
||||
#ifndef MB_TOPMOST
|
||||
#define MB_TOPMOST 0x00040000L
|
||||
#endif
|
||||
#ifndef MB_ICONWARNING
|
||||
#define MB_ICONWARNING 0x00000030L
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
29
host/posix/xinput.h
Normal file
29
host/posix/xinput.h
Normal file
@@ -0,0 +1,29 @@
|
||||
/* (linux) XInput is Windows' alone: no pad answers here, and every controller comes through SDL (host/pad_sdl.c). */
|
||||
#ifndef HOOKSHOT_POSIX_XINPUT_H
|
||||
#define HOOKSHOT_POSIX_XINPUT_H
|
||||
#include <windows.h>
|
||||
#define XUSER_MAX_COUNT 4
|
||||
#define XINPUT_GAMEPAD_DPAD_UP 0x0001
|
||||
#define XINPUT_GAMEPAD_DPAD_DOWN 0x0002
|
||||
#define XINPUT_GAMEPAD_DPAD_LEFT 0x0004
|
||||
#define XINPUT_GAMEPAD_DPAD_RIGHT 0x0008
|
||||
#define XINPUT_GAMEPAD_START 0x0010
|
||||
#define XINPUT_GAMEPAD_BACK 0x0020
|
||||
#define XINPUT_GAMEPAD_LEFT_THUMB 0x0040
|
||||
#define XINPUT_GAMEPAD_RIGHT_THUMB 0x0080
|
||||
#define XINPUT_GAMEPAD_LEFT_SHOULDER 0x0100
|
||||
#define XINPUT_GAMEPAD_RIGHT_SHOULDER 0x0200
|
||||
#define XINPUT_GAMEPAD_A 0x1000
|
||||
#define XINPUT_GAMEPAD_B 0x2000
|
||||
#define XINPUT_GAMEPAD_X 0x4000
|
||||
#define XINPUT_GAMEPAD_Y 0x8000
|
||||
typedef struct {
|
||||
WORD wButtons;
|
||||
BYTE bLeftTrigger, bRightTrigger;
|
||||
SHORT sThumbLX, sThumbLY, sThumbRX, sThumbRY;
|
||||
} XINPUT_GAMEPAD;
|
||||
typedef struct { DWORD dwPacketNumber; XINPUT_GAMEPAD Gamepad; } XINPUT_STATE;
|
||||
typedef struct { WORD wLeftMotorSpeed, wRightMotorSpeed; } XINPUT_VIBRATION;
|
||||
static inline DWORD XInputGetState(DWORD user, XINPUT_STATE *s) { (void)user, (void)s; return ERROR_DEVICE_NOT_CONNECTED; }
|
||||
static inline DWORD XInputSetState(DWORD user, XINPUT_VIBRATION *v) { (void)user, (void)v; return ERROR_DEVICE_NOT_CONNECTED; }
|
||||
#endif
|
||||
520
host/prompts.c
Normal file
520
host/prompts.c
Normal file
@@ -0,0 +1,520 @@
|
||||
/* (hookshot) The button prompts of the controller in use: the game's button-icon font (Font2/Scalable/External.*.bfotf,
|
||||
every icon in a text: dialogue, the control hints, menus) served from prompts/<face>/External.bfotf in the game folder,
|
||||
which nx2/prompt_assets.py draws per controller face at build time, with each Switch button's icon pointed at the icon of
|
||||
the pad input bound to it (host/nn_hid.c's controls, the menu's Layout preset and Controls page). So the icons say which
|
||||
button to press on this pad, custom controls too.
|
||||
|
||||
The face: triforce_options.ini's button_prompts (the menu's Button prompts row): 0 Auto, from the first controller's name
|
||||
(SDL), else 1 Switch, 2 Xbox, 3 PlayStation 4, 4 PlayStation 5, 5 Steam Deck. The game reads the font once, at its start:
|
||||
a new face or new controls show at the next start.
|
||||
|
||||
The font as built: an OpenType font behind an 8-byte header, XORed per little-endian word with the key the header's magic
|
||||
(0x18029a7f) gives. Its cmap has one icon per pad input at U+F700 + HOS_PAD_*, and each Switch button's code point in a
|
||||
format 4 segment of its own, by idDelta: pointing a button at another icon is that segment's idDelta. The result goes out
|
||||
as a zstd frame of raw blocks (the file name says .zs; the game's decoder takes a frame made without its dictionary). */
|
||||
#include "hos.h"
|
||||
#include "hos_paths.h"
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#include "../gpu/vk/vk_api.h" /* (HOS_SW_*, HOS_PAD_*, HOS_BIND_PAD) */
|
||||
|
||||
int hos_binding(int set, int button, int slot); /* nn_hid.c */
|
||||
int hos_sdl_pads(uint64_t *buttons, int32_t stick[4]); /* pad_sdl.c */
|
||||
void hos_sdl_pad_first_name(char *out, size_t cap);
|
||||
int hos_mods_has(const char *prefix, const char *suffix); /* mods.c */
|
||||
|
||||
#define FONT_PATH "font2/scalable/external.nin_ounce_nvn2.bfotf.zs" /* (as hos_mods_romfs's keys: lower case) */
|
||||
#define TEXTURES_PATH "ui/layout2archive/common.product.100.nin_ounce_nvn2.bntx.zs"
|
||||
#define LAYOUTS_PATH "ui/layout2archive/common.product.100.nin_ounce_nvn2.blarc.zs"
|
||||
#define SIZES_PATH "system/resource/resourcesizetable." /* (then the version, ".rsizetable.zs") */
|
||||
#define MAGIC 0x18029a7fu
|
||||
#define PAD_BASE 0xF700
|
||||
static const char *const faces[HOS_PROMPT_N] = {"switch", "xbox", "ps4", "ps5", "steamdeck"};
|
||||
/* the Switch buttons' code points in the font, in HOS_SW_* order (nx2/prompt_assets.py SWITCH) */
|
||||
static const uint16_t switch_code[HOS_SW_N] = {0xE040, 0xE041, 0xE042, 0xE043, 0xE056, 0xE057, 0xE044, 0xE045,
|
||||
0xE046, 0xE047, 0xE04B, 0xE04C, 0xE062, 0xE060, 0xE063, 0xE061};
|
||||
|
||||
static int game_dir(char *out, size_t cap) { /* the game folder, with its separator */
|
||||
char path[MAX_PATH];
|
||||
const DWORD len = hos_game_path_a(path, MAX_PATH);
|
||||
char *slash = len ? (strrchr(path, 92) ? strrchr(path, 92) : strrchr(path, 47)) : NULL; /* (linux: '/') */
|
||||
if (!slash) return 0;
|
||||
slash[1] = 0;
|
||||
snprintf(out, cap, "%s", path);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int contains(const char *text, const char *word) { /* (any case) */
|
||||
for (; *text; text++) {
|
||||
size_t i = 0;
|
||||
while (word[i] && tolower((unsigned char)text[i]) == word[i]) i++;
|
||||
if (!word[i]) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* HOS_PROMPT_* (faces[]) */
|
||||
static int choose_face(const char *dir) {
|
||||
char path[MAX_PATH], line[80];
|
||||
int choice = 0;
|
||||
snprintf(path, sizeof path, "%striforce_options.ini", dir);
|
||||
FILE *f = fopen(path, "r");
|
||||
if (f) {
|
||||
while (fgets(line, sizeof line, f))
|
||||
if (!strncmp(line, "button_prompts=", 15)) choice = atoi(line + 15);
|
||||
fclose(f);
|
||||
}
|
||||
if (choice >= 1 && choice <= HOS_PROMPT_N) return choice - 1;
|
||||
/* Auto: the first controller SDL opens (it scans every second: up to 1.5 s for one, at the game's start) */
|
||||
char name[128] = "";
|
||||
uint64_t b = 0;
|
||||
int32_t s[4] = {0};
|
||||
for (int i = 0; i < 30 && !name[0]; i++) {
|
||||
hos_sdl_pads(&b, s);
|
||||
hos_sdl_pad_first_name(name, sizeof name);
|
||||
if (!name[0]) Sleep(50);
|
||||
}
|
||||
int face;
|
||||
if (!name[0]) face = HOS_PROMPT_SWITCH; /* (no controller: the keyboard, the game's own icons; or XInput without SDL) */
|
||||
else if (contains(name, "dualsense") || contains(name, "ps5")) face = HOS_PROMPT_PS5;
|
||||
else if (contains(name, "dualshock") || contains(name, "ps4") || contains(name, "playstation")) face = HOS_PROMPT_PS4;
|
||||
else if (contains(name, "steam deck")) face = HOS_PROMPT_STEAMDECK;
|
||||
else if (contains(name, "nintendo") || contains(name, "switch") || contains(name, "joy-con")) face = HOS_PROMPT_SWITCH;
|
||||
else face = HOS_PROMPT_XBOX; /* (Xbox pads, and the many that copy their layout) */
|
||||
hos_log("prompts: auto: controller \"%s\": %s", name[0] ? name : "(none)", faces[face]);
|
||||
return face;
|
||||
}
|
||||
|
||||
static uint32_t rd32le(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; }
|
||||
static void wr32le(uint8_t *p, uint32_t v) { p[0] = (uint8_t)v, p[1] = (uint8_t)(v >> 8), p[2] = (uint8_t)(v >> 16), p[3] = (uint8_t)(v >> 24); }
|
||||
static unsigned rd16(const uint8_t *p) { return p[0] << 8 | p[1]; }
|
||||
static uint32_t rd32(const uint8_t *p) { return (uint32_t)p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]; }
|
||||
static void wr16(uint8_t *p, unsigned v) { p[0] = (uint8_t)(v >> 8), p[1] = (uint8_t)v; }
|
||||
|
||||
/* the glyph of a code point in a format 4 subtable (st: its start, n its bytes), 0 none */
|
||||
static unsigned cmap4_glyph(const uint8_t *st, size_t n, unsigned code) {
|
||||
const unsigned segs = rd16(st + 6) / 2;
|
||||
if (14 + 8 * (size_t)segs + 2 > n) return 0;
|
||||
const uint8_t *ends = st + 14, *starts = ends + 2 * segs + 2, *deltas = starts + 2 * segs, *ranges = deltas + 2 * segs;
|
||||
for (unsigned i = 0; i < segs; i++) {
|
||||
if (rd16(ends + 2 * i) < code) continue;
|
||||
if (rd16(starts + 2 * i) > code) return 0;
|
||||
const unsigned ro = rd16(ranges + 2 * i);
|
||||
if (!ro) return (code + rd16(deltas + 2 * i)) & 0xFFFF;
|
||||
const uint8_t *g = ranges + 2 * i + ro + 2 * (code - rd16(starts + 2 * i));
|
||||
if (g + 2 > st + n) return 0;
|
||||
const unsigned gid = rd16(g);
|
||||
return gid ? (gid + rd16(deltas + 2 * i)) & 0xFFFF : 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* each Switch button's segment pointed at its pad input's icon; how many */
|
||||
static int cmap4_bind(uint8_t *st, size_t n) {
|
||||
const unsigned segs = rd16(st + 6) / 2;
|
||||
if (14 + 8 * (size_t)segs + 2 > n) return 0; /* (as cmap4_glyph: the ranges' last entry too) */
|
||||
uint8_t *ends = st + 14, *starts = ends + 2 * segs + 2, *deltas = starts + 2 * segs, *ranges = deltas + 2 * segs;
|
||||
int done = 0;
|
||||
for (int b = 0; b < HOS_SW_N; b++) {
|
||||
const int pad = hos_binding(HOS_BIND_PAD, b, 0);
|
||||
if (pad < 0 || pad >= HOS_PAD_N) continue; /* (unbound: the default icon stays) */
|
||||
const unsigned gid = cmap4_glyph(st, n, PAD_BASE + (unsigned)pad);
|
||||
if (!gid) continue;
|
||||
for (unsigned i = 0; i < segs; i++)
|
||||
if (rd16(starts + 2 * i) == switch_code[b] && rd16(ends + 2 * i) == switch_code[b] && !rd16(ranges + 2 * i)) {
|
||||
wr16(deltas + 2 * i, (gid - switch_code[b]) & 0xFFFF);
|
||||
done++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
/* the controls into the decrypted font's format 4 subtables; how many buttons */
|
||||
static int bind_font(uint8_t *otf, size_t n) {
|
||||
if (n < 12) return 0;
|
||||
const unsigned tables = rd16(otf + 4);
|
||||
for (unsigned t = 0; t < tables && 12 + 16 * (size_t)(t + 1) <= n; t++) {
|
||||
const uint8_t *rec = otf + 12 + 16 * t;
|
||||
if (memcmp(rec, "cmap", 4)) continue;
|
||||
const uint32_t off = rd32(rec + 8), len = rd32(rec + 12);
|
||||
if (off > n || len > n - off || len < 4) return 0;
|
||||
uint8_t *cmap = otf + off;
|
||||
const unsigned subs = rd16(cmap + 2);
|
||||
uint32_t seen[8];
|
||||
int nseen = 0, done = 0;
|
||||
for (unsigned s = 0; s < subs && 4 + 8 * (size_t)(s + 1) <= len; s++) {
|
||||
const uint32_t so = rd32(cmap + 4 + 8 * s + 4);
|
||||
if (so > len || len - so < 14 || rd16(cmap + so) != 4) continue; /* (so + 14 wrapped past 4 GB) */
|
||||
int dup = 0; /* (platforms 0 and 3 share one subtable) */
|
||||
for (int k = 0; k < nseen; k++) dup |= seen[k] == so;
|
||||
if (dup) continue;
|
||||
if (nseen < 8) seen[nseen++] = so;
|
||||
const unsigned sl = rd16(cmap + so + 2);
|
||||
done = cmap4_bind(cmap + so, sl <= len - so ? sl : len - so);
|
||||
}
|
||||
return done;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* a zstd frame's header for raw blocks of 128 KB: the 4-byte content size, and a window of 128 KB (raw blocks never look back:
|
||||
a single-segment frame's window, the whole content, is more than decoders take: zstd's own refuses 244 MB) */
|
||||
static void zstd_head(uint8_t head[10], size_t n) {
|
||||
wr32le(head, 0xFD2FB528u);
|
||||
head[4] = 0x80; /* (FCS 4 bytes, not single segment, no checksum, no dictionary) */
|
||||
head[5] = 7 << 3; /* (window 2^(10+7)) */
|
||||
wr32le(head + 6, (uint32_t)n);
|
||||
}
|
||||
|
||||
/* one raw block of a frame (zstd_head): k bytes (at most 128 KB), last for the frame's last */
|
||||
static int zstd_block(FILE *o, const uint8_t *data, size_t k, int last) {
|
||||
const uint32_t bh = (uint32_t)(k << 3) | (last ? 1u : 0u);
|
||||
const uint8_t b3[3] = {(uint8_t)bh, (uint8_t)(bh >> 8), (uint8_t)(bh >> 16)};
|
||||
return fwrite(b3, 1, 3, o) == 3 && fwrite(data, 1, k, o) == k;
|
||||
}
|
||||
|
||||
/* data as a zstd frame of raw blocks (zstd_head) */
|
||||
static int write_zstd_raw(const char *path, const uint8_t *data, size_t n) {
|
||||
FILE *f = fopen(path, "wb");
|
||||
if (!f) return 0;
|
||||
uint8_t head[10];
|
||||
zstd_head(head, n);
|
||||
int ok = fwrite(head, 1, 10, f) == 10;
|
||||
size_t at = 0;
|
||||
do {
|
||||
const size_t k = n - at < 131072 ? n - at : 131072;
|
||||
ok &= zstd_block(f, data + at, k, at + k == n);
|
||||
at += k;
|
||||
} while (at < n);
|
||||
ok &= fclose(f) == 0;
|
||||
return ok;
|
||||
}
|
||||
|
||||
static uint8_t *read_all(const char *path, const char *magic, long *n) { /* (the whole file, if it starts with magic: NULL any) */
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (!f) return NULL;
|
||||
fseek(f, 0, SEEK_END);
|
||||
*n = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
uint8_t *t = *n > 8 ? (uint8_t *)malloc((size_t)*n) : NULL;
|
||||
const int got = t && fread(t, 1, (size_t)*n, f) == (size_t)*n;
|
||||
fclose(f);
|
||||
if (!got || (magic && memcmp(t, magic, 4))) {
|
||||
free(t);
|
||||
return NULL;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
static volatile LONG setup_state; /* setup's: 0 not looked, 1 looking, 2 prompts, 3 none */
|
||||
|
||||
/* the game folder and the face, found once; 0 when the folder has no prompts/ (built before them: the game's own icons) */
|
||||
static int setup(char *dir, size_t cap, int *face) {
|
||||
static char d[MAX_PATH];
|
||||
static int f;
|
||||
if (InterlockedCompareExchange(&setup_state, 1, 0) == 0) {
|
||||
char path[MAX_PATH];
|
||||
int ok = game_dir(d, sizeof d);
|
||||
if (ok) {
|
||||
snprintf(path, sizeof path, "%sprompts", d);
|
||||
ok = GetFileAttributesA(path) != INVALID_FILE_ATTRIBUTES;
|
||||
}
|
||||
if (ok) f = choose_face(d);
|
||||
InterlockedExchange(&setup_state, ok ? 2 : 3);
|
||||
}
|
||||
while (setup_state == 1) Sleep(1);
|
||||
snprintf(dir, cap, "%s", d);
|
||||
*face = f;
|
||||
return setup_state == 2;
|
||||
}
|
||||
|
||||
static uint64_t fnv(uint64_t h, const void *p, size_t n) {
|
||||
for (size_t i = 0; i < n; i++) h = (h ^ ((const uint8_t *)p)[i]) * 0x100000001b3ull;
|
||||
return h;
|
||||
}
|
||||
|
||||
typedef struct { uint32_t off, len, idx; const uint8_t *data; } Run; /* (idx: its place in textures.bin) */
|
||||
static int run_cmp(const void *a, const void *b) {
|
||||
const Run *x = (const Run *)a, *y = (const Run *)b;
|
||||
return x->off != y->off ? (x->off < y->off ? -1 : 1) : (x->idx > y->idx) - (x->idx < y->idx);
|
||||
}
|
||||
static int run_order(const void *a, const void *b) {
|
||||
const uint32_t x = (*(const Run *const *)a)->idx, y = (*(const Run *const *)b)->idx;
|
||||
return (x > y) - (x < y);
|
||||
}
|
||||
|
||||
static void add_run(Run **runs, size_t *nruns, size_t *cap, uint32_t off, uint32_t len, const uint8_t *data) {
|
||||
if (*nruns == *cap) *runs = (Run *)realloc(*runs, (*cap *= 2) * sizeof **runs);
|
||||
(*runs)[*nruns] = (Run){off, len, (uint32_t)*nruns, data};
|
||||
(*nruns)++;
|
||||
}
|
||||
|
||||
/* prompts/Common.bntx.zs: the game's textures (prompts/Common.bntx) with the blocks of prompts/<face>/textures.bin that this
|
||||
pad's controls choose (nx2/prompt_assets.py: "HPTX", u32 count; each: u8 Switch button (0xff: always), u8 pad input, u16,
|
||||
u32 runs; each run: u32 offset, u32 length, the bytes; a later entry over an earlier). Written again only when the face, the
|
||||
controls or the blocks changed (prompts/Common.key) */
|
||||
/* out: the game's file (game) with the runs written over it (a later one over an earlier where they meet), as raw zstd blocks;
|
||||
written again only when its key (keypath: the hash h of what chose the runs) changed */
|
||||
static int write_patched(const char *game, const char *out, const char *keypath, uint64_t h, Run *runs, size_t nruns) {
|
||||
qsort(runs, nruns, sizeof *runs, run_cmp);
|
||||
char keyline[32] = "", want[32];
|
||||
FILE *f;
|
||||
if ((f = fopen(keypath, "r"))) {
|
||||
if (!fgets(keyline, sizeof keyline, f)) keyline[0] = 0;
|
||||
fclose(f);
|
||||
}
|
||||
snprintf(want, sizeof want, "%016llx", (unsigned long long)h);
|
||||
int ok = !strcmp(keyline, want) && GetFileAttributesA(out) != INVALID_FILE_ATTRIBUTES;
|
||||
if (!ok) { /* the game's file through, the chosen runs written over it, out as raw zstd blocks */
|
||||
FILE *in = fopen(game, "rb"), *o = fopen(out, "wb");
|
||||
uint8_t *chunk = (uint8_t *)malloc(131072);
|
||||
ok = in && o && chunk;
|
||||
if (ok) {
|
||||
fseek(in, 0, SEEK_END);
|
||||
const uint64_t n = (uint64_t)ftell(in);
|
||||
fseek(in, 0, SEEK_SET);
|
||||
uint8_t head[10];
|
||||
zstd_head(head, n);
|
||||
ok = n < 0xFFFFFFFFull && fwrite(head, 1, 10, o) == 10;
|
||||
size_t first = 0; /* (the first run that may reach this chunk) */
|
||||
const Run **here = (const Run **)malloc((nruns ? nruns : 1) * sizeof *here);
|
||||
ok = ok && here;
|
||||
for (uint64_t pos = 0; ok && pos < n;) {
|
||||
const size_t k = n - pos < 131072 ? (size_t)(n - pos) : 131072;
|
||||
ok = fread(chunk, 1, k, in) == k;
|
||||
while (first < nruns && runs[first].off + runs[first].len <= pos) first++;
|
||||
size_t nh = 0; /* (the runs in this chunk, written in their order: a later one over an earlier) */
|
||||
for (size_t r = first; r < nruns && runs[r].off < pos + k; r++)
|
||||
if (runs[r].off + runs[r].len > pos) here[nh++] = &runs[r];
|
||||
qsort(here, nh, sizeof *here, run_order);
|
||||
for (size_t i = 0; i < nh; i++) {
|
||||
const Run *r = here[i];
|
||||
const uint64_t a = r->off > pos ? r->off : pos;
|
||||
const uint64_t z = r->off + r->len < pos + k ? r->off + r->len : pos + k;
|
||||
memcpy(chunk + (a - pos), r->data + (a - r->off), (size_t)(z - a));
|
||||
}
|
||||
ok = ok && zstd_block(o, chunk, k, pos + k == n);
|
||||
pos += k;
|
||||
}
|
||||
free(here);
|
||||
}
|
||||
if (in) fclose(in);
|
||||
if (o) ok &= fclose(o) == 0;
|
||||
free(chunk);
|
||||
if (ok && (f = fopen(keypath, "w"))) {
|
||||
fputs(want, f);
|
||||
fclose(f);
|
||||
}
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
static int build_textures(char *out, size_t cap) {
|
||||
char dir[MAX_PATH], path[MAX_PATH];
|
||||
int face;
|
||||
if (!setup(dir, sizeof dir, &face)) return 0;
|
||||
snprintf(path, sizeof path, "%sprompts/%s/textures.bin", dir, faces[face]);
|
||||
long tn;
|
||||
uint8_t *t = read_all(path, "HPTX", &tn);
|
||||
if (!t) return 0; /* (built without the textures: the game's) */
|
||||
int bind[HOS_SW_N];
|
||||
for (int b = 0; b < HOS_SW_N; b++) bind[b] = hos_binding(HOS_BIND_PAD, b, 0);
|
||||
uint64_t h = fnv(fnv(fnv(0xcbf29ce484222325ull, &face, sizeof face), bind, sizeof bind), t, (size_t)tn);
|
||||
/* the runs these controls choose */
|
||||
const uint32_t count = rd32le(t + 4);
|
||||
size_t at = 8, nruns = 0, cap_runs = 256;
|
||||
Run *runs = (Run *)malloc(cap_runs * sizeof *runs);
|
||||
for (uint32_t e = 0; e < count && at + 8 <= (size_t)tn; e++) {
|
||||
const int sw = t[at], pad = t[at + 1];
|
||||
const uint32_t nr = rd32le(t + at + 4);
|
||||
const int on = sw == 0xff || (sw < HOS_SW_N && bind[sw] == pad);
|
||||
at += 8;
|
||||
for (uint32_t r = 0; r < nr && at + 8 <= (size_t)tn; r++) {
|
||||
const uint32_t off = rd32le(t + at), len = rd32le(t + at + 4);
|
||||
if (len > (size_t)tn - at - 8) break;
|
||||
if (on) add_run(&runs, &nruns, &cap_runs, off, len, t + at + 8);
|
||||
at += 8 + len;
|
||||
}
|
||||
}
|
||||
snprintf(out, cap, "%sprompts/Common.bntx.zs", dir);
|
||||
snprintf(path, sizeof path, "%sprompts/Common.bntx", dir);
|
||||
char keypath[MAX_PATH];
|
||||
snprintf(keypath, sizeof keypath, "%sprompts/Common.key", dir);
|
||||
const int ok = write_patched(path, out, keypath, h, runs, nruns);
|
||||
hos_log("prompts: %s textures, %zu runs for this pad's controls%s", faces[face], nruns,
|
||||
ok ? "" : ": could not be written");
|
||||
free(runs);
|
||||
free(t);
|
||||
return ok;
|
||||
}
|
||||
|
||||
/* the face the game was given (faces[]), -1 none: the Insert menu names the pad inputs as that controller does. -1 too
|
||||
until the game has asked for a prompt file: the menu asks from the present thread, and choose_face can wait for SDL */
|
||||
int hos_prompts_face(void) {
|
||||
char dir[MAX_PATH];
|
||||
int face;
|
||||
return setup_state >= 2 && setup(dir, sizeof dir, &face) ? face : -1;
|
||||
}
|
||||
|
||||
/* the Talk ring's place for each of A B X Y (0 east, 1 south, 2 north, 3 west: nx2/prompt_assets.py RING_PLACES): where its pad
|
||||
input is among the face buttons, else its own place on the Switch when free, else the first one free */
|
||||
static void ring_places(const int *bind, int place[4]) {
|
||||
static const int of_pad[4] = {1, 0, 3, 2}; /* (HOS_PAD_SOUTH, EAST, WEST, NORTH) */
|
||||
int taken[4] = {0};
|
||||
for (int s = 0; s < 4; s++) {
|
||||
const int p = bind[s] >= 0 && bind[s] < 4 ? of_pad[bind[s]] : -1;
|
||||
place[s] = p >= 0 && !taken[p] ? p : -1;
|
||||
if (place[s] >= 0) taken[place[s]] = 1;
|
||||
}
|
||||
for (int s = 0; s < 4; s++) {
|
||||
if (place[s] >= 0) continue;
|
||||
int p = s; /* (A B X Y's own places are 0 1 2 3) */
|
||||
if (taken[p])
|
||||
for (p = 0; taken[p]; p++) {}
|
||||
place[s] = p;
|
||||
taken[p] = 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* prompts/Common.blarc.zs: the game's layouts (prompts/Common.blarc) with
|
||||
- the Talk ring's A B X Y where their pad inputs are (prompts/ring.bin, nx2/prompt_assets.py: "HPRG", u32 count; each: u8
|
||||
group, u8 Switch button placed, u8 place, u8, u32 runs, the runs);
|
||||
- the ocarina hint's icons moved apart for the wide ones bound (prompts/<face>/hint.bin, nx2/prompt_assets.py HINTS: "HPHN",
|
||||
u32 count of pad inputs, each one's icon's extra width (f32), u32 panes; each: u32 offset, u8 slot, 3 bytes, f32 x): each
|
||||
icon the one before's extra further on, the last one where it is;
|
||||
none when both are as the game has them (the game's own file) */
|
||||
static int build_layouts(char *out, size_t cap) {
|
||||
char dir[MAX_PATH], path[MAX_PATH];
|
||||
int face;
|
||||
if (!setup(dir, sizeof dir, &face)) return 0;
|
||||
int bind[HOS_SW_N], place[4];
|
||||
for (int b = 0; b < HOS_SW_N; b++) bind[b] = hos_binding(HOS_BIND_PAD, b, 0);
|
||||
ring_places(bind, place);
|
||||
const int ring_moved = !(place[0] == 0 && place[1] == 1 && place[2] == 2 && place[3] == 3);
|
||||
size_t nruns = 0, cap_runs = 64;
|
||||
Run *runs = (Run *)malloc(cap_runs * sizeof *runs);
|
||||
uint64_t h = fnv(0xcbf29ce484222325ull, place, sizeof place);
|
||||
long tn = 0, hn = 0;
|
||||
snprintf(path, sizeof path, "%sprompts/ring.bin", dir);
|
||||
uint8_t *t = ring_moved ? read_all(path, "HPRG", &tn) : NULL;
|
||||
if (t) {
|
||||
const uint32_t count = rd32le(t + 4);
|
||||
size_t at = 8;
|
||||
for (uint32_t e = 0; e < count && at + 8 <= (size_t)tn; e++) {
|
||||
const int placed = t[at + 1], where = t[at + 2];
|
||||
const uint32_t nr = rd32le(t + at + 4);
|
||||
const int on = placed < 4 && place[placed] == where;
|
||||
at += 8;
|
||||
for (uint32_t r = 0; r < nr && at + 8 <= (size_t)tn; r++) {
|
||||
const uint32_t off = rd32le(t + at), len = rd32le(t + at + 4);
|
||||
if (len > (size_t)tn - at - 8) break;
|
||||
if (on) add_run(&runs, &nruns, &cap_runs, off, len, t + at + 8);
|
||||
at += 8 + len;
|
||||
}
|
||||
}
|
||||
h = fnv(h, t, (size_t)tn);
|
||||
}
|
||||
/* the hint's notes, in its order (Switch L R Y X A: up, down, left, right, A) */
|
||||
static const int notes[5] = {HOS_SW_L, HOS_SW_R, HOS_SW_Y, HOS_SW_X, HOS_SW_A};
|
||||
snprintf(path, sizeof path, "%sprompts/%s/hint.bin", dir, faces[face]);
|
||||
uint8_t *hint = read_all(path, "HPHN", &hn);
|
||||
float *xs = NULL;
|
||||
int spread = 0;
|
||||
if (hint) {
|
||||
const uint32_t npads = rd32le(hint + 4);
|
||||
const size_t panes_at = 8 + 4 * (size_t)npads;
|
||||
float extra[5], shift[6] = {0};
|
||||
for (int i = 0; i < 5; i++) {
|
||||
const int p = bind[notes[i]];
|
||||
extra[i] = 0;
|
||||
if (p >= 0 && (uint32_t)p < npads && panes_at <= (size_t)hn) memcpy(&extra[i], hint + 8 + 4 * p, 4);
|
||||
}
|
||||
for (int i = 3; i >= 0; i--) shift[i] = shift[i + 1] - extra[i]; /* (an icon is drawn from its pane's left) */
|
||||
shift[5] = shift[0]; /* (the text with the first icon) */
|
||||
spread = shift[0] != 0;
|
||||
const uint32_t count = panes_at + 4 <= (size_t)hn ? rd32le(hint + panes_at) : 0;
|
||||
if (spread && count <= ((size_t)hn - panes_at - 4) / 12) {
|
||||
xs = (float *)malloc(count * sizeof *xs);
|
||||
for (uint32_t k = 0; k < count; k++) {
|
||||
const uint8_t *e = hint + panes_at + 4 + 12 * k;
|
||||
memcpy(&xs[k], e + 8, 4);
|
||||
xs[k] += shift[e[4] < 6 ? e[4] : 5];
|
||||
add_run(&runs, &nruns, &cap_runs, rd32le(e), 4, (const uint8_t *)&xs[k]);
|
||||
}
|
||||
h = fnv(fnv(h, shift, sizeof shift), hint, (size_t)hn);
|
||||
}
|
||||
}
|
||||
int ok = 0;
|
||||
if (nruns) {
|
||||
char keypath[MAX_PATH];
|
||||
snprintf(out, cap, "%sprompts/Common.blarc.zs", dir);
|
||||
snprintf(path, sizeof path, "%sprompts/Common.blarc", dir);
|
||||
snprintf(keypath, sizeof keypath, "%sprompts/Common.blarc.key", dir);
|
||||
ok = write_patched(path, out, keypath, h, runs, nruns);
|
||||
hos_log("prompts: the Talk ring's A B X Y at places %d %d %d %d, the ocarina hint %s%s", place[0], place[1], place[2],
|
||||
place[3], xs ? "spread" : "as is", ok ? "" : ": could not be written");
|
||||
}
|
||||
free(xs);
|
||||
free(hint);
|
||||
free(runs);
|
||||
free(t);
|
||||
return ok;
|
||||
}
|
||||
|
||||
/* builds prompts/External.bfotf.zs for this run; 1 when there is one */
|
||||
static int build(char *out, size_t cap) {
|
||||
char dir[MAX_PATH], path[MAX_PATH];
|
||||
int face;
|
||||
if (!setup(dir, sizeof dir, &face)) return 0;
|
||||
/* (a mod's size table is served, not ours: the faces' fonts, larger than the game's, do not fit it) */
|
||||
if (hos_mods_has(SIZES_PATH, ".rsizetable.zs")) {
|
||||
hos_log("prompts: a mod has the resource size table: the game's own icons in texts");
|
||||
return 0;
|
||||
}
|
||||
snprintf(path, sizeof path, "%sprompts/%s/External.bfotf", dir, faces[face]);
|
||||
long n;
|
||||
uint8_t *b = read_all(path, NULL, &n);
|
||||
if (!b || n < 16 || n % 4) {
|
||||
hos_log("prompts: no %s: the game's own icons", path);
|
||||
free(b);
|
||||
return 0;
|
||||
}
|
||||
const uint32_t key = rd32le(b) ^ MAGIC;
|
||||
for (long i = 8; i < n; i += 4) wr32le(b + i, rd32le(b + i) ^ key);
|
||||
const int bound = bind_font(b + 8, (size_t)n - 8);
|
||||
for (long i = 8; i < n; i += 4) wr32le(b + i, rd32le(b + i) ^ key);
|
||||
snprintf(out, cap, "%sprompts/External.bfotf.zs", dir);
|
||||
const int ok = write_zstd_raw(out, b, (size_t)n);
|
||||
free(b);
|
||||
hos_log("prompts: %s icons, %d buttons on this pad's controls%s", faces[face], bound, ok ? "" : ": could not be written");
|
||||
return ok;
|
||||
}
|
||||
|
||||
/* mods.c: the file for a RomFS path the prompts replace (key: lower case, '/'), 1 with one. Asked only when no mod has
|
||||
the file: a mod's own wins */
|
||||
int hos_prompts_romfs(const char *key, char *out, size_t cap) {
|
||||
static volatile LONG state[3]; /* the font, the textures, the layouts: 0 not built, 1 being built, 2 built, 3 none */
|
||||
static char path[3][MAX_PATH];
|
||||
const size_t kn = strlen(key);
|
||||
if (!strncmp(key, SIZES_PATH, sizeof SIZES_PATH - 1) && kn > 14 && !strcmp(key + kn - 14, ".rsizetable.zs")) {
|
||||
char dir[MAX_PATH]; /* (the game's size table with room for the faces' fonts, larger than its: nx2/prompt_assets.py) */
|
||||
int face;
|
||||
if (!setup(dir, sizeof dir, &face)) return 0;
|
||||
snprintf(out, cap, "%sprompts/rsizetable.zs", dir);
|
||||
return GetFileAttributesA(out) != INVALID_FILE_ATTRIBUTES;
|
||||
}
|
||||
const int which = !strcmp(key, FONT_PATH) ? 0 : !strcmp(key, TEXTURES_PATH) ? 1 : !strcmp(key, LAYOUTS_PATH) ? 2 : -1;
|
||||
if (which < 0) return 0;
|
||||
static int (*const builders[3])(char *, size_t) = {build, build_textures, build_layouts};
|
||||
if (InterlockedCompareExchange(&state[which], 1, 0) == 0)
|
||||
InterlockedExchange(&state[which], builders[which](path[which], MAX_PATH) ? 2 : 3);
|
||||
while (state[which] == 1) Sleep(1);
|
||||
if (state[which] != 2) return 0;
|
||||
snprintf(out, cap, "%s", path[which]);
|
||||
return 1;
|
||||
}
|
||||
459
host/rx_backend.c
Normal file
459
host/rx_backend.c
Normal file
@@ -0,0 +1,459 @@
|
||||
/* Which renderer the rx_* calls go to (gpu/vk/vk_api.h): the WebGPU one in the executable (gpu/render, its
|
||||
functions renamed wgr_* by rx_wgpu_names.h) or, with RX_BACKEND=vulkan, the Vulkan one in mkw_vk.dll beside the
|
||||
executable. Decided at rx_start, before any other rx_* call; a DLL that is missing or finds no usable Vulkan
|
||||
device leaves the WebGPU renderer in place (logged). */
|
||||
#include "hos.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
|
||||
#include "../gpu/vk/vk_api.h"
|
||||
#include "../gpu/vk/dlss_math.h"
|
||||
|
||||
/* the WebGPU renderer (gpu/render, renamed) */
|
||||
int wgr_start(void *hwnd);
|
||||
void wgr_resize(int width, int height);
|
||||
const char *wgr_describe(void);
|
||||
void wgr_stats(int64_t *draws, int64_t *skipped, int64_t *pipelines);
|
||||
void wgr_nvn_submit(const uint64_t *handles, int n);
|
||||
uint64_t wgr_nvn_fence(void);
|
||||
uint64_t wgr_nvn_pushed(void);
|
||||
uint64_t wgr_nvn_replayed(void);
|
||||
int wgr_nvn_wait(uint64_t fence, uint64_t timeout_ns);
|
||||
void wgr_wait_writebacks_reading(const void *p, uint64_t n);
|
||||
void wgr_nvn_finish(void);
|
||||
void wgr_nvn_present(const nvn_tex *t, const int crop[4]);
|
||||
void wgr_nvn_register_texture(int id, const nvn_tex *t, const nvn_view *v);
|
||||
void wgr_nvn_register_sampler(int id, const nvn_samp_par *p);
|
||||
void wgr_nvn_set_texture_pool_size(int n);
|
||||
void wgr_nvn_texture_released(const nvn_tex *t);
|
||||
void wgr_nvn_program_released(const nvn_prog *p);
|
||||
void wgr_nvn_read_texels(const nvn_tex *t, unsigned level, unsigned layer0, const NVNcopyRegion *r, uint8_t *dst,
|
||||
uint64_t row, uint64_t img);
|
||||
void wgr_nvn_write_texels(const nvn_tex *t, unsigned level, unsigned layer0, const NVNcopyRegion *r,
|
||||
const uint8_t *src, uint64_t row, uint64_t img);
|
||||
void wgr_nvn_invalidate(uint64_t gpu, uint64_t size);
|
||||
|
||||
/* what the Vulkan back end is given */
|
||||
uint8_t *hos_guest_base(void);
|
||||
uint64_t hos_guest_size(void);
|
||||
uint8_t *hos_gpu_ptr(uint64_t va, uint64_t *avail);
|
||||
uint64_t nvn_gpu_guest(uint64_t gpu);
|
||||
int nvn_gpu_read(uint64_t gpu, void *dst, uint64_t n);
|
||||
int nvn_gpu_write(uint64_t gpu, const void *src, uint64_t n);
|
||||
uint32_t *rx_collect_written(int64_t *count); /* gpu/render/rx_core.cpp: the soft write watch's pages */
|
||||
void nvn_tex_layout(const nvn_texdesc *d, nvn_texlayout *o);
|
||||
uint64_t nvn_tex_level_offset(const nvn_texdesc *d, unsigned level);
|
||||
int nvn_fmt_bpb(int format, int *bw, int *bh);
|
||||
int nvn_depth_minus_w(void);
|
||||
int hos_gpu_pools(uint64_t (*out)[2], int max);
|
||||
uint32_t hos_gpu_maps_generation(void);
|
||||
uint32_t nvn_vmap_generation(void);
|
||||
uint64_t hos_reserved_cpus(void); /* hos_thread.c */
|
||||
extern float hos_aspect_ratio; /* hos_main.c: the guest camera aspect applied at startup, or 0 */
|
||||
uint32_t hos_pad_raw(void); /* nn_hid.c: the gamepads and the controls, for the Insert menu */
|
||||
int hos_binding(int set, int button, int slot);
|
||||
int hos_mic_count(void); /* nn_audio_in.c: the microphones, for the Insert menu */
|
||||
const char *hos_mic_name(int index);
|
||||
void hos_mic_select(int mode, const char *name, int index);
|
||||
void hos_bind(int set, int button, int slot, int code);
|
||||
int hos_prompts_face(void); /* prompts.c */
|
||||
#if defined(A64_WRITE_TRACK) && !defined(__EMSCRIPTEN__)
|
||||
void hos_mark_written(const void *p, size_t n);
|
||||
#endif
|
||||
|
||||
static void host_log(const char *line) { hos_log("%s", line); }
|
||||
#if defined(A64_WRITE_TRACK) && !defined(__EMSCRIPTEN__)
|
||||
int hos_gpu_guest_ranges(uint64_t (*out)[2], int max);
|
||||
/* The soft write watch's marks (rt/a64.h A64_MARK, hos_mark_written) over the GPU-visible ranges, read and cleared:
|
||||
the Vulkan back end's own collection (gpu/render's rx_collect_written works only with the WebGPU renderer started).
|
||||
One consumer: with Vulkan the WebGPU renderer never runs. */
|
||||
static int64_t collect_in(const uint64_t (*ranges)[2], int nranges, uint32_t **pages) {
|
||||
size_t n = 0, cap = 4096;
|
||||
uint32_t *out = malloc(cap * sizeof *out);
|
||||
for (int r = 0; r < nranges; r++) {
|
||||
const uint64_t lo = ranges[r][0], hi = ranges[r][1] < hos_guest_size() ? ranges[r][1] : hos_guest_size();
|
||||
uint64_t p1 = (hi + 4095) >> 12;
|
||||
if (p1 > A64_DIRTY_PAGES) p1 = A64_DIRTY_PAGES;
|
||||
for (uint64_t p = lo >> 12; p < p1;) {
|
||||
if (!(p & 31) && p + 32 <= p1) { /* (32 pages at a time while none is marked) */
|
||||
uint64_t w[4];
|
||||
memcpy(w, &a64_dirty[p], 32);
|
||||
if (!(w[0] | w[1] | w[2] | w[3])) {
|
||||
p += 32;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (!(p & 7) && p + 8 <= p1) { /* (eight pages a load while none is marked) */
|
||||
uint64_t w;
|
||||
memcpy(&w, &a64_dirty[p], 8);
|
||||
if (!w) {
|
||||
p += 8;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (__atomic_load_n(&a64_dirty[p], __ATOMIC_RELAXED) && __atomic_exchange_n(&a64_dirty[p], 0, __ATOMIC_ACQUIRE)) {
|
||||
if (n == cap) out = realloc(out, (cap *= 2) * sizeof *out);
|
||||
out[n++] = (uint32_t)p;
|
||||
}
|
||||
p++;
|
||||
}
|
||||
}
|
||||
*pages = out;
|
||||
return (int64_t)n;
|
||||
}
|
||||
static int64_t host_collect(uint32_t **pages) {
|
||||
static uint64_t (*ranges)[2];
|
||||
if (!ranges) ranges = malloc(sizeof *ranges * 4096);
|
||||
return collect_in(ranges, hos_gpu_guest_ranges(ranges, 4096), pages);
|
||||
}
|
||||
/* (only within the given guest ranges: the submit-time capture of the mirrored pools, a small part of the 20 ms the
|
||||
whole collection takes) */
|
||||
static int64_t host_collect_in(const uint64_t (*ranges)[2], int n, uint32_t **pages) { return collect_in(ranges, n, pages); }
|
||||
#else
|
||||
static int64_t host_collect(uint32_t **pages) {
|
||||
int64_t n = -1;
|
||||
*pages = rx_collect_written(&n);
|
||||
return n;
|
||||
}
|
||||
static int64_t host_collect_in(const uint64_t (*ranges)[2], int n, uint32_t **pages) { (void)ranges, (void)n; *pages = 0; return 0; }
|
||||
#endif
|
||||
static void host_free_pages(uint32_t *pages) { free(pages); }
|
||||
static void host_mark_written(const void *p, uint64_t n) {
|
||||
#if defined(A64_WRITE_TRACK) && !defined(__EMSCRIPTEN__)
|
||||
hos_mark_written(p, (size_t)n);
|
||||
#else
|
||||
(void)p, (void)n;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* (the renderer's own guest memory: the address space above the heap, as the game's own regions, committed and
|
||||
zeroed; the region allocator never hands it to the game) */
|
||||
static uint64_t host_guest_alloc(uint64_t size) {
|
||||
const uint64_t a = hos_region_alloc(size, 0x10000);
|
||||
if (a) memset(hos_guest_base() + a, 0, size);
|
||||
return a;
|
||||
}
|
||||
|
||||
void hos_watch_guest_writes(const uint8_t *data, uint64_t size); /* nvn_native.c */
|
||||
static void host_watch_guest_writes(uint64_t guest, uint64_t size) { hos_watch_guest_writes(hos_guest_base() + guest, size); }
|
||||
static float host_aspect_ratio(void) { return hos_aspect_ratio; }
|
||||
static float host_wide_menus(uint32_t keep_mask) { /* (MkwVkHost.wide_menus) */
|
||||
extern volatile uint32_t hos_wide_keep_mask;
|
||||
extern volatile float hos_wide_margin;
|
||||
static const char *forced;
|
||||
static int looked;
|
||||
if (!looked) looked = 1, forced = getenv("HOS_WIDE_KEEP");
|
||||
hos_wide_keep_mask = forced ? (uint32_t)strtoul(forced, NULL, 16) : keep_mask;
|
||||
return hos_wide_margin;
|
||||
}
|
||||
int hos_mouse_pointer(MkwVkPointer *out); /* display.c, posix/display_sdl.c */
|
||||
int hos_sdl_gyro_status(void); /* pad_sdl.c */
|
||||
extern const char *hos_romfs_dir; /* nn_fs.c, set by hos_main.c */
|
||||
static const char *host_romfs_dir(void) { return hos_romfs_dir; }
|
||||
|
||||
#ifdef _WIN32
|
||||
static unsigned char menu_key_press[256];
|
||||
void hos_vk_note_key_press(unsigned key) {
|
||||
if (key < sizeof menu_key_press) __atomic_store_n(&menu_key_press[key], 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
int hos_vk_take_key_press(int key) {
|
||||
return (unsigned)key < sizeof menu_key_press &&
|
||||
__atomic_exchange_n(&menu_key_press[key], 0, __ATOMIC_RELAXED);
|
||||
}
|
||||
#define host_take_key_press hos_vk_take_key_press
|
||||
#else
|
||||
#define host_take_key_press NULL
|
||||
#endif
|
||||
|
||||
static const MkwVkHost vk_host = {
|
||||
MKWVK_API_VERSION, host_log, hos_guest_base, hos_guest_size, hos_gpu_ptr, nvn_gpu_guest, nvn_gpu_read,
|
||||
nvn_gpu_write, host_collect, host_free_pages, host_mark_written, hos_ticks, hos_now_ns, nvn_tex_layout,
|
||||
nvn_tex_level_offset, nvn_fmt_bpb, nvn_tex_level_tiles, nvn_tex_linear_stride, nvn_depth_minus_w, hos_gpu_pools,
|
||||
hos_gpu_maps_generation, nvn_vmap_generation, hos_reserved_cpus, host_collect_in, host_guest_alloc,
|
||||
host_watch_guest_writes, hos_pad_raw, hos_binding, hos_bind, host_aspect_ratio, host_take_key_press,
|
||||
hos_mouse_pointer, hos_mic_count, hos_mic_name, hos_mic_select, hos_sdl_gyro_status, hos_log_flush, hos_prompts_face,
|
||||
host_romfs_dir, host_wide_menus,
|
||||
};
|
||||
|
||||
static const MkwVkRenderer *vk; /* the Vulkan back end, when it was chosen and started */
|
||||
static HMODULE vk_module; /* (the last back end loaded: rx_close_asked) */
|
||||
|
||||
/* The game registers its first textures and samplers before the window's thread starts the renderer (NVN is up
|
||||
first): those calls are kept here and given to the renderer rx_start chose, in order. Without that the Vulkan back
|
||||
end never knew the first ~0x60 texture slots, and lit geometry sampled them as its black dummy.
|
||||
The texels the game writes then (WriteTexels) are kept too, with a copy of their data: without a renderer they went
|
||||
nowhere (Linux has no WebGPU renderer to take them), and a texture filled so at boot kept zeros in its storage. OoT's
|
||||
4x4 white placeholder is one: bound in place of the ground fog's depth, it read 0 and hid the ground fog at some camera
|
||||
angles. That happened when the window's thread started the renderer after the game had begun (windowed, not headless). */
|
||||
typedef struct {
|
||||
int kind; /* 0 texture registration, 1 sampler registration, 2 texture pool size, 3 texture finalized, 4 texture
|
||||
made, 5 texels written */
|
||||
int id;
|
||||
nvn_tex t;
|
||||
nvn_view v;
|
||||
int has_view;
|
||||
nvn_samp_par p;
|
||||
/* (5: WriteTexels) */
|
||||
unsigned level, layer0;
|
||||
NVNcopyRegion r;
|
||||
uint64_t row, img;
|
||||
uint8_t *data;
|
||||
} early_call;
|
||||
static early_call *early;
|
||||
static size_t n_early, cap_early;
|
||||
static volatile LONG started; /* rx_start chose (the calls go straight to the renderer from then on) */
|
||||
static SRWLOCK early_lock = SRWLOCK_INIT;
|
||||
|
||||
static void forward(const early_call *c);
|
||||
/* Keeps a call made before rx_start; 0 when the renderer is chosen already (the caller forwards it) */
|
||||
static int keep_early(const early_call *c) {
|
||||
if (started) return 0;
|
||||
AcquireSRWLockExclusive(&early_lock);
|
||||
if (started) {
|
||||
ReleaseSRWLockExclusive(&early_lock);
|
||||
return 0;
|
||||
}
|
||||
if (n_early == cap_early) {
|
||||
cap_early = cap_early ? cap_early * 2 : 1024;
|
||||
early = (early_call *)realloc(early, cap_early * sizeof *early);
|
||||
}
|
||||
early[n_early++] = *c;
|
||||
ReleaseSRWLockExclusive(&early_lock);
|
||||
return 1;
|
||||
}
|
||||
/* rx_start: the kept calls given to the renderer chosen, then the gate opened */
|
||||
static void flush_early(void) {
|
||||
AcquireSRWLockExclusive(&early_lock);
|
||||
size_t texels = 0;
|
||||
for (size_t i = 0; i < n_early; i++) {
|
||||
forward(&early[i]);
|
||||
if (early[i].kind == 5) texels++, free(early[i].data);
|
||||
}
|
||||
if (n_early)
|
||||
hos_log("rx: %zu texture and sampler calls made before the renderer started (%zu texel writes), given to it", n_early,
|
||||
texels);
|
||||
free(early);
|
||||
early = NULL, n_early = cap_early = 0;
|
||||
InterlockedExchange(&started, 1);
|
||||
ReleaseSRWLockExclusive(&early_lock);
|
||||
}
|
||||
|
||||
/* dll: mkw_vk.dll (our Vulkan back end) or mkw_eden.dll (Eden's renderer driven natively, gpu/eden): one export */
|
||||
static const MkwVkRenderer *load_vulkan(const char *dll) {
|
||||
char path[MAX_PATH];
|
||||
const DWORD n = GetModuleFileNameA(NULL, path, MAX_PATH);
|
||||
char *slash = n ? (strrchr(path, '\\') ? strrchr(path, '\\') : strrchr(path, '/')) : NULL; /* (linux: '/') */
|
||||
if (!slash || (size_t)(slash + 1 - path) + strlen(dll) >= sizeof path) return NULL; /* (a path near MAX_PATH) */
|
||||
memcpy(slash + 1, dll, strlen(dll) + 1);
|
||||
HMODULE m = LoadLibraryA(path);
|
||||
if (!m) {
|
||||
hos_log("rx: RX_BACKEND=vulkan, but %s did not load (%lu): WebGPU", path, GetLastError());
|
||||
return NULL;
|
||||
}
|
||||
vk_module = m;
|
||||
mkwvk_init_fn init = (mkwvk_init_fn)(void *)GetProcAddress(m, "mkwvk_init");
|
||||
const MkwVkRenderer *r = init ? init(&vk_host) : NULL;
|
||||
if (!r || r->version != MKWVK_API_VERSION) {
|
||||
hos_log("rx: the Vulkan back end did not start: WebGPU");
|
||||
return NULL;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
int rx_start(void *hwnd) {
|
||||
const char *b = getenv("RX_BACKEND");
|
||||
const int eden = b && !_stricmp(b, "eden");
|
||||
if (!b || !_stricmp(b, "vulkan") || eden) { /* (hookshot: Vulkan unless told otherwise; a started game has no RX_BACKEND) */
|
||||
const char *dll = eden ? "mkw_eden.dll" : "triforce_vk.dll";
|
||||
const MkwVkRenderer *r = load_vulkan(dll);
|
||||
if (r && r->start(hwnd)) {
|
||||
vk = r;
|
||||
hos_log("rx: renderer: %s (%s)", eden ? "Eden's" : "Vulkan", dll);
|
||||
flush_early();
|
||||
return 1;
|
||||
}
|
||||
if (r) hos_log("rx: the Vulkan back end could not start on the window: WebGPU");
|
||||
}
|
||||
const int ok = wgr_start(hwnd);
|
||||
flush_early();
|
||||
return ok;
|
||||
}
|
||||
/* (hookshot) hookshot --prepare-shaders: the Vulkan back end started with no window and no game, which prepares
|
||||
every shader in its start (gpu/vk/vk_main.cpp started_up) and is then let go. 0 when there is no usable Vulkan */
|
||||
int rx_prepare_shaders(void) {
|
||||
const MkwVkRenderer *r = load_vulkan("triforce_vk.dll");
|
||||
return r && r->start(NULL);
|
||||
}
|
||||
/* (hookshot) the window is being closed: a back end still preparing its shaders stops and keeps what it made first (a few
|
||||
seconds at most). One without the export (an older one) has nothing to keep */
|
||||
void rx_close_asked(void) {
|
||||
if (!vk_module) return;
|
||||
void (*close_asked)(void) = (void (*)(void))(void *)GetProcAddress(vk_module, "mkwvk_close_asked");
|
||||
if (close_asked) close_asked();
|
||||
}
|
||||
void rx_resize(int width, int height) { vk ? vk->resize(width, height) : wgr_resize(width, height); }
|
||||
const char *rx_describe(void) { return vk ? vk->describe() : wgr_describe(); }
|
||||
void rx_stats(int64_t *draws, int64_t *skipped, int64_t *pipelines) {
|
||||
vk ? vk->stats(draws, skipped, pipelines) : wgr_stats(draws, skipped, pipelines);
|
||||
}
|
||||
void rx_nvn_submit(const uint64_t *handles, int n) { vk ? vk->nvn_submit(handles, n) : wgr_nvn_submit(handles, n); }
|
||||
void rx_nvn_submit_q(const uint64_t *handles, int n, uint64_t queue) {
|
||||
if (vk && vk->nvn_submit_q) vk->nvn_submit_q(handles, n, queue);
|
||||
else rx_nvn_submit(handles, n);
|
||||
}
|
||||
uint64_t rx_nvn_fence(void) { return vk ? vk->nvn_fence() : wgr_nvn_fence(); }
|
||||
uint64_t rx_nvn_fence_q(uint64_t queue) { return vk && vk->nvn_fence_q ? vk->nvn_fence_q(queue) : rx_nvn_fence(); }
|
||||
uint64_t rx_nvn_pushed(void) { return vk ? vk->nvn_pushed() : wgr_nvn_pushed(); }
|
||||
uint64_t rx_nvn_replayed(void) { return vk ? vk->nvn_replayed() : wgr_nvn_replayed(); }
|
||||
int rx_nvn_wait(uint64_t fence, uint64_t timeout_ns) {
|
||||
return vk ? vk->nvn_wait(fence, timeout_ns) : wgr_nvn_wait(fence, timeout_ns);
|
||||
}
|
||||
void rx_wait_writebacks_reading(const void *p, uint64_t n) {
|
||||
vk ? vk->wait_writebacks_reading(p, n) : wgr_wait_writebacks_reading(p, n);
|
||||
}
|
||||
void rx_nvn_finish(void) { vk ? vk->nvn_finish() : wgr_nvn_finish(); }
|
||||
static volatile LONG presents; /* (the frames shown, for the camera jitter below) */
|
||||
void rx_nvn_present(const nvn_tex *t, const int crop[4]) {
|
||||
InterlockedIncrement(&presents);
|
||||
vk ? vk->nvn_present(t, crop) : wgr_nvn_present(t, crop);
|
||||
}
|
||||
/* (hookshot, nx2/oot_jitter.py) the temporal upscaler's camera jitter (NVIDIA DLSS, AMD FSR 4: gpu/vk/vk_temporal.cpp): this frame's sub-pixel offset of the scene's projection, in clip
|
||||
space (what P[0][2] and P[1][2] get), into out, for the projection matrix at guest address projection (row major, as the
|
||||
game fills its views' uniform buffers from it); 0 when there is none: DLSS and FSR off (or a renderer without them: rx_option
|
||||
HOS_OPT_DLSS_JITTER_W and _H, the scene's size in pixels, are 0), or a projection that is not one of the picture's
|
||||
(gpu/vk/dlss_math.h dlss_jitter_clip: a shadow map's, the HUD's). The renderer reads the offset back from
|
||||
the camera's uniform buffer (gpu/vk/vk_temporal.cpp), so this only has to pick sub-pixel offsets that cover a pixel evenly:
|
||||
the Halton (2, 3) sequence, over as many frames as the upscaler's scale wants (HOS_OPT_DLSS_JITTER_PHASES: gpu/vk/dlss_math.h
|
||||
dlss_jitter_phases, 8 for DLAA up to 64). */
|
||||
int hos_dlss_jitter_clip(uint64_t projection, float out[2]) {
|
||||
static LONG at = -1;
|
||||
static float w, h;
|
||||
static int phases;
|
||||
const LONG frame = presents;
|
||||
if (frame != at) { /* (asked once a frame: the renderer's lock is not taken for every view) */
|
||||
at = frame;
|
||||
w = (float)rx_option(HOS_OPT_DLSS_JITTER_W, 0), h = (float)rx_option(HOS_OPT_DLSS_JITTER_H, 0);
|
||||
phases = rx_option(HOS_OPT_DLSS_JITTER_PHASES, 16);
|
||||
}
|
||||
float p[16];
|
||||
memcpy(p, GP(projection), sizeof p);
|
||||
extern volatile float hos_wide_ratio;
|
||||
return dlss_jitter_clip(p, hos_wide_ratio, (unsigned)frame, phases, w, h, out);
|
||||
}
|
||||
static void forward(const early_call *c) {
|
||||
switch (c->kind) {
|
||||
case 0: {
|
||||
const nvn_view *v = c->has_view ? &c->v : NULL;
|
||||
vk ? vk->nvn_register_texture(c->id, &c->t, v) : wgr_nvn_register_texture(c->id, &c->t, v);
|
||||
break;
|
||||
}
|
||||
case 1: vk ? vk->nvn_register_sampler(c->id, &c->p) : wgr_nvn_register_sampler(c->id, &c->p); break;
|
||||
case 2: vk ? vk->nvn_set_texture_pool_size(c->id) : wgr_nvn_set_texture_pool_size(c->id); break;
|
||||
case 3: vk ? vk->nvn_texture_released(&c->t) : wgr_nvn_texture_released(&c->t); break;
|
||||
case 4: if (vk && vk->nvn_texture_created) vk->nvn_texture_created(&c->t); break;
|
||||
case 5:
|
||||
vk ? vk->nvn_write_texels(&c->t, c->level, c->layer0, &c->r, c->data, c->row, c->img)
|
||||
: wgr_nvn_write_texels(&c->t, c->level, c->layer0, &c->r, c->data, c->row, c->img);
|
||||
break;
|
||||
}
|
||||
}
|
||||
void rx_nvn_register_texture(int id, const nvn_tex *t, const nvn_view *v) {
|
||||
if (!started && t) {
|
||||
early_call c = {0, id};
|
||||
c.t = *t;
|
||||
if (v) c.v = *v, c.has_view = 1;
|
||||
if (keep_early(&c)) return;
|
||||
}
|
||||
vk ? vk->nvn_register_texture(id, t, v) : wgr_nvn_register_texture(id, t, v);
|
||||
}
|
||||
void rx_nvn_register_sampler(int id, const nvn_samp_par *p) {
|
||||
if (!started && p) {
|
||||
early_call c = {1, id};
|
||||
c.p = *p;
|
||||
if (keep_early(&c)) return;
|
||||
}
|
||||
vk ? vk->nvn_register_sampler(id, p) : wgr_nvn_register_sampler(id, p);
|
||||
}
|
||||
void rx_nvn_set_texture_pool_size(int n) {
|
||||
if (!started) {
|
||||
early_call c = {2, n};
|
||||
if (keep_early(&c)) return;
|
||||
}
|
||||
vk ? vk->nvn_set_texture_pool_size(n) : wgr_nvn_set_texture_pool_size(n);
|
||||
}
|
||||
void rx_nvn_texture_released(const nvn_tex *t) {
|
||||
if (!started && t) {
|
||||
early_call c = {3, 0};
|
||||
c.t = *t;
|
||||
if (keep_early(&c)) return;
|
||||
}
|
||||
vk ? vk->nvn_texture_released(t) : wgr_nvn_texture_released(t);
|
||||
}
|
||||
void rx_nvn_texture_created(const nvn_tex *t) {
|
||||
if (!started && t) {
|
||||
early_call c = {4, 0};
|
||||
c.t = *t;
|
||||
if (keep_early(&c)) return;
|
||||
}
|
||||
if (vk && vk->nvn_texture_created) vk->nvn_texture_created(t);
|
||||
}
|
||||
void rx_nvn_program_released(const nvn_prog *p) { vk ? vk->nvn_program_released(p) : wgr_nvn_program_released(p); }
|
||||
void rx_nvn_read_texels(const nvn_tex *t, unsigned level, unsigned layer0, const NVNcopyRegion *r, uint8_t *dst,
|
||||
size_t row, size_t img) {
|
||||
vk ? vk->nvn_read_texels(t, level, layer0, r, dst, row, img) : wgr_nvn_read_texels(t, level, layer0, r, dst, row, img);
|
||||
}
|
||||
void rx_nvn_write_texels(const nvn_tex *t, unsigned level, unsigned layer0, const NVNcopyRegion *r, const uint8_t *src,
|
||||
size_t row, size_t img) {
|
||||
if (!started && t && r && src) { /* (kept with a copy of the data: the caller's buffer is its own again on return) */
|
||||
int bw = 1, bh = 1;
|
||||
const int bpb = nvn_fmt_bpb(t->d.format, &bw, &bh);
|
||||
if (bpb > 0 && bw > 0 && bh > 0 && r->width > 0 && r->height > 0) {
|
||||
const uint64_t wb = (uint64_t)((r->width + bw - 1) / bw) * (uint64_t)bpb, hb = (uint64_t)((r->height + bh - 1) / bh);
|
||||
const uint64_t depth = r->depth > 0 ? (uint64_t)r->depth : 1;
|
||||
/* (the bytes the copy reads: the last row of the last slice ends the data, whatever the strides) */
|
||||
const uint64_t n = (depth - 1) * img + (hb - 1) * row + wb;
|
||||
early_call c = {5, 0};
|
||||
c.t = *t, c.level = level, c.layer0 = layer0, c.r = *r, c.row = row, c.img = img;
|
||||
c.data = (uint8_t *)malloc(n);
|
||||
if (c.data) {
|
||||
memcpy(c.data, src, n);
|
||||
if (keep_early(&c)) return;
|
||||
free(c.data);
|
||||
}
|
||||
}
|
||||
}
|
||||
vk ? vk->nvn_write_texels(t, level, layer0, r, src, row, img)
|
||||
: wgr_nvn_write_texels(t, level, layer0, r, src, row, img);
|
||||
}
|
||||
void rx_nvn_invalidate(uint64_t gpu, uint64_t size) {
|
||||
/* The callback can wait for replay or GPU write-back: let another guest thread use this core meanwhile. */
|
||||
const int away = hos_vcore_away();
|
||||
vk ? vk->nvn_invalidate(gpu, size) : wgr_nvn_invalidate(gpu, size);
|
||||
if (away) hos_vcore_back();
|
||||
}
|
||||
int rx_guest_imported(uint64_t lo, uint64_t hi) {
|
||||
/* (mkw-recomp 16bc3bc: it takes the back end's pool lock, which the replay holds at times: no virtual core held) */
|
||||
const int away = hos_vcore_away();
|
||||
const int r = vk && vk->guest_imported ? vk->guest_imported(lo, hi) : 0;
|
||||
if (away) hos_vcore_back();
|
||||
return r;
|
||||
}
|
||||
/* (nvn_native.c: the CPU set an event's value) in order with the submits, for the GPU's waits on it */
|
||||
int rx_option(int id, int otherwise) { return vk && vk->option ? vk->option(id) : otherwise; }
|
||||
void rx_option_set(int id, int value) { if (vk && vk->option_set) vk->option_set(id, value); }
|
||||
void rx_nvn_event_signal(uint64_t gpu, uint32_t value) {
|
||||
if (vk && vk->nvn_event_signal) vk->nvn_event_signal(gpu, value);
|
||||
}
|
||||
/* (nvn_native.c: virtual pages about to be unmapped or remapped) the Vulkan back end writes what the GPU drew there into
|
||||
their memory first */
|
||||
void rx_nvn_vmap_changing(uint64_t gpu, uint64_t size) {
|
||||
/* (mkw-recomp 16bc3bc: it may wait for the replay and the GPU's texels: no virtual core held meanwhile) */
|
||||
const int away = hos_vcore_away();
|
||||
if (vk && vk->nvn_vmap_changing) vk->nvn_vmap_changing(gpu, size);
|
||||
if (away) hos_vcore_back();
|
||||
}
|
||||
void rx_nvn_pool_created(uint64_t gpu, uint64_t size) {
|
||||
if (vk && vk->nvn_pool_created) vk->nvn_pool_created(gpu, size);
|
||||
}
|
||||
48
host/rx_nowgpu.c
Normal file
48
host/rx_nowgpu.c
Normal file
@@ -0,0 +1,48 @@
|
||||
/* (EvilOOT, 11-06) Stand-ins for the WebGPU renderer (gpu/render, renamed wgr_* by rx_wgpu_names.h) when the build
|
||||
has no wgpu-native release (nx2/build.py: "building without the renderer"): host/rx_backend.c and nn_hid.c still
|
||||
name its functions, so the executable did not link. Built only then (build.py leaves this file out when
|
||||
wgpu-native is there). With RX_BACKEND=vulkan none of the wgr_* calls is made; wgr_start fails, so a missing or
|
||||
unusable triforce_vk.dll shows as "no renderer" instead of a game that runs with nothing drawn. */
|
||||
#include "hos.h"
|
||||
#include <stdint.h>
|
||||
|
||||
int wgr_start(void *hwnd) {
|
||||
(void)hwnd;
|
||||
hos_log("rx: this build has no WebGPU renderer (no wgpu-native): only the Vulkan back end (RX_BACKEND=vulkan) draws");
|
||||
return 0;
|
||||
}
|
||||
void wgr_resize(int width, int height) { (void)width, (void)height; }
|
||||
const char *wgr_describe(void) { return "none (built without wgpu-native)"; }
|
||||
void wgr_stats(int64_t *draws, int64_t *skipped, int64_t *pipelines) {
|
||||
if (draws) *draws = 0;
|
||||
if (skipped) *skipped = 0;
|
||||
if (pipelines) *pipelines = 0;
|
||||
}
|
||||
void wgr_nvn_submit(const uint64_t *handles, int n) { (void)handles, (void)n; }
|
||||
uint64_t wgr_nvn_fence(void) { return 0; }
|
||||
uint64_t wgr_nvn_pushed(void) { return 0; }
|
||||
uint64_t wgr_nvn_replayed(void) { return 0; }
|
||||
int wgr_nvn_wait(uint64_t fence, uint64_t timeout_ns) { (void)fence, (void)timeout_ns; return 1; }
|
||||
void wgr_wait_writebacks_reading(const void *p, uint64_t n) { (void)p, (void)n; }
|
||||
void wgr_nvn_finish(void) {}
|
||||
void wgr_nvn_present(const void *t, const int crop[4]) { (void)t, (void)crop; }
|
||||
void wgr_nvn_register_texture(int id, const void *t, const void *v) { (void)id, (void)t, (void)v; }
|
||||
void wgr_nvn_register_sampler(int id, const void *p) { (void)id, (void)p; }
|
||||
void wgr_nvn_set_texture_pool_size(int n) { (void)n; }
|
||||
void wgr_nvn_texture_released(const void *t) { (void)t; }
|
||||
void wgr_nvn_program_released(const void *p) { (void)p; }
|
||||
void wgr_nvn_read_texels(const void *t, unsigned level, unsigned layer0, const void *r, uint8_t *dst, uint64_t row,
|
||||
uint64_t img) {
|
||||
(void)t, (void)level, (void)layer0, (void)r, (void)dst, (void)row, (void)img;
|
||||
}
|
||||
void wgr_nvn_write_texels(const void *t, unsigned level, unsigned layer0, const void *r, const uint8_t *src,
|
||||
uint64_t row, uint64_t img) {
|
||||
(void)t, (void)level, (void)layer0, (void)r, (void)src, (void)row, (void)img;
|
||||
}
|
||||
void wgr_nvn_invalidate(uint64_t gpu, uint64_t size) { (void)gpu, (void)size; }
|
||||
|
||||
/* the live-input file's !commands that only the WebGPU renderer implements (nn_hid.c) */
|
||||
void rx_request_frame_dump(void) { hos_log("rx: !dump needs the WebGPU renderer (Vulkan: RX_VK_DUMP)"); }
|
||||
void rx_set_screenshot_ms(int64_t ms) { (void)ms; hos_log("rx: !shots needs the WebGPU renderer (Vulkan: RX_VK_SHOTS)"); }
|
||||
void rx_request_rdoc_capture(int frames) { (void)frames; hos_log("rx: !rdoc needs the WebGPU renderer"); }
|
||||
void rx_flash_dark_arm(void) { hos_log("rx: !flasharm needs the WebGPU renderer (Vulkan: RX_VK_FLASH)"); }
|
||||
Reference in New Issue
Block a user