diff --git a/README.md b/README.md index 488c35b..a66f680 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ layer cake, and every setting lives in one menu. **Laptop-style display switching** - Plug HDMI in and the picture moves to the TV (720p, or 640x480 for the retro look). Unplug it and it's back on the LCD, even mid-game. + The native **Ports** do the same: they render at 640x480 and the display engine scales them to the screen in use ([docs/native-games.md](docs/native-games.md)). - In docked mode, the controller that starts a game becomes player 1. **Controls** @@ -150,6 +151,7 @@ program also builds and tests on a PC: `cd frontend && make check`. Details: [do | [rom-transfer.md](docs/rom-transfer.md) | USB, web page and Windows share | | [updates.md](docs/updates.md) | Signed system updates (`.rsu` packages, keys) | | [power.md](docs/power.md) | Battery, charging, shutdown | +| [native-games.md](docs/native-games.md) | Ports: native games, HDMI switching, N64 pad layouts | | [pro-storage.md](docs/pro-storage.md) | RetroStone2 Pro: eMMC and M.2 storage, starter card; game covers, multi-disc games, memory speed | | [translating.md](docs/translating.md) | Adding or fixing a translation | | [homebrew.md](docs/homebrew.md) | The bundled games and their licences | diff --git a/buildroot-external/board/retrostone2/linux.fragment b/buildroot-external/board/retrostone2/linux.fragment index 534d36b..d133369 100644 --- a/buildroot-external/board/retrostone2/linux.fragment +++ b/buildroot-external/board/retrostone2/linux.fragment @@ -50,6 +50,8 @@ CONFIG_INPUT_EVDEV=y CONFIG_INPUT_JOYSTICK=y CONFIG_JOYSTICK_ADC=y CONFIG_JOYSTICK_XPAD=y +# rsos-gamepad: the built-in controls as one virtual gamepad for native games +CONFIG_INPUT_UINPUT=y CONFIG_INPUT_KEYBOARD=y CONFIG_KEYBOARD_GPIO=y CONFIG_KEYBOARD_GPIO_POLLED=y diff --git a/buildroot-external/board/retrostone2/patches/sdl2/0001-kmsdrm-output-policy.patch b/buildroot-external/board/retrostone2/patches/sdl2/0001-kmsdrm-output-policy.patch new file mode 100644 index 0000000..b5d1e64 --- /dev/null +++ b/buildroot-external/board/retrostone2/patches/sdl2/0001-kmsdrm-output-policy.patch @@ -0,0 +1,1012 @@ +--- a/src/video/kmsdrm/SDL_kmsdrmvideo.c ++++ b/src/video/kmsdrm/SDL_kmsdrmvideo.c +@@ -45,6 +45,7 @@ + #include "SDL_kmsdrmmouse.h" + #include "SDL_kmsdrmdyn.h" + #include "SDL_kmsdrmvulkan.h" ++#include "policy.h" /* RetroStoneOS output policy (rsos patch) */ + #include + #include + #include +@@ -711,6 +712,262 @@ + return SDL_FALSE; + } + ++ ++/* ---- RetroStoneOS output policy (sdl2 patch 0001) ---------------------- ++ * The game picks its output as the libretro host does (display.c): HDMI when ++ * plugged in, else the built-in panel; the policy mode; HDMI never on the ++ * panel's CRTC. The menu's environment sets the settings (RSOS_HDMI_W/H/HZ, ++ * RSOS_HDMI_CRTC, RSOS_PANEL_KEEP); defaults are the RetroStone2's. */ ++static int rsos_env_int(const char *name, int def) ++{ ++ const char *v = SDL_getenv(name); ++ return v && *v ? SDL_atoi(v) : def; ++} ++ ++/* Does the connector have an EDID blob? (The kernel's no-EDID DMT list is ++ * not a real EDID.) */ ++static SDL_bool rsos_connector_has_edid(int drm_fd, drmModeConnector *connector) ++{ ++ int i; ++ ++ for (i = 0; i < connector->count_props; i++) { ++ drmModePropertyPtr prop = KMSDRM_drmModeGetProperty(drm_fd, connector->props[i]); ++ SDL_bool edid = SDL_FALSE; ++ ++ if (prop && SDL_strcmp(prop->name, "EDID") == 0 && connector->prop_values[i] != 0) { ++ edid = SDL_TRUE; ++ } ++ if (prop) { ++ KMSDRM_drmModeFreeProperty(prop); ++ } ++ if (edid) { ++ return SDL_TRUE; ++ } ++ } ++ return SDL_FALSE; ++} ++ ++/* The connector's possible CRTCs: the union over its encoders. */ ++static uint32_t rsos_possible_crtcs(int drm_fd, drmModeRes *resources, drmModeConnector *connector) ++{ ++ uint32_t mask = 0; ++ int i, j; ++ ++ for (i = 0; i < resources->count_encoders; i++) { ++ drmModeEncoder *enc = KMSDRM_drmModeGetEncoder(drm_fd, resources->encoders[i]); ++ ++ if (!enc) { ++ continue; ++ } ++ for (j = 0; j < connector->count_encoders; j++) { ++ if (connector->encoders[j] == enc->encoder_id) { ++ mask |= enc->possible_crtcs; ++ } ++ } ++ KMSDRM_drmModeFreeEncoder(enc); ++ } ++ return mask; ++} ++ ++/* Forced by the policy for the next AddDisplay() (0 = none). */ ++static uint32_t rsos_force_crtc_id; ++static int rsos_force_w, rsos_force_h, rsos_force_hz; ++static uint32_t rsos_force_conn_id; ++static int rsos_choice_hdmi; ++ ++/* The policy's choice among the connectors: sets rsos_force_* and returns ++ * the connector id to open first (0 = none). */ ++static uint32_t rsos_policy_choose(int drm_fd, drmModeRes *resources, int probe) ++{ ++ struct pf_cfg cfg; ++ struct pf_conn conns[PF_MAX_CONNS]; ++ int idx[PF_MAX_CONNS]; ++ struct pf_choice ch; ++ int n = 0, i; ++ ++ SDL_memset(&cfg, 0, sizeof(cfg)); ++ cfg.hdmi_w = rsos_env_int("RSOS_HDMI_W", 1280); ++ cfg.hdmi_h = rsos_env_int("RSOS_HDMI_H", 720); ++ cfg.hdmi_hz = rsos_env_int("RSOS_HDMI_HZ", 60); ++ cfg.hdmi_builtin_mode = SDL_TRUE; ++ cfg.hdmi_crtc_index = rsos_env_int("RSOS_HDMI_CRTC", 1); ++ cfg.panel_keep_scanning = rsos_env_int("RSOS_PANEL_KEEP", 1) != 0; ++ cfg.crtc_count = resources->count_crtcs; ++ rsos_rw = rsos_env_int("RSOS_RENDER_W", 640); ++ rsos_rh = rsos_env_int("RSOS_RENDER_H", 480); ++ ++ for (i = 0; i < resources->count_connectors && n < PF_MAX_CONNS; i++) { ++ drmModeConnector *c = probe ? KMSDRM_drmModeGetConnector(drm_fd, resources->connectors[i]) ++ : KMSDRM_drmModeGetConnectorCurrent(drm_fd, resources->connectors[i]); ++ struct pf_conn *p = &conns[n]; ++ int m; ++ ++ if (!c) { ++ continue; ++ } ++ SDL_memset(p, 0, sizeof(*p)); ++ p->kind = (c->connector_type == DRM_MODE_CONNECTOR_HDMIA || ++ c->connector_type == DRM_MODE_CONNECTOR_HDMIB || ++ c->connector_type == DRM_MODE_CONNECTOR_DVID || ++ c->connector_type == DRM_MODE_CONNECTOR_DVII || ++ c->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ? PF_KIND_HDMI : PF_KIND_LCD; ++ p->connected = c->connection == DRM_MODE_CONNECTED && c->count_modes > 0; ++ p->has_edid = rsos_connector_has_edid(drm_fd, c); ++ p->possible_crtcs = rsos_possible_crtcs(drm_fd, resources, c); ++ for (m = 0; m < c->count_modes && p->nmodes < PF_MAX_MODES; m++) { ++ p->modes[p->nmodes].w = c->modes[m].hdisplay; ++ p->modes[p->nmodes].h = c->modes[m].vdisplay; ++ p->modes[p->nmodes].hz = (int)c->modes[m].vrefresh; ++ p->modes[p->nmodes].preferred = (c->modes[m].type & DRM_MODE_TYPE_PREFERRED) != 0; ++ p->nmodes++; ++ } ++ idx[n] = i; ++ n++; ++ KMSDRM_drmModeFreeConnector(c); ++ } ++ ++ ch = pf_choose(&cfg, conns, n); ++ for (i = 0; i < n; i++) { ++ SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "rsos: conn %d kind %d connected %d edid %d modes %d possible_crtcs %x", ++ i, (int)conns[i].kind, conns[i].connected, conns[i].has_edid, conns[i].nmodes, (unsigned)conns[i].possible_crtcs); ++ } ++ SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "rsos: policy conn %d crtc %d mode %dx%d@%d (crtcs %d)", ch.conn, ch.crtc, ch.w, ch.h, ch.hz, cfg.crtc_count); ++ if (ch.conn < 0 || ch.crtc < 0) { ++ return 0; ++ } ++ rsos_force_crtc_id = resources->crtcs[ch.crtc]; ++ rsos_crtc_index = ch.crtc; ++ rsos_scaled = 1; ++ rsos_force_w = ch.w; ++ rsos_force_h = ch.h; ++ rsos_force_hz = ch.hz; ++ rsos_force_conn_id = resources->connectors[idx[ch.conn]]; ++ rsos_choice_hdmi = conns[ch.conn].kind == PF_KIND_HDMI; ++ return rsos_force_conn_id; ++} ++ ++ ++/* The built-in panel's backlight (on = 0, off = 4): off behind HDMI, as the ++ * libretro host does. The panel itself keeps scanning a black frame. */ ++static void rsos_backlight(SDL_bool on) ++{ ++ DIR *d = opendir("/sys/class/backlight"); ++ struct dirent *de; ++ ++ if (!d) { ++ return; ++ } ++ while ((de = readdir(d)) != NULL) { ++ char path[256]; ++ int fd; ++ ++ if (de->d_name[0] == '.') { ++ continue; ++ } ++ SDL_snprintf(path, sizeof(path), "/sys/class/backlight/%s/bl_power", de->d_name); ++ fd = open(path, O_WRONLY | O_CLOEXEC); ++ if (fd >= 0) { ++ if (write(fd, on ? "0\n" : "4\n", 2) < 0) { ++ /* nothing to do */ ++ } ++ close(fd); ++ } ++ } ++ closedir(d); ++} ++ ++static SDL_bool rsos_is_external(uint32_t type) ++{ ++ return type == DRM_MODE_CONNECTOR_HDMIA || type == DRM_MODE_CONNECTOR_HDMIB || ++ type == DRM_MODE_CONNECTOR_DVID || type == DRM_MODE_CONNECTOR_DVII || ++ type == DRM_MODE_CONNECTOR_DisplayPort; ++} ++ ++/* Called now and then from SwapWindow: when the policy would choose another ++ * output (HDMI plugged in or unplugged), moves the game there. The game ++ * renders the same size all along, so it never notices. Returns 1 when the ++ * output changed (the caller shows the frame with rsos_scanout(first=1)). */ ++int rsos_check_output(SDL_VideoData *viddata, SDL_DisplayData *dispdata) ++{ ++ int fd = viddata->drm_fd; ++ drmModeRes *res = KMSDRM_drmModeGetResources(fd); ++ drmModeConnector *c; ++ drmModeCrtc *crtc; ++ uint32_t nc; ++ int i, found = -1, idx = -1; ++ ++ if (!res) { ++ return 0; ++ } ++ nc = rsos_policy_choose(fd, res, 0); ++ if (!nc || nc == dispdata->connector->connector_id) { ++ KMSDRM_drmModeFreeResources(res); ++ return 0; ++ } ++ c = KMSDRM_drmModeGetConnector(fd, nc); ++ crtc = KMSDRM_drmModeGetCrtc(fd, rsos_force_crtc_id); ++ if (!c || !crtc || c->count_modes <= 0) { ++ if (c) { ++ KMSDRM_drmModeFreeConnector(c); ++ } ++ if (crtc) { ++ KMSDRM_drmModeFreeCrtc(crtc); ++ } ++ KMSDRM_drmModeFreeResources(res); ++ return 0; ++ } ++ for (i = 0; i < c->count_modes; i++) { ++ if ((int)c->modes[i].hdisplay == rsos_force_w && (int)c->modes[i].vdisplay == rsos_force_h && ++ (int)c->modes[i].vrefresh == rsos_force_hz) { ++ found = i; ++ break; ++ } ++ } ++ for (i = 0; found < 0 && i < c->count_modes; i++) { ++ if (c->modes[i].type & DRM_MODE_TYPE_PREFERRED) { ++ found = i; ++ } ++ } ++ if (found < 0) { ++ found = 0; ++ } ++ for (i = 0; i < res->count_crtcs; i++) { ++ if (res->crtcs[i] == crtc->crtc_id) { ++ idx = i; ++ } ++ } ++ ++ SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "rsos: output change: conn %u -> %u crtc %u mode %dx%d", ++ dispdata->connector->connector_id, nc, crtc->crtc_id, ++ (int)c->modes[found].hdisplay, (int)c->modes[found].vdisplay); ++ ++ if (rsos_is_external(dispdata->connector->connector_type)) { ++ /* leaving HDMI: its CRTC off */ ++ KMSDRM_drmModeSetCrtc(fd, dispdata->crtc->crtc_id, 0, 0, 0, NULL, 0, NULL); ++ } else { ++ /* leaving the panel: it keeps scanning a black frame (never switched off) */ ++ uint32_t black = rsos_black_fb(fd, dispdata->mode.hdisplay, dispdata->mode.vdisplay); ++ uint32_t oc = dispdata->connector->connector_id; ++ ++ if (black) { ++ KMSDRM_drmModeSetCrtc(fd, dispdata->crtc->crtc_id, black, 0, 0, &oc, 1, &dispdata->mode); ++ } ++ } ++ rsos_backlight(rsos_is_external(c->connector_type) ? SDL_FALSE : SDL_TRUE); ++ rsos_audio_hdmi = rsos_is_external(c->connector_type) ? 1 : 0; /* the sound follows (SDL_alsa_audio.c) */ ++ ++ KMSDRM_drmModeFreeConnector(dispdata->connector); ++ KMSDRM_drmModeFreeCrtc(dispdata->crtc); ++ dispdata->connector = c; ++ dispdata->crtc = crtc; ++ dispdata->mode = c->modes[found]; ++ if (idx >= 0) { ++ rsos_crtc_index = idx; ++ } ++ KMSDRM_drmModeFreeResources(res); ++ return 1; ++} ++ + /* Gets a DRM connector, builds an SDL_Display with it, and adds it to the + list of SDL Displays in _this->displays[] */ + static void KMSDRM_AddDisplay(_THIS, drmModeConnector *connector, drmModeRes *resources) +@@ -790,6 +1047,11 @@ + goto cleanup; + } + ++ /* RetroStoneOS: the policy's CRTC for the chosen connector */ ++ if (rsos_force_crtc_id && connector->connector_id == rsos_force_conn_id) { ++ encoder->crtc_id = rsos_force_crtc_id; ++ } ++ + /* Try to find a CRTC connected to this encoder */ + crtc = KMSDRM_drmModeGetCrtc(viddata->drm_fd, encoder->crtc_id); + +@@ -845,6 +1107,29 @@ + } + } + ++ /* RetroStoneOS: the policy's mode (1280x720@60 on HDMI by default) */ ++ if (rsos_force_crtc_id && connector->connector_id == rsos_force_conn_id) { ++ for (i = 0; i < connector->count_modes; i++) { ++ drmModeModeInfo *mode = &connector->modes[i]; ++ ++ if ((int)mode->hdisplay == rsos_force_w && (int)mode->vdisplay == rsos_force_h && ++ (int)mode->vrefresh == rsos_force_hz) { ++ mode_index = i; ++ crtc->mode = connector->modes[i]; ++ break; ++ } ++ } ++ if (mode_index >= 0) { ++ /* One output, one mode, as the libretro host runs it: SDL offers ++ only the policy mode, whatever size the game asks for. */ ++ connector->modes[0] = connector->modes[mode_index]; ++ connector->count_modes = 1; ++ mode_index = 0; ++ crtc->mode = connector->modes[0]; ++ } ++ } ++ ++ SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "rsos: AddDisplay conn %u forced=%d mode_index %d crtc %u", connector->connector_id, (int)(rsos_force_crtc_id && connector->connector_id == rsos_force_conn_id), mode_index, crtc ? crtc->crtc_id : 0); + if (mode_index == -1) { + ret = SDL_SetError("Failed to find index of mode attached to the CRTC."); + goto cleanup; +@@ -898,8 +1183,8 @@ + modedata->mode_index = mode_index; + + display.driverdata = dispdata; +- display.desktop_mode.w = dispdata->mode.hdisplay; +- display.desktop_mode.h = dispdata->mode.vdisplay; ++ display.desktop_mode.w = rsos_scaled ? rsos_rw : dispdata->mode.hdisplay; ++ display.desktop_mode.h = rsos_scaled ? rsos_rh : dispdata->mode.vdisplay; + display.desktop_mode.refresh_rate = dispdata->mode.vrefresh; + display.desktop_mode.format = SDL_PIXELFORMAT_ARGB8888; + display.desktop_mode.driverdata = modedata; +@@ -963,6 +1248,21 @@ + goto cleanup; + } + ++ /* RetroStoneOS: the output policy's connector becomes display 0 */ ++ rsos_force_crtc_id = 0; ++ rsos_scaled = 0; ++ if (rsos_policy_choose(viddata->drm_fd, resources, 1)) { ++ drmModeConnector *connector = KMSDRM_drmModeGetConnector(viddata->drm_fd, rsos_force_conn_id); ++ ++ rsos_audio_hdmi = rsos_choice_hdmi; ++ ++ if (connector && connector->connection == DRM_MODE_CONNECTED && connector->count_modes) { ++ KMSDRM_AddDisplay(_this, connector, resources); ++ } else if (connector) { ++ KMSDRM_drmModeFreeConnector(connector); ++ } ++ } ++ + /* Iterate on the available connectors. For every connected connector, + we create an SDL_Display and add it to the list of SDL Displays. */ + for (i = 0; i < resources->count_connectors; i++) { +@@ -972,6 +1272,13 @@ + if (!connector) { + continue; + } ++ /* One output at a time, as the libretro host does: once the output ++ chosen by the policy is open, no other display exists, so a window ++ cannot land on the other screen whatever its position. */ ++ if (rsos_force_crtc_id && SDL_GetNumVideoDisplays() > 0) { ++ KMSDRM_drmModeFreeConnector(connector); ++ continue; ++ } + + if (connector->connection == DRM_MODE_CONNECTED && connector->count_modes) { + /* If it's a connected connector with available videomodes, try to add +@@ -1181,7 +1488,8 @@ + or SetWindowFullscreen, send a fake event for now since the actual + recreation is deferred */ + KMSDRM_GetModeToSet(window, &mode); +- SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESIZED, mode.hdisplay, mode.vdisplay); ++ SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESIZED, rsos_scaled ? rsos_rw : mode.hdisplay, ++ rsos_scaled ? rsos_rh : mode.vdisplay); + } + + /* This determines the size of the fb, which comes from the GBM surface +@@ -1193,7 +1501,9 @@ + SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); + SDL_DisplayData *dispdata = (SDL_DisplayData *)display->driverdata; + +- uint32_t surface_fmt = GBM_FORMAT_ARGB8888; ++ /* RetroStoneOS: the scaled plane takes XRGB8888 (as the libretro host does); ++ the sun4i scaler refuses the alpha format */ ++ uint32_t surface_fmt = rsos_scaled ? GBM_FORMAT_XRGB8888 : GBM_FORMAT_ARGB8888; + uint32_t surface_flags = GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING; + + EGLContext egl_context; +@@ -1216,13 +1526,14 @@ + mode that's set in sync with what SDL_video.c thinks is set */ + KMSDRM_GetModeToSet(window, &dispdata->mode); + +- display->current_mode.w = dispdata->mode.hdisplay; +- display->current_mode.h = dispdata->mode.vdisplay; ++ display->current_mode.w = rsos_scaled ? rsos_rw : dispdata->mode.hdisplay; ++ display->current_mode.h = rsos_scaled ? rsos_rh : dispdata->mode.vdisplay; + display->current_mode.refresh_rate = dispdata->mode.vrefresh; + display->current_mode.format = SDL_PIXELFORMAT_ARGB8888; + + windata->gs = KMSDRM_gbm_surface_create(viddata->gbm_dev, +- dispdata->mode.hdisplay, dispdata->mode.vdisplay, ++ rsos_scaled ? rsos_rw : dispdata->mode.hdisplay, ++ rsos_scaled ? rsos_rh : dispdata->mode.vdisplay, + surface_fmt, surface_flags); + + if (!windata->gs) { +@@ -1246,7 +1557,8 @@ + ret = SDL_EGL_MakeCurrent(_this, windata->egl_surface, egl_context); + + SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESIZED, +- dispdata->mode.hdisplay, dispdata->mode.vdisplay); ++ rsos_scaled ? rsos_rw : dispdata->mode.hdisplay, ++ rsos_scaled ? rsos_rh : dispdata->mode.vdisplay); + + windata->egl_surface_dirty = SDL_FALSE; + +@@ -1363,8 +1675,8 @@ + modedata->mode_index = i; + } + +- mode.w = conn->modes[i].hdisplay; +- mode.h = conn->modes[i].vdisplay; ++ mode.w = rsos_scaled ? rsos_rw : conn->modes[i].hdisplay; ++ mode.h = rsos_scaled ? rsos_rh : conn->modes[i].vdisplay; + mode.refresh_rate = conn->modes[i].vrefresh; + mode.format = SDL_PIXELFORMAT_ARGB8888; + mode.driverdata = modedata; +--- a/src/video/kmsdrm/SDL_kmsdrmvideo.h ++++ b/src/video/kmsdrm/SDL_kmsdrmvideo.h +@@ -123,6 +123,7 @@ + + typedef struct SDL_WindowData + { ++ int rsos_poll; /* frames since the last output check */ + SDL_VideoData *viddata; + /* SDL internals expect EGL surface to be here, and in KMSDRM the GBM surface is + what supports the EGL surface on the driver side, so all these surfaces and buffers +@@ -192,6 +193,14 @@ + int KMSDRM_GLES_SwapWindow(_THIS, SDL_Window *window); + void KMSDRM_GLES_DeleteContext(_THIS, SDL_GLContext context); + ++ ++/* RetroStoneOS scaled scan-out (rsos_scanout.c) */ ++extern volatile int rsos_audio_hdmi; ++extern int rsos_scaled, rsos_rw, rsos_rh, rsos_crtc_index; ++int rsos_scanout(SDL_VideoData *viddata, SDL_DisplayData *dispdata, uint32_t fb_id, int first); ++uint32_t rsos_black_fb(int fd, int w, int h); ++int rsos_check_output(SDL_VideoData *viddata, SDL_DisplayData *dispdata); ++ + #endif /* __SDL_KMSDRMVIDEO_H__ */ + + /* vi: set ts=4 sw=4 expandtab: */ +--- a/src/video/kmsdrm/SDL_kmsdrmopengles.c ++++ b/src/video/kmsdrm/SDL_kmsdrmopengles.c +@@ -149,13 +149,27 @@ + return 0; + } + ++ if (windata->bo && rsos_scaled && ++windata->rsos_poll >= 15) { ++ /* about four times a second: HDMI plugged in or out? */ ++ windata->rsos_poll = 0; ++ if (rsos_check_output(viddata, dispdata)) { ++ ret = rsos_scanout(viddata, dispdata, fb_info->fb_id, 1); ++ return ret == 0 ? 1 : 0; ++ } ++ } ++ + if (!windata->bo) { + /* On the first swap, immediately present the new front buffer. Before + drmModePageFlip can be used the CRTC has to be configured to use + the current connector and mode with drmModeSetCrtc */ +- ret = KMSDRM_drmModeSetCrtc(viddata->drm_fd, +- dispdata->crtc->crtc_id, fb_info->fb_id, 0, 0, +- &dispdata->connector->connector_id, 1, &dispdata->mode); ++ SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "rsos: first SetCrtc crtc %u conn %u mode %dx%d@%d", dispdata->crtc->crtc_id, dispdata->connector->connector_id, (int)dispdata->mode.hdisplay, (int)dispdata->mode.vdisplay, (int)dispdata->mode.vrefresh); ++ if (rsos_scaled) { ++ ret = rsos_scanout(viddata, dispdata, fb_info->fb_id, 1); ++ } else { ++ ret = KMSDRM_drmModeSetCrtc(viddata->drm_fd, ++ dispdata->crtc->crtc_id, fb_info->fb_id, 0, 0, ++ &dispdata->connector->connector_id, 1, &dispdata->mode); ++ } + + if (ret) { + SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "Could not set videomode on CRTC."); +@@ -178,6 +192,9 @@ + flip_flags |= DRM_MODE_PAGE_FLIP_ASYNC; + } + ++ /* RetroStoneOS: with the scaled plane the usual page flip is kept (it only ++ changes the framebuffer: the plane keeps its scaling), so the game does not ++ wait for the vblank inside the swap, as before. */ + ret = KMSDRM_drmModePageFlip(viddata->drm_fd, dispdata->crtc->crtc_id, + fb_info->fb_id, flip_flags, &windata->waiting_for_flip); + +--- a/src/video/kmsdrm/SDL_kmsdrmsym.h ++++ b/src/video/kmsdrm/SDL_kmsdrmsym.h +@@ -80,6 +80,7 @@ + int32_t hot_x, int32_t hot_y)) + SDL_KMSDRM_SYM(int,drmModeMoveCursor,(int fd, uint32_t crtcId, int x, int y)) + SDL_KMSDRM_SYM(drmModeEncoderPtr,drmModeGetEncoder,(int fd, uint32_t encoder_id)) ++SDL_KMSDRM_SYM(drmModeConnectorPtr,drmModeGetConnectorCurrent,(int fd, uint32_t connector_id)) + SDL_KMSDRM_SYM(drmModeConnectorPtr,drmModeGetConnector,(int fd, uint32_t connector_id)) + SDL_KMSDRM_SYM(int,drmHandleEvent,(int fd,drmEventContextPtr evctx)) + SDL_KMSDRM_SYM(int,drmModePageFlip,(int fd, uint32_t crtc_id, uint32_t fb_id, +--- a/src/video/kmsdrm/rsos_scanout.c ++++ b/src/video/kmsdrm/rsos_scanout.c +@@ -0,0 +1,168 @@ ++/* ++ * rsos_scanout.c - RetroStoneOS: scaled scan-out for SDL's KMSDRM driver. ++ * ++ * The game renders into a fixed-size GBM surface (rsos_rw x rsos_rh, the ++ * built-in panel's size by default). The surface is shown on the CRTC's ++ * primary plane, scaled by the display engine to the active output (the ++ * panel 1:1, an HDMI monitor aspect-fit with black bars), as the libretro ++ * host does (display.c, "XR24 640x480 scaled to 1440x1080+240+0"). The game ++ * never sees a resolution change. ++ */ ++#include "../../SDL_internal.h" ++ ++#ifdef SDL_VIDEO_DRIVER_KMSDRM ++ ++#include "SDL_kmsdrmvideo.h" ++#include "SDL_kmsdrmdyn.h" ++ ++#include ++#include ++#include ++ ++/* 1 while the game is on an external screen (HDMI), 0 on the built-in one, -1 unknown: ++ * SDL's ALSA backend plays on the HDMI sound card or the speaker accordingly */ ++volatile int rsos_audio_hdmi = -1; ++int rsos_scaled; /* the policy chose the output: scaled scan-out */ ++int rsos_rw = 640, rsos_rh = 480; /* the size the game renders at */ ++int rsos_crtc_index; ++ ++static uint32_t plane_id; ++static struct { int w, h; uint32_t fb; } blacks[4]; ++static int dst_x, dst_y, dst_w, dst_h; ++ ++#define RSOS_UNIVERSAL_PLANES 2 ++#define RSOS_PLANE_PRIMARY 1 ++ ++static uint32_t find_primary_plane(int fd, int crtc_index) ++{ ++ drmModePlaneRes *pr; ++ uint32_t found = 0; ++ uint32_t i; ++ ++ KMSDRM_drmSetClientCap(fd, RSOS_UNIVERSAL_PLANES, 1); ++ pr = KMSDRM_drmModeGetPlaneResources(fd); ++ if (!pr) { ++ return 0; ++ } ++ for (i = 0; i < pr->count_planes && !found; i++) { ++ drmModePlane *p = KMSDRM_drmModeGetPlane(fd, pr->planes[i]); ++ drmModeObjectProperties *props; ++ uint32_t j; ++ ++ if (!p) { ++ continue; ++ } ++ if (p->possible_crtcs & (1u << crtc_index)) { ++ props = KMSDRM_drmModeObjectGetProperties(fd, p->plane_id, DRM_MODE_OBJECT_PLANE); ++ for (j = 0; props && j < props->count_props; j++) { ++ drmModePropertyPtr prop = KMSDRM_drmModeGetProperty(fd, props->props[j]); ++ ++ if (prop) { ++ if (SDL_strcmp(prop->name, "type") == 0 && props->prop_values[j] == RSOS_PLANE_PRIMARY) { ++ found = p->plane_id; ++ } ++ KMSDRM_drmModeFreeProperty(prop); ++ } ++ } ++ if (props) { ++ KMSDRM_drmModeFreeObjectProperties(props); ++ } ++ } ++ KMSDRM_drmModeFreePlane(p); ++ } ++ KMSDRM_drmModeFreePlaneResources(pr); ++ return found; ++} ++ ++/* A mode-sized black framebuffer: SetCrtc needs one at least as big as the ++ * mode, and it is what shows around the scaled picture. */ ++static int make_black_fb(int fd, int w, int h, uint32_t *out) ++{ ++ struct drm_mode_create_dumb c; ++ uint32_t fb = 0; ++ ++ SDL_memset(&c, 0, sizeof(c)); ++ c.width = (uint32_t)w; ++ c.height = (uint32_t)h; ++ c.bpp = 32; ++ if (ioctl(fd, DRM_IOCTL_MODE_CREATE_DUMB, &c) < 0) { ++ return -errno; ++ } ++ if (KMSDRM_drmModeAddFB(fd, (uint32_t)w, (uint32_t)h, 24, 32, c.pitch, c.handle, &fb) != 0) { ++ return -EINVAL; ++ } ++ *out = fb; ++ return 0; ++} ++ ++/* The black framebuffer for a mode size (made once per size). */ ++uint32_t rsos_black_fb(int fd, int w, int h) ++{ ++ int i; ++ ++ for (i = 0; i < 4; i++) { ++ if (blacks[i].fb && blacks[i].w == w && blacks[i].h == h) { ++ return blacks[i].fb; ++ } ++ } ++ for (i = 0; i < 4; i++) { ++ if (!blacks[i].fb) { ++ if (make_black_fb(fd, w, h, &blacks[i].fb) != 0) { ++ return 0; ++ } ++ blacks[i].w = w; ++ blacks[i].h = h; ++ return blacks[i].fb; ++ } ++ } ++ return 0; ++} ++ ++static void fit_rect(int mw, int mh) ++{ ++ if ((long)mw * rsos_rh >= (long)mh * rsos_rw) { /* height-limited */ ++ dst_h = mh; ++ dst_w = (int)((long)mh * rsos_rw / rsos_rh); ++ } else { ++ dst_w = mw; ++ dst_h = (int)((long)mw * rsos_rh / rsos_rw); ++ } ++ dst_x = (mw - dst_w) / 2; ++ dst_y = (mh - dst_h) / 2; ++} ++ ++/* Shows fb_id (the game's frame) on the display's CRTC. first = 1 sets the ++ * mode (the first swap, or a new output); then every frame is one plane ++ * update, which the kernel completes at the next vblank. */ ++int rsos_scanout(SDL_VideoData *viddata, SDL_DisplayData *dispdata, uint32_t fb_id, int first) ++{ ++ int fd = viddata->drm_fd; ++ uint32_t conn = dispdata->connector->connector_id; ++ uint32_t black; ++ int ret; ++ ++ if (first) { ++ plane_id = find_primary_plane(fd, rsos_crtc_index); ++ if (!plane_id) { ++ SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "rsos: no primary plane for CRTC %d", rsos_crtc_index); ++ return -ENODEV; ++ } ++ black = rsos_black_fb(fd, dispdata->mode.hdisplay, dispdata->mode.vdisplay); ++ if (!black) { ++ return -ENOMEM; ++ } ++ ret = KMSDRM_drmModeSetCrtc(fd, dispdata->crtc->crtc_id, black, 0, 0, &conn, 1, &dispdata->mode); ++ if (ret) { ++ return ret; ++ } ++ fit_rect(dispdata->mode.hdisplay, dispdata->mode.vdisplay); ++ SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "rsos: plane %u shows %dx%d scaled to %dx%d+%d+%d on %dx%d", ++ plane_id, rsos_rw, rsos_rh, dst_w, dst_h, dst_x, dst_y, ++ (int)dispdata->mode.hdisplay, (int)dispdata->mode.vdisplay); ++ } ++ return KMSDRM_drmModeSetPlane(fd, plane_id, dispdata->crtc->crtc_id, fb_id, 0, ++ dst_x, dst_y, (uint32_t)dst_w, (uint32_t)dst_h, ++ 0, 0, (uint32_t)rsos_rw << 16, (uint32_t)rsos_rh << 16); ++} ++ ++#endif /* SDL_VIDEO_DRIVER_KMSDRM */ +--- a/src/video/kmsdrm/policy.c ++++ b/src/video/kmsdrm/policy.c +@@ -0,0 +1,117 @@ ++/* ++ * policy.c - output decision, see policy.h. Same rules as display.c: ++ * - HDMI when it is connected and has a usable mode, else the built-in panel; ++ * - HDMI mode: the configured size and refresh, else the preferred one, ++ * else the first; with no EDID the CEA 720p60 timing (builtin); ++ * - panel_keep_scanning: the panel keeps CRTC 0 (the first LCD's CRTC), ++ * HDMI takes hdmi_crtc_index (or the lowest free one), never the panel's. ++ */ ++#include ++ ++#include "policy.h" ++ ++static const struct pf_mode cea_720p60 = { 1280, 720, 60, false }; ++ ++static const struct pf_mode *find_mode(const struct pf_conn *c, int w, int h, int hz) ++{ ++ for (int i = 0; i < c->nmodes; i++) ++ if (c->modes[i].w == w && c->modes[i].h == h && c->modes[i].hz == hz) ++ return &c->modes[i]; ++ for (int i = 0; i < c->nmodes; i++) ++ if (c->modes[i].w == w && c->modes[i].h == h) ++ return &c->modes[i]; ++ return NULL; ++} ++ ++bool pf_pick_mode(const struct pf_cfg *cfg, const struct pf_conn *c, struct pf_mode *out, bool *builtin) ++{ ++ const struct pf_mode *m = NULL; ++ ++ *builtin = false; ++ if (c->kind == PF_KIND_HDMI) { ++ if ((!c->has_edid || c->nmodes == 0) && cfg->hdmi_builtin_mode) { ++ *out = cea_720p60; ++ *builtin = true; ++ return true; ++ } ++ if (cfg->hdmi_w > 0 && cfg->hdmi_h > 0) ++ m = find_mode(c, cfg->hdmi_w, cfg->hdmi_h, cfg->hdmi_hz > 0 ? cfg->hdmi_hz : 60); ++ } ++ for (int i = 0; !m && i < c->nmodes; i++) ++ if (c->modes[i].preferred) ++ m = &c->modes[i]; ++ if (!m && c->nmodes > 0) ++ m = &c->modes[0]; ++ if (!m) ++ return false; ++ *out = *m; ++ return true; ++} ++ ++static bool crtc_ok(const struct pf_conn *c, const struct pf_cfg *cfg, int i) ++{ ++ return i >= 0 && i < cfg->crtc_count && (c->possible_crtcs & (1u << i)); ++} ++ ++/* First CRTC that conn can use, lowest index first. */ ++static int first_crtc(const struct pf_conn *c, const struct pf_cfg *cfg, int avoid) ++{ ++ for (int i = 0; i < cfg->crtc_count; i++) ++ if (i != avoid && crtc_ok(c, cfg, i)) ++ return i; ++ return -1; ++} ++ ++struct pf_choice pf_choose(const struct pf_cfg *cfg, const struct pf_conn *conns, int nconns) ++{ ++ struct pf_choice ch = { .conn = -1, .crtc = -1 }; ++ int lcd = -1, hdmi = -1, panel_crtc = -1; ++ struct pf_mode m; ++ bool builtin; ++ ++ for (int i = 0; i < nconns && i < PF_MAX_CONNS; i++) { ++ if (!conns[i].connected) ++ continue; ++ if (conns[i].kind == PF_KIND_LCD && lcd < 0) ++ lcd = i; ++ if (conns[i].kind == PF_KIND_HDMI && hdmi < 0) ++ hdmi = i; ++ } ++ if (lcd >= 0) { ++ /* the panel's CRTC: the lowest one it can use */ ++ panel_crtc = first_crtc(&conns[lcd], cfg, -1); ++ } ++ ++ /* HDMI wins when it can show a picture, else the panel */ ++ if (hdmi >= 0 && pf_pick_mode(cfg, &conns[hdmi], &m, &builtin)) { ++ int crtc; ++ ++ if (cfg->panel_keep_scanning && lcd >= 0) { ++ /* HDMI never on the panel's CRTC */ ++ crtc = crtc_ok(&conns[hdmi], cfg, cfg->hdmi_crtc_index) && ++ cfg->hdmi_crtc_index != panel_crtc ? cfg->hdmi_crtc_index ++ : first_crtc(&conns[hdmi], cfg, panel_crtc); ++ } else { ++ crtc = crtc_ok(&conns[hdmi], cfg, cfg->hdmi_crtc_index) ? cfg->hdmi_crtc_index ++ : first_crtc(&conns[hdmi], cfg, -1); ++ } ++ if (crtc >= 0) { ++ ch.conn = hdmi; ++ ch.crtc = crtc; ++ ch.w = m.w; ++ ch.h = m.h; ++ ch.hz = m.hz; ++ ch.builtin = builtin; ++ return ch; ++ } ++ } ++ if (lcd >= 0 && pf_pick_mode(cfg, &conns[lcd], &m, &builtin) && panel_crtc >= 0) { ++ ch.conn = lcd; ++ ch.crtc = panel_crtc; ++ ch.w = m.w; ++ ch.h = m.h; ++ ch.hz = m.hz; ++ ch.builtin = builtin; ++ } ++ return ch; ++} +--- a/src/video/kmsdrm/policy.h ++++ b/src/video/kmsdrm/policy.h +@@ -0,0 +1,54 @@ ++/* ++ * policy.h - which output (built-in panel or HDMI), which CRTC and which ++ * mode a RetroStoneOS process uses. Pure logic: no DRM, no I/O. It mirrors ++ * pick_mode() and choose_crtc() in frontend/src/display.c, so the libretro ++ * host and the native ports (SDL2 patch, ports/) take the same decision. ++ */ ++#ifndef RSOS_FOLLOW_POLICY_H ++#define RSOS_FOLLOW_POLICY_H ++ ++#include ++#include ++ ++#define PF_MAX_MODES 64 ++#define PF_MAX_CONNS 8 ++ ++enum pf_kind { PF_KIND_LCD = 0, PF_KIND_HDMI = 1 }; ++ ++struct pf_mode { ++ int w, h, hz; ++ bool preferred; ++}; ++ ++struct pf_conn { ++ enum pf_kind kind; ++ bool connected; ++ bool has_edid; ++ uint32_t possible_crtcs; /* bit i = CRTC i can drive this connector */ ++ int nmodes; ++ struct pf_mode modes[PF_MAX_MODES]; ++}; ++ ++struct pf_cfg { ++ int hdmi_w, hdmi_h, hdmi_hz; /* policy mode, default 1280x720@60 */ ++ bool hdmi_builtin_mode; /* no EDID: use CEA 720p60 */ ++ int hdmi_crtc_index; /* preferred CRTC for HDMI (default 1) */ ++ bool panel_keep_scanning; /* the panel keeps its CRTC for good */ ++ int crtc_count; ++}; ++ ++struct pf_choice { ++ int conn; /* index into conns, -1 = none usable */ ++ int crtc; /* -1 = none */ ++ int w, h, hz; ++ bool builtin; /* the CEA timing, not an EDID mode */ ++}; ++ ++/* Decide the output. want_hdmi = the user's choice when HDMI is connected ++ * (always true in the default policy: HDMI when plugged in). */ ++struct pf_choice pf_choose(const struct pf_cfg *cfg, const struct pf_conn *conns, int nconns); ++ ++/* The mode pf_choose() would give one connector (no CRTC check). */ ++bool pf_pick_mode(const struct pf_cfg *cfg, const struct pf_conn *c, struct pf_mode *out, bool *builtin); ++ ++#endif +--- a/src/audio/alsa/SDL_alsa_audio.c ++++ b/src/audio/alsa/SDL_alsa_audio.c +@@ -368,12 +368,66 @@ + } + #endif /* SND_CHMAP_API_VERSION */ + ++ ++/* RetroStoneOS: the sound follows the picture. The KMSDRM video driver says whether the game is on HDMI ++ (rsos_audio_hdmi, rsos_scanout.c); then the HDMI sound card plays, else the usual device. A device the ++ game or the user chose (AUDIODEV, a named device) is left alone. */ ++static int ALSA_configure_pcm(_THIS, snd_pcm_t *pcm_handle); ++extern volatile int rsos_audio_hdmi __attribute__((weak)); ++ ++static const char *rsos_hdmi_device(void) ++{ ++ const char *d = SDL_getenv("RSOS_AUDIO_HDMI_DEV"); ++ ++ return d && *d ? d : "plughw:CARD=sun4ihdmi,DEV=0"; ++} ++ ++static int rsos_route_hdmi(_THIS) ++{ ++ if (this->iscapture || this->handle || SDL_getenv("AUDIODEV") || !&rsos_audio_hdmi) { ++ return 0; ++ } ++ return rsos_audio_hdmi > 0; ++} ++ ++/* Plays on another sound card from now on: the new pcm is set up as the first one was. */ ++static void rsos_alsa_reopen(_THIS, const char *device) ++{ ++ SDL_AudioSpec keep = this->spec; ++ snd_pcm_t *old = this->hidden->pcm_handle, *pcm = NULL; ++ void (*swizzle)(_THIS, void *, Uint32) = this->hidden->swizzle_func; ++ ++ if (ALSA_snd_pcm_open(&pcm, device, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK) < 0) { ++ return; ++ } ++ this->hidden->pcm_handle = pcm; ++ if (ALSA_configure_pcm(this, pcm) < 0) { ++ this->hidden->pcm_handle = old; ++ this->hidden->swizzle_func = swizzle; ++ this->spec = keep; ++ ALSA_snd_pcm_close(pcm); ++ return; ++ } ++ this->spec = keep; /* the game's buffers stay as they are: writei takes any size */ ++#if !SDL_ALSA_NON_BLOCKING ++ ALSA_snd_pcm_nonblock(pcm, 0); ++#endif ++ ALSA_snd_pcm_close(old); ++ SDL_LogDebug(SDL_LOG_CATEGORY_AUDIO, "rsos: the sound moved to %s", device); ++} ++ + static void ALSA_PlayDevice(_THIS) + { + const Uint8 *sample_buf = (const Uint8 *)this->hidden->mixbuf; + const int frame_size = ((SDL_AUDIO_BITSIZE(this->spec.format)) / 8) * + this->spec.channels; + snd_pcm_uframes_t frames_left = ((snd_pcm_uframes_t)this->spec.samples); ++ int rsos_route = rsos_route_hdmi(this); ++ ++ if (rsos_route != this->hidden->rsos_route) { ++ this->hidden->rsos_route = rsos_route; ++ rsos_alsa_reopen(this, rsos_route ? rsos_hdmi_device() : get_audio_device(this->handle, this->spec.channels)); ++ } + + this->hidden->swizzle_func(this, this->hidden->mixbuf, frames_left); + +@@ -585,11 +639,11 @@ + return 0; + } + +-static int ALSA_OpenDevice(_THIS, const char *devname) ++/* RetroStoneOS: the configuration of an open pcm, from ALSA_OpenDevice (also used to move ++ the sound to another card). */ ++static int ALSA_configure_pcm(_THIS, snd_pcm_t *pcm_handle) + { + int status = 0; +- SDL_bool iscapture = this->iscapture; +- snd_pcm_t *pcm_handle = NULL; + snd_pcm_hw_params_t *hwparams = NULL; + snd_pcm_sw_params_t *swparams = NULL; + snd_pcm_format_t format = 0; +@@ -601,26 +655,6 @@ + char chmap_str[64]; + #endif + +- /* Initialize all variables that we clean on shutdown */ +- this->hidden = (struct SDL_PrivateAudioData *)SDL_malloc(sizeof(*this->hidden)); +- if (!this->hidden) { +- return SDL_OutOfMemory(); +- } +- SDL_zerop(this->hidden); +- +- /* Open the audio device */ +- /* Name of device should depend on # channels in spec */ +- status = ALSA_snd_pcm_open(&pcm_handle, +- get_audio_device(this->handle, this->spec.channels), +- iscapture ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK, +- SND_PCM_NONBLOCK); +- +- if (status < 0) { +- return SDL_SetError("ALSA: Couldn't open audio device: %s", ALSA_snd_strerror(status)); +- } +- +- this->hidden->pcm_handle = pcm_handle; +- + /* Figure out what the hardware is capable of */ + snd_pcm_hw_params_alloca(&hwparams); + status = ALSA_snd_pcm_hw_params_any(pcm_handle, hwparams); +@@ -744,6 +778,40 @@ + return SDL_SetError("Couldn't set software audio parameters: %s", ALSA_snd_strerror(status)); + } + ++ return 0; ++} ++ ++static int ALSA_OpenDevice(_THIS, const char *devname) ++{ ++ int status = 0; ++ SDL_bool iscapture = this->iscapture; ++ snd_pcm_t *pcm_handle = NULL; ++ ++ /* Initialize all variables that we clean on shutdown */ ++ this->hidden = (struct SDL_PrivateAudioData *)SDL_malloc(sizeof(*this->hidden)); ++ if (!this->hidden) { ++ return SDL_OutOfMemory(); ++ } ++ SDL_zerop(this->hidden); ++ ++ /* Open the audio device */ ++ /* Name of device should depend on # channels in spec */ ++ this->hidden->rsos_route = rsos_route_hdmi(this); ++ status = ALSA_snd_pcm_open(&pcm_handle, ++ this->hidden->rsos_route ? rsos_hdmi_device() : get_audio_device(this->handle, this->spec.channels), ++ iscapture ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK, ++ SND_PCM_NONBLOCK); ++ ++ if (status < 0) { ++ return SDL_SetError("ALSA: Couldn't open audio device: %s", ALSA_snd_strerror(status)); ++ } ++ ++ this->hidden->pcm_handle = pcm_handle; ++ ++ if (ALSA_configure_pcm(this, pcm_handle) < 0) { ++ return -1; ++ } ++ + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(&this->spec); + +--- a/src/audio/alsa/SDL_alsa_audio.h ++++ b/src/audio/alsa/SDL_alsa_audio.h +@@ -39,6 +39,9 @@ + Uint8 *mixbuf; + int mixlen; + ++ /* RetroStoneOS: 1 while the sound is on the HDMI card */ ++ int rsos_route; ++ + /* swizzle function */ + void (*swizzle_func)(_THIS, void *buffer, Uint32 bufferlen); + }; diff --git a/buildroot-external/board/retrostone2/patches/sdl2/README.md b/buildroot-external/board/retrostone2/patches/sdl2/README.md new file mode 100644 index 0000000..33bc00c --- /dev/null +++ b/buildroot-external/board/retrostone2/patches/sdl2/README.md @@ -0,0 +1,13 @@ +# SDL2 patch (RetroStone2) + +`0001-kmsdrm-output-policy.patch` changes SDL 2.32.10's KMS/DRM video driver (`src/video/kmsdrm`) for the native +Ports: it opens only the output RetroStoneOS would use (HDMI when plugged in, else the built-in panel), renders +at a fixed size and scales it in the display engine, and follows HDMI being plugged or unplugged, the sound +included (the ALSA backend plays on the HDMI sound card or the speaker). See +`docs/display-design.md`, section 9b. + +SDL is Copyright (C) 1997-2025 Sam Lantinga and is under the **zlib license**. This patch alters that source and +is marked as such; the changed files (`SDL_kmsdrmvideo.c`, `SDL_kmsdrmvideo.h`, `SDL_kmsdrmopengles.c`, +`SDL_kmsdrmsym.h`, and the ALSA backend `SDL_alsa_audio.c` and `.h`) and the files it adds (`rsos_scanout.c`, `policy.c`, `policy.h`) carry RetroStoneOS comments. +The patched library is the one in the image, so the legal-info archive of a build has the SDL2 license text and +this patch. Buildroot applies every `*.patch` of this folder to the `sdl2` package. diff --git a/buildroot-external/board/retrostone2/post-build.sh b/buildroot-external/board/retrostone2/post-build.sh index 7945035..b9ae0ed 100755 --- a/buildroot-external/board/retrostone2/post-build.sh +++ b/buildroot-external/board/retrostone2/post-build.sh @@ -49,6 +49,10 @@ mkdir -p "$TARGET/usr/libexec/rsos" # (Settings > Power > Memory speed; rsos-boot-ok, tools/rsos-memtest.c). "$CC" -O2 -s -Wall -Wextra -Werror -o "$TARGET/usr/libexec/rsos/memtest" \ "$BOARD_DIR/tools/rsos-memtest.c" +# /usr/bin/rsos-gamepad: the built-in controls as one standard gamepad for +# native games that read SDL game controllers (docs/native-games.md, +# tools/rsos-gamepad.c; needs CONFIG_INPUT_UINPUT) +"$CC" -O2 -s -Wall -Wextra -Werror -o "$TARGET/usr/bin/rsos-gamepad" "$BOARD_DIR/tools/rsos-gamepad.c" # --- The boot loader, for "Install to internal storage" on the Pro # (rsos-storage install writes it at 8 KiB on the eMMC): the image's own diff --git a/buildroot-external/board/retrostone2/tools/rsos-gamepad.c b/buildroot-external/board/retrostone2/tools/rsos-gamepad.c new file mode 100644 index 0000000..e7e98ba --- /dev/null +++ b/buildroot-external/board/retrostone2/tools/rsos-gamepad.c @@ -0,0 +1,272 @@ +/* + * rsos-gamepad - the RetroStone2's built-in controls as one standard gamepad + * (uinput), for native games that read SDL game controllers (docs/native-games.md). + * + * The controls are three evdev devices: "RetroStone2 Buttons" (face, D-pad, + * Start/Select, optional C/Z), "RetroStone2 Shoulder Buttons" and the optional + * analog stick ("analog-stick", which SDL does not even take for a joystick). + * This reads them (no grab: the menu reads them too, for Select+Start) and + * writes "RetroStoneOS Gamepad": the Linux gamepad layout by position (bottom + * = BTN_SOUTH), C/Z as the stick clicks, the D-pad as hat 0, the stick as + * ABS_X/ABS_Y. The launch script starts it in the game's process group, so + * the menu stops it with the game, and gives SDL its mapping: + * + * SDL_GAMECONTROLLERCONFIG= RSOS_GAMEPAD_SDL_MAPPING below + * SDL_GAMECONTROLLER_IGNORE_DEVICES=0x0001/0x0001 (the raw gpio-keys) + * + * rsos-gamepad [--print-mapping] + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define NAME "RetroStoneOS Gamepad" +#define VENDOR 0x1209 /* pid.codes test vendor: no real device to clash with */ +#define PRODUCT 0x5253 /* "RS" */ +#define VERSION 0x0001 +/* SDL's GUID for it with the name CRC left 0 (matches any name): bus + * BUS_VIRTUAL (0x06), vendor, product, version, little-endian 16-bit words; + * buttons numbered in key code order (BTN_SOUTH 0x130 ... BTN_THUMBR 0x13e) */ +#define RSOS_GAMEPAD_SDL_MAPPING \ + "06000000091200005352000001000000," NAME ",a:b0,b:b1,y:b2,x:b3,leftshoulder:b4," \ + "rightshoulder:b5,lefttrigger:b6,righttrigger:b7,back:b8,start:b9,leftstick:b10," \ + "rightstick:b11,dpup:h0.1,dpright:h0.2,dpdown:h0.4,dpleft:h0.8,leftx:a0,lefty:a1," \ + "platform:Linux," + +#define MAX_SRC 4 + +static const int out_keys[] = { + BTN_SOUTH, BTN_EAST, BTN_NORTH, BTN_WEST, BTN_TL, BTN_TR, BTN_TL2, BTN_TR2, + BTN_SELECT, BTN_START, BTN_THUMBL, BTN_THUMBR, +}; + +static volatile sig_atomic_t quit; + +static void on_signal(int sig) +{ + (void)sig; + quit = 1; +} + +static void emit(int fd, int type, int code, int value) +{ + struct input_event ev; + + memset(&ev, 0, sizeof(ev)); + ev.type = (unsigned short)type; + ev.code = (unsigned short)code; + ev.value = value; + if (write(fd, &ev, sizeof(ev)) < 0 && errno != EAGAIN) + fprintf(stderr, "rsos-gamepad: write: %s\n", strerror(errno)); +} + +static int create_pad(void) +{ + struct uinput_setup us; + struct uinput_abs_setup abs; + int fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK | O_CLOEXEC); + + if (fd < 0) { + fprintf(stderr, "rsos-gamepad: /dev/uinput: %s\n", strerror(errno)); + return -1; + } + ioctl(fd, UI_SET_EVBIT, EV_KEY); + ioctl(fd, UI_SET_EVBIT, EV_ABS); + ioctl(fd, UI_SET_EVBIT, EV_SYN); + for (size_t i = 0; i < sizeof(out_keys) / sizeof(out_keys[0]); i++) + ioctl(fd, UI_SET_KEYBIT, out_keys[i]); + memset(&abs, 0, sizeof(abs)); + abs.absinfo.minimum = -32767; + abs.absinfo.maximum = 32767; + abs.code = ABS_X; + ioctl(fd, UI_SET_ABSBIT, ABS_X); + ioctl(fd, UI_ABS_SETUP, &abs); + abs.code = ABS_Y; + ioctl(fd, UI_SET_ABSBIT, ABS_Y); + ioctl(fd, UI_ABS_SETUP, &abs); + abs.absinfo.minimum = -1; + abs.absinfo.maximum = 1; + abs.code = ABS_HAT0X; + ioctl(fd, UI_SET_ABSBIT, ABS_HAT0X); + ioctl(fd, UI_ABS_SETUP, &abs); + abs.code = ABS_HAT0Y; + ioctl(fd, UI_SET_ABSBIT, ABS_HAT0Y); + ioctl(fd, UI_ABS_SETUP, &abs); + + memset(&us, 0, sizeof(us)); + us.id.bustype = BUS_VIRTUAL; + us.id.vendor = VENDOR; + us.id.product = PRODUCT; + us.id.version = VERSION; + snprintf(us.name, sizeof(us.name), "%s", NAME); + if (ioctl(fd, UI_DEV_SETUP, &us) < 0 || ioctl(fd, UI_DEV_CREATE) < 0) { + fprintf(stderr, "rsos-gamepad: cannot create the device: %s\n", strerror(errno)); + close(fd); + return -1; + } + return fd; +} + +struct src { + int fd; + bool stick; + struct input_absinfo ax, ay; +}; + +static int open_sources(struct src *s) +{ + DIR *d = opendir("/dev/input"); + struct dirent *de; + int n = 0; + + if (!d) + return 0; + while ((de = readdir(d)) && n < MAX_SRC) { + char path[300], name[128] = ""; + int fd; + + if (strncmp(de->d_name, "event", 5)) + continue; + snprintf(path, sizeof(path), "/dev/input/%s", de->d_name); + fd = open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC); + if (fd < 0) + continue; + if (ioctl(fd, EVIOCGNAME(sizeof(name) - 1), name) < 0 || + (strcmp(name, "RetroStone2 Buttons") && strcmp(name, "RetroStone2 Shoulder Buttons") && + strcmp(name, "analog-stick"))) { + close(fd); + continue; + } + memset(&s[n], 0, sizeof(s[n])); + s[n].fd = fd; + s[n].stick = !strcmp(name, "analog-stick") && ioctl(fd, EVIOCGABS(ABS_X), &s[n].ax) == 0 && + ioctl(fd, EVIOCGABS(ABS_Y), &s[n].ay) == 0 && s[n].ax.maximum != s[n].ax.minimum && + s[n].ay.maximum != s[n].ay.minimum; + fprintf(stderr, "rsos-gamepad: %s (%s)\n", path, name); + n++; + } + closedir(d); + return n; +} + +static bool in_range(int v, const struct input_absinfo *a, bool near_centre) +{ + int lo = a->minimum < a->maximum ? a->minimum : a->maximum; + int hi = a->minimum < a->maximum ? a->maximum : a->minimum; + + if (near_centre) + return abs(v - (lo + (hi - lo) / 2)) <= (hi - lo) / 4; + return v >= lo && v <= hi; +} + +/* -32767..32767 from the ADC range */ +static int scale(int v, const struct input_absinfo *a) +{ + int lo = a->minimum < a->maximum ? a->minimum : a->maximum; + int hi = a->minimum < a->maximum ? a->maximum : a->minimum; + long r = ((long)(v - lo) * 65534) / (hi - lo) - 32767; + + return r < -32767 ? -32767 : r > 32767 ? 32767 : (int)r; +} + +int main(int argc, char **argv) +{ + struct src src[MAX_SRC]; + struct pollfd pfd[MAX_SRC]; + int out, n, sx = 0, sy = 0, hat_x = 0, hat_y = 0; + bool fitted = false, dpad[4] = { false }; /* up, down, left, right */ + + if (argc > 1 && !strcmp(argv[1], "--print-mapping")) { + puts(RSOS_GAMEPAD_SDL_MAPPING); + return 0; + } + signal(SIGTERM, on_signal); + signal(SIGINT, on_signal); + signal(SIGHUP, on_signal); + n = open_sources(src); + if (n == 0) { + fprintf(stderr, "rsos-gamepad: no built-in controls found\n"); + return 1; + } + out = create_pad(); + if (out < 0) + return 1; + for (int i = 0; i < n; i++) { + pfd[i].fd = src[i].fd; + pfd[i].events = POLLIN; + if (src[i].stick) { + sx = src[i].ax.value; + sy = src[i].ay.value; + } + } + + while (!quit) { + if (poll(pfd, (nfds_t)n, 1000) <= 0) + continue; + for (int i = 0; i < n; i++) { + struct input_event ev; + bool changed = false; + + if (!(pfd[i].revents & POLLIN)) + continue; + while (read(src[i].fd, &ev, sizeof(ev)) == sizeof(ev)) { + if (ev.type == EV_KEY) { + int code = ev.code; + + changed = true; + switch (code) { + case BTN_C: code = BTN_THUMBL; break; + case BTN_Z: code = BTN_THUMBR; break; + case BTN_DPAD_UP: dpad[0] = ev.value; code = -1; break; + case BTN_DPAD_DOWN: dpad[1] = ev.value; code = -1; break; + case BTN_DPAD_LEFT: dpad[2] = ev.value; code = -1; break; + case BTN_DPAD_RIGHT: dpad[3] = ev.value; code = -1; break; + default: break; + } + if (code >= 0 && ev.value != 2) + emit(out, EV_KEY, code, ev.value != 0); + } else if (ev.type == EV_ABS && src[i].stick && (ev.code == ABS_X || ev.code == ABS_Y)) { + if (ev.code == ABS_X) + sx = ev.value; + else + sy = ev.value; + changed = true; + } + } + if (!changed) + continue; + { + int hx = dpad[3] - dpad[2], hy = dpad[1] - dpad[0]; + + if (hx != hat_x) + emit(out, EV_ABS, ABS_HAT0X, hat_x = hx); + if (hy != hat_y) + emit(out, EV_ABS, ABS_HAT0Y, hat_y = hy); + } + if (src[i].stick) { + /* the menu's rule (input.c): out of range = not fitted; + * fitted again once both axes read near the centre */ + if (!in_range(sx, &src[i].ax, false) || !in_range(sy, &src[i].ay, false)) + fitted = false; + else if (!fitted && in_range(sx, &src[i].ax, true) && in_range(sy, &src[i].ay, true)) + fitted = true; + emit(out, EV_ABS, ABS_X, fitted ? scale(sx, &src[i].ax) : 0); + emit(out, EV_ABS, ABS_Y, fitted ? scale(sy, &src[i].ay) : 0); + } + emit(out, EV_SYN, SYN_REPORT, 0); + } + } + ioctl(out, UI_DEV_DESTROY); + close(out); + return 0; +} diff --git a/buildroot-external/configs/retrostone2_defconfig b/buildroot-external/configs/retrostone2_defconfig index 3db2d23..744ae23 100644 --- a/buildroot-external/configs/retrostone2_defconfig +++ b/buildroot-external/configs/retrostone2_defconfig @@ -77,6 +77,20 @@ BR2_PACKAGE_MESA3D=y BR2_PACKAGE_MESA3D_GALLIUM_DRIVER_LIMA=y BR2_PACKAGE_MESA3D_OPENGL_EGL=y BR2_PACKAGE_MESA3D_OPENGL_ES=y +# SDL2 on KMS/DRM + GLES2 and ALSA, for native games (docs/native-games.md) +BR2_PACKAGE_SDL2=y +BR2_PACKAGE_SDL2_KMSDRM=y +BR2_PACKAGE_SDL2_OPENGLES=y +# and the libraries of the libultraship ports (ports/starship, ports/soh: docs/native-games.md) +BR2_PACKAGE_LIBOGG=y +BR2_PACKAGE_LIBVORBIS=y +BR2_PACKAGE_LIBZIP=y +BR2_PACKAGE_TINYXML2=y +BR2_PACKAGE_SPDLOG=y +BR2_PACKAGE_JSON_FOR_MODERN_CPP=y +BR2_PACKAGE_OPUS=y +BR2_PACKAGE_OPUSFILE=y +BR2_PACKAGE_SDL2_NET=y BR2_PACKAGE_KMSCUBE=y # Bring-up tools diff --git a/buildroot-external/configs/retrostone2_release_defconfig b/buildroot-external/configs/retrostone2_release_defconfig index de6f24d..550e564 100644 --- a/buildroot-external/configs/retrostone2_release_defconfig +++ b/buildroot-external/configs/retrostone2_release_defconfig @@ -77,6 +77,20 @@ BR2_PACKAGE_MESA3D=y BR2_PACKAGE_MESA3D_GALLIUM_DRIVER_LIMA=y BR2_PACKAGE_MESA3D_OPENGL_EGL=y BR2_PACKAGE_MESA3D_OPENGL_ES=y +# SDL2 on KMS/DRM + GLES2 and ALSA, for native games (docs/native-games.md) +BR2_PACKAGE_SDL2=y +BR2_PACKAGE_SDL2_KMSDRM=y +BR2_PACKAGE_SDL2_OPENGLES=y +# and the libraries of the libultraship ports (ports/starship, ports/soh: docs/native-games.md) +BR2_PACKAGE_LIBOGG=y +BR2_PACKAGE_LIBVORBIS=y +BR2_PACKAGE_LIBZIP=y +BR2_PACKAGE_TINYXML2=y +BR2_PACKAGE_SPDLOG=y +BR2_PACKAGE_JSON_FOR_MODERN_CPP=y +BR2_PACKAGE_OPUS=y +BR2_PACKAGE_OPUSFILE=y +BR2_PACKAGE_SDL2_NET=y BR2_PACKAGE_KMSCUBE=y # Bring-up tools diff --git a/docs/display-design.md b/docs/display-design.md index 06c2f62..85f202d 100644 --- a/docs/display-design.md +++ b/docs/display-design.md @@ -579,6 +579,33 @@ check`): screen off never commits `ACTIVE` = 0 on the panel CRTC, shows black an - `CONFIG_DRM_FBDEV_EMULATION` is off (`linux.fragment`), so nothing lights the panel before `display_init()`: the frontend's first modeset is the first picture. There is no fbdev client to fight over master either. +## 9b. Native ports on SDL2 (RetroStoneOS 0.1.5.23) + +The native ports (docs/native-games.md) are separate SDL2 programs, not libretro hosts, so they do not use +`display.c`. The RetroStone2's SDL2 (Buildroot patch `board/retrostone2/patches/sdl2/0001-kmsdrm-output-policy.patch`, +SDL 2.32.10 `kmsdrm`) takes the same decisions: + +- **Output policy** (`frontend/src/follow/policy.[ch]`, pure C, tested by `tests/test_follow_policy.c`): HDMI when it + is connected and usable, else the built-in panel; the policy mode (`RSOS_HDMI_W/H/HZ`, default 1280x720@60, else + the preferred mode); HDMI never on the panel's CRTC (`RSOS_HDMI_CRTC`, default 1; `RSOS_PANEL_KEEP`, default 1). + SDL opens only that output, as one display. +- **Fixed render size**: the game gets one display of `RSOS_RENDER_W/H` (default 640x480) and an XRGB8888 GBM + surface of that size (the sun4i scaler refuses the alpha format). A first modeset puts a black framebuffer on + the CRTC, then every frame is a `drmModeSetPlane` of the game's buffer on the primary plane, scaled to the mode + and aspect-fit (the panel 1:1, HDMI e.g. 1440x1080 in 1920x1080). The game never sees a resolution change. +- **Live switching**: every 15 swaps SDL re-reads the connectors without probing (`drmModeGetConnectorCurrent`; the + HPD poll of kernel patch 0001 keeps them current) and runs the policy again. On a change the output left is + switched off (HDMI) or put on a black frame (the panel never stops scanning, section 8.5), the panel's backlight + goes off behind HDMI (`bl_power` 4) and on again for the panel, and the same frame is shown on the new output. +- **Sound follows the picture** (0.1.5.28): `SDL_alsa_audio.c` plays on the HDMI sound card (`sun4ihdmi`, or + `RSOS_AUDIO_HDMI_DEV`) while `rsos_audio_hdmi` says the game is on HDMI, else on the usual device, and moves the + sound with the same switch (the pcm is closed and opened again on the other card, set up as the first one was). +- Per frame the game's buffer is shown with the usual non-blocking page flip once the first modeset has put the + scaled plane in place (a plane update per frame waits for the vblank and slowed the ports down). +- Not done: the menu does not hand its output choice to the game (SDL decides by itself, with the same policy). +- The 640x480 mode on HDMI (an unscaled plane on CRTC 1) showed nothing on a Dell P2312H; 800x600 and 1920x1080 + work. Not understood yet. + ## 10. Hardware test checklist (UART console) Build with `BR2_PACKAGE_RSOS_FRONTEND=y`. `rsos-kmstest` and `rsos-display-selftest` are in `/usr/bin`. Save every diff --git a/docs/input-design.md b/docs/input-design.md index e3c0db1..99c12f0 100644 --- a/docs/input-design.md +++ b/docs/input-design.md @@ -80,14 +80,55 @@ Each input device is resolved in this order: come from the board profile (board.ini `builtin_pad_prefix`, `builtin_stick`, docs/porting.md); a board without them (a Raspberry Pi with USB pads) has no built-in pad. 2. **User mapping** saved earlier: `/data/rsos/input/.cfg` (made with the "Configure controller" screen). -3. **SDL GameControllerDB** (`gamecontrollerdb.txt`, zlib licence, shipped in the rootfs). We compute the SDL-style GUID from + "Configure controller" first asks what kind of pad it is, then walks through that pad's buttons. Only A, B and + Start are needed; any other step is skipped by pressing a button already set, or by waiting 6 s. + - **SNES, Xbox, PlayStation, Switch or similar** (`modern`): the usual 20 steps, by position. + - **Nintendo 64** (`n64`): A, B, Z, L, R, Start, the four C buttons, the stick. + - **GameCube** (`gc`): A, B, X, Y, Z, L, R, Start, the stick, the C stick. + - **Forget my set-up (automatic)** (shown once a pad has a user mapping) deletes it: the pad is mapped by (3)-(6) + again, or is unconfigured. + - A mapping without the left stick (skipped, or made before the stick could be set) still gets `ABS_X`/`ABS_Y`. + - The wizard reads a stick push past a third of the axis range: an 8-bit stick resting at 128 never goes + past half. +3. **Built-in profiles** (`g_profiles` in `src/input/input.c`) for pads whose kernel layout no database line describes + right, by vendor:product (and, for pads that pass as another, by the keys they have). All are hid-nintendo's + (linux 6.18): the Switch Online **N64** pad (C-up on Select, B on the right button), the Switch Online **NES** + pads (they say they are Joy-Cons; A at the bottom), the Switch Online **Genesis** pad (the database's line is for + another layout). + Then pads of **drivers that follow the Linux gamepad spec**: `xpad` (Xbox 360/One/Series over USB, many clones), + `playstation` (DualSense), `sony` (DualShock 3/4), `nintendo` (Switch Pro, Joy-Cons, Switch Online SNES), + `hid-steam` (Steam Controller; its left touch pad is no d-pad, its clicks are). The driver is read from + `/sys/class/input/eventN/device/device/driver` and logged (`input: ... (xpad) ...`). The database is not asked + for them: a line made under another driver or version could only be wrong. +4. **SDL GameControllerDB** (`gamecontrollerdb.txt`, zlib licence, shipped in the rootfs). We compute the SDL-style GUID from the evdev `input_id` (bus, vendor, product, version) and parse the mapping line ourselves. SDL isn't needed. This covers - thousands of USB/BT pads, including cheap clones. -4. **Linux gamepad spec**: if the device reports BTN_GAMEPAD and uses the standard codes (xpad, hid-sony, - hid-playstation, hid-nintendo, and hid-generic for many pads), use the codes directly, since they are already positional. -5. **Unknown device**: the UI shows a "New controller detected: hold any button to configure" prompt, which opens a guided + thousands of USB/BT pads, including cheap clones, adapters and 8BitDo pads. The kind of pad comes from its name + there: "GameCube" or the word "GC" is a GameCube pad (an adapter for both GameCube and N64 maps the GameCube way), + "N64" or "Nintendo 64" an N64 pad. +5. **Linux gamepad spec**: any other device with BTN_GAMEPAD, by its codes (already positional). +6. **Unknown device**: the UI shows a "New controller detected: hold any button to configure" prompt, which opens a guided mapping screen (the EmulationStation "configure input" flow) and saves to (2). +### Kinds of pad +The SDL names in a mapping mean what the database means by them for that kind of pad (`input.h`, +`enum input_pad_type`): + +| Kind | Names | In a game (RetroPad) | In the menus | +|---|---|---|---| +| `modern` | by position: `a` bottom, `b` right, `x` left, `y` top | `a` = B, `b` = A, `x` = Y, `y` = X | A (right) confirms, B (bottom) goes back | +| `n64` | `a` = A, `b` = B, `-righty`/`+righty`/`-rightx`/`+rightx` = C-up/down/left/right (buttons or a stick), `lefttrigger` = Z, `leftshoulder` = L, `rightshoulder` = R | A = B, B = Y, C-up/down/left/right = X/A/L3/R3 **and** the right stick (what the N64 core reads as C), Z = L2 | A confirms, B goes back, Z is Select | +| `gc` | by label: `a` = A, `b` = B, `x` = X, `y` = Y, `rightshoulder` = Z, `lefttrigger`/`righttrigger` = L/R, `rightx`/`righty` = C stick | A = B, B = Y, X = A, Y = X (by position), Z = R1, L/R = L2/R2 | A confirms, B goes back | + +- N64 and GameCube pads have no Select: **Z + Start held 1 s** opens the in-game menu, and quits a native game. +- **Home / Guide / PS** (any pad that has one): opens the in-game menu; held, it quits a native game. +- A **PlayStation pad's touch pad** is a device of its own with ABS_X and a few keys: it is not taken for a pad + (no BTN_TOUCH / multitouch axes on a pad). The motion sensors (PlayStation, Switch) have no keys: ignored too. +- Not supported: Nintendo's GameCube adapter (WUP-028, 057e:0337) and a Mayflash in its "Wii U" mode need a driver + Linux does not have; a Mayflash adapter in **PC mode** works (the database knows it). Two Joy-Cons are two pads, + not one (that needs joycond). +- Test: `make check-input` (`n64_pad`, `known_pads`: each known pad laid out from its kernel driver's codes or its + database line, with no hardware). + Additional handling: - **Hats** (ABS_HAT0X/Y) become the D-pad. - **Analog triggers** (ABS_Z/ABS_RZ, ABS_GAS/BRAKE) become L2/R2 over a threshold, and are also passed as analog. diff --git a/docs/native-games.md b/docs/native-games.md new file mode 100644 index 0000000..67a7d2e --- /dev/null +++ b/docs/native-games.md @@ -0,0 +1,105 @@ +# Native games + +A native game is a program built for the console itself (ARM, Linux), started without an emulator: an +open-source game engine, a source port, a homebrew game. The menu lists them in the one system **Ports**, with the +Doom and Cave Story games (folders `roms/native`, `roms/doom`, `roms/cavestory`, and `roms/ports` for any of them). +A game of the list starts as the system it belongs to: a `.sh` launch script as a native game (this page), a `.wad` +as Doom, an `.exe` as Cave Story (their libretro cores). Favorites and play statistics follow the games. + +[ports/](../ports/README.md) has build scripts for three N64 PC ports (Super Mario 64, Star Fox 64, Ocarina of +Time), each built on a PC from the user's own ROM. No game or game data is in this repository. + +## On the SD card + +One launch script per game in `roms/native/` (subfolders are fine), with the game's own files next to it: + +``` +roms/native/ + My Game.sh <- the entry in the menu ("My Game") + mygame/ + mygame <- the program (ARM, linked against this system's libraries) + data files... +``` + +The script runs with `/bin/sh` in **its own folder** (the working directory), so it can use relative paths. It +should end with `exec` so the game is the process the menu watches: + +```sh +#!/bin/sh +cd mygame +exec ./mygame +``` + +A program that the exFAT partition does not mark executable can be started through the dynamic loader: +`exec /lib/ld-linux-armhf.so.3 ./mygame`. + +## What the game gets + +* The display, the sound and the pads, as a libretro game does: the menu drops DRM master before the launch and + takes it back afterwards. **SDL2** is installed with the KMS/DRM video driver (GLES2 on the Mali-400 through + Mesa's lima) and ALSA; the menu sets `SDL_VIDEODRIVER=kmsdrm` and `SDL_AUDIODRIVER=alsa`. +* **HDMI**: like a libretro game, the game is on the TV or monitor while HDMI is plugged in (the built-in screen is off) and + back on the built-in screen when it is unplugged, live. The SDL2 of the image does this (docs/display-design.md, + 9b): the game always renders 640x480 and the display engine scales it, so it must not assume another size. The sound + follows: SDL's ALSA backend plays on the HDMI sound card while the game is on HDMI and on the speaker otherwise + (a device the game chose itself, or `AUDIODEV`, is left alone). +* `HOME=/data/rsos/native-home` (the root file system is read-only), with `XDG_CONFIG_HOME` and + `XDG_DATA_HOME` under it. A game that saves next to itself (its working directory) keeps its saves on the card. +* `RSOS_GAME_DIR` (the script's folder) and `RSOS_LANG` (the menu's language, e.g. `en`). +* Its output goes to `/run/rsos/game.log`, copied to `rsos/logs/` on the SD card at the next start. + +The built-in controls are three input devices (the buttons, the shoulder buttons, the optional analog stick): +a game that reads only one SDL game controller would see only one of them, and SDL does not take the stick for a +joystick at all. **`rsos-gamepad`** (RetroStone2, build 18 or newer) merges them into one standard virtual +gamepad, "RetroStoneOS Gamepad" (uinput): the buttons by position (bottom = SDL "a", left = "x"), L1/R1 the +shoulders, L2/R2 the triggers, the optional C/Z the stick clicks, the D-pad as hat 0, the stick as the left stick +(centred while it is not fitted, as in the menu). A launch script for an SDL game starts it and gives SDL its +mapping (ports/starship/Star Fox 64.sh): + +```sh +SDL_GAMECONTROLLERCONFIG="$(/usr/bin/rsos-gamepad --print-mapping)" +export SDL_GAMECONTROLLERCONFIG +export SDL_GAMECONTROLLER_IGNORE_DEVICES=0x0001/0x0001 # the raw button devices +/usr/bin/rsos-gamepad & +``` + +It runs in the game's process group, so the menu stops it with the game. A game can also read the devices +itself from `/dev/input` (ports/sm64/controller_rsos.c does, to follow the N64 emulator's button settings). + +## What the menu does around it + +* **Select + Start** held for one second quits the game (SIGTERM to its process group, SIGKILL if it is still + there 5 s later); on an N64 or GameCube pad (no Select) **Z + Start**, on any pad **Home / Guide / PS**. A native + game has no in-game menu of ours. +* **External pads**: each one's mapping, as the menu resolved it (user, built-in profile, database or the Linux + standard), is written as an SDL line to `/run/rsos/sdl-controllers.txt` and passed in + `SDL_GAMECONTROLLERCONFIG_FILE`, so a game sees a pad as the menu does. N64 and GameCube pads get the database's + names for them (an N64 pad: A/B on a/b, the C buttons on the right stick, Z on the left trigger, R also on the + right trigger), which the libultraship ports and sm64-port read. +* **Sleep** (power key): the game is frozen (SIGSTOP) and the backlight goes off; waking continues it. +* **Power-off**: the game gets SIGTERM, then SIGKILL after 8 s. There is no save state: the game must save on + its own. +* The **idle power-off** waits while a native game runs (it could not resume it). +* An exit code other than 0 (and other than a stop by Select+Start or the menu) shows "The game ended with an + error". + +`make check-frontend` (steps 2a-2c) covers the launch, the environment, the error message and the process group. + +## Layouts: an N64 pad that plays like the built-in buttons + +A port's bindings are usually changed for the built-in buttons (the C buttons on the shoulders, L on Select...), +so a real N64 pad, plugged in with the menu's own N64 mapping (C buttons on the right stick, Z on the left trigger, +L and R on the shoulders), would press the wrong things. A **layout** says which SDL element the game reads for each +N64 function; the menu applies it to an N64 pad's mapping when it starts the game, so the pad does what the +built-in buttons do in that game. + +* The file is `.layout` next to the script (`Ocarina of Time.sh` → `Ocarina of Time.layout`), + lines of `function = SDL element`, `#` for comments. A line left out keeps the default; `none` drops the element. +* Functions: `a b z l r start cup cdown cleft cright dpup dpdown dpleft dpright`. Elements are SDL names + (`a b x y back start leftshoulder rightshoulder lefttrigger righttrigger dpup dpdown dpleft dpright`, and the + right-stick halves `-righty +righty -rightx +rightx`). +* All lines apply at once, so two functions can swap. Naming `r` also removes the default's copy of R on the right + trigger (an N64 pad has no ZR), which a port could read as another button. +* The menu also gives an N64 pad whose name does not say so (a USB adapter's "Generic USB Joystick") the name + "N64 Controller (...)", for games that pick their layout by the pad's name (GoldenEye does). +* Edit the file on the card to change it; no new build is needed. Layouts shipped with the ports are in `ports/`. diff --git a/docs/store-design.md b/docs/store-design.md new file mode 100644 index 0000000..68e311d --- /dev/null +++ b/docs/store-design.md @@ -0,0 +1,123 @@ +# Store (homebrew and freeware downloads) - design + +Status: proposal, nothing implemented. Scope for v1: **homebrew and freeware only**. No commercial ROMs, no +ports that need Nintendo assets (those stay build-it-yourself in `ports/`). + +## Goal +Settings-free, on-device browsing of a signed catalog: pick a system or "Ports", see entries with cover, size +and description, press A to download, play from the normal game list. + +## Reuse (already in the tree) +| Need | Existing piece | +|---|---| +| HTTPS download with range/resume, timeouts | `frontend/src/update/http.c` (`http_get`, mbedTLS) | +| JSON catalog parsing | `update/json.c` | +| Integrity | `update/sha256.c` | +| Authenticity | `update/rsu.c` signify-compatible Ed25519 (`manifest.sig`), same trust model as OTA | +| Long job with progress and cancel | `rsos-covers` helper: runs as its own process, writes a progress file, SIGTERM cancels; UI polls it (`ui/storage.c`) | +| Destination choice | game libraries (SD / eMMC / M.2) from `loader.c` and the "Copy games to" import screen | +| Covers | `rsos-covers` / `apply_covers` and `roms/native/media/covers/` | + +## Pieces +1. **Catalog** (`catalog.json` + `catalog.json.sig`), static files on GitHub Pages or Releases. Signed with a store + key kept separate from the OTA key, public key built in (`BR2_RETROSTONE_STORE_PUBKEY`, same pattern as the + update repo/key options). +2. **`rsos-store` helper** (new, `update/rsos-store.c`): subcommands `list`, `get `, `verify`. + `get` downloads to `/.store-tmp`, checks size and SHA-256, unpacks, then renames into place, so a + cancelled or failed download never leaves a half game. It writes the progress file in the `rsos-covers` format. +3. **Frontend screen** (`ui/store.c`): a "Store" entry beside Settings. System tabs, list with installed marker, + detail view, destination picker reusing the library chooser, Update/Remove for installed entries. +4. **Install record**: `/data/rsos/store/installed.json` (id, version, files), so updates and Remove work and + other tools never have to guess what the store put on the card. + +## Catalog entry +```json +{ "id": "micro-mages", "name": "Micro Mages", "system": "nes", "version": "1.2", + "license": "freeware, author-permitted redistribution", "author": "Morphcat Games", + "desc": "...", "size": 41040, "sha256": "...", "url": "https://.../micro-mages.nes", + "cover": "https://.../micro-mages.png", + "kind": "rom" } +``` +`kind` is `rom` (single file, goes to `roms//`), `zip` (extract into `roms//`), or `native` +(archive with a `Name.sh` launcher + data, goes to `roms/native/`; arch must be `armhf` and the `.sh` is shown +before install). Every entry carries a `license` string and a `source` URL; the catalog tooling refuses an entry +without them. + +## Safety rules +- Catalog signature checked before anything is parsed; entries signed as a whole, so a swapped URL fails. +- Download size capped by the catalog's `size`; extra bytes abort. SHA-256 checked before unpack. +- Archive extraction rejects absolute paths, `..`, symlinks and device files; files land only under the chosen + library's `roms//` (or `roms/native/`). +- `native` entries run code, so the store requires the signed catalog and the install screen shows author and + license first. No catalog entry can touch the read-only rootfs. +- Works with WiFi off: the screen says so and offers "Turn WiFi on" (existing Network setting). + +## Content sourcing (v1) +Only titles whose licence allows redistribution: public-domain homebrew, Homebrew Hub (checking each licence), +itch.io freeware that permits it, and open-source native games that cross-build on the A20. Each added with the +author's licence recorded. Port build scripts stay in `ports/` and are linked from the store as "How to build", +not downloaded. + +## Server side +- `store/` directory in the fork (or a separate repo): `entries/*.toml` -> `make-catalog.py` -> `catalog.json`, + hashes the files, signs with the store key. GitHub Actions publishes to Pages. +- Entry files are mirrored on our release page so a third-party site vanishing does not break a download. + +## Milestones +1. Catalog format + `make-catalog.py` + signing + host tests (golden catalog, tamper cases). +2. `rsos-store` helper: list/get/verify; tests with a local HTTP server and malicious archives. +3. UI screen using `rsos-uipreview` for screenshots, then hardware test over the Dev SSH card. +4. Seed catalog with ~10 licence-checked titles; release as a fork build (0.1.5.21). +5. Upstream PR as its own feature (maintainer asked one feature per PR), after the fork build is hw-tested. + +## Open points +- Store key custody and the fork vs upstream catalog URL (build option, like the OTA repo). +- Whether upstream wants a store at all; fork build works either way. +- Cover size/format limits for catalog images (match the current 640x480 title style). + +## Implementation notes (as built, milestones 1-2) +- Archives are plain **ustar** tar (`tar --format=ustar`), not zip: the helper unpacks them itself, with no extra + library. Regular files and folders only; links, `..`, absolute paths and unpacked bytes beyond the catalog's + `unpacked` are refused. +- The catalog is signed with `rsos-mkupdate signfile` / checked with `verifyfile` (signify-compatible, same code as + the updater); `scripts/store/make-catalog.py` builds `catalog.json` from `entries/*.json` and refuses an entry + without a licence or source. +- `native` entries carry `arch` and are hidden unless it matches the console's (`armhf`). +- `rsos-store` is `frontend/src/update/rsos-store.c` (`list`, `get`, `remove`, `installed`); tests: + `frontend/src/update/tests/store_test.sh` (40 checks, run by `make check-update`). +- The store's public key goes to `/usr/share/rsos/store.pub` (`RSOS_STORE_PUBKEY`, default `assets/store.pub`; + the key pair is not generated yet) and the catalog URL is `RSOS_STORE_URL`. + +## Idea: ports from the user's own ROM +Proposed 2026-11-06: if the ROM is already in the user's N64 folder, offer "Install ", which makes the +port, adds it to Ports and removes every temporary file. +- **Compiling on the console is not realistic**: the image has no compiler (read-only rootfs), the ports need + hours of build time and more than the A20's 1 GB of RAM for the C++ ones. +- **Realistic version**: the store ships the port's prebuilt `armhf` binary *without* assets (that is legal to + host). The device then does the one step that needs the user's ROM: check its SHA-1 against the port's list, + extract the game assets into the port's `.o2r`/data files with a small extractor, add the launcher to Ports, + and delete the temporary files. That needs the extractor built for armhf per port (SoH/2Ship use ZAPD, Starship + Torch; SM64 builds assets at compile time and would need its own packer). +- Catalog support: a new entry kind `port` with `rom_sha1` list, `extract` command and the asset-free archive. +- Open: measure the extractor's time and memory on the A20 (PC: SoH ~19 s). + +## Milestone 3 (built): Settings > Game store +`frontend/src/ui/store_ui.c`: the helper's catalog as a menu grouped by system ("Ports" for native games), a +game's page (description, author, licence, size) with INSTALL / UPDATE / REMOVE, a drive choice when the console +has several game drives, download progress as a percentage, translated error messages (full drive, existing +file, damaged download, invalid package). Preview tests: `tests/fake-rsos-store.sh` + `make check-ui`. + +## Idea (2026-11-06): a "Store" tile on the main carousel +Appears only while the console is online; opens the same list, with a cover and description per game and a +category (console) level when the list is long. Needs: a pseudo-system entry in the carousel (like Favorites), +theme art for it, a list view with covers (the catalog already carries a `cover` URL; thumbnails would be fetched +on demand and cached), and the console categories as the first level. + +See also [store-ports.md](store-ports.md): installing ports from the user's own ROM (design, 2026-11-06). + +## Screens (preview tool, fake helper) +| | | +|---|---| +| ![the list](ui-previews/store-list.png) | ![a game](ui-previews/store-game.png) | +| ![a port, ROM found](ui-previews/store-port-found.png) | ![a port, no ROM](ui-previews/store-port-no-rom.png) | +| ![the question before preparing](ui-previews/store-port-confirm.png) | ![preparing](ui-previews/store-port-preparing.png) | diff --git a/docs/store-ports.md b/docs/store-ports.md new file mode 100644 index 0000000..c7ad184 --- /dev/null +++ b/docs/store-ports.md @@ -0,0 +1,131 @@ +# Store: installing ports from the user's own ROM - design + +Status: implemented in this fork (design written 2026-11-06; see "Status" at the end for what is built). Extends [store-design.md](store-design.md). Scope: the store carries +**only the ports built for this console** (curated, signed by the maintainer, each one tested on hardware). The store never +holds or downloads any game data: the data is made on the console from a ROM the player already has. + +## What was measured (hardware, 2026-11-06) +Ship of Harkinian 9.3.1's own extractor, run on a RetroStone2 Pro with an Ocarina of Time 1.2 dump: + +| | | +|---|---| +| Time | 207 s | +| Peak memory (process) | 810 MB of 1006 MB; lowest MemAvailable 129 MB | +| Result | `oot.o2r` 33,914,022 bytes, all 39,032 entries identical to the PC build | +| Extractor files | ~150 MB in thousands of small files = 2.6 GB on the data partition (128 KB per file) | +| What failed | an address-space cap of 768 MB (silent failure); the GUI "Generate one now?" popup (no gamepad navigation) | + +So extraction on the console is possible but takes nearly all RAM: it must run alone, guarded, and be one-shot. + +## Three kinds of port +| Kind | Examples | Package holds | Install step on the console | +|---|---|---|---| +| `port` / extract | Ocarina of Time, Majora's Mask, Star Fox 64, Mario Kart 64, Smash | program, libraries, launcher, port archive (`soh.o2r`), extractor description files (one archive) | find the ROM, run the extractor headless, keep the made archive (`oot.o2r`) | +| `port` / copy-rom | Perfect Dark, GoldenEye (if its data is not compiled in) | program, launcher | find the ROM, convert to `.z64`, copy it into the port's folder | +| not offered | Super Mario 64 (data compiled into the program) | - | store page says "build it on a PC" and links the recipe | + +## Catalog entry (new kind `port`) +```json +{ "id": "oot", "name": "Ocarina of Time", "system": "native", "kind": "port", "arch": "armhf", "version": "9.3.1.5", + "url": ".../oot-9.3.1.5.tar", "size": 61000000, "sha256": "...", "unpacked": 140000000, + "launcher": "Ocarina of Time.sh", "cover": ".../oot.png", + "rom": { "name": "Ocarina of Time (US 1.2)", "sha1": ["41b3bdc4...", "..."], "size": [33554432], + "mode": "extract", "extract": "extract.sh", "needs_ram_mb": 850, "est_minutes": 4, "needs_disk_mb": 400 }, + "quality": { "tested_build": "0.1.5.26", "speed": "smooth", "fps": "20-30", "controls": "..." } } +``` +- `rom.sha1` is every accepted dump (byte order does not matter: the helper converts); `rom.size` lets the console hash only + files of the right size. +- `mode`: `extract` (run `extract.sh` from the package) or `copy` (copy the converted ROM to `rom.dest`). +- `quality` is shown on the page; only entries tested on hardware are signed into the catalog. + +## ROM discovery +1. Candidates: `*.z64|*.v64|*.n64` in `/roms/n64*/` of every game drive, and the root of a mounted USB drive. +2. Skip any file whose size is not in `rom.size` (most of a 40-game folder is skipped without reading it). +3. SHA-1 of the remaining files (a 32 MB file takes a few seconds from the SD card); hashes are cached by path, size and + mtime so "Look again" is instant. +4. Page states: **ROM found** (file name shown), **not found** ("put your ROM in your N64 folder or on a USB drive, + then Look again"), **wrong version** (a ROM of this game with another hash: says which versions are accepted). + +## Install sequence (`rsos-store install-port ID [--rom FILE]`) +1. Preconditions, checked before anything is written: free disk (`needs_disk_mb` + package), battery above a floor or a + charger, no game running, and enough free RAM (`needs_ram_mb`; the menu's background workers are paused, other helpers + refused). If RAM is short: "Restart the console and try again" (nothing else is running right after boot). +2. Download the package (existing path: size and SHA-256 against the signed catalog), unpack into + `/.store-/` (a hidden temp folder; one place to delete). +3. Extract (mode `extract`): run the package's `extract.sh` as a **guarded child**: `oom_score_adj` 1000 (it dies before + the menu or the system), address-space limit of 1.8 GB, a watchdog that kills it if MemAvailable < 90 MB, a timeout + (3x `est_minutes`), progress and the child's log written to the temp folder. Needs a headless entry in the port + (see "Port changes"). +4. Verify: the output archive exists and is non-empty, and the extractor's own "done" marker is present. +5. Commit atomically: move the program folder into `/roms/native//`, the launcher next to it, the cover into + `roms/native/media/covers/`; write the install record (`installed.tsv`, with the ROM's SHA-1 and the archive format). + The record is `/data/rsos/store/installed.tsv` for the console's own `/data/roms`; an install into another roms + folder (`--roms`, a test into a scratch folder) keeps its record in that folder, `/.rsos-store/installed.tsv`, + so it never shows as installed in the menu. +6. **Always clean up**, success or failure or cancel: delete `.store-/` and the downloaded package. A start-up sweep + removes any `.store-*` left by a power cut. + +Failure never touches an installed copy: an update stages beside it and swaps at step 5. + +## Remove / update +- **Remove** deletes the program, archives and launcher; **saves and settings are kept** by default (they live in the port's + folder, so the helper moves them to `/roms/native/.removed-saves//` and a later install restores them). +- **Delete this game** in the Ports list, on a launcher the store installed, removes the whole port the same way + (`rsos-store remove-path `), with the files an earlier install moved aside into + `roms/native/.store-replaced//`; any other native game loses its launcher only. +- **Update** replaces program and launcher. The made archive (`oot.o2r`) is kept unless the catalog's `rom.archive_format` + changed; then the page asks for the ROM again ("This update needs your game data prepared again"). + +## Port changes needed (in RetroStone-Ports) +- A headless extraction entry for each Torch/ZAPD port (`soh.elf --rsos-extract `: no window, no popups, exit + code, one-line progress, run before SDL initialises). The measured run used the GUI path; headless should also save + memory (no GL, no ImGui). +- Package script per port (`package-.sh`): builds the asset-free tarball and the catalog fragment. +- Perfect Dark / GoldenEye: a launcher variant that takes the ROM from `Data/` (already how they work) and a check of + whether GoldenEye's converted assets are inside the binary (if so it moves to "not offered"). + +## UI (Game store page, then the carousel tile) +Page for a port: cover, description, quality line (speed, tested build), the ROM line, then one button: INSTALL (disabled +until a ROM is found). Progress screen: phases "Downloading", "Preparing game data (about 4 min)", "Installing"; B cancels +(kills the child, cleans up). The screen stays awake and the idle power-off is held. The carousel tile later just opens +this list (flat while there are fewer than ~20 entries). + +## Safety summary +- No game data is hosted, downloaded or kept: only the player's own ROM is read, and only the made archive is stored. +- The package runs code as root: it is covered by the signed catalog, like `native` entries. +- Memory guard, timeout, atomic commit, mandatory cleanup, saves preserved on remove. + +## Milestones +1. `rsos-store find-rom`: size filter, SHA-1, byte-order check, hash cache (host tests). +2. Headless extract for Ship of Harkinian; re-measure time and RAM on the console (expect lower than 810 MB). +3. `rsos-store install-port` with the guard, cleanup and failure tests (kill mid-way, no space, wrong ROM, power-cut sweep). +4. Port page in the Store UI and preview tests with a fake helper. +5. Extraction test per port on the console: Majora's Mask, Star Fox 64, Mario Kart 64, Smash (memory is unknown for these). +6. Copy-ROM ports (Perfect Dark, GoldenEye). +7. Package build automation (self-hosted runner on the home server or a local script) and the signed catalog. +8. Carousel tile (online only). + +## Open questions +- Headless extraction's real RAM peak (may drop well below 810 MB; if not, only Ocarina of Time-sized ports fit). +- Whether to reduce the 2.6 GB on-disk cost further (extractor files could be streamed from the package tar instead of + unpacked). +- Legal review of distributing the asset-free binaries, per port (see the earlier notes), before anything is public. + +## Status (2026-11-06) +Measured on the console (all five extractors, byte-identical archives except Majora's Mask, which also plays): Ocarina of Time +200 s / 757 MB peak, Majora's Mask 384 s / 342 MB, Star Fox 64 857 s / 267 MB, Mario Kart 64 199 s / 684 MB, Smash 25 s / 114 MB. +Headless extraction patches live in RetroStone-Ports (`*-extract.patch`, Smash uses `smash/build-torch-arm.sh`). + +Built: `rsos-store find-rom` and `install-port` (guarded extractor, atomic commit, mandatory cleanup, per-file install record; 62 host +checks in `store_test.sh`) and the port page in Settings > Game store (`ui/store_ui.c`): searches the ROM, shows the game, the question +before a long preparation, the charger/battery check, progress ("preparing N%"), the translated errors, LOOK AGAIN when there is no ROM; +leaving the screen cancels an install; no idle power-off meanwhile. Preview tests with `tests/fake-rsos-store.sh` (`make check-ui`). + +Since then (2026-11-13): the store is live. The signed catalog and the packages are in +[KurdtNervanna/RetroStoneOS-Store](https://github.com/KurdtNervanna/RetroStoneOS-Store) with eight ports (Ocarina of Time, +Majora's Mask, Star Fox 64, Mario Kart 64, Smash 64 and Super Mario 64: the game data is extracted from the player's ROM; +Perfect Dark and GoldenEye 007: the ROM is copied), and the fork's releases ship the Settings > Game store screen. A Star Fox 64 install from the +store was confirmed on a RetroStone2 with fork build 0.1.5.30. + +Not built yet: the carousel tile (online only). A full install on the console has been confirmed for Star Fox 64 only; the other +ports' installs have not all been repeated through the store on hardware. The legal review in "Open questions" is still open. diff --git a/docs/ui-design.md b/docs/ui-design.md index 0eb8d90..2033d4b 100644 --- a/docs/ui-design.md +++ b/docs/ui-design.md @@ -559,7 +559,8 @@ to the default, then to the first theme found. The default stays `rsos-dark` (pr - **Hide / Delete** (batch 2, game options): "Hide this game" (gamedb `hidden`; also the gamelist.xml `hidden` flag) removes it from the lists; Settings > Game lists > "Show hidden games" (key `show_hidden`) shows them again, marked "(hidden)". "Delete this game" asks `Delete "" from the SD card?` [DELETE] [CANCEL] (CANCEL - selected; for .m3u/.cue: "The discs/tracks it lists are kept"), deletes the file only, then asks "Also delete its + selected; for .m3u/.cue: "The discs/tracks it lists are kept"), deletes the file only (a Ports launcher the game + store installed: the store removes the whole port, keeping its saves and settings), then asks "Also delete its saves and save states?" [NO] [YES] (NO selected): `.srm`/`.rtc` in `/data/saves//`, `.state*` (and their `.png`) in `/data/states//` (their `.bak` copies too). The game is removed from every list and from gamedb.tsv. If another file of the system's ROM folder has the same save name (`Game.zip` next to `Game.sfc`, the diff --git a/docs/ui-previews/store-game.png b/docs/ui-previews/store-game.png new file mode 100644 index 0000000..88e001c Binary files /dev/null and b/docs/ui-previews/store-game.png differ diff --git a/docs/ui-previews/store-list.png b/docs/ui-previews/store-list.png new file mode 100644 index 0000000..c630f45 Binary files /dev/null and b/docs/ui-previews/store-list.png differ diff --git a/docs/ui-previews/store-port-confirm.png b/docs/ui-previews/store-port-confirm.png new file mode 100644 index 0000000..bba2749 Binary files /dev/null and b/docs/ui-previews/store-port-confirm.png differ diff --git a/docs/ui-previews/store-port-done.png b/docs/ui-previews/store-port-done.png new file mode 100644 index 0000000..73c29f4 Binary files /dev/null and b/docs/ui-previews/store-port-done.png differ diff --git a/docs/ui-previews/store-port-found.png b/docs/ui-previews/store-port-found.png new file mode 100644 index 0000000..fca3320 Binary files /dev/null and b/docs/ui-previews/store-port-found.png differ diff --git a/docs/ui-previews/store-port-no-rom.png b/docs/ui-previews/store-port-no-rom.png new file mode 100644 index 0000000..ad66bae Binary files /dev/null and b/docs/ui-previews/store-port-no-rom.png differ diff --git a/docs/ui-previews/store-port-preparing.png b/docs/ui-previews/store-port-preparing.png new file mode 100644 index 0000000..c83978e Binary files /dev/null and b/docs/ui-previews/store-port-preparing.png differ diff --git a/frontend/Makefile b/frontend/Makefile index ec0423a..53118fe 100644 --- a/frontend/Makefile +++ b/frontend/Makefile @@ -266,8 +266,9 @@ check-power: $(POWER_TEST) check-transfer: $(TR_BUILD)/test_transfer $(TR_BUILD)/test_transfer @# USB import and network upload know every system of the carousel - @# (sysmap.c lacked the second batch of cores until 0.1.4) - @sed -n 's/^\t{ "\([a-z0-9]*\)", NC_("system".*/\1/p' src/ui/systems.c | grep -vx retrostone | sort > $(TR_BUILD)/sys-ui.txt + @# (sysmap.c lacked the second batch of cores until 0.1.4); "ports" only + @# lists the games of doom, cavestory and native, which have their own folders + @sed -n 's/^\t{ "\([a-z0-9]*\)", NC_("system".*/\1/p' src/ui/systems.c | grep -vxE 'retrostone|ports' | sort > $(TR_BUILD)/sys-ui.txt @sed -n 's/^\t{ "\([a-z0-9]*\)", "[^"]*", {.*/\1/p' src/transfer/sysmap.c | sort > $(TR_BUILD)/sys-tr.txt @diff $(TR_BUILD)/sys-ui.txt $(TR_BUILD)/sys-tr.txt || \ { echo "check-transfer: src/ui/systems.c (<) and src/transfer/sysmap.c (>) list different systems"; exit 1; } @@ -360,6 +361,25 @@ check-ui: $(UIPREVIEW) expect:|Wireless_Controller a sleep:1500 expect:dialog:Could_not_pair a wait:300 \ expect:menu:Bluetooth_devices|Wireless_Controller b sleep:500" rm -rf $(UI_CHECK_DIR)/bt $(UI_CHECK_DIR)/data/rsos/settings.ini + @echo "check-ui: Game store (tests/fake-rsos-store.sh): the list by system, install, update flag, remove, a full drive" + rm -rf $(UI_CHECK_DIR)/store + FAKE_STORE_DIR=$(UI_CHECK_DIR)/store $(UIPREVIEW) --root $(UI_CHECK_DIR) --quiet --store-helper $(CURDIR)/tests/fake-rsos-store.sh --keys "start down down down down down down down down expect:menu:Settings|Game_store a sleep:500 wait:1500 expect:menu:Game_store|Micro_Mage a wait:300 expect:dialog:Micro_Mage_1.0_by_Test_Author_-_CC0_40_KB__A_platformer_for_the_NES.|INSTALL a sleep:3000 wait:1500 expect:toast=Micro_Mage_installed a wait:300 expect:dialog:Micro_Mage_1.0_by_Test_Author_-_CC0_40_KB__A_platformer_for_the_NES.|REMOVE a sleep:2500 wait:1500 expect:toast=Micro_Mage_removed b sleep:300 expect:menu:Settings" + grep -q -- '^--out .* list$$' $(UI_CHECK_DIR)/store/calls.log + grep -q -- '--roms .*/roms get micro-mage$$' $(UI_CHECK_DIR)/store/calls.log + grep -q -- '--roms .*/roms remove micro-mage$$' $(UI_CHECK_DIR)/store/calls.log + rm -rf $(UI_CHECK_DIR)/store + FAKE_STORE_DIR=$(UI_CHECK_DIR)/store FAKE_STORE_FAIL=space $(UIPREVIEW) --root $(UI_CHECK_DIR) --quiet --store-helper $(CURDIR)/tests/fake-rsos-store.sh --keys "start down down down down down down down down a sleep:500 wait:1500 a wait:300 a sleep:1500 wait:1500 expect:dialog:There_is_not_enough_free_space a wait:300" + rm -rf $(UI_CHECK_DIR)/store + @echo "check-ui: Game store ports: the ROM found, the question, preparing with progress, installed; no ROM: LOOK AGAIN" + rm -rf $(UI_CHECK_DIR)/store + FAKE_STORE_DIR=$(UI_CHECK_DIR)/store $(UIPREVIEW) --root $(UI_CHECK_DIR) --quiet --store-helper $(CURDIR)/tests/fake-rsos-store.sh --keys "start down down down down down down down down a sleep:500 wait:1500 down down expect:menu:Game_store|Ocarina_of_Time a sleep:800 wait:1500 expect:dialog:Ocarina_of_Time_9.3.1_by_Test_Author_-_CC0_58_MB__A_port_made_from_your_own_ROM.__Your_ROM:_Ocarina_of_Time_(U)_(V1.2).z64|INSTALL a wait:300 expect:dialog:Preparing_the_game_data_from_your_ROM_takes_about_4_minutes._Keep_the_console_on_and_nothing_else_running.|START a wait:300 sleep:3500 wait:1500 expect:toast=Ocarina_of_Time_installed expect:menu:Game_store|Ocarina_of_Time" + grep -q -- 'find-rom zelda-port$$' $(UI_CHECK_DIR)/store/calls.log + grep -q -- '--rom /data/roms/n64/Ocarina of Time (U) (V1.2).z64 install-port zelda-port$$' $(UI_CHECK_DIR)/store/calls.log + rm -rf $(UI_CHECK_DIR)/store && mkdir -p $(UI_CHECK_DIR)/store && touch $(UI_CHECK_DIR)/store/norom + FAKE_STORE_DIR=$(UI_CHECK_DIR)/store $(UIPREVIEW) --root $(UI_CHECK_DIR) --quiet --store-helper $(CURDIR)/tests/fake-rsos-store.sh --keys "start down down down down down down down down a sleep:500 wait:1500 down down a sleep:800 wait:1500 expect:dialog:Ocarina_of_Time_9.3.1_by_Test_Author_-_CC0_58_MB__A_port_made_from_your_own_ROM.__Needs_your_own_ROM:_Ocarina_of_Time_(US_1.2)._Put_it_in_your_N64_folder_or_on_a_USB_drive,_then_choose_LOOK_AGAIN.|LOOK_AGAIN" + rm -rf $(UI_CHECK_DIR)/store + FAKE_STORE_DIR=$(UI_CHECK_DIR)/store FAKE_STORE_FAIL=memory $(UIPREVIEW) --root $(UI_CHECK_DIR) --quiet --store-helper $(CURDIR)/tests/fake-rsos-store.sh --keys "start down down down down down down down down a sleep:500 wait:1500 down down a sleep:800 wait:1500 a wait:300 a sleep:1500 wait:1500 expect:dialog:Preparing_the_game_needs_more_free_memory." + rm -rf $(UI_CHECK_DIR)/store @echo "check-ui: game options act on their game after Favorite re-sorts the list (review F-H4)" rm -rf $(UI_CHECK_DIR)-games && mkdir -p $(UI_CHECK_DIR)-games/data/roms/nes \ $(UI_CHECK_DIR)-games/data/rsos $(UI_CHECK_DIR)-games/usr/share/rsos/cores @@ -595,6 +615,38 @@ check-frontend: $(FRONTEND) $(HOST_TESTCORE) $(SPLASH) grep -q 'crashed' $(FE_LOG) grep -q 'signal 15: exiting' $(FE_LOG) grep -q 'exit 0 after' $(FE_LOG) + @echo "check-frontend: 2a. a native game: its script runs in its folder, HOME on /data, SDL on KMS" + @# the native games only: the menu starts on them + mv $(FE_CHECK_DIR)/data/roms/nes $(FE_CHECK_DIR)/data/nes.aside + rm -f $(FE_CHECK_DIR)/data/rsos/cache/systems.idx + printf 'language = en\nlast_system = native\n' > $(FE_SETTINGS) + rm -f $(FE_LOG) + mkdir -p $(FE_CHECK_DIR)/data/roms/native/files + printf 'echo "$$PWD|$$HOME|$$SDL_VIDEODRIVER|$$RSOS_GAME_DIR" > files/ran.txt\nexit $${RSOS_TEST_NATIVE_EXIT:-0}\n' \ + > "$(FE_CHECK_DIR)/data/roms/native/Native Test.sh" + $(FE_RUN) --script "wait:600 a wait:500 a wait:1500 shot:$(FE_CHECK_DIR)/native.png term" + grep -q 'launch native Native Test' $(FE_LOG) + grep -q 'native game ended: 0' $(FE_LOG) + test "$$(cat $(FE_CHECK_DIR)/data/roms/native/files/ran.txt)" = \ + "$(FE_CHECK_DIR)/data/roms/native|$(FE_CHECK_DIR)/data/rsos/native-home|kmsdrm|$(FE_CHECK_DIR)/data/roms/native" + grep -q '^=== \[.*\] launch native: .*Native Test.sh' $(FE_GAME_LOG) + @echo "check-frontend: 2b. a native game that fails: its exit code is shown" + printf 'language = en\nlast_system = native\n' > $(FE_SETTINGS) + rm -f $(FE_LOG) + RSOS_TEST_NATIVE_EXIT=3 $(FE_RUN) --script "wait:600 a wait:500 a wait:1500 term" + grep -q 'native game ended: 3' $(FE_LOG) + @echo "check-frontend: 2c. the menu stops: the native game and what it started go too" + printf 'language = en\nlast_system = native\n' > $(FE_SETTINGS) + rm -f $(FE_LOG) $(FE_CHECK_DIR)/data/roms/native/files/bg.pid + printf 'sleep 300 &\necho $$! > files/bg.pid\nwait\n' > "$(FE_CHECK_DIR)/data/roms/native/Native Test.sh" + $(FE_RUN) --script "wait:600 a wait:500 a game:wait:1000 game:term" + grep -q 'signal 15: asking the game to quit' $(FE_LOG) + grep -q 'native game ended: 143' $(FE_LOG) + test -s $(FE_CHECK_DIR)/data/roms/native/files/bg.pid + ! kill -0 $$(cat $(FE_CHECK_DIR)/data/roms/native/files/bg.pid) 2> /dev/null + rm -rf $(FE_CHECK_DIR)/data/roms/native + mv $(FE_CHECK_DIR)/data/nes.aside $(FE_CHECK_DIR)/data/roms/nes + rm -f $(FE_CHECK_DIR)/data/rsos/cache/systems.idx @echo "check-frontend: 3. charge mode, charger already unplugged: power-off" rm -f $(FE_LOG) printf 'charger\n' > $(FE_CHECK_DIR)/run/rsos/bootreason diff --git a/frontend/assets/store.pub b/frontend/assets/store.pub new file mode 100644 index 0000000..f6893bf --- /dev/null +++ b/frontend/assets/store.pub @@ -0,0 +1,2 @@ +untrusted comment: RetroStoneOS game store catalog key public key +RWQArwxCK1FtKkksuMmujN8738kLFofDNosbAY+2Y2jPiaNnt5Rih2FA diff --git a/frontend/po/rsos.pot b/frontend/po/rsos.pot index 99f0d5f..d400ba4 100644 --- a/frontend/po/rsos.pot +++ b/frontend/po/rsos.pot @@ -71,7 +71,7 @@ msgid "%s needs %s in %s" msgstr "" #. TRANSLATORS: toast over the last game picture while the saves are written -#: src/host/host.c:431 src/ui/ui.c:1680 +#: src/host/host.c:431 src/ui/ui.c:1682 msgid "Powering off..." msgstr "" @@ -80,7 +80,7 @@ msgid "Player 1 controller disconnected: paused" msgstr "" #. TRANSLATORS: toast; %s is the controller's name -#: src/host/host.c:766 src/ui/ui.c:1224 +#: src/host/host.c:766 src/ui/ui.c:1226 #, c-format msgid "Player 1: %s" msgstr "" @@ -157,7 +157,7 @@ msgstr "" #. TRANSLATORS: shown 10 s before the automatic power-off (no input #. for the time set in Settings > Power); any button cancels it -#: src/host/host.c:1293 src/ui/ui.c:1696 src/ui/ui.c:1703 +#: src/host/host.c:1293 src/ui/ui.c:1698 src/ui/ui.c:1705 msgid "Powering off in 10 s — press any button to cancel" msgstr "" @@ -266,63 +266,63 @@ msgstr "" msgid "No GPU found (lima)" msgstr "" -#: src/host/launch.c:322 +#: src/host/launch.c:427 msgid "The game was stopped" msgstr "" #. TRANSLATORS: shown by the menu after a crash; %s is the #. signal name in English ("Segmentation fault") -#: src/host/launch.c:327 +#: src/host/launch.c:432 #, c-format msgid "The emulator crashed (%s). Game saves up to a few seconds ago are kept." msgstr "" -#: src/host/launch.c:343 +#: src/host/launch.c:448 msgid "Could not start the game" msgstr "" -#: src/host/launch.c:356 +#: src/host/launch.c:461 msgid "The emulator stopped responding. Game saves up to a few seconds ago are kept." msgstr "" -#: src/host/launch.c:360 +#: src/host/launch.c:465 msgid "Cannot start the game process" msgstr "" -#: src/host/launch.c:365 +#: src/host/launch.c:470 #, c-format msgid "The emulator failed (code %d)" msgstr "" #. TRANSLATORS: in-game menu > Scaling values (right-aligned on a 640 px row) -#: src/host/menu.c:110 src/ui/screens.c:2776 src/ui/screens.c:2780 +#: src/host/menu.c:110 src/ui/screens.c:2973 src/ui/screens.c:2977 msgctxt "scaling" msgid "Integer" msgstr "" -#: src/host/menu.c:111 src/ui/screens.c:2781 +#: src/host/menu.c:111 src/ui/screens.c:2978 msgctxt "scaling" msgid "Stretch" msgstr "" -#: src/host/menu.c:111 src/ui/screens.c:2777 src/ui/screens.c:2779 +#: src/host/menu.c:111 src/ui/screens.c:2974 src/ui/screens.c:2976 msgctxt "scaling" msgid "Aspect" msgstr "" #. TRANSLATORS: in-game menu > CPU profile values: the emulator's own #. setting / full speed / slower and cooler, saves battery -#: src/host/menu.c:126 src/ui/screens.c:2789 +#: src/host/menu.c:126 src/ui/screens.c:2986 msgctxt "cpu profile" msgid "Performance" msgstr "" -#: src/host/menu.c:127 src/ui/screens.c:2790 +#: src/host/menu.c:127 src/ui/screens.c:2987 msgctxt "cpu profile" msgid "Battery saver" msgstr "" -#: src/host/menu.c:127 src/ui/screens.c:2788 +#: src/host/menu.c:127 src/ui/screens.c:2985 msgctxt "cpu profile" msgid "Automatic" msgstr "" @@ -415,13 +415,13 @@ msgid "Core options" msgstr "" #. TRANSLATORS: game options: how the picture fills the screen, for this game -#: src/host/menu.c:218 src/ui/screens.c:2786 +#: src/host/menu.c:218 src/ui/screens.c:2983 msgid "Scaling" msgstr "" #. TRANSLATORS: in-game menu: how fast the processor runs for this game #. TRANSLATORS: game options: how fast the processor runs for this game -#: src/host/menu.c:222 src/ui/screens.c:2796 +#: src/host/menu.c:222 src/ui/screens.c:2993 msgid "CPU profile" msgstr "" @@ -437,7 +437,7 @@ msgstr "" msgid "Benchmark this game" msgstr "" -#: src/host/menu.c:231 src/host/menu.c:389 src/ui/screens.c:754 src/ui/screens.c:1887 +#: src/host/menu.c:231 src/host/menu.c:389 src/ui/screens.c:896 src/ui/screens.c:2037 msgid "Controls" msgstr "" @@ -459,7 +459,7 @@ msgid "Reset to defaults" msgstr "" #. TRANSLATORS: in-game menu > Controls: the row of a player -#: src/host/menu.c:259 src/ui/screens.c:771 +#: src/host/menu.c:259 src/ui/screens.c:913 #, c-format msgid "Player %d" msgstr "" @@ -746,68 +746,79 @@ msgctxt "strftime" msgid "%Y-%m-%d %H:%M" msgstr "" -#: src/main.c:1195 +#: src/main.c:1198 msgid "The screen refused this refresh rate" msgstr "" -#: src/main.c:2327 -msgid "No emulator is installed for this game." -msgstr "" - -#: src/main.c:2334 -msgid "This game cannot start (missing BIOS?)." +#: src/main.c:2390 +msgid "This game cannot start: its launch script is missing." msgstr "" #. TRANSLATORS: %s is a system error message (in English) -#: src/main.c:2514 +#: src/main.c:2483 src/main.c:2712 #, c-format msgid "Cannot start the game process (%s)." msgstr "" +#. TRANSLATORS: a native game (no emulator) ended with an +#. error; %d is its exit code +#: src/main.c:2493 +#, c-format +msgid "The game ended with an error (%d). Its messages are in rsos/logs on the SD card." +msgstr "" + +#: src/main.c:2525 +msgid "No emulator is installed for this game." +msgstr "" + +#: src/main.c:2532 +msgid "This game cannot start (missing BIOS?)." +msgstr "" + #. TRANSLATORS: the automatic power-off (no input for a while) #. was stopped because the game's state could not be saved -#: src/main.c:2529 +#: src/main.c:2727 msgid "Automatic power-off cancelled: the game could not be saved." msgstr "" -#: src/main.c:2541 src/ui/ui.c:586 +#: src/main.c:2739 src/ui/ui.c:588 msgid "The game could not be started." msgstr "" #. TRANSLATORS: boot message: the SD card's data partition (games, saves) -#: src/main.c:2626 +#: src/main.c:2824 msgid "The data partition could not be restored. Your games and saves may need to be copied again." msgstr "" -#: src/main.c:2630 +#: src/main.c:2828 msgid "The data partition was unreadable and was reformatted." msgstr "" -#: src/main.c:2633 +#: src/main.c:2831 msgid "The data partition has errors: saving may fail. Back up your saves." msgstr "" #. TRANSLATORS: boot toast: the SD card's data partition is mounted read-only #. (its first-boot setup finishes at the next start) -#: src/main.c:2641 +#: src/main.c:2839 msgid "Storage is read-only until the console restarts" msgstr "" -#: src/main.c:2646 +#: src/main.c:2844 msgid "The last update didn't start; the previous version was restored." msgstr "" -#: src/main.c:2652 +#: src/main.c:2850 msgid "The SD card was checked after an unexpected power loss" msgstr "" #. TRANSLATORS: boot screen under the logo (first start, or after an update) -#: src/main.c:2924 +#: src/main.c:3122 msgid "Preparing the SD card, please wait..." msgstr "" #. TRANSLATORS: boot screen under the logo, after the power was cut -#: src/main.c:2926 +#: src/main.c:3124 msgid "Checking the SD card, please wait..." msgstr "" @@ -835,7 +846,9 @@ msgstr "" msgid "connecting..." msgstr "" -#: src/ui/bt_ui.c:142 src/ui/bt_ui.c:201 src/ui/screens.c:819 +#. TRANSLATORS: Game store: a game is being installed or removed +#: src/ui/bt_ui.c:142 src/ui/bt_ui.c:201 src/ui/screens.c:968 src/ui/store_ui.c:241 +#: src/ui/store_ui.c:731 msgid "please wait..." msgstr "" @@ -848,7 +861,8 @@ msgstr "" msgid "Searching..." msgstr "" -#: src/ui/bt_ui.c:205 src/ui/screens.c:846 src/ui/update_ui.c:930 +#: src/ui/bt_ui.c:205 src/ui/screens.c:995 src/ui/store_ui.c:396 src/ui/store_ui.c:418 +#: src/ui/update_ui.c:930 #, c-format msgid "Cannot run %s" msgstr "" @@ -875,17 +889,17 @@ msgstr "" #. TRANSLATORS: dialog buttons, uppercase, short (CANCEL is selected) #. TRANSLATORS: dialog button, uppercase, short -#: src/ui/bt_ui.c:246 src/ui/screens.c:2476 src/ui/screens.c:2991 src/ui/storage.c:1037 +#: src/ui/bt_ui.c:246 src/ui/screens.c:2671 src/ui/screens.c:3188 src/ui/storage.c:1037 #: src/ui/storage.c:1067 src/ui/storage.c:1075 src/ui/storage.c:1122 src/ui/storage.c:1179 -#: src/ui/storage.c:1192 src/ui/storage.c:1204 src/ui/storage.c:1338 src/ui/update_ui.c:535 -#: src/ui/update_ui.c:973 +#: src/ui/storage.c:1192 src/ui/storage.c:1204 src/ui/storage.c:1338 src/ui/store_ui.c:632 +#: src/ui/store_ui.c:701 src/ui/update_ui.c:535 src/ui/update_ui.c:973 msgid "CANCEL" msgstr "" #. TRANSLATORS: Settings > Network: the Bluetooth pairing screen #. TRANSLATORS: Settings > Network, under the Bluetooth switch: pair #. and connect Bluetooth controllers -#: src/ui/bt_ui.c:263 src/ui/screens.c:1008 +#: src/ui/bt_ui.c:263 src/ui/screens.c:1157 msgid "Bluetooth devices" msgstr "" @@ -909,33 +923,33 @@ msgstr "" msgid "%s forgotten" msgstr "" -#: src/ui/bt_ui.c:317 src/ui/bt_ui.c:321 src/ui/screens.c:1072 src/ui/transfer_ui.c:1908 +#: src/ui/bt_ui.c:317 src/ui/bt_ui.c:321 src/ui/screens.c:1221 src/ui/transfer_ui.c:1908 msgid "failed" msgstr "" #. TRANSLATORS: the favorite games collection in the system carousel #. (big text, uppercase in the built-in themes) and its list header -#: src/ui/loader.c:589 +#: src/ui/loader.c:636 msgid "Favorites" msgstr "" #. TRANSLATORS: the recently played games collection in the system #. carousel (big text, uppercase in the built-in themes) and its list header -#: src/ui/loader.c:593 +#: src/ui/loader.c:640 msgid "Last played" msgstr "" #. TRANSLATORS: toast when a system opened from the carousel has no #. game any more (removed while the console was off) -#: src/ui/loader.c:1348 +#: src/ui/loader.c:1395 msgid "No games found any more in this folder" msgstr "" #. TRANSLATORS: help bar at the bottom of the screen: one short word each #. TRANSLATORS: first-boot language picker: help bar, one short word each #. TRANSLATORS: help bar labels (uppercase, short: ~10 characters) -#: src/ui/menu.c:99 src/ui/menu.c:471 src/ui/menu.c:474 src/ui/screens.c:1988 -#: src/ui/screens.c:2868 src/ui/storage.c:560 src/ui/view_gamelist.c:1005 +#: src/ui/menu.c:99 src/ui/menu.c:471 src/ui/menu.c:474 src/ui/screens.c:2141 +#: src/ui/screens.c:3065 src/ui/storage.c:560 src/ui/view_gamelist.c:1005 #: src/ui/view_system.c:115 src/ui/view_system.c:119 msgid "choose" msgstr "" @@ -944,7 +958,7 @@ msgstr "" msgid "change" msgstr "" -#: src/ui/menu.c:99 src/ui/menu.c:471 src/ui/menu.c:474 src/ui/screens.c:2868 +#: src/ui/menu.c:99 src/ui/menu.c:471 src/ui/menu.c:474 src/ui/screens.c:3065 #: src/ui/storage.c:560 src/ui/view_system.c:115 src/ui/view_system.c:119 msgid "select" msgstr "" @@ -956,7 +970,7 @@ msgstr "" #. TRANSLATORS: dialog button, uppercase, short #. TRANSLATORS: storage task page button -#: src/ui/menu.c:633 src/ui/screens.c:1988 src/ui/storage.c:525 src/ui/transfer_ui.c:279 +#: src/ui/menu.c:633 src/ui/screens.c:2141 src/ui/storage.c:525 src/ui/transfer_ui.c:279 msgid "OK" msgstr "" @@ -1027,7 +1041,7 @@ msgstr "" #. TRANSLATORS: game list style: automatic, a plain list, list + picture and details #. TRANSLATORS: how the battery level is measured: automatic, from the voltage, #. or the power chip's (AXP) fuel gauge -#: src/ui/screens.c:66 src/ui/screens.c:1564 +#: src/ui/screens.c:66 src/ui/screens.c:1713 msgid "Automatic" msgstr "" @@ -1074,7 +1088,7 @@ msgstr "" msgid "External" msgstr "" -#: src/ui/screens.c:106 src/ui/ui.c:450 src/ui/ui.c:680 +#: src/ui/screens.c:106 src/ui/ui.c:451 src/ui/ui.c:682 msgid "Could not save the settings" msgstr "" @@ -1109,11 +1123,11 @@ msgid "" "Keep this setting? Reverting in %d s" msgstr "" -#: src/ui/screens.c:279 src/ui/screens.c:1531 src/ui/screens.c:1886 +#: src/ui/screens.c:279 src/ui/screens.c:1680 src/ui/screens.c:2036 msgid "Display" msgstr "" -#: src/ui/screens.c:285 src/ui/ui.c:1426 +#: src/ui/screens.c:285 src/ui/ui.c:1428 msgid "Brightness" msgstr "" @@ -1141,7 +1155,7 @@ msgstr "" msgid "Battery position" msgstr "" -#: src/ui/screens.c:342 src/ui/screens.c:757 +#: src/ui/screens.c:342 src/ui/screens.c:899 msgid "Button test" msgstr "" @@ -1154,575 +1168,694 @@ msgid "Hold SELECT + START to exit" msgstr "" #. TRANSLATORS: controller set-up wizard: what to press now (big text, one line) -#: src/ui/screens.c:480 +#: src/ui/screens.c:486 src/ui/screens.c:511 src/ui/screens.c:532 msgid "Press D-pad UP" msgstr "" -#: src/ui/screens.c:481 +#: src/ui/screens.c:487 src/ui/screens.c:512 src/ui/screens.c:533 msgid "Press D-pad DOWN" msgstr "" -#: src/ui/screens.c:482 +#: src/ui/screens.c:488 src/ui/screens.c:513 src/ui/screens.c:534 msgid "Press D-pad LEFT" msgstr "" -#: src/ui/screens.c:483 +#: src/ui/screens.c:489 src/ui/screens.c:514 src/ui/screens.c:535 msgid "Press D-pad RIGHT" msgstr "" -#: src/ui/screens.c:484 +#: src/ui/screens.c:490 msgid "Press the RIGHT face button (A)" msgstr "" -#: src/ui/screens.c:485 +#: src/ui/screens.c:491 msgid "Press the BOTTOM face button (B)" msgstr "" -#: src/ui/screens.c:486 +#: src/ui/screens.c:492 msgid "Press the TOP face button (X)" msgstr "" -#: src/ui/screens.c:487 +#: src/ui/screens.c:493 msgid "Press the LEFT face button (Y)" msgstr "" -#: src/ui/screens.c:488 +#: src/ui/screens.c:494 msgid "Press L1" msgstr "" -#: src/ui/screens.c:489 +#: src/ui/screens.c:495 msgid "Press R1" msgstr "" -#: src/ui/screens.c:490 +#: src/ui/screens.c:496 msgid "Press L2" msgstr "" -#: src/ui/screens.c:491 +#: src/ui/screens.c:497 msgid "Press R2" msgstr "" -#: src/ui/screens.c:492 +#: src/ui/screens.c:498 msgid "Press SELECT" msgstr "" -#: src/ui/screens.c:493 +#: src/ui/screens.c:499 src/ui/screens.c:520 src/ui/screens.c:543 msgid "Press START" msgstr "" -#: src/ui/screens.c:494 +#: src/ui/screens.c:500 msgid "Press the left stick (L3)" msgstr "" -#: src/ui/screens.c:495 +#: src/ui/screens.c:501 msgid "Press the right stick (R3)" msgstr "" -#: src/ui/screens.c:496 +#: src/ui/screens.c:502 msgid "Push the left stick RIGHT" msgstr "" -#: src/ui/screens.c:497 +#: src/ui/screens.c:503 msgid "Push the left stick DOWN" msgstr "" -#: src/ui/screens.c:498 +#: src/ui/screens.c:504 msgid "Push the right stick RIGHT" msgstr "" -#: src/ui/screens.c:499 +#: src/ui/screens.c:505 msgid "Push the right stick DOWN" msgstr "" -#: src/ui/screens.c:528 -msgid "Configure controller" +#: src/ui/screens.c:515 +msgid "Press A" +msgstr "" + +#: src/ui/screens.c:516 src/ui/screens.c:537 +msgid "Press B" +msgstr "" + +#: src/ui/screens.c:517 +msgid "Press Z (the trigger underneath)" +msgstr "" + +#: src/ui/screens.c:518 +msgid "Press L" +msgstr "" + +#: src/ui/screens.c:519 +msgid "Press R" +msgstr "" + +#: src/ui/screens.c:521 +msgid "Press C-UP" +msgstr "" + +#: src/ui/screens.c:522 +msgid "Press C-DOWN" +msgstr "" + +#: src/ui/screens.c:523 +msgid "Press C-LEFT" +msgstr "" + +#: src/ui/screens.c:524 +msgid "Press C-RIGHT" +msgstr "" + +#: src/ui/screens.c:525 src/ui/screens.c:544 +msgid "Push the stick RIGHT" +msgstr "" + +#: src/ui/screens.c:526 src/ui/screens.c:545 +msgid "Push the stick DOWN" msgstr "" #: src/ui/screens.c:536 +msgid "Press A (the big button)" +msgstr "" + +#: src/ui/screens.c:538 +msgid "Press X" +msgstr "" + +#: src/ui/screens.c:539 +msgid "Press Y" +msgstr "" + +#: src/ui/screens.c:540 +msgid "Press Z" +msgstr "" + +#: src/ui/screens.c:541 +msgid "Press L all the way" +msgstr "" + +#: src/ui/screens.c:542 +msgid "Press R all the way" +msgstr "" + +#: src/ui/screens.c:546 +msgid "Push the C stick RIGHT" +msgstr "" + +#: src/ui/screens.c:547 +msgid "Push the C stick DOWN" +msgstr "" + +#: src/ui/screens.c:580 +msgid "Configure controller" +msgstr "" + +#: src/ui/screens.c:588 #, c-format msgid "Step %d of %d" msgstr "" -#: src/ui/screens.c:539 +#. TRANSLATORS: controller wizard; %d is seconds +#: src/ui/screens.c:592 #, c-format -msgid "Not on this pad? Wait %d s to skip" +msgid "Not on this pad? Press a button already set, or wait %d s" msgstr "" -#: src/ui/screens.c:565 +#: src/ui/screens.c:625 msgid "Controller saved" msgstr "" -#: src/ui/screens.c:567 +#: src/ui/screens.c:627 msgid "The mapping could not be saved." msgstr "" -#: src/ui/screens.c:677 src/ui/screens.c:758 -msgid "Configure a controller" +#. TRANSLATORS: toast after removing a controller's own set-up +#: src/ui/screens.c:769 +msgid "Controller set up automatically again" +msgstr "" + +#. TRANSLATORS: controller set-up: the first question, a menu title +#: src/ui/screens.c:779 +msgid "What kind of controller is it?" +msgstr "" + +#. TRANSLATORS: kinds of controller (menu entries) +#: src/ui/screens.c:786 +msgid "SNES, Xbox, PlayStation, Switch or similar" msgstr "" -#. TRANSLATORS: how a controller is set up: your own mapping, from the -#. database of known pads, the Linux standard, a keyboard, none -#: src/ui/screens.c:692 +#: src/ui/screens.c:787 +msgid "Nintendo 64" +msgstr "" + +#: src/ui/screens.c:788 src/ui/screens.c:810 +msgid "GameCube" +msgstr "" + +#. TRANSLATORS: controller set-up: remove your own set-up of this +#. controller and use the automatic one (or none) +#: src/ui/screens.c:792 +msgid "Forget my set-up (automatic)" +msgstr "" + +#. TRANSLATORS: how a controller is set up (the value next to its name): +#. your own mapping of an N64 / GameCube / other pad, a known N64 / +#. GameCube / other pad, the Linux standard, a keyboard, none +#: src/ui/screens.c:808 +msgid "N64, custom" +msgstr "" + +#: src/ui/screens.c:808 +msgid "N64" +msgstr "" + +#: src/ui/screens.c:810 +msgid "GameCube, custom" +msgstr "" + +#: src/ui/screens.c:811 msgid "custom" msgstr "" -#: src/ui/screens.c:693 +#: src/ui/screens.c:811 msgid "known pad" msgstr "" -#: src/ui/screens.c:694 +#: src/ui/screens.c:812 msgid "standard" msgstr "" -#: src/ui/screens.c:695 +#: src/ui/screens.c:813 msgid "keyboard" msgstr "" -#: src/ui/screens.c:695 +#: src/ui/screens.c:813 msgid "not configured" msgstr "" -#: src/ui/screens.c:700 +#: src/ui/screens.c:825 src/ui/screens.c:900 +msgid "Configure a controller" +msgstr "" + +#: src/ui/screens.c:842 msgid "No external controller detected" msgstr "" -#: src/ui/screens.c:715 +#: src/ui/screens.c:857 msgid "built-in" msgstr "" -#: src/ui/screens.c:759 +#: src/ui/screens.c:901 msgid "Player 1" msgstr "" -#: src/ui/screens.c:761 +#: src/ui/screens.c:903 msgid "Extra C/Z buttons fitted" msgstr "" #. TRANSLATORS: Settings > Controls: games can make the USB or Bluetooth #. controllers that have motors vibrate (on/off) -#: src/ui/screens.c:765 +#: src/ui/screens.c:907 msgid "Controller vibration" msgstr "" -#: src/ui/screens.c:767 +#: src/ui/screens.c:909 msgid "Players" msgstr "" #. TRANSLATORS: "stop when idle for": durations, and never -#: src/ui/screens.c:784 src/ui/screens.c:1556 src/ui/screens.c:1559 +#: src/ui/screens.c:926 src/ui/screens.c:1705 src/ui/screens.c:1708 msgid "10 min" msgstr "" -#: src/ui/screens.c:784 src/ui/screens.c:1560 +#: src/ui/screens.c:926 src/ui/screens.c:1709 msgid "30 min" msgstr "" -#: src/ui/screens.c:784 +#: src/ui/screens.c:926 msgid "1 hour" msgstr "" #. TRANSLATORS: dim / turn off the screen after: never, or minutes -#: src/ui/screens.c:784 src/ui/screens.c:1202 src/ui/screens.c:1554 src/ui/screens.c:1556 -#: src/ui/screens.c:1559 +#: src/ui/screens.c:926 src/ui/screens.c:1351 src/ui/screens.c:1703 src/ui/screens.c:1705 +#: src/ui/screens.c:1708 msgid "Never" msgstr "" -#: src/ui/screens.c:824 +#: src/ui/screens.c:973 msgid "not set" msgstr "" #. TRANSLATORS: the network transfer is on -#: src/ui/screens.c:830 +#: src/ui/screens.c:979 msgid "running" msgstr "" -#: src/ui/screens.c:839 +#: src/ui/screens.c:988 msgid "WiFi: turning off, please wait..." msgstr "" -#: src/ui/screens.c:839 +#: src/ui/screens.c:988 msgid "Ethernet: turning off, please wait..." msgstr "" -#: src/ui/screens.c:840 +#: src/ui/screens.c:989 msgid "Bluetooth: turning off, please wait..." msgstr "" #. TRANSLATORS: toast: WiFi is being turned on for the update check -#: src/ui/screens.c:841 src/ui/update_ui.c:936 +#: src/ui/screens.c:990 src/ui/update_ui.c:936 msgid "WiFi: turning on, please wait..." msgstr "" -#: src/ui/screens.c:841 +#: src/ui/screens.c:990 msgid "Ethernet: turning on, please wait..." msgstr "" -#: src/ui/screens.c:842 +#: src/ui/screens.c:991 msgid "Bluetooth: turning on, please wait..." msgstr "" -#: src/ui/screens.c:881 src/ui/screens.c:903 +#: src/ui/screens.c:1030 src/ui/screens.c:1052 msgid "Could not save the WiFi settings" msgstr "" -#: src/ui/screens.c:894 +#: src/ui/screens.c:1043 msgid "A WiFi password has at least 8 characters." msgstr "" -#: src/ui/screens.c:899 +#: src/ui/screens.c:1048 msgid "Set the network name first." msgstr "" -#: src/ui/screens.c:917 +#: src/ui/screens.c:1066 msgid "WiFi password saved" msgstr "" -#: src/ui/screens.c:937 +#: src/ui/screens.c:1086 msgid "WiFi network name" msgstr "" -#: src/ui/screens.c:942 src/ui/screens.c:1002 +#: src/ui/screens.c:1091 src/ui/screens.c:1151 msgid "WiFi password" msgstr "" -#: src/ui/screens.c:950 src/ui/screens.c:1014 +#: src/ui/screens.c:1099 src/ui/screens.c:1163 msgid "Console name" msgstr "" -#: src/ui/screens.c:989 +#: src/ui/screens.c:1138 msgid "Use letters, digits and dashes." msgstr "" -#: src/ui/screens.c:993 +#: src/ui/screens.c:1142 #, c-format msgid "Console name: %s (next transfer)" msgstr "" #. TRANSLATORS: the wireless network ("Wi-Fi" in French, "WLAN" in German) -#: src/ui/screens.c:1000 +#: src/ui/screens.c:1149 msgid "WiFi" msgstr "" -#: src/ui/screens.c:1001 +#: src/ui/screens.c:1150 msgid "WiFi network" msgstr "" -#: src/ui/screens.c:1012 +#: src/ui/screens.c:1161 msgid "Transfer games from a computer or phone" msgstr "" #. TRANSLATORS: screen title (the Settings > Network row of the same name) -#: src/ui/screens.c:1013 src/ui/transfer_ui.c:2053 +#: src/ui/screens.c:1162 src/ui/transfer_ui.c:2053 msgid "Transfer over network" msgstr "" -#: src/ui/screens.c:1015 +#: src/ui/screens.c:1164 msgid "Stop when idle for" msgstr "" -#: src/ui/screens.c:1018 +#: src/ui/screens.c:1167 msgid "Keep receiving in the background" msgstr "" #. TRANSLATORS: Settings > Network: also share the SD card as a #. Windows network folder (\\RETROSTONE) while "Transfer over #. network" runs -#: src/ui/screens.c:1027 +#: src/ui/screens.c:1176 msgid "Windows file share" msgstr "" -#: src/ui/screens.c:1035 src/ui/screens.c:1888 +#: src/ui/screens.c:1184 src/ui/screens.c:2038 msgid "Network" msgstr "" -#: src/ui/screens.c:1062 +#: src/ui/screens.c:1211 msgid "WiFi off" msgstr "" -#: src/ui/screens.c:1062 +#: src/ui/screens.c:1211 msgid "Ethernet off" msgstr "" -#: src/ui/screens.c:1062 +#: src/ui/screens.c:1211 msgid "Bluetooth off" msgstr "" -#: src/ui/screens.c:1063 +#: src/ui/screens.c:1212 msgid "WiFi on" msgstr "" -#: src/ui/screens.c:1063 +#: src/ui/screens.c:1212 msgid "Ethernet on" msgstr "" -#: src/ui/screens.c:1063 +#: src/ui/screens.c:1212 msgid "Bluetooth on" msgstr "" -#: src/ui/screens.c:1102 src/ui/screens.c:1889 +#: src/ui/screens.c:1251 src/ui/screens.c:2039 msgid "Theme" msgstr "" -#: src/ui/screens.c:1113 +#: src/ui/screens.c:1262 msgid "No theme found" msgstr "" #. TRANSLATORS: Settings > Game lists > Sort games by: alphabetical, the most #. played first (play time), the most recently played first -#: src/ui/screens.c:1123 +#: src/ui/screens.c:1272 msgid "Name" msgstr "" -#: src/ui/screens.c:1123 +#: src/ui/screens.c:1272 msgid "Most played" msgstr "" -#: src/ui/screens.c:1123 +#: src/ui/screens.c:1272 msgid "Recently played" msgstr "" -#: src/ui/screens.c:1148 +#: src/ui/screens.c:1297 msgid "Game lists refreshed" msgstr "" -#: src/ui/screens.c:1164 src/ui/screens.c:1890 +#: src/ui/screens.c:1313 src/ui/screens.c:2040 msgid "Game lists" msgstr "" -#: src/ui/screens.c:1167 +#: src/ui/screens.c:1316 msgid "Favorites first" msgstr "" -#: src/ui/screens.c:1169 +#: src/ui/screens.c:1318 msgid "Favorites & last played pages" msgstr "" #. TRANSLATORS: Settings > Game lists: the order of the games in a list -#: src/ui/screens.c:1172 +#: src/ui/screens.c:1321 msgid "Sort games by" msgstr "" #. TRANSLATORS: Settings > Game lists: also list the games hidden with #. "Hide this game" (or in gamelist.xml) -#: src/ui/screens.c:1176 +#: src/ui/screens.c:1325 msgid "Show hidden games" msgstr "" -#: src/ui/screens.c:1178 +#: src/ui/screens.c:1327 msgid "Refresh game lists" msgstr "" #. TRANSLATORS: Settings > Game lists: box pictures from the libretro thumbnail server -#: src/ui/screens.c:1180 +#: src/ui/screens.c:1329 msgid "Download game covers" msgstr "" #. TRANSLATORS: Settings > Game lists: one entry per multi-disc game (.m3u playlists) -#: src/ui/screens.c:1182 +#: src/ui/screens.c:1331 msgid "Group multi-disc games" msgstr "" #. TRANSLATORS: what launching a game that has an automatic save does -#: src/ui/screens.c:1195 src/ui/screens.c:1202 +#: src/ui/screens.c:1344 src/ui/screens.c:1351 msgid "Ask" msgstr "" -#: src/ui/screens.c:1195 +#: src/ui/screens.c:1344 msgid "Always resume" msgstr "" -#: src/ui/screens.c:1195 +#: src/ui/screens.c:1344 msgid "Always start fresh" msgstr "" #. TRANSLATORS: Settings > Games > Resume on boot: relaunch the game without #. asking / ask / never (the menu comes up) -#: src/ui/screens.c:1202 +#: src/ui/screens.c:1351 msgid "Always" msgstr "" #. TRANSLATORS: toggle: copy the games -#: src/ui/screens.c:1229 src/ui/screens.c:1532 src/ui/screens.c:1891 src/ui/transfer_ui.c:701 +#: src/ui/screens.c:1378 src/ui/screens.c:1681 src/ui/screens.c:2041 src/ui/transfer_ui.c:701 msgid "Games" msgstr "" -#: src/ui/screens.c:1232 +#: src/ui/screens.c:1381 msgid "Resume games" msgstr "" -#: src/ui/screens.c:1233 +#: src/ui/screens.c:1382 msgid "Auto-save on exit" msgstr "" -#: src/ui/screens.c:1235 +#: src/ui/screens.c:1384 msgid "On launch" msgstr "" #. TRANSLATORS: Settings > Games: what happens at start-up after the #. console was turned off during a game -#: src/ui/screens.c:1240 +#: src/ui/screens.c:1389 msgid "Resume on boot" msgstr "" -#: src/ui/screens.c:1243 +#: src/ui/screens.c:1392 msgid "Powering off in a game always saves it" msgstr "" #. TRANSLATORS: Settings > Games: section of the in-game shortcuts -#: src/ui/screens.c:1245 +#: src/ui/screens.c:1394 msgid "In game" msgstr "" #. TRANSLATORS: Settings > Games: how fast SELECT + R2 runs the game -#: src/ui/screens.c:1247 +#: src/ui/screens.c:1396 msgid "Fast-forward speed" msgstr "" -#: src/ui/screens.c:1292 +#: src/ui/screens.c:1441 msgid "Could not update /boot/rsos.env." msgstr "" #. TRANSLATORS: dialog buttons, uppercase, short -#: src/ui/screens.c:1296 +#: src/ui/screens.c:1445 msgid "REBOOT NOW" msgstr "" -#: src/ui/screens.c:1297 src/ui/screens.c:1619 src/ui/storage.c:1137 src/ui/storage.c:1152 -#: src/ui/ui.c:1173 src/ui/update_ui.c:898 +#: src/ui/screens.c:1446 src/ui/screens.c:1768 src/ui/storage.c:1137 src/ui/storage.c:1152 +#: src/ui/ui.c:1175 src/ui/update_ui.c:898 msgid "LATER" msgstr "" -#: src/ui/screens.c:1299 +#: src/ui/screens.c:1448 msgid "Reboot required: the change applies at the next start." msgstr "" #. TRANSLATORS: storage: "12.5 GB free of 29.1 GB" -#: src/ui/screens.c:1329 src/ui/screens.c:1451 src/ui/storage.c:998 +#: src/ui/screens.c:1478 src/ui/screens.c:1600 src/ui/storage.c:998 #, c-format msgid "%s free of %s" msgstr "" -#: src/ui/screens.c:1354 +#: src/ui/screens.c:1503 msgid "Game storage" msgstr "" #. TRANSLATORS: a USB stick with no volume label and no vendor name -#: src/ui/screens.c:1356 src/ui/transfer_ui.c:184 src/ui/transfer_ui.c:805 +#: src/ui/screens.c:1505 src/ui/transfer_ui.c:184 src/ui/transfer_ui.c:805 #: src/ui/transfer_ui.c:1101 msgid "USB drive" msgstr "" -#: src/ui/screens.c:1357 +#: src/ui/screens.c:1506 msgid "Import games" msgstr "" -#: src/ui/screens.c:1358 +#: src/ui/screens.c:1507 msgid "Export games" msgstr "" -#: src/ui/screens.c:1359 +#: src/ui/screens.c:1508 msgid "Back up saves" msgstr "" -#: src/ui/screens.c:1360 +#: src/ui/screens.c:1509 msgid "Eject USB drive" msgstr "" -#: src/ui/screens.c:1361 +#: src/ui/screens.c:1510 msgid "Ask when a USB drive is plugged in" msgstr "" -#: src/ui/screens.c:1372 +#: src/ui/screens.c:1521 msgid "Advanced: off for a fast boot, restart needed" msgstr "" #. TRANSLATORS: toggle: make the eMMC visible (needs a restart) -#: src/ui/screens.c:1374 src/ui/storage.c:902 +#: src/ui/screens.c:1523 src/ui/storage.c:902 msgid "Internal eMMC" msgstr "" #. TRANSLATORS: toggle: make the M.2 slot work (needs a restart) -#: src/ui/screens.c:1378 src/ui/storage.c:962 +#: src/ui/screens.c:1527 src/ui/storage.c:962 msgid "M.2 SATA drive" msgstr "" -#: src/ui/screens.c:1385 src/ui/screens.c:1530 src/ui/screens.c:1892 +#: src/ui/screens.c:1534 src/ui/screens.c:1679 src/ui/screens.c:2042 msgid "Storage" msgstr "" -#: src/ui/screens.c:1410 +#: src/ui/screens.c:1559 msgid "no battery" msgstr "" #. TRANSLATORS: battery: percent, then the time until full: hours, minutes -#: src/ui/screens.c:1413 +#: src/ui/screens.c:1562 #, c-format msgid "%d %%, full in %d h %02d" msgstr "" #. TRANSLATORS: battery: percent, then about how long it lasts: hours, minutes -#: src/ui/screens.c:1417 +#: src/ui/screens.c:1566 #, c-format msgid "%d %%, about %d h %02d" msgstr "" -#: src/ui/screens.c:1420 +#: src/ui/screens.c:1569 #, c-format msgid "%d %%, charging" msgstr "" -#: src/ui/screens.c:1422 +#: src/ui/screens.c:1571 #, c-format msgid "%d %%, full" msgstr "" #. TRANSLATORS: battery percent ("80 %") -#: src/ui/screens.c:1425 +#: src/ui/screens.c:1574 #, c-format msgid "%d %%" msgstr "" #. TRANSLATORS: power source and battery voltage ("charger, 4.12 V") -#: src/ui/screens.c:1433 +#: src/ui/screens.c:1582 #, c-format msgid "charger, %s V" msgstr "" -#: src/ui/screens.c:1434 +#: src/ui/screens.c:1583 #, c-format msgid "battery, %s V" msgstr "" -#: src/ui/screens.c:1436 +#: src/ui/screens.c:1585 msgid "charger connected" msgstr "" -#: src/ui/screens.c:1436 +#: src/ui/screens.c:1585 msgid "battery" msgstr "" -#: src/ui/screens.c:1442 +#: src/ui/screens.c:1591 #, c-format msgid "%d °C (hot)" msgstr "" -#: src/ui/screens.c:1442 +#: src/ui/screens.c:1591 #, c-format msgid "%d °C" msgstr "" -#: src/ui/screens.c:1453 +#: src/ui/screens.c:1602 msgid "not mounted" msgstr "" #. TRANSLATORS: display: HDMI or LCD, then the menu's size in pixels -#: src/ui/screens.c:1458 +#: src/ui/screens.c:1607 #, c-format msgid "%s, UI %dx%d" msgstr "" #. TRANSLATORS: part of "3 systems, 120 games, 1.5 GB" -#: src/ui/screens.c:1469 src/ui/transfer_ui.c:572 +#: src/ui/screens.c:1618 src/ui/transfer_ui.c:572 #, c-format msgid "%d system" msgid_plural "%d systems" @@ -1730,7 +1863,7 @@ msgstr[0] "" msgstr[1] "" #. TRANSLATORS: "25 games in 3 systems": %s is the "3 systems" part -#: src/ui/screens.c:1471 +#: src/ui/screens.c:1620 #, c-format msgid "%d game in %s" msgid_plural "%d games in %s" @@ -1738,282 +1871,288 @@ msgstr[0] "" msgstr[1] "" #. TRANSLATORS: System information: the people who made RetroStoneOS -#: src/ui/screens.c:1484 src/ui/screens.c:1536 +#: src/ui/screens.c:1633 src/ui/screens.c:1685 msgid "Credits" msgstr "" #. TRANSLATORS: System information > Credits, when the list is missing -#: src/ui/screens.c:1502 +#: src/ui/screens.c:1651 msgid "No credits list on this system" msgstr "" -#: src/ui/screens.c:1515 src/ui/screens.c:1893 +#: src/ui/screens.c:1664 src/ui/screens.c:2043 msgid "System information" msgstr "" -#: src/ui/screens.c:1520 +#: src/ui/screens.c:1669 msgid "Version" msgstr "" #. TRANSLATORS: System information: RetroStone2 or RetroStone2 Pro #. TRANSLATORS: Settings > Storage: RetroStone2 or RetroStone2 Pro (found at the first start) -#: src/ui/screens.c:1524 src/ui/storage.c:881 +#: src/ui/screens.c:1673 src/ui/storage.c:881 msgid "Model" msgstr "" -#: src/ui/screens.c:1527 +#: src/ui/screens.c:1676 msgid "Battery" msgstr "" #. TRANSLATORS: where the power comes from (charger or battery) -#: src/ui/screens.c:1529 +#: src/ui/screens.c:1678 msgctxt "power source" msgid "Power" msgstr "" -#: src/ui/screens.c:1533 +#: src/ui/screens.c:1682 msgid "Input devices" msgstr "" -#: src/ui/screens.c:1534 +#: src/ui/screens.c:1683 msgid "CPU temperature" msgstr "" -#: src/ui/screens.c:1554 +#: src/ui/screens.c:1703 msgid "1 min" msgstr "" -#: src/ui/screens.c:1554 src/ui/screens.c:1556 +#: src/ui/screens.c:1703 src/ui/screens.c:1705 msgid "2 min" msgstr "" -#: src/ui/screens.c:1554 src/ui/screens.c:1556 src/ui/screens.c:1559 +#: src/ui/screens.c:1703 src/ui/screens.c:1705 src/ui/screens.c:1708 msgid "5 min" msgstr "" -#: src/ui/screens.c:1559 +#: src/ui/screens.c:1708 msgid "15 min" msgstr "" -#: src/ui/screens.c:1560 +#: src/ui/screens.c:1709 msgid "60 min" msgstr "" -#: src/ui/screens.c:1564 +#: src/ui/screens.c:1713 msgid "Voltage" msgstr "" -#: src/ui/screens.c:1564 +#: src/ui/screens.c:1713 msgid "AXP fuel gauge" msgstr "" #. TRANSLATORS: Settings > Power > Memory speed: the DRAM clock (normal 384 MHz, #. +12 % = 432 MHz, +25 % = 480 MHz) -#: src/ui/screens.c:1568 +#: src/ui/screens.c:1717 msgid "Normal" msgstr "" -#: src/ui/screens.c:1568 +#: src/ui/screens.c:1717 msgid "Faster (+12 %)" msgstr "" -#: src/ui/screens.c:1568 +#: src/ui/screens.c:1717 msgid "Fastest (+25 %)" msgstr "" #. TRANSLATORS: dialog buttons, uppercase, short -#: src/ui/screens.c:1591 src/ui/screens.c:2430 +#: src/ui/screens.c:1740 src/ui/screens.c:2625 msgid "YES" msgstr "" #. TRANSLATORS: dialog buttons, uppercase, short (NO is selected) -#: src/ui/screens.c:1592 src/ui/screens.c:2429 src/ui/screens.c:2600 +#: src/ui/screens.c:1741 src/ui/screens.c:2624 src/ui/screens.c:2795 msgid "NO" msgstr "" -#: src/ui/screens.c:1597 +#: src/ui/screens.c:1746 msgid "Restart the console?" msgstr "" -#: src/ui/screens.c:1602 +#: src/ui/screens.c:1751 msgid "Power off the console?" msgstr "" #. TRANSLATORS: dialog buttons, uppercase, short -#: src/ui/screens.c:1619 src/ui/storage.c:1137 src/ui/storage.c:1152 src/ui/update_ui.c:898 +#: src/ui/screens.c:1768 src/ui/storage.c:1137 src/ui/storage.c:1152 src/ui/update_ui.c:898 msgid "RESTART NOW" msgstr "" #. TRANSLATORS: Settings > Storage: the switch could not be saved -#: src/ui/screens.c:1622 src/ui/storage.c:795 src/ui/storage.c:1140 src/ui/storage.c:1156 +#: src/ui/screens.c:1771 src/ui/storage.c:795 src/ui/storage.c:1140 src/ui/storage.c:1156 msgid "The setting could not be saved." msgstr "" #. TRANSLATORS: Settings > Power > Memory speed, a faster level chosen -#: src/ui/screens.c:1627 +#: src/ui/screens.c:1776 msgid "The next start tries the faster memory speed. After 30 seconds without a problem, a quick memory test confirms it. If the console freezes, hold the power button to turn it off: it then starts at the normal speed by itself." msgstr "" #. TRANSLATORS: Settings > Power > Memory speed, back to normal -#: src/ui/screens.c:1631 src/ui/storage.c:1160 +#: src/ui/screens.c:1780 src/ui/storage.c:1160 msgid "Restart required: the change applies at the next start." msgstr "" #. TRANSLATORS: Settings section: restart, power off, battery saving -#: src/ui/screens.c:1640 src/ui/screens.c:1898 +#: src/ui/screens.c:1789 src/ui/screens.c:2051 msgctxt "settings" msgid "Power" msgstr "" -#: src/ui/screens.c:1643 +#: src/ui/screens.c:1792 msgid "Restart" msgstr "" -#: src/ui/screens.c:1644 +#: src/ui/screens.c:1793 msgid "Power off" msgstr "" -#: src/ui/screens.c:1645 +#: src/ui/screens.c:1794 msgid "Battery saving" msgstr "" -#: src/ui/screens.c:1646 +#: src/ui/screens.c:1795 msgid "Dim the screen after" msgstr "" -#: src/ui/screens.c:1649 +#: src/ui/screens.c:1798 msgid "Screen off after" msgstr "" #. TRANSLATORS: Settings > Power: turn the console off by itself after #. this long without a button pressed (never while copying or updating) -#: src/ui/screens.c:1654 +#: src/ui/screens.c:1803 msgid "Power off after" msgstr "" -#: src/ui/screens.c:1657 +#: src/ui/screens.c:1806 msgid "Battery gauge" msgstr "" #. TRANSLATORS: Settings > Power section header -#: src/ui/screens.c:1666 +#: src/ui/screens.c:1815 msgid "Performance" msgstr "" #. TRANSLATORS: Settings > Power: the faster memory did not work on this unit -#: src/ui/screens.c:1670 +#: src/ui/screens.c:1819 msgid "Last faster try failed" msgstr "" #. TRANSLATORS: value: the console went back to the normal memory speed -#: src/ui/screens.c:1672 +#: src/ui/screens.c:1821 msgid "normal speed" msgstr "" -#: src/ui/screens.c:1675 +#: src/ui/screens.c:1824 msgid "Memory clock now" msgstr "" #. TRANSLATORS: Settings > Power: the DRAM clock -#: src/ui/screens.c:1680 +#: src/ui/screens.c:1829 msgid "Memory speed" msgstr "" -#: src/ui/screens.c:1716 +#: src/ui/screens.c:1865 #, c-format msgid "Time zone: %s" msgstr "" -#: src/ui/screens.c:1722 src/ui/screens.c:1802 +#: src/ui/screens.c:1871 src/ui/screens.c:1951 msgid "Time zone" msgstr "" -#: src/ui/screens.c:1776 +#: src/ui/screens.c:1925 msgid "That date is not valid." msgstr "" -#: src/ui/screens.c:1781 +#: src/ui/screens.c:1930 msgid "The clock could not be set." msgstr "" -#: src/ui/screens.c:1783 +#: src/ui/screens.c:1932 msgid "Date and time set" msgstr "" -#: src/ui/screens.c:1785 +#: src/ui/screens.c:1934 msgid "Setting the clock needs the power module" msgstr "" -#: src/ui/screens.c:1794 src/ui/screens.c:1897 +#: src/ui/screens.c:1943 src/ui/screens.c:2050 msgid "Date & time" msgstr "" #. TRANSLATORS: the date and time now -#: src/ui/screens.c:1801 +#: src/ui/screens.c:1950 msgid "Now" msgstr "" -#: src/ui/screens.c:1803 +#: src/ui/screens.c:1952 msgid "Set the clock" msgstr "" -#: src/ui/screens.c:1804 +#: src/ui/screens.c:1953 msgid "Year" msgstr "" -#: src/ui/screens.c:1808 +#: src/ui/screens.c:1957 msgid "Month" msgstr "" -#: src/ui/screens.c:1812 +#: src/ui/screens.c:1961 msgid "Day" msgstr "" -#: src/ui/screens.c:1816 +#: src/ui/screens.c:1965 msgid "Hour" msgstr "" -#: src/ui/screens.c:1820 +#: src/ui/screens.c:1969 msgid "Minute" msgstr "" -#: src/ui/screens.c:1824 +#: src/ui/screens.c:1973 msgid "Set date and time" msgstr "" #. TRANSLATORS: Settings item that opens the list of languages -#: src/ui/screens.c:1873 +#: src/ui/screens.c:2023 msgid "Language" msgstr "" -#: src/ui/screens.c:1883 +#: src/ui/screens.c:2033 msgid "Settings" msgstr "" #. TRANSLATORS: Settings item: check for and install a new RetroStoneOS version -#: src/ui/screens.c:1896 src/ui/update_ui.c:1265 +#: src/ui/screens.c:2046 src/ui/update_ui.c:1265 msgid "System update" msgstr "" +#. TRANSLATORS: Settings item: download homebrew and freeware games +#. TRANSLATORS: Settings: the game store (homebrew and freeware downloads) +#: src/ui/screens.c:2049 src/ui/store_ui.c:756 +msgid "Game store" +msgstr "" + #. TRANSLATORS: Settings item: find a game by its name in every system -#: src/ui/screens.c:1900 src/ui/screens.c:2279 +#: src/ui/screens.c:2053 src/ui/screens.c:2432 msgid "Search all games" msgstr "" -#: src/ui/screens.c:1939 +#: src/ui/screens.c:2092 #, c-format msgid "%s is not installed" msgstr "" #. TRANSLATORS: first-boot language picker title (shown in each language as #. the cursor moves: keep it short and simple, children read it) -#: src/ui/screens.c:1999 src/ui/screens.c:2061 +#: src/ui/screens.c:2152 src/ui/screens.c:2214 msgid "Choose your language" msgstr "" #. TRANSLATORS: title of the search keyboard, with the number of games #. that match what is typed so far -#: src/ui/screens.c:2210 +#: src/ui/screens.c:2363 #, c-format msgid "Search: %s game" msgid_plural "Search: %s games" @@ -2023,254 +2162,254 @@ msgstr[1] "" #. TRANSLATORS: title of the search keyboard (nothing typed yet) #. TRANSLATORS: game options: find games of this list by name (the #. keyboard opens; the list shows the matches as you type) -#: src/ui/screens.c:2213 src/ui/screens.c:2247 src/ui/screens.c:2718 +#: src/ui/screens.c:2366 src/ui/screens.c:2400 src/ui/screens.c:2915 msgid "Search this list" msgstr "" #. TRANSLATORS: toast: "Search all games" found nothing; %s is the text searched -#: src/ui/screens.c:2268 +#: src/ui/screens.c:2421 #, c-format msgid "No game found for \"%s\"" msgstr "" #. TRANSLATORS: toast after "Hide this game"; the menu path must match #. your translations of Settings, Game lists and Show hidden games -#: src/ui/screens.c:2300 +#: src/ui/screens.c:2453 msgid "Game hidden: Settings > Game lists > Show hidden games shows it again" msgstr "" #. TRANSLATORS: after "Delete this game": the saves question is not asked, because #. another game file has the same name (the saves belong to both) -#: src/ui/screens.c:2372 src/ui/screens.c:2421 +#: src/ui/screens.c:2525 src/ui/screens.c:2616 msgid "Game deleted. Its saves were kept: another game uses the same save files." msgstr "" #. TRANSLATORS: toast after deleting a game and its saves -#: src/ui/screens.c:2377 +#: src/ui/screens.c:2530 msgid "Game and saves deleted" msgstr "" #. TRANSLATORS: toast after deleting a game (its saves are kept) -#: src/ui/screens.c:2380 +#: src/ui/screens.c:2533 msgid "Game deleted" msgstr "" #. TRANSLATORS: the game file could not be deleted; %s is the system's reason -#: src/ui/screens.c:2403 +#: src/ui/screens.c:2598 #, c-format msgid "The game could not be deleted (%s)." msgstr "" #. TRANSLATORS: second question after deleting a game -#: src/ui/screens.c:2433 +#: src/ui/screens.c:2628 msgid "Also delete its saves and save states?" msgstr "" #. TRANSLATORS: delete confirmation; %s is the game's file name (French #. quotes: « %s ») -#: src/ui/screens.c:2466 +#: src/ui/screens.c:2661 #, c-format msgid "Delete \"%s\" from the SD card?" msgstr "" #. TRANSLATORS: added to the delete confirmation of a multi-disc playlist -#: src/ui/screens.c:2471 +#: src/ui/screens.c:2666 msgid "Only this playlist is deleted: the disc files it lists stay on the SD card." msgstr "" #. TRANSLATORS: added to the delete confirmation of a CD image's .cue file -#: src/ui/screens.c:2473 +#: src/ui/screens.c:2668 msgid "Only this .cue file is deleted: the track files it lists stay on the SD card." msgstr "" #. TRANSLATORS: dialog buttons, uppercase, short (CANCEL is selected) -#: src/ui/screens.c:2475 +#: src/ui/screens.c:2670 msgid "DELETE" msgstr "" #. TRANSLATORS: Rename this game: the characters a file name cannot have on the card -#: src/ui/screens.c:2554 +#: src/ui/screens.c:2749 msgid "A game name cannot start with a dot or contain / \\ : * ? \" < > |" msgstr "" #. TRANSLATORS: Rename this game: the new name is taken -#: src/ui/screens.c:2561 +#: src/ui/screens.c:2756 msgid "Another game already has this name." msgstr "" #. TRANSLATORS: Rename this game failed; %s is the system's reason -#: src/ui/screens.c:2568 +#: src/ui/screens.c:2763 #, c-format msgid "The game could not be renamed (%s)." msgstr "" #. TRANSLATORS: toast after Rename this game -#: src/ui/screens.c:2595 +#: src/ui/screens.c:2790 msgid "Game renamed" msgstr "" #. TRANSLATORS: dialog buttons, uppercase, short -#: src/ui/screens.c:2600 +#: src/ui/screens.c:2795 msgid "SEARCH" msgstr "" #. TRANSLATORS: after Rename this game -#: src/ui/screens.c:2603 +#: src/ui/screens.c:2798 msgid "Look for a cover with the new name now?" msgstr "" #. TRANSLATORS: on-screen keyboard title: the game's new file name -#: src/ui/screens.c:2627 +#: src/ui/screens.c:2824 msgid "Rename game" msgstr "" -#: src/ui/screens.c:2638 +#: src/ui/screens.c:2835 msgid "This game is not in the list any more" msgstr "" #. TRANSLATORS: the game is one of the favorites (on/off) -#: src/ui/screens.c:2710 +#: src/ui/screens.c:2907 msgid "Favorite" msgstr "" #. TRANSLATORS: core for this game: the one chosen for the whole system -#: src/ui/screens.c:2725 +#: src/ui/screens.c:2922 msgid "System default" msgstr "" #. TRANSLATORS: a core (emulator) name, marked as not finished -#: src/ui/screens.c:2729 +#: src/ui/screens.c:2926 #, c-format msgid "%s (experimental)" msgstr "" #. TRANSLATORS: the default core of a system, with its name -#: src/ui/screens.c:2734 src/ui/screens.c:2775 +#: src/ui/screens.c:2931 src/ui/screens.c:2972 #, c-format msgid "Default (%s)" msgstr "" #. TRANSLATORS: no core #. TRANSLATORS: value: no card in the slot -#: src/ui/screens.c:2736 src/ui/storage.c:934 +#: src/ui/screens.c:2933 src/ui/storage.c:934 msgid "none" msgstr "" #. TRANSLATORS: "core" = the emulator used to run the game -#: src/ui/screens.c:2750 +#: src/ui/screens.c:2947 msgid "Core for this game" msgstr "" #. TRANSLATORS: %s is a system name ("Core for all Game Boy games") -#: src/ui/screens.c:2761 +#: src/ui/screens.c:2958 #, c-format msgid "Core for all %s games" msgstr "" -#: src/ui/screens.c:2766 +#: src/ui/screens.c:2963 msgid "Core" msgstr "" -#: src/ui/screens.c:2767 +#: src/ui/screens.c:2964 msgid "none installed" msgstr "" #. TRANSLATORS: start the game -#: src/ui/screens.c:2800 +#: src/ui/screens.c:2997 msgid "Launch" msgstr "" #. TRANSLATORS: game options: take the game out of the lists (Settings > #. Game lists > Show hidden games brings it back) -#: src/ui/screens.c:2803 +#: src/ui/screens.c:3000 msgid "Hide this game" msgstr "" #. TRANSLATORS: game options: delete the game's file from the SD card (asks first) -#: src/ui/screens.c:2809 +#: src/ui/screens.c:3006 msgid "Delete this game" msgstr "" #. TRANSLATORS: game options: change the game's file name (covers are found by it) -#: src/ui/screens.c:2812 +#: src/ui/screens.c:3009 msgid "Rename this game" msgstr "" #. TRANSLATORS: game options: the time spent playing this game -#: src/ui/screens.c:2814 +#: src/ui/screens.c:3011 msgid "Play time" msgstr "" #. TRANSLATORS: the game's file name -#: src/ui/screens.c:2817 +#: src/ui/screens.c:3014 msgid "File" msgstr "" #. TRANSLATORS: storage problem screen (the data partition of the SD card could not be read) -#: src/ui/screens.c:2847 +#: src/ui/screens.c:3044 msgid "The SD card reports read errors: it may be failing." msgstr "" #. TRANSLATORS: storage problem screen; %s is a file system name ("ntfs", "ext4") -#: src/ui/screens.c:2850 +#: src/ui/screens.c:3047 #, c-format msgid "The data partition uses a format this console does not use (%s)." msgstr "" #. TRANSLATORS: storage problem screen; %s is a file system name ("exfat") -#: src/ui/screens.c:2853 +#: src/ui/screens.c:3050 #, c-format msgid "The data partition (%s) could not be opened: it may be damaged." msgstr "" #. TRANSLATORS: storage problem screen -#: src/ui/screens.c:2856 +#: src/ui/screens.c:3053 msgid "The data partition could not be opened: it may be damaged." msgstr "" #. TRANSLATORS: title of the screen shown instead of the menu when the storage #. (the SD card's data partition: games, saves) cannot be read -#: src/ui/screens.c:2875 +#: src/ui/screens.c:3072 msgid "The storage could not be read" msgstr "" #. TRANSLATORS: storage problem screen: formatted, the console restarts -#: src/ui/screens.c:2880 +#: src/ui/screens.c:3077 msgid "Done. Restarting..." msgstr "" #. TRANSLATORS: storage problem screen, while the format runs -#: src/ui/screens.c:2882 +#: src/ui/screens.c:3079 msgid "Formatting the storage, please wait. Do not turn the console off." msgstr "" #. TRANSLATORS: storage problem screen, after what happened -#: src/ui/screens.c:2887 +#: src/ui/screens.c:3084 msgid "Nothing was erased: your games and saves may still be recoverable. Turn the console off and read the SD card on a PC to copy them." msgstr "" #. TRANSLATORS: storage problem screen: the format did not work; %d is its exit code -#: src/ui/screens.c:2893 +#: src/ui/screens.c:3090 #, c-format msgid "The storage could not be formatted (error %d)." msgstr "" #. TRANSLATORS: storage problem screen: power off, to read the SD card on a computer -#: src/ui/screens.c:2912 +#: src/ui/screens.c:3109 msgid "Turn off (to back up on a PC)" msgstr "" #. TRANSLATORS: storage problem screen: erase the data partition and start again -#: src/ui/screens.c:2914 +#: src/ui/screens.c:3111 msgid "Format the storage (erases everything)" msgstr "" -#: src/ui/screens.c:2991 +#: src/ui/screens.c:3188 msgid "FORMAT" msgstr "" #. TRANSLATORS: the second question before formatting the storage -#: src/ui/screens.c:2995 +#: src/ui/screens.c:3192 msgid "Erase everything on the storage? All games, saves and settings on it are lost. This cannot be undone." msgstr "" @@ -2779,6 +2918,187 @@ msgstr "" msgid "%d multi-disc games grouped: each is one entry now. Change discs in the in-game menu (SELECT + X)." msgstr "" +#. TRANSLATORS: Game store: the heading of the native games (the Ports system) +#: src/ui/store_ui.c:214 +msgid "Ports" +msgstr "" + +#. TRANSLATORS: Game store: looking for the player's ROM of a port +#: src/ui/store_ui.c:226 +msgid "looking for your ROM..." +msgstr "" + +#. TRANSLATORS: Game store: preparing a port's game data from the ROM; %d is the percent +#: src/ui/store_ui.c:230 +#, c-format +msgid "preparing %d%%" +msgstr "" + +#: src/ui/store_ui.c:232 +msgid "preparing..." +msgstr "" + +#. TRANSLATORS: Game store: %d is the percent downloaded +#: src/ui/store_ui.c:235 +#, c-format +msgid "%d%%" +msgstr "" + +#. TRANSLATORS: Game store: the downloaded game is checked and put in place +#: src/ui/store_ui.c:238 +msgid "installing..." +msgstr "" + +#. TRANSLATORS: Game store: the catalog is being loaded +#: src/ui/store_ui.c:254 +msgid "Loading the catalog..." +msgstr "" + +#. TRANSLATORS: Game store: the catalog could not be loaded (no network, or nothing in it) +#: src/ui/store_ui.c:261 +msgid "Could not load the catalog. Check the network (WiFi or Ethernet)." +msgstr "" + +#: src/ui/store_ui.c:261 +msgid "The store is empty" +msgstr "" + +#. TRANSLATORS: Game store: right of a game: installed / a newer version exists +#. TRANSLATORS: help bar: A installs the update / explains how to update +#: src/ui/store_ui.c:285 src/ui/update_ui.c:566 +msgid "update" +msgstr "" + +#: src/ui/store_ui.c:285 +msgid "installed" +msgstr "" + +#. TRANSLATORS: Game store: right of a port that needs the player's own ROM +#: src/ui/store_ui.c:288 +msgid "needs your ROM" +msgstr "" + +#. TRANSLATORS: Game store: not enough free space on the drive +#: src/ui/store_ui.c:489 +msgid "There is not enough free space on that drive." +msgstr "" + +#. TRANSLATORS: Game store: a file with that name is already there and was not installed by the store +#: src/ui/store_ui.c:492 +msgid "A file with the same name is already there. Rename or move it first." +msgstr "" + +#. TRANSLATORS: Game store: the download is damaged or has been changed +#: src/ui/store_ui.c:495 +msgid "The download did not match the catalog and was thrown away." +msgstr "" + +#. TRANSLATORS: Game store: the package is not safe to unpack +#: src/ui/store_ui.c:498 +msgid "The package is not valid and was not installed." +msgstr "" + +#. TRANSLATORS: Game store: preparing a port needs nearly all the memory +#: src/ui/store_ui.c:501 +msgid "Preparing the game needs more free memory. Restart the console and try again before starting anything else." +msgstr "" + +#. TRANSLATORS: Game store: preparing the game data took far too long and was stopped +#: src/ui/store_ui.c:505 +msgid "Preparing the game data took too long and was stopped. Nothing was installed." +msgstr "" + +#. TRANSLATORS: Game store: the game data could not be made from the ROM +#: src/ui/store_ui.c:508 +msgid "The game data could not be made from your ROM. Nothing was installed." +msgstr "" + +#. TRANSLATORS: Game store: the ROM is not the one the port needs +#: src/ui/store_ui.c:511 +msgid "That is not the ROM this game needs." +msgstr "" + +#. TRANSLATORS: Game store: the download failed (network) +#: src/ui/store_ui.c:516 +msgid "The game could not be downloaded. Check the network (WiFi or Ethernet) and try again." +msgstr "" + +#. TRANSLATORS: Game store: toast after an install; %s is the game's name +#: src/ui/store_ui.c:571 +#, c-format +msgid "%s installed" +msgstr "" + +#. TRANSLATORS: Game store: toast after a removal; %s is the game's name +#: src/ui/store_ui.c:576 +#, c-format +msgid "%s removed" +msgstr "" + +#. TRANSLATORS: Game store: preparing a port takes minutes; plug in the charger first; %d is the percent +#: src/ui/store_ui.c:620 +#, c-format +msgid "Plug in the charger first (battery %d%%)" +msgstr "" + +#. TRANSLATORS: Game store: before preparing a port's game data from the player's ROM; %d is the minutes +#: src/ui/store_ui.c:628 +#, c-format +msgid "Preparing the game data from your ROM takes about %d minutes. Keep the console on and nothing else running." +msgstr "" + +#. TRANSLATORS: dialog buttons, uppercase, short +#: src/ui/store_ui.c:631 +msgid "START" +msgstr "" + +#. TRANSLATORS: Game store: the question when several drives could hold the game +#: src/ui/store_ui.c:663 +msgid "Install on which drive?" +msgstr "" + +#. TRANSLATORS: Game store: a game's page; %1$s name, %2$s version, %3$s author, %4$s licence, +#. %5$s download size, %6$s the description +#: src/ui/store_ui.c:680 +#, c-format +msgid "" +"%1$s %2$s\n" +"by %3$s - %4$s\n" +"%5$s\n" +"\n" +"%6$s" +msgstr "" + +#. TRANSLATORS: Game store dialog button: search for the ROM again +#: src/ui/store_ui.c:690 +msgid "LOOK AGAIN" +msgstr "" + +#. TRANSLATORS: Game store dialog buttons, uppercase, short +#: src/ui/store_ui.c:694 +msgid "UPDATE" +msgstr "" + +#: src/ui/store_ui.c:694 +msgid "INSTALL" +msgstr "" + +#: src/ui/store_ui.c:698 +msgid "REMOVE" +msgstr "" + +#. TRANSLATORS: Game store: a port's page, the ROM found; %s is the file name +#: src/ui/store_ui.c:716 +#, c-format +msgid "Your ROM: %s" +msgstr "" + +#. TRANSLATORS: Game store: a port's page, no ROM found; %s is the game and version it needs +#: src/ui/store_ui.c:719 +#, c-format +msgid "Needs your own ROM: %s. Put it in your N64 folder or on a USB drive, then choose LOOK AGAIN." +msgstr "" + #: src/ui/systems.c:25 msgctxt "system" msgid "RetroStone" @@ -2994,6 +3314,11 @@ msgctxt "system" msgid "Cave Story" msgstr "" +#: src/ui/systems.c:72 src/ui/systems.c:76 +msgctxt "system" +msgid "Ports" +msgstr "" + #: src/ui/transfer_ui.c:35 msgctxt "system" msgid "NES / Famicom" @@ -3849,141 +4174,141 @@ msgstr "" #. TRANSLATORS: toast after ALWAYS RESUME / NEVER ASK at boot; the #. path must match your translations of Settings and Games -#: src/ui/ui.c:684 +#: src/ui/ui.c:686 msgid "Setting saved: you can change it in Settings > Games" msgstr "" #. TRANSLATORS: dialog buttons, uppercase, short: continue the saved game / #. start the game from the beginning -#: src/ui/ui.c:740 src/ui/ui.c:934 +#: src/ui/ui.c:742 src/ui/ui.c:936 msgid "RESUME" msgstr "" -#: src/ui/ui.c:741 src/ui/ui.c:935 +#: src/ui/ui.c:743 src/ui/ui.c:937 msgid "START FRESH" msgstr "" #. TRANSLATORS: boot resume dialog buttons, uppercase, short: resume now and #. at every start from now on / start fresh now and never ask again (both #. saved in Settings > Games > Resume on boot) -#: src/ui/ui.c:745 +#: src/ui/ui.c:747 msgid "ALWAYS RESUME" msgstr "" -#: src/ui/ui.c:746 +#: src/ui/ui.c:748 msgid "NEVER ASK" msgstr "" #. TRANSLATORS: %s is a game name: continue it where it was left? -#: src/ui/ui.c:749 +#: src/ui/ui.c:751 #, c-format msgid "Resume %s?" msgstr "" -#: src/ui/ui.c:836 src/ui/ui.c:939 +#: src/ui/ui.c:838 src/ui/ui.c:941 msgid "No emulator is installed for this system." msgstr "" -#: src/ui/ui.c:949 +#: src/ui/ui.c:951 msgid "Files are being copied. Wait for the copy to finish, or cancel it." msgstr "" -#: src/ui/ui.c:973 +#: src/ui/ui.c:975 msgid "Resume where you left off?" msgstr "" #. TRANSLATORS: dialog buttons, uppercase, short -#: src/ui/ui.c:1172 +#: src/ui/ui.c:1174 msgid "SETTINGS" msgstr "" -#: src/ui/ui.c:1195 +#: src/ui/ui.c:1197 #, c-format msgid "Controller connected: %s" msgstr "" -#: src/ui/ui.c:1198 +#: src/ui/ui.c:1200 #, c-format msgid "Controller removed: %s" msgstr "" #. TRANSLATORS: %s is the controller's name; "Settings > Controls" is #. the menu path: use your translations of "Settings" and "Controls" -#: src/ui/ui.c:1208 src/ui/ui.c:1215 +#: src/ui/ui.c:1210 src/ui/ui.c:1217 #, c-format msgid "New controller: %s (Settings > Controls)" msgstr "" -#: src/ui/ui.c:1212 +#: src/ui/ui.c:1214 #, c-format msgid "New controller: %s. Configure it in Settings > Controls?" msgstr "" #. TRANSLATORS: first boot, "Preparing your console": %s is a system name -#: src/ui/ui.c:1270 +#: src/ui/ui.c:1272 #, c-format msgid "Reading %s games" msgstr "" #. TRANSLATORS: first boot, while the game lists are read -#: src/ui/ui.c:1394 +#: src/ui/ui.c:1396 msgid "Preparing your console..." msgstr "" -#: src/ui/ui.c:1666 +#: src/ui/ui.c:1668 #, c-format msgid "Battery low (%d %%)" msgstr "" -#: src/ui/ui.c:1675 +#: src/ui/ui.c:1677 msgid "Battery empty, saving..." msgstr "" -#: src/ui/ui.c:1680 +#: src/ui/ui.c:1682 msgid "Restarting..." msgstr "" #. TRANSLATORS: the console is hot and runs slower to cool down -#: src/ui/ui.c:1689 +#: src/ui/ui.c:1691 msgid "Hot, slowing down" msgstr "" #. TRANSLATORS: charge screen (the console is off, on the charger) -#: src/ui/ui.c:1732 +#: src/ui/ui.c:1734 msgid "Charging" msgstr "" -#: src/ui/ui.c:1737 +#: src/ui/ui.c:1739 msgid "Fully charged" msgstr "" -#: src/ui/ui.c:1739 +#: src/ui/ui.c:1741 msgid "Charger unplugged" msgstr "" -#: src/ui/ui.c:1742 +#: src/ui/ui.c:1744 msgid "Not charging" msgstr "" #. TRANSLATORS: the big battery percentage of the charge screen ("80%") #. TRANSLATORS: battery level in the help bar ("%d %%" in French) -#: src/ui/ui.c:1755 src/ui/widgets.c:750 +#: src/ui/ui.c:1757 src/ui/widgets.c:750 #, c-format msgctxt "battery" msgid "%d%%" msgstr "" #. TRANSLATORS: charge screen: time until the battery is full (hours, minutes) -#: src/ui/ui.c:1762 +#: src/ui/ui.c:1764 #, c-format msgid "Full in %d h %02d min" msgstr "" -#: src/ui/ui.c:1768 +#: src/ui/ui.c:1770 msgid "Press the power button to start" msgstr "" -#: src/ui/ui.c:1779 +#: src/ui/ui.c:1781 msgid "Battery very low: plug in the charger" msgstr "" @@ -4132,11 +4457,6 @@ msgstr "" msgid "scroll" msgstr "" -#. TRANSLATORS: help bar: A installs the update / explains how to update -#: src/ui/update_ui.c:566 -msgid "update" -msgstr "" - #: src/ui/update_ui.c:566 msgid "how to update" msgstr "" diff --git a/frontend/src/follow/policy.c b/frontend/src/follow/policy.c new file mode 100644 index 0000000..7cf15ff --- /dev/null +++ b/frontend/src/follow/policy.c @@ -0,0 +1,117 @@ +/* + * policy.c - output decision, see policy.h. Same rules as display.c: + * - HDMI when it is connected and has a usable mode, else the built-in panel; + * - HDMI mode: the configured size and refresh, else the preferred one, + * else the first; with no EDID the CEA 720p60 timing (builtin); + * - panel_keep_scanning: the panel keeps CRTC 0 (the first LCD's CRTC), + * HDMI takes hdmi_crtc_index (or the lowest free one), never the panel's. + */ +#include + +#include "policy.h" + +static const struct pf_mode cea_720p60 = { 1280, 720, 60, false }; + +static const struct pf_mode *find_mode(const struct pf_conn *c, int w, int h, int hz) +{ + for (int i = 0; i < c->nmodes; i++) + if (c->modes[i].w == w && c->modes[i].h == h && c->modes[i].hz == hz) + return &c->modes[i]; + for (int i = 0; i < c->nmodes; i++) + if (c->modes[i].w == w && c->modes[i].h == h) + return &c->modes[i]; + return NULL; +} + +bool pf_pick_mode(const struct pf_cfg *cfg, const struct pf_conn *c, struct pf_mode *out, bool *builtin) +{ + const struct pf_mode *m = NULL; + + *builtin = false; + if (c->kind == PF_KIND_HDMI) { + if ((!c->has_edid || c->nmodes == 0) && cfg->hdmi_builtin_mode) { + *out = cea_720p60; + *builtin = true; + return true; + } + if (cfg->hdmi_w > 0 && cfg->hdmi_h > 0) + m = find_mode(c, cfg->hdmi_w, cfg->hdmi_h, cfg->hdmi_hz > 0 ? cfg->hdmi_hz : 60); + } + for (int i = 0; !m && i < c->nmodes; i++) + if (c->modes[i].preferred) + m = &c->modes[i]; + if (!m && c->nmodes > 0) + m = &c->modes[0]; + if (!m) + return false; + *out = *m; + return true; +} + +static bool crtc_ok(const struct pf_conn *c, const struct pf_cfg *cfg, int i) +{ + return i >= 0 && i < cfg->crtc_count && (c->possible_crtcs & (1u << i)); +} + +/* First CRTC that conn can use, lowest index first. */ +static int first_crtc(const struct pf_conn *c, const struct pf_cfg *cfg, int avoid) +{ + for (int i = 0; i < cfg->crtc_count; i++) + if (i != avoid && crtc_ok(c, cfg, i)) + return i; + return -1; +} + +struct pf_choice pf_choose(const struct pf_cfg *cfg, const struct pf_conn *conns, int nconns) +{ + struct pf_choice ch = { .conn = -1, .crtc = -1 }; + int lcd = -1, hdmi = -1, panel_crtc = -1; + struct pf_mode m; + bool builtin; + + for (int i = 0; i < nconns && i < PF_MAX_CONNS; i++) { + if (!conns[i].connected) + continue; + if (conns[i].kind == PF_KIND_LCD && lcd < 0) + lcd = i; + if (conns[i].kind == PF_KIND_HDMI && hdmi < 0) + hdmi = i; + } + if (lcd >= 0) { + /* the panel's CRTC: the lowest one it can use */ + panel_crtc = first_crtc(&conns[lcd], cfg, -1); + } + + /* HDMI wins when it can show a picture, else the panel */ + if (hdmi >= 0 && pf_pick_mode(cfg, &conns[hdmi], &m, &builtin)) { + int crtc; + + if (cfg->panel_keep_scanning && lcd >= 0) { + /* HDMI never on the panel's CRTC */ + crtc = crtc_ok(&conns[hdmi], cfg, cfg->hdmi_crtc_index) && + cfg->hdmi_crtc_index != panel_crtc ? cfg->hdmi_crtc_index + : first_crtc(&conns[hdmi], cfg, panel_crtc); + } else { + crtc = crtc_ok(&conns[hdmi], cfg, cfg->hdmi_crtc_index) ? cfg->hdmi_crtc_index + : first_crtc(&conns[hdmi], cfg, -1); + } + if (crtc >= 0) { + ch.conn = hdmi; + ch.crtc = crtc; + ch.w = m.w; + ch.h = m.h; + ch.hz = m.hz; + ch.builtin = builtin; + return ch; + } + } + if (lcd >= 0 && pf_pick_mode(cfg, &conns[lcd], &m, &builtin) && panel_crtc >= 0) { + ch.conn = lcd; + ch.crtc = panel_crtc; + ch.w = m.w; + ch.h = m.h; + ch.hz = m.hz; + ch.builtin = builtin; + } + return ch; +} diff --git a/frontend/src/follow/policy.h b/frontend/src/follow/policy.h new file mode 100644 index 0000000..d4e8dc6 --- /dev/null +++ b/frontend/src/follow/policy.h @@ -0,0 +1,54 @@ +/* + * policy.h - which output (built-in panel or HDMI), which CRTC and which + * mode a RetroStoneOS process uses. Pure logic: no DRM, no I/O. It mirrors + * pick_mode() and choose_crtc() in frontend/src/display.c, so the libretro + * host and the native ports (SDL2 patch, ports/) take the same decision. + */ +#ifndef RSOS_FOLLOW_POLICY_H +#define RSOS_FOLLOW_POLICY_H + +#include +#include + +#define PF_MAX_MODES 64 +#define PF_MAX_CONNS 8 + +enum pf_kind { PF_KIND_LCD = 0, PF_KIND_HDMI = 1 }; + +struct pf_mode { + int w, h, hz; + bool preferred; +}; + +struct pf_conn { + enum pf_kind kind; + bool connected; + bool has_edid; + uint32_t possible_crtcs; /* bit i = CRTC i can drive this connector */ + int nmodes; + struct pf_mode modes[PF_MAX_MODES]; +}; + +struct pf_cfg { + int hdmi_w, hdmi_h, hdmi_hz; /* policy mode, default 1280x720@60 */ + bool hdmi_builtin_mode; /* no EDID: use CEA 720p60 */ + int hdmi_crtc_index; /* preferred CRTC for HDMI (default 1) */ + bool panel_keep_scanning; /* the panel keeps its CRTC for good */ + int crtc_count; +}; + +struct pf_choice { + int conn; /* index into conns, -1 = none usable */ + int crtc; /* -1 = none */ + int w, h, hz; + bool builtin; /* the CEA timing, not an EDID mode */ +}; + +/* Decide the output. want_hdmi = the user's choice when HDMI is connected + * (always true in the default policy: HDMI when plugged in). */ +struct pf_choice pf_choose(const struct pf_cfg *cfg, const struct pf_conn *conns, int nconns); + +/* The mode pf_choose() would give one connector (no CRTC check). */ +bool pf_pick_mode(const struct pf_cfg *cfg, const struct pf_conn *c, struct pf_mode *out, bool *builtin); + +#endif diff --git a/frontend/src/host/host.h b/frontend/src/host/host.h index b50ebe9..9f83af0 100644 --- a/frontend/src/host/host.h +++ b/frontend/src/host/host.h @@ -207,6 +207,18 @@ struct host_launch_result { int host_launch(const char *core_path, const char *rom_path, const char *system, const struct host_launch_opts *opts, struct host_launch_result *res); +/* + * A native game (system "native"): "/bin/sh script" in its own process + * group (pgid = pid: signal it with kill(-pid, ...), which reaches what the + * script started), with cwd as the working directory and env (NAME=value, + * NULL-terminated) added to this process's environment. Output appended to + * log_path. idle() runs every ~100 ms; true kills the group (SIGKILL). + * No status pipe, no save states: *exit_code = the exit status, or 128 + + * the signal. Returns 0, or -errno if fork/exec failed. + */ +int host_launch_native(const char *script, const char *cwd, const char *const *env, + const char *log_path, bool (*idle)(void *), void *user, int *exit_code); + /* The running game process (0 if none): forward SIGTERM to it. */ pid_t host_child_pid(void); diff --git a/frontend/src/host/launch.c b/frontend/src/host/launch.c index 8893ffb..d232c3d 100644 --- a/frontend/src/host/launch.c +++ b/frontend/src/host/launch.c @@ -28,6 +28,111 @@ pid_t host_child_pid(void) return child_pid; } +extern char **environ; + +int host_launch_native(const char *script, const char *cwd, const char *const *env, + const char *log_path, bool (*idle)(void *), void *user, int *exit_code) +{ + const char *argv[] = { "/bin/sh", script, NULL }; + const char **envp; + char hdr[1200]; + struct timespec ts; + int n = 0, ne = 0, wstatus = 0, hdr_len, log_flags = O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC; + struct stat lst; + pid_t pid; + + *exit_code = -1; + /* the environment is made before fork(): the child only calls + * async-signal-safe functions (the menu has threads) */ + while (environ && environ[n]) + n++; + while (env && env[ne]) + ne++; + envp = calloc((size_t)(n + ne + 1), sizeof(*envp)); + if (!envp) + return -ENOMEM; + n = 0; + for (int i = 0; env && env[i]; i++) + envp[n++] = env[i]; + for (int i = 0; environ && environ[i]; i++) { + const char *eq = strchr(environ[i], '='); + bool replaced = false; + + for (int j = 0; eq && env && env[j]; j++) + if (!strncmp(env[j], environ[i], (size_t)(eq - environ[i]) + 1)) + replaced = true; + if (!replaced) + envp[n++] = environ[i]; + } + envp[n] = NULL; + + clock_gettime(CLOCK_MONOTONIC, &ts); + hdr_len = snprintf(hdr, sizeof(hdr), "\n=== [%5lld.%03ld] launch native: %s\n", + (long long)ts.tv_sec, ts.tv_nsec / 1000000, script); + if (hdr_len < 0) + hdr_len = 0; + if (hdr_len > (int)sizeof(hdr) - 1) + hdr_len = (int)sizeof(hdr) - 1; + if (stat(log_path, &lst) == 0 && lst.st_size > (1 << 20)) + log_flags |= O_TRUNC; /* keep /run small */ + + pid = fork(); + if (pid < 0) { + int e = errno; + + free(envp); + return -e; + } + if (pid == 0) { + sigset_t none; + int fd; + + sigemptyset(&none); + sigprocmask(SIG_SETMASK, &none, NULL); + signal(SIGPIPE, SIG_DFL); + signal(SIGCHLD, SIG_DFL); + setsid(); /* its own process group: kill(-pid) */ + fd = open(log_path, log_flags, 0644); + if (fd >= 0) { + if (hdr_len > 0 && write(fd, hdr, (size_t)hdr_len) < 0) { + /* the game runs without its header */ + } + dup2(fd, 1); + dup2(fd, 2); + } + if (chdir(cwd) < 0) + _exit(126); + execve(argv[0], (char *const *)argv, (char *const *)envp); + _exit(127); + } + free(envp); + child_pid = pid; + hlog(HLOG_INFO, "native game %d started: %s", (int)pid, script); + + for (;;) { + pid_t w = waitpid(pid, &wstatus, WNOHANG); + + if (w == pid) + break; + if (w < 0 && errno != EINTR) + break; + if (idle && idle(user)) { + hlog(HLOG_WARN, "killing native game %d on request", (int)pid); + kill(-pid, SIGKILL); + } + poll(NULL, 0, 100); + } + /* what the script started and left behind goes too */ + kill(-pid, SIGKILL); + child_pid = 0; + if (WIFEXITED(wstatus)) + *exit_code = WEXITSTATUS(wstatus); + else if (WIFSIGNALED(wstatus)) + *exit_code = 128 + WTERMSIG(wstatus); + hlog(HLOG_INFO, "native game %d ended: %d", (int)pid, *exit_code); + return 0; +} + static void parse_line(char *line, const struct host_launch_opts *opts, struct host_launch_result *res) { char *arg = strchr(line, ' '); diff --git a/frontend/src/input/input.c b/frontend/src/input/input.c index 1707448..7a472dc 100644 --- a/frontend/src/input/input.c +++ b/frontend/src/input/input.c @@ -6,6 +6,7 @@ #endif #include "input.h" +#include #include #include #include @@ -13,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -57,6 +59,8 @@ struct pad { int16_t trig[2]; /* L2, R2 analog */ bool has_analog; bool stick_nav[4]; /* up, down, left, right from the stick */ + int64_t combo_since; /* N64 pad: Z + Start held since (hotkey) */ + bool combo_fired; }; struct dev { @@ -69,6 +73,9 @@ struct dev { bool builtin, builtin_stick, keyboard, power_only; bool configured; enum input_mapping_source source; + enum input_pad_type type; /* the kind of controller (input.h) */ + bool guide; /* Home / Guide / PS held (quit combination) */ + char driver[24]; /* the kernel driver ("xpad", "nintendo", ...) */ int seq; /* connection order */ int16_t key_map[KEY_CNT]; /* evdev key code -> target */ struct axmap ax[ABS_CNT]; @@ -336,6 +343,22 @@ static void map_reset(struct dev *d) for (int i = 0; i < KEY_CNT; i++) d->key_map[i] = T_NONE; memset(d->ax, 0, sizeof(d->ax)); + d->type = IN_PAD_MODERN; +} + +static const char *const g_pad_type_ids[IN_PAD_TYPES] = { "modern", "n64", "gc" }; + +const char *input_pad_type_id(enum input_pad_type t) +{ + return t >= 0 && t < IN_PAD_TYPES ? g_pad_type_ids[t] : g_pad_type_ids[0]; +} + +enum input_pad_type input_pad_type_from_id(const char *id) +{ + for (int t = 0; id && t < IN_PAD_TYPES; t++) + if (!strcmp(id, g_pad_type_ids[t])) + return (enum input_pad_type)t; + return IN_PAD_MODERN; } /* Linux gamepad spec codes, already positional. Also the built-in pad. */ @@ -435,8 +458,23 @@ static int code_for_axis_index(const struct dev *d, int idx) return -1; } -/* SDL target name -> RetroPad id / stick axis. */ -static int sdl_target(const char *t, int *stick, int *axis) +/* + * The SDL names that mean another button for a kind of pad (input.h, enum + * input_pad_type): the database's own conventions for N64 and GameCube pads. + */ +static const struct { enum input_pad_type type; const char *n; int b; } g_type_names[] = { + /* N64: A and B where an N64 game wants them (A on RetroPad B, B on + * RetroPad Y); the C buttons on X / A / L3 / R3, which n64_c_stick() + * turns into the right stick */ + { IN_PAD_N64, "b", IN_Y }, + { IN_PAD_N64, "-righty", IN_X }, { IN_PAD_N64, "+righty", IN_A }, + { IN_PAD_N64, "-rightx", IN_L3 }, { IN_PAD_N64, "+rightx", IN_R3 }, + /* GameCube, by label: B is the left one, X the right one */ + { IN_PAD_GC, "b", IN_Y }, { IN_PAD_GC, "x", IN_A }, +}; + +/* SDL target name -> RetroPad id / stick axis, for a kind of pad. */ +static int sdl_target(const char *t, enum input_pad_type type, int *stick, int *axis) { static const struct { const char *n; int b; } btns[] = { { "a", IN_B }, { "b", IN_A }, { "x", IN_Y }, { "y", IN_X }, @@ -449,6 +487,9 @@ static int sdl_target(const char *t, int *stick, int *axis) }; *stick = *axis = -1; + for (size_t i = 0; i < ARRAY_SIZE(g_type_names); i++) + if (g_type_names[i].type == type && !strcmp(t, g_type_names[i].n)) + return g_type_names[i].b; if (!strcmp(t, "leftx")) { *stick = 0; *axis = 0; return -2; } if (!strcmp(t, "lefty")) { *stick = 0; *axis = 1; return -2; } if (!strcmp(t, "rightx")) { *stick = 1; *axis = 0; return -2; } @@ -466,7 +507,19 @@ static int apply_sdl_mapping(struct dev *d, const char *mapping) char *save = NULL, *tok; int n = 0; + /* the kind of pad first: it gives the names their meaning */ strlcpy_(buf, mapping, sizeof(buf)); + for (tok = strtok_r(buf, ",", &save); tok; tok = strtok_r(NULL, ",", &save)) { + char *colon = strchr(tok, ':'); + + if (!colon) + continue; + *colon = 0; + if (!strcmp(str_trim(tok), "type")) + d->type = input_pad_type_from_id(str_trim(colon + 1)); + } + strlcpy_(buf, mapping, sizeof(buf)); + save = NULL; for (tok = strtok_r(buf, ",", &save); tok; tok = strtok_r(NULL, ",", &save)) { char *colon = strchr(tok, ':'); char *src; @@ -478,7 +531,9 @@ static int apply_sdl_mapping(struct dev *d, const char *mapping) continue; *colon = 0; src = colon + 1; - t = sdl_target(str_trim(tok), &stick, &axis); + if (!strcmp(str_trim(tok), "type")) + continue; + t = sdl_target(str_trim(tok), d->type, &stick, &axis); if (t == T_NONE) continue; if (*src == '+' || *src == '-') @@ -599,6 +654,150 @@ static bool find_gcdb(const struct input *in, const struct dev *d, char *out, si return found; } +/* + * Pads the kernel drives with a layout of its own that the database does + * not describe right (or under versions it does not list), by evdev code + * (linux 6.18 drivers/hid/hid-nintendo.c). They win over the database. + * Every other known pad comes from the database or the Linux standard. + */ +struct profile_key { uint16_t code; int8_t t; }; + +/* Nintendo Switch Online N64: BTN_A / BTN_B are A / B, the C buttons are on + * Select (up), X (down), Y (left) and C (right), Z on TL2, ZR on TR2 */ +static const struct profile_key g_nso_n64_keys[] = { + { BTN_SOUTH, IN_B }, { BTN_EAST, IN_Y }, + { BTN_SELECT, IN_X }, { BTN_NORTH, IN_A }, { BTN_WEST, IN_L3 }, { BTN_C, IN_R3 }, + { BTN_TL2, IN_L2 }, { BTN_TL, IN_L }, { BTN_TR, IN_R }, { BTN_TR2, IN_R2 }, + { BTN_START, IN_START }, { BTN_MODE, T_GUIDE }, + { 0, 0 }, +}; + +/* Nintendo Switch Online NES: the kernel puts A at the bottom and B on the + * right; on the pad A is the right one */ +static const struct profile_key g_nso_nes_keys[] = { + { BTN_SOUTH, IN_A }, { BTN_EAST, IN_B }, { BTN_TL, IN_L }, { BTN_TR, IN_R }, + { BTN_SELECT, IN_SELECT }, { BTN_START, IN_START }, + { 0, 0 }, +}; + +struct pad_profile { + uint16_t vendor, product; + int has, lacks; /* key codes that tell it apart, 0 = none */ + enum input_pad_type type; + const struct profile_key *keys; /* NULL: the Linux standard is right */ +}; + +static const struct pad_profile g_profiles[] = { + { 0x057e, 0x2019, 0, 0, IN_PAD_N64, g_nso_n64_keys }, + /* NES pads say they are Joy-Cons: they have A and B but no X */ + { 0x057e, 0x2006, BTN_SOUTH, BTN_NORTH, IN_PAD_MODERN, g_nso_nes_keys }, + { 0x057e, 0x2007, BTN_SOUTH, BTN_NORTH, IN_PAD_MODERN, g_nso_nes_keys }, + /* NSO Mega Drive / Genesis: the database's line is for another layout + * (its C on rightshoulder); the kernel's is positional (A left, B + * bottom, C right; X Y Z above: L1, X, R1) like Genesis Plus GX wants */ + { 0x057e, 0x201e, 0, 0, IN_PAD_MODERN, NULL }, +}; + +/* + * Kernel drivers that lay their pads out by the Linux gamepad standard + * (Documentation/input/gamepad.rst): their pads need no database line, and + * a line made for another driver or version could only be wrong. + */ +static bool driver_follows_spec(const char *drv) +{ + static const char *const drivers[] = { "xpad", "playstation", "sony", "nintendo", "hid-steam" }; + + for (size_t i = 0; i < ARRAY_SIZE(drivers); i++) + if (!strcmp(drv, drivers[i])) + return true; + return false; +} + +/* The name of the driver of /dev/input/eventN, "" if unknown */ +static void read_driver(const char *path, char *out, size_t n) +{ + const char *ev = strrchr(path, '/'); + char sys[128], link[256]; + ssize_t r; + + out[0] = 0; + snprintf(sys, sizeof(sys), "/sys/class/input/%s/device/device/driver", ev ? ev + 1 : path); + r = readlink(sys, link, sizeof(link) - 1); + if (r <= 0) + return; + link[r] = 0; + strlcpy_(out, strrchr(link, '/') ? strrchr(link, '/') + 1 : link, n); +} + +static const struct pad_profile *find_profile(const struct dev *d, const unsigned long *keybits) +{ + for (size_t i = 0; i < ARRAY_SIZE(g_profiles); i++) { + const struct pad_profile *pf = &g_profiles[i]; + + /* (all of them hid-nintendo's: another driver lays them out + * another way) */ + if (pf->vendor == d->id.vendor && pf->product == d->id.product && + (!d->driver[0] || !strcmp(d->driver, "nintendo")) && + (!pf->has || TEST_BIT(pf->has, keybits)) && + (!pf->lacks || !TEST_BIT(pf->lacks, keybits))) + return pf; + } + return NULL; +} + +static bool has_word(const char *hay, const char *w) +{ + size_t n = strlen(w); + + for (const char *p = hay; *p; p++) + if (!strncasecmp(p, w, n) && (p == hay || !isalnum((unsigned char)p[-1])) && + !isalnum((unsigned char)p[n])) + return true; + return false; +} + +/* The kind of pad from its name in the database: N64 and GameCube pads and + * adapters follow the database's conventions for them (input.h). An + * adapter for both maps the GameCube way. */ +static enum input_pad_type type_from_name(const char *name) +{ + if (strcasestr(name, "gamecube") || has_word(name, "GC")) + return IN_PAD_GC; + if (has_word(name, "N64") || strcasestr(name, "nintendo 64")) + return IN_PAD_N64; + return IN_PAD_MODERN; +} + +/* + * A game controller, from its capabilities. A device without gamepad or + * joystick buttons counts when it has a stick and a few keys, but not a + * touchpad: PlayStation pads add theirs as a device of its own, with ABS_X + * and enough keys to look like a pad (their motion sensors have no keys). + */ +static bool caps_are_pad(const unsigned long *keybits, const unsigned long *absbits, int nkeys) +{ + if (TEST_BIT(BTN_GAMEPAD, keybits) || TEST_BIT(BTN_JOYSTICK, keybits) || + TEST_BIT(BTN_TRIGGER_HAPPY1, keybits)) + return true; + return TEST_BIT(ABS_X, absbits) && nkeys >= 4 && !TEST_BIT(KEY_A, keybits) && + !TEST_BIT(BTN_TOUCH, keybits) && !TEST_BIT(ABS_MT_SLOT, absbits) && + !TEST_BIT(ABS_MT_POSITION_X, absbits); +} + +/* A mapping without the left stick (skipped in the wizard, or a profile + * made before the stick worked there): ABS_X / ABS_Y, as for unknown pads */ +static void default_left_stick(struct dev *d, const unsigned long *absbits) +{ + for (int a = 0; a < ABS_CNT; a++) + if (d->ax[a].kind == AX_STICK && d->ax[a].a == 0) + return; + if (!TEST_BIT(ABS_X, absbits) || !TEST_BIT(ABS_Y, absbits) || + d->ax[ABS_X].kind != AX_NONE || d->ax[ABS_Y].kind != AX_NONE) + return; + d->ax[ABS_X] = (struct axmap){ AX_STICK, 0, 0, false, false }; + d->ax[ABS_Y] = (struct axmap){ AX_STICK, 0, 1, false, false }; +} + static void resolve_mapping(struct input *in, struct dev *d, const unsigned long *keybits, const unsigned long *absbits) { @@ -637,14 +836,49 @@ static void resolve_mapping(struct input *in, struct dev *d, const unsigned long } if (m && apply_sdl_mapping(d, m) > 0) { free(s); + default_left_stick(d, absbits); d->source = IN_MAP_USER; return; } free(s); } - /* 3. SDL GameControllerDB */ + /* 3. a pad the kernel lays out its own way */ + { + const struct pad_profile *pf = find_profile(d, keybits); + + if (pf) { + map_reset(d); + map_gamepad_spec(d, absbits); /* sticks and hats */ + if (pf->keys) { + for (int c = 0; c < KEY_CNT; c++) + if (d->key_map[c] >= 0 && d->key_map[c] < IN_NUM_BUTTONS) + d->key_map[c] = T_NONE; + d->key_map[BTN_MODE] = T_NONE; + for (const struct profile_key *k = pf->keys; k->code; k++) + d->key_map[k->code] = k->t; + } + d->type = pf->type; + d->source = IN_MAP_PROFILE; + return; + } + } + /* 3b. a driver that follows the Linux standard (Xbox, PlayStation, + * Switch, Steam pads) */ + if (driver_follows_spec(d->driver) && TEST_BIT(BTN_GAMEPAD, keybits)) { + map_reset(d); + map_gamepad_spec(d, absbits); + if (!strcmp(d->driver, "hid-steam")) { + /* its left touch pad reports where it is touched: no d-pad + * (the pad's clicks are BTN_DPAD_*) */ + d->ax[ABS_HAT0X] = (struct axmap){ 0 }; + d->ax[ABS_HAT0Y] = (struct axmap){ 0 }; + } + d->source = IN_MAP_PROFILE; + return; + } + /* 4. SDL GameControllerDB */ if (in->cfg.gcdb_path && find_gcdb(in, d, line, sizeof(line), in->cfg.gcdb_path, false)) { - char *m = line; + char *m = line, *name = strchr(line, ','); for (int k = 0; k < 2 && m; k++) { m = strchr(m, ','); @@ -652,19 +886,25 @@ static void resolve_mapping(struct input *in, struct dev *d, const unsigned long m++; } map_reset(d); + if (name && m) { + m[-1] = 0; + d->type = type_from_name(name + 1); + m[-1] = ','; + } if (m && apply_sdl_mapping(d, m) > 0) { + default_left_stick(d, absbits); d->source = IN_MAP_GCDB; return; } } - /* 4. Linux gamepad spec */ + /* 5. Linux gamepad spec */ map_reset(d); if (TEST_BIT(BTN_GAMEPAD, keybits)) { map_gamepad_spec(d, absbits); d->source = IN_MAP_GAMEPAD_SPEC; return; } - /* 5. unknown: hats and sticks still navigate; buttons need the wizard */ + /* 6. unknown: hats and sticks still navigate; buttons need the wizard */ d->ax[ABS_X] = (struct axmap){ AX_STICK, 0, 0, false, false }; d->ax[ABS_Y] = (struct axmap){ AX_STICK, 0, 1, false, false }; d->ax[ABS_HAT0X] = (struct axmap){ AX_HAT, 0, 0, false, false }; @@ -905,12 +1145,61 @@ uint16_t input_port_buttons(const struct input *in, int port) return out; } +/* The external device of a port, NULL for the built-in pad or none. */ +static const struct dev *port_device(const struct input *in, int port) +{ + int pd = port >= 0 && port < INPUT_MAX_PORTS ? in->port_dev[port] : -2; + + return pd >= 0 && pd < INPUT_MAX_DEVICES ? in->devs[pd] : NULL; +} + +/* + * N64 pad: its C buttons (RetroPad X, A, L3, R3) also push the right + * stick, full deflection, as the N64 core reads C buttons there. + */ +static int16_t n64_c_stick(uint16_t b, int axis) +{ + if (axis == 0) + return (int16_t)((b & BTN_MASK(IN_L3)) ? -0x7fff : (b & BTN_MASK(IN_R3)) ? 0x7fff : 0); + return (int16_t)((b & BTN_MASK(IN_X)) ? -0x7fff : (b & BTN_MASK(IN_A)) ? 0x7fff : 0); +} + +/* + * The menu's view of a pad's buttons. N64 and GameCube pads confirm with A + * and go back with B (in the games they stay positional: A on RetroPad B, + * B on RetroPad Y); the button on RetroPad A (C-down, GameCube X) is Y, and + * an N64's Z is Select (the menu's options button). + */ +static uint16_t ui_buttons(const struct dev *d, uint16_t b) +{ + uint16_t o; + + if (!d || (d->type != IN_PAD_N64 && d->type != IN_PAD_GC)) + return b; + o = b & (uint16_t)~(BTN_MASK(IN_A) | BTN_MASK(IN_B) | BTN_MASK(IN_Y)); + if (b & BTN_MASK(IN_B)) o |= BTN_MASK(IN_A); + if (b & BTN_MASK(IN_Y)) o |= BTN_MASK(IN_B); + if (b & BTN_MASK(IN_A)) o |= BTN_MASK(IN_Y); + if (d->type == IN_PAD_N64 && (b & BTN_MASK(IN_L2))) { + o &= (uint16_t)~BTN_MASK(IN_L2); + o |= BTN_MASK(IN_SELECT); + } + return o; +} + int16_t input_port_analog(const struct input *in, int port, int stick, int axis) { const struct pad *p = port_pad(in, port); + const struct dev *d = port_device(in, port); if (!p || stick < 0 || stick > 1 || axis < 0 || axis > 1) return 0; + if (stick == 1 && d && d->type == IN_PAD_N64) { + int16_t c = n64_c_stick(pad_buttons(p) & (uint16_t)~p->suppress, axis); + + if (c) + return c; + } if (stick == 0 && in->dpad_analog[port]) { uint16_t b = pad_buttons(p); @@ -1407,8 +1696,9 @@ static void capture_event(struct input *in, struct dev *d, const struct input_ev if (range <= 0) return; - if (abs(delta) > range / 2 || (abs(delta) > range / 3 && - (rest == ai->minimum || rest == ai->maximum))) + /* a third of the range: a centred 8-bit stick (0..255, rest 128) + * goes only 127 from rest, never past half the range */ + if (abs(delta) > range / 3) st = delta < 0 ? 1 : 2; else if (abs(delta) < range / 6) st = 0; @@ -1451,7 +1741,12 @@ static void handle_key(struct input *in, struct dev *d, int code, int value) } switch (t) { case T_NONE: + return; case T_GUIDE: + /* Home / Guide / PS: the in-game menu; held, the quit combination */ + d->guide = value != 0; + if (value == 1 && in->mode == INPUT_MODE_GAME) + push_hk(in, IN_HK_MENU); return; case T_BRIGHT_UP: case T_BRIGHT_DOWN: @@ -1629,6 +1924,7 @@ static int dev_open(struct input *in, const char *node) strlcpy_(d->path, path, sizeof(d->path)); ioctl(fd, EVIOCGNAME(sizeof(d->name) - 1), d->name); ioctl(fd, EVIOCGID, &d->id); + read_driver(path, d->driver, sizeof(d->driver)); ioctl(fd, EVIOCGBIT(0, sizeof(evbits)), evbits); if (TEST_BIT(EV_KEY, evbits)) ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybits)), keybits); @@ -1650,11 +1946,7 @@ static int dev_open(struct input *in, const char *node) if (d->builtin_stick) d->builtin = true; if (!d->builtin) { - bool pad = TEST_BIT(BTN_GAMEPAD, keybits) || TEST_BIT(BTN_JOYSTICK, keybits) || - TEST_BIT(BTN_TRIGGER_HAPPY1, keybits) || - (TEST_BIT(ABS_X, absbits) && nkeys >= 4 && !TEST_BIT(KEY_A, keybits)); - - if (pad) { + if (caps_are_pad(keybits, absbits, nkeys)) { /* external gamepad */ } else if (TEST_BIT(KEY_ENTER, keybits) && TEST_BIT(KEY_A, keybits)) { d->keyboard = true; @@ -1684,11 +1976,13 @@ static int dev_open(struct input *in, const char *node) epoll_ctl(in->epfd, EPOLL_CTL_ADD, fd, &ev); } - LOGI("input: %s \"%s\" %04x:%04x guid %s -> %s%s%s", path, d->name, d->id.vendor, - d->id.product, d->guid, + LOGI("input: %s \"%s\" %04x:%04x (%s) guid %s -> %s%s%s%s", path, d->name, d->id.vendor, + d->id.product, d->driver[0] ? d->driver : "?", d->guid, d->builtin ? "built-in" : d->keyboard ? "keyboard" : d->power_only ? "power key" : d->source == IN_MAP_USER ? "user mapping" : d->source == IN_MAP_GCDB ? "gamecontrollerdb" : + d->source == IN_MAP_PROFILE ? "built-in profile" : d->source == IN_MAP_GAMEPAD_SPEC ? "gamepad spec" : "UNCONFIGURED", + d->type == IN_PAD_N64 ? " (N64)" : d->type == IN_PAD_GC ? " (GameCube)" : "", d->builtin_stick ? " (analog stick)" : "", d->ff_rumble ? " (rumble)" : ""); if (d->builtin) { in->builtin_present = true; @@ -1891,6 +2185,46 @@ static void hotkeys(struct input *in, struct pad *p, uint16_t before, uint16_t n } } +/* + * A pad without Select (an N64 pad) has no hotkey button: Z + Start held + * for a second opens the in-game menu instead (Resume, save states, Quit). + * A hold, not a press: holding Z (targeting, crouching) and pressing Start + * to pause is ordinary play. + */ +#define COMBO_HOLD_MS 1000 +/* Z + Start on the pads without Select (Z is L2 on an N64, R on a GameCube) */ +static uint16_t pad_combo(enum input_pad_type t) +{ + return t == IN_PAD_N64 ? (uint16_t)(BTN_MASK(IN_L2) | BTN_MASK(IN_START)) : + t == IN_PAD_GC ? (uint16_t)(BTN_MASK(IN_R) | BTN_MASK(IN_START)) : 0; +} + +static void combo_holds(struct input *in, int64_t now) +{ + for (int i = 0; i < INPUT_MAX_DEVICES; i++) { + struct dev *d = in->devs[i]; + struct pad *p; + + uint16_t combo; + + if (!d || !(combo = pad_combo(d->type)) || d->pad != &d->own) + continue; + p = &d->own; + if (in->mode != INPUT_MODE_GAME || (pad_buttons(p) & combo) != combo) { + p->combo_since = 0; + p->combo_fired = false; + continue; + } + if (!p->combo_since) { + p->combo_since = now; + } else if (!p->combo_fired && now - p->combo_since >= COMBO_HOLD_MS) { + p->combo_fired = true; + p->suppress |= combo; + push_hk(in, IN_HK_MENU); + } + } +} + static uint16_t nav_bits(const struct pad *p) { uint16_t b = pad_buttons(p); @@ -1916,7 +2250,7 @@ static void update_nav(struct input *in, int64_t now) all |= nav_bits(&in->builtin); for (int i = 0; i < INPUT_MAX_DEVICES; i++) if (in->devs[i] && in->devs[i]->pad == &in->devs[i]->own && i != in->cap_slot) - all |= nav_bits(&in->devs[i]->own); + all |= ui_buttons(in->devs[i], nav_bits(&in->devs[i]->own)); for (int b = 0; b < IN_NUM_BUTTONS; b++) { bool was = in->nav_state & BTN_MASK(b), is = all & BTN_MASK(b); @@ -2060,6 +2394,7 @@ int input_poll(struct input *in) for (int i = 0; i < INPUT_MAX_DEVICES; i++) if (in->devs[i] && in->devs[i]->keyboard) hotkeys(in, &in->devs[i]->own, before[i], pad_buttons(&in->devs[i]->own)); + combo_holds(in, now); update_nav(in, now); return handled; } @@ -2086,6 +2421,12 @@ int input_timeout_ms(const struct input *in) if (d && any_down(d) && (next < 0 || d->held_check_at < next)) next = d->held_check_at; /* check_held() */ + if (d && d->own.combo_since && !d->own.combo_fired) { + int64_t t = d->own.combo_since + COMBO_HOLD_MS; /* combo_holds() */ + + if (next < 0 || t < next) + next = t; + } } if (next < 0) return -1; @@ -2135,9 +2476,330 @@ void input_device_info(const struct input *in, int slot, struct input_device_inf strlcpy_(out->guid, d->guid, sizeof(out->guid)); strlcpy_(out->path, d->path, sizeof(out->path)); out->source = d->source; + out->type = d->type; out->port = d->port; } +bool input_quit_combo_held(const struct input *in) +{ + const uint16_t sel = BTN_MASK(IN_SELECT) | BTN_MASK(IN_START); + + if (in->builtin_present && (pad_buttons(&in->builtin) & sel) == sel) + return true; + for (int i = 0; i < INPUT_MAX_DEVICES; i++) { + const struct dev *d = in->devs[i]; + uint16_t want = d && pad_combo(d->type) ? pad_combo(d->type) : sel; + + if (d && d->pad == &d->own && ((pad_buttons(&d->own) & want) == want || d->guide)) + return true; + } + return false; +} + +/* The database name of a RetroPad id for a kind of pad (sdl_target() the + * other way round); NULL for what SDL has no name for */ +static const char *sdl_name(enum input_pad_type type, int t) +{ + static const struct { int b; const char *n; } names[] = { + { IN_B, "a" }, { IN_A, "b" }, { IN_Y, "x" }, { IN_X, "y" }, + { IN_SELECT, "back" }, { IN_START, "start" }, { T_GUIDE, "guide" }, + { IN_L, "leftshoulder" }, { IN_R, "rightshoulder" }, + { IN_L2, "lefttrigger" }, { IN_R2, "righttrigger" }, + { IN_L3, "leftstick" }, { IN_R3, "rightstick" }, + { IN_UP, "dpup" }, { IN_DOWN, "dpdown" }, { IN_LEFT, "dpleft" }, { IN_RIGHT, "dpright" }, + }; + + for (size_t i = 0; i < ARRAY_SIZE(g_type_names); i++) + if (g_type_names[i].type == type && g_type_names[i].b == t) + return g_type_names[i].n; + for (size_t i = 0; i < ARRAY_SIZE(names); i++) + if (names[i].b == t) + return names[i].n; + return NULL; +} + +static void put_elem(char *line, size_t n, size_t *l, const char *name, const char *src) +{ + if (name && *l < n) + *l += (size_t)snprintf(line + *l, n - *l, "%s:%s,", name, src); +} + +/* + * One pad's mapping as an SDL database line, from what the menu resolved + * (key_map, ax): whatever its source, a native game sees the pad as the + * menu does. An N64 pad's R is also the right trigger (the libultraship + * ports' default R) when it has no ZR. + */ +static size_t export_dev(const struct dev *d, char *line, size_t n) +{ + char src[24], rshoulder[24] = "", nbuf[160]; + bool rtrig = false; + const char *name = d->name; + size_t l; + + /* The menu knows an N64 pad when the pad does not say so (a USB + * adapter's "Generic USB Joystick"): games that choose their layout by + * the controller's name (GoldenEye) then find their N64 one. */ + if (d->type == IN_PAD_N64 && !strstr(d->name, "64")) { + snprintf(nbuf, sizeof(nbuf), "N64 Controller (%s)", d->name); + name = nbuf; + } + l = (size_t)snprintf(line, n, "%s,%s,", d->guid, name); + + for (int c = 0; c < KEY_CNT; c++) { + int t = d->key_map[c]; + + if (t == T_NONE || d->btn_index[c] < 0) + continue; + snprintf(src, sizeof(src), "b%d", d->btn_index[c]); + put_elem(line, n, &l, sdl_name(d->type, t), src); + if (t == IN_R2) + rtrig = true; + if (t == IN_R && !rshoulder[0]) + strlcpy_(rshoulder, src, sizeof(rshoulder)); + } + for (int a = 0; a < ABS_CNT; a++) { + const struct axmap *x = &d->ax[a]; + int idx = d->axis_index[a]; + + if (idx < 0) + continue; /* (hats have no axis index) */ + switch (x->kind) { + case AX_STICK: + snprintf(src, sizeof(src), "a%d%s", idx, x->invert ? "~" : ""); + put_elem(line, n, &l, x->a == 0 ? (x->b == 0 ? "leftx" : "lefty") : + (x->b == 0 ? "rightx" : "righty"), src); + break; + case AX_TRIGGER: + snprintf(src, sizeof(src), "%sa%d%s", x->half ? "+" : "", idx, x->invert ? "~" : ""); + put_elem(line, n, &l, sdl_name(d->type, x->a), src); + if (x->a == IN_R2) + rtrig = true; + break; + case AX_BUTTONS: + snprintf(src, sizeof(src), "-a%d", idx); + if (x->a >= 0) + put_elem(line, n, &l, sdl_name(d->type, x->a), src); + src[0] = '+'; + if (x->b >= 0) + put_elem(line, n, &l, sdl_name(d->type, x->b), src); + break; + default: + break; + } + } + for (int h = 0; h < 4; h++) { + /* 1 up, 2 right, 4 down, 8 left */ + static const struct { int axis, neg, pos; const char *nn, *pn; } dirs[2] = { + { 0, 8, 2, "dpleft", "dpright" }, { 1, 1, 4, "dpup", "dpdown" }, + }; + + if (d->hat_index[h] < 0) + continue; + for (int k = 0; k < 2; k++) { + const struct axmap *x = &d->ax[ABS_HAT0X + 2 * h + dirs[k].axis]; + + if (x->kind == AX_HAT) { + snprintf(src, sizeof(src), "h%d.%d", d->hat_index[h], dirs[k].neg); + put_elem(line, n, &l, dirs[k].nn, src); + snprintf(src, sizeof(src), "h%d.%d", d->hat_index[h], dirs[k].pos); + put_elem(line, n, &l, dirs[k].pn, src); + } else if (x->kind == AX_BUTTONS) { + snprintf(src, sizeof(src), "h%d.%d", d->hat_index[h], dirs[k].neg); + if (x->a >= 0) + put_elem(line, n, &l, sdl_name(d->type, x->a), src); + snprintf(src, sizeof(src), "h%d.%d", d->hat_index[h], dirs[k].pos); + if (x->b >= 0) + put_elem(line, n, &l, sdl_name(d->type, x->b), src); + } + } + } + if (d->type == IN_PAD_N64 && !rtrig && rshoulder[0]) + put_elem(line, n, &l, "righttrigger", rshoulder); + if (l < n) + l += (size_t)snprintf(line + l, n - l, "platform:Linux,\n"); + return l; +} + +/* + * A port's layout for an N64 pad: which SDL element the port reads for each + * N64 function, so a real N64 pad does what the built-in buttons do in that + * game, whatever the port's bindings were changed to. One "function = element" + * per line (# comments), the functions being the ones the default N64 mapping + * names below; "none" drops the element. + */ +static const struct { const char *fn, *def; } g_n64_fn[] = { + { "a", "a" }, { "b", "b" }, { "z", "lefttrigger" }, { "l", "leftshoulder" }, + { "r", "rightshoulder" }, { "start", "start" }, + { "cup", "-righty" }, { "cdown", "+righty" }, { "cleft", "-rightx" }, { "cright", "+rightx" }, + { "dpup", "dpup" }, { "dpdown", "dpdown" }, { "dpleft", "dpleft" }, { "dpright", "dpright" }, +}; +#define N64_FN_COUNT ARRAY_SIZE(g_n64_fn) + +struct n64_layout { + bool has[N64_FN_COUNT]; + char to[N64_FN_COUNT][24]; +}; + +static void layout_parse(struct n64_layout *lay, const char *text) +{ + memset(lay, 0, sizeof(*lay)); + while (text && *text) { + const char *eol = strchr(text, '\n'); + size_t len = eol ? (size_t)(eol - text) : strlen(text); + char ln[96], *eq, *k, *v; + + if (len >= sizeof(ln)) + len = sizeof(ln) - 1; + memcpy(ln, text, len); + ln[len] = 0; + text = eol ? eol + 1 : text + strlen(text); + if (ln[0] == '#' || !(eq = strchr(ln, '='))) + continue; + *eq = 0; + k = ln; + v = eq + 1; + while (*k == ' ' || *k == '\t') + k++; + for (char *e = k + strlen(k); e > k && (e[-1] == ' ' || e[-1] == '\t' || e[-1] == '\r'); *--e = 0) + ; + while (*v == ' ' || *v == '\t') + v++; + for (char *e = v + strlen(v); e > v && (e[-1] == ' ' || e[-1] == '\t' || e[-1] == '\r'); *--e = 0) + ; + for (size_t i = 0; i < N64_FN_COUNT; i++) + if (!strcmp(k, g_n64_fn[i].fn) && v[0] && strlen(v) < sizeof(lay->to[i])) { + lay->has[i] = true; + strlcpy_(lay->to[i], v, sizeof(lay->to[i])); + } + } +} + +/* Renames the elements of one N64 mapping line (guid,name,elem:src,...,platform:Linux,) + * by the layout; all at once, so two functions can swap. */ +static size_t layout_apply(char *line, size_t cap, size_t len, const struct n64_layout *lay) +{ + char out[1536]; + size_t o = 0; + const char *p = line, *end; + char rsrc[24] = ""; + int commas = 0; + size_t orig_len = len; + + if (len && line[len - 1] == '\n') + len--; /* the newline goes back at the end */ + end = line + len; + + /* the source of the right shoulder: the right trigger on it is only the + * default's copy of R (an N64 pad has no ZR) */ + for (const char *t = line; t < end; ) { + const char *c = memchr(t, ',', (size_t)(end - t)); + size_t tl = c ? (size_t)(c - t) : (size_t)(end - t); + + if (tl > 14 && !strncmp(t, "rightshoulder:", 14) && tl - 14 < sizeof(rsrc)) { + memcpy(rsrc, t + 14, tl - 14); + rsrc[tl - 14] = 0; + } + t = c ? c + 1 : end; + } + while (p < end) { + const char *c = memchr(p, ',', (size_t)(end - p)); + size_t tl = c ? (size_t)(c - p) : (size_t)(end - p); + char tok[64]; + const char *colon; + bool keep = true; + + if (tl == 0 && !c) + break; + if (tl >= sizeof(tok)) + return orig_len; /* odd line: leave it */ + memcpy(tok, p, tl); + tok[tl] = 0; + p = c ? c + 1 : end; + if (commas++ < 2 || !(colon = strchr(tok, ':'))) { + /* guid and name (the name may hold a comma-free text) and odd tokens */ + if (o + tl + 1 < sizeof(out)) { + memcpy(out + o, tok, tl); + o += tl; + out[o++] = ','; + } + continue; + } + { + char nm[32]; + size_t nl = (size_t)(colon - tok); + const char *src = colon + 1; + + if (nl >= sizeof(nm)) + return orig_len; + memcpy(nm, tok, nl); + nm[nl] = 0; + if (!strcmp(nm, "righttrigger") && rsrc[0] && !strcmp(src, rsrc)) { + for (size_t i = 0; i < N64_FN_COUNT; i++) + if (!strcmp(g_n64_fn[i].fn, "r") && lay->has[i]) + keep = false; /* R is placed by the layout */ + } + for (size_t i = 0; keep && i < N64_FN_COUNT; i++) { + if (lay->has[i] && !strcmp(nm, g_n64_fn[i].def)) { + if (!strcmp(lay->to[i], "none")) { + keep = false; + } else { + strlcpy_(nm, lay->to[i], sizeof(nm)); + } + break; + } + } + if (keep) { + int w = snprintf(out + o, sizeof(out) - o, "%s:%s,", nm, src); + + if (w < 0 || (size_t)w >= sizeof(out) - o) + return orig_len; + o += (size_t)w; + } + } + } + if (o + 2 >= cap || o + 2 >= sizeof(out)) + return orig_len; + memcpy(line, out, o); + line[o++] = '\n'; + line[o] = 0; + return o; +} + +size_t input_sdl_mappings_layout(const struct input *in, char *buf, size_t n, const char *layout) +{ + size_t len = 0; + struct n64_layout lay; + + if (n) + buf[0] = 0; + if (layout) + layout_parse(&lay, layout); + for (int i = 0; i < INPUT_MAX_DEVICES; i++) { + const struct dev *d = in->devs[i]; + char line[1536]; + size_t l; + + if (!d || d->builtin || d->keyboard || d->power_only || !d->configured) + continue; + l = export_dev(d, line, sizeof(line)); + if (l >= sizeof(line) - 1) + continue; /* cut short: better none than a wrong one */ + if (layout && d->type == IN_PAD_N64) + l = layout_apply(line, sizeof(line), l, &lay); + if (len + l < n) { + memcpy(buf + len, line, l + 1); + len += l; + } + } + return len; +} + +size_t input_sdl_mappings(const struct input *in, char *buf, size_t n) +{ + return input_sdl_mappings_layout(in, buf, n, NULL); +} + /* --------------------------------------------------------------- capture */ void input_capture_begin(struct input *in, int slot) { @@ -2173,12 +2835,24 @@ void input_capture_end(struct input *in) in->cap_slot = -1; } +/* The device's mapping again, after its user mapping changed */ +static void reresolve(struct input *in, struct dev *d) +{ + unsigned long keybits[NBITS(KEY_CNT)] = { 0 }; + unsigned long absbits[NBITS(ABS_CNT)] = { 0 }; + + ioctl(d->fd, EVIOCGBIT(EV_KEY, sizeof(keybits)), keybits); + ioctl(d->fd, EVIOCGBIT(EV_ABS, sizeof(absbits)), absbits); + resolve_mapping(in, d, keybits, absbits); + pad_release_all(&d->own); + memset(d->down, 0, sizeof(d->down)); /* the key map changed */ + d->guide = false; +} + int input_save_user_mapping(struct input *in, int slot, const char *mapping) { struct dev *d; char p[512], buf[4096]; - unsigned long keybits[NBITS(KEY_CNT)] = { 0 }; - unsigned long absbits[NBITS(ABS_CNT)] = { 0 }; int r; if (slot < 0 || slot >= INPUT_MAX_DEVICES || !(d = in->devs[slot])) @@ -2189,11 +2863,23 @@ int input_save_user_mapping(struct input *in, int slot, const char *mapping) r = file_write_atomic(p, buf, strlen(buf)); if (r < 0) return r; - ioctl(d->fd, EVIOCGBIT(EV_KEY, sizeof(keybits)), keybits); - ioctl(d->fd, EVIOCGBIT(EV_ABS, sizeof(absbits)), absbits); - resolve_mapping(in, d, keybits, absbits); - pad_release_all(&d->own); - memset(d->down, 0, sizeof(d->down)); /* the key map changed */ + reresolve(in, d); LOGI("input: saved mapping for %s to %s", d->name, p); return 0; } + +int input_forget_user_mapping(struct input *in, int slot) +{ + struct dev *d; + char p[512]; + + if (slot < 0 || slot >= INPUT_MAX_DEVICES || !(d = in->devs[slot])) + return -ENODEV; + snprintf(p, sizeof(p), "%s/%s.cfg", in->cfg.user_map_dir, d->guid); + if (unlink(p) < 0 && errno != ENOENT) + return -errno; + reresolve(in, d); + LOGI("input: removed the mapping of %s (%s): %s", d->name, p, + d->source == IN_MAP_NONE ? "not configured" : "automatic again"); + return 0; +} diff --git a/frontend/src/input/input.h b/frontend/src/input/input.h index 5dd5fe6..5ceeae3 100644 --- a/frontend/src/input/input.h +++ b/frontend/src/input/input.h @@ -26,6 +26,7 @@ #define RSOS_INPUT_H #include +#include #include /* RetroPad button ids: identical to RETRO_DEVICE_ID_JOYPAD_*, so the @@ -78,6 +79,7 @@ enum input_p1_policy { INPUT_P1_AUTO = 0, INPUT_P1_BUILTIN, INPUT_P1_EXTERNAL }; enum input_mapping_source { IN_MAP_BUILTIN = 0, IN_MAP_USER, IN_MAP_GCDB, IN_MAP_GAMEPAD_SPEC, IN_MAP_KEYBOARD, IN_MAP_NONE, + IN_MAP_PROFILE, /* a known pad's built-in profile (input.c) */ }; struct input_config { @@ -121,6 +123,26 @@ struct input_port_info { enum input_mapping_source source; }; +/* + * The kind of controller (docs/input-design.md §2). The SDL element names of + * a mapping mean what they mean in the SDL GameControllerDB for that kind of + * pad, and each use (menu, games, native games) derives its layout from it: + * MODERN: a SNES/Xbox/PlayStation/Switch shape, by position (the default): + * a = bottom, b = right, x = left, y = top face button + * N64: a = A, b = B, -righty / +righty / -rightx / +rightx = C-up / + * C-down / C-left / C-right (buttons, or a stick), lefttrigger = Z, + * leftshoulder = L, rightshoulder = R; no Select: Z + Start held + * GC: GameCube, by label: a = A, b = B, x = X, y = Y, + * rightshoulder = Z, lefttrigger / righttrigger = L / R, + * rightx / righty = the C stick; no Select: Z + Start held + * In the games N64 and GameCube pads are positional like any pad (A on + * RetroPad B, B on RetroPad Y; an N64's C buttons are also its right stick); + * in the menus A confirms and B goes back. A user mapping saves the type as + * "type:n64" (other programs ignore it); the database and the built-in + * profiles give it for the pads they know. + */ +enum input_pad_type { IN_PAD_MODERN = 0, IN_PAD_N64, IN_PAD_GC, IN_PAD_TYPES }; + struct input_device_info { bool present; bool builtin; @@ -129,9 +151,13 @@ struct input_device_info { char guid[33]; char path[32]; enum input_mapping_source source; + enum input_pad_type type; int port; /* -1 = none */ }; +const char *input_pad_type_id(enum input_pad_type t); /* "modern", "n64", "gc" */ +enum input_pad_type input_pad_type_from_id(const char *id); /* unknown: MODERN */ + struct input; void input_config_defaults(struct input_config *cfg); @@ -242,7 +268,7 @@ int input_brightness_set(struct input *in, int value); /* * Raw capture for the "Configure controller" screen: while active, the * events of `slot` are not mapped; each new button press, hat direction or - * axis push past half range is reported by input_capture_next() as an SDL + * axis push past a third of its range is reported by input_capture_next() as an SDL * mapping element ("b3", "h0.1", "+a2", "-a1"). */ void input_capture_begin(struct input *in, int slot); @@ -251,6 +277,36 @@ void input_capture_end(struct input *in); /* Saves ",,a:b0,..." (SDL format, targets in SDL names) to * /.cfg and re-resolves the device. */ int input_save_user_mapping(struct input *in, int slot, const char *mapping); +/* Removes the user mapping of `slot` (back to the automatic one). */ +int input_forget_user_mapping(struct input *in, int slot); + +/* + * The quit combination is held on some pad: Select + Start, on a pad + * without Select (N64, GameCube) Z + Start, or a Home / Guide / PS button. + * For the native games, which the menu watches while they run (it quits + * them after a hold). + */ +bool input_quit_combo_held(const struct input *in); + +/* + * SDL GameControllerDB lines ("guid,name,mapping,platform:Linux,\n") for + * the external pads, made from the mapping the menu uses (user, built-in + * profile, database or the Linux standard), in the database's names for + * their type (an N64 pad: A/B on a/b, the C buttons on the right stick, Z + * on the left trigger). For the native games + * (SDL_GAMECONTROLLERCONFIG_FILE), so they see each pad as the menu does. + * Returns the length written. + */ +size_t input_sdl_mappings(const struct input *in, char *buf, size_t n); + +/* + * The same, with a port's layout for an N64 pad (docs/native-games.md, + * "Layouts"): text of "function = SDL element" lines (a, b, z, l, r, start, + * cup, cdown, cleft, cright, dpup..dpright; "none" drops one) that renames + * the elements of an N64 pad's mapping, so the pad does in that game what + * the built-in buttons do there. NULL = no layout. + */ +size_t input_sdl_mappings_layout(const struct input *in, char *buf, size_t n, const char *layout); const char *input_btn_name(enum input_btn b); /* "A", "B", "L1", ... */ diff --git a/frontend/src/main.c b/frontend/src/main.c index dfffaa4..700ca20 100644 --- a/frontend/src/main.c +++ b/frontend/src/main.c @@ -66,6 +66,7 @@ #include "i18n/i18n.h" #include "splash.h" #include "ui/settings.h" +#include "ui/systems.h" #include "ui/ui.h" #include "ui/util.h" #include "board_apply.h" /* after ui/ui.h: board_apply_ui() */ @@ -77,6 +78,7 @@ #define MENU_UP_PATH "/run/rsos/menu-up" /* written once the menu is on screen */ #define CHILD_GRACE_MS 8000 /* game child: time to save after SIGTERM/SIGUSR2 */ #define HANG_KILL_MS 5000 /* Select+Start held this long: kill the game */ +#define NATIVE_QUIT_MS 1000 /* native game: Select+Start held this long asks it to quit */ #define SHUTDOWN_MSG_MS 0 /* no hold: the "Powering off..." frame is drawn at the next loop pass, then the state is flushed and init signalled right away (docs/power.md, shutdown) */ @@ -174,6 +176,7 @@ static struct { /* game */ bool in_game; + bool native; /* the game is a native one (host_launch_native: a process group) */ int64_t combo_since; int64_t term_sent_at; int64_t poweroff_sent_at; @@ -1271,12 +1274,50 @@ static void pw_critical(const struct power_status *st, void *user) scr_draw(); } +/* A native game's sleep: every backlight's bl_power (0 = on, 4 = off). */ +static void native_backlight(bool on) +{ + const char *dir = P("/sys/class/backlight"); + DIR *d = opendir(dir); + struct dirent *de; + + if (!d) + return; + while ((de = readdir(d))) { + char p[PATH_MAX]; + int fd; + + if (de->d_name[0] == '.') + continue; + snprintf(p, sizeof(p), "%s/%s/bl_power", dir, de->d_name); + fd = open(p, O_WRONLY | O_CLOEXEC); + if (fd < 0) + continue; + if (write(fd, on ? "0\n" : "4\n", 2) < 0) + mlog("%s: %s", p, strerror(errno)); + close(fd); + } + closedir(d); +} + static void pw_sleep(bool enter, void *user) { pid_t c = host_child_pid(); (void)user; mlog("%s", enter ? "sleep" : "wake"); + if (M.in_game && M.native && c > 0) { + /* a native game knows nothing of RetroStoneOS: frozen (sound and + * picture stop), the backlight off by hand (it owns the display) */ + if (enter) { + kill(-c, SIGSTOP); + native_backlight(false); + } else { + native_backlight(true); + kill(-c, SIGCONT); + } + return; + } if (M.in_game && c > 0) { /* the game pauses, closes ALSA and turns its own display off */ kill(c, enter ? RSOS_SIG_SLEEP : RSOS_SIG_WAKE); @@ -1349,6 +1390,14 @@ static void pw_shutdown(enum power_reason why, void *user) * gamedb, caches */ if (M.ui) ui_power_event(M.ui, why == POWER_REASON_REBOOT ? UI_PWR_REBOOT : UI_PWR_SHUTDOWN); + if (M.in_game && M.native && c > 0) { + /* no save state: the game saves on its own (sm64: at each star); + * SIGCONT in case it was asleep */ + kill(-c, SIGTERM); + kill(-c, SIGCONT); + M.poweroff_sent_at = now_ms(); + return; + } if (M.in_game && c > 0) { /* SRAM flush + .state.auto, exit 3; launch_idle() waits for it * (then SIGKILL after CHILD_GRACE_MS) and the launch callback @@ -1386,6 +1435,8 @@ static void pw_idle(enum power_idle_event ev, int seconds, void *user) (void)user; mlog("idle power-off: %s", ev == POWER_IDLE_WARN ? "notice (10 s)" : "cancelled"); (void)seconds; + if (M.in_game && M.native) + return; /* held off (game_nostate): it cannot come */ if (M.in_game && c > 0) { kill(c, ev == POWER_IDLE_WARN ? RSOS_SIG_IDLE_WARN : RSOS_SIG_IDLE_CANCEL); return; @@ -1492,6 +1543,8 @@ static void idle_busy_check(bool force) why = "os-update"; else if (M.ui && ui_storage_busy(M.ui)) why = "storage-or-covers"; + else if (M.ui && ui_store_busy(M.ui)) + why = "game-store"; else if (M.ui && !M.in_game && !ui_is_loaded(M.ui)) why = "loading"; power_set_busy(why != NULL, why); @@ -1773,7 +1826,7 @@ static bool launch_idle(void *user) if (M.quit && c > 0) { if (!M.term_sent_at) { mlog("signal %d: asking the game to quit", (int)M.quit); - kill(c, SIGTERM); + kill(M.native ? -c : c, SIGTERM); M.term_sent_at = t; } else if (t - M.term_sent_at > CHILD_GRACE_MS) { return true; @@ -1784,17 +1837,24 @@ static bool launch_idle(void *user) return true; } /* Hang kill switch: the game quits on Select+Start at once; if it is - * still there after HANG_KILL_MS of holding them, it is stuck. */ + * still there after HANG_KILL_MS of holding them, it is stuck. A pad + * without Select (an N64 pad) holds Z+Start instead. */ if (M.in) { - const uint16_t combo = (1u << IN_SELECT) | (1u << IN_START); bool awake = !M.power_ok || power_get_mode() == POWER_MODE_NORMAL; input_drain(); if (awake) pads_activity(true); - if (awake && (input_any_buttons(M.in) & combo) == combo) { + if (awake && input_quit_combo_held(M.in)) { if (!M.combo_since) { M.combo_since = t; + } else if (M.native && !M.term_sent_at && c > 0 && t - M.combo_since >= NATIVE_QUIT_MS) { + /* a native game has no menu of ours: Select+Start + * held quits it (SIGKILL after HANG_KILL_MS) */ + mlog("Select+Start held: asking the native game to quit"); + kill(-c, SIGTERM); + kill(-c, SIGCONT); + M.term_sent_at = t; } else if (t - M.combo_since >= HANG_KILL_MS) { mlog("Select+Start held %d s: killing the game", HANG_KILL_MS / 1000); M.combo_since = 0; @@ -1838,6 +1898,8 @@ static bool has_resume(const struct ui_launch *req, void *user) const char *core_path = req->core_path; (void)user; + if (systems_is_native(req->system)) + return false; if (!core_path || !*core_path || access(core_path, R_OK) != 0) { if (host_pick_core(req->system, req->rom_path, core, sizeof(core)) < 0) return false; @@ -2306,6 +2368,140 @@ static int game_saves(const struct ui_launch *req, bool remove, void *user) return n; } +/* + * A native game (system "native", docs/native-games.md): its launch script + * runs with /bin/sh in the script's folder, in its own process group, with + * the display, sound and pads handed over as for a libretro game. It has + * no save states, no in-game menu and no RetroStoneOS signals: Select+Start + * held quits it (SIGTERM, SIGKILL later), sleep freezes it, a power-off + * stops it, and the idle power-off waits until it has ended. + */ +static int launch_native(const struct ui_launch *req) +{ + char dir[PATH_MAX], home[PATH_MAX], e_home[PATH_MAX + 8], e_cfg[PATH_MAX + 32]; + char e_data[PATH_MAX + 32], e_dir[PATH_MAX + 16], e_lang[64], e_pads[PATH_MAX + 40]; + const char *env[12]; + const char *slash; + bool suspended; + int r, exit_code = -1, ne = 0, ret = 0; + + slash = strrchr(req->rom_path, '/'); + if (!slash || access(req->rom_path, R_OK) != 0) { + set_msg(req, "%s", _("This game cannot start: its launch script is missing.")); + mlog("launch native %s: %s", req->rom_path, strerror(errno)); + return -1; + } + snprintf(dir, sizeof(dir), "%.*s", (int)(slash - req->rom_path), req->rom_path); + /* the root file system is read-only: settings a game keeps in its + * HOME go to the data partition */ + snprintf(home, sizeof(home), "%s", P("/data/rsos/native-home")); + if (mkdir(home, 0755) < 0 && errno != EEXIST) + mlog("%s: %s", home, strerror(errno)); + snprintf(e_home, sizeof(e_home), "HOME=%s", home); + snprintf(e_cfg, sizeof(e_cfg), "XDG_CONFIG_HOME=%s/.config", home); + snprintf(e_data, sizeof(e_data), "XDG_DATA_HOME=%s/.local/share", home); + snprintf(e_dir, sizeof(e_dir), "RSOS_GAME_DIR=%s", dir); + snprintf(e_lang, sizeof(e_lang), "RSOS_LANG=%s", i18n_language()); + env[ne++] = e_home; + env[ne++] = e_cfg; + env[ne++] = e_data; + env[ne++] = e_dir; + env[ne++] = e_lang; + /* SDL games: straight to KMS and ALSA, no window system here */ + env[ne++] = "SDL_VIDEODRIVER=kmsdrm"; + env[ne++] = "SDL_AUDIODRIVER=alsa"; + /* the pads set up in Settings > Controls, in the layout SDL games + * expect for their kind (an N64 pad's C buttons on the right stick); + * a file of its own, as the launchers set SDL_GAMECONTROLLERCONFIG */ + if (M.in) { + static char pads[8192], layout[2048]; + char lpath[PATH_MAX]; + size_t n, ll = 0; + char *dot; + FILE *lf; + + /* the port's layout for an N64 pad: ".layout" next + * to the script (docs/native-games.md, "Layouts") */ + layout[0] = 0; + snprintf(lpath, sizeof(lpath), "%s", req->rom_path); + if ((dot = strrchr(lpath, '.')) && !strcmp(dot, ".sh")) { + strcpy(dot, ".layout"); + if ((lf = fopen(lpath, "r"))) { + ll = fread(layout, 1, sizeof(layout) - 1, lf); + layout[ll] = 0; + fclose(lf); + mlog("N64 pad layout: %s", lpath); + } + } + n = input_sdl_mappings_layout(M.in, pads, sizeof(pads), ll ? layout : NULL); + + if (n > 0 && file_write_atomic(P("/run/rsos/sdl-controllers.txt"), pads, n) == 0) { + snprintf(e_pads, sizeof(e_pads), "SDL_GAMECONTROLLERCONFIG_FILE=%s", + P("/run/rsos/sdl-controllers.txt")); + env[ne++] = e_pads; + } + } + env[ne] = NULL; + + if (M.in) { + input_set_mode(M.in, INPUT_MODE_GAME); + input_set_docked(M.in, true); + } + if (M.power_ok) + power_set_game_running(true); + suspended = scr_suspend() == 0; + if (!suspended) { + mlog("display_suspend failed: closing the display for the game"); + scr_shutdown(); + } + M.in_game = M.native = true; + M.combo_since = M.term_sent_at = M.poweroff_sent_at = 0; + M.game_busy = M.resume_recorded = false; + M.game_nostate = true; /* no resume state: the idle power-off waits */ + idle_busy_check(true); + M.game_log_checked_at = 0; + mlog("launch native %s (%s)", req->game_name, req->rom_path); + + r = host_launch_native(req->rom_path, dir, env, P(GAME_LOG_PATH), launch_idle, (void *)req, &exit_code); + + native_backlight(true); /* asleep when it was stopped */ + M.in_game = M.native = false; + M.game_buttons = 0; + M.game_nostate = false; + idle_busy_check(true); + /* the menu comes back, also to show "Powering off..." */ + restore_display_after_game(suspended); + if (M.in) { + input_set_docked(M.in, M.out.type == DISPLAY_OUTPUT_HDMI); + input_drain(); + input_set_mode(M.in, INPUT_MODE_UI); + } + if (M.power_ok) + power_set_game_running(false); + + if (r < 0) { + set_msg(req, _("Cannot start the game process (%s)."), strerror(-r)); + mlog("host_launch_native: %s", strerror(-r)); + ret = -1; + } else { + mlog("native game ended: %d", exit_code); + /* 143 = SIGTERM, 137 = SIGKILL: Select+Start or a power-off */ + if (exit_code != 0 && exit_code != 128 + SIGTERM && exit_code != 128 + SIGKILL && + !M.term_sent_at && !M.poweroff_sent_at && !M.quit && !M.shutdown_req) { + /* TRANSLATORS: a native game (no emulator) ended with an + * error; %d is its exit code */ + set_msg(req, _("The game ended with an error (%d). Its messages are in rsos/logs on the SD card."), + exit_code); + ret = -1; + } + } + if (M.shutdown_req && !M.shutdown_at) + M.shutdown_at = now_ms() + SHUTDOWN_MSG_MS; + M.poweroff_sent_at = 0; + M.need_redraw = true; + return ret; +} + static int launch_game(const struct ui_launch *req, void *user) { char core[PATH_MAX], msg[256] = "", game[256], p1dev[320] = ""; @@ -2319,6 +2515,8 @@ static int launch_game(const struct ui_launch *req, void *user) int na = 0, r, ret = 0; (void)user; + if (systems_is_native(req->system)) + return launch_native(req); /* The UI picked the core (game > system > default); host_pick_core() * only when it has no library path. */ if (!core_path || !*core_path || access(core_path, R_OK) != 0) { diff --git a/frontend/src/tools/rsos-mkupdate.c b/frontend/src/tools/rsos-mkupdate.c index 839c6af..07a1dd3 100644 --- a/frontend/src/tools/rsos-mkupdate.c +++ b/frontend/src/tools/rsos-mkupdate.c @@ -13,6 +13,8 @@ * rsos-mkupdate sign (-s SECKEY | --key-env VAR) -o OUT.rsu IN.rsu * rsos-mkupdate verify -p PUBKEY FILE.rsu * rsos-mkupdate info FILE.rsu + * rsos-mkupdate signfile (-s SECKEY | --key-env VAR) -o OUT.sig FILE sign any file (the store catalog) + * rsos-mkupdate verifyfile -p PUBKEY -x SIG FILE * * Keys are signify keys without a passphrase (a CI secret cannot type * one): `signify -V -p update.pub -x manifest.sig -m manifest` checks a @@ -405,10 +407,93 @@ static int cmd_info(const char *path) return 0; } +/* The whole file in memory (a catalog: small), NUL-terminated. */ +static char *slurp(const char *path, size_t *len) +{ + FILE *f = fopen(path, "rb"); + char *b; + long n; + + if (!f) + return NULL; + if (fseek(f, 0, SEEK_END) < 0 || (n = ftell(f)) < 0 || n > (32 << 20) || fseek(f, 0, SEEK_SET) < 0) { + fclose(f); + return NULL; + } + b = malloc((size_t)n + 1); + if (!b || fread(b, 1, (size_t)n, f) != (size_t)n) { + free(b); + fclose(f); + return NULL; + } + fclose(f); + b[n] = 0; + *len = (size_t)n; + return b; +} + +static int cmd_signfile(const char *sk_path, const char *env, const char *out, const char *in) +{ + static char sig[1024]; + struct rsu_seckey sk; + struct rsu_sig s; + size_t n; + char *data; + + if (!out || !in) + return die("signfile needs -o OUT.sig and a file%s", ""); + data = slurp(in, &n); + if (!data) + return die("cannot read %s", in); + if (load_seckey(sk_path, env, &sk) < 0) { + free(data); + return 1; + } + rsu_sign(&sk, data, n, &s); + crypto_wipe(&sk, sizeof(sk)); + free(data); + if (rsu_sig_format(&s, "verify with store.pub (RetroStoneOS store key)", sig, sizeof(sig)) < 0) + return die("signature does not fit%s", ""); + unlink(out); + if (write_new(out, sig, 0644) < 0) + return die("cannot write %s", out); + printf("%s: signed\n", in); + return 0; +} + +static int cmd_verifyfile(const char *pk_path, const char *sig_path, const char *in) +{ + struct rsu_pubkey pk; + struct rsu_sig s; + size_t n, sn; + char *data, *st; + int ok; + + if (!pk_path || !sig_path || !in) + return die("verifyfile needs -p PUBKEY -x SIG and a file%s", ""); + if (rsu_pubkey_load(pk_path, &pk) < 0) + return die("%s: not a signify public key", pk_path); + st = slurp(sig_path, &sn); + if (!st || rsu_sig_parse(st, sn, &s) < 0) { + free(st); + return die("%s: not a signify signature", sig_path); + } + free(st); + data = slurp(in, &n); + if (!data) + return die("cannot read %s", in); + ok = rsu_verify(&pk, &s, data, n); + free(data); + if (!ok) + return die("%s: bad signature", in); + printf("%s: good signature\n", in); + return 0; +} + int main(int argc, char **argv) { struct pack_opts po = { 0 }; - const char *cmd = argc > 1 ? argv[1] : NULL, *pk = NULL, *comment = NULL, *pos = NULL; + const char *cmd = argc > 1 ? argv[1] : NULL, *pk = NULL, *comment = NULL, *pos = NULL, *sigf = NULL; for (int i = 2; i < argc; i++) { const char *a = argv[i], *v = i + 1 < argc ? argv[i + 1] : NULL; @@ -420,6 +505,7 @@ int main(int argc, char **argv) OPT("-s", po.sk) OPT("-p", pk) OPT("-c", comment) + OPT("-x", sigf) OPT("--key-env", po.key_env) OPT("--image", po.image) OPT("--payload", po.payload) @@ -455,6 +541,10 @@ int main(int argc, char **argv) return cmd_pack(&po); if (!strcmp(cmd, "sign")) return cmd_sign(po.sk, po.key_env, po.out, pos); + if (!strcmp(cmd, "signfile")) + return cmd_signfile(po.sk, po.key_env, po.out, pos); + if (!strcmp(cmd, "verifyfile")) + return cmd_verifyfile(pk, sigf, pos); if (!strcmp(cmd, "verify") && pos) return cmd_verify(pk, pos); if (!strcmp(cmd, "info") && pos) diff --git a/frontend/src/tools/uipreview.c b/frontend/src/tools/uipreview.c index f412838..a3987ff 100644 --- a/frontend/src/tools/uipreview.c +++ b/frontend/src/tools/uipreview.c @@ -1022,6 +1022,7 @@ int main(int argc, char **argv) cfg.update_helper = ""; /* --update-helper: Settings > System update */ cfg.smb_helper = ""; /* --smb-helper: the Windows file share */ cfg.bt_helper = ""; /* --bt-helper: Settings > Network > Bluetooth devices */ + cfg.store_helper = ""; /* --store-helper: Settings > Game store */ cfg.storage_helper = ""; /* --storage-helper: the Pro's storage (RSOS_RUN for its files) */ cfg.boot_env = ""; roms[0] = data[0] = cache[0] = themes_user[0] = cores[0] = 0; @@ -1085,6 +1086,8 @@ int main(int argc, char **argv) cfg.update_helper = v; /* e.g. tests/fake-rsos-update.sh */ else if (OPT("--smb-helper")) cfg.smb_helper = v; /* Settings > Network > Windows file share */ + else if (OPT("--store-helper")) + cfg.store_helper = v; else if (OPT("--bt-helper")) cfg.bt_helper = v; /* e.g. tests/fake-rsos-bt.sh */ else if (OPT("--storage-helper")) diff --git a/frontend/src/transfer/sysmap.c b/frontend/src/transfer/sysmap.c index 71ed902..f7efe0a 100644 --- a/frontend/src/transfer/sysmap.c +++ b/frontend/src/transfer/sysmap.c @@ -76,6 +76,8 @@ static const struct sysmap g_sys[] = { { "pico8", "PICO-8", { "p8", "fake08", NULL } }, { "doom", "Doom", { "prboom", "gzdoom", NULL } }, { "cavestory", "Cave Story", { "nxengine", "doukutsu", NULL } }, + /* not "ports": RetroPie's port scripts start its own emulators */ + { "native", "Ports", { "nativegames", NULL } }, }; #define NSYS ((int)(sizeof(g_sys) / sizeof(g_sys[0]))) diff --git a/frontend/src/ui/games.c b/frontend/src/ui/games.c index b889752..d039821 100644 --- a/frontend/src/ui/games.c +++ b/frontend/src/ui/games.c @@ -1303,7 +1303,9 @@ struct gamedb *gamedb_open(const char *path) } if (nf < 2 || !*f[0] || !*f[1]) continue; - e = db_find(db, f[0], f[1], true); + /* doom, cavestory and native are one list now ("ports"): what was + * kept for their games (favorites, play time...) is theirs still */ + e = db_find(db, systems_is_ports_member(f[0]) ? "ports" : f[0], f[1], true); e->favorite = nf > 2 && atoi(f[2]); e->lastplayed = nf > 3 ? strtoll(f[3], NULL, 10) : 0; e->playcount = nf > 4 ? atoi(f[4]) : 0; diff --git a/frontend/src/ui/hw.c b/frontend/src/ui/hw.c index f1a90f0..e6208a8 100644 --- a/frontend/src/ui/hw.c +++ b/frontend/src/ui/hw.c @@ -418,6 +418,14 @@ bool hw_job_poll(struct hw_job_result *r) return false; } +bool hw_job_kill(int id, int sig) +{ + for (int i = 0; i < HW_MAX_JOBS; i++) + if (g_jobs[i].id == id && g_jobs[i].pid > 0) + return kill(g_jobs[i].pid, sig) == 0; + return false; +} + int hw_jobs_running(void) { int n = 0; diff --git a/frontend/src/ui/hw.h b/frontend/src/ui/hw.h index 99f30a7..377147d 100644 --- a/frontend/src/ui/hw.h +++ b/frontend/src/ui/hw.h @@ -50,6 +50,8 @@ int hw_job_start(const char *const argv[], int tag); /* Non-blocking: returns one finished job, if any. */ bool hw_job_poll(struct hw_job_result *r); int hw_jobs_running(void); +/* Sends sig to job id's process (its own session leader); false when it is not running. */ +bool hw_job_kill(int id, int sig); /* True if a non-loopback interface has an IPv4 address (copied to addr). */ bool hw_has_ipv4(char *addr, size_t n); diff --git a/frontend/src/ui/loader.c b/frontend/src/ui/loader.c index ec76252..476dc7d 100644 --- a/frontend/src/ui/loader.c +++ b/frontend/src/ui/loader.c @@ -183,6 +183,49 @@ static bool has_folder_alias(const struct sysdef *sd) return false; } +/* The one Ports entry (systems.c): the games of every folder it is made of, + * in one list: roms/ports, roms/doom, roms/cavestory and roms/native, also on + * the other disks. The games keep their folder (the scan cache, which is by + * system name, is not used here: these folders are small). Thread-safe. */ +static void load_ports(struct loader *L, struct lres *r) +{ + static const char *const folders[] = { "ports", "doom", "cavestory", "native" }; + int64_t t0 = ui_now_us(); + + r->st.from_cache = true; + for (int d = -1; d < L->nlibs; d++) { + const char *roms = d < 0 ? L->roms_dir : L->lib_roms[d]; + + for (size_t i = 0; i < ARRAY_SIZE(folders); i++) { + char dir[1100]; + struct gamelist *gl; + struct games_load_stats st; + + snprintf(dir, sizeof(dir), "%s/%s", roms, folders[i]); + if (!dir_exists(dir)) + continue; + gl = games_load("ports", dir, NULL, L->alt, &st); + r->st.read_us += st.read_us; + r->st.stat_us += st.stat_us; + r->st.parse_us += st.parse_us; + r->st.scan_us += st.scan_us; + r->st.xml_us += st.xml_us; + r->st.save_us += st.save_us; + r->st.ndirs += st.ndirs; + r->st.from_cache = false; + if (!gl) + continue; + if (!r->gl) { + r->gl = gl; + continue; + } + games_merge(r->gl, gl); + games_free(gl); + } + } + r->st.total_us = ui_now_us() - t0; +} + static struct lres *load_one(struct loader *L, int sidx) { const struct sysdef *sd = systems_get(sidx); @@ -193,6 +236,10 @@ static struct lres *load_one(struct loader *L, int sidx) r->sidx = sidx; if (!sd) return r; + if (!strcmp(sd->name, "ports")) { + load_ports(L, r); + return r; + } if (L->empty_mt[sidx] && !has_folder_alias(sd) && !L->nlibs) { /* empty last time: its stamp (one stat() and one readdir: * games_dir_stamp) says whether it still is (and one more stat() diff --git a/frontend/src/ui/screens.c b/frontend/src/ui/screens.c index 1c0a120..411a80f 100644 --- a/frontend/src/ui/screens.c +++ b/frontend/src/ui/screens.c @@ -475,22 +475,28 @@ struct wstep { bool axis; /* expects a stick axis */ }; +/* + * One list of steps per kind of controller (input.h, enum input_pad_type), + * in the controller's own words. Only the buttons the menu cannot do + * without are required; any other step is skipped by pressing a button + * already set, or by waiting. + */ /* TRANSLATORS: controller set-up wizard: what to press now (big text, one line) */ -static const struct wstep g_steps[] = { - { "dpup", N_("Press D-pad UP"), false, false }, - { "dpdown", N_("Press D-pad DOWN"), false, false }, - { "dpleft", N_("Press D-pad LEFT"), false, false }, - { "dpright", N_("Press D-pad RIGHT"), false, false }, +static const struct wstep g_steps_modern[] = { + { "dpup", N_("Press D-pad UP"), true, false }, + { "dpdown", N_("Press D-pad DOWN"), true, false }, + { "dpleft", N_("Press D-pad LEFT"), true, false }, + { "dpright", N_("Press D-pad RIGHT"), true, false }, { "b", N_("Press the RIGHT face button (A)"), false, false }, { "a", N_("Press the BOTTOM face button (B)"), false, false }, - { "y", N_("Press the TOP face button (X)"), false, false }, - { "x", N_("Press the LEFT face button (Y)"), false, false }, + { "y", N_("Press the TOP face button (X)"), true, false }, + { "x", N_("Press the LEFT face button (Y)"), true, false }, { "leftshoulder", N_("Press L1"), true, false }, { "rightshoulder", N_("Press R1"), true, false }, { "lefttrigger", N_("Press L2"), true, false }, { "righttrigger", N_("Press R2"), true, false }, - { "back", N_("Press SELECT"), false, false }, - { "start", N_("Press START"), false, false }, + { "back", N_("Press SELECT"), true, false }, + { "start", N_("Press START"), true, false }, { "leftstick", N_("Press the left stick (L3)"), true, false }, { "rightstick", N_("Press the right stick (R3)"), true, false }, { "leftx", N_("Push the left stick RIGHT"), true, true }, @@ -499,16 +505,62 @@ static const struct wstep g_steps[] = { { "righty", N_("Push the right stick DOWN"), true, true }, }; -#define WIZ_STEPS ((int)ARRAY_SIZE(g_steps)) +/* N64, in the database's names for it (input.h): the C buttons on the + * right stick halves, Z on lefttrigger; no Select (Z + Start held) */ +static const struct wstep g_steps_n64[] = { + { "dpup", N_("Press D-pad UP"), true, false }, + { "dpdown", N_("Press D-pad DOWN"), true, false }, + { "dpleft", N_("Press D-pad LEFT"), true, false }, + { "dpright", N_("Press D-pad RIGHT"), true, false }, + { "a", N_("Press A"), false, false }, + { "b", N_("Press B"), false, false }, + { "lefttrigger", N_("Press Z (the trigger underneath)"), true, false }, + { "leftshoulder", N_("Press L"), true, false }, + { "rightshoulder", N_("Press R"), true, false }, + { "start", N_("Press START"), false, false }, + { "-righty", N_("Press C-UP"), true, false }, + { "+righty", N_("Press C-DOWN"), true, false }, + { "-rightx", N_("Press C-LEFT"), true, false }, + { "+rightx", N_("Press C-RIGHT"), true, false }, + { "leftx", N_("Push the stick RIGHT"), true, true }, + { "lefty", N_("Push the stick DOWN"), true, true }, +}; + +/* GameCube, by label (input.h): Z on rightshoulder, L / R on the triggers, + * the C stick on the right stick; no Select (Z + Start held) */ +static const struct wstep g_steps_gc[] = { + { "dpup", N_("Press D-pad UP"), true, false }, + { "dpdown", N_("Press D-pad DOWN"), true, false }, + { "dpleft", N_("Press D-pad LEFT"), true, false }, + { "dpright", N_("Press D-pad RIGHT"), true, false }, + { "a", N_("Press A (the big button)"), false, false }, + { "b", N_("Press B"), false, false }, + { "x", N_("Press X"), true, false }, + { "y", N_("Press Y"), true, false }, + { "rightshoulder", N_("Press Z"), true, false }, + { "lefttrigger", N_("Press L all the way"), true, false }, + { "righttrigger", N_("Press R all the way"), true, false }, + { "start", N_("Press START"), false, false }, + { "leftx", N_("Push the stick RIGHT"), true, true }, + { "lefty", N_("Push the stick DOWN"), true, true }, + { "rightx", N_("Push the C stick RIGHT"), true, true }, + { "righty", N_("Push the C stick DOWN"), true, true }, +}; + +#define WIZ_MAX_STEPS 20 #define WIZ_SKIP_MS 6000 +#define WIZ_BOUNCE_MS 500 struct wizard { struct screen base; int slot; char name[80]; + enum input_pad_type type; + const struct wstep *steps; + int nsteps; int step; int64_t step_t0; - char result[WIZ_STEPS][24]; + char result[WIZ_MAX_STEPS][24]; bool done; }; @@ -527,16 +579,18 @@ static void wiz_render(struct ui *ui, struct screen *scr, struct gfx_surface *s) draw_panel(s, x, y, pw, ph, MAX(4, H / 60), ms->bg); draw_text_box(ui, s, f, _("Configure controller"), x, y + lh / 3, pw, lh, AL_CENTER, ms->title); draw_text_box(ui, s, fs, w->name, x, y + lh, pw, lh, AL_CENTER, ms->text_dim); - if (w->step < WIZ_STEPS) { - const struct wstep *st = &g_steps[w->step]; + if (w->step < w->nsteps) { + const struct wstep *st = &w->steps[w->step]; int left = (int)((WIZ_SKIP_MS - (ui->now - w->step_t0)) / 1000); draw_text_box(ui, s, fb, _(st->prompt), x, y + ph / 2 - lh, pw, lh * 3 / 2, AL_CENTER, ms->accent); - snprintf(buf, sizeof(buf), _("Step %d of %d"), w->step + 1, WIZ_STEPS); + snprintf(buf, sizeof(buf), _("Step %d of %d"), w->step + 1, w->nsteps); draw_text_box(ui, s, fs, buf, x, y + ph / 2 + lh / 2, pw, lh, AL_CENTER, ms->text_dim); if (st->optional) { - snprintf(buf, sizeof(buf), _("Not on this pad? Wait %d s to skip"), MAX(0, left)); + /* TRANSLATORS: controller wizard; %d is seconds */ + snprintf(buf, sizeof(buf), _("Not on this pad? Press a button already set, or wait %d s"), + MAX(0, left)); draw_text_box(ui, s, fs, buf, x, y + ph - lh * 3 / 2, pw, lh, AL_CENTER, ms->text_dim); } @@ -548,12 +602,18 @@ static void wiz_finish(struct ui *ui, struct wizard *w) char map[1024] = ""; int r = -1; - for (int i = 0; i < WIZ_STEPS; i++) { + for (int i = 0; i < w->nsteps; i++) { char e[40]; if (!w->result[i][0]) continue; - snprintf(e, sizeof(e), "%s%s:%s", map[0] ? "," : "", g_steps[i].target, w->result[i]); + snprintf(e, sizeof(e), "%s%s:%s", map[0] ? "," : "", w->steps[i].target, w->result[i]); + strncat(map, e, sizeof(map) - strlen(map) - 1); + } + if (w->type != IN_PAD_MODERN) { + char e[40]; + + snprintf(e, sizeof(e), ",type:%s", input_pad_type_id(w->type)); strncat(map, e, sizeof(map) - strlen(map) - 1); } if (ui->cfg.input) { @@ -569,7 +629,7 @@ static void wiz_finish(struct ui *ui, struct wizard *w) static void wiz_record(struct ui *ui, struct wizard *w, const char *elem) { - const struct wstep *st = &g_steps[w->step]; + const struct wstep *st = &w->steps[w->step]; char v[24]; if (st->axis) { @@ -578,16 +638,24 @@ static void wiz_record(struct ui *ui, struct wizard *w, const char *elem) return; snprintf(v, sizeof(v), "%s%s", elem + 1, elem[0] == '-' ? "~" : ""); } else { - /* buttons, hats and half axes ("+a5" for analog triggers) */ + /* buttons, hats and half axes ("+a5" for analog triggers, an + * N64 adapter's C buttons on a stick) */ if ((elem[0] == '+' || elem[0] == '-') && strcmp(st->target, "lefttrigger") && - strcmp(st->target, "righttrigger") && strncmp(st->target, "dp", 2)) + strcmp(st->target, "righttrigger") && strncmp(st->target, "dp", 2) && + st->target[0] != '+' && st->target[0] != '-') return; strlcpy_(v, elem, sizeof(v)); } - /* refuse an element already used (bouncing buttons) */ + /* an element already used: the last one again within the bounce time is + * a bouncing button; otherwise it skips an optional step */ for (int i = 0; i < w->step; i++) - if (!strcmp(w->result[i], v)) + if (!strcmp(w->result[i], v)) { + if (st->optional && (i != w->step - 1 || ui->now - w->step_t0 > WIZ_BOUNCE_MS)) { + w->step++; + w->step_t0 = ui->now; + } return; + } strlcpy_(w->result[w->step], v, sizeof(w->result[0])); w->step++; w->step_t0 = ui->now; @@ -603,21 +671,21 @@ static bool wiz_update(struct ui *ui, struct screen *scr) ui_pop(ui); return true; } - while (w->step < WIZ_STEPS && input_capture_next(ui->cfg.input, elem, sizeof(elem))) { + while (w->step < w->nsteps && input_capture_next(ui->cfg.input, elem, sizeof(elem))) { wiz_record(ui, w, elem); redraw = true; } - if (w->step < WIZ_STEPS && g_steps[w->step].optional && + if (w->step < w->nsteps && w->steps[w->step].optional && ui->now - w->step_t0 > WIZ_SKIP_MS) { w->step++; w->step_t0 = ui->now; redraw = true; } - if (w->step >= WIZ_STEPS) { + if (w->step >= w->nsteps) { wiz_finish(ui, w); return true; } - return redraw || g_steps[w->step].optional; + return redraw || w->steps[w->step].optional; } static int wiz_timeout(struct ui *ui, struct screen *s) @@ -649,13 +717,24 @@ static const struct screen_ops wiz_ops = { .opaque = false, }; -static void wizard_open(struct ui *ui, int slot) +static void wizard_open(struct ui *ui, int slot, enum input_pad_type type) { struct wizard *w = xcalloc(1, sizeof(*w)); struct input_device_info di; w->base.ops = &wiz_ops; w->slot = slot; + w->type = type; + if (type == IN_PAD_N64) { + w->steps = g_steps_n64; + w->nsteps = (int)ARRAY_SIZE(g_steps_n64); + } else if (type == IN_PAD_GC) { + w->steps = g_steps_gc; + w->nsteps = (int)ARRAY_SIZE(g_steps_gc); + } else { + w->steps = g_steps_modern; + w->nsteps = (int)ARRAY_SIZE(g_steps_modern); + } w->step_t0 = ui->now; if (ui->cfg.input) { input_device_info(ui->cfg.input, slot, &di); @@ -665,11 +744,80 @@ static void wizard_open(struct ui *ui, int slot) ui_push(ui, &w->base); } +/* "What kind of controller is this?": the wizard's steps and the layouts + * derived from the mapping follow the answer (input.h, enum input_pad_type) */ +static int g_padtype_slot = -1; +#define ID_PAD_FORGET (ID_PAD0 + IN_PAD_TYPES) + +static void open_padcfg(struct ui *ui); + +static void padtype_item(struct ui *ui, struct menu *m, struct menu_item *it, int dir) +{ + int slot = g_padtype_slot; + + (void)m; + if (dir != 0 || it->id < ID_PAD0 || slot < 0) + return; + if (it->id == ID_PAD_FORGET) { + int r = ui->cfg.input ? input_forget_user_mapping(ui->cfg.input, slot) : -1; + + ui_pop(ui); /* frees m */ + ui_pop(ui); /* the list of controllers: its values changed */ + open_padcfg(ui); + if (r == 0) + /* TRANSLATORS: toast after removing a controller's own set-up */ + ui_toastf(ui, "%s", _("Controller set up automatically again")); + return; + } + ui_pop(ui); /* frees m */ + wizard_open(ui, slot, (enum input_pad_type)(it->id - ID_PAD0)); +} + +static void padtype_open(struct ui *ui, int slot) +{ + /* TRANSLATORS: controller set-up: the first question, a menu title */ + struct menu *m = menu_new(ui, _("What kind of controller is it?"), K_PADCFG); + struct input_device_info di = { 0 }; + + g_padtype_slot = slot; + if (ui->cfg.input) + input_device_info(ui->cfg.input, slot, &di); + /* TRANSLATORS: kinds of controller (menu entries) */ + menu_add(m, MI_ACTION, ID_PAD0 + IN_PAD_MODERN, _("SNES, Xbox, PlayStation, Switch or similar")); + menu_add(m, MI_ACTION, ID_PAD0 + IN_PAD_N64, _("Nintendo 64")); + menu_add(m, MI_ACTION, ID_PAD0 + IN_PAD_GC, _("GameCube")); + if (di.present && di.source == IN_MAP_USER) + /* TRANSLATORS: controller set-up: remove your own set-up of this + * controller and use the automatic one (or none) */ + menu_add(m, MI_ACTION, ID_PAD_FORGET, _("Forget my set-up (automatic)")); + m->on_item = padtype_item; + menu_open(ui, m); +} + +/* How a controller is set up, for the list: its kind and where the mapping + * comes from */ +static const char *padcfg_value(const struct input_device_info *di) +{ + bool user = di->source == IN_MAP_USER; + bool known = di->source == IN_MAP_GCDB || di->source == IN_MAP_PROFILE; + + /* TRANSLATORS: how a controller is set up (the value next to its name): + * your own mapping of an N64 / GameCube / other pad, a known N64 / + * GameCube / other pad, the Linux standard, a keyboard, none */ + if (di->type == IN_PAD_N64 && (user || known)) + return user ? _("N64, custom") : _("N64"); + if (di->type == IN_PAD_GC && (user || known)) + return user ? _("GameCube, custom") : _("GameCube"); + return user ? _("custom") : known ? _("known pad") : + di->source == IN_MAP_GAMEPAD_SPEC ? _("standard") : + di->source == IN_MAP_KEYBOARD ? _("keyboard") : _("not configured"); +} + static void padcfg_item(struct ui *ui, struct menu *m, struct menu_item *it, int dir) { (void)m; if (dir == 0 && it->id >= ID_PAD0) - wizard_open(ui, it->id - ID_PAD0); + padtype_open(ui, it->id - ID_PAD0); } static void open_padcfg(struct ui *ui) @@ -686,13 +834,7 @@ static void open_padcfg(struct ui *ui) if (!di.present || di.builtin || !strncmp(di.path, "", 1)) continue; it = menu_add(m, MI_ACTION, ID_PAD0 + i, di.name); - /* TRANSLATORS: how a controller is set up: your own mapping, from the - * database of known pads, the Linux standard, a keyboard, none */ - snprintf(it->value, sizeof(it->value), "%s", - di.source == IN_MAP_USER ? _("custom") : - di.source == IN_MAP_GCDB ? _("known pad") : - di.source == IN_MAP_GAMEPAD_SPEC ? _("standard") : - di.source == IN_MAP_KEYBOARD ? _("keyboard") : _("not configured")); + snprintf(it->value, sizeof(it->value), "%s", padcfg_value(&di)); n++; } } @@ -1060,7 +1202,7 @@ void screens_job_done(struct ui *ui, const struct hw_job_result *r) storage_job_done(ui, r); return; } - if (bt_job_done(ui, r)) + if (bt_job_done(ui, r) || store_job_done(ui, r)) return; if (r->tag >= JOB_WIFI && r->tag <= JOB_BT) { int i = r->tag - JOB_WIFI; @@ -1838,7 +1980,7 @@ static void open_time(struct ui *ui) /* ---------------------------------------------------------------- main menu */ /* Settings > System update (ui/update_ui.c, docs/updates.md) */ -enum { ID_SYSUPDATE = 290 }; +enum { ID_SYSUPDATE = 290, ID_STORE = 291 }; static void main_refresh(struct ui *ui, struct menu *m) { @@ -1865,6 +2007,7 @@ static void main_item(struct ui *ui, struct menu *m, struct menu_item *it, int d case ID_STORAGE: open_storage(ui); break; case ID_INFO: open_info(ui); break; case ID_SYSUPDATE: update_open(ui); break; + case ID_STORE: store_open(ui); break; case ID_DATETIME: open_time(ui); break; case ID_POWER: open_power(ui); break; case ID_LANGUAGE: language_open(ui, false); break; @@ -1901,6 +2044,9 @@ void settings_open_main(struct ui *ui) if (update_available(ui)) /* TRANSLATORS: Settings item: check for and install a new RetroStoneOS version */ menu_add(m, MI_SUBMENU, ID_SYSUPDATE, _("System update")); + if (store_available(ui)) + /* TRANSLATORS: Settings item: download homebrew and freeware games */ + menu_add(m, MI_SUBMENU, ID_STORE, _("Game store")); menu_add(m, MI_SUBMENU, ID_DATETIME, _("Date & time")); menu_add(m, MI_SUBMENU, ID_POWER, C_("settings", "Power")); /* TRANSLATORS: Settings item: find a game by its name in every system */ @@ -2394,16 +2540,58 @@ static void delete_saves_answer(struct ui *ui, int choice, void *user) game_delete_finish(ui, choice == 1); /* 0 NO (selected), 1 YES, -1 (B) no */ } +/* A Ports launcher the game store installed: the store removes the whole port + * (rsos-store remove-path: its program and the data made from the ROM; the + * game's saves and settings stay), not the launcher alone. True if it did; + * false for any other game (not in native/, not from the store, the store + * busy with an install), which is then deleted as usual. Quick (a few + * files), so it runs here and is waited for. */ +static bool game_delete_by_store(struct ui *ui, const char *path) +{ + const char *helper = ui->cfg.store_helper, *roms = ui->cfg.roms_dir ? ui->cfg.roms_dir : "/data/roms"; + char native[600]; + size_t l; + pid_t pid; + int st; + + snprintf(native, sizeof(native), "%s/native/", roms); + l = strlen(native); + if (!helper || access(helper, X_OK) < 0 || strncmp(path, native, l) || strchr(path + l, '/') || + ui_store_busy(ui)) + return false; + pid = fork(); + if (pid < 0) + return false; + if (pid == 0) { + int fd = open("/dev/null", O_WRONLY); + + if (fd >= 0) { + dup2(fd, 1); + dup2(fd, 2); + } + execl(helper, helper, "--roms", roms, "remove-path", path, (char *)NULL); + _exit(127); + } + while (waitpid(pid, &st, 0) < 0 && errno == EINTR) + ; + if (!WIFEXITED(st) || WEXITSTATUS(st) != 0) + return false; + LOGI("ui: %s: the game store removed its port", path); + return true; +} + static void delete_answer(struct ui *ui, int choice, void *user) { const char *buttons[3]; struct screen *d; + bool by_store; int n; (void)user; if (choice != 0) return; /* CANCEL (selected) or B */ - if (unlink(g_del.path) < 0) { + by_store = game_delete_by_store(ui, g_del.path); + if (unlink(g_del.path) < 0 && !(by_store && errno == ENOENT)) { char msg[400]; /* TRANSLATORS: the game file could not be deleted; %s is the system's reason */ @@ -2496,7 +2684,7 @@ static void game_delete_ask(struct ui *ui, struct game *g) * or .m3u keeps the track / disc files it lists (they are not renamed). */ struct ren_ctx { - char system[32], path[1024], rel[1024], root[1024], stem[256], ext[32]; + char system[32], esys[32], path[1024], rel[1024], root[1024], stem[256], ext[32]; }; static struct ren_ctx g_ren; @@ -2534,7 +2722,7 @@ static void rename_cover_answer(struct ui *ui, int choice, void *user) { (void)user; if (choice == 0) - covers_start_one(ui, g_ren.system, g_ren.root, g_ren.path); + covers_start_one(ui, g_ren.esys, g_ren.root, g_ren.path); } static void rename_done(struct ui *ui, const char *text, bool ok, void *user) @@ -2581,9 +2769,9 @@ static void rename_done(struct ui *ui, const char *text, bool ok, void *user) snprintf(sub, sizeof(sub), "%s/media/covers", g_ren.root); rename_by_stem(sub, g_ren.stem, name); path_dirname(ui->cfg.data_dir, root, sizeof(root)); - snprintf(sub, sizeof(sub), "%s/saves/%s", root, g_ren.system); + snprintf(sub, sizeof(sub), "%s/saves/%s", root, g_ren.esys); nsaves += rename_by_stem(sub, g_ren.stem, name); - snprintf(sub, sizeof(sub), "%s/states/%s", root, g_ren.system); + snprintf(sub, sizeof(sub), "%s/states/%s", root, g_ren.esys); nsaves += rename_by_stem(sub, g_ren.stem, name); slash = strrchr(g_ren.rel, '/'); if (slash) @@ -2620,6 +2808,8 @@ static void game_rename_ask(struct ui *ui, struct game *g) return; memset(&g_ren, 0, sizeof(g_ren)); strlcpy_(g_ren.system, g->system, sizeof(g_ren.system)); + /* its saves and covers go by the system it launches as */ + strlcpy_(g_ren.esys, systems_effective(g->system, g->path), sizeof(g_ren.esys)); strlcpy_(g_ren.path, g->path, sizeof(g_ren.path)); strlcpy_(g_ren.rel, g->rel, sizeof(g_ren.rel)); /* the system's ROM folder (the covers' parent): the path without rel */ diff --git a/frontend/src/ui/storage.c b/frontend/src/ui/storage.c index 9040f3e..b402bc8 100644 --- a/frontend/src/ui/storage.c +++ b/frontend/src/ui/storage.c @@ -1322,7 +1322,7 @@ void covers_start(struct ui *ui) lr = strlen(g->rel); if (lr + 1 >= lp || strcmp(g->path + lp - lr, g->rel) || g->path[lp - lr - 1] != '/') continue; - fprintf(f, "%s\t%.*s\t%s\n", se->name, (int)(lp - lr - 1), g->path, g->path); + fprintf(f, "%s\t%.*s\t%s\n", systems_effective(g->system, g->path), (int)(lp - lr - 1), g->path, g->path); n++; } nsys += n > before; diff --git a/frontend/src/ui/store_ui.c b/frontend/src/ui/store_ui.c new file mode 100644 index 0000000..f0af13d --- /dev/null +++ b/frontend/src/ui/store_ui.c @@ -0,0 +1,768 @@ +/* + * store_ui.c - Settings > Game store (docs/store-design.md, docs/store-ports.md): the games the signed + * catalog offers, grouped by system. A opens a game: its description, author, licence and size, with INSTALL + * (or UPDATE) and REMOVE. With several game drives, INSTALL asks where. + * + * A port (a game made from the player's own ROM) first looks for that ROM (rsos-store find-rom): found, + * INSTALL downloads the package and prepares the game data from the ROM; not found, the page says which game + * and where to put it, and LOOK AGAIN searches again. Preparing can take minutes and nearly all the memory, so + * the page asks first, wants the charger or a charged battery, and the idle power-off waits (ui_store_busy). + * Leaving the screen while a port installs cancels it (the helper cleans up what it made). + * + * All the work is done by the rsos-store helper (ui->cfg.store_helper), run as a helper job (hw_job_start) + * that writes its lines into a file; it never blocks the menu: + * rsos-store --out F list + * rsos-store --out F [--roms D] [--scan MOUNT]... find-rom ID + * rsos-store --out F [--roms D] [--rom FILE] get ID | install-port ID | remove ID + * One job at a time. + */ +#include +#include +#include +#include +#include +#include +#include + +#include "ui_internal.h" + +enum { K_STORE = 150 }; +enum { ID_S_NOTE = 1, ID_S_E0 = 100 }; +enum { J_NONE = 0, J_LIST, J_GET, J_REMOVE, J_FIND, J_PORT }; +enum { A_INSTALL = 1, A_REMOVE, A_LOOK }; + +#define SE_MAX 96 +#define POLL_MS 600 +#define BATTERY_MIN 40 /* percent, without a charger, to prepare a port */ + +struct sentry { + char id[48], name[96], system[32], version[32], author[64], license[64], desc[480], kind[8]; + char installed[32], rom[96], mode[8]; + long long size; + int minutes; + bool update; +}; + +static struct { + struct menu *m; + struct sentry e[SE_MAX]; + int n; + char path[96]; + int job_kind, job; + int cur; /* the entry the job or dialog is about */ + bool loaded, failed; + char root[1100]; /* the drive's root for the install ("" = the system's) */ + int dlg_act[3]; + int ntargets; + const char *troots[4]; + const char *tlabels[4]; + int pct; /* the download or the preparing, -1 unknown */ + char phase[16]; + char rom_path[1100]; /* the ROM a find-rom found for the entry in T.cur ("" = none) */ + bool port_going; /* a port install runs (also after the screen is closed) */ +} T; + +bool store_available(const struct ui *ui) +{ + return ui->cfg.store_helper && *ui->cfg.store_helper && access(ui->cfg.store_helper, X_OK) == 0; +} + +/* A port is being installed or a game downloaded (no idle power-off). */ +bool ui_store_busy(const struct ui *ui) +{ + (void)ui; + return T.job && (T.job_kind == J_PORT || T.job_kind == J_GET); +} + +/* ------------------------------------------------------------ parsing */ +static void unescape(char *s) +{ + char *o = s; + + for (; *s; s++) { + if (*s == '\\' && s[1]) { + s++; + *o++ = *s == 'n' ? '\n' : *s == 't' ? '\t' : *s; + } else { + *o++ = *s; + } + } + *o = 0; +} + +/* "typek=vk=v" */ +struct fields { + char *type; + int n; + char *k[16], *v[16]; +}; + +static void split(char *line, struct fields *f) +{ + char *p = line; + + f->n = 0; + f->type = p; + p = strchr(p, '\t'); + if (p) + *p++ = 0; + while (p && f->n < 16) { + char *next = strchr(p, '\t'), *eq; + + if (next) + *next++ = 0; + eq = strchr(p, '='); + if (eq) { + *eq++ = 0; + unescape(eq); + f->k[f->n] = p; + f->v[f->n++] = eq; + } + p = next; + } +} + +static const char *fget(const struct fields *f, const char *key) +{ + for (int i = 0; i < f->n; i++) + if (!strcmp(f->k[i], key)) + return f->v[i]; + return ""; +} + +/* the next line of a buffer being cut up in place */ +static bool next_line(char **save, char **line) +{ + char *nl; + + if (!*save || !**save) + return false; + *line = *save; + nl = strchr(*save, '\n'); + if (nl) { + *nl = 0; + *save = nl + 1; + } else { + *save += strlen(*save); + } + return true; +} + +/* The last "ok" or "error" line of an output file, as fields (the buffer is cut up). */ +static bool read_result(char *buf, struct fields *f, char *errtext, size_t en) +{ + char *save = buf, *l; + bool have = false; + + while (next_line(&save, &l)) { + if (!strncmp(l, "ok", 2) || !strncmp(l, "error", 5)) { + split(l, f); + have = true; + if (en) + strlcpy_(errtext, fget(f, "text"), en); + } + } + return have; +} + +static void load_list(const char *buf_in) +{ + char *copy = strdup(buf_in), *save, *l; + + T.n = 0; + if (!copy) + return; + save = copy; + while (next_line(&save, &l) && T.n < SE_MAX) { + struct fields f; + struct sentry *e = &T.e[T.n]; + + if (strncmp(l, "entry\t", 6)) + continue; + split(l, &f); + memset(e, 0, sizeof(*e)); + strlcpy_(e->id, fget(&f, "id"), sizeof(e->id)); + strlcpy_(e->name, fget(&f, "name"), sizeof(e->name)); + strlcpy_(e->system, fget(&f, "system"), sizeof(e->system)); + strlcpy_(e->version, fget(&f, "version"), sizeof(e->version)); + strlcpy_(e->author, fget(&f, "author"), sizeof(e->author)); + strlcpy_(e->license, fget(&f, "license"), sizeof(e->license)); + strlcpy_(e->desc, fget(&f, "desc"), sizeof(e->desc)); + strlcpy_(e->kind, fget(&f, "kind"), sizeof(e->kind)); + strlcpy_(e->installed, fget(&f, "installed"), sizeof(e->installed)); + strlcpy_(e->rom, fget(&f, "rom"), sizeof(e->rom)); + strlcpy_(e->mode, fget(&f, "mode"), sizeof(e->mode)); + e->minutes = atoi(fget(&f, "minutes")); + e->size = atoll(fget(&f, "size")); + e->update = !strcmp(fget(&f, "update"), "1"); + if (e->id[0] && e->name[0]) + T.n++; + } + free(copy); +} + +static bool is_port(const struct sentry *e) +{ + return !strcmp(e->kind, "port"); +} + +/* ------------------------------------------------------------ screen */ +static const char *system_title(struct ui *ui, const char *sys) +{ + if (!strcmp(sys, "native")) + /* TRANSLATORS: Game store: the heading of the native games (the Ports system) */ + return _("Ports"); + for (int i = 0; i < ui->nsys; i++) + if (!ui->sys[i].is_collection && !strcmp(ui->sys[i].name, sys) && ui->sys[i].fullname[0]) + return ui->sys[i].fullname; + return sys; +} + +/* the value right of the game a job is working on */ +static void busy_value(struct menu_item *it) +{ + if (T.job_kind == J_FIND) { + /* TRANSLATORS: Game store: looking for the player's ROM of a port */ + strlcpy_(it->value, _("looking for your ROM..."), sizeof(it->value)); + } else if (!strcmp(T.phase, "extract")) { + if (T.pct >= 0) + /* TRANSLATORS: Game store: preparing a port's game data from the ROM; %d is the percent */ + snprintf(it->value, sizeof(it->value), _("preparing %d%%"), T.pct); + else + strlcpy_(it->value, _("preparing..."), sizeof(it->value)); + } else if (!strcmp(T.phase, "download") && T.pct >= 0) { + /* TRANSLATORS: Game store: %d is the percent downloaded */ + snprintf(it->value, sizeof(it->value), _("%d%%"), T.pct); + } else if (!strcmp(T.phase, "install") || !strcmp(T.phase, "verify")) { + /* TRANSLATORS: Game store: the downloaded game is checked and put in place */ + strlcpy_(it->value, _("installing..."), sizeof(it->value)); + } else { + /* TRANSLATORS: Game store: a game is being installed or removed */ + strlcpy_(it->value, _("please wait..."), sizeof(it->value)); + } +} + +static void items(struct ui *ui, struct menu *m) +{ + struct menu_item *it; + char seen[SE_MAX][32]; + int nseen = 0; + + m->n = 0; + if (T.job_kind == J_LIST) { + /* TRANSLATORS: Game store: the catalog is being loaded */ + it = menu_add(m, MI_INFO, ID_S_NOTE, _("Loading the catalog...")); + it->disabled = true; + return; + } + if (T.failed || !T.n) { + /* TRANSLATORS: Game store: the catalog could not be loaded (no network, or nothing in it) */ + it = menu_add(m, MI_INFO, ID_S_NOTE, + T.failed ? _("Could not load the catalog. Check the network (WiFi or Ethernet).") : _("The store is empty")); + it->disabled = true; + return; + } + for (int i = 0; i < T.n; i++) { + bool done = false; + + for (int k = 0; k < nseen; k++) + done |= !strcmp(seen[k], T.e[i].system); + if (done) + continue; + strlcpy_(seen[nseen++], T.e[i].system, sizeof(seen[0])); + menu_add(m, MI_HEADER, 0, system_title(ui, T.e[i].system)); + for (int j = 0; j < T.n; j++) { + const struct sentry *e = &T.e[j]; + char sz[32]; + + if (strcmp(e->system, T.e[i].system)) + continue; + it = menu_add(m, MI_ACTION, ID_S_E0 + j, e->name); + if (T.job_kind && T.cur == j) { + busy_value(it); + } else if (e->installed[0]) { + /* TRANSLATORS: Game store: right of a game: installed / a newer version exists */ + strlcpy_(it->value, e->update ? _("update") : _("installed"), sizeof(it->value)); + } else if (is_port(e)) { + /* TRANSLATORS: Game store: right of a port that needs the player's own ROM */ + strlcpy_(it->value, _("needs your ROM"), sizeof(it->value)); + } else { + format_bytes((uint64_t)e->size, sz, sizeof(sz)); + strlcpy_(it->value, sz, sizeof(it->value)); + } + } + } +} + +static void rebuild(struct ui *ui, struct menu *m) +{ + int cur_id = m->cursor >= 0 && m->cursor < m->n ? m->items[m->cursor].id : 0; + + items(ui, m); + m->cursor = 0; + for (int i = 0; i < m->n; i++) + if (m->items[i].id == cur_id) + m->cursor = i; + for (int k = 0; k < m->n && (m->items[m->cursor].type == MI_HEADER || m->items[m->cursor].disabled); k++) + m->cursor = (m->cursor + 1) % m->n; + m->top = MIN(m->top, m->cursor); + ui->dirty = true; +} + +/* ------------------------------------------------------------- jobs */ +/* the drives a USB stick may be mounted on: ROMs are looked for there too */ +static int usb_mounts(char out[3][300]) +{ + DIR *d = opendir("/media"); + struct dirent *de; + int n = 0; + + if (!d) + return 0; + while ((de = readdir(d)) && n < 3) { + if (de->d_name[0] == '.') + continue; + snprintf(out[n++], 300, "/media/%s", de->d_name); + } + closedir(d); + return n; +} + +static int run_helper(struct ui *ui, const char *cmd, const char *arg, const char *roms, const char *rom, int tag) +{ + const char *argv[24]; + char mounts[3][300]; + int n = 0, nm = 0; + + argv[n++] = ui->cfg.store_helper; + argv[n++] = "--out"; + argv[n++] = T.path; + if (roms && *roms) { + argv[n++] = "--roms"; + argv[n++] = roms; + } + if (rom && *rom) { + argv[n++] = "--rom"; + argv[n++] = rom; + } + if (!strcmp(cmd, "find-rom") || !strcmp(cmd, "install-port")) + for (nm = usb_mounts(mounts); nm > 0; nm--) { + argv[n++] = "--scan"; + argv[n++] = mounts[nm - 1]; + } + argv[n++] = cmd; + if (arg) + argv[n++] = arg; + argv[n] = NULL; + unlink(T.path); + return hw_job_start(argv, tag); +} + +static void roms_of(struct ui *ui, const char *root, char *out, size_t n) +{ + if (root && *root) + snprintf(out, n, "%s/roms", root); + else + snprintf(out, n, "%s", ui->cfg.roms_dir ? ui->cfg.roms_dir : "/data/roms"); +} + +static void start_list(struct ui *ui) +{ + int id; + + if (T.job) + return; + id = run_helper(ui, "list", NULL, NULL, NULL, UI_JOB_STORE); + if (id < 0) { + T.failed = true; + return; + } + T.job = id; + T.job_kind = J_LIST; + T.failed = false; +} + +static void start_action(struct ui *ui, int kind, int idx, const char *root, const char *rom) +{ + char roms[1200]; + const char *cmd = kind == J_GET ? "get" : kind == J_PORT ? "install-port" : "remove"; + int id; + + if (T.job) + return; + roms_of(ui, root, roms, sizeof(roms)); + id = run_helper(ui, cmd, T.e[idx].id, roms, rom, UI_JOB_STORE); + if (id < 0) { + ui_toastf(ui, _("Cannot run %s"), ui->cfg.store_helper); + return; + } + T.job = id; + T.job_kind = kind; + T.cur = idx; + T.pct = -1; + T.phase[0] = 0; + if (T.m) + rebuild(ui, T.m); +} + +static void start_find(struct ui *ui, int idx) +{ + char roms[1200]; + int id; + + if (T.job) + return; + roms_of(ui, NULL, roms, sizeof(roms)); + id = run_helper(ui, "find-rom", T.e[idx].id, roms, NULL, UI_JOB_STORE); + if (id < 0) { + ui_toastf(ui, _("Cannot run %s"), ui->cfg.store_helper); + return; + } + T.job = id; + T.job_kind = J_FIND; + T.cur = idx; + T.rom_path[0] = 0; + T.phase[0] = 0; + T.pct = -1; + if (T.m) + rebuild(ui, T.m); +} + +/* the last progress line of the running download or install */ +static void read_progress(struct ui *ui) +{ + size_t len = 0; + char *buf = file_read(T.path, &len), *p; + int pct = T.pct; + char phase[16]; + + if (!buf) + return; + strlcpy_(phase, T.phase, sizeof(phase)); + p = strstr(buf, "progress"); + while (p) { + char *nl = strchr(p, '\n'), *next = nl ? strstr(nl, "progress") : NULL; + + if (!next) { + struct fields f; + char line[256]; + long long done, total; + + strlcpy_(line, p, sizeof(line)); + line[strcspn(line, "\n")] = 0; + split(line, &f); + strlcpy_(phase, fget(&f, "phase"), sizeof(phase)); + done = atoll(fget(&f, "done")); + total = atoll(fget(&f, "total")); + if ((!strcmp(phase, "download") || !strcmp(phase, "extract")) && total > 0) { + pct = (int)(done * 100 / total); + if (pct > 99) + pct = 99; + } else { + pct = -1; + } + break; + } + p = next; + } + free(buf); + if (pct != T.pct || strcmp(phase, T.phase)) { + T.pct = pct; + strlcpy_(T.phase, phase, sizeof(T.phase)); + if (T.m) + rebuild(ui, T.m); + } +} + +static void refresh(struct ui *ui, struct menu *m) +{ + (void)m; + if (T.job_kind == J_GET || T.job_kind == J_PORT) + read_progress(ui); +} + +/* a helper error code -> the player's words */ +static void error_message(struct ui *ui, const char *code, const char *text) +{ + if (!strcmp(code, "space")) + /* TRANSLATORS: Game store: not enough free space on the drive */ + message_open(ui, _("There is not enough free space on that drive.")); + else if (!strcmp(code, "exists")) + /* TRANSLATORS: Game store: a file with that name is already there and was not installed by the store */ + message_open(ui, _("A file with the same name is already there. Rename or move it first.")); + else if (!strcmp(code, "hash") || !strcmp(code, "size")) + /* TRANSLATORS: Game store: the download is damaged or has been changed */ + message_open(ui, _("The download did not match the catalog and was thrown away.")); + else if (!strcmp(code, "archive")) + /* TRANSLATORS: Game store: the package is not safe to unpack */ + message_open(ui, _("The package is not valid and was not installed.")); + else if (!strcmp(code, "memory")) + /* TRANSLATORS: Game store: preparing a port needs nearly all the memory */ + message_open(ui, _("Preparing the game needs more free memory. Restart the console and try again " + "before starting anything else.")); + else if (!strcmp(code, "timeout")) + /* TRANSLATORS: Game store: preparing the game data took far too long and was stopped */ + message_open(ui, _("Preparing the game data took too long and was stopped. Nothing was installed.")); + else if (!strcmp(code, "extract") || !strcmp(code, "rom")) + /* TRANSLATORS: Game store: the game data could not be made from the ROM */ + message_open(ui, _("The game data could not be made from your ROM. Nothing was installed.")); + else if (!strcmp(code, "norom")) + /* TRANSLATORS: Game store: the ROM is not the one the port needs */ + message_open(ui, _("That is not the ROM this game needs.")); + else if (!strcmp(code, "cancelled")) + return; + else + /* TRANSLATORS: Game store: the download failed (network) */ + message_open(ui, _("The game could not be downloaded. Check the network (WiFi or Ethernet) and try again.")); + LOGW("store: %s: %s", code, text); +} + +static void port_dialog(struct ui *ui); + +bool store_job_done(struct ui *ui, const struct hw_job_result *r) +{ + size_t len = 0; + char *buf; + int kind = T.job_kind, cur = T.cur; + + if (r->tag != UI_JOB_STORE) + return false; + T.job = 0; + T.job_kind = J_NONE; + buf = file_read(T.path, &len); + if (!buf) + buf = strdup(""); + if (kind == J_LIST) { + load_list(buf); + T.loaded = true; + T.failed = r->status != 0 || !strstr(buf, "\ndone") ? (strstr(buf, "entry\t") == NULL) : false; + if (T.failed) + LOGW("store: list: %s", buf); + } else if (kind == J_FIND) { + char *copy = strdup(buf), *save = copy, *l; + + T.rom_path[0] = 0; + while (copy && next_line(&save, &l)) { + if (!strncmp(l, "rom\t", 4)) { + struct fields f; + + split(l, &f); + strlcpy_(T.rom_path, fget(&f, "path"), sizeof(T.rom_path)); + } + } + free(copy); + if (T.m) + rebuild(ui, T.m); + free(buf); + port_dialog(ui); + return true; + } else if (cur >= 0 && cur < T.n) { + struct fields f; + char text[256] = ""; + bool have = buf && read_result(buf, &f, text, sizeof(text)); + + if (have && !strcmp(f.type, "ok")) { + struct sentry *e = &T.e[cur]; + + if (kind == J_GET || kind == J_PORT) { + strlcpy_(e->installed, e->version, sizeof(e->installed)); + e->update = false; + /* TRANSLATORS: Game store: toast after an install; %s is the game's name */ + ui_toastf(ui, _("%s installed"), e->name); + } else { + e->installed[0] = 0; + e->update = false; + /* TRANSLATORS: Game store: toast after a removal; %s is the game's name */ + ui_toastf(ui, _("%s removed"), e->name); + } + ui_invalidate_system(ui, !strcmp(e->system, "native") ? "native" : e->system); + ui->reload_pending = true; + } else if (have) { + error_message(ui, fget(&f, "code"), text); + } else { + error_message(ui, "download", r->out); + } + } + free(buf); + if (T.m) + rebuild(ui, T.m); + ui->dirty = true; + return true; +} + +/* ----------------------------------------------------------- dialogs */ +static void where_choice(struct ui *ui, int choice, void *user) +{ + (void)user; + if (choice < 0 || choice >= T.ntargets) + return; + start_action(ui, J_GET, T.cur, T.troots[choice], NULL); +} + +/* a port's install: the charger or a charged battery first, then the question, then the job */ +static void port_start(struct ui *ui, int choice, void *user) +{ + (void)user; + if (choice == 0) + start_action(ui, J_PORT, T.cur, NULL, T.rom_path); +} + +static void port_install(struct ui *ui) +{ + const struct sentry *e = &T.e[T.cur]; + const struct power_status *ps = ui_battery(ui); + const char *buttons[3]; + char text[500]; + + if (!strcmp(e->mode, "extract") && ps && ps->valid && ps->battery_present && !ps->charger_online && + ps->percent >= 0 && ps->percent < BATTERY_MIN) { + /* TRANSLATORS: Game store: preparing a port takes minutes; plug in the charger first; %d is the percent */ + ui_toastf(ui, _("Plug in the charger first (battery %d%%)"), ps->percent); + return; + } + if (strcmp(e->mode, "extract")) { + start_action(ui, J_PORT, T.cur, NULL, T.rom_path); + return; + } + /* TRANSLATORS: Game store: before preparing a port's game data from the player's ROM; %d is the minutes */ + snprintf(text, sizeof(text), _("Preparing the game data from your ROM takes about %d minutes. Keep the " + "console on and nothing else running."), e->minutes > 0 ? e->minutes : 5); + /* TRANSLATORS: dialog buttons, uppercase, short */ + buttons[0] = _("START"); + buttons[1] = _("CANCEL"); + buttons[2] = NULL; + dialog_open(ui, text, buttons, port_start, NULL); +} + +static void entry_choice(struct ui *ui, int choice, void *user) +{ + (void)user; + if (choice < 0 || choice >= 3 || !T.dlg_act[choice]) + return; + if (T.dlg_act[choice] == A_REMOVE) { + start_action(ui, J_REMOVE, T.cur, NULL, NULL); + return; + } + if (T.dlg_act[choice] == A_LOOK) { + start_find(ui, T.cur); + return; + } + if (is_port(&T.e[T.cur])) { + port_install(ui); + return; + } + T.ntargets = storage_import_targets(ui, T.troots, T.tlabels, 4); + if (T.ntargets > 1 && !T.e[T.cur].installed[0]) { + const char *buttons[6]; + int n = 0; + + for (int i = 0; i < T.ntargets; i++) + buttons[n++] = T.tlabels[i]; + buttons[n] = NULL; + /* TRANSLATORS: Game store: the question when several drives could hold the game */ + dialog_open(ui, _("Install on which drive?"), buttons, where_choice, NULL); + return; + } + start_action(ui, J_GET, T.cur, NULL, NULL); +} + +/* a game's page */ +static void page(struct ui *ui, const char *extra) +{ + const struct sentry *e = &T.e[T.cur]; + const char *buttons[4]; + char text[1200], sz[32]; + int n = 0; + + format_bytes((uint64_t)e->size, sz, sizeof(sz)); + /* TRANSLATORS: Game store: a game's page; %1$s name, %2$s version, %3$s author, %4$s licence, + * %5$s download size, %6$s the description */ + snprintf(text, sizeof(text), _("%1$s %2$s\nby %3$s - %4$s\n%5$s\n\n%6$s"), e->name, e->version, e->author, + e->license, sz, e->desc); + if (extra && *extra) { + size_t l = strlen(text); + + snprintf(text + l, sizeof(text) - l, "\n\n%s", extra); + } + memset(T.dlg_act, 0, sizeof(T.dlg_act)); + if (is_port(e) && T.rom_path[0] == 0 && (!e->installed[0] || e->update)) { + /* TRANSLATORS: Game store dialog button: search for the ROM again */ + buttons[n] = _("LOOK AGAIN"); + T.dlg_act[n++] = A_LOOK; + } else if (!e->installed[0] || e->update) { + /* TRANSLATORS: Game store dialog buttons, uppercase, short */ + buttons[n] = e->update ? _("UPDATE") : _("INSTALL"); + T.dlg_act[n++] = A_INSTALL; + } + if (e->installed[0]) { + buttons[n] = _("REMOVE"); + T.dlg_act[n++] = A_REMOVE; + } + buttons[n++] = _("CANCEL"); + buttons[n] = NULL; + dialog_open(ui, text, buttons, entry_choice, NULL); +} + +/* after the ROM search: the page with what was found */ +static void port_dialog(struct ui *ui) +{ + const struct sentry *e = &T.e[T.cur]; + char extra[400]; + + if (T.rom_path[0]) { + const char *base = strrchr(T.rom_path, '/'); + + /* TRANSLATORS: Game store: a port's page, the ROM found; %s is the file name */ + snprintf(extra, sizeof(extra), _("Your ROM: %s"), base ? base + 1 : T.rom_path); + } else { + /* TRANSLATORS: Game store: a port's page, no ROM found; %s is the game and version it needs */ + snprintf(extra, sizeof(extra), _("Needs your own ROM: %s. Put it in your N64 folder or on a USB " + "drive, then choose LOOK AGAIN."), e->rom); + } + page(ui, extra); +} + +static void item(struct ui *ui, struct menu *m, struct menu_item *it, int dir) +{ + (void)m; + if (dir || it->id < ID_S_E0 || it->id >= ID_S_E0 + T.n) + return; + if (T.job) { + ui_toastf(ui, "%s", _("please wait...")); + return; + } + T.cur = it->id - ID_S_E0; + T.rom_path[0] = 0; + if (is_port(&T.e[T.cur]) && (!T.e[T.cur].installed[0] || T.e[T.cur].update)) { + start_find(ui, T.cur); + return; + } + page(ui, NULL); +} + +static void destroy(struct ui *ui, struct menu *m) +{ + (void)ui; + (void)m; + T.m = NULL; + /* leaving while a port installs cancels it: the helper stops its extractor and cleans up */ + if (T.job && T.job_kind == J_PORT) + hw_job_kill(T.job, SIGTERM); +} + +void store_open(struct ui *ui) +{ + /* TRANSLATORS: Settings: the game store (homebrew and freeware downloads) */ + struct menu *m = menu_new(ui, _("Game store"), K_STORE); + + snprintf(T.path, sizeof(T.path), "/tmp/rsos-store-%d.out", (int)getpid()); + T.m = m; + m->on_item = item; + m->on_refresh = refresh; + m->on_destroy = destroy; + m->refresh_every = POLL_MS; + if (!T.job) + start_list(ui); + items(ui, m); + menu_open(ui, m); +} diff --git a/frontend/src/ui/systems.c b/frontend/src/ui/systems.c index 903ed76..ebffb70 100644 --- a/frontend/src/ui/systems.c +++ b/frontend/src/ui/systems.c @@ -67,6 +67,13 @@ static const struct sysdef g_systems[] = { { "pico8", NC_("system", "PICO-8"), "Fantasy console", { "pico8", "pico-8", NULL }, { "pico-8", NULL }, "fake08", "p8,png", 2015 }, { "doom", NC_("system", "Doom"), "Ports", { "doom", "ports", NULL }, { "prboom", NULL }, "prboom", "wad,iwad,pwad", 1993 }, { "cavestory", NC_("system", "Cave Story"), "Ports", { "cavestory", "ports", NULL }, { "nxengine", NULL }, "nxengine", "exe", 2004 }, + /* native games: programs built for this console, no emulator (one + * launch script per game, docs/native-games.md) */ + { "native", NC_("system", "Ports"), "Ports", { "native", "ports", NULL }, { NULL }, "", "sh", 0 }, + /* The one Ports entry of the carousel: the games of doom, cavestory and + * native (and of roms/ports) in one list. Each game keeps launching as a + * game of its own system (systems_effective()). */ + { "ports", NC_("system", "Ports"), "Ports", { "ports", NULL }, { NULL }, "", "wad,iwad,pwad,exe,sh", 0 }, }; /* Used only when no core .ini is installed (development host). */ @@ -247,6 +254,33 @@ const struct sysdef *systems_find(const char *name) return NULL; } +bool systems_is_native(const char *system) +{ + return system && !strcmp(system, "native"); +} + +/* The systems the one "ports" entry of the carousel is made of. */ +bool systems_is_ports_member(const char *system) +{ + return system && (!strcmp(system, "doom") || !strcmp(system, "cavestory") || !strcmp(system, "native")); +} + +/* A game of the "ports" list launches as a game of the system it belongs to + * (its core, its saves, its launch script): the extension tells which. */ +const char *systems_effective(const char *system, const char *path) +{ + const char *dot; + + if (!system || strcmp(system, "ports") || !path) + return system; + dot = strrchr(path_basename(path), '.'); + if (dot && !strcasecmp(dot, ".sh")) + return "native"; + if (dot && !strcasecmp(dot, ".exe")) + return "cavestory"; + return "doom"; +} + static bool any_core_runs(const char *system) { for (int i = 0; i < g_ncores; i++) @@ -260,7 +294,9 @@ static void build_list(void) g_list = xrealloc(g_list, sizeof(*g_list) * (ARRAY_SIZE(g_systems) + 64)); g_nlist = 0; for (size_t i = 0; i < ARRAY_SIZE(g_systems); i++) { - if (any_core_runs(g_systems[i].name)) + if (systems_is_ports_member(g_systems[i].name)) + continue; /* shown inside "ports" */ + if (any_core_runs(g_systems[i].name) || !strcmp(g_systems[i].name, "ports")) g_list[g_nlist++] = &g_systems[i]; else LOGD("systems: no core for %s", g_systems[i].name); @@ -301,6 +337,14 @@ int systems_cores_for(const char *system, const struct core_info **out, int max) const struct sysdef *sd = systems_find(system); int n = 0; + if (system && !strcmp(system, "ports")) { + /* the engines of the ports list: Doom's, then Cave Story's */ + n = systems_cores_for("doom", out, max); + if (n < max) + n += systems_cores_for("cavestory", out + n, max - n); + return n; + } + /* 1. the table default (explicit, may be experimental if it is the * only core, e.g. neocd) */ if (sd && sd->default_core[0]) { @@ -331,8 +375,11 @@ int systems_cores_for_file(const char *system, const char *path, const struct core_info **out, int max) { const struct core_info *all[MAX_CORES_PER_SYSTEM]; - int n = systems_cores_for(system, all, MAX_CORES_PER_SYSTEM), k = 0; + int n, k = 0; const char *dot = strrchr(path_basename(path), '.'); + + system = systems_effective(system, path); + n = systems_cores_for(system, all, MAX_CORES_PER_SYSTEM); const char *ext = dot ? dot + 1 : ""; bool archive = !strcasecmp(ext, "zip") || !strcasecmp(ext, "7z"); @@ -353,7 +400,13 @@ const struct core_info *systems_core(const char *id) bool systems_ext_ok(const char *system, const char *ext) { const struct core_info *cs[MAX_CORES_PER_SYSTEM]; - int n = systems_cores_for(system, cs, MAX_CORES_PER_SYSTEM); + int n; + + if (systems_is_native(system)) + return !strcasecmp(ext, "sh"); + if (system && !strcmp(system, "ports")) + return !strcasecmp(ext, "sh") || systems_ext_ok("doom", ext) || systems_ext_ok("cavestory", ext); + n = systems_cores_for(system, cs, MAX_CORES_PER_SYSTEM); for (int i = 0; i < n; i++) if (list_has(cs[i]->exts, ext)) diff --git a/frontend/src/ui/systems.h b/frontend/src/ui/systems.h index e58946c..0c41ab1 100644 --- a/frontend/src/ui/systems.h +++ b/frontend/src/ui/systems.h @@ -62,5 +62,14 @@ int systems_cores_for_file(const char *system, const char *path, const struct core_info *systems_core(const char *id); /* True if ext (no dot, any case) is a ROM extension for the system. */ bool systems_ext_ok(const char *system, const char *ext); +/* "native": games built for the console, started by their own launch + * script (no core) */ +bool systems_is_native(const char *system); +/* "ports": the one carousel entry that lists the games of doom, cavestory and + * native (and roms/ports). Those three are not shown on their own. */ +bool systems_is_ports_member(const char *system); +/* The system a game of the "ports" list launches as (its extension decides: + * .sh native, .exe cavestory, else doom); any other system unchanged. */ +const char *systems_effective(const char *system, const char *path); #endif diff --git a/frontend/src/ui/ui.c b/frontend/src/ui/ui.c index 701e001..43b6fc3 100644 --- a/frontend/src/ui/ui.c +++ b/frontend/src/ui/ui.c @@ -56,6 +56,7 @@ void ui_config_defaults(struct ui_config *cfg) cfg->update_helper = "/usr/bin/rsos-update"; /* used only if it is there */ cfg->smb_helper = "/usr/bin/rsos-smb"; /* the same */ cfg->bt_helper = "/usr/bin/rsos-bt"; /* the same */ + cfg->store_helper = "/usr/bin/rsos-store"; /* the same */ cfg->data_partition_helper = "/usr/libexec/rsos/data-partition"; cfg->storage_helper = "/usr/bin/rsos-storage"; /* used only if it is there */ cfg->wpa_conf = "/data/rsos/wpa_supplicant.conf"; @@ -465,13 +466,14 @@ bool ui_first_boot_busy(const struct ui *ui) /* ---------------------------------------------------------------- launching */ const char *ui_game_core(struct ui *ui, const struct game *g, const char **name) { + const char *sys = systems_effective(g->system, g->path); const struct core_info *cores[MAX_CORES_PER_SYSTEM]; int n = systems_cores_for_file(g->system, g->path, cores, MAX_CORES_PER_SYSTEM); char key[64]; const char *want; const struct core_info *c = NULL; - snprintf(key, sizeof(key), "core.%s", g->system); + snprintf(key, sizeof(key), "core.%s", sys); want = g->core && *g->core ? g->core : settings_get(ui->settings, key, ""); for (int i = 0; i < n && want && *want; i++) if (!strcmp(cores[i]->id, want)) @@ -507,12 +509,12 @@ static void fill_launch(struct ui *ui, const struct game *g, struct ui_launch *r memset(req, 0, sizeof(*req)); req->rom_path = g->path; - req->system = g->system; + req->system = systems_effective(g->system, g->path); req->core = core; req->core_path = ci ? ci->library : ""; req->game_name = g->name; req->bios_dir = ui->cfg.bios_dir; - snprintf(key, sizeof(key), "core.%s", g->system); + snprintf(key, sizeof(key), "core.%s", req->system); sys_core = settings_get(ui->settings, key, ""); req->core_source = g->core && *g->core && !strcmp(g->core, core) ? "game" : sys_core && *sys_core && !strcmp(sys_core, core) ? "system" : "default"; @@ -621,7 +623,7 @@ static struct game *find_game(struct ui *ui, const char *system, const char *rom for (int i = 0; i < ui->nsys; i++) { struct sysent *se = &ui->sys[i]; - if (se->is_collection || strcmp(se->name, system)) + if (se->is_collection || strcmp(se->name, systems_is_ports_member(system) ? "ports" : system)) continue; /* during a game (play time, settings from the game process) only * the lists already there: the loader is paused */ @@ -832,7 +834,7 @@ static void switch_launch(struct ui *ui) req.core = ui->switch_req.core; req.core_path = ci ? ci->library : ""; } - if (!req.core[0]) { + if (!req.core[0] && !systems_is_native(req.system)) { message_open(ui, _("No emulator is installed for this system.")); return; } @@ -935,7 +937,7 @@ void ui_launch_game(struct ui *ui, struct sysent *se, struct game *g) buttons[1] = _("START FRESH"); buttons[2] = NULL; fill_launch(ui, g, &req); - if (!req.core[0]) { + if (!req.core[0] && !systems_is_native(req.system)) { message_open(ui, _("No emulator is installed for this system.")); return; } diff --git a/frontend/src/ui/ui.h b/frontend/src/ui/ui.h index 7b11210..bf13f08 100644 --- a/frontend/src/ui/ui.h +++ b/frontend/src/ui/ui.h @@ -285,6 +285,9 @@ struct ui_config { * the Bluetooth switch while Bluetooth is on; missing / NULL / "": no * such item. The string must outlive the UI. */ const char *bt_helper; /* "/usr/bin/rsos-bt" */ + /* Settings > Game store (store_ui.c): downloads from the signed catalog; + * missing / NULL / "": no such item. The string must outlive the UI. */ + const char *store_helper; /* "/usr/bin/rsos-store" */ /* formats an unreadable /data after the player confirmed it on the * storage screen (ui_data_problem): run with --format-confirmed. The * string must outlive the UI. */ @@ -457,6 +460,8 @@ bool ui_update_busy(const struct ui *ui); /* A storage task (eMMC install, starter card, disk erase) or a game cover * download runs, also in the background (no idle power-off; storage.c). */ bool ui_storage_busy(const struct ui *ui); +/* A game store download or a port install runs (no idle power-off; store_ui.c). */ +bool ui_store_busy(const struct ui *ui); /* True once every game list has been loaded/validated (the background * loader is done and the carousel matches a full load). */ bool ui_lists_complete(const struct ui *ui); diff --git a/frontend/src/ui/ui_internal.h b/frontend/src/ui/ui_internal.h index 9971786..f61937e 100644 --- a/frontend/src/ui/ui_internal.h +++ b/frontend/src/ui/ui_internal.h @@ -566,7 +566,7 @@ void webshare_open(struct ui *ui); * transfer: available (the helper is installed), start (with the transfer's * PIN), stop; the helper's end comes back as a job (UI_JOB_SMB*). */ enum { UI_JOB_SMB = 40, UI_JOB_SMB_STOP = 41, UI_JOB_STORAGE = 42, UI_JOB_STORAGE_TASK = 43, - UI_JOB_BT_LIST = 44, UI_JOB_BT_SCAN = 45, UI_JOB_BT_ACT = 46 }; + UI_JOB_BT_LIST = 44, UI_JOB_BT_SCAN = 45, UI_JOB_BT_ACT = 46, UI_JOB_STORE = 47 }; /* bt_ui.c - Settings > Network > Bluetooth devices (ui->cfg.bt_helper, * rsos-bt): pair, connect and forget controllers. */ @@ -620,6 +620,13 @@ void smb_start(struct ui *ui); void smb_stop(struct ui *ui); void smb_job_done(struct ui *ui, const struct hw_job_result *r); +/* store_ui.c - Settings > Game store (docs/store-design.md): the rsos-store helper + * (ui->cfg.store_helper) lists, installs and removes the games of the signed catalog. */ +bool store_available(const struct ui *ui); /* the helper is installed */ +void store_open(struct ui *ui); +/* true when it was the store's job (UI_JOB_STORE) */ +bool store_job_done(struct ui *ui, const struct hw_job_result *r); + /* update_ui.c - Settings > System update (docs/updates.md): the menu runs * the rsos-update helper (cfg.update_helper) and reads its lines. */ bool update_available(const struct ui *ui); /* a helper is installed */ diff --git a/frontend/src/update/rsos-store.c b/frontend/src/update/rsos-store.c new file mode 100644 index 0000000..f97875d --- /dev/null +++ b/frontend/src/update/rsos-store.c @@ -0,0 +1,2177 @@ +/* + * rsos-store - the game store helper (docs/store-design.md). The menu runs it as + * a helper process (like rsos-covers / rsos-update) and reads its lines: + * + * rsos-store [options] list [SYSTEM] the signed catalog (online, else the cached copy) + * rsos-store [options] get ID download, verify, install + * rsos-store [options] remove ID delete what the store installed for ID + * rsos-store [options] remove-path PATH the same for the game a file belongs to (the menu's Delete + * of a launcher; error code=notstore if no game owns it) + * rsos-store [options] installed what is installed + * rsos-store [options] find-rom ID the player's ROM for a port (by SHA-1), if there is one + * rsos-store [options] install-port ID download, make the game data from the ROM, install + * + * Options: --roms DIR (default /data/roms) --state DIR (/data/rsos/store) + * --pubkey FILE (/usr/share/rsos/store.pub) --url URL | --catalog FILE (local, tests) + * --arch NAME (armhf) --allow-http --cover-dir DIR --max-bytes N + * --scan DIR (more places to look for ROMs, repeatable) --rom FILE (a ROM to use, install-port) + * --out FILE (the lines go there, not to stdout: the menu reads the file) + * + * What is installed is recorded in /installed.tsv for the console's own roms folder (/data/roms). For + * another --roms (a test install into a scratch folder) the record is /.rsos-store/installed.tsv, + * so that install never shows up in the menu's store as installed, nor a remove there touches it. + * + * Output: lines "typekey=value..." (\\ \t \n escaped), the same shape as rsos-update --machine: + * entry id name system version author license desc size kind installed update + * progress phase=download|verify|install done total + * done / ok / error code=... text=... + * + * Nothing is trusted before the catalog's Ed25519 signature checks out, and + * nothing reaches the games folders before the size and SHA-256 of the + * download match the signed catalog entry. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "http.h" +#include "json.h" +#include "rsu.h" +#include "sha1.h" +#include "sha256.h" + +#ifndef STORE_URL +#define STORE_URL "https://raw.githubusercontent.com/KurdtNervanna/RetroStoneOS-Store/main/catalog.json" +#endif +#ifndef STORE_ARCH +#define STORE_ARCH "armhf" +#endif + +#define CATALOG_MAX (4 << 20) +#define COVER_MAX (2 << 20) +#define NAME_MAX_LEN 120 + +struct cfg { + char roms[512], state[512], record[1100], pubkey[512], url[1024], catalog_file[512], arch[32], cover_dir[512]; + bool allow_http; + int64_t max_bytes; + char scan[4][512]; + int nscan; + char rom_arg[512]; +}; + +static struct cfg C; +static volatile int g_cancel; + +static void on_term(int sig) +{ + (void)sig; + g_cancel = 1; +} + +/* ------------------------------------------------------------- output */ +static void field(const char *k, const char *v) +{ + printf("\t%s=", k); + for (const char *p = v ? v : ""; *p; p++) { + if (*p == '\\') + fputs("\\\\", stdout); + else if (*p == '\t') + fputs("\\t", stdout); + else if (*p == '\n') + fputs("\\n", stdout); + else if (*p != '\r') + fputc(*p, stdout); + } +} + +static void fieldf(const char *k, const char *fmt, ...) __attribute__((format(printf, 2, 3))); +static void fieldf(const char *k, const char *fmt, ...) +{ + char b[256]; + va_list ap; + + va_start(ap, fmt); + vsnprintf(b, sizeof(b), fmt, ap); + va_end(ap); + field(k, b); +} + +static void endl(void) +{ + fputc('\n', stdout); + fflush(stdout); +} + +static int fail(const char *code, const char *fmt, ...) __attribute__((format(printf, 2, 3))); +static int fail(const char *code, const char *fmt, ...) +{ + char b[512]; + va_list ap; + + va_start(ap, fmt); + vsnprintf(b, sizeof(b), fmt, ap); + va_end(ap); + printf("error"); + field("code", code); + field("text", b); + endl(); + return 1; +} + +static void progress(const char *phase, uint64_t done, uint64_t total) +{ + static time_t last; + time_t now = time(NULL); + + if (done != total && now == last) + return; + last = now; + printf("progress"); + field("phase", phase); + fieldf("done", "%" PRIu64, done); + fieldf("total", "%" PRIu64, total); + endl(); +} + +/* ------------------------------------------------------------ helpers */ +static void cpy(char *d, size_t n, const char *s) +{ + snprintf(d, n, "%s", s ? s : ""); +} + +static int mkdir_p(const char *path) +{ + char tmp[1024], *p; + + cpy(tmp, sizeof(tmp), path); + for (p = tmp + 1; *p; p++) { + if (*p == '/') { + *p = 0; + if (mkdir(tmp, 0755) < 0 && errno != EEXIST) + return -1; + *p = '/'; + } + } + return mkdir(tmp, 0755) < 0 && errno != EEXIST ? -1 : 0; +} + +/* a file name for the games folder: no path, no leading dot, plain characters */ +static bool safe_name(const char *s) +{ + size_t n = s ? strlen(s) : 0; + + if (n == 0 || n > NAME_MAX_LEN || s[0] == '.') + return false; + for (size_t i = 0; i < n; i++) { + unsigned char c = (unsigned char)s[i]; + + if (c < 0x20 || c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' || c == '"' || + c == '<' || c == '>' || c == '|' || c == 0x7f) + return false; + } + return true; +} + +/* a relative archive path: every component safe, no "..", no absolute path */ +static bool safe_relpath(const char *s) +{ + char tmp[512], *p, *q; + + if (!s || !*s || strlen(s) >= sizeof(tmp) || s[0] == '/') + return false; + cpy(tmp, sizeof(tmp), s); + for (p = tmp; p; p = q) { + q = strchr(p, '/'); + if (q) + *q++ = 0; + if (!*p) { + if (q) + return false; /* "a//b" */ + break; /* trailing slash */ + } + if (!strcmp(p, ".") || !strcmp(p, "..") || !safe_name(p)) + return false; + } + return true; +} + +static int read_all(const char *path, char **out, size_t *len, size_t max) +{ + FILE *f = fopen(path, "rb"); + long n; + char *b; + + if (!f) + return -1; + if (fseek(f, 0, SEEK_END) < 0 || (n = ftell(f)) < 0 || (size_t)n > max || fseek(f, 0, SEEK_SET) < 0) { + fclose(f); + return -1; + } + b = malloc((size_t)n + 1); + if (!b || fread(b, 1, (size_t)n, f) != (size_t)n) { + free(b); + fclose(f); + return -1; + } + fclose(f); + b[n] = 0; + *out = b; + *len = (size_t)n; + return 0; +} + +static int write_atomic(const char *path, const void *data, size_t n) +{ + char tmp[1100]; + int fd; + + snprintf(tmp, sizeof(tmp), "%s.tmp", path); + fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + if (fd < 0) + return -1; + if (write(fd, data, n) != (ssize_t)n || fsync(fd) < 0) { + close(fd); + unlink(tmp); + return -1; + } + close(fd); + return rename(tmp, path); +} + +static void http_opts(struct http_opts *o) +{ + memset(o, 0, sizeof(*o)); + o->timeout_ms = 30000; + o->max_redirects = 5; + o->allow_http = C.allow_http; + o->user_agent = "RetroStoneOS-store"; + o->cancel = &g_cancel; +} + +/* ---------------------------------------------------------------- fetch */ +struct membuf { + char *b; + size_t len, cap, max; +}; + +static int mem_data(const void *data, size_t n, void *user) +{ + struct membuf *m = user; + + if (m->len + n > m->max) + return -1; + if (m->len + n + 1 > m->cap) { + size_t c = (m->len + n + 1) * 2; + char *nb = realloc(m->b, c); + + if (!nb) + return -1; + m->b = nb; + m->cap = c; + } + memcpy(m->b + m->len, data, n); + m->len += n; + m->b[m->len] = 0; + return 0; +} + +static int fetch_mem(const char *url, struct membuf *m, size_t max, char *err, size_t en) +{ + struct http_opts o; + struct http_resp r; + + http_opts(&o); + memset(m, 0, sizeof(*m)); + m->max = max; + if (http_get(&o, url, 0, -1, NULL, mem_data, m, &r, err, en) != RSU_OK) { + free(m->b); + m->b = NULL; + return -1; + } + if (!m->b) + m->b = calloc(1, 1); + return 0; +} + +/* ------------------------------------------------------------- catalog */ +struct catalog { + char *text; /* the verified catalog.json, owned */ + size_t len; + struct json *root; + const struct json *entries; + bool cached; /* the offline copy was used */ +}; + +static void catalog_free(struct catalog *c) +{ + json_free(c->root); + free(c->text); + memset(c, 0, sizeof(*c)); +} + +static int verify_catalog(const char *text, size_t len, const char *sigtext, size_t siglen) +{ + struct rsu_pubkey pk; + struct rsu_sig sg; + + if (rsu_pubkey_load(C.pubkey, &pk) < 0) + return -1; + if (rsu_sig_parse(sigtext, siglen, &sg) < 0) + return -1; + return rsu_verify(&pk, &sg, text, len) ? 0 : -1; +} + +static int catalog_open(struct catalog *c, char *err, size_t en) +{ + char cpath[1100], spath[1100], err2[200] = ""; + struct membuf cat = { 0 }, sig = { 0 }; + char *text = NULL, *st = NULL; + size_t tl = 0, sl = 0; + + memset(c, 0, sizeof(*c)); + snprintf(cpath, sizeof(cpath), "%s/catalog.json", C.state); + snprintf(spath, sizeof(spath), "%s/catalog.json.sig", C.state); + + if (C.catalog_file[0]) { + char sf[600]; + + snprintf(sf, sizeof(sf), "%s.sig", C.catalog_file); + if (read_all(C.catalog_file, &text, &tl, CATALOG_MAX) < 0 || read_all(sf, &st, &sl, 4096) < 0) { + snprintf(err, en, "cannot read %s or its .sig", C.catalog_file); + free(text); + free(st); + return -1; + } + } else { + char url[1100]; + + snprintf(url, sizeof(url), "%s", C.url); + if (fetch_mem(url, &cat, CATALOG_MAX, err2, sizeof(err2)) == 0) { + snprintf(url, sizeof(url), "%s.sig", C.url); + if (fetch_mem(url, &sig, 4096, err2, sizeof(err2)) == 0) { + text = cat.b; + tl = cat.len; + st = sig.b; + sl = sig.len; + cat.b = sig.b = NULL; + } + } + free(cat.b); + free(sig.b); + if (!text) { + /* offline: the last verified copy */ + if (read_all(cpath, &text, &tl, CATALOG_MAX) < 0 || read_all(spath, &st, &sl, 4096) < 0) { + snprintf(err, en, "no network and no saved catalog (%s)", err2); + free(text); + free(st); + return -1; + } + c->cached = true; + } + } + if (verify_catalog(text, tl, st, sl) < 0) { + snprintf(err, en, "the catalog's signature is not valid"); + free(text); + free(st); + return -1; + } + if (!c->cached && !C.catalog_file[0] && mkdir_p(C.state) == 0) { + write_atomic(cpath, text, tl); + write_atomic(spath, st, sl); + } + free(st); + c->text = text; + c->len = tl; + c->root = json_parse(text, tl, err, en); + if (!c->root) { + catalog_free(c); + return -1; + } + if ((int)json_num(c->root, "format", 0) != 1) { + snprintf(err, en, "unknown catalog format"); + catalog_free(c); + return -1; + } + c->entries = json_get(c->root, "entries"); + if (!c->entries || c->entries->type != JSON_ARR) { + snprintf(err, en, "the catalog has no entries"); + catalog_free(c); + return -1; + } + return 0; +} + +enum kind { K_ROM, K_TAR, K_NATIVE, K_PORT }; + +/* A port made from the player's own ROM (kind "port"): which ROM, and what to do with it. */ +struct rominfo { + char name[96], mode[8], dest[96], copy_as[96]; + char sha1[6][41]; + int nsha; + int64_t size[4]; + int nsize; + char output[4][96]; + int nout; + char system[2][32]; + int nsys; + int need_ram_mb, est_min, need_disk_mb; +}; + +struct entry { + const char *id, *name, *system, *version, *author, *license, *desc, *url, *sha, *file, *cover, *launcher; + enum kind kind; + int64_t size, unpacked; + struct rominfo rom; +}; + + +/* the "rom" object of a port entry; false when anything the install needs is missing or unsafe */ +static bool rom_parse(const struct json *j, struct rominfo *r) +{ + const struct json *o = json_get(j, "rom"), *a; + const char *m; + + memset(r, 0, sizeof(*r)); + if (!o || o->type != JSON_OBJ) + return false; + cpy(r->name, sizeof(r->name), json_str(o, "name")); + m = json_str(o, "mode"); + if (!m || (strcmp(m, "extract") && strcmp(m, "copy"))) + return false; + cpy(r->mode, sizeof(r->mode), m); + cpy(r->dest, sizeof(r->dest), json_str(o, "dest")); + if (!safe_relpath(r->dest)) + return false; + a = json_get(o, "sha1"); + for (const struct json *x = a && a->type == JSON_ARR ? a->child : NULL; x && r->nsha < 6; x = x->next) { + if (x->type != JSON_STR || !x->str || strlen(x->str) != 40) + return false; + for (int i = 0; i < 40; i++) { + if (!isxdigit((unsigned char)x->str[i])) + return false; + r->sha1[r->nsha][i] = (char)tolower((unsigned char)x->str[i]); + } + r->sha1[r->nsha][40] = 0; + r->nsha++; + } + if (!r->nsha) + return false; + a = json_get(o, "size"); + for (const struct json *x = a && a->type == JSON_ARR ? a->child : NULL; x && r->nsize < 4; x = x->next) + if (x->type == JSON_NUM && x->num > 0) + r->size[r->nsize++] = (int64_t)x->num; + a = json_get(o, "output"); + for (const struct json *x = a && a->type == JSON_ARR ? a->child : NULL; x && r->nout < 4; x = x->next) { + if (x->type != JSON_STR || !safe_relpath(x->str)) + return false; + cpy(r->output[r->nout++], sizeof(r->output[0]), x->str); + } + if (!strcmp(r->mode, "copy")) { + cpy(r->copy_as, sizeof(r->copy_as), json_str(o, "copy_as")); + if (!safe_relpath(r->copy_as)) + return false; + cpy(r->output[0], sizeof(r->output[0]), r->copy_as); + r->nout = 1; + } else if (!r->nout) { + return false; + } + a = json_get(o, "systems"); + for (const struct json *x = a && a->type == JSON_ARR ? a->child : NULL; x && r->nsys < 2; x = x->next) + if (x->type == JSON_STR && rsu_safe_token(x->str)) + cpy(r->system[r->nsys++], sizeof(r->system[0]), x->str); + if (!r->nsys) + cpy(r->system[r->nsys++], sizeof(r->system[0]), "n64"); + r->need_ram_mb = (int)json_num(o, "needs_ram_mb", 0); + r->est_min = (int)json_num(o, "est_minutes", 5); + r->need_disk_mb = (int)json_num(o, "needs_disk_mb", 400); + if (r->est_min < 1) + r->est_min = 1; + return true; +} + +/* A usable entry: every field the install needs, safely spelled. */ +static bool entry_parse(const struct json *j, struct entry *e) +{ + const char *k; + + memset(e, 0, sizeof(*e)); + e->id = json_str(j, "id"); + e->name = json_str(j, "name"); + e->system = json_str(j, "system"); + e->version = json_str(j, "version"); + e->author = json_str(j, "author"); + e->license = json_str(j, "license"); + e->desc = json_str(j, "desc"); + e->url = json_str(j, "url"); + e->sha = json_str(j, "sha256"); + e->file = json_str(j, "file"); + e->cover = json_str(j, "cover"); + e->launcher = json_str(j, "launcher"); + e->size = (int64_t)json_num(j, "size", -1); + e->unpacked = (int64_t)json_num(j, "unpacked", (double)e->size); + k = json_str(j, "kind"); + if (!e->id || !e->name || !e->system || !e->version || !e->url || !e->sha || !k || !e->license) + return false; + if (!rsu_safe_token(e->id) || !rsu_safe_token(e->system) || !rsu_safe_token(e->version)) + return false; + if (e->size <= 0 || e->unpacked <= 0 || strlen(e->sha) != 64) + return false; + if (!strcmp(k, "rom")) { + e->kind = K_ROM; + if (!safe_name(e->file)) + return false; + } else if (!strcmp(k, "tar")) { + e->kind = K_TAR; + } else if (!strcmp(k, "native")) { + e->kind = K_NATIVE; + if (!safe_name(e->launcher)) + return false; + /* the code runs on the console: only for this CPU */ + if (!json_str(j, "arch") || strcmp(json_str(j, "arch"), C.arch)) + return false; + } else if (!strcmp(k, "port")) { + e->kind = K_PORT; + if (!json_str(j, "arch") || strcmp(json_str(j, "arch"), C.arch)) + return false; + if (!rom_parse(j, &e->rom)) + return false; + } else { + return false; + } + return true; +} + +static const struct json *catalog_find(const struct catalog *c, const char *id, struct entry *e) +{ + for (const struct json *j = c->entries->child; j; j = j->next) { + if (j->type == JSON_OBJ && json_str(j, "id") && !strcmp(json_str(j, "id"), id)) + return entry_parse(j, e) ? j : NULL; + } + return NULL; +} + +/* ------------------------------------------------------ installed record */ +/* installed.tsv: "idversionrelative path" per top-level path installed */ +static void installed_path(char *out, size_t n) +{ + cpy(out, n, C.record); +} + +/* the folder of the record (made before it is written) */ +static int record_dir(void) +{ + char d[1100], *sl; + + cpy(d, sizeof(d), C.record); + sl = strrchr(d, '/'); + if (sl && sl != d) + *sl = 0; + return mkdir_p(d); +} + +/* --roms names the console's own roms folder (the default), whatever its spelling */ +static bool roms_is_default(void) +{ + char a[PATH_MAX], b[PATH_MAX]; + size_t l; + + if (realpath(C.roms, a) && realpath("/data/roms", b)) + return !strcmp(a, b); + cpy(a, sizeof(a), C.roms); + l = strlen(a); + while (l > 1 && a[l - 1] == '/') + a[--l] = 0; + return !strcmp(a, "/data/roms"); +} + +static bool installed_version(const char *id, char *ver, size_t vn) +{ + char path[1100], line[1500]; + FILE *f; + bool found = false; + + installed_path(path, sizeof(path)); + f = fopen(path, "r"); + if (!f) + return false; + while (fgets(line, sizeof(line), f)) { + char *a = strtok(line, "\t"), *b = strtok(NULL, "\t"); + + if (a && b && !strcmp(a, id)) { + cpy(ver, vn, b); + found = true; + break; + } + } + fclose(f); + return found; +} + +/* Rewrites the record without ID's lines, then adds the new ones. */ +static int installed_update(const char *id, const char *version, char **paths, int np) +{ + char path[1100], line[1500]; + char *out = NULL; + size_t len = 0, cap = 0; + FILE *f; + int rc; + + installed_path(path, sizeof(path)); + f = fopen(path, "r"); + if (f) { + while (fgets(line, sizeof(line), f)) { + char cp[1500], *a; + size_t l = strlen(line); + + cpy(cp, sizeof(cp), line); + a = strtok(cp, "\t"); + if (a && !strcmp(a, id)) + continue; + if (len + l + 1 > cap) { + cap = (len + l + 1) * 2; + out = realloc(out, cap); + if (!out) { + fclose(f); + return -1; + } + } + memcpy(out + len, line, l); + len += l; + } + fclose(f); + } + for (int i = 0; i < np; i++) { + char l[1500]; + int ln = snprintf(l, sizeof(l), "%s\t%s\t%s\n", id, version, paths[i]); + + if (len + (size_t)ln + 1 > cap) { + cap = (len + (size_t)ln + 1) * 2; + out = realloc(out, cap); + if (!out) + return -1; + } + memcpy(out + len, l, (size_t)ln); + len += (size_t)ln; + } + if (record_dir() < 0) { + free(out); + return -1; + } + rc = write_atomic(path, out ? out : "", len); + free(out); + return rc; +} + +static void rm_tree(const char *path) +{ + struct stat st; + + if (lstat(path, &st) < 0) + return; + if (S_ISDIR(st.st_mode)) { + DIR *d = opendir(path); + struct dirent *de; + + if (d) { + while ((de = readdir(d))) { + char sub[1100]; + + if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) + continue; + snprintf(sub, sizeof(sub), "%s/%s", path, de->d_name); + rm_tree(sub); + } + closedir(d); + } + rmdir(path); + } else { + unlink(path); + } +} + +/* remove ID's files; returns how many top-level paths went */ +static int installed_remove(const char *id) +{ + char path[1100], line[1500]; + FILE *f; + int n = 0; + + installed_path(path, sizeof(path)); + f = fopen(path, "r"); + if (!f) + return 0; + while (fgets(line, sizeof(line), f)) { + char *a = strtok(line, "\t"), *b = strtok(NULL, "\t"), *p = strtok(NULL, "\n"); + char full[1100]; + + if (!a || !b || !p || strcmp(a, id) || !safe_relpath(p)) + continue; + snprintf(full, sizeof(full), "%s/%s", C.roms, p); + rm_tree(full); + /* a port's files are recorded one by one: the folders the store made go when they are empty + * (saves and settings the game wrote keep theirs) */ + for (char *sl = strrchr(p, '/'); sl; sl = strrchr(p, '/')) { + *sl = 0; + snprintf(full, sizeof(full), "%s/%s", C.roms, p); + if (rmdir(full) < 0) + break; + } + n++; + } + fclose(f); + installed_update(id, "", NULL, 0); + return n; +} + +/* --------------------------------------------------------------- list */ +static int cmd_list(const char *system) +{ + struct catalog c; + char err[256], iv[64]; + int count = 0; + + if (catalog_open(&c, err, sizeof(err)) < 0) + return fail("catalog", "%s", err); + for (const struct json *j = c.entries->child; j; j = j->next) { + struct entry e; + bool inst; + + if (j->type != JSON_OBJ || !entry_parse(j, &e)) + continue; + if (system && strcmp(system, e.system)) + continue; + inst = installed_version(e.id, iv, sizeof(iv)); + printf("entry"); + field("id", e.id); + field("name", e.name); + field("system", e.system); + field("version", e.version); + field("author", e.author); + field("license", e.license); + field("desc", e.desc); + fieldf("size", "%" PRId64, e.size); + field("kind", e.kind == K_ROM ? "rom" : e.kind == K_TAR ? "tar" : e.kind == K_PORT ? "port" : "native"); + field("installed", inst ? iv : ""); + field("update", inst && rsu_version_cmp(e.version, 0, iv, 0) > 0 ? "1" : "0"); + if (e.kind == K_PORT) { + field("rom", e.rom.name); + field("mode", e.rom.mode); + fieldf("minutes", "%d", e.rom.est_min); + } + endl(); + count++; + } + printf("done"); + fieldf("count", "%d", count); + field("source", c.cached ? "cache" : "net"); + endl(); + catalog_free(&c); + return 0; +} + +static int cmd_installed(void) +{ + char path[1100], line[1500], last[128] = ""; + FILE *f; + int n = 0; + + installed_path(path, sizeof(path)); + f = fopen(path, "r"); + if (f) { + while (fgets(line, sizeof(line), f)) { + char *a = strtok(line, "\t"), *b = strtok(NULL, "\t"); + + if (a && b && strcmp(a, last)) { + printf("installed"); + field("id", a); + field("version", b); + endl(); + cpy(last, sizeof(last), a); + n++; + } + } + fclose(f); + } + printf("done"); + fieldf("count", "%d", n); + endl(); + return 0; +} + +/* ----------------------------------------------------------- download */ +struct dl { + int fd; + struct sha256 sha; + int64_t got, max, total; + int status; +}; + +static int dl_head(const struct http_resp *r, void *user) +{ + struct dl *d = user; + + d->status = r->status; + return 0; +} + +static int dl_data(const void *data, size_t n, void *user) +{ + struct dl *d = user; + const uint8_t *p = data; + + if (d->got + (int64_t)n > d->max) + return -1; /* more than the signed size: stop */ + while (n) { + ssize_t w = write(d->fd, p, n); + + if (w < 0 && errno == EINTR) + continue; + if (w <= 0) + return -1; + sha256_update(&d->sha, p, (size_t)w); + d->got += w; + p += w; + n -= (size_t)w; + } + progress("download", (uint64_t)d->got, (uint64_t)d->total); + return g_cancel ? -1 : 0; +} + +static int download(const char *url, const char *dest, int64_t size, uint8_t digest[32], char *err, size_t en) +{ + struct http_opts o; + struct http_resp r; + struct dl d; + enum rsu_err rc; + + memset(&d, 0, sizeof(d)); + d.fd = open(dest, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + if (d.fd < 0) { + snprintf(err, en, "cannot write %s: %s", dest, strerror(errno)); + return -1; + } + d.max = size; + d.total = size; + sha256_init(&d.sha); + http_opts(&o); + rc = http_get(&o, url, 0, -1, dl_head, dl_data, &d, &r, err, en); + if (close(d.fd) < 0 && rc == RSU_OK) + rc = RSU_E_IO; + if (rc != RSU_OK) { + if (!*err) + snprintf(err, en, "download failed (%s)", rsu_err_code(rc)); + unlink(dest); + return g_cancel ? -2 : -1; + } + if (d.got != size) { + snprintf(err, en, "the download is %" PRId64 " bytes, the catalog says %" PRId64, d.got, size); + unlink(dest); + return -1; + } + sha256_final(&d.sha, digest); + return 0; +} + +/* ------------------------------------------------------------ tar unpack */ +static uint64_t tar_num(const char *p, size_t n) +{ + uint64_t v = 0; + + if ((unsigned char)p[0] & 0x80) { /* base-256 */ + v = (unsigned char)p[0] & 0x7f; + for (size_t i = 1; i < n; i++) + v = (v << 8) | (unsigned char)p[i]; + return v; + } + for (size_t i = 0; i < n && p[i] >= '0' && p[i] <= '7'; i++) + v = (v << 3) | (uint64_t)(p[i] - '0'); + return v; +} + +/* + * Unpack the plain ustar archive FILE into DIR. Regular files and directories only; every name + * must be a safe relative path; the unpacked bytes may not exceed LIMIT. Top-level names are + * collected into *tops (malloc'd strings). + */ +static int untar(const char *file, const char *dir, int64_t limit, char ***tops, int *ntops, char *err, size_t en) +{ + FILE *f = fopen(file, "rb"); + uint8_t blk[512]; + int64_t total = 0; + int cap = 0; + + *tops = NULL; + *ntops = 0; + if (!f) { + snprintf(err, en, "cannot open the archive"); + return -1; + } + while (fread(blk, 1, 512, f) == 512) { + char name[300], path[1200]; + uint64_t size; + char type = (char)blk[156]; + bool zero = true; + + for (int i = 0; i < 512; i++) + if (blk[i]) { + zero = false; + break; + } + if (zero) + break; + if (memcmp(blk + 257, "ustar", 5)) { + snprintf(err, en, "not a ustar archive"); + goto bad; + } + memcpy(name, blk, 100); + name[100] = 0; + if (blk[345]) { /* prefix field */ + char pre[156]; + + memcpy(pre, blk + 345, 155); + pre[155] = 0; + snprintf(name, sizeof(name), "%s/%.100s", pre, (char *)blk); + } + size = tar_num((const char *)blk + 124, 12); + if (!safe_relpath(name)) { + snprintf(err, en, "unsafe path in the archive"); + goto bad; + } + snprintf(path, sizeof(path), "%s/%s", dir, name); + if (type == '5') { + if (mkdir_p(path) < 0) { + snprintf(err, en, "cannot create a folder"); + goto bad; + } + } else if (type == '0' || type == 0) { + int fd; + uint64_t left = size; + char *slash; + + total += (int64_t)size; + if (total > limit || size > (uint64_t)limit) { + snprintf(err, en, "the archive unpacks to more than the catalog says"); + goto bad; + } + slash = strrchr(path, '/'); + *slash = 0; + mkdir_p(path); + *slash = '/'; + fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644); + if (fd < 0) { + snprintf(err, en, "cannot create %s", name); + goto bad; + } + while (left) { + uint8_t buf[8192]; + size_t want = left < sizeof(buf) ? (size_t)left : sizeof(buf); + + if (fread(buf, 1, want, f) != want || write(fd, buf, want) != (ssize_t)want) { + close(fd); + snprintf(err, en, "the archive is cut short"); + goto bad; + } + left -= want; + } + close(fd); + if (size % 512) + fseek(f, (long)(512 - size % 512), SEEK_CUR); + } else { + snprintf(err, en, "the archive holds a link or special file"); + goto bad; + } + /* top-level name */ + { + char top[300], *s; + bool have = false; + + cpy(top, sizeof(top), name); + s = strchr(top, '/'); + if (s) + *s = 0; + for (int i = 0; i < *ntops; i++) + if (!strcmp((*tops)[i], top)) + have = true; + if (!have) { + if (*ntops == cap) { + cap = cap ? cap * 2 : 8; + *tops = realloc(*tops, (size_t)cap * sizeof(char *)); + } + (*tops)[(*ntops)++] = strdup(top); + } + } + } + fclose(f); + if (!*ntops) { + snprintf(err, en, "the archive is empty"); + return -1; + } + return 0; +bad: + fclose(f); + return -1; +} + + +/* ------------------------------------------------- zstd-compressed packages */ +/* A package may be a .tar.zst (the downloads are much smaller): the same SHA-256 and size of the file as + * downloaded; unpacked to a plain tar next to it, within the catalog's unpacked size (plus the tar headers). */ +static bool is_zstd(const char *path) +{ + uint8_t m[4]; + int fd = open(path, O_RDONLY | O_CLOEXEC); + bool r; + + if (fd < 0) + return false; + r = read(fd, m, 4) == 4 && m[0] == 0x28 && m[1] == 0xb5 && m[2] == 0x2f && m[3] == 0xfd; + close(fd); + return r; +} + +static int unzstd(const char *src, const char *dst, int64_t limit, char *err, size_t en) +{ + static uint8_t in_buf[1 << 16], out_buf[1 << 17]; + int in = open(src, O_RDONLY | O_CLOEXEC), out; + ZSTD_DCtx *z = ZSTD_createDCtx(); + int64_t total = 0; + int rc = -1; + ssize_t r; + + if (in < 0 || !z) { + snprintf(err, en, "cannot unpack the package"); + goto done; + } + ZSTD_DCtx_setParameter(z, ZSTD_d_windowLogMax, 25); + out = open(dst, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + if (out < 0) { + snprintf(err, en, "cannot write %s", dst); + goto done; + } + while ((r = read(in, in_buf, sizeof(in_buf))) > 0) { + ZSTD_inBuffer ib = { in_buf, (size_t)r, 0 }; + + while (ib.pos < ib.size) { + ZSTD_outBuffer ob = { out_buf, sizeof(out_buf), 0 }; + size_t zr = ZSTD_decompressStream(z, &ob, &ib); + + if (ZSTD_isError(zr)) { + snprintf(err, en, "the package is damaged (%s)", ZSTD_getErrorName(zr)); + close(out); + goto done; + } + total += (int64_t)ob.pos; + if (total > limit) { + snprintf(err, en, "the package unpacks to more than the catalog says"); + close(out); + goto done; + } + if (ob.pos && write(out, out_buf, ob.pos) != (ssize_t)ob.pos) { + snprintf(err, en, "cannot write %s", dst); + close(out); + goto done; + } + } + if (g_cancel) { + snprintf(err, en, "cancelled"); + close(out); + goto done; + } + } + if (close(out) < 0 || r < 0) { + snprintf(err, en, "cannot write %s", dst); + goto done; + } + rc = 0; +done: + if (z) + ZSTD_freeDCtx(z); + if (in >= 0) + close(in); + if (rc < 0) + unlink(dst); + return rc; +} + +/* untar() of a plain or zstd-compressed tar */ +static int untar_any(const char *file, const char *dir, int64_t limit, char ***tops, int *ntops, char *err, size_t en) +{ + char plain[2200]; + int rc; + + if (!is_zstd(file)) + return untar(file, dir, limit, tops, ntops, err, en); + snprintf(plain, sizeof(plain), "%s.tar", file); + if (unzstd(file, plain, limit + limit / 8 + (4 << 20), err, en) < 0) + return -1; + rc = untar(plain, dir, limit, tops, ntops, err, en); + unlink(plain); + return rc; +} + +static void free_tops(char **tops, int n) +{ + for (int i = 0; i < n; i++) + free(tops[i]); + free(tops); +} + +/* ---------------------------------------------------------------- get */ +static int cmd_get(const char *id) +{ + struct catalog c; + struct entry e; + char err[300] = "", stage[2048], part[2048], target[2048], iv[64], hex[65]; + uint8_t want[32], got[32]; + char **tops = NULL, *single[1]; + int ntops = 0, rc; + struct statvfs vf; + + if (catalog_open(&c, err, sizeof(err)) < 0) + return fail("catalog", "%s", err); + if (!catalog_find(&c, id, &e)) { + catalog_free(&c); + return fail("notfound", "no usable entry %s in the catalog", id); + } + if (sha256_parse_hex(e.sha, want) < 0) { + catalog_free(&c); + return fail("catalog", "bad hash for %s", id); + } + if (C.max_bytes > 0 && e.size > C.max_bytes) { + catalog_free(&c); + return fail("size", "%s is larger than allowed", id); + } + + mkdir_p(C.roms); + /* room for the download and its unpacked copy, plus a margin */ + if (statvfs(C.roms, &vf) == 0 && + (int64_t)vf.f_bavail * (int64_t)vf.f_frsize < e.size + e.unpacked + (4 << 20)) { + catalog_free(&c); + return fail("space", "not enough free space for %s", e.name); + } + + snprintf(stage, sizeof(stage), "%s/.store-%s", C.roms, e.id); + snprintf(part, sizeof(part), "%s/.store-%s.part", C.roms, e.id); + rm_tree(stage); + unlink(part); + + rc = download(e.url, part, e.size, got, err, sizeof(err)); + if (rc < 0) { + catalog_free(&c); + return fail(rc == -2 ? "cancelled" : "download", "%s", err); + } + progress("verify", 1, 1); + sha256_hex(got, hex); + if (memcmp(got, want, 32)) { + unlink(part); + catalog_free(&c); + return fail("hash", "the download does not match the catalog's SHA-256"); + } + + progress("install", 0, 1); + if (e.kind == K_ROM) { + /* DIR//, replacing the store's own earlier copy */ + char dir[2048], rel[600]; + + snprintf(dir, sizeof(dir), "%s/%s", C.roms, e.system); + mkdir_p(dir); + snprintf(rel, sizeof(rel), "%s/%s", e.system, e.file); + snprintf(target, sizeof(target), "%s/%s", C.roms, rel); + if (access(target, F_OK) == 0 && !installed_version(e.id, iv, sizeof(iv))) { + unlink(part); + catalog_free(&c); + return fail("exists", "%s already exists and is not from the store", e.file); + } + if (rename(part, target) < 0) { + unlink(part); + catalog_free(&c); + return fail("io", "cannot place %s: %s", e.file, strerror(errno)); + } + single[0] = rel; + installed_update(e.id, e.version, single, 1); + } else { + const char *sub = e.kind == K_NATIVE ? "native" : e.system; + char dir[2048]; + + mkdir_p(stage); + if (untar_any(part, stage, e.unpacked, &tops, &ntops, err, sizeof(err)) < 0) { + rm_tree(stage); + unlink(part); + free_tops(tops, ntops); + catalog_free(&c); + return fail("archive", "%s", err); + } + unlink(part); + snprintf(dir, sizeof(dir), "%s/%s", C.roms, sub); + mkdir_p(dir); + /* refuse to overwrite anything the store did not put there */ + bool mine = installed_version(e.id, iv, sizeof(iv)); + + for (int i = 0; i < ntops; i++) { + snprintf(target, sizeof(target), "%s/%s", dir, tops[i]); + if (access(target, F_OK) == 0 && !mine) { + rm_tree(stage); + fail("exists", "%s already exists and is not from the store", tops[i]); + free_tops(tops, ntops); + catalog_free(&c); + return 1; + } + } + if (mine) + installed_remove(e.id); + char **rels = calloc((size_t)ntops, sizeof(char *)); + + for (int i = 0; i < ntops; i++) { + char from[2048], rel[600]; + + snprintf(from, sizeof(from), "%s/%s", stage, tops[i]); + snprintf(target, sizeof(target), "%s/%s", dir, tops[i]); + snprintf(rel, sizeof(rel), "%s/%s", sub, tops[i]); + rels[i] = strdup(rel); + if (rename(from, target) < 0) { + fail("io", "cannot place %s: %s", tops[i], strerror(errno)); + for (int k = 0; k < i; k++) { + char t[1100]; + + snprintf(t, sizeof(t), "%s/%s", C.roms, rels[k]); + rm_tree(t); + } + for (int k = 0; k <= i; k++) + free(rels[k]); + free(rels); + rm_tree(stage); + free_tops(tops, ntops); + catalog_free(&c); + return 1; + } + } + rm_tree(stage); + installed_update(e.id, e.version, rels, ntops); + for (int i = 0; i < ntops; i++) + free(rels[i]); + free(rels); + free_tops(tops, ntops); + } + progress("install", 1, 1); + + /* a cover for a native game (best effort): /.png */ + if (e.kind == K_NATIVE && e.cover && C.cover_dir[0] && !g_cancel) { + struct membuf m; + char stem[160], cp[1300], cerr[200]; + + cpy(stem, sizeof(stem), e.launcher); + if (strlen(stem) > 3 && !strcmp(stem + strlen(stem) - 3, ".sh")) + stem[strlen(stem) - 3] = 0; + if (fetch_mem(e.cover, &m, COVER_MAX, cerr, sizeof(cerr)) == 0) { + if (m.len > 8 && !memcmp(m.b, "\x89PNG\r\n\x1a\n", 8)) { + mkdir_p(C.cover_dir); + snprintf(cp, sizeof(cp), "%s/%s.png", C.cover_dir, stem); + write_atomic(cp, m.b, m.len); + } + free(m.b); + } + } + printf("ok"); + field("id", e.id); + field("version", e.version); + endl(); + catalog_free(&c); + return 0; +} + +/* the port's files an install moved aside (native/.store-replaced//, see cmd_install_port) */ +static void replaced_remove(const char *id) +{ + char keep[1300]; + + snprintf(keep, sizeof(keep), "%s/native/.store-replaced/%s", C.roms, id); + rm_tree(keep); + snprintf(keep, sizeof(keep), "%s/native/.store-replaced", C.roms); + rmdir(keep); +} + +static int cmd_remove(const char *id) +{ + char iv[64]; + int n; + + if (!rsu_safe_token(id)) + return fail("notfound", "bad id"); + if (!installed_version(id, iv, sizeof(iv))) + return fail("notfound", "%s is not installed from the store", id); + n = installed_remove(id); + replaced_remove(id); + printf("ok"); + field("id", id); + fieldf("removed", "%d", n); + endl(); + return 0; +} + +/* The game that PATH (relative to the roms folder, or a full path in it) belongs to, removed like + * remove ID: the menu's "Delete this game" on a store port's launcher removes the whole port, not + * the launcher alone (its saves and settings stay, as with remove). */ +static int cmd_remove_path(const char *arg) +{ + char path[1100], line[1500], id[128] = ""; + const char *rel = arg; + size_t rl = strlen(C.roms); + FILE *f; + + while (rl > 1 && C.roms[rl - 1] == '/') + rl--; + if (!strncmp(arg, C.roms, rl) && arg[rl] == '/') + rel = arg + rl + 1; + if (!safe_relpath(rel)) + return fail("notstore", "%s is not in the roms folder", arg); + installed_path(path, sizeof(path)); + f = fopen(path, "r"); + while (f && fgets(line, sizeof(line), f)) { + char *a = strtok(line, "\t"), *b = strtok(NULL, "\t"), *p = strtok(NULL, "\n"); + + if (a && b && p && !strcmp(p, rel)) { + cpy(id, sizeof(id), a); + break; + } + } + if (f) + fclose(f); + if (!id[0] || !rsu_safe_token(id)) + return fail("notstore", "%s was not installed from the store", rel); + return cmd_remove(id); +} + + +/* ============================================================ ports from the player's ROM */ +/* The ROM formats of the N64 dumps: z64 big-endian, v64 swapped in pairs, n64 little-endian words. */ +enum { RF_Z64 = 0, RF_V64, RF_N64, RF_UNKNOWN = -1 }; + +static int rom_format(const uint8_t *h) +{ + if (h[0] == 0x80 && h[1] == 0x37 && h[2] == 0x12 && h[3] == 0x40) + return RF_Z64; + if (h[0] == 0x37 && h[1] == 0x80 && h[2] == 0x40 && h[3] == 0x12) + return RF_V64; + if (h[0] == 0x40 && h[1] == 0x12 && h[2] == 0x37 && h[3] == 0x80) + return RF_N64; + return RF_UNKNOWN; +} + +/* to z64 order, in place; n is a multiple of 4 */ +static void rom_normalize(int fmt, uint8_t *b, size_t n) +{ + if (fmt == RF_V64) { + for (size_t i = 0; i + 1 < n; i += 2) { + uint8_t t = b[i]; + + b[i] = b[i + 1]; + b[i + 1] = t; + } + } else if (fmt == RF_N64) { + for (size_t i = 0; i + 3 < n; i += 4) { + uint8_t t = b[i]; + + b[i] = b[i + 3]; + b[i + 3] = t; + t = b[i + 1]; + b[i + 1] = b[i + 2]; + b[i + 2] = t; + } + } +} + +/* SHA-1 of the file in z64 order (what the published checksums are); false: not an N64 dump */ +static bool rom_hash(const char *path, char sha[41], int *fmt_out) +{ + static uint8_t buf[1 << 16]; + struct sha1 c; + uint8_t d[20]; + int fd = open(path, O_RDONLY | O_CLOEXEC); + int fmt = RF_UNKNOWN; + ssize_t r; + size_t have = 0; + + if (fd < 0) + return false; + sha1_init(&c); + for (;;) { + r = read(fd, buf + have, sizeof(buf) - have); + if (r < 0 && errno == EINTR) + continue; + if (r <= 0) + break; + have += (size_t)r; + if (have == sizeof(buf) || have % 4 == 0) { + size_t use = have - have % 4; + + if (fmt == RF_UNKNOWN) { + if (use < 4 || (fmt = rom_format(buf)) == RF_UNKNOWN) { + close(fd); + return false; + } + } + rom_normalize(fmt, buf, use); + sha1_update(&c, buf, use); + memmove(buf, buf + use, have - use); + have -= use; + } + if (g_cancel) { + close(fd); + return false; + } + } + close(fd); + if (r < 0 || have || fmt == RF_UNKNOWN) + return false; + sha1_final(&c, d); + sha1_hex(d, sha); + if (fmt_out) + *fmt_out = fmt; + return true; +} + +/* hashes already made: "sizemtimesha1path" */ +static bool hash_cached(const char *path, int64_t size, int64_t mtime, char sha[41]) +{ + char cp[1100], line[1400]; + FILE *f; + bool found = false; + + snprintf(cp, sizeof(cp), "%s/romhash.tsv", C.state); + f = fopen(cp, "r"); + if (!f) + return false; + while (fgets(line, sizeof(line), f)) { + long long sz, mt; + char h[64], *p; + + if (sscanf(line, "%lld\t%lld\t%63[0-9a-f]\t", &sz, &mt, h) != 3 || strlen(h) != 40) + continue; + p = strchr(strchr(strchr(line, '\t') + 1, '\t') + 1, '\t') + 1; + p[strcspn(p, "\n")] = 0; + if (sz == size && mt == mtime && !strcmp(p, path)) { + cpy(sha, 41, h); + found = true; + } + } + fclose(f); + return found; +} + +static void hash_remember(const char *path, int64_t size, int64_t mtime, const char *sha) +{ + char cp[1100]; + FILE *f; + + if (mkdir_p(C.state) < 0) + return; + snprintf(cp, sizeof(cp), "%s/romhash.tsv", C.state); + f = fopen(cp, "a"); + if (f) { + fprintf(f, "%lld\t%lld\t%s\t%s\n", (long long)size, (long long)mtime, sha, path); + fclose(f); + } +} + +static bool has_rom_ext(const char *name) +{ + const char *dot = strrchr(name, '.'); + + return dot && (!strcasecmp(dot, ".z64") || !strcasecmp(dot, ".v64") || !strcasecmp(dot, ".n64")); +} + +static bool size_ok(const struct rominfo *r, int64_t size) +{ + if (!r->nsize) + return true; + for (int i = 0; i < r->nsize; i++) + if (r->size[i] == size) + return true; + return false; +} + +/* does this file hold one of the accepted dumps? */ +static bool rom_matches(const struct rominfo *r, const char *path, char sha[41]) +{ + struct stat st; + + if (stat(path, &st) < 0 || !S_ISREG(st.st_mode) || !size_ok(r, st.st_size)) + return false; + if (!hash_cached(path, st.st_size, st.st_mtime, sha)) { + if (!rom_hash(path, sha, NULL)) + return false; + hash_remember(path, st.st_size, st.st_mtime, sha); + } + for (int i = 0; i < r->nsha; i++) + if (!strcmp(sha, r->sha1[i])) + return true; + return false; +} + +/* the first dump of the game in the places a player keeps ROMs: the games folders (/n64, ...) of + * every drive, and anything given with --scan (a USB drive's root and its n64 folder) */ +static bool find_rom(const struct rominfo *r, char *path_out, size_t pn, char sha[41]) +{ + const char *bases[5]; + int nb = 0; + + bases[nb++] = C.roms; + for (int i = 0; i < C.nscan; i++) + bases[nb++] = C.scan[i]; + for (int b = 0; b < nb; b++) { + for (int s = -1; s < r->nsys; s++) { + char dir[1100]; + DIR *d; + struct dirent *de; + + if (s < 0 && b == 0) + continue; /* the games folder itself holds system folders, not ROMs */ + if (s < 0) + cpy(dir, sizeof(dir), bases[b]); + else + snprintf(dir, sizeof(dir), "%s/%s", bases[b], r->system[s]); + d = opendir(dir); + if (!d) + continue; + while ((de = readdir(d))) { + char full[2048]; + + if (de->d_name[0] == '.' || !has_rom_ext(de->d_name)) + continue; + snprintf(full, sizeof(full), "%s/%s", dir, de->d_name); + if (rom_matches(r, full, sha)) { + cpy(path_out, pn, full); + closedir(d); + return true; + } + if (g_cancel) { + closedir(d); + return false; + } + } + closedir(d); + } + } + return false; +} + +static int cmd_find_rom(const char *id) +{ + struct catalog c; + struct entry e; + char err[256], path[1100], sha[41]; + + if (catalog_open(&c, err, sizeof(err)) < 0) + return fail("catalog", "%s", err); + if (!catalog_find(&c, id, &e) || e.kind != K_PORT) { + catalog_free(&c); + return fail("notfound", "no port %s in the catalog", id); + } + if (find_rom(&e.rom, path, sizeof(path), sha)) { + printf("rom"); + field("path", path); + field("sha1", sha); + field("name", e.rom.name); + endl(); + printf("done"); + field("count", "1"); + endl(); + catalog_free(&c); + return 0; + } + catalog_free(&c); + return fail("norom", "no %s ROM found", e.rom.name); +} + +/* MemAvailable in kB (RSOS_MEMINFO: a file for the tests), -1 when unknown */ +static long mem_available_kb(void) +{ + const char *mi = getenv("RSOS_MEMINFO"); + FILE *f = fopen(mi ? mi : "/proc/meminfo", "r"); + char line[200]; + long v = -1; + + if (!f) + return -1; + while (fgets(line, sizeof(line), f)) + if (sscanf(line, "MemAvailable: %ld kB", &v) == 1) + break; + fclose(f); + return v; +} + +/* + * Runs the package's extract.sh as a guarded child: its own process group, the first thing the kernel kills when + * memory runs out (oom_score_adj 1000), an address-space limit, killed by us when free memory falls below the + * floor or after the time allowed, or on cancel. Its stdout lines "progressdone=Ntotal=M" are passed on. + * Returns 0 or a code: "extract" (it failed), "memory", "timeout", "cancelled". + */ +static const char *run_guarded(const char *script, const char *cwd, const char *rom, const char *out, const char *tmp, + const char *logfile, int est_min) +{ + int pfd[2]; + pid_t pid; + time_t start = time(NULL); + long floor_kb = getenv("RSOS_MEMFLOOR_KB") ? atol(getenv("RSOS_MEMFLOOR_KB")) : 90000; + long limit_s = getenv("RSOS_TIMEOUT_S") ? atol(getenv("RSOS_TIMEOUT_S")) : 3L * est_min * 60; + const char *why = NULL; + char buf[512]; + size_t have = 0; + int status = 0; + + if (pipe2(pfd, O_CLOEXEC) < 0) + return "extract"; + pid = fork(); + if (pid < 0) { + close(pfd[0]); + close(pfd[1]); + return "extract"; + } + if (pid == 0) { + struct rlimit rl = { 1800UL << 20, 1800UL << 20 }; + int fd, lg; + + setsid(); + signal(SIGTERM, SIG_DFL); + signal(SIGINT, SIG_DFL); + fd = open("/proc/self/oom_score_adj", O_WRONLY); + if (fd >= 0) { + if (write(fd, "1000", 4) < 0) { + /* not fatal */ + } + close(fd); + } + if (!getenv("RSOS_NO_RLIMIT")) + setrlimit(RLIMIT_AS, &rl); + dup2(pfd[1], 1); + lg = open(logfile, O_WRONLY | O_CREAT | O_TRUNC, 0644); + if (lg >= 0) + dup2(lg, 2); + fd = open("/dev/null", O_RDONLY); + if (fd >= 0) + dup2(fd, 0); + if (chdir(cwd) < 0) + _exit(126); + setenv("RSOS_ROM", rom, 1); + setenv("RSOS_OUT", out, 1); + setenv("TMPDIR", tmp, 1); + execl("/bin/sh", "sh", script, (char *)NULL); + _exit(127); + } + close(pfd[1]); + for (;;) { + struct pollfd p = { pfd[0], POLLIN, 0 }; + long avail; + pid_t w; + + if (poll(&p, 1, 500) > 0 && (p.revents & POLLIN)) { + ssize_t r = read(pfd[0], buf + have, sizeof(buf) - 1 - have); + + if (r > 0) { + char *nl; + + have += (size_t)r; + buf[have] = 0; + while ((nl = strchr(buf, '\n'))) { + long long dn, tt; + + *nl = 0; + if (sscanf(buf, "progress\tdone=%lld\ttotal=%lld", &dn, &tt) == 2 && tt > 0) + progress("extract", (uint64_t)dn, (uint64_t)tt); + memmove(buf, nl + 1, have - (size_t)(nl + 1 - buf)); + have -= (size_t)(nl + 1 - buf); + buf[have] = 0; + } + if (have >= sizeof(buf) - 1) + have = 0; + } + } + w = waitpid(pid, &status, WNOHANG); + if (w == pid) + break; + if (!why) { + avail = mem_available_kb(); + if (g_cancel) + why = "cancelled"; + else if (avail >= 0 && avail < floor_kb) + why = "memory"; + else if (time(NULL) - start > limit_s) + why = "timeout"; + if (why) { + kill(-pid, SIGKILL); + kill(pid, SIGKILL); + } + } + /* no progress lines from the script: show the time against the estimate */ + if (!why) + progress("extract", (uint64_t)(time(NULL) - start), (uint64_t)est_min * 60); + } + close(pfd[0]); + kill(-pid, SIGKILL); /* stragglers of its group */ + if (why) + return why; + return WIFEXITED(status) && WEXITSTATUS(status) == 0 ? NULL : "extract"; +} + +/* the ROM in z64 order, written to dest */ +static bool rom_write_z64(const char *src, const char *dest) +{ + static uint8_t buf[1 << 16]; + int in = open(src, O_RDONLY | O_CLOEXEC), out; + int fmt = RF_UNKNOWN; + size_t have = 0; + ssize_t r; + bool ok = true; + + if (in < 0) + return false; + out = open(dest, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + if (out < 0) { + close(in); + return false; + } + for (;;) { + r = read(in, buf + have, sizeof(buf) - have); + if (r < 0 && errno == EINTR) + continue; + if (r <= 0) + break; + have += (size_t)r; + if (have == sizeof(buf)) { + if (fmt == RF_UNKNOWN && (fmt = rom_format(buf)) == RF_UNKNOWN) { + ok = false; + break; + } + rom_normalize(fmt, buf, have); + if (write(out, buf, have) != (ssize_t)have) { + ok = false; + break; + } + have = 0; + } + } + if (ok && r == 0 && have) { + if (fmt == RF_UNKNOWN && (fmt = rom_format(buf)) == RF_UNKNOWN) + ok = false; + else { + size_t use = have - have % 4; + + rom_normalize(fmt, buf, use); + ok = write(out, buf, use) == (ssize_t)use; + } + } else if (r < 0) { + ok = false; + } + close(in); + if (close(out) < 0) + ok = false; + return ok; +} + +struct pathlist { + char **p; + int n, cap; +}; + +static void pl_add(struct pathlist *l, const char *s) +{ + if (l->n == l->cap) { + l->cap = l->cap ? l->cap * 2 : 32; + l->p = realloc(l->p, (size_t)l->cap * sizeof(char *)); + } + l->p[l->n++] = strdup(s); +} + +static void pl_free(struct pathlist *l) +{ + for (int i = 0; i < l->n; i++) + free(l->p[i]); + free(l->p); + memset(l, 0, sizeof(*l)); +} + +/* every regular file below root/rel, as paths relative to root */ +static void walk_files(const char *root, const char *rel, struct pathlist *l) +{ + char dir[2048]; + DIR *d; + struct dirent *de; + + snprintf(dir, sizeof(dir), "%s%s%s", root, rel[0] ? "/" : "", rel); + d = opendir(dir); + if (!d) + return; + while ((de = readdir(d))) { + char sub[1100], full[2200]; + struct stat st; + + if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) + continue; + snprintf(sub, sizeof(sub), "%s%s%s", rel, rel[0] ? "/" : "", de->d_name); + snprintf(full, sizeof(full), "%s/%s", root, sub); + if (lstat(full, &st) < 0) + continue; + if (S_ISDIR(st.st_mode)) + walk_files(root, sub, l); + else if (S_ISREG(st.st_mode)) + pl_add(l, sub); + } + closedir(d); +} + +static int cmd_install_port(const char *id) +{ + struct catalog c; + struct entry e; + char err[300] = "", stage[2048], part[2048], pkg[2200], out[2200], tmp[2200], rom[1100], sha[41], iv[64], hex[65]; + char zrom[2200], inst[2300], script[2300], logf[2200], target[2600], from[2600], native[1100]; + uint8_t want[32], got[32]; + struct pathlist files = { 0 }, moved = { 0 }; + char **tops = NULL; + int ntops = 0, rc, result = 1; + long avail; + struct statvfs vf; + const char *why; + bool mine; + + if (catalog_open(&c, err, sizeof(err)) < 0) + return fail("catalog", "%s", err); + if (!catalog_find(&c, id, &e) || e.kind != K_PORT) { + catalog_free(&c); + return fail("notfound", "no port %s in the catalog", id); + } + if (sha256_parse_hex(e.sha, want) < 0) { + catalog_free(&c); + return fail("catalog", "bad hash for %s", id); + } + snprintf(native, sizeof(native), "%s/native", C.roms); + snprintf(stage, sizeof(stage), "%s/.store-%s", C.roms, e.id); + snprintf(part, sizeof(part), "%s/.store-%s.part", C.roms, e.id); + snprintf(pkg, sizeof(pkg), "%s/pkg", stage); + snprintf(out, sizeof(out), "%s/out", stage); + snprintf(tmp, sizeof(tmp), "%s/tmp", stage); + snprintf(zrom, sizeof(zrom), "%s/rom.z64", stage); + snprintf(logf, sizeof(logf), "%s/extract.log", stage); + + /* the ROM first: nothing is downloaded for a game the player cannot install */ + if (C.rom_arg[0]) { + if (!rom_matches(&e.rom, C.rom_arg, sha)) { + fail("norom", "%s is not a %s ROM", C.rom_arg, e.rom.name); + goto done; + } + cpy(rom, sizeof(rom), C.rom_arg); + } else { + progress("rom", 0, 1); + if (!find_rom(&e.rom, rom, sizeof(rom), sha)) { + fail(g_cancel ? "cancelled" : "norom", "no %s ROM found", e.rom.name); + goto done; + } + } + printf("rom"); + field("path", rom); + field("sha1", sha); + endl(); + + /* room: free memory for the extractor, free disk for the package and what it makes */ + avail = mem_available_kb(); + if (!strcmp(e.rom.mode, "extract") && avail >= 0 && avail / 1024 < e.rom.need_ram_mb) { + fail("memory", "needs %d MB of free memory, %ld MB available: restart the console and try again", + e.rom.need_ram_mb, avail / 1024); + goto done; + } + mkdir_p(C.roms); + if (statvfs(C.roms, &vf) == 0 && + (int64_t)vf.f_bavail * (int64_t)vf.f_frsize < e.size + e.unpacked + ((int64_t)e.rom.need_disk_mb << 20)) { + fail("space", "not enough free space for %s", e.name); + goto done; + } + + rm_tree(stage); + unlink(part); + if (mkdir_p(pkg) < 0 || mkdir_p(out) < 0 || mkdir_p(tmp) < 0) { + fail("io", "cannot make the work folder"); + goto done; + } + rc = download(e.url, part, e.size, got, err, sizeof(err)); + if (rc < 0) { + fail(rc == -2 ? "cancelled" : "download", "%s", err); + goto done; + } + progress("verify", 1, 1); + sha256_hex(got, hex); + if (memcmp(got, want, 32)) { + fail("hash", "the download does not match the catalog's SHA-256"); + goto done; + } + if (untar_any(part, pkg, e.unpacked, &tops, &ntops, err, sizeof(err)) < 0) { + fail("archive", "%s", err); + goto done; + } + unlink(part); + snprintf(inst, sizeof(inst), "%s/install", pkg); + snprintf(script, sizeof(script), "%s/extract/extract.sh", pkg); + { + struct stat st; + + if (stat(inst, &st) < 0 || !S_ISDIR(st.st_mode) || + (!strcmp(e.rom.mode, "extract") && access(script, R_OK) < 0)) { + fail("archive", "the package has no install folder or extract.sh"); + goto done; + } + } + + /* the game data from the ROM */ + progress("extract", 0, (uint64_t)e.rom.est_min * 60); + if (!rom_write_z64(rom, zrom)) { + fail("rom", "cannot read the ROM"); + goto done; + } + if (!strcmp(e.rom.mode, "extract")) { + char cwd[2300]; + + snprintf(cwd, sizeof(cwd), "%s/extract", pkg); + why = run_guarded(script, cwd, zrom, out, tmp, logf, e.rom.est_min); + if (why) { + fail(why, "the game data could not be made (%s); see %s", why, logf); + goto done; + } + } else { + char dst[2400], dir[2400]; + + snprintf(dst, sizeof(dst), "%s/%s", out, e.rom.copy_as); + cpy(dir, sizeof(dir), dst); + *strrchr(dir, '/') = 0; + mkdir_p(dir); + if (rename(zrom, dst) < 0) { + fail("io", "cannot place the ROM: %s", strerror(errno)); + goto done; + } + } + for (int i = 0; i < e.rom.nout; i++) { + struct stat st; + + snprintf(from, sizeof(from), "%s/%s", out, e.rom.output[i]); + if (stat(from, &st) < 0 || !S_ISREG(st.st_mode) || st.st_size <= 0) { + fail("extract", "%s was not made", e.rom.output[i]); + goto done; + } + } + unlink(zrom); + + /* commit: the program files, then the made files, each moved into native/ (folders merge) */ + mine = installed_version(e.id, iv, sizeof(iv)); + walk_files(inst, "", &files); + for (int i = 0; i < files.n; i++) { + if (!safe_relpath(files.p[i])) { + fail("archive", "unsafe path in the package"); + goto done; + } + } + if (!mine) { + /* Files of the port that the store did not put there: what "Delete this game" + * left behind (it deletes the launcher only), or a copy installed by hand. They + * are this port's own program files, never its saves (no package holds a save), + * so they are moved aside into native/.store-replaced// (hidden from the game + * list; the previous one is replaced) instead of blocking the install. */ + char keep[1300]; + bool cleared = false; + + snprintf(keep, sizeof(keep), "%s/.store-replaced/%s", native, e.id); + for (int i = 0; i < files.n; i++) { + struct stat st; + char to[2700], *sl; + + snprintf(target, sizeof(target), "%s/%s", native, files.p[i]); + if (lstat(target, &st) < 0) + continue; + if (!cleared) { + rm_tree(keep); + cleared = true; + } + snprintf(to, sizeof(to), "%s/%s", keep, files.p[i]); + sl = strrchr(to, '/'); + *sl = 0; + mkdir_p(to); + *sl = '/'; + if (rename(target, to) < 0) { + fail("exists", "%s already exists and cannot be moved aside: %s", files.p[i], strerror(errno)); + goto done; + } + fprintf(stderr, "rsos-store: %s was not from the store: moved to %s\n", files.p[i], to); + } + } + if (mine) + installed_remove(e.id); + for (int i = 0; i < files.n + e.rom.nout; i++) { + char rel[1100], *sl; + + if (i < files.n) { + cpy(rel, sizeof(rel), files.p[i]); + snprintf(from, sizeof(from), "%s/%s", inst, rel); + } else { + snprintf(rel, sizeof(rel), "%s/%s", e.rom.dest, e.rom.output[i - files.n]); + snprintf(from, sizeof(from), "%s/%s", out, e.rom.output[i - files.n]); + } + snprintf(target, sizeof(target), "%s/%s", native, rel); + sl = strrchr(target, '/'); + *sl = 0; + mkdir_p(target); + *sl = '/'; + if (rename(from, target) < 0) { + fail("io", "cannot place %s: %s", rel, strerror(errno)); + for (int k = 0; k < moved.n; k++) { + snprintf(from, sizeof(from), "%s/%s", native, moved.p[k]); + unlink(from); + } + goto done; + } + pl_add(&moved, rel); + } + { + char **rels = calloc((size_t)moved.n + 1, sizeof(char *)); + + for (int i = 0; i < moved.n; i++) { + char r2[1200]; + + snprintf(r2, sizeof(r2), "native/%s", moved.p[i]); + rels[i] = strdup(r2); + } + installed_update(e.id, e.version, rels, moved.n); + for (int i = 0; i < moved.n; i++) + free(rels[i]); + free(rels); + } + progress("install", 1, 1); + printf("ok"); + field("id", e.id); + field("version", e.version); + endl(); + result = 0; +done: + pl_free(&files); + pl_free(&moved); + free_tops(tops, ntops); + rm_tree(stage); + unlink(part); + catalog_free(&c); + return result; +} + + +/* /store.ini: the player's own catalog (a home server): "url=https://host/catalog.json" and, for a + * server without HTTPS, "allow_http=1". Options on the command line win. */ +static void read_store_ini(bool url_given, bool http_given) +{ + char path[1100], line[1200]; + FILE *f; + + snprintf(path, sizeof(path), "%s/store.ini", C.state); + f = fopen(path, "r"); + if (!f) + return; + while (fgets(line, sizeof(line), f)) { + line[strcspn(line, "\r\n")] = 0; + if (!url_given && !strncmp(line, "url=", 4) && line[4]) + cpy(C.url, sizeof(C.url), line + 4); + else if (!http_given && !strcmp(line, "allow_http=1")) + C.allow_http = true; + } + fclose(f); +} + +int main(int argc, char **argv) +{ + const char *cmd = NULL, *arg = NULL; + bool url_given = false, http_given = false; + + cpy(C.roms, sizeof(C.roms), "/data/roms"); + cpy(C.state, sizeof(C.state), "/data/rsos/store"); + cpy(C.pubkey, sizeof(C.pubkey), "/usr/share/rsos/store.pub"); + cpy(C.url, sizeof(C.url), STORE_URL); + cpy(C.arch, sizeof(C.arch), STORE_ARCH); + cpy(C.cover_dir, sizeof(C.cover_dir), ""); + + for (int i = 1; i < argc; i++) { + const char *a = argv[i], *v = i + 1 < argc ? argv[i + 1] : NULL; + + if (v && !strcmp(a, "--roms")) { + cpy(C.roms, sizeof(C.roms), v), i++; + } else if (v && !strcmp(a, "--state")) { + cpy(C.state, sizeof(C.state), v), i++; + } else if (v && !strcmp(a, "--pubkey")) { + cpy(C.pubkey, sizeof(C.pubkey), v), i++; + } else if (v && !strcmp(a, "--url")) { + cpy(C.url, sizeof(C.url), v), url_given = true, i++; + } else if (v && !strcmp(a, "--catalog")) { + cpy(C.catalog_file, sizeof(C.catalog_file), v), url_given = true, i++; + } else if (v && !strcmp(a, "--arch")) { + cpy(C.arch, sizeof(C.arch), v), i++; + } else if (v && !strcmp(a, "--cover-dir")) { + cpy(C.cover_dir, sizeof(C.cover_dir), v), i++; + } else if (v && !strcmp(a, "--max-bytes")) { + C.max_bytes = strtoll(v, NULL, 10), i++; + } else if (v && !strcmp(a, "--out")) { + if (!freopen(v, "w", stdout)) + return 1; + setvbuf(stdout, NULL, _IOLBF, 0); + i++; + } else if (v && !strcmp(a, "--scan")) { + if (C.nscan < 4) + cpy(C.scan[C.nscan++], sizeof(C.scan[0]), v); + i++; + } else if (v && !strcmp(a, "--rom")) { + cpy(C.rom_arg, sizeof(C.rom_arg), v), i++; + } else if (!strcmp(a, "--allow-http")) { + C.allow_http = true; + http_given = true; + } else if (!cmd) { + cmd = a; + } else if (!arg) { + arg = a; + } else { + return fail("usage", "unexpected argument %s", a); + } + } + read_store_ini(url_given, http_given); + if (roms_is_default()) + snprintf(C.record, sizeof(C.record), "%s/installed.tsv", C.state); + else + snprintf(C.record, sizeof(C.record), "%s/.rsos-store/installed.tsv", C.roms); + signal(SIGTERM, on_term); + signal(SIGINT, on_term); + signal(SIGPIPE, SIG_IGN); + if (!cmd) + return fail("usage", "list [SYSTEM] | get ID | install-port ID | find-rom ID | remove ID | remove-path PATH | installed"); + if (!strcmp(cmd, "list")) + return cmd_list(arg); + if (!strcmp(cmd, "installed")) + return cmd_installed(); + if (!strcmp(cmd, "get") && arg) + return rsu_safe_token(arg) ? cmd_get(arg) : fail("notfound", "bad id"); + if (!strcmp(cmd, "find-rom") && arg) + return rsu_safe_token(arg) ? cmd_find_rom(arg) : fail("notfound", "bad id"); + if (!strcmp(cmd, "install-port") && arg) + return rsu_safe_token(arg) ? cmd_install_port(arg) : fail("notfound", "bad id"); + if (!strcmp(cmd, "remove") && arg) + return cmd_remove(arg); + if (!strcmp(cmd, "remove-path") && arg) + return cmd_remove_path(arg); + return fail("usage", "unknown command %s", cmd); +} diff --git a/frontend/src/update/sha1.c b/frontend/src/update/sha1.c new file mode 100644 index 0000000..a648e7d --- /dev/null +++ b/frontend/src/update/sha1.c @@ -0,0 +1,106 @@ +/* sha1.c - see sha1.h */ +#include "sha1.h" + +#include + +#define ROL(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) + +static void block(struct sha1 *c, const uint8_t *p) +{ + uint32_t w[80], a = c->h[0], b = c->h[1], cc = c->h[2], d = c->h[3], e = c->h[4], t; + + for (int i = 0; i < 16; i++) + w[i] = (uint32_t)p[4 * i] << 24 | (uint32_t)p[4 * i + 1] << 16 | (uint32_t)p[4 * i + 2] << 8 | p[4 * i + 3]; + for (int i = 16; i < 80; i++) + w[i] = ROL(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1); + for (int i = 0; i < 80; i++) { + uint32_t f, k; + + if (i < 20) { + f = (b & cc) | (~b & d); + k = 0x5a827999; + } else if (i < 40) { + f = b ^ cc ^ d; + k = 0x6ed9eba1; + } else if (i < 60) { + f = (b & cc) | (b & d) | (cc & d); + k = 0x8f1bbcdc; + } else { + f = b ^ cc ^ d; + k = 0xca62c1d6; + } + t = ROL(a, 5) + f + e + k + w[i]; + e = d; + d = cc; + cc = ROL(b, 30); + b = a; + a = t; + } + c->h[0] += a; + c->h[1] += b; + c->h[2] += cc; + c->h[3] += d; + c->h[4] += e; +} + +void sha1_init(struct sha1 *c) +{ + c->h[0] = 0x67452301; + c->h[1] = 0xefcdab89; + c->h[2] = 0x98badcfe; + c->h[3] = 0x10325476; + c->h[4] = 0xc3d2e1f0; + c->len = 0; + c->n = 0; +} + +void sha1_update(struct sha1 *c, const void *data, size_t n) +{ + const uint8_t *p = data; + + c->len += n; + while (n) { + size_t k = 64 - c->n; + + if (k > n) + k = n; + memcpy(c->buf + c->n, p, k); + c->n += k; + p += k; + n -= k; + if (c->n == 64) { + block(c, c->buf); + c->n = 0; + } + } +} + +void sha1_final(struct sha1 *c, uint8_t out[20]) +{ + uint64_t bits = c->len * 8; + uint8_t pad = 0x80, zero = 0, lenb[8]; + + sha1_update(c, &pad, 1); + while (c->n != 56) + sha1_update(c, &zero, 1); + for (int i = 0; i < 8; i++) + lenb[i] = (uint8_t)(bits >> (56 - 8 * i)); + sha1_update(c, lenb, 8); + for (int i = 0; i < 5; i++) { + out[4 * i] = (uint8_t)(c->h[i] >> 24); + out[4 * i + 1] = (uint8_t)(c->h[i] >> 16); + out[4 * i + 2] = (uint8_t)(c->h[i] >> 8); + out[4 * i + 3] = (uint8_t)c->h[i]; + } +} + +void sha1_hex(const uint8_t d[20], char out[41]) +{ + static const char hx[] = "0123456789abcdef"; + + for (int i = 0; i < 20; i++) { + out[2 * i] = hx[d[i] >> 4]; + out[2 * i + 1] = hx[d[i] & 15]; + } + out[40] = 0; +} diff --git a/frontend/src/update/sha1.h b/frontend/src/update/sha1.h new file mode 100644 index 0000000..7169025 --- /dev/null +++ b/frontend/src/update/sha1.h @@ -0,0 +1,25 @@ +/* + * sha1.h - SHA-1 (RFC 3174), only to recognise game dumps by the checksum the community publishes for + * them (the game store's ROM finding). Never used for security: the catalog and the downloads are + * checked with SHA-256 and signatures. + */ +#ifndef RSOS_UPDATE_SHA1_H +#define RSOS_UPDATE_SHA1_H + +#include +#include + +struct sha1 { + uint32_t h[5]; + uint64_t len; + uint8_t buf[64]; + size_t n; +}; + +void sha1_init(struct sha1 *c); +void sha1_update(struct sha1 *c, const void *data, size_t n); +void sha1_final(struct sha1 *c, uint8_t out[20]); +/* 40 lower-case hex characters and a NUL */ +void sha1_hex(const uint8_t d[20], char out[41]); + +#endif diff --git a/frontend/src/update/tests/store_test.sh b/frontend/src/update/tests/store_test.sh new file mode 100644 index 0000000..5d50c8f --- /dev/null +++ b/frontend/src/update/tests/store_test.sh @@ -0,0 +1,336 @@ +#!/bin/sh +# Tests of rsos-store as the menu uses it (make check-update), against a local HTTP server: +# signed catalog (good, tampered, wrong key), download + SHA-256 + size checks, rom / tar / native +# installs, update + remove, files the store does not own, hostile archives, offline cache. +# store_test.sh +set -u +ST=$1 +MK=$2 +W=$3 +MC=$4 +rm -rf "$W" && mkdir -p "$W/e" "$W/out" +pass=0 +fail=0 +check() { if eval "$2"; then pass=$((pass + 1)); else echo " FAIL: $1"; fail=$((fail + 1)); fi; } + +PORT=$((20000 + $$ % 20000)) +export PORT W +BASE=http://127.0.0.1:$PORT +"$MK" keygen -s "$W/store.key" -p "$W/store.pub" -c "test store" > /dev/null +"$MK" keygen -s "$W/other.key" -p "$W/other.pub" > /dev/null + +# --- content (payloads sit next to the entry files) +printf 'NES\032 pretend ROM v1' > "$W/e/mage.nes" +mkdir -p "$W/g/data" +printf '#!/bin/sh\necho hi\n' > "$W/g/Cool Game.sh" +printf 'level data' > "$W/g/data/level1.bin" +(cd "$W/g" && tar --format=ustar -cf ../e/cool.tar "Cool Game.sh" data) +(cd "$W/g" && tar --format=ustar -cf ../e/pack.tar data) +python3 - <<'EOF' +import json, os +W = os.environ["W"] +def entry(name, **kw): + d = dict(id=name, name=name, system="nes", version="1.0", author="A", license="CC0", source="https://x/", + desc="d", kind="rom") + d.update(kw) + json.dump(d, open(f"{W}/e/{name}.json", "w")) +entry("mage", file="Micro Mage.nes", payload="mage.nes") +entry("coolgame", system="native", kind="native", launcher="Cool Game.sh", arch="armhf", payload="cool.tar") +entry("wrongarch", system="native", kind="native", launcher="x.sh", arch="x86_64", payload="cool.tar") +entry("pack", system="snes", kind="tar", payload="pack.tar") +EOF + +# --- a fake N64 dump (z64 order) in the three formats, and port packages +python3 - <<'EOF' +import hashlib, json, os, random +W = os.environ["W"] +random.seed(7) +z = bytes([0x80, 0x37, 0x12, 0x40]) + bytes(random.getrandbits(8) for _ in range(1048572)) +open(f"{W}/game.z64", "wb").write(z) +v = bytearray(z) +v[0::2], v[1::2] = z[1::2], z[0::2] +open(f"{W}/game.v64", "wb").write(bytes(v)) +n = bytearray(z) +for i in range(0, len(n), 4): + n[i:i + 4] = z[i:i + 4][::-1] +open(f"{W}/game.n64", "wb").write(bytes(n)) +open(f"{W}/rom.sha1", "w").write(hashlib.sha1(z).hexdigest()) +EOF +SHA1=$(cat "$W/rom.sha1") +mkdir -p "$W/pk/ok/install/portgame" "$W/pk/ok/extract" "$W/pk/fail/install" "$W/pk/fail/extract" "$W/pk/slow/install" "$W/pk/slow/extract" \ + "$W/pk/copy/install" +printf '#!/bin/sh\necho port\n' > "$W/pk/ok/install/Port Game.sh" +printf 'program' > "$W/pk/ok/install/portgame/prog.bin" +cat > "$W/pk/ok/extract/extract.sh" <<'EOT' +#!/bin/sh +# the ROM comes in z64 order; TMPDIR is a folder of ours +[ -f "$RSOS_ROM" ] && [ -d "$TMPDIR" ] && [ -d "$RSOS_OUT" ] || exit 9 +echo "progress done=1 total=2" +cp "$RSOS_ROM" "$RSOS_OUT/game.o2r" +echo "progress done=2 total=2" +EOT +printf '#!/bin/sh\n' > "$W/pk/fail/install/Fail Game.sh" +printf '#!/bin/sh\nexit 3\n' > "$W/pk/fail/extract/extract.sh" +printf '#!/bin/sh\n' > "$W/pk/slow/install/Slow Game.sh" +printf '#!/bin/sh\nsleep 30\n' > "$W/pk/slow/extract/extract.sh" +printf '#!/bin/sh\n' > "$W/pk/copy/install/Copy Game.sh" +for k in ok fail slow copy; do (cd "$W/pk/$k" && tar --format=ustar -cf "$W/e/$k-port.tar" *); done +python3 - <<'EOF' +import json, os +W = os.environ["W"] +sha = open(f"{W}/rom.sha1").read() +def port(name, tar, rom): + d = dict(id=name, name=name, system="native", version="1.0", author="A", license="CC0", source="https://x/", + desc="a port", kind="port", arch="armhf", payload=tar, rom=rom) + json.dump(d, open(f"{W}/e/{name}.json", "w")) +base = dict(name="Test Game (US)", sha1=[sha], size=[1048576], mode="extract", dest="portgame", output=["game.o2r"], + needs_ram_mb=1, est_minutes=1, needs_disk_mb=1) +port("goport", "ok-port.tar", base) +port("failport", "fail-port.tar", dict(base, dest="failgame")) +port("slowport", "slow-port.tar", dict(base, dest="slowgame")) +port("copyport", "copy-port.tar", dict(base, mode="copy", dest="copygame", copy_as="data/rom.z64", output=[])) +import tarfile +with tarfile.open(f"{W}/e/ok-port.tar.zst", "w:zst", format=tarfile.USTAR_FORMAT) as t: + for n in ("install", "extract"): + t.add(f"{W}/pk/ok/{n}", arcname=n) +port("zstdport", "ok-port.tar.zst", dict(base, dest="zstdgame")) +EOF +python3 "$MC" --entries "$W/e" --base-url "$BASE" -o "$W/out" --key "$W/store.key" --mkupdate "$MK" > /dev/null +check "make-catalog signs" "$MK verifyfile -p $W/store.pub -x $W/out/catalog.json.sig $W/out/catalog.json > /dev/null" +check "verifyfile: another key refused" "! $MK verifyfile -p $W/other.pub -x $W/out/catalog.json.sig $W/out/catalog.json 2> /dev/null" + +# an entry without a licence is refused by the catalog tool +mkdir -p "$W/bad" +cp "$W/e/mage.nes" "$W/bad/" +python3 - <<'EOF' +import json, os +W = os.environ["W"] +d = json.load(open(f"{W}/e/mage.json")); d["id"] = "nolicense"; d["license"] = "" +json.dump(d, open(f"{W}/bad/x.json", "w")) +EOF +check "catalog tool: no licence refused" "! python3 $MC --entries $W/bad --base-url $BASE -o $W/badout > /dev/null 2>&1" + +# --- server +(cd "$W/out" && exec python3 -m http.server "$PORT" --bind 127.0.0.1 > "$W/server.log" 2>&1) & +SRV=$! +trap 'kill $SRV 2> /dev/null' EXIT +sleep 1 + +S="$ST --allow-http --pubkey $W/store.pub --url $BASE/catalog.json --roms $W/roms --state $W/state --cover-dir $W/covers" +OUT=$($S list) +check "list: entries" "echo \"\$OUT\" | grep -q '^entry.id=mage'" +check "list: native armhf shown" "echo \"\$OUT\" | grep -q 'id=coolgame'" +check "list: other CPU hidden" "! echo \"\$OUT\" | grep -q 'id=wrongarch'" +check "list: source net" "echo \"\$OUT\" | grep -q '^done.count=8.source=net'" +check "list by system" "[ \"\$($S list snes | grep -c '^entry')\" = 1 ]" + +# rom +OUT=$($S get mage) +check "get rom ok" "echo \"\$OUT\" | grep -q '^ok.id=mage'" +check "rom placed" "cmp -s '$W/roms/nes/Micro Mage.nes' $W/e/mage.nes" +check "installed" "$S installed | grep -q 'id=mage.version=1.0'" +check "list marks installed" "$S list | grep -q 'id=mage.*installed=1.0.update=0'" +check "no staging left" "[ -z \"\$(ls -A $W/roms | grep '^\\.store')\" ]" + +# tar + native +$S get pack > /dev/null +check "tar unpacked" "[ -f $W/roms/snes/data/level1.bin ]" +$S get coolgame > /dev/null +check "native placed" "[ -f '$W/roms/native/Cool Game.sh' ] && [ -f $W/roms/native/data/level1.bin ]" +check "native: record lists top-level paths" "[ \"\$(grep -c '^coolgame' $W/roms/.rsos-store/installed.tsv)\" = 2 ]" +check "a roms folder that is not the console's: its record is in it, not in the state" "[ ! -e $W/state/installed.tsv ]" + +# remove +OUT=$($S remove coolgame) +check "remove ok" "echo \"\$OUT\" | grep -q '^ok.id=coolgame.removed=2'" +check "remove deletes files" "[ ! -e '$W/roms/native/Cool Game.sh' ] && [ ! -e $W/roms/native/data ]" +check "remove unknown" "! $S remove coolgame > /dev/null" +check "remove keeps the others" "[ -f '$W/roms/nes/Micro Mage.nes' ]" + +# not ours: refuse to overwrite +mkdir -p "$W/roms/native" && printf 'mine' > "$W/roms/native/Cool Game.sh" +OUT=$($S get coolgame) +check "foreign file: refused" "echo \"\$OUT\" | grep -q '^error.code=exists'" +check "foreign file untouched" "[ \"\$(cat '$W/roms/native/Cool Game.sh')\" = mine ]" +rm -f "$W/roms/native/Cool Game.sh" + +# wrong bytes on the server: hash / size +cp "$W/out/files/mage.nes" "$W/mage.good" +printf 'NES\032 pretend ROM v9' > "$W/out/files/mage.nes" +OUT=$($S get mage) +check "wrong bytes refused" "echo \"\$OUT\" | grep -q '^error.code=\\(hash\\|download\\)'" +check "old file kept" "cmp -s '$W/roms/nes/Micro Mage.nes' $W/e/mage.nes" +head -c 100 /dev/zero > "$W/out/files/mage.nes" +OUT=$($S get mage) +check "wrong size refused" "echo \"\$OUT\" | grep -q '^error.code=download'" +cp "$W/mage.good" "$W/out/files/mage.nes" +check "nothing left in the games folder" "[ -z \"\$(ls -A $W/roms | grep '^\\.store')\" ]" + +# update: a new version replaces the old +python3 - <<'EOF' +import json, os, hashlib +W = os.environ["W"] +c = json.load(open(f"{W}/out/catalog.json")) +data = b"NES\x1a pretend ROM v2 longer" +open(f"{W}/out/files/mage.nes", "wb").write(data) +for e in c["entries"]: + if e["id"] == "mage": + e.update(version="1.1", size=len(data), unpacked=len(data), sha256=hashlib.sha256(data).hexdigest()) +json.dump(c, open(f"{W}/out/catalog.json", "w"), sort_keys=True, indent=1) +EOF +"$MK" signfile -s "$W/store.key" -o "$W/out/catalog.json.sig" "$W/out/catalog.json" > /dev/null +check "update flagged" "$S list | grep -q 'id=mage.*installed=1.0.update=1'" +$S get mage > /dev/null +check "update installed" "$S installed | grep -q 'id=mage.version=1.1' && grep -q 'longer' '$W/roms/nes/Micro Mage.nes'" + + +# --- ports made from the player's ROM +mkdir -p "$W/roms/n64" "$W/proms/n64" +cp "$W/game.v64" "$W/proms/n64/Test Game.v64" +head -c 1048576 /dev/zero > "$W/proms/n64/Other.z64" +printf 'NOTAROM' > "$W/proms/n64/Short.z64" +cp "$W/game.n64" "$W/proms/n64/readme.txt" +P="$ST --allow-http --pubkey $W/store.pub --url $BASE/catalog.json --roms $W/proms --state $W/pstate" +OUT=$($P find-rom goport) +check "find-rom: the v64 dump is found by its z64 SHA-1" "echo \"\$OUT\" | grep -q '^rom.path=.*Test Game.v64.sha1='\"$SHA1\"" +check "find-rom: the hash is remembered" "[ -s $W/pstate/romhash.tsv ]" +OUT=$($ST --allow-http --pubkey $W/store.pub --url $BASE/catalog.json --roms $W/roms --state $W/pstate find-rom goport) +check "find-rom: no ROM" "echo \"\$OUT\" | grep -q '^error.code=norom'" +mkdir -p "$W/usb/n64" && cp "$W/game.n64" "$W/usb/n64/Dump.n64" +OUT=$($ST --allow-http --pubkey $W/store.pub --url $BASE/catalog.json --roms $W/roms --scan $W/usb --state $W/pstate find-rom goport) +check "find-rom: a scanned drive, n64 byte order" "echo \"\$OUT\" | grep -q '^rom.path=.*Dump.n64'" + +OUT=$($P install-port goport) +check "install-port ok" "echo \"\$OUT\" | grep -q '^ok.id=goport'" +check "port: program files placed" "[ -f '$W/proms/native/Port Game.sh' ] && [ -f $W/proms/native/portgame/prog.bin ]" +check "port: the made archive is in the port's folder (ROM given in z64 order)" "cmp -s $W/proms/native/portgame/game.o2r $W/game.z64" +check "port: progress from the extractor" "echo \"\$OUT\" | grep -q '^progress.phase=extract.done=2.total=2'" +check "port: no work folder left" "[ -z \"\$(ls -A $W/proms | grep '^\\.store')\" ]" +check "port: listed as installed" "$P list | grep -q 'id=goport.*kind=port.*installed=1.0'" +printf 'savegame' > $W/proms/native/portgame/save.dat +OUT=$($P remove goport) +check "port remove ok" "echo \"\$OUT\" | grep -q '^ok.id=goport'" +check "port remove: store files gone, the game's own save stays" "[ ! -e '$W/proms/native/Port Game.sh' ] && [ ! -e $W/proms/native/portgame/game.o2r ] && [ -f $W/proms/native/portgame/save.dat ]" +rm -rf $W/proms/native + +OUT=$($P install-port failport) +check "failing extractor: error" "echo \"\$OUT\" | grep -q '^error.code=extract'" +check "failing extractor: nothing installed, no work folder" "[ ! -e '$W/proms/native/Fail Game.sh' ] && [ -z \"\$(ls -A $W/proms | grep '^\\.store')\" ]" +printf 'MemTotal: 1000000 kB\nMemAvailable: 500 kB\n' > "$W/lowmem.txt" +OUT=$(RSOS_MEMINFO=$W/lowmem.txt $P install-port goport) +check "not enough free memory: asked to restart" "echo \"\$OUT\" | grep -q '^error.code=memory'" +OUT=$($P --rom "$W/proms/n64/Other.z64" install-port goport) +check "a wrong ROM given: refused" "echo \"\$OUT\" | grep -q '^error.code=norom'" + +T0=$(date +%s) +OUT=$(RSOS_MEMFLOOR_KB=999999999 $P install-port slowport) +T1=$(date +%s) +check "memory floor: the extractor is killed" "echo \"\$OUT\" | grep -q '^error.code=memory'" +check "memory floor: quickly, nothing left" "[ $((T1 - T0)) -lt 10 ] && [ ! -e '$W/proms/native/Slow Game.sh' ] && [ -z \"\$(ls -A $W/proms | grep '^\\.store')\" ]" +check "the killed extractor is gone" "! pgrep -f 'sleep 30' > /dev/null" +OUT=$(RSOS_TIMEOUT_S=2 $P install-port slowport) +check "timeout: the extractor is killed" "echo \"\$OUT\" | grep -q '^error.code=timeout'" + +OUT=$($P install-port copyport) +check "copy mode: the ROM goes into the port's folder in z64 order" "echo \"\$OUT\" | grep -q '^ok.id=copyport' && cmp -s $W/proms/native/copygame/data/rom.z64 $W/game.z64" +$P remove copyport > /dev/null +mkdir -p $W/proms/native && printf 'mine' > "$W/proms/native/Copy Game.sh" +OUT=$($P install-port copyport) +check "port: a file that is not the store's is moved aside, then the port installs" "echo \"\$OUT\" | grep -q '^ok.id=copyport' && [ \"\$(cat '$W/proms/native/.store-replaced/copyport/Copy Game.sh')\" = mine ] && [ \"\$(cat '$W/proms/native/Copy Game.sh')\" != mine ]" +# removed by the store (the game's save stays in its folder), then installed again +$P remove copyport > /dev/null +mkdir -p $W/proms/native/copygame && printf 'old' > $W/proms/native/copygame/save.dat +OUT=$($P install-port copyport) +check "port: installs again over what a delete left, its save kept" "echo \"\$OUT\" | grep -q '^ok.id=copyport' && [ -f '$W/proms/native/Copy Game.sh' ] && [ \"\$(cat $W/proms/native/copygame/save.dat)\" = old ]" +# the menu's "Delete this game" on the launcher: the whole port goes, the save and other games stay +mkdir -p $W/proms/native/.store-replaced/copyport && printf 'mine' > "$W/proms/native/.store-replaced/copyport/Copy Game.sh" +printf 'by hand' > "$W/proms/native/Hand Game.sh" +OUT=$($P remove-path "$W/proms/native/Copy Game.sh") +check "remove-path: the launcher's port is removed" "echo \"\$OUT\" | grep -q '^ok.id=copyport' && [ ! -e '$W/proms/native/Copy Game.sh' ] && [ ! -e $W/proms/native/copygame/data/rom.z64 ]" +check "remove-path: the save stays, the moved-aside copy goes" "[ \"\$(cat $W/proms/native/copygame/save.dat)\" = old ] && [ ! -e $W/proms/native/.store-replaced ]" +check "remove-path: no longer installed" "! $P installed | grep -q 'id=copyport'" +OUT=$($P remove-path "native/Hand Game.sh") +check "remove-path: a game not from the store is left alone" "echo \"\$OUT\" | grep -q '^error.code=notstore' && [ -f '$W/proms/native/Hand Game.sh' ]" +OUT=$($P remove-path "../outside.sh") +check "remove-path: a path outside the roms folder" "echo \"\$OUT\" | grep -q '^error.code=notstore'" +rm -rf $W/proms/native + + +OUT=$($P install-port zstdport) +check "a zstd-compressed port package installs" "echo \"\$OUT\" | grep -q '^ok.id=zstdport' && cmp -s $W/proms/native/zstdgame/game.o2r $W/game.z64" +check "zstd: no temporary tar left" "[ -z \"\$(ls -A $W/proms | grep '^\.store')\" ]" +$P remove zstdport > /dev/null +rm -rf $W/proms/native + + +# the player's own catalog: /store.ini +mkdir -p "$W/inistate" && printf 'url=%s/catalog.json +allow_http=1 +' "$BASE" > "$W/inistate/store.ini" +OUT=$($ST --pubkey $W/store.pub --state $W/inistate --roms $W/roms list) +check "store.ini: the catalog URL and allow_http are used" "echo \"\$OUT\" | grep -q '^done.count=8.source=net'" +OUT=$($ST --pubkey $W/store.pub --state $W/inistate --roms $W/roms --url http://127.0.0.1:1/x.json list) +check "store.ini: an option wins over it (the dead URL falls back to the saved catalog)" "echo \"\$OUT\" | grep -q 'source=cache'" + +# tampered / wrongly signed catalog +cp "$W/out/catalog.json" "$W/cat.good" +sed 's/"version": "1.1"/"version": "9.9"/' "$W/cat.good" > "$W/out/catalog.json" +OUT=$($ST --allow-http --pubkey $W/store.pub --url $BASE/catalog.json --state $W/state2 list) +check "tampered catalog refused" "echo \"\$OUT\" | grep -q '^error.code=catalog'" +cp "$W/cat.good" "$W/out/catalog.json" +OUT=$($ST --allow-http --pubkey $W/other.pub --url $BASE/catalog.json --state $W/state3 list) +check "catalog from another key refused" "echo \"\$OUT\" | grep -q '^error.code=catalog'" +check "refused catalog not cached" "[ ! -e $W/state3/catalog.json ]" + +# hostile archives (hand-made signed catalog) +python3 - <<'EOF' +import json, os, tarfile, io, hashlib +W, PORT = os.environ["W"], os.environ["PORT"] +def tarbytes(members): + b = io.BytesIO() + with tarfile.open(fileobj=b, mode="w", format=tarfile.USTAR_FORMAT) as t: + for name, data, typ in members: + ti = tarfile.TarInfo(name) + ti.type = typ + if typ == tarfile.REGTYPE: + ti.size = len(data) + t.addfile(ti, io.BytesIO(data)) + else: + ti.linkname = "/etc/passwd" + t.addfile(ti) + return b.getvalue() +evil = {"dots": [("../evil.txt", b"x", tarfile.REGTYPE)], + "abs": [("/tmp/evil.txt", b"x", tarfile.REGTYPE)], + "link": [("ln", b"", tarfile.SYMTYPE)], + "bomb": [("big.bin", b"\0" * 100000, tarfile.REGTYPE)]} +entries = [] +for k, m in evil.items(): + data = tarbytes(m) + open(f"{W}/out/files/{k}.tar", "wb").write(data) + entries.append(dict(id=k, name=k, system="snes", version="1", author="a", license="x", source="x", desc="d", + kind="tar", size=len(data), unpacked=2000 if k == "bomb" else len(data) + 10, + sha256=hashlib.sha256(data).hexdigest(), url=f"http://127.0.0.1:{PORT}/files/{k}.tar")) +json.dump({"format": 1, "entries": entries}, open(f"{W}/out/catalog.json", "w")) +EOF +"$MK" signfile -s "$W/store.key" -o "$W/out/catalog.json.sig" "$W/out/catalog.json" > /dev/null +for k in dots abs link bomb; do + OUT=$($S get $k) + check "hostile archive $k refused" "echo \"\$OUT\" | grep -q '^error.code=archive'" +done +check "nothing escaped" "[ ! -e $W/evil.txt ] && [ ! -e /tmp/evil.txt ] && [ ! -e $W/roms/snes/big.bin ] && [ ! -e $W/roms/snes/ln ]" +check "staging cleaned" "[ -z \"\$(ls -A $W/roms | grep '^\\.store')\" ]" + +# offline: the last verified catalog (state) is used +kill $SRV 2> /dev/null +sleep 1 +OUT=$($S list) +check "offline: cached catalog" "echo \"\$OUT\" | grep -q '^done.count=4.source=cache'" +OUT=$($ST --allow-http --pubkey $W/store.pub --url $BASE/catalog.json --state $W/state9 list) +check "offline without a cache: error" "echo \"\$OUT\" | grep -q '^error.code=catalog'" + +# local catalog file mode +OUT=$($ST --pubkey $W/store.pub --catalog $W/out/catalog.json --state $W/state8 list) +check "local catalog file" "echo \"\$OUT\" | grep -q '^done.count=4'" + +echo "store_test: $pass passed, $fail failed" +[ "$fail" = 0 ] diff --git a/frontend/tests/fake-rsos-store.sh b/frontend/tests/fake-rsos-store.sh new file mode 100644 index 0000000..70e2961 --- /dev/null +++ b/frontend/tests/fake-rsos-store.sh @@ -0,0 +1,94 @@ +#!/bin/sh +# fake-rsos-store.sh: a stand-in for rsos-store (src/update/rsos-store.c) for the preview tool +# (--store-helper): three games, the install state in $FAKE_STORE_DIR/installed, every call logged +# to $FAKE_STORE_DIR/calls.log. FAKE_STORE_FAIL=space makes "get" fail like a full drive; a port needs a ROM: +# "find-rom" finds one unless $FAKE_STORE_DIR/norom exists (FAKE_STORE_FAIL=memory: install-port fails). +D=${FAKE_STORE_DIR:?FAKE_STORE_DIR is not set} +mkdir -p "$D" +echo "$*" >> "$D/calls.log" +OUT=/dev/stdout +ROMS= +ROMARG= +while [ $# -gt 0 ]; do + case "$1" in + --out) OUT=$2; shift 2 ;; + --roms) ROMS=$2; shift 2 ;; + --rom) ROMARG=$2; shift 2 ;; + --scan) shift 2 ;; + *) break ;; + esac +done +CMD=$1 +ID=${2:-} +INS=$D/installed +touch "$INS" +T=$(printf '\t') +entry() { # id name system version size desc kind + v=$(grep "^$1$T" "$INS" | cut -f2) + upd=0 + [ -n "$v" ] && [ "$v" != "$4" ] && upd=1 + extra= + [ "$7" = port ] && extra=$(printf ' rom=Ocarina of Time (US 1.2) mode=extract minutes=4') + printf 'entry id=%s name=%s system=%s version=%s author=Test Author license=CC0 desc=%s size=%s kind=%s installed=%s update=%s%s +' "$1" "$2" "$3" "$4" "$6" "$5" "$7" "$v" "$upd" "$extra" +} +case "$CMD" in +find-rom) + if [ -e "$D/norom" ]; then + printf 'error code=norom text=no ROM found +' > "$OUT" + exit 1 + fi + printf 'rom path=/data/roms/n64/Ocarina of Time (U) (V1.2).z64 sha1=41b3bdc4 name=Ocarina of Time +done count=1 +' > "$OUT" + ;; +install-port) + if [ "${FAKE_STORE_FAIL:-}" = memory ]; then + printf 'error code=memory text=not enough memory +' > "$OUT" + exit 1 + fi + printf 'progress phase=extract done=30 total=100 +' > "$OUT" + sleep 1 + printf 'progress phase=extract done=90 total=100 +ok id=%s version=x +' "$ID" >> "$OUT" + grep -v "^$ID$T" "$INS" > "$INS.tmp" + printf '%s %s +' "$ID" 9.3.1 >> "$INS.tmp" + mv "$INS.tmp" "$INS" + ;; +list) + { + entry micro-mage "Micro Mage" nes 1.0 41040 "A platformer for the NES." rom + entry cool-game "Cool Game" native 2.1 5242880 "A native game." native + entry zelda-port "Ocarina of Time" native 9.3.1 61000000 "A port made from your own ROM." port + entry puzzle "Puzzle Pack" snes 1.1 800000 "Ten puzzles." tar + printf 'done\tcount=3\tsource=net\n' + } > "$OUT" + ;; +get) + if [ "${FAKE_STORE_FAIL:-}" = space ]; then + printf 'error\tcode=space\ttext=not enough free space\n' > "$OUT" + exit 1 + fi + printf 'progress\tphase=download\tdone=500\ttotal=1000\n' > "$OUT" + sleep 1 + printf 'progress\tphase=download\tdone=1000\ttotal=1000\nok\tid=%s\tversion=x\n' "$ID" >> "$OUT" + grep -v "^$ID$T" "$INS" > "$INS.tmp" + case "$ID" in + micro-mage) ver=1.0 ;; cool-game) ver=2.1 ;; *) ver=1.1 ;; + esac + printf '%s\t%s\n' "$ID" "$ver" >> "$INS.tmp" + mv "$INS.tmp" "$INS" + ;; +remove) + grep -v "^$ID$T" "$INS" > "$INS.tmp" + mv "$INS.tmp" "$INS" + printf 'ok\tid=%s\tremoved=1\n' "$ID" > "$OUT" + ;; +*) exit 2 ;; +esac +exit 0 diff --git a/frontend/tests/test_b2.c b/frontend/tests/test_b2.c index bc3e84d..299c48f 100644 --- a/frontend/tests/test_b2.c +++ b/frontend/tests/test_b2.c @@ -56,8 +56,10 @@ static void test_systems(const char *cores) int n = systems_cores_for(nw[i].name, cs, MAX_CORES_PER_SYSTEM); CHECK(sd && !strcmp(sd->fullname, nw[i].full) && sd->maker[0] && sd->year > 1900 && n > 0 && - !strcmp(cs[0]->id, nw[i].core) && pos(nw[i].name) >= 0, - "%s: \"%s\" (%s, %d), default core %s, in the carousel at %d", nw[i].name, sd ? sd->fullname : "?", + !strcmp(cs[0]->id, nw[i].core) && + /* Doom and Cave Story are listed inside the one Ports entry */ + (systems_is_ports_member(nw[i].name) ? pos(nw[i].name) < 0 : pos(nw[i].name) >= 0), + "%s: \"%s\" (%s, %d), default core %s, carousel position %d", nw[i].name, sd ? sd->fullname : "?", sd ? sd->maker : "?", sd ? sd->year : 0, n ? cs[0]->id : "none", pos(nw[i].name)); } for (int i = 0; i < systems_count(); i++) @@ -69,8 +71,8 @@ static void test_systems(const char *cores) pos("amstradcpc") < pos("dos") && pos("dos") < pos("scummvm") && pos("c64") > pos("coleco") && pos("scummvm") < pos("arcade"), "the computers together (C64, Spectrum, MSX, CPC, then DOS and ScummVM), before the arcade systems"); - CHECK(pos("pico8") > pos("neocd") && pos("doom") == pos("pico8") + 1 && pos("cavestory") == pos("doom") + 1, - "PICO-8, then the ports (Doom, Cave Story), after the arcade systems"); + CHECK(pos("pico8") > pos("neocd") && pos("ports") == pos("pico8") + 1, + "PICO-8, then the one Ports entry (Doom, Cave Story, native games), after the arcade systems"); CHECK(systems_find("dos")->theme[1] && !strcmp(systems_find("dos")->theme[1], "pc") && !strcmp(systems_find("doom")->theme[1], "ports") && !strcmp(systems_find("supergrafx")->theme[2], "pcengine"), "theme folders: dos -> pc, doom -> ports, supergrafx -> pcengine (sets without their own)"); diff --git a/frontend/tests/test_follow_policy.c b/frontend/tests/test_follow_policy.c new file mode 100644 index 0000000..81c610d --- /dev/null +++ b/frontend/tests/test_follow_policy.c @@ -0,0 +1,113 @@ +/* test_follow_policy.c - host unit test for frontend/src/follow/policy.c */ +#include +#include + +#include "../src/follow/policy.h" + +static int fails; +#define CHECK(c, msg) do { if (!(c)) { fprintf(stderr, "FAIL %s:%d %s\n", __FILE__, __LINE__, msg); fails++; } } while (0) + +static struct pf_cfg cfg_rs2(void) +{ + struct pf_cfg c = { .hdmi_w = 1280, .hdmi_h = 720, .hdmi_hz = 60, .hdmi_builtin_mode = true, + .hdmi_crtc_index = 1, .panel_keep_scanning = true, .crtc_count = 2 }; + return c; +} + +static struct pf_conn panel(void) +{ + struct pf_conn p = { .kind = PF_KIND_LCD, .connected = true, .has_edid = false, .possible_crtcs = 1u }; + p.nmodes = 1; + p.modes[0] = (struct pf_mode){ 800, 480, 60, true }; + return p; +} + +static struct pf_conn hdmi(bool edid) +{ + struct pf_conn h = { .kind = PF_KIND_HDMI, .connected = true, .has_edid = edid, .possible_crtcs = 3u }; + h.nmodes = 3; + h.modes[0] = (struct pf_mode){ 1920, 1080, 60, true }; + h.modes[1] = (struct pf_mode){ 1280, 720, 60, false }; + h.modes[2] = (struct pf_mode){ 640, 480, 60, false }; + return h; +} + +static void test_hdmi_plugged_wins_on_crtc1(void) +{ + struct pf_cfg c = cfg_rs2(); + struct pf_conn cs[2] = { panel(), hdmi(true) }; + struct pf_choice ch = pf_choose(&c, cs, 2); + + CHECK(ch.conn == 1, "HDMI chosen when plugged in"); + CHECK(ch.crtc == 1, "HDMI on CRTC 1 (panel keeps CRTC 0)"); + CHECK(ch.w == 1280 && ch.h == 720 && ch.hz == 60, "policy 720p60, not the preferred 1080p"); +} + +static void test_hdmi_never_on_panel_crtc(void) +{ + struct pf_cfg c = cfg_rs2(); + struct pf_conn cs[2] = { panel(), hdmi(true) }; + + cs[1].possible_crtcs = 1u; /* HDMI can only use CRTC 0 */ + struct pf_choice ch = pf_choose(&c, cs, 2); + CHECK(ch.conn != 1, "HDMI refused when it could only use the panel's CRTC"); + CHECK(ch.conn == 0 && ch.crtc == 0, "falls back to the panel"); +} + +static void test_no_edid_uses_cea720(void) +{ + struct pf_cfg c = cfg_rs2(); + struct pf_conn cs[2] = { panel(), hdmi(false) }; + struct pf_choice ch = pf_choose(&c, cs, 2); + + CHECK(ch.conn == 1 && ch.builtin, "no EDID: CEA 720p60 builtin"); + CHECK(ch.w == 1280 && ch.h == 720, "builtin 1280x720"); +} + +static void test_hdmi_unplugged_is_panel(void) +{ + struct pf_cfg c = cfg_rs2(); + struct pf_conn cs[2] = { panel(), hdmi(true) }; + struct pf_choice ch; + + cs[1].connected = false; + ch = pf_choose(&c, cs, 2); + CHECK(ch.conn == 0 && ch.crtc == 0, "unplugged: built-in panel on CRTC 0"); +} + +static void test_no_panel_board(void) +{ + /* a board with HDMI only (no built-in screen) and no panel */ + struct pf_cfg c = cfg_rs2(); + struct pf_conn cs[1] = { hdmi(true) }; + struct pf_choice ch = pf_choose(&c, cs, 1); + + CHECK(ch.conn == 0 && ch.crtc == 1, "HDMI-only board: HDMI on CRTC 1"); +} + +static void test_nothing_connected(void) +{ + struct pf_cfg c = cfg_rs2(); + struct pf_conn cs[1] = { panel() }; + struct pf_choice ch; + + cs[0].connected = false; + ch = pf_choose(&c, cs, 1); + CHECK(ch.conn == -1 && ch.crtc == -1, "no output: none"); +} + +int main(void) +{ + test_hdmi_plugged_wins_on_crtc1(); + test_hdmi_never_on_panel_crtc(); + test_no_edid_uses_cea720(); + test_hdmi_unplugged_is_panel(); + test_no_panel_board(); + test_nothing_connected(); + if (fails) { + fprintf(stderr, "%d failure(s)\n", fails); + return 1; + } + printf("follow policy: all tests pass\n"); + return 0; +} diff --git a/frontend/tests/test_input.c b/frontend/tests/test_input.c index 1bd66b2..91edaab 100644 --- a/frontend/tests/test_input.c +++ b/frontend/tests/test_input.c @@ -304,6 +304,355 @@ static void keyboard_in_game(void) rig_close(&r); } +/* A Retrolink N64 pad (0079:0006, buttons as recorded on a console): + * A b6, B b8, Z b7, L b4, R b5, Start b9, C-up b0, C-down b2, C-left b3, + * C-right b1, in the database's names for an N64 pad (input.h) */ +#define RETROLINK_N64 "a:b6,b:b8,-righty:b0,+righty:b2,-rightx:b3,+rightx:b1,lefttrigger:b7," \ + "leftshoulder:b4,rightshoulder:b5,start:b9,dpup:h0.1,type:n64" +#define N64B(i) (BTN_TRIGGER + (i)) + +static bool next_nav(struct input *in, enum input_btn want) +{ + struct input_nav ev; + bool seen = false; + + while (input_next_nav(in, &ev)) + if (ev.btn == want && ev.type == IN_NAV_PRESS) + seen = true; + return seen; +} + +static void n64_pad(void) +{ + struct rig r; + enum input_hotkey hk; + char sdl[2048]; + bool seen; + + puts("input: an N64 pad profile (type n64)"); + rig_open(&r); + kernel_held = false; + map_reset(&r.ext); + for (int c = 0; c < KEY_CNT; c++) + r.ext.btn_index[c] = -1; + for (int i = 0; i < 12; i++) + r.ext.btn_index[N64B(i)] = (int16_t)i; + r.ext.hat_index[0] = 0; + CHECK(apply_sdl_mapping(&r.ext, RETROLINK_N64) >= 10, "the profile applies"); + CHECK(r.ext.type == IN_PAD_N64, "its type is n64"); + strlcpy_(r.ext.guid, "03000000790000000600000010010000", sizeof(r.ext.guid)); + strlcpy_(r.ext.name, "Generic USB Joystick", sizeof(r.ext.name)); + r.ext.source = IN_MAP_USER; + r.ext.configured = true; + + /* its stick: not in the profile, so the usual X / Y axes */ + { + unsigned long absbits[ABS_CNT / (8 * sizeof(unsigned long)) + 1] = { 0 }; + struct input_event ev = { .type = EV_ABS, .code = ABS_X, .value = 255 }; + char elem[16]; + + absbits[0] = (1UL << ABS_X) | (1UL << ABS_Y); + default_left_stick(&r.ext, absbits); + CHECK(r.ext.ax[ABS_X].kind == AX_STICK && r.ext.ax[ABS_Y].kind == AX_STICK, + "a profile without the stick gets X / Y"); + /* the wizard: an 8-bit stick (0..255, rest 128) pushed all the way */ + r.ext.axis_index[ABS_X] = 0; + r.ext.axis_index[ABS_Y] = 1; + for (int a = ABS_X; a <= ABS_Y; a++) { + r.ext.absinfo[a] = (struct input_absinfo){ .minimum = 0, .maximum = 255 }; + r.ext.abs_rest[a] = 128; + } + r.in.cap_slot = 1; + capture_event(&r.in, &r.ext, &ev); + seen = input_capture_next(&r.in, elem, sizeof(elem)) && !strcmp(elem, "+a0"); + CHECK(seen, "the wizard sees an 8-bit stick pushed right"); + r.in.cap_slot = -1; + } + + /* in a game: positional for the N64 core, C buttons also on the right stick */ + r.in.mode = INPUT_MODE_GAME; + key(&r, true, N64B(6), 1); + CHECK(HELD(&r, 1, IN_B), "A is RetroPad B (the N64 core's A)"); + key(&r, true, N64B(6), 0); + key(&r, true, N64B(0), 1); + CHECK(input_port_analog(&r.in, 1, 1, 1) == -0x7fff, "C-up pushes the right stick up"); + key(&r, true, N64B(0), 0); + CHECK(input_port_analog(&r.in, 1, 1, 1) == 0, "and lets it go"); + key(&r, true, N64B(1), 1); + CHECK(input_port_analog(&r.in, 1, 1, 0) == 0x7fff, "C-right pushes it right"); + key(&r, true, N64B(1), 0); + + /* Z + Start: a short press is ordinary play, a held second the menu */ + while (input_next_hotkey(&r.in, &hk)) + ; + key(&r, true, N64B(7), 1); + key(&r, true, N64B(9), 1); + CHECK(input_quit_combo_held(&r.in), "Z + Start counts as the quit combination"); + seen = next_hk(&r.in, IN_HK_MENU); + CHECK(!seen, "Z + Start pressed: no menu yet"); + CHECK(input_timeout_ms(&r.in) > 0 && input_timeout_ms(&r.in) <= 1000, "the hold is timed"); + r.ext.held_check_at = ui_now_ms() + 60000; /* the mock's kernel state says released */ + usleep(1100 * 1000); + input_poll(&r.in); + seen = next_hk(&r.in, IN_HK_MENU); + CHECK(seen, "Z + Start held a second opens the in-game menu"); + key(&r, true, N64B(9), 0); + key(&r, true, N64B(7), 0); + + /* in the menus: A confirms, B goes back */ + input_set_mode(&r.in, INPUT_MODE_UI); + while (next_nav(&r.in, IN_A)) + ; + key(&r, true, N64B(6), 1); + seen = next_nav(&r.in, IN_A); + CHECK(seen, "in the menu, A confirms"); + key(&r, true, N64B(6), 0); + key(&r, true, N64B(8), 1); + seen = next_nav(&r.in, IN_B); + CHECK(seen, "and B goes back"); + key(&r, true, N64B(8), 0); + + /* for the native games: SDL's layout, without our own fields */ + input_sdl_mappings(&r.in, sdl, sizeof(sdl)); + CHECK(strstr(sdl, "03000000790000000600000010010000,N64 Controller (Generic USB Joystick),") != NULL, + "an SDL line per pad, named N64 for the games that choose a layout by name"); + CHECK(strstr(sdl, "b:b8,") && strstr(sdl, "-righty:b0,") && strstr(sdl, "+rightx:b1,"), + "B on b, the C buttons on the right stick"); + CHECK(strstr(sdl, "rightshoulder:b5,") && strstr(sdl, "righttrigger:b5,"), "R on the shoulder and the trigger"); + CHECK(strstr(sdl, "a:b6,") && strstr(sdl, "lefttrigger:b7,") && strstr(sdl, "dpup:h0.1,"), + "A, Z and the d-pad as set up"); + CHECK(!strstr(sdl, "type:"), "no type field for SDL"); + CHECK(strstr(sdl, "leftx:a0,lefty:a1,") != NULL, "and the default stick for SDL"); + rig_close(&r); +} + +/* ------------------------------------------ known pads (no hardware here) */ +#define END (-1) + +static void set_bits(unsigned long *bits, const int *codes) +{ + for (; *codes != END; codes++) + bits[*codes / BITS_PER_LONG_] |= 1ul << (*codes % BITS_PER_LONG_); +} + +/* The pad as the kernel would show it (bus, ids, driver, codes), resolved + * as input_open() does, into the rig's USB slot */ +static void plug(struct rig *r, uint16_t vendor, uint16_t product, uint16_t version, + const char *driver, const char *name, const int *keys, const int *abs) +{ + unsigned long kb[NBITS(KEY_CNT)] = { 0 }, ab[NBITS(ABS_CNT)] = { 0 }; + struct input_nav ev; + enum input_hotkey hk; + + set_bits(kb, keys); + set_bits(ab, abs); + r->ext.id = (struct input_id){ .bustype = BUS_USB, .vendor = vendor, .product = product, + .version = version }; + strlcpy_(r->ext.driver, driver, sizeof(r->ext.driver)); + strlcpy_(r->ext.name, name, sizeof(r->ext.name)); + resolve_mapping(&r->in, &r->ext, kb, ab); + pad_release_all(&r->ext.own); + memset(r->ext.down, 0, sizeof(r->ext.down)); + r->ext.guide = false; + r->ext.own.has_analog = true; + while (input_next_nav(&r->in, &ev)) + ; + while (input_next_hotkey(&r->in, &hk)) + ; +} + +/* A press and release in a game: the RetroPad buttons it held */ +static uint16_t game_press(struct rig *r, int code) +{ + uint16_t b; + + input_set_mode(&r->in, INPUT_MODE_GAME); + key(r, true, code, 1); + b = input_port_buttons(&r->in, 1); + key(r, true, code, 0); + return b; +} + +/* A press and release in the menus: did the menu see `want`? */ +static bool ui_press(struct rig *r, int code, enum input_btn want) +{ + bool seen; + + input_set_mode(&r->in, INPUT_MODE_UI); + while (next_nav(&r->in, want)) + ; + key(r, true, code, 1); + seen = next_nav(&r->in, want); + key(r, true, code, 0); + return seen; +} + +static void known_pads(void) +{ + /* linux 6.18 hid-nintendo, n64con_button_mappings */ + static const int nso_n64_keys[] = { BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z, BTN_TL, BTN_TR, + BTN_TL2, BTN_TR2, BTN_SELECT, BTN_START, BTN_MODE, END }; + static const int stick_hat[] = { ABS_X, ABS_Y, ABS_HAT0X, ABS_HAT0Y, END }; + /* a 16-button HID joystick (hid-generic) with six axes */ + static const int hid16[] = { 0x120, 0x121, 0x122, 0x123, 0x124, 0x125, 0x126, 0x127, 0x128, + 0x129, 0x12a, 0x12b, 0x12c, 0x12d, 0x12e, 0x12f, END }; + static const int six_axes[] = { ABS_X, ABS_Y, ABS_Z, ABS_RX, ABS_RY, ABS_RZ, END }; + /* a 15-button HID gamepad (BTN_SOUTH ...) */ + static const int gp15[] = { 0x130, 0x131, 0x132, 0x133, 0x134, 0x135, 0x136, 0x137, 0x138, + 0x139, 0x13a, 0x13b, 0x13c, 0x13d, 0x13e, END }; + static const int four_axes_hat[] = { ABS_X, ABS_Y, ABS_Z, ABS_RZ, ABS_HAT0X, ABS_HAT0Y, END }; + /* xpad */ + static const int x360_keys[] = { BTN_A, BTN_B, BTN_X, BTN_Y, BTN_TL, BTN_TR, BTN_SELECT, + BTN_START, BTN_MODE, BTN_THUMBL, BTN_THUMBR, END }; + static const int x360_abs[] = { ABS_X, ABS_Y, ABS_Z, ABS_RX, ABS_RY, ABS_RZ, ABS_HAT0X, + ABS_HAT0Y, END }; + /* hid-nintendo gencon / nescon / a right Joy-Con */ + static const int gen_keys[] = { BTN_SOUTH, BTN_EAST, BTN_NORTH, BTN_WEST, BTN_Z, BTN_TL, + BTN_TR, BTN_SELECT, BTN_START, BTN_MODE, END }; + static const int nes_keys[] = { BTN_SOUTH, BTN_EAST, BTN_TL, BTN_TR, BTN_SELECT, BTN_START, END }; + static const int jcr_keys[] = { BTN_SOUTH, BTN_EAST, BTN_NORTH, BTN_WEST, BTN_TR, BTN_TR2, + BTN_START, BTN_THUMBR, BTN_MODE, END }; + /* a DualSense's touch pad, a device of its own */ + static const int touch_keys[] = { BTN_LEFT, BTN_TOOL_FINGER, BTN_TOUCH, BTN_TOOL_DOUBLETAP, END }; + static const int touch_abs[] = { ABS_X, ABS_Y, ABS_MT_SLOT, ABS_MT_POSITION_X, + ABS_MT_POSITION_Y, END }; + struct rig r; + char dir[] = "/tmp/rsos-input-XXXXXX", sdl[4096], path[128]; + unsigned long kb[NBITS(KEY_CNT)] = { 0 }, ab[NBITS(ABS_CNT)] = { 0 }; + enum input_hotkey hk; + bool seen; + uint16_t b; + FILE *f; + + puts("input: known pads, as their kernel drivers and the database lay them out"); + rig_open(&r); + kernel_held = false; + if (!mkdtemp(dir)) + exit(2); + r.in.cfg.user_map_dir = dir; + r.in.cfg.gcdb_path = "third_party/sdl-gamecontrollerdb/gamecontrollerdb.txt"; + + /* Nintendo Switch Online N64 (hid-nintendo) */ + plug(&r, 0x057e, 0x2019, 0x8111, "nintendo", "N64 Controller", nso_n64_keys, stick_hat); + CHECK(r.ext.source == IN_MAP_PROFILE && r.ext.type == IN_PAD_N64, "NSO N64: a built-in N64 profile"); + input_set_mode(&r.in, INPUT_MODE_GAME); + key(&r, true, BTN_SELECT, 1); + CHECK(input_port_analog(&r.in, 1, 1, 1) == -0x7fff, "NSO N64: C-up (the kernel's Select) is C-up"); + key(&r, true, BTN_SELECT, 0); + CHECK(game_press(&r, BTN_EAST) == BTN_MASK(IN_Y), "NSO N64: B (the kernel's EAST) is the N64 core's B"); + CHECK(game_press(&r, BTN_TL2) == BTN_MASK(IN_L2), "NSO N64: Z is L2"); + CHECK(ui_press(&r, BTN_SOUTH, IN_A), "NSO N64: A confirms in the menu"); + input_sdl_mappings(&r.in, sdl, sizeof(sdl)); + CHECK(strstr(sdl, "a:b0,") && strstr(sdl, "b:b1,") && strstr(sdl, "-righty:b10,") && + strstr(sdl, "+rightx:b2,") && strstr(sdl, "lefttrigger:b8,") && strstr(sdl, "guide:b12,"), + "NSO N64: native games get the database's layout for it"); + { + /* a port's layout renames the elements (all at once: two can swap) */ + static char s2[8192]; + + input_sdl_mappings_layout(&r.in, s2, sizeof(s2), + "# comment\nz = righttrigger\ncup = leftshoulder\nl=back\nb = x\nr = none\n"); + CHECK(strstr(s2, "righttrigger:b8,") && !strstr(s2, "lefttrigger:"), "layout: Z moved to the right trigger"); + CHECK(strstr(s2, "leftshoulder:b10,") && !strstr(s2, "-righty:"), "layout: C-up moved to the left shoulder"); + CHECK(strstr(s2, "x:b1,") && !strstr(s2, "b:b1,"), "layout: B moved to x"); + CHECK(strstr(s2, "back:") && !strstr(s2, "rightshoulder:"), "layout: L is back, R dropped"); + CHECK(strstr(s2, "+rightx:b2,") && strstr(s2, "a:b0,"), "layout: what it does not name stays"); + CHECK(strstr(s2, "platform:Linux,\n"), "layout: the line still ends properly"); + input_sdl_mappings_layout(&r.in, s2, sizeof(s2), NULL); + CHECK(strstr(s2, "lefttrigger:b8,") && strstr(s2, "b:b1,"), "no layout: unchanged"); + } + + /* Mayflash GameCube adapter, PC mode (hid-generic; the database knows it) */ + plug(&r, 0x0079, 0x1844, 0x0110, "hid-generic", "Mayflash GC", hid16, six_axes); + CHECK(r.ext.source == IN_MAP_GCDB && r.ext.type == IN_PAD_GC, "Mayflash: a GameCube pad from the database"); + CHECK(game_press(&r, 0x121) == BTN_MASK(IN_B), "GameCube: A is RetroPad B"); + CHECK(game_press(&r, 0x120) == BTN_MASK(IN_Y), "GameCube: B (left of A) is RetroPad Y"); + CHECK(game_press(&r, 0x122) == BTN_MASK(IN_A), "GameCube: X (right of A) is RetroPad A"); + CHECK(game_press(&r, 0x127) == BTN_MASK(IN_R), "GameCube: Z is R1"); + CHECK(ui_press(&r, 0x121, IN_A), "GameCube: A confirms in the menu"); + CHECK(ui_press(&r, 0x120, IN_B), "GameCube: B goes back"); + input_set_mode(&r.in, INPUT_MODE_GAME); + key(&r, true, 0x127, 1); + key(&r, true, 0x129, 1); + CHECK(input_quit_combo_held(&r.in), "GameCube: Z + Start is the quit combination"); + key(&r, true, 0x129, 0); + key(&r, true, 0x127, 0); + input_sdl_mappings(&r.in, sdl, sizeof(sdl)); + CHECK(strstr(sdl, "a:b1,") && strstr(sdl, "b:b0,") && strstr(sdl, "x:b2,") && + strstr(sdl, "rightshoulder:b7,"), "GameCube: native games get the database's labels"); + + /* 8BitDo N64 (hid-generic; the database knows it): C on a real stick */ + plug(&r, 0x2dc8, 0x2869, 0x0111, "hid-generic", "8BitDo N64", gp15, four_axes_hat); + CHECK(r.ext.source == IN_MAP_GCDB && r.ext.type == IN_PAD_N64, "8BitDo N64: an N64 pad from the database"); + CHECK(game_press(&r, 0x131) == BTN_MASK(IN_Y), "8BitDo N64: B is the N64 core's B"); + CHECK(game_press(&r, 0x138) == BTN_MASK(IN_L2), "8BitDo N64: Z is L2"); + CHECK(r.ext.ax[ABS_Z].kind == AX_STICK && r.ext.ax[ABS_Z].a == 1, "8BitDo N64: its C stick is the right stick"); + + /* Xbox 360 (xpad): the Linux standard */ + plug(&r, 0x045e, 0x028e, 0x0114, "xpad", "Microsoft X-Box 360 pad", x360_keys, x360_abs); + CHECK(r.ext.source == IN_MAP_PROFILE && r.ext.type == IN_PAD_MODERN, "Xbox 360: the Linux standard"); + CHECK(game_press(&r, BTN_SOUTH) == BTN_MASK(IN_B), "Xbox 360: A (bottom) is RetroPad B"); + CHECK(game_press(&r, BTN_EAST) == BTN_MASK(IN_A), "Xbox 360: B (right) is RetroPad A"); + CHECK(r.ext.ax[ABS_Z].kind == AX_TRIGGER && r.ext.ax[ABS_RX].kind == AX_STICK, + "Xbox 360: analog triggers, the right stick on RX / RY"); + input_set_mode(&r.in, INPUT_MODE_GAME); + while (input_next_hotkey(&r.in, &hk)) + ; + key(&r, true, BTN_MODE, 1); + seen = next_hk(&r.in, IN_HK_MENU); + CHECK(seen, "Guide in a game opens the in-game menu"); + CHECK(input_quit_combo_held(&r.in), "Guide held is the quit combination (native games)"); + key(&r, true, BTN_MODE, 0); + CHECK(!input_quit_combo_held(&r.in), "and released, it is not"); + + /* NSO Genesis: the kernel, not the database line for another layout */ + plug(&r, 0x057e, 0x201e, 0x8111, "", "Sega Genesis Control Pad", gen_keys, stick_hat); + CHECK(r.ext.source == IN_MAP_PROFILE, "NSO Genesis: not the database's line"); + CHECK(game_press(&r, BTN_WEST) == BTN_MASK(IN_Y), "NSO Genesis: A is RetroPad Y"); + CHECK(game_press(&r, BTN_SOUTH) == BTN_MASK(IN_B), "NSO Genesis: B is RetroPad B"); + CHECK(game_press(&r, BTN_EAST) == BTN_MASK(IN_A), "NSO Genesis: C is RetroPad A"); + + /* NSO NES (it says it is a Joy-Con) and a real right Joy-Con */ + plug(&r, 0x057e, 0x2007, 0x8111, "nintendo", "Joy-Con (R)", nes_keys, stick_hat); + CHECK(game_press(&r, BTN_SOUTH) == BTN_MASK(IN_A), "NSO NES: A (the kernel's SOUTH) is RetroPad A"); + CHECK(game_press(&r, BTN_EAST) == BTN_MASK(IN_B), "NSO NES: B is RetroPad B"); + plug(&r, 0x057e, 0x2007, 0x8111, "nintendo", "Joy-Con (R)", jcr_keys, stick_hat); + CHECK(game_press(&r, BTN_SOUTH) == BTN_MASK(IN_B), "a Joy-Con keeps the standard layout"); + + /* names in the database */ + CHECK(type_from_name("Raphnet GC and N64 Adapter") == IN_PAD_GC && + type_from_name("NSO GameCube Controller") == IN_PAD_GC && + type_from_name("PS SS N64 Adapter") == IN_PAD_N64 && + type_from_name("Hyperkin Admiral N64 Controller") == IN_PAD_N64 && + type_from_name("MSI GC20 V2") == IN_PAD_MODERN && + type_from_name("Be1 GC101 Xbox 360 Controller") == IN_PAD_MODERN, + "N64 and GameCube pads by their names in the database"); + + /* not a pad: a PlayStation pad's touch pad */ + set_bits(kb, touch_keys); + set_bits(ab, touch_abs); + CHECK(!caps_are_pad(kb, ab, 4), "a DualSense touch pad is not a player"); + memset(kb, 0, sizeof(kb)); + set_bits(kb, hid16); + CHECK(caps_are_pad(kb, ab, 16), "a HID joystick is"); + + /* a user mapping wins; forgetting it goes back to the automatic one */ + snprintf(path, sizeof(path), "%s/03000000790000004418000010010000.cfg", dir); + f = fopen(path, "w"); + if (!f) + exit(2); + fputs("03000000790000004418000010010000,Mayflash GC,a:b0,b:b1,start:b9,type:n64,platform:Linux,\n", f); + fclose(f); + plug(&r, 0x0079, 0x1844, 0x0110, "hid-generic", "Mayflash GC", hid16, six_axes); + CHECK(r.ext.source == IN_MAP_USER && r.ext.type == IN_PAD_N64, "a user mapping wins over the database"); + b = game_press(&r, 0x121); + CHECK(b == BTN_MASK(IN_Y), "with its own kind of pad"); + CHECK(input_forget_user_mapping(&r.in, 1) == 0 && access(path, F_OK) != 0, "forgetting it removes the file"); + CHECK(r.ext.source != IN_MAP_USER, "and the mapping is automatic again"); + rmdir(dir); + rig_close(&r); +} + int main(void) { puts("input: overflow recovery with stale events in the read buffer"); @@ -313,5 +662,7 @@ int main(void) menu_to_game(); stick_detect(); keyboard_in_game(); + n64_pad(); + known_pads(); return failures ? 1 : 0; } diff --git a/frontend/tests/test_loader.c b/frontend/tests/test_loader.c index acec4e6..9cbcce2 100644 --- a/frontend/tests/test_loader.c +++ b/frontend/tests/test_loader.c @@ -43,7 +43,7 @@ static const char *const g_systems[][2] = { { "gamegear", "gg" }, { "psx", "pbp" }, { "pcengine", "pce" }, { "pcenginecd", "ccd" }, { "ngp", "ngp" }, { "ngpc", "ngc" }, { "wonderswan", "ws" }, { "wonderswancolor", "wsc" }, { "atari2600", "a26" }, { "atari7800", "a78" }, { "atarilynx", "lnx" }, { "coleco", "col" }, - { "msx", "mx1" }, { "arcade", "zip" }, { "fbneo", "7z" }, { "neogeo", "neo" }, { "neocd", "cue" }, + { "msx", "mx1" }, { "doom", "wad" }, { "cavestory", "exe" }, { "arcade", "zip" }, { "fbneo", "7z" }, { "neogeo", "neo" }, { "neocd", "cue" }, }; /* src/ui/ui_internal.h: Settings > Game lists > Refresh game lists (force) */ @@ -643,6 +643,28 @@ int main(int argc, char **argv) ui_destroy(ui); } + printf("12. Doom, Cave Story and the native games are one Ports list\n"); + { + struct boot e; + char c1[512]; + + dir("data/roms/native"); + dir("data/roms/ports"); + put("data/roms/doom/E1M1.wad", "x"); + put("data/roms/cavestory/Doukutsu.exe", "x"); + put("data/roms/native/Test Game.sh", "x"); + put("data/roms/ports/Other.wad", "x"); + boot(&e, NULL, NULL); + CHECK(strstr(e.final, "ports:4"), "one Ports entry with the four games: %s", + field(e.final, "carousel", c1, sizeof(c1))); + CHECK(!strstr(e.final, "doom:") && !strstr(e.final, "cavestory:") && !strstr(e.final, "native:"), + "the three are not shown on their own"); + CHECK(!strcmp(systems_effective("ports", "/r/native/Test Game.sh"), "native"), "a .sh launches as a native game"); + CHECK(!strcmp(systems_effective("ports", "/r/ports/Doukutsu.EXE"), "cavestory"), "an .exe as Cave Story"); + CHECK(!strcmp(systems_effective("ports", "/r/doom/E1M1.wad"), "doom"), "a .wad as Doom"); + CHECK(!strcmp(systems_effective("snes", "/r/snes/x.sfc"), "snes"), "any other system is unchanged"); + } + printf(g_fail ? "test_loader: %d FAILED\n" : "test_loader: all passed\n", g_fail); return g_fail ? 1 : 0; } diff --git a/frontend/themes/rsos-dark/ports/theme.xml b/frontend/themes/rsos-dark/ports/theme.xml new file mode 100644 index 0000000..437c03c --- /dev/null +++ b/frontend/themes/rsos-dark/ports/theme.xml @@ -0,0 +1,10 @@ + + + 7 + + b3432f + carbon/ports + Game engines and native games + + ./../theme.xml + diff --git a/frontend/themes/rsos-light/ports/theme.xml b/frontend/themes/rsos-light/ports/theme.xml new file mode 100644 index 0000000..51b3ca0 --- /dev/null +++ b/frontend/themes/rsos-light/ports/theme.xml @@ -0,0 +1,10 @@ + + + 7 + + b3432f + carbon/ports + Game engines and native games + + ./../theme.xml + diff --git a/frontend/ui.mk b/frontend/ui.mk index 5fbbf77..c66fa19 100644 --- a/frontend/ui.mk +++ b/frontend/ui.mk @@ -34,6 +34,7 @@ UI_SRCS := \ $(UI_DIR)/src/ui/storage.c \ $(UI_DIR)/src/ui/update_ui.c \ $(UI_DIR)/src/ui/bt_ui.c \ + $(UI_DIR)/src/ui/store_ui.c \ $(UI_DIR)/src/ui/ui.c \ $(UI_DIR)/src/gfx/gfx.c \ $(UI_DIR)/src/gfx/font.c \ diff --git a/frontend/update.mk b/frontend/update.mk index 66bc40a..5748757 100644 --- a/frontend/update.mk +++ b/frontend/update.mk @@ -100,6 +100,24 @@ $(COVERS_BIN): $(COVERS_OBJS) update-all: $(COVERS_BIN) +# rsos-store: the game store helper (docs/store-design.md): signed catalog, verified downloads. +STORE_BIN = $(BUILDDIR)/rsos-store +STORE_OBJS = $(UPD_BUILD)/src/update/rsos-store.o $(UPD_BUILD)/src/update/http.o $(UPD_BUILD)/src/update/json.o \ + $(UPD_BUILD)/src/update/sha256.o $(UPD_BUILD)/src/update/sha1.o $(UPD_BUILD)/src/update/rsu.o \ + $(UPD_BUILD)/third_party/monocypher/monocypher.o $(UPD_BUILD)/third_party/monocypher/monocypher-ed25519.o +# The store catalog URL and the public key of its signing key (a fork sets its own) +RSOS_STORE_URL ?= +RSOS_STORE_PUBKEY ?= $(UPD_DIR)/assets/store.pub + +$(UPD_BUILD)/src/update/rsos-store.o: $(UPD_DIR)/src/update/rsos-store.c + @mkdir -p $(dir $@) + $(CC) $(UPD_CFLAGS) $(if $(RSOS_STORE_URL),-DSTORE_URL='"$(RSOS_STORE_URL)"') -MMD -MP -c -o $@ $< + +$(STORE_BIN): $(STORE_OBJS) + $(CC) $(LDFLAGS) -o $@ $^ $(UPD_TLS_LIBS) $(UPD_ZSTD_LIBS) -lpthread + +update-all: $(STORE_BIN) + $(UPD_TEST): $(UPD_OBJS) $(UPD_BUILD)/src/update/tests/test_update.o $(CC) $(LDFLAGS) -o $@ $^ $(UPD_LIBS) @@ -111,9 +129,10 @@ $(UPD_MKUPDATE): $(UPD_MKUPDATE_SRCS) $(wildcard $(UPD_DIR)/src/update/*.h) mkupdate: $(UPD_MKUPDATE) -check-update: $(UPD_TEST) $(UPD_BIN) $(UPD_MKUPDATE) +check-update: $(UPD_TEST) $(UPD_BIN) $(UPD_MKUPDATE) $(STORE_BIN) $(UPD_TEST) $(abspath $(BUILDDIR))/update-check sh $(UPD_DIR)/src/update/tests/cli_test.sh $(UPD_BIN) $(UPD_MKUPDATE) $(abspath $(BUILDDIR))/update-cli + sh $(UPD_DIR)/src/update/tests/store_test.sh $(STORE_BIN) $(UPD_MKUPDATE) $(abspath $(BUILDDIR))/store-check $(UPD_DIR)/../scripts/store/make-catalog.py # The menu screens (ui/update_ui.c) with the preview tool and a fake helper # (tests/fake-rsos-update.sh): check, notes, install, restart dialog; up to @@ -174,10 +193,12 @@ RSOS_OS_VARIANT ?= dev RSOS_BOARD_ID ?= RSOS_OS_BUILD_TIME ?= $(UPD_BUILD_EPOCH) RSOS_OS_BUILD_DATE ?= $(shell date -u -d @$(RSOS_OS_BUILD_TIME) +%Y-%m-%d 2>/dev/null) -update-install: $(UPD_BIN) $(COVERS_BIN) +update-install: $(UPD_BIN) $(COVERS_BIN) $(STORE_BIN) install -d $(DESTDIR)$(BINDIR) $(DESTDIR)$(DATADIR) $(DESTDIR)$(SYSCONFDIR)/rsos install -m 0755 $(UPD_BIN) $(DESTDIR)$(BINDIR)/rsos-update install -m 0755 $(COVERS_BIN) $(DESTDIR)$(BINDIR)/rsos-covers + install -m 0755 $(STORE_BIN) $(DESTDIR)$(BINDIR)/rsos-store + test ! -f $(RSOS_STORE_PUBKEY) || install -m 0644 $(RSOS_STORE_PUBKEY) $(DESTDIR)$(DATADIR)/store.pub install -m 0644 $(RSOS_UPDATE_PUBKEY) $(DESTDIR)$(DATADIR)/update.pub printf "# Generated by the rsos-frontend package (frontend/update.mk).\nRSOS_VERSION='%s'\nRSOS_VARIANT='%s'\nRSOS_BUILD_TIME='%s'\nRSOS_BUILD_DATE='%s'\nRSOS_BOARD_ID='%s'\n" \ '$(RSOS_OS_VERSION)' '$(RSOS_OS_VARIANT)' '$(RSOS_OS_BUILD_TIME)' '$(RSOS_OS_BUILD_DATE)' \ diff --git a/ports/2ship/.gitattributes b/ports/2ship/.gitattributes new file mode 100644 index 0000000..ec1ffa8 --- /dev/null +++ b/ports/2ship/.gitattributes @@ -0,0 +1 @@ +*.patch -text diff --git a/ports/2ship/2ship.patch b/ports/2ship/2ship.patch new file mode 100644 index 0000000..11fe45c --- /dev/null +++ b/ports/2ship/2ship.patch @@ -0,0 +1,206 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index a9378e8..b31788d 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -123,6 +123,9 @@ elseif(MSVC) + string(REGEX REPLACE "/RTC(su|[1su])" "" CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}") + set(CMAKE_C_FLAGS_RELEASE "/O2 /DNDEBUG") + set(CMAKE_CXX_FLAGS_RELEASE "/O2 /DNDEBUG") ++elseif(USE_GLES2) ++ set(CMAKE_C_FLAGS_RELEASE "-O3 -fno-math-errno -funsafe-math-optimizations -DNDEBUG") ++ set(CMAKE_CXX_FLAGS_RELEASE "-O3 -fno-math-errno -funsafe-math-optimizations -DNDEBUG") + else() + set(CMAKE_C_FLAGS_RELEASE "-O2 -DNDEBUG") + set(CMAKE_CXX_FLAGS_RELEASE "-O2 -DNDEBUG") +diff --git a/mm/2s2h/BenPort.cpp b/mm/2s2h/BenPort.cpp +index 653de66..eee4d60 100644 +--- a/mm/2s2h/BenPort.cpp ++++ b/mm/2s2h/BenPort.cpp +@@ -836,15 +836,20 @@ void OTRAudio_Thread() { + int samples_left = AudioPlayer_Buffered(); + u32 num_audio_samples = samples_left < AudioPlayer_GetDesiredBuffered() ? SAMPLES_HIGH : SAMPLES_LOW; + +- // 3 is the maximum authentic frame divisor. +- s16 audio_buffer[SAMPLES_HIGH * NUM_AUDIO_CHANNELS * 3]; +- for (int i = 0; i < AUDIO_FRAMES_PER_UPDATE; i++) { ++ // 3 is the maximum authentic frame divisor, plus up to 3 frames to catch up (below) ++ int audioFrames = AUDIO_FRAMES_PER_UPDATE; ++ if (samples_left < AudioPlayer_GetDesiredBuffered()) { ++ int extra = (AudioPlayer_GetDesiredBuffered() - samples_left + SAMPLES_HIGH - 1) / SAMPLES_HIGH; ++ audioFrames += extra > 3 ? 3 : extra; ++ } ++ s16 audio_buffer[SAMPLES_HIGH * NUM_AUDIO_CHANNELS * 6]; ++ for (int i = 0; i < audioFrames; i++) { + AudioMgr_CreateNextAudioBuffer(audio_buffer + i * (num_audio_samples * NUM_AUDIO_CHANNELS), + num_audio_samples); + } + + AudioPlayer_Play((u8*)audio_buffer, +- num_audio_samples * (sizeof(int16_t) * NUM_AUDIO_CHANNELS * AUDIO_FRAMES_PER_UPDATE)); ++ num_audio_samples * (sizeof(int16_t) * NUM_AUDIO_CHANNELS * audioFrames)); + + audio.processing = false; + audio.cv_from_thread.notify_one(); +diff --git a/mm/2s2h/mixer.c b/mm/2s2h/mixer.c +index 6364fa5..6cccdb4 100644 +--- a/mm/2s2h/mixer.c ++++ b/mm/2s2h/mixer.c +@@ -18,6 +18,8 @@ + + //#define DMEM_BUF_SIZE (0x1000 - 0x0330 - 0x10 - 0x40) + #define DMEM_BUF_SIZE 0xC80 ++// past the end of DMEM: the largest 16-bit address plus the largest command (mixing: count << 4) ++#define DMEM_GUARD_SIZE 0x110000 + #define BUF_U8(a) (rspa.buf.as_u8 + ((a)-0x0330)) + #define BUF_S16(a) (rspa.buf.as_s16 + ((a)-0x0330) / sizeof(int16_t)) + +@@ -39,8 +41,8 @@ static struct { + int16_t filter[8]; + + union { +- int16_t as_s16[DMEM_BUF_SIZE / sizeof(int16_t)]; +- uint8_t as_u8[DMEM_BUF_SIZE]; ++ int16_t as_s16[(DMEM_BUF_SIZE + DMEM_GUARD_SIZE) / sizeof(int16_t)]; ++ uint8_t as_u8[DMEM_BUF_SIZE + DMEM_GUARD_SIZE]; + } buf; + } rspa; + +@@ -90,8 +92,17 @@ static inline int32_t clamp32(int64_t v) { + return (int32_t)v; + } + ++// a length that ends inside the buffer and its guard (none if negative) ++static int DmemFit(uint16_t addr, int nbytes) { ++ long room = (long)sizeof(rspa.buf) - ((long)addr - 0x0330); ++ if (nbytes <= 0 || room <= 0) { ++ return 0; ++ } ++ return nbytes > room ? (int)room : nbytes; ++} ++ + void aClearBufferImpl(uint16_t addr, int nbytes) { +- nbytes = ROUND_UP_16(nbytes); ++ nbytes = DmemFit(addr, ROUND_UP_16(nbytes)); + memset(BUF_U8(addr), 0, nbytes); + } + +@@ -173,7 +184,7 @@ void aInterleaveImpl(uint16_t dest, uint16_t left, uint16_t right, uint16_t c) { + } + + void aDMEMMoveImpl(uint16_t in_addr, uint16_t out_addr, int nbytes) { +- nbytes = ROUND_UP_16(nbytes); ++ nbytes = DmemFit(in_addr, DmemFit(out_addr, ROUND_UP_16(nbytes))); + memmove(BUF_U8(out_addr), BUF_U8(in_addr), nbytes); + } + +@@ -721,11 +732,11 @@ void aMixImplNEON(uint16_t count, int16_t gain, uint16_t in_addr, uint16_t out_a + int16x8_t outLoVec2 = vcombine_s16(outLoVec, outLoVec); + int16x4_t inLoVec = vget_low_s16(inVec); + int16x8_t inLoVec2 = vcombine_s16(inLoVec, inLoVec); +- int32x4_t outX7fffHiVec = vmull_high_n_s16(outVec, 0x7FFF); +- int32x4_t outX7fffLoVec = vmull_high_n_s16(outLoVec2, 0x7FFF); ++ int32x4_t outX7fffHiVec = vmull_n_s16(vget_high_s16(outVec), 0x7FFF); ++ int32x4_t outX7fffLoVec = vmull_n_s16(vget_high_s16(outLoVec2), 0x7FFF); + +- int32x4_t inGainLoVec = vmull_high_s16(inLoVec2, gainVec); +- int32x4_t inGainHiVec = vmull_high_s16(inVec, gainVec); ++ int32x4_t inGainLoVec = vmull_s16(vget_high_s16(inLoVec2), vget_high_s16(gainVec)); ++ int32x4_t inGainHiVec = vmull_s16(vget_high_s16(inVec), vget_high_s16(gainVec)); + int32x4_t addVecLo = vaddq_s32(outX7fffLoVec, inGainLoVec); + int32x4_t addVecHi = vaddq_s32(outX7fffHiVec, inGainHiVec); + addVecHi = vaddq_s32(addVecHi, x4000Vec); +diff --git a/mm/2s2h/resource/importer/AudioSampleFactory.cpp b/mm/2s2h/resource/importer/AudioSampleFactory.cpp +index 8948a67..a18b98e 100644 +--- a/mm/2s2h/resource/importer/AudioSampleFactory.cpp ++++ b/mm/2s2h/resource/importer/AudioSampleFactory.cpp +@@ -190,6 +190,26 @@ static void OggDecoderWorker(std::shared_ptr audioSample, std: + } + } + ++// the sample's length in samples, for AdpcmLoop.sampleEnd (0x0C) ++static void SetSampleEnd(SOH::AdpcmLoop& loop, uint32_t codec, uint32_t size) { ++ uint32_t samples; ++ switch (codec) { ++ case 0: // CODEC_ADPCM: 16 samples in 9 bytes ++ samples = size / 9 * 16; ++ break; ++ case 3: // CODEC_SMALL_ADPCM: 16 samples in 5 bytes ++ samples = size / 5 * 16; ++ break; ++ case 1: // CODEC_S8 ++ samples = size; ++ break; ++ default: // 16-bit samples ++ samples = size / 2; ++ break; ++ } ++ memcpy(loop.unk_0C, &samples, sizeof(samples)); ++} ++ + namespace SOH { + std::shared_ptr + ResourceFactoryBinaryAudioSampleV2::ReadResource(std::shared_ptr file, +@@ -225,6 +245,7 @@ ResourceFactoryBinaryAudioSampleV2::ReadResource(std::shared_ptr fil + audioSample->loop.state[i] = reader->ReadInt16(); + } + audioSample->sample.loop = &audioSample->loop; ++ SetSampleEnd(audioSample->loop, audioSample->sample.codec, audioSample->sample.size); + + audioSample->book.order = reader->ReadInt32(); + audioSample->book.npredictors = reader->ReadInt32(); +@@ -288,6 +309,7 @@ ResourceFactoryXMLAudioSampleV0::ReadResource(std::shared_ptr file, + audioSample->sample.loop = &audioSample->loop; + size_t size = child->Int64Attribute("Size"); + audioSample->sample.size = size; ++ SetSampleEnd(audioSample->loop, audioSample->sample.codec, audioSample->sample.size); + + const char* path = child->Attribute("Path"); + +diff --git a/mm/assets/custom/shaders/opengl/default.shader.glsl b/mm/assets/custom/shaders/opengl/default.shader.glsl +index 5309260..c204478 100644 +--- a/mm/assets/custom/shaders/opengl/default.shader.glsl ++++ b/mm/assets/custom/shaders/opengl/default.shader.glsl +@@ -134,14 +134,18 @@ + + float random(in vec3 value) { + float random = dot(sin(value), vec3(12.9898, 78.233, 37.719)); ++ @if(gles2) ++ return fract(sin(random) * 43758.5453); ++ @else + return fract(sin(random) * 143758.5453); ++ @end + } + + vec4 fromLinear(vec4 linearRGB){ + bvec3 cutoff = lessThan(linearRGB.rgb, vec3(0.0031308)); + vec3 higher = vec3(1.055)*pow(linearRGB.rgb, vec3(1.0/2.4)) - vec3(0.055); + vec3 lower = linearRGB.rgb * vec3(12.92); +- return vec4(mix(higher, lower, cutoff), linearRGB.a); ++ return vec4(mix(higher, lower, vec3(cutoff)), linearRGB.a); + } + + vec4 filter3point(in sampler2D tex, in vec2 texCoord, in vec2 texSize) { +@@ -187,7 +191,9 @@ + vec4 texVal@{i} = hookTexture2D(@{i}, uTex@{i}, vTexCoordAdj@{i}, texSize@{i}); + + @if(o_masks[i]) +- @if(opengles) ++ @if(gles2) ++ vec2 maskSize@{i} = texSize@{i}; ++ @elseif(opengles) + vec2 maskSize@{i} = vec2(textureSize(uTexMask@{i}, 0)); + @else + vec2 maskSize@{i} = textureSize(uTexMask@{i}, 0); +diff --git a/mm/src/audio/lib/playback.c b/mm/src/audio/lib/playback.c +index a349540..c7526d0 100644 +--- a/mm/src/audio/lib/playback.c ++++ b/mm/src/audio/lib/playback.c +@@ -196,7 +196,7 @@ void AudioPlayback_ProcessNotes(void) { + sampleState = &gAudioCtx.sampleStateList[gAudioCtx.sampleStateOffset + i]; + playbackState = ¬e->playbackState; + if (playbackState->parentLayer != NO_LAYER) { +-#ifndef __WIIU__ ++#if !defined(__WIIU__) && UINTPTR_MAX > 0xFFFFFFFFu // 32-bit pointers are all below 0x7FFFFFFF + // OTRTODO: This skips playback if the pointer is below where memory on the N64 normally would be. + // This does not translate well to modern platforms and how they map memory. + // Considering that this check is not present in OoT/SoH, we may be able to remove this altogether. diff --git a/ports/2ship/Majora's Mask.layout b/ports/2ship/Majora's Mask.layout new file mode 100644 index 0000000..cba43af --- /dev/null +++ b/ports/2ship/Majora's Mask.layout @@ -0,0 +1,8 @@ +# N64 pad layout for this port: which SDL element the game reads for each N64 function, +# so a real N64 pad plays like the built-in buttons do here. Used when an N64 pad is +# plugged in (Settings > Controls); see docs/native-games.md, "Layouts". +# Functions: a b z l r start cup cdown cleft cright dpup dpdown dpleft dpright ("none" drops one). +# Left alone, an N64 pad is: a=a b=b z=lefttrigger l=leftshoulder r=rightshoulder +# (+ a copy of r on the right trigger), C buttons on the right stick, D-pad on the hat. +# Majora's Mask: the built-in R1 is C-right here, so N64 R is the right trigger. +r = righttrigger diff --git a/ports/2ship/Majora's Mask.sh b/ports/2ship/Majora's Mask.sh new file mode 100644 index 0000000..3cd5f3b --- /dev/null +++ b/ports/2ship/Majora's Mask.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# The Legend of Zelda: Majora's Mask (2Ship2Harkinian), built from your own ROM by +# ports/2ship/build-2ship.sh. The game data (mm.o2r, 2ship.o2r), settings and saves stay in 2ship/. +cd 2ship || exit 1 +export SHIP_HOME="$PWD" +# Opus and OpusFile, copied next to the game for a RetroStoneOS without them +export LD_LIBRARY_PATH="$PWD/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" +# The built-in controls as one standard gamepad (rsos-gamepad); SDL then +# ignores the raw button devices. It runs in the +# game's process group: the menu stops it with the game. +if [ -x /usr/bin/rsos-gamepad ]; then + SDL_GAMECONTROLLERCONFIG="$(/usr/bin/rsos-gamepad --print-mapping)" + export SDL_GAMECONTROLLERCONFIG + export SDL_GAMECONTROLLER_IGNORE_DEVICES=0x0001/0x0001 + /usr/bin/rsos-gamepad & + usleep 300000 +fi +# Not through /lib/ld-linux-armhf.so.3 as the other ports can: 2Ship looks for its .o2r files +# next to the program it was started as, which would then be /lib +exec ./2s2h.elf diff --git a/ports/2ship/README.md b/ports/2ship/README.md new file mode 100644 index 0000000..9b10c1e --- /dev/null +++ b/ports/2ship/README.md @@ -0,0 +1,101 @@ +# The Legend of Zelda: Majora's Mask (2Ship2Harkinian) on the RetroStone2 + +[2Ship2Harkinian](https://github.com/HarbourMasters/2ship2harkinian) is the PC port of the Majora's Mask +decompilation, built on HarbourMasters' [libultraship](https://github.com/Kenix3/libultraship), like Ocarina of +Time ([../soh](../soh/README.md)). This folder adds the same OpenGL ES 2.0 mode to 2Ship's libultraship, fixes +2Ship for 32-bit ARM and builds the game for the console as a native game (docs/native-games.md). + +**Nothing from the game is in this repository, the OS images or the updates.** The game's data comes from **your +own ROM** on your PC and stays yours. Tested with the N64 US ROM (SHA-1 `d6133ace5afaa0882cf214cf88daba39e266c078` +in `.z64` order); 2Ship's extractor also takes the decompressed N64 US ROM and the GameCube US one. `.z64`, `.v64` +and `.n64` byte orders are all fine. + +## Build + +2Ship's extractor (ZAPD) runs on the PC and is built with libultraship, so the PC needs libultraship's libraries +too, once: + +```sh +sudo apt install libsdl2-dev libsdl2-net-dev libpng-dev libzip-dev zipcmp zipmerge ziptool libtinyxml2-dev \ + nlohmann-json3-dev libspdlog-dev libgles-dev libegl-dev libogg-dev libvorbis-dev libopusfile-dev libbz2-dev +``` + +Then: + +```sh +ports/2ship/build-2ship.sh ~/"Majora's Mask (U).z64" ~/my-ports +``` + +It fetches 2Ship2Harkinian at a fixed commit into `~/rsos/2ship-work`, applies `2ship.patch` and +`libultraship-gles2.patch`, builds ZAPD for the PC and makes `mm.o2r` from the ROM and `2ship.o2r` (which carries +the patched shaders), builds a static libpng and the game for the console (`USE_GLES2`, the RetroStoneOS cross +compiler), then writes: + +``` +~/my-ports/roms/native/Majora's Mask.sh +~/my-ports/roms/native/2ship/ 2s2h.elf, mm.o2r, 2ship.o2r, gamecontrollerdb.txt, lib/, assets/ +``` + +Copy the `roms` folder onto the SD card's **RETROSTONE** partition; in the menu: **Native games > Majora's +Mask**. Settings and saves stay in `roms/native/2ship/` (`SHIP_HOME`). Hold **Select + Start** for a second to go +back to the menu. + +The console needs a RetroStoneOS with Native games and `rsos-gamepad`. Opus and OpusFile are in the RetroStone2 +configs too; `build-2ship.sh` also copies them into `2ship/lib/` for a RetroStoneOS that doesn't have them. + +## Controls + +`rsos-gamepad` makes the built-in controls one SDL gamepad, by position. By the labels on the console: + +| RetroStone2 | N64 | +|---|---| +| B (bottom) / A (right) | A / B | +| X (top) / Y (left) / R1 | C-down / C-left / C-right | +| L2 / R2 | Z / R | +| L1 | L | +| Start | Start | +| Analog stick (Pro) | the stick | +| D-pad | the D-pad | + +As in Ocarina of Time, the C buttons go on X, Y and R1 (the default with `USE_GLES2`); C-up is free to set in +2Ship's own controller settings. + +## What the patches change + +* **`libultraship-gles2.patch`**: Ship of Harkinian's GLES2 patch ([../soh](../soh/README.md): the OpenGL ES 2.0 + mode, the 32-bit ARM and Mali-400 fixes, the speed work), which applies to 2Ship's libultraship (`7cb1022`) as + it is, plus: + * backported from newer libultraship (`766a6bad`): SIGTERM no longer calls `exit()` inside the signal handler, + whose destructors deadlocked, so quitting from the menu is immediate (as for Mario Kart 64); + * loading a texture that is already bound no longer ends the draw call (as for Mario Kart 64); + * first start: linear texture filtering (one sample instead of three-point's three); + * the crash handler also catches SIGBUS and, on 32-bit ARM, logs the registers and the program's load address. +* **`2ship.patch`**, 2Ship's own code: + * **notes on 32-bit** (an upstream bug, the cause of the broken music): `AudioPlayback_ProcessNotes` skips a + note whose layer pointer is below `0x7FFFFFFF`, a check from the N64, where RAM starts at `0x80000000`. On a + 64-bit PC no heap pointer is that low; on 32-bit ARM every one is, so no playing note got its volume, pitch or + start, and instruments were cut off or missing. The check is now for 64-bit builds only (2Ship already left + it out on the Wii U, its other 32-bit platform); + * **the mixer's DMEM buffer** (an upstream bug, found with AddressSanitizer on the console): some audio commands + clear or move more bytes than the 0xC80-byte buffer holds, which overwrote the memory after it (crashes and a + freeze in the opening cutscene). The buffer has a guard area and those lengths are clamped to it; + * **samples' `sampleEnd`** (an upstream bug): the sample importers never set it, so the synthesizer read + leftover memory for where a sample ends. It is now the sample's length; + * when the game runs below 20 fps, the audio thread makes up to three extra audio frames to refill the buffer, + instead of gaps; + * the GLES2 changes in 2Ship's own copy of the shaders (packed into `2ship.o2r`); + * `mixer.c`'s NEON code uses AArch64-only intrinsics: their ARMv7 equivalents; + * Release builds with `USE_GLES2` use `-O3 -funsafe-math-optimizations` instead of 2Ship's `-O2` on Linux: + GCC uses NEON for float math on 32-bit ARM only with unsafe math. + +The launcher starts `2s2h.elf` directly, never through `/lib/ld-linux-armhf.so.3` as the other ports can: 2Ship +looks for its `.o2r` files next to the program it was started as, which would be `/lib`. + +## Status + +**Works on a RetroStone2 Pro**: title screen, the opening, 3D, music and sound, at the game's own speed (20 fps +in most places). The game's messages are in `rsos/logs/boot/game.log` on the SD card, and 2Ship's own log in +`roms/native/2ship/logs/`. + +`mm.o2r` is not the same byte for byte from one build to the next: ZAPD writes uninitialized memory into fields the +game doesn't use (the vertex count of limbs without skin, the tuning of drums without a sample). diff --git a/ports/2ship/build-2ship.sh b/ports/2ship/build-2ship.sh new file mode 100755 index 0000000..cf70cf7 --- /dev/null +++ b/ports/2ship/build-2ship.sh @@ -0,0 +1,133 @@ +#!/bin/bash +# Builds The Legend of Zelda: Majora's Mask (2Ship2Harkinian) for RetroStoneOS from +# YOUR OWN ROM, on the PC (Linux/WSL), as a native game for the SD card +# (docs/native-games.md). +# +# ports/2ship/build-2ship.sh [output folder] +# +# Needs a built RetroStoneOS tree for the RetroStone2 with SDL2 and the port +# libraries (the RetroStone2 configs): ~/rsos/output, or RSOS_OUTPUT=; cmake, +# ninja, python3, a C++ compiler for the PC and the PC libraries of 2Ship's extractor +# (ZAPD, which runs here and is built with libultraship): see README.md. +# 2Ship2Harkinian is fetched at a fixed commit into ~/rsos/2ship-work +# (RSOS_2SHIP_WORK) and patched (2ship.patch, libultraship-gles2.patch). +# RSOS_HOST_CMAKE_ARGS: extra cmake arguments for the PC build (libraries outside /usr). +# +# The result contains the game's data, taken from your ROM: keep it for +# yourself. Never put it in a release, an update or a repository. +# +# Output (default ./2ship-retrostone2): roms/native/Majora's Mask.sh and +# roms/native/2ship/. Copy the "roms" folder onto the SD card's RETROSTONE +# partition (it merges with the roms folder there). +set -euo pipefail + +REPO=https://github.com/HarbourMasters/2ship2harkinian.git +COMMIT=8a24047fbce8915993804e7819f4df4fa591551f # 5.0.1 + fixes, libultraship 7cb1022 +LIBPNG_REPO=https://github.com/pnggroup/libpng.git +LIBPNG_COMMIT=95ab3fdca83ea294efd3b092e9a53c5a39886444 # v1.6.57 + +here=$(cd "$(dirname "$0")" && pwd) +rom=${1:-} +out=${2:-$PWD/2ship-retrostone2} +O=${RSOS_OUTPUT:-$HOME/rsos/output} +W=${RSOS_2SHIP_WORK:-$HOME/rsos/2ship-work} + +die() { echo "build-2ship: $*" >&2; exit 1; } + +[ -n "$rom" ] || die "usage: $0 [output folder]" +[ -f "$rom" ] || die "$rom: no such file" +rom=$(cd "$(dirname "$rom")" && pwd)/$(basename "$rom") +case "$out" in /*) ;; *) out=$PWD/$out ;; esac +[ -x "$O/host/bin/arm-linux-gcc" ] || die "no cross compiler in $O/host/bin (build RetroStoneOS first)" +# libopus and libopusfile are also copied next to the game, for consoles whose +# RetroStoneOS does not have them yet +LIBS="libSDL2.so libzip.so libtinyxml2.so libspdlog.so libvorbisfile.so libopus.so.0 libopusfile.so.0" +for lib in $LIBS; do + [ -e "$O/staging/usr/lib/$lib" ] || die "$lib is not in $O/staging (build RetroStoneOS with the RetroStone2 configs)" +done +TOOLCHAIN=$O/host/share/buildroot/toolchainfile.cmake + +# only the fixed commit (the whole history is large) +if [ ! -d "$W/.git" ]; then + git init -q "$W" + git -C "$W" remote add origin "$REPO" +fi +cd "$W" +git fetch -q --depth 1 origin "$COMMIT" +# a clean tree at the fixed commit, then our changes (the build folders and the +# ROM are ignored by git and stay) +git checkout -q -f "$COMMIT" +git submodule update -q --init --recursive --force --depth 1 +git -C libultraship checkout -q -f . +git apply "$here/2ship.patch" +git -C libultraship apply "$here/libultraship-gles2.patch" + +# the ROM, in .z64 byte order, in OTRExporter/ (where the extractor looks for it) +rm -f OTRExporter/*.z64 +python3 - "$rom" OTRExporter/baserom.z64 << 'EOF' || die "$rom is not an N64 ROM" +import sys +data = bytearray(open(sys.argv[1], 'rb').read()) +head = bytes(data[:4]) +if head == b'\x37\x80\x40\x12': # .v64: 16-bit words swapped + data[0::2], data[1::2] = data[1::2], data[0::2] +elif head == b'\x40\x12\x37\x80': # .n64: 32-bit words reversed + for i in range(0, len(data) - 3, 4): + data[i:i + 4] = data[i:i + 4][::-1] +elif head != b'\x80\x37\x12\x40': + sys.exit(1) +open(sys.argv[2], 'wb').write(data) +EOF + +# ZAPD for this PC: mm.o2r from the ROM, and 2ship.o2r, which carries the (patched) shaders. +# 2Ship has no tools-only build: this configures the whole game for the PC, and builds ZAPD only. +rm -f mm/mm.o2r mm/2ship.o2r mm.o2r 2ship.o2r +# shellcheck disable=SC2086 +cmake -S . -B build-tools -G Ninja -DCMAKE_BUILD_TYPE=Release -DUSE_OPENGLES=ON -DUSE_GLES2=ON \ + -DNON_PORTABLE=OFF ${RSOS_HOST_CMAKE_ARGS:-} +cmake --build build-tools --target ExtractAssets || + die "the extraction failed: is $rom Majora's Mask (US), N64 or GameCube?" +[ -f build-tools/mm/mm.o2r ] && [ -f build-tools/mm/2ship.o2r ] || + die "no mm.o2r: $rom is not a Majora's Mask ROM that 2Ship2Harkinian supports" + +# The game links ZAPD's library (its own extractor), which needs libpng. RetroStoneOS has +# none: a static one, built with the console's compiler from libpng's repository. +P=$W-libpng +if [ ! -f "$P/arm/lib/libpng16.a" ]; then + rm -rf "$P" + git init -q "$P/src" + git -C "$P/src" fetch -q --depth 1 "$LIBPNG_REPO" "$LIBPNG_COMMIT" + git -C "$P/src" checkout -q FETCH_HEAD + cmake -S "$P/src" -B "$P/build" -G Ninja -DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN" \ + -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_BUILD_TYPE=Release -DCMAKE_POSITION_INDEPENDENT_CODE=ON \ + -DPNG_SHARED=OFF -DPNG_STATIC=ON -DPNG_TESTS=OFF -DPNG_TOOLS=OFF -DPNG_FRAMEWORK=OFF \ + -DCMAKE_INSTALL_PREFIX="$P/arm" + cmake --build "$P/build" --target install +fi + +# the game for the console. CMAKE_SYSTEM_NAME Linux: Buildroot's toolchain file names +# it "Buildroot", which skips the Linux parts of 2Ship and libultraship. The release +# flags (-O3, unsafe math for NEON) are in 2ship.patch: 2Ship sets its own on Linux. +cmake -S . -B build-gles2 -G Ninja -DCMAKE_BUILD_TYPE=Release -DUSE_OPENGLES=ON -DUSE_GLES2=ON \ + -DNON_PORTABLE=OFF -DPNG_LIBRARY="$P/arm/lib/libpng16.a" -DPNG_PNG_INCLUDE_DIR="$P/arm/include" \ + -DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN" -DCMAKE_SYSTEM_NAME=Linux +cmake --build build-gles2 --target 2ship + +file build-gles2/mm/2s2h.elf | grep -q 'ARM' || die "build-gles2/mm/2s2h.elf is not an ARM program" +S=$out/roms/native/2ship +mkdir -p "$S/lib" "$S/assets" +"$O/host/bin/arm-linux-strip" -o "$S/2s2h.elf" build-gles2/mm/2s2h.elf +cp build-tools/mm/mm.o2r build-tools/mm/2ship.o2r "$S/" +[ -f build-gles2/gamecontrollerdb.txt ] && cp build-gles2/gamecontrollerdb.txt "$S/" +for lib in libopus.so.0 libopusfile.so.0; do + cp -L "$O/staging/usr/lib/$lib" "$S/lib/" + "$O/host/bin/arm-linux-strip" "$S/lib/$lib" +done +# 2Ship quits at start without an assets/ folder next to the program; it reads it only to +# make mm.o2r on the console, which this script does on the PC instead +printf '2Ship2Harkinian checks that this folder exists. mm.o2r is made on the PC\n(ports/2ship/build-2ship.sh), so the extraction files are not needed here.\n' \ + > "$S/assets/README.txt" +install -m 0644 "$here/Majora's Mask.sh" "$out/roms/native/Majora's Mask.sh" +echo +echo "Done: $out/roms" +echo "Copy that \"roms\" folder onto the SD card's RETROSTONE partition, then in the menu:" +echo "Native games > Majora's Mask. Hold Select + Start to quit." diff --git a/ports/2ship/libultraship-gles2.patch b/ports/2ship/libultraship-gles2.patch new file mode 100644 index 0000000..cf432c2 --- /dev/null +++ b/ports/2ship/libultraship-gles2.patch @@ -0,0 +1,892 @@ +diff --git a/cmake/dependencies/linux.cmake b/cmake/dependencies/linux.cmake +index 02301f1..8e231e1 100644 +--- a/cmake/dependencies/linux.cmake ++++ b/cmake/dependencies/linux.cmake +@@ -2,7 +2,10 @@ + find_package(SDL2 REQUIRED) + target_link_libraries(ImGui PUBLIC SDL2::SDL2) + +-if (USE_OPENGLES) ++if (USE_GLES2) ++ target_link_libraries(ImGui PUBLIC GLESv2) ++ add_compile_definitions(IMGUI_IMPL_OPENGL_ES2) ++elseif (USE_OPENGLES) + target_link_libraries(ImGui PUBLIC ${OPENGL_GLESv2_LIBRARY}) + add_compile_definitions(IMGUI_IMPL_OPENGL_ES3) + else() +diff --git a/include/fast/backends/gfx_opengl.h b/include/fast/backends/gfx_opengl.h +index af24c70..efdf5c5 100644 +--- a/include/fast/backends/gfx_opengl.h ++++ b/include/fast/backends/gfx_opengl.h +@@ -16,6 +16,10 @@ + #elif __APPLE__ + #include + #include ++#elif defined(USE_GLES2) ++#include ++#include ++#include + #elif USE_OPENGLES + #include + #include +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index 45989b6..0209da4 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -11,6 +11,11 @@ find_package(Python3 REQUIRED COMPONENTS Interpreter) + + set(INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../include) + option(USE_OPENGLES "Enable GLES3" OFF) ++# OpenGL ES 2.0 (Mali-400 and other GLES2-only GPUs); implies USE_OPENGLES ++option(USE_GLES2 "Enable GLES2" OFF) ++if (USE_GLES2) ++ set(USE_OPENGLES ON) ++endif() + option(GFX_DEBUG_DISASSEMBLER "Enable libgfxd" OFF) + + if (CMAKE_SYSTEM_NAME STREQUAL "Windows") +@@ -208,6 +213,7 @@ else() + $<$>:NDEBUG> + SPDLOG_ACTIVE_LEVEL=${SPDLOG_MIN_CUTOFF} + $<$:USE_OPENGLES> ++ $<$:USE_GLES2> + $<$:GFX_DEBUG_DISASSEMBLER> + ) + endif() +diff --git a/src/fast/Fast3dGui.cpp b/src/fast/Fast3dGui.cpp +index 237a502..8c939c0 100644 +--- a/src/fast/Fast3dGui.cpp ++++ b/src/fast/Fast3dGui.cpp +@@ -146,6 +146,8 @@ void Fast3dGui::ImGuiBackendInit() { + case WindowBackend::FAST3D_SDL_OPENGL: + #ifdef __APPLE__ + ImGui_ImplOpenGL3_Init("#version 410 core"); ++#elif defined(USE_GLES2) ++ ImGui_ImplOpenGL3_Init("#version 100"); + #elif USE_OPENGLES + ImGui_ImplOpenGL3_Init("#version 300 es"); + #else +diff --git a/src/fast/Fast3dWindow.cpp b/src/fast/Fast3dWindow.cpp +index 2b77a5f..6b0380f 100644 +--- a/src/fast/Fast3dWindow.cpp ++++ b/src/fast/Fast3dWindow.cpp +@@ -109,6 +109,12 @@ void Fast3dWindow::Init() { + mWindowManagerApi->SetKeyboardCallbacks(KeyDown, KeyUp, AllKeysUp); + mWindowManagerApi->SetMouseCallbacks(MouseButtonDown, MouseButtonUp); + ++#ifdef USE_GLES2 ++ if (Ship::Context::GetRawInstance()->GetConsoleVariables()->Get(CVAR_TEXTURE_FILTER) == nullptr) { ++ Ship::Context::GetRawInstance()->GetConsoleVariables()->SetInteger(CVAR_TEXTURE_FILTER, FILTER_LINEAR); ++ Ship::Context::GetRawInstance()->GetConsoleVariables()->Save(); ++ } ++#endif + SetTextureFilter((FilteringMode)Ship::Context::GetRawInstance()->GetConsoleVariables()->GetInteger( + CVAR_TEXTURE_FILTER, FILTER_THREE_POINT)); + } +diff --git a/src/fast/backends/gfx_opengl.cpp b/src/fast/backends/gfx_opengl.cpp +index ad9b1dd..2f6e080 100644 +--- a/src/fast/backends/gfx_opengl.cpp ++++ b/src/fast/backends/gfx_opengl.cpp +@@ -27,6 +27,52 @@ + #include "fast/interpreter.h" + #include "ship/config/ConsoleVariable.h" + ++// a texture was bound outside SelectTexture(): its cache no longer says what is bound ++#define FORGET_TEXTURE_BINDINGS() do { mLastActiveTexture = -1; for (GLuint& bound : mLastBoundTextures) bound = (GLuint)-1; } while (0) ++ ++#include ++ ++#ifdef USE_GLES2 ++/* ++ * OpenGL ES 2.0: no sized texture formats, no multisampling, no blits and no ++ * depth reads. Multisampling stays off (mMaxMsaaLevel 1), so the multisample ++ * calls below are never reached; CopyFramebuffer and GetPixelDepth have their ++ * own GLES2 versions. Depth: packed depth+stencil when the driver has ++ * GL_OES_packed_depth_stencil, else a 16-bit depth buffer. ++ */ ++#define GL_RGB8 GL_RGB ++#define GL_RGBA8 GL_RGBA ++#define GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8_OES ++#define GL_DEPTH_STENCIL GL_DEPTH_STENCIL_OES ++#define GL_UNSIGNED_INT_24_8 GL_UNSIGNED_INT_24_8_OES ++#define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER ++#define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER ++#define glBlitFramebuffer(...) ((void)0) ++#define glReadBuffer(b) ((void)0) ++#define glRenderbufferStorageMultisample(target, samples, format, w, h) glRenderbufferStorage(target, format, w, h) ++static bool sPackedDepthStencil = true; ++#endif ++ ++namespace Fast { ++static void RenderbufferDepthStorage(GLsizei width, GLsizei height) { ++#ifdef USE_GLES2 ++ glRenderbufferStorage(GL_RENDERBUFFER, sPackedDepthStencil ? GL_DEPTH24_STENCIL8_OES : GL_DEPTH_COMPONENT16, ++ width, height); ++#else ++ glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); ++#endif ++} ++ ++static void FramebufferDepthAttach(GLuint rb) { ++#ifdef USE_GLES2 ++ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb); ++ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, sPackedDepthStencil ? rb : 0); ++#else ++ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb); ++#endif ++} ++} // namespace Fast ++ + namespace Fast { + int GfxRenderingAPIOGL::GetMaxTextureSize() { + GLint max_texture_size; +@@ -42,7 +88,17 @@ GfxClipParameters GfxRenderingAPIOGL::GetClipParameters() { + return { false, mFrameBuffers[mCurrentFrameBuffer].invertY }; + } + +-static void VertexArraySetAttribs(ShaderProgram* prg) { ++#ifdef USE_GLES2 ++static ShaderProgram* sClientArrayProgram; ++static const float* sClientArrayBase; ++#endif ++ ++static void VertexArraySetAttribs(ShaderProgram* prg, const float* clientArray = nullptr) { ++#ifdef USE_GLES2 ++ if (clientArray == nullptr) { ++ sClientArrayProgram = nullptr; // set for a buffer object: the next draw sets them again ++ } ++#endif + size_t numFloats = prg->numFloats; + size_t pos = 0; + +@@ -50,7 +106,9 @@ static void VertexArraySetAttribs(ShaderProgram* prg) { + if (prg->attribLocations[i] >= 0) { + glEnableVertexAttribArray(prg->attribLocations[i]); + glVertexAttribPointer(prg->attribLocations[i], prg->attribSizes[i], GL_FLOAT, GL_FALSE, +- numFloats * sizeof(float), (void*)(pos * sizeof(float))); ++ numFloats * sizeof(float), ++ clientArray != nullptr ? (const void*)(clientArray + pos) ++ : (const void*)(pos * sizeof(float))); + } + pos += prg->attribSizes[i]; + } +@@ -285,13 +343,23 @@ std::string GfxRenderingAPIOGL::BuildFsShader(const CCFeatures& cc_features) { + { "attr", "in" }, + { "opengles", false }, + { "core_opengl", true }, ++ { "gles2", false }, + { "texture", "texture" }, + { "vOutColor", "vOutColor" }, ++#elif defined(USE_GLES2) ++ { "GLSL_VERSION", "#version 100\nprecision mediump float;" }, ++ { "attr", "varying" }, ++ { "opengles", false }, ++ { "core_opengl", false }, ++ { "gles2", true }, ++ { "texture", "texture2D" }, ++ { "vOutColor", "gl_FragColor" }, + #elif defined(USE_OPENGLES) + { "GLSL_VERSION", "#version 300 es\nprecision mediump float;" }, + { "attr", "in" }, + { "opengles", true }, + { "core_opengl", false }, ++ { "gles2", false }, + { "texture", "texture" }, + { "vOutColor", "vOutColor" }, + #else +@@ -299,6 +367,7 @@ std::string GfxRenderingAPIOGL::BuildFsShader(const CCFeatures& cc_features) { + { "attr", "varying" }, + { "opengles", false }, + { "core_opengl", false }, ++ { "gles2", false }, + { "texture", "texture2D" }, + { "vOutColor", "gl_FragColor" }, + #endif +@@ -356,6 +425,11 @@ static std::string BuildVsShader(const CCFeatures& cc_features) { + { "attr", "in" }, + { "out", "out" }, + { "opengles", false } ++#elif defined(USE_GLES2) ++ { "GLSL_VERSION", "#version 100" }, ++ { "attr", "attribute" }, ++ { "out", "varying" }, ++ { "opengles", false } + #elif defined(USE_OPENGLES) + { "GLSL_VERSION", "#version 300 es" }, + { "attr", "in" }, +@@ -420,9 +494,8 @@ ShaderProgram* GfxRenderingAPIOGL::CreateAndLoadNewShader(uint64_t shader_id0, u + GLint max_length = 0; + glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &max_length); + char error_log[1024]; +- // fprintf(stderr, "Vertex shader compilation failed\n"); +- glGetShaderInfoLog(vertex_shader, max_length, &max_length, &error_log[0]); +- // fprintf(stderr, "%s\n", &error_log[0]); ++ glGetShaderInfoLog(vertex_shader, sizeof(error_log), nullptr, error_log); ++ fprintf(stderr, "Vertex shader compilation failed:\n%s\n%s\n", error_log, vs_buf.c_str()); + abort(); + } + +@@ -434,9 +507,8 @@ ShaderProgram* GfxRenderingAPIOGL::CreateAndLoadNewShader(uint64_t shader_id0, u + GLint max_length = 0; + glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &max_length); + char error_log[1024]; +- fprintf(stderr, "Fragment shader compilation failed\n"); +- glGetShaderInfoLog(fragment_shader, max_length, &max_length, &error_log[0]); +- fprintf(stderr, "%s\n", &error_log[0]); ++ glGetShaderInfoLog(fragment_shader, sizeof(error_log), nullptr, error_log); ++ fprintf(stderr, "Fragment shader compilation failed:\n%s\n%s\n", error_log, fs_buf.c_str()); + abort(); + } + +@@ -559,6 +631,7 @@ GLuint GfxRenderingAPIOGL::NewTexture() { + + void GfxRenderingAPIOGL::DeleteTexture(uint32_t texID) { + glDeleteTextures(1, &texID); ++ FORGET_TEXTURE_BINDINGS(); // deleting unbinds it, and the name comes back with the next texture + } + + void GfxRenderingAPIOGL::SelectTexture(int tile, GLuint texture_id) { +@@ -583,7 +656,9 @@ void GfxRenderingAPIOGL::UploadTexture(const uint8_t* rgba32_buf, uint32_t width + textures[mCurrentTextureIds[mCurrentTile]].height = height; + } + +-#ifdef USE_OPENGLES ++#ifdef USE_GLES2 ++#define GL_MIRROR_CLAMP_TO_EDGE GL_MIRRORED_REPEAT ++#elif defined(USE_OPENGLES) + #define GL_MIRROR_CLAMP_TO_EDGE 0x8743 + #endif + +@@ -703,7 +778,17 @@ void GfxRenderingAPIOGL::DrawTriangles(float buf_vbo[], size_t buf_vbo_len, size + SetPerDrawUniforms(); + + // printf("flushing %d tris\n", buf_vbo_num_tris); ++#ifdef USE_GLES2 ++ // the pointers stay valid until the program changes or ImGui draws (after the frame) ++ if (mCurrentShaderProgram != sClientArrayProgram || buf_vbo != sClientArrayBase) { ++ glBindBuffer(GL_ARRAY_BUFFER, 0); ++ VertexArraySetAttribs(mCurrentShaderProgram, buf_vbo); ++ sClientArrayProgram = mCurrentShaderProgram; ++ sClientArrayBase = buf_vbo; ++ } ++#else + glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buf_vbo_len, buf_vbo, GL_STREAM_DRAW); ++#endif + glDrawArrays(GL_TRIANGLES, 0, 3 * buf_vbo_num_tris); + } + +@@ -715,7 +800,16 @@ void GfxRenderingAPIOGL::Init() { + glGenBuffers(1, &mOpenglVbo); + glBindBuffer(GL_ARRAY_BUFFER, mOpenglVbo); + +-#if defined(__APPLE__) || defined(USE_OPENGLES) ++#ifdef USE_GLES2 ++ { ++ const char* ext = (const char*)glGetString(GL_EXTENSIONS); ++ ++ sPackedDepthStencil = ext != nullptr && strstr(ext, "GL_OES_packed_depth_stencil") != nullptr; ++ SPDLOG_INFO("OpenGL ES 2.0: {} ({}), depth buffer {}", (const char*)glGetString(GL_RENDERER), ++ (const char*)glGetString(GL_VERSION), sPackedDepthStencil ? "24-bit + stencil" : "16-bit"); ++ } ++#endif ++#if defined(__APPLE__) || (defined(USE_OPENGLES) && !defined(USE_GLES2)) + glGenVertexArrays(1, &mOpenglVao); + glBindVertexArray(mOpenglVao); + #endif +@@ -730,17 +824,21 @@ void GfxRenderingAPIOGL::Init() { + + glGenRenderbuffers(1, &mPixelDepthRb); + glBindRenderbuffer(GL_RENDERBUFFER, mPixelDepthRb); +- glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 1, 1); ++ RenderbufferDepthStorage(1, 1); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + + glGenFramebuffers(1, &mPixelDepthFb); + glBindFramebuffer(GL_FRAMEBUFFER, mPixelDepthFb); +- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mPixelDepthRb); ++ FramebufferDepthAttach(mPixelDepthRb); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + + mPixelDepthRbSize = 1; + ++#ifdef USE_GLES2 ++ mMaxMsaaLevel = 1; ++#else + glGetIntegerv(GL_MAX_SAMPLES, &mMaxMsaaLevel); ++#endif + } + + void GfxRenderingAPIOGL::OnResize() { +@@ -748,6 +846,9 @@ void GfxRenderingAPIOGL::OnResize() { + + void GfxRenderingAPIOGL::StartFrame() { + mFrameCount++; ++#ifdef USE_GLES2 ++ sClientArrayProgram = nullptr; // ImGui drew with its own arrays ++#endif + } + + void GfxRenderingAPIOGL::EndFrame() { +@@ -764,7 +865,12 @@ int GfxRenderingAPIOGL::CreateFramebuffer() { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); ++#ifdef USE_GLES2 ++ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); ++ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); ++#endif + glBindTexture(GL_TEXTURE_2D, 0); ++ FORGET_TEXTURE_BINDINGS(); + + GLuint clrbufMsaa; + glGenRenderbuffers(1, &clrbufMsaa); +@@ -772,7 +878,7 @@ int GfxRenderingAPIOGL::CreateFramebuffer() { + GLuint rbo; + glGenRenderbuffers(1, &rbo); + glBindRenderbuffer(GL_RENDERBUFFER, rbo); +- glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 1, 1); ++ RenderbufferDepthStorage(1, 1); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + + GLuint fbo; +@@ -806,6 +912,7 @@ void GfxRenderingAPIOGL::UpdateFramebufferParameters(int fb_id, uint32_t width, + glBindTexture(GL_TEXTURE_2D, fb.clrbuf); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); + glBindTexture(GL_TEXTURE_2D, 0); ++ FORGET_TEXTURE_BINDINGS(); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb.clrbuf, 0); + } else { + glBindRenderbuffer(GL_RENDERBUFFER, fb.clrbufMsaa); +@@ -819,7 +926,7 @@ void GfxRenderingAPIOGL::UpdateFramebufferParameters(int fb_id, uint32_t width, + (fb.width != width || fb.height != height || fb.msaa_level != msaa_level || !fb.has_depth_buffer)) { + glBindRenderbuffer(GL_RENDERBUFFER, fb.rbo); + if (msaa_level <= 1) { +- glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); ++ RenderbufferDepthStorage(width, height); + } else { + glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa_level, GL_DEPTH24_STENCIL8, width, height); + } +@@ -827,9 +934,9 @@ void GfxRenderingAPIOGL::UpdateFramebufferParameters(int fb_id, uint32_t width, + } + + if (!fb.has_depth_buffer && has_depth_buffer) { +- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fb.rbo); ++ FramebufferDepthAttach(fb.rbo); + } else if (fb.has_depth_buffer && !has_depth_buffer) { +- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0); ++ FramebufferDepthAttach(0); + } + } + +@@ -932,6 +1039,35 @@ void GfxRenderingAPIOGL::CopyFramebuffer(int fb_dst_id, int fb_src_id, int srcX0 + FramebufferOGL src = mFrameBuffers[fb_src_id]; + const FramebufferOGL& dst = mFrameBuffers[fb_dst_id]; + ++#ifdef USE_GLES2 ++ // No blits: copy into the destination's colour texture, unscaled and in the ++ // same orientation only (G_COPYFB effects; Starship does not use them). ++ if (fb_dst_id == 0 || srcX1 - srcX0 != dstX1 - dstX0 || srcY1 - srcY0 != dstY1 - dstY0 || ++ src.invertY != dst.invertY) { ++ static bool warned; ++ if (!warned) { ++ SPDLOG_WARN("GLES2: scaled, flipped or on-screen framebuffer copies are not supported"); ++ warned = true; ++ } ++ return; ++ } ++ // OpenGL's origin is the bottom left, as in the blit path below ++ if (!src.invertY) { ++ int h = srcY1 - srcY0; ++ srcY1 = src.height - srcY0; ++ srcY0 = srcY1 - h; ++ } ++ glDisable(GL_SCISSOR_TEST); ++ glBindFramebuffer(GL_FRAMEBUFFER, src.fbo); ++ glActiveTexture(GL_TEXTURE0); ++ glBindTexture(GL_TEXTURE_2D, dst.clrbuf); ++ glCopyTexSubImage2D(GL_TEXTURE_2D, 0, dstX0, dstY0, srcX0, srcY0, srcX1 - srcX0, srcY1 - srcY0); ++ glBindFramebuffer(GL_FRAMEBUFFER, mFrameBuffers[mCurrentFrameBuffer].fbo); ++ glEnable(GL_SCISSOR_TEST); ++ FORGET_TEXTURE_BINDINGS(); ++ return; ++#endif ++ + // Adjust y values for non-inverted source frame buffers because opengl uses bottom left for origin + if (!src.invertY) { + int temp = srcY1 - srcY0; +@@ -1024,6 +1160,14 @@ std::unordered_map, uint16_t, hash_pair_ff> + GfxRenderingAPIOGL::GetPixelDepth(int fb_id, const std::set>& coordinates) { + std::unordered_map, uint16_t, hash_pair_ff> res; + ++#ifdef USE_GLES2 ++ // GLES2 cannot read the depth buffer: every point is reported at the far plane ++ for (const auto& coord : coordinates) { ++ res.emplace(coord, 0xFFFC); ++ } ++ return res; ++#endif ++ + FramebufferOGL& fb = mFrameBuffers[fb_id]; + + // When looking up one value and the framebuffer is single-sampled, we can read pixels directly +@@ -1045,8 +1189,8 @@ GfxRenderingAPIOGL::GetPixelDepth(int fb_id, const std::set + #ifndef _WIN32 + #include ++#include ++#include + #endif + + #include +@@ -134,6 +136,46 @@ void GfxSetInstance(std::shared_ptr gfx) { + // N64 prim_depth is 15-bit (0 near, 0x7FFF far). + static constexpr float N64_PRIM_DEPTH_MAX = 32767.0f; + ++// Alternate ("alt/") assets are unloaded and loaded again as new objects; with any in the ++// archives, nothing is kept (decided once: archives are added at start only) ++static bool NoAltAssetFiles() { ++ static const bool none = ++ Ship::Context::GetRawInstance()->GetResourceManager()->GetArchiveManager()->ListFiles("alt/*")->empty(); ++ return none; ++} ++ ++static std::unordered_map> sHashResourceCache; ++ ++// texture paths named by pointer: kept per pointer, checked against a copy of the path ++struct ResolvedPath { ++ std::string path; ++ std::shared_ptr res; ++}; ++static std::unordered_map sPathResourceCache; ++ ++static std::shared_ptr CachedResourceByHash(uint64_t hash) { ++ if (!NoAltAssetFiles()) { ++ return Ship::Context::GetRawInstance()->GetResourceManager()->LoadResource(hash); ++ } ++ auto it = sHashResourceCache.find(hash); ++ if (it != sHashResourceCache.end()) { ++ return it->second; ++ } ++ auto res = Ship::Context::GetRawInstance()->GetResourceManager()->LoadResource(hash); ++ if (res != nullptr) { ++ if (sHashResourceCache.size() >= 4096) { ++ sHashResourceCache.clear(); ++ } ++ sHashResourceCache.emplace(hash, res); ++ } ++ return res; ++} ++ ++static void* CachedResourceRawPointer(uint64_t hash) { ++ auto res = CachedResourceByHash(hash); ++ return res != nullptr ? res->GetRawPointer() : nullptr; ++} ++ + void Interpreter::Flush() { + if (mBufVboLen > 0) { + mRapi->SetCurrentPrimDepth((float)mRdp->prim_depth / N64_PRIM_DEPTH_MAX); +@@ -458,7 +500,21 @@ std::shared_ptr Interpreter::ResolveResourceCached(const char* + return nullptr; + } + if (!mResolvedResourceCacheEnabled) { +- return Ship::Context::GetRawInstance()->GetResourceManager()->LoadResourceProcess(path); ++ if (!NoAltAssetFiles()) { ++ return Ship::Context::GetRawInstance()->GetResourceManager()->LoadResourceProcess(path); ++ } ++ auto found = sPathResourceCache.find(path); ++ if (found != sPathResourceCache.end() && found->second.path == path) { ++ return found->second.res; ++ } ++ auto res = Ship::Context::GetRawInstance()->GetResourceManager()->LoadResourceProcess(path); ++ if (res != nullptr) { ++ if (sPathResourceCache.size() >= 4096) { ++ sPathResourceCache.clear(); ++ } ++ sPathResourceCache[path] = { path, res }; ++ } ++ return res; + } + auto it = mResolvedResourceCache.find(path); + if (it != mResolvedResourceCache.end()) { +@@ -481,6 +537,8 @@ void Interpreter::TextureCacheClear() { + mTextureCache.map.clear(); + mTextureCache.lru.clear(); + mResolvedResourceCache.clear(); ++ sHashResourceCache.clear(); ++ sPathResourceCache.clear(); + // Pre-allocate buckets so the map never rehashes during normal operation. + // Rehashing invalidates all iterators, including those stored in LRU entries. + mTextureCache.map.reserve(TEXTURE_CACHE_MAX_SIZE); +@@ -1275,6 +1333,7 @@ void Interpreter::ImportTexture(int i, int tile, bool importReplacement) { + if (fbIt != mFbTextures.end()) { + Flush(); + mRapi->SelectTextureFb(fbIt->second); ++ mRenderingState.mTextures[i] = nullptr; + mRdp->textures_changed[i] = false; + return; + } +@@ -1318,6 +1377,15 @@ void Interpreter::ImportTexture(int i, int tile, bool importReplacement) { + key = { origAddr, {}, fmt, siz, paletteIndex, origSizeBytes }; + } + ++ // The texture already bound to this slot: the triangles so far can keep going (selected ++ // again in case the backend lost its bindings) ++ if (!importReplacement && mRenderingState.mTextures[i] != nullptr && ++ mRenderingState.mTextures[i]->first == key) { ++ mRapi->SelectTexture(i, mRenderingState.mTextures[i]->second.texture_id); ++ return; ++ } ++ Flush(); ++ + if (TextureCacheLookup(i, key)) { + return; + } +@@ -1919,9 +1987,11 @@ void Interpreter::GfxSpTri1(uint8_t vtx1_idx, uint8_t vtx2_idx, uint8_t vtx3_idx + if (use_grayscale) { + cc_options |= SHADER_OPT(GRAYSCALE); + } ++#ifndef USE_GLES2 + if (use_prim_depth) { + cc_options |= SHADER_OPT(PRIM_DEPTH); + } ++#endif + + if (!mShaderStack.empty()) { + cc_options |= (mShaderStack.top() << SHADER_ID_SHIFT); +@@ -1949,8 +2019,9 @@ void Interpreter::GfxSpTri1(uint8_t vtx1_idx, uint8_t vtx2_idx, uint8_t vtx3_idx + ColorCombiner* comb = LookupOrCreateColorCombiner(key); + + uint32_t tm = 0; +- uint32_t tex_width[2], tex_height[2], tex_width2[2], tex_height2[2]; +- uint32_t effective_tile[2]; ++ uint32_t tex_width[2] = { 1, 1 }, tex_height[2] = { 1, 1 }, tex_width2[2] = { 1, 1 }, ++ tex_height2[2] = { 1, 1 }; ++ uint32_t effective_tile[2] = { mRdp->first_tile_index, mRdp->first_tile_index }; + + for (int i = 0; i < 2; i++) { + uint32_t tile = mRdp->first_tile_index + i; +@@ -1963,12 +2034,13 @@ void Interpreter::GfxSpTri1(uint8_t vtx1_idx, uint8_t vtx2_idx, uint8_t vtx3_idx + + if (comb->usedTextures[i]) { + if (mRdp->textures_changed[i]) { +- Flush(); +- ImportTexture(i, tile, false); ++ ImportTexture(i, tile, false); // flushes if the texture changes + if (mRdp->loaded_texture[i].masked) { ++ Flush(); + ImportTextureMask(SHADER_FIRST_MASK_TEXTURE + i, tile); + } + if (mRdp->loaded_texture[i].blended) { ++ Flush(); + ImportTexture(SHADER_FIRST_REPLACEMENT_TEXTURE + i, tile, true); + } + mRdp->textures_changed[i] = false; +@@ -2077,6 +2149,15 @@ void Interpreter::GfxSpTri1(uint8_t vtx1_idx, uint8_t vtx2_idx, uint8_t vtx3_idx + } + } + ++ for (int i = 0; i < 2; i++) { ++ if (!comb->usedTextures[i] && comb->usedTextures[i ^ 1]) { ++ tex_width[i] = tex_width[i ^ 1]; ++ tex_height[i] = tex_height[i ^ 1]; ++ tex_width2[i] = tex_width2[i ^ 1]; ++ tex_height2[i] = tex_height2[i ^ 1]; ++ } ++ } ++ + struct ShaderProgram* prg = comb->prg[tm]; + if (prg == NULL) { + comb->prg[tm] = prg = +@@ -2102,6 +2183,11 @@ void Interpreter::GfxSpTri1(uint8_t vtx1_idx, uint8_t vtx2_idx, uint8_t vtx3_idx + + for (int i = 0; i < 3; i++) { + float z = v_arr[i]->z, w = v_arr[i]->w; ++#ifdef USE_GLES2 ++ if (use_prim_depth) { ++ z = ((float)mRdp->prim_depth / N64_PRIM_DEPTH_MAX * 2.0f - 1.0f) * w; ++ } ++#endif + if (clip_parameters.z_is_from_0_to_1) { + z = (z + w) / 2.0f; + } +@@ -3418,7 +3504,7 @@ bool gfx_mtx_otr_handler_custom_f3dex2(F3DGfx** cmd0) { + + const uint64_t hash = ((uint64_t)cmd->words.w0 << 32) + cmd->words.w1; + const int32_t* mtx = +- (const int32_t*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ (const int32_t*)CachedResourceRawPointer(hash); + + if (mtx != NULL) { + Interpreter* gfx = mInstance.lock().get(); +@@ -3437,7 +3523,7 @@ bool gfx_mtx_otr_handler_custom_f3d(F3DGfx** cmd0) { + + const uint64_t hash = ((uint64_t)cmd->words.w0 << 32) + cmd->words.w1; + const int32_t* mtx = +- (const int32_t*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ (const int32_t*)CachedResourceRawPointer(hash); + if (mtx != nullptr) { + cmd--; + gfx->GfxSpMatrix(C0(16, 8), mtx); +@@ -3504,10 +3590,10 @@ bool gfx_movemem_handler_otr(F3DGfx** cmd0) { + + if (ucode_handler_index == ucode_f3dex2) { + gfx->GfxSpMovememF3dex2(index, offset, +- Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash)); ++ CachedResourceRawPointer(hash)); + } else { + auto light = +- (Fast::LightEntry*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ (Fast::LightEntry*)CachedResourceRawPointer(hash); + uintptr_t data = (uintptr_t)&light->Ambient; + gfx->GfxSpMovememF3d(index, offset, (void*)(data + (hasOffset == 1 ? 0x8 : 0))); + } +@@ -3646,7 +3732,7 @@ bool gfx_vtx_hash_handler_custom(F3DGfx** cmd0) { + gfx->GfxSpVertex(C0(12, 8), C0(1, 7) - C0(12, 8), (F3DVtx*)offset); + (*cmd0)++; + } else { +- F3DVtx* vtx = (F3DVtx*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ F3DVtx* vtx = (F3DVtx*)CachedResourceRawPointer(hash); + + if (vtx != NULL) { + vtx = (F3DVtx*)((char*)vtx + offset); +@@ -3738,7 +3824,7 @@ bool gfx_dl_otr_hash_handler_custom(F3DGfx** cmd0) { + + uint64_t hash = ((uint64_t)(*cmd0)->words.w0 << 32) + (*cmd0)->words.w1; + +- F3DGfx* gfx = (F3DGfx*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ F3DGfx* gfx = (F3DGfx*)CachedResourceRawPointer(hash); + + if (gfx != 0) { + g_exec_stack.call(cmd, gfx); +@@ -3796,7 +3882,7 @@ bool gfx_branch_z_otr_handler_f3dex2(F3DGfx** cmd0) { + (gfx->mRsp->extra_geometry_mode & G_EX_ALWAYS_EXECUTE_BRANCH) != 0) { + uint64_t hash = ((uint64_t)(*cmd0)->words.w0 << 32) + (*cmd0)->words.w1; + +- F3DGfx* gfx = (F3DGfx*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ F3DGfx* gfx = (F3DGfx*)CachedResourceRawPointer(hash); + + if (gfx != 0) { + (*cmd0) = gfx; +@@ -3986,9 +4072,17 @@ static bool IsValidResolvedAddress(uintptr_t addr) { + reinterpret_cast(addr), &module) != 0; + #else + // For non-Windows platforms, check whether the address belongs to a loaded object. ++#if UINTPTR_MAX <= 0xFFFFFFFFu ++ // 32-bit: the heap and mappings live below 0x10000000 as well; a mapped page is a real address. ++ // mincore is one cheap system call (dladdr searched symbol tables: 3% of the CPU time on an A20). ++ static const uintptr_t pageSize = (uintptr_t)sysconf(_SC_PAGESIZE); ++ unsigned char resident; ++ return mincore(reinterpret_cast(addr & ~(pageSize - 1)), 1, &resident) == 0; ++#else + Dl_info info; + return dladdr(reinterpret_cast(addr), &info) != 0; + #endif ++#endif + } + + bool gfx_set_timg_handler_rdp(F3DGfx** cmd0) { +@@ -4003,6 +4097,7 @@ bool gfx_set_timg_handler_rdp(F3DGfx** cmd0) { + // from the resource, but raw textures would leave them at 0. + rawTexMetdata.h_byte_scale = 1; + rawTexMetdata.v_pixel_scale = 1; ++ bool fromResource = false; + + if ((i & 1) != 1) { + if (gfx_check_image_signature(imgData) == 1) { +@@ -4022,10 +4117,11 @@ bool gfx_set_timg_handler_rdp(F3DGfx** cmd0) { + rawTexMetdata.v_pixel_scale = tex->VPixelScale; + rawTexMetdata.type = tex->Type; + rawTexMetdata.resource = tex; ++ fromResource = true; + } + } + +- if (!IsValidResolvedAddress(i)) { ++ if (!fromResource && !IsValidResolvedAddress(i)) { + return false; + } + +@@ -4050,8 +4146,7 @@ bool gfx_set_timg_otr_hash_handler_custom(F3DGfx** cmd0) { + } + + std::shared_ptr texture = std::static_pointer_cast( +- Ship::Context::GetRawInstance()->GetResourceManager()->LoadResourceProcess( +- Ship::Context::GetRawInstance()->GetResourceManager()->GetArchiveManager()->HashToCString(hash))); ++ CachedResourceByHash(hash)); + if (texture != nullptr) { + texFlags = texture->Flags; + rawTexMetadata.width = texture->Width; +diff --git a/src/fast/shaders/opengl/default.shader.glsl b/src/fast/shaders/opengl/default.shader.glsl +index 1fe86aa..ff45672 100644 +--- a/src/fast/shaders/opengl/default.shader.glsl ++++ b/src/fast/shaders/opengl/default.shader.glsl +@@ -134,14 +134,18 @@ + + float random(in vec3 value) { + float random = dot(sin(value), vec3(12.9898, 78.233, 37.719)); ++ @if(gles2) ++ return fract(sin(random) * 43758.5453); ++ @else + return fract(sin(random) * 143758.5453); ++ @end + } + + vec4 fromLinear(vec4 linearRGB){ + bvec3 cutoff = lessThan(linearRGB.rgb, vec3(0.0031308)); + vec3 higher = vec3(1.055)*pow(linearRGB.rgb, vec3(1.0/2.4)) - vec3(0.055); + vec3 lower = linearRGB.rgb * vec3(12.92); +- return vec4(mix(higher, lower, cutoff), linearRGB.a); ++ return vec4(mix(higher, lower, vec3(cutoff)), linearRGB.a); + } + + vec4 filter3point(in sampler2D tex, in vec2 texCoord, in vec2 texSize) { +@@ -187,7 +191,9 @@ + vec4 texVal@{i} = hookTexture2D(@{i}, uTex@{i}, vTexCoordAdj@{i}, texSize@{i}); + + @if(o_masks[i]) +- @if(opengles) ++ @if(gles2) ++ vec2 maskSize@{i} = texSize@{i}; ++ @elseif(opengles) + vec2 maskSize@{i} = vec2(textureSize(uTexMask@{i}, 0)); + @else + vec2 maskSize@{i} = textureSize(uTexMask@{i}, 0); +diff --git a/src/libultraship/controller/controldevice/controller/mapping/ControllerDefaultMappings.cpp b/src/libultraship/controller/controldevice/controller/mapping/ControllerDefaultMappings.cpp +index c431c34..35f66b2 100644 +--- a/src/libultraship/controller/controldevice/controller/mapping/ControllerDefaultMappings.cpp ++++ b/src/libultraship/controller/controldevice/controller/mapping/ControllerDefaultMappings.cpp +@@ -80,6 +80,11 @@ void ControllerDefaultMappings::SetDefaultSDLButtonToButtonMappings( + { BTN_DDOWN, { SDL_CONTROLLER_BUTTON_DPAD_DOWN } }, + { BTN_DLEFT, { SDL_CONTROLLER_BUTTON_DPAD_LEFT } }, + { BTN_DRIGHT, { SDL_CONTROLLER_BUTTON_DPAD_RIGHT } }, ++#ifdef USE_GLES2 ++ { BTN_CDOWN, { SDL_CONTROLLER_BUTTON_Y } }, ++ { BTN_CLEFT, { SDL_CONTROLLER_BUTTON_X } }, ++ { BTN_CRIGHT, { SDL_CONTROLLER_BUTTON_RIGHTSHOULDER } }, ++#endif + }); + } + +diff --git a/src/ship/audio/Audio.cpp b/src/ship/audio/Audio.cpp +index 8cc5b12..604a30c 100644 +--- a/src/ship/audio/Audio.cpp ++++ b/src/ship/audio/Audio.cpp +@@ -36,8 +36,11 @@ void Audio::InitAudioPlayer() { + + if (mAudioPlayer && !mAudioPlayer->Init()) { + // Failed to initialize system audio player. +- // Fallback to Null if the native system player does not work. +- SetCurrentAudioBackend(AudioBackend::NUL); ++ // Fallback to Null if the native system player does not work: for this run only, ++ // the saved backend stays and the next start tries it again ++ mAudioBackend = AudioBackend::NUL; ++ mAudioPlayer = std::make_shared(this->mAudioSettings); ++ mAudioPlayer->Init(); + } + } + +diff --git a/src/ship/debug/CrashHandler.cpp b/src/ship/debug/CrashHandler.cpp +index 39d76be..311b80d 100644 +--- a/src/ship/debug/CrashHandler.cpp ++++ b/src/ship/debug/CrashHandler.cpp +@@ -2,6 +2,9 @@ + #include "ship/utils/StringHelper.h" + #include "ship/debug/CrashHandler.h" + #include "ship/Context.h" ++#ifndef _WIN32 ++#include // _exit ++#endif + + #ifdef _WIN32 + #include +@@ -134,6 +137,23 @@ void CrashHandler::PrintRegisters(ucontext_t* ctx) { + AppendLine(regbuffer); + snprintf(regbuffer, std::size(regbuffer), "EFL: 0x%08lX", ctx->uc_mcontext.gregs[REG_EFL]); + AppendLine(regbuffer); ++#elif defined(__arm__) ++ const struct { ++ const char* name; ++ unsigned long value; ++ } regs[] = { { "PC", ctx->uc_mcontext.arm_pc }, { "LR", ctx->uc_mcontext.arm_lr }, ++ { "SP", ctx->uc_mcontext.arm_sp }, { "R0", ctx->uc_mcontext.arm_r0 }, ++ { "R1", ctx->uc_mcontext.arm_r1 }, { "R2", ctx->uc_mcontext.arm_r2 }, ++ { "R3", ctx->uc_mcontext.arm_r3 }, { "FAULT", ctx->uc_mcontext.fault_address } }; ++ for (const auto& reg : regs) { ++ snprintf(regbuffer, std::size(regbuffer), "%s: 0x%08lX", reg.name, reg.value); ++ AppendLine(regbuffer); ++ } ++ Dl_info module; ++ if (dladdr((void*)ctx->uc_mcontext.arm_pc, &module) != 0) { ++ snprintf(regbuffer, std::size(regbuffer), "BASE: 0x%08lX", (unsigned long)module.dli_fbase); ++ AppendLine(regbuffer); ++ } + #endif + } + +@@ -163,6 +183,9 @@ static void ErrorHandler(int sig, siginfo_t* sigInfo, void* data) { + case SIGSEGV: + crashHandler->AppendLine("INVALID ACCESS TO STORAGE"); + break; ++ case SIGBUS: ++ crashHandler->AppendLine("BUS ERROR (UNALIGNED OR INVALID ADDRESS)"); ++ break; + } + + crashHandler->PrintRegisters(ctx); +@@ -199,11 +222,13 @@ static void ErrorHandler(int sig, siginfo_t* sigInfo, void* data) { + + Context::GetRawInstance()->GetLogger()->flush(); + spdlog::shutdown(); +- exit(1); ++ _exit(128 + sig); + } + + static void ShutdownHandler(int sig, siginfo_t* sigInfo, void* data) { +- exit(1); ++ SDL_Event event; ++ event.type = SDL_QUIT; ++ SDL_PushEvent(&event); + } + + #elif _WIN32 +@@ -426,6 +451,7 @@ CrashHandler::CrashHandler() : mOutBuffer(std::make_unique(gMaxBufferSiz + sigaction(SIGABRT, &action, nullptr); + sigaction(SIGFPE, &action, nullptr); + sigaction(SIGSEGV, &action, nullptr); ++ sigaction(SIGBUS, &action, nullptr); + + shutdownAction.sa_flags = SA_SIGINFO; + shutdownAction.sa_sigaction = ShutdownHandler; diff --git a/ports/README.md b/ports/README.md new file mode 100644 index 0000000..5fbe017 --- /dev/null +++ b/ports/README.md @@ -0,0 +1,86 @@ +# Native ports for the RetroStone2 + +PC ports of N64 games (and other open-source engines) can run on the RetroStone2 **as native games**: ARM programs +that draw with the console's GPU, with no emulator in between. They are much faster and look much better than +emulating the N64: Super Mario 64 runs at full speed on the RetroStone2. + +**RetroStoneOS never ships any game.** This folder holds only build scripts and code changes. A port's game data is +made **from your own ROM**, either **on your PC** with the scripts here (the steps below), or **on the console itself** +through Settings > Game store ([docs/store-ports.md](../docs/store-ports.md)), and it stays on your own SD card. Keep it +to yourself: never upload it, share it or put it in a release. + +## How to get a native port (step by step) + +1. **Update the console** to a RetroStoneOS with **Ports** in the menu (build 20 or newer; Settings > System update). The + libultraship ports (Star Fox 64, Ocarina of Time, Majora's Mask, Mario Kart 64) also need `rsos-gamepad` and the port libraries in the + RetroStone2 configs (Ogg/Vorbis, Opus, libzip, tinyxml2, spdlog, SDL2_net). +2. **Set up the build on a PC** with Linux or Windows + WSL (Ubuntu): + * the usual tools: `sudo apt install build-essential git python3 cmake ninja-build`; + * RetroStoneOS, built once for the RetroStone2: it provides the compiler for the console and its libraries. + Follow [docs/build.md](../docs/build.md) with `retrostone2_release_defconfig` (the output in + `~/rsos/output`). A port built once usually keeps working after the console's System updates. +3. **Build the port** with its script, giving it your ROM (each port's README says which ROM version): + ```sh + ports/sm64/build-sm64.sh ~/baserom.us.z64 ~/my-ports + ``` +4. **Copy** the `roms` folder from the output (`~/my-ports/roms`) onto the SD card's **RETROSTONE** partition + (it merges with the `roms` folder there). From WSL, Windows sees it at `\\wsl$\Ubuntu\home\\my-ports`. +5. In the menu: **Ports** > the game. **Select + Start** goes back to the menu (Super Mario 64 and Star Fox + 64 quit at once, as the emulators do; any other native game when both are held for a second). + +## Available ports + +| Game | Folder | Port | Status on the RetroStone2 | +|---|---|---|---| +| Super Mario 64 | [sm64](sm64/README.md) | [sm64-port](https://github.com/sm64-port/sm64-port) | **Works**: full speed, built-in controls, analog stick (Pro) or D-pad | +| Star Fox 64 | [starship](starship/README.md) | [Starship](https://github.com/HarbourMasters/Starship) + a GLES2 libultraship | **Works**: built-in controls, cheaper first-start settings; some slowdown in busy scenes | +| Mario Kart 64 | [spaghettikart](spaghettikart/README.md) | [SpaghettiKart](https://github.com/HarbourMasters/SpaghettiKart) + a GLES2 libultraship | **Works**: races, sound, saves, built-in controls; mostly 30 fps, some slowdown in busy places | +| The Legend of Zelda: Ocarina of Time | [soh](soh/README.md) | [Ship of Harkinian](https://github.com/HarbourMasters/Shipwright) 9.3.1 + a GLES2 libultraship | **Works**: menus, 3D, sound, saves; a little slowdown in busy places | +| GoldenEye 007 | [goldeneye](goldeneye/README.md) | [Project Midas](https://github.com/murkantor/Project-Midas) + a GLES2 fast3d renderer | **Works**: intro, menus, levels, sound; 30 fps in light areas, 10-15 in busy views | +| The Legend of Zelda: Majora's Mask | [2ship](2ship/README.md) | [2Ship2Harkinian](https://github.com/HarbourMasters/2ship2harkinian) + a GLES2 libultraship | **Works**: 3D, music and sound, at the game's own 20 fps in most places | + +## HDMI, pads and the Ports list + +* **One Ports list** (RetroStoneOS 0.1.5.24): Doom, Cave Story and the native games are in a single **Ports** entry of the + menu; each game starts as it always did (a `.sh` launch script natively, a `.wad` in the Doom engine, an `.exe` in the + Cave Story engine). +* **HDMI** (0.1.5.23, sound 0.1.5.28): a native port follows HDMI exactly like a libretro game: plug a TV or monitor in and the game is + on it with the built-in screen off, unplug it and the game is back on the built-in screen, without restarting. The + game always renders 640x480; the display engine scales it, so it never sees a resolution change. The sound + follows the picture: the TV's sound while the game is on HDMI, the speaker when it is not. +* **A real N64 pad** plays like the built-in buttons in every port: each port has a `.layout` file next to its + launch script (in this folder, and in [RetroStone-Ports](https://github.com/KurdtNervanna/RetroStone-Ports) for + Perfect Dark and Smash 64) that says which control the game reads for each N64 function. Edit it on the card to + change it; see [docs/native-games.md](../docs/native-games.md), "Layouts". + +## Other N64 PC ports: can they run here? + +The RetroStone2's GPU is a **Mali-400 MP2: OpenGL ES 2.0 only** (Mesa's lima driver), with 1 GB of RAM and two +Cortex-A7 cores at 960-1056 MHz. That decides which ports can work: + +| Port family | Games | GPU it needs | Here | +|---|---|---|---| +| sm64-port's renderer (Fast3D, GLSL 1.10 / ES 1.00) | Super Mario 64 (sm64-port, sm64ex) | OpenGL 2.1 / **ES 2.0** | **Yes** (Super Mario 64 works) | +| [libultraship](https://github.com/Kenix3/libultraship) (HarbourMasters) | Star Fox 64 ([Starship](https://github.com/HarbourMasters/Starship)), Ocarina of Time ([Ship of Harkinian](https://github.com/HarbourMasters/Shipwright)), Majora's Mask ([2Ship2Harkinian](https://github.com/HarbourMasters/2ship2harkinian)), Mario Kart 64 ([SpaghettiKart](https://github.com/HarbourMasters/SpaghettiKart)), [Ghostship](https://github.com/HarbourMasters/Ghostship), Banjo-Kazooie ([Lighthouse](https://github.com/HarbourMasters/Lighthouse)), Paper Mario ([PaperBoat](https://github.com/HarbourMasters/PaperBoat)) | OpenGL 3.0 (GLSL 1.30) or **ES 3.0** | **Yes with the GLES2 mode** in these patches (Star Fox 64, Ocarina of Time, Majora's Mask and Mario Kart 64 work); ports on the newest libultraship also need SDL3 | +| The [Perfect Dark port](https://github.com/fgsfdsfgs/perfect_dark)'s fast3d (also in [Project Midas](https://github.com/murkantor/Project-Midas)) | Perfect Dark, GoldenEye 007 | OpenGL 3.0 / ES 3.0 | **Yes with the GLES2 mode** in [goldeneye](goldeneye/README.md) (GoldenEye works); Perfect Dark would need the same changes | +| N64 Recompiled (RT64) | Zelda 64 Recomp, Banjo: Recompiled, DK64, Star Fox 64 Recomp, ... | Vulkan / Direct3D 12 | **No**: the Mali-400 has neither | + +### libultraship on OpenGL ES 2.0 + +libultraship's OpenGL renderer has shader variants for desktop GL and **GLES 3.0**; the ports here add a **GLES +2.0** mode (`USE_GLES2`): GLSL ES 1.00 shaders, GLES2 framebuffers and depth buffers, no multisampling. Each port +pins its own libultraship, so each has its own copy of the change: [starship/libultraship-gles2.patch](starship/libultraship-gles2.patch) +(libultraship `eaaf9d0`), [soh/libultraship-gles2.patch](soh/libultraship-gles2.patch) (libultraship `da6daf1`, +with fixes for 32-bit ARM and speed work measured on the console) and +[spaghettikart/libultraship-gles2.patch](spaghettikart/libultraship-gles2.patch) (libultraship `60c9bb7`: Ship of +Harkinian's, plus fewer draw calls) and [2ship/libultraship-gles2.patch](2ship/libultraship-gles2.patch) +(libultraship `7cb1022`: the same). These libultraship versions still use SDL2. + +## Making a new port + +A native game is any ARM program with a launch script in `roms/native/` (docs/native-games.md). For an SDL2 port: +build it with the RetroStoneOS cross compiler (`~/rsos/output/host/bin/arm-linux-`) against the staging +libraries (`~/rsos/output/staging`), use GLES2 for 3D, and either start `rsos-gamepad` for the built-in controls +as one SDL gamepad (`starship/Star Fox 64.sh`) or read them from `/dev/input` yourself (three devices: +"RetroStone2 Buttons", "RetroStone2 Shoulder Buttons" and "analog-stick"; `sm64/controller_rsos.c` is an +example). Put the game's code changes in a patch next to a build script, never the game's data. diff --git a/ports/goldeneye/.gitattributes b/ports/goldeneye/.gitattributes new file mode 100644 index 0000000..ec1ffa8 --- /dev/null +++ b/ports/goldeneye/.gitattributes @@ -0,0 +1 @@ +*.patch -text diff --git a/ports/goldeneye/GoldenEye 007.layout b/ports/goldeneye/GoldenEye 007.layout new file mode 100644 index 0000000..d256d1a --- /dev/null +++ b/ports/goldeneye/GoldenEye 007.layout @@ -0,0 +1,9 @@ +# N64 pad layout for this port: which SDL element the game reads for each N64 function, +# so a real N64 pad plays like the built-in buttons do here. Used when an N64 pad is +# plugged in (Settings > Controls); see docs/native-games.md, "Layouts". +# Functions: a b z l r start cup cdown cleft cright dpup dpdown dpleft dpright ("none" drops one). +# Left alone, an N64 pad is: a=a b=b z=lefttrigger l=leftshoulder r=rightshoulder +# (+ a copy of r on the right trigger), C buttons on the right stick, D-pad on the hat. +# GoldenEye: it has its own N64 layout for a pad named N64 (the menu names the pad so). +# Keep R only on R (the default's copy of R on the right trigger would also fire Z). +r = rightshoulder diff --git a/ports/goldeneye/GoldenEye 007.sh b/ports/goldeneye/GoldenEye 007.sh new file mode 100644 index 0000000..06a3caf --- /dev/null +++ b/ports/goldeneye/GoldenEye 007.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# GoldenEye 007 (Project Midas), built from your own ROM by ports/goldeneye/build-goldeneye.sh. +# The program, your ROM (Data/), settings (midas.ini) and saves (Data/Saves/) stay in goldeneye/. +cd goldeneye || exit 1 +# first start: settings for the console (the game fills in the rest and keeps them): one game +# tick per frame, so maxfps is also the game's speed +if [ ! -f midas.ini ]; then + printf '[display]\nfullscreen=fullscreen\nmaxfps=30\nfiltering=bilinear\nshow_fps=1\n' > midas.ini +fi +# The built-in controls as one standard gamepad (rsos-gamepad); SDL then +# ignores the raw button devices. It runs in the +# game's process group: the menu stops it with the game. +if [ -x /usr/bin/rsos-gamepad ]; then + SDL_GAMECONTROLLERCONFIG="$(/usr/bin/rsos-gamepad --print-mapping)" + export SDL_GAMECONTROLLERCONFIG + export SDL_GAMECONTROLLER_IGNORE_DEVICES=0x0001/0x0001 + /usr/bin/rsos-gamepad & + usleep 300000 +fi +exec ./ProjectMidas diff --git a/ports/goldeneye/README.md b/ports/goldeneye/README.md new file mode 100644 index 0000000..372d1ae --- /dev/null +++ b/ports/goldeneye/README.md @@ -0,0 +1,90 @@ +# GoldenEye 007 (Project Midas) on the RetroStone2 + +[Project Midas](https://github.com/murkantor/Project-Midas) is a PC port of GoldenEye 007 built from the +[N64 decompilation](https://github.com/n64decomp/007). Its renderer is fast3d (the Perfect Dark port's, the same +family as Super Mario 64's) and its PC builds are deliberately **32-bit**: GoldenEye's code keeps N64 pointers in +32-bit fields, so Midas runs it on the ILP32 model. The RetroStone2's ARMv7 is that same 32-bit, little-endian +model, so the game itself needs almost no change; the work is the renderer, which needs OpenGL 3.0. This folder +adds an OpenGL ES 2.0 mode to it and builds the game for the console as a native game (docs/native-games.md). + +**Nothing from the game is in this repository, the OS images or the updates.** The game's data comes from **your +own ROM** on your PC and stays yours. Project Midas takes the **GoldenEye 007 (US)** ROM, SHA-1 +`abe01e4aeb033b6c0836819f549c791b26cfde83` in `.z64` order (`.v64` and `.n64` dumps are converted). The game +also reads the ROM itself at every start, so a copy goes into `goldeneye/Data/` on the card. + +## Build + +```sh +ports/goldeneye/build-goldeneye.sh ~/"GoldenEye 007 (U).z64" ~/my-ports +``` + +It fetches Project Midas at a fixed commit (1.0.2b) into `~/rsos/goldeneye-work`, applies `goldeneye.patch`, +extracts the assets from the ROM with Midas's own tools (built for the PC: `make`, a C compiler and `python3` +are enough), builds the game for the console (`GE_GLES2`, the RetroStoneOS cross compiler), then writes: + +``` +~/my-ports/roms/native/GoldenEye 007.sh +~/my-ports/roms/native/goldeneye/ ProjectMidas, gamecontrollerdb.txt, gamecontrollerdefault.txt, + midas_ini_help.txt, Data/ (your ROM, shaders_base.txt) +``` + +Copy the `roms` folder onto the SD card's **RETROSTONE** partition; in the menu: **Native games > GoldenEye +007**. Settings (`midas.ini`) and saves (`Data/Saves/`) stay in `roms/native/goldeneye/`. Hold **Select + Start** +for a second to go back to the menu. The console needs a RetroStoneOS with Native games and `rsos-gamepad`. + +On the first start the launcher writes a `midas.ini` for the console: 30 fps (Midas runs one game tick per +frame, so this is also the game's pace), bilinear filtering and the frame counter in the top-left corner +(`show_fps=0` hides it). `midas_ini_help.txt` explains every setting. + +## Controls + +The original N64 control styles (1.1 Honey by default, 1.1-2.4 in the game's options), through `rsos-gamepad`. By +the labels on the console: + +| RetroStone2 | N64 | +|---|---| +| Analog stick (Pro) | the stick (move, turn) | +| D-pad | C buttons (look up/down, strafe) | +| R2 or Y (left) | Z (fire) | +| R1 or X (top) | R (aim) | +| L1 or L2 | L | +| B (bottom) / A (right) | A (change weapon) / B (use, reload) | +| Start | Start | + +The layout is the "RetroStone2" line at the top of `goldeneye/gamecontrollerdefault.txt`. + +## What the patch changes + +**OpenGL ES 2.0** (`GE_GLES2`, for the Mali-400): an ES 2.0 context and glad's GLES2 loader, GLSL ES 1.00 shaders, +texture sizes as uniforms (GLSL ES 1.00 has no `textureSize()`), no vertex array objects, unsized texture +formats, edge clamping instead of border clamping, no mipmaps on non-power-of-two textures without +`OES_texture_npot`, linear instead of three-point filtering, no framebuffer effects (they need blits and +multisampling: no MSAA, N64 edge AA, Low Res or Classic Mode), a window that is visible from the start (SDL's +KMSDRM backend), and streamed vertices as client-side arrays (lima made a new buffer object for every upload). + +**The Mali-400's 16-bit fragment shaders**, found on the console: +* GoldenEye's far clip discards fragments past the far plane by comparing clip z with w. In 16-bit floats those + two large, nearly equal numbers rounded to the wrong side, and the whole intro, the menus and many effects + (muzzle flashes, impacts, the Dam's gate switch) were discarded. The vertex shader (32-bit) now passes w - z. +* The noise (alpha dither) multiplied by 143758.5453, which is infinity in 16 bits: a hash that stays small. + +**32-bit ARM**: the x86 flags give way to ARM's (single-precision VFP rounds like the N64 already; +`-ffp-contract=off` keeps multiply-adds unfused, as on the N64 and SSE), the program is linked at `0x10000000` +(the address the Windows build uses: the display-list code takes any value below it for an N64 segment address), +`-fpermissive` for GCC 14, and crash reports with the ARM registers and the return addresses on the stack. +Upstream bug fixed: `stanCheckLinkedSpecialTile` declared the float arguments of the tile-walk callback as `s32`; +on the hard-float ARM ABI the floats travel in other registers, so its last argument came from the stack and +walking onto some tiles crashed the game. + +**Speed** (CPU profiles on the console): drawing on its own thread (the A20 has two cores), `-O3` and NEON math +for the renderer, `-O3` for the audio mixer. Midas's room cache (geometry kept on the GPU) stays off: its vertex +shader exceeds the Mali-400 vertex processor's 512 instructions. Its setting now applies at start-up (it only +did from an ini line). + +**The controls**: the "RetroStone2" layout above, on the N64 control styles. + +## Status + +**Works on a RetroStone2 Pro** (played: the intro, the menus and the Dam): picture, effects and sound. 30 fps in light areas, around 10-15 in the +busiest views (the N64 itself often ran GoldenEye at 15-20); the time goes to GL draw calls in the Mesa lima +driver, a few hundred a frame. The game's messages are in `rsos/logs/boot/game.log` on the SD card. diff --git a/ports/goldeneye/build-goldeneye.sh b/ports/goldeneye/build-goldeneye.sh new file mode 100755 index 0000000..db9364d --- /dev/null +++ b/ports/goldeneye/build-goldeneye.sh @@ -0,0 +1,96 @@ +#!/bin/bash +# Builds GoldenEye 007 (Project Midas) for RetroStoneOS from YOUR OWN ROM, on the PC +# (Linux/WSL), as a native game for the SD card (docs/native-games.md). +# +# ports/goldeneye/build-goldeneye.sh [output folder] +# +# Needs a built RetroStoneOS tree for the RetroStone2 with SDL2 (the RetroStone2 +# configs): ~/rsos/output, or RSOS_OUTPUT=; cmake, ninja, make, python3 and a C +# compiler for the PC (the asset extraction runs here). Project Midas is fetched at a +# fixed commit into ~/rsos/goldeneye-work (RSOS_GOLDENEYE_WORK) and patched +# (goldeneye.patch). +# +# The result contains the game's data, taken from your ROM (the game also reads the +# ROM itself at every start, from goldeneye/Data/): keep it for yourself. Never put +# it in a release, an update or a repository. +# +# Output (default ./goldeneye-retrostone2): roms/native/GoldenEye 007.sh and +# roms/native/goldeneye/. Copy the "roms" folder onto the SD card's RETROSTONE +# partition (it merges with the roms folder there). +set -euo pipefail + +REPO=https://github.com/murkantor/Project-Midas.git +COMMIT=9062f9f120b7f64d39e5db59500ed50e8e7a6686 # Project Midas 1.0.2b +ROM_SHA1=abe01e4aeb033b6c0836819f549c791b26cfde83 # GoldenEye 007 (US), .z64 order + +here=$(cd "$(dirname "$0")" && pwd) +rom=${1:-} +out=${2:-$PWD/goldeneye-retrostone2} +O=${RSOS_OUTPUT:-$HOME/rsos/output} +W=${RSOS_GOLDENEYE_WORK:-$HOME/rsos/goldeneye-work} + +die() { echo "build-goldeneye: $*" >&2; exit 1; } + +[ -n "$rom" ] || die "usage: $0 [output folder]" +[ -f "$rom" ] || die "$rom: no such file" +rom=$(cd "$(dirname "$rom")" && pwd)/$(basename "$rom") +case "$out" in /*) ;; *) out=$PWD/$out ;; esac +[ -x "$O/host/bin/arm-linux-gcc" ] || die "no cross compiler in $O/host/bin (build RetroStoneOS first)" +[ -e "$O/staging/usr/lib/libSDL2.so" ] || die "libSDL2.so is not in $O/staging (build RetroStoneOS with the RetroStone2 configs)" +TOOLCHAIN=$O/host/share/buildroot/toolchainfile.cmake + +# only the fixed commit (the whole history is large) +if [ ! -d "$W/.git" ]; then + git init -q "$W" + git -C "$W" remote add origin "$REPO" +fi +cd "$W" +git fetch -q --depth 1 origin "$COMMIT" +# a clean tree at the fixed commit, then our changes (the build folder, the ROM and +# the extracted assets are ignored by git and stay) +git checkout -q -f "$COMMIT" +git apply "$here/goldeneye.patch" + +# the ROM, in .z64 byte order, as baserom.u.z64 (where the extraction reads it) +python3 - "$rom" baserom.u.z64 << 'EOF' || die "$rom is not an N64 ROM" +import sys +data = bytearray(open(sys.argv[1], 'rb').read()) +head = bytes(data[:4]) +if head == b'\x37\x80\x40\x12': # .v64: 16-bit words swapped + data[0::2], data[1::2] = data[1::2], data[0::2] +elif head == b'\x40\x12\x37\x80': # .n64: 32-bit words reversed + for i in range(0, len(data) - 3, 4): + data[i:i + 4] = data[i:i + 4][::-1] +elif head != b'\x80\x37\x12\x40': + sys.exit(1) +open(sys.argv[2], 'wb').write(data) +EOF +sum=$(sha1sum baserom.u.z64 | cut -d' ' -f1) +[ "$sum" = "$ROM_SHA1" ] || + die "$rom is not the GoldenEye 007 (US) ROM Project Midas takes (SHA-1 $sum in .z64 order, needs $ROM_SHA1)" + +# the assets the build compiles in or includes (images, music, demos), with tools built for this PC +TERM=${TERM:-dumb} ./scripts/extract_baserom.u.sh +make convert_props convert_chrs convert_guns combine_images + +# the game for the console: the fast3d renderer on OpenGL ES 2.0 (GE_GLES2). CMAKE_SYSTEM_NAME +# Linux: Buildroot's toolchain file names it "Buildroot". 32-bit ARM is the same ILP32 +# little-endian model Midas is written for (its PC builds are 32-bit x86). +cmake -S . -B build-gles2 -G Ninja -DCMAKE_BUILD_TYPE=Release -DGE_VIDEO=ON -DGE_GLES2=ON \ + -DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN" -DCMAKE_SYSTEM_NAME=Linux +cmake --build build-gles2 + +file build-gles2/ProjectMidas | grep -q 'ARM' || die "build-gles2/ProjectMidas is not an ARM program" +G=$out/roms/native/goldeneye +mkdir -p "$G/Data" +"$O/host/bin/arm-linux-strip" -o "$G/ProjectMidas" build-gles2/ProjectMidas +cp tools/gamecontrollerdb.txt tools/gamecontrollerdefault.txt tools/midas_ini_help.txt "$G/" +cp tools/shaders_base.txt "$G/Data/" +cp tools/Data_README.txt "$G/Data/README.txt" +# the game reads its levels, models and sounds from the ROM at every start +cp baserom.u.z64 "$G/Data/ge007.u.z64" +install -m 0644 "$here/GoldenEye 007.sh" "$out/roms/native/GoldenEye 007.sh" +echo +echo "Done: $out/roms" +echo "Copy that \"roms\" folder onto the SD card's RETROSTONE partition, then in the menu:" +echo "Native games > GoldenEye 007. Hold Select + Start to quit." diff --git a/ports/goldeneye/goldeneye.patch b/ports/goldeneye/goldeneye.patch new file mode 100644 index 0000000..1b9c029 --- /dev/null +++ b/ports/goldeneye/goldeneye.patch @@ -0,0 +1,733 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 2df2e82..f9e4c61 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -7,13 +7,18 @@ project(ge007 C) + + set(CMAKE_C_STANDARD 11) + ++if(CMAKE_SYSTEM_PROCESSOR MATCHES "^arm") ++ set(GE_ARM ON) ++ add_compile_options(-ffp-contract=off) ++else() ++ set(GE_ARM OFF) ++ add_compile_options(-m32 -msse2 -mfpmath=sse) ++endif() ++ + add_compile_options( +- -m32 + # Use SSE scalar floats so every operation rounds to single precision like + # the N64 FPU; x87's 80-bit excess precision flips borderline comparisons + # (it broke the stan.c tile-walk edge test and room visibility in Egypt). +- -msse2 +- -mfpmath=sse + -fno-strict-aliasing + -fwrapv + -funsigned-char +@@ -50,7 +55,11 @@ if(WIN32) + -Wl,--stack,16777216) + link_libraries(dbghelp) + else() +- add_link_options(-m32 -no-pie) ++ if(GE_ARM) ++ add_link_options(-no-pie -Wl,-Ttext-segment=0x10000000) ++ else() ++ add_link_options(-m32 -no-pie) ++ endif() + endif() + + add_compile_definitions( +@@ -175,7 +184,6 @@ set(GU_SRC + # oddtextures texel data are big-endian blobs. + set(ASSET_C_FLAGS + -std=gnu11 +- -m32 -malign-data=abi + -fms-extensions -ffreestanding -fno-strict-aliasing -fwrapv -funsigned-char + -fno-common -fno-zero-initialized-in-bss -fno-toplevel-reorder -fno-pic + -Og -w +@@ -192,6 +200,15 @@ set(ASSET_C_FLAGS + -I${CMAKE_SOURCE_DIR}/port/include + -I${CMAKE_SOURCE_DIR}/src/libultra) + ++if(CMAKE_C_COMPILER_ID STREQUAL "GNU" AND CMAKE_C_COMPILER_VERSION VERSION_GREATER_EQUAL 14) ++ list(APPEND ASSET_C_FLAGS -fpermissive) ++ add_compile_options($<$:-fpermissive>) ++endif() ++ ++if(NOT GE_ARM) ++ list(APPEND ASSET_C_FLAGS -m32 -malign-data=abi) ++endif() ++ + if(NOT CMAKE_OBJCOPY) + set(CMAKE_OBJCOPY objcopy) + endif() +@@ -359,6 +376,10 @@ list(APPEND PORT_SRC src/libultrare/io/vitbl.c) + # GE microcode opcode work lands (docs/port/ge-microcode.md); the null + # renderer in pcsched.c stays the headless default. + option(GE_VIDEO "Build the fast3d renderer (SDL2 + OpenGL)" OFF) ++option(GE_GLES2 "fast3d on OpenGL ES 2.0 (no framebuffer effects)" OFF) ++if(GE_GLES2) ++ add_compile_definitions(USE_GLES2) ++endif() + + # Testing convenience: every solo mission, bonus stage and difficulty + # (incl. 007 mode) selectable regardless of save state. Progression logic +@@ -388,6 +409,11 @@ if(GE_VIDEO) + port/fast3d/glad/glad.c + ) + add_compile_definitions(GE_VIDEO=1) ++ if(GE_ARM) ++ set_source_files_properties(${FAST3D_SRC} PROPERTIES ++ COMPILE_OPTIONS "-O3;-fno-math-errno;-funsafe-math-optimizations") ++ set_source_files_properties(port/src/audio_pc.c PROPERTIES COMPILE_OPTIONS "-O3") ++ endif() + else() + set(FAST3D_SRC) + # video.c/input_pc.c/raphnet.c are GE_VIDEO-only; exclude them from the port glob. +@@ -448,7 +474,10 @@ if(GE_VIDEO) + # 32-bit SDL2: needs libsdl2-dev:i386 (+ libgl-dev:i386), or set + # SDL2_LINUX_ROOT to a self-built prefix (e.g. CI's cached, user-writable + # install, avoiding a system-wide /usr install). +- if(SDL2_LINUX_ROOT) ++ if(GE_GLES2) ++ find_package(SDL2 REQUIRED) ++ target_link_libraries(ge SDL2::SDL2 dl pthread) ++ elseif(SDL2_LINUX_ROOT) + target_include_directories(ge PRIVATE ${SDL2_LINUX_ROOT}/include/SDL2) + target_link_libraries(ge ${SDL2_LINUX_ROOT}/lib/i386-linux-gnu/libSDL2.so GL dl pthread) + set_target_properties(ge PROPERTIES BUILD_RPATH ${SDL2_LINUX_ROOT}/lib/i386-linux-gnu) +diff --git a/port/fast3d/gfx_opengl.cpp b/port/fast3d/gfx_opengl.cpp +index e1efb53..269376f 100644 +--- a/port/fast3d/gfx_opengl.cpp ++++ b/port/fast3d/gfx_opengl.cpp +@@ -67,6 +67,8 @@ struct ShaderProgram { + GLint frame_count_location; + GLint noise_scale_location; + GLint three_point_filter_locations[2]; ++ GLint tex_size_locations[2]; /* GLSL < 1.30: uTexSize0/1 */ ++ float tex_size_pushed[2][2]; + /* GE retained geometry (below): the fragment shader object outlives the + * link so the twin program can share it, plus the ids its features come from */ + GLuint fragment_shader; +@@ -91,6 +93,11 @@ static GLuint opengl_vao; + static bool current_depth_mask; + + static uint32_t frame_count; ++#ifdef USE_GLES2 ++#define GL_FRAME_COUNT ((GLint)(frame_count & 63)) ++#else ++#define GL_FRAME_COUNT ((GLint)frame_count) ++#endif + + static std::vector framebuffers; + static size_t current_framebuffer; +@@ -120,6 +127,24 @@ static void gl_set_has_mips(GLuint id, uint8_t v) { + } + gl_tex_has_mips[id] = v; + } ++/* each texture object's size (GLSL < 1.30 shaders get it as a uniform) */ ++static std::vector> gl_tex_size; ++static void gl_set_tex_size(GLuint id, uint32_t w, uint32_t h) { ++ if (id >= gl_tex_size.size()) { ++ gl_tex_size.resize((size_t)id + 64, std::make_pair((uint16_t)1, (uint16_t)1)); ++ } ++ gl_tex_size[id] = std::make_pair((uint16_t)w, (uint16_t)h); ++} ++static void gl_tex_size_of(GLuint id, float out[2]) { ++ if (id < gl_tex_size.size()) { ++ out[0] = gl_tex_size[id].first; ++ out[1] = gl_tex_size[id].second; ++ } else { ++ out[0] = out[1] = 1.0f; ++ } ++} ++/* push the bound textures' sizes into a program whose cache says otherwise */ ++static void gl_sync_tex_size(const GLint loc[2], float pushed[2][2]); + static bool gl_has_mips(GLuint id) { + return id < gl_tex_has_mips.size() && gl_tex_has_mips[id] != 0; + } +@@ -129,6 +154,7 @@ static char gl_glsl_version_str[16] = "130"; + static GLenum gl_mirror_clamp = GL_MIRROR_CLAMP_TO_EDGE; + static bool gl_es = false; + static bool gl_core_profile = false; ++static bool gl_npot = true; /* GLES2 without OES_texture_npot: no mipmaps on NPOT textures */ + + static void gl_ret_restore(void); /* GE retained geometry: back to the interpreter's VBO / program (defined below) */ + static struct ShaderProgram* gl_current_prg_set(struct ShaderProgram* prg); +@@ -163,7 +189,7 @@ static void gfx_opengl_vertex_array_set_attribs(struct ShaderProgram* prg) { + + static void gfx_opengl_set_uniforms(struct ShaderProgram* prg) { + if (prg->frame_count_location >= 0) { +- glUniform1i(prg->frame_count_location, frame_count); ++ glUniform1i(prg->frame_count_location, GL_FRAME_COUNT); + } + if (prg->noise_scale_location >= 0) { + glUniform1f(prg->noise_scale_location, current_noise_scale); +@@ -387,6 +413,8 @@ static struct ShaderProgram* gfx_opengl_create_and_load_new_shader(uint64_t shad + * to the fragment stage; both interpolate perspective-correct, so + * z/w is the fragment's true NDC depth. No extra attribute. */ + append_line(vs_buf, &vs_len, "OUTPUT vec2 vGeZw;"); ++ if (gl_glsl_version < 130) ++ append_line(vs_buf, &vs_len, "OUTPUT float vGeFar;"); + } + if (cc_features.opt_ge_pixfog) { + /* fog register curve (mul, offset) rides as a constant attribute */ +@@ -445,6 +473,8 @@ static struct ShaderProgram* gfx_opengl_create_and_load_new_shader(uint64_t shad + + if (cc_features.opt_ge_farclip || cc_features.opt_ge_pixfog) { + append_line(vs_buf, &vs_len, " vGeZw = aVtxPos.zw;"); ++ if (gl_glsl_version < 130) ++ append_line(vs_buf, &vs_len, " vGeFar = aVtxPos.w - aVtxPos.z;"); + } + if (cc_features.opt_ge_pixfog) { + append_line(vs_buf, &vs_len, " vGeFogP = aGeFogP;"); +@@ -455,7 +485,7 @@ static struct ShaderProgram* gfx_opengl_create_and_load_new_shader(uint64_t shad + append_line(vs_buf, &vs_len, " gl_Position = aVtxPos;"); + if (!GLAD_GL_ARB_depth_clamp) { + // HACK: workaround for no GL_DEPTH_CLAMP +- append_line(vs_buf, &vs_len, " gl_Position.z *= 0.3f;"); ++ append_line(vs_buf, &vs_len, " gl_Position.z *= 0.3;"); + } + append_line(vs_buf, &vs_len, "}"); + +@@ -499,6 +529,8 @@ static struct ShaderProgram* gfx_opengl_create_and_load_new_shader(uint64_t shad + } + if (cc_features.opt_ge_farclip || cc_features.opt_ge_pixfog) { + append_line(fs_buf, &fs_len, "INPUT vec2 vGeZw;"); ++ if (gl_glsl_version < 130) ++ append_line(fs_buf, &fs_len, "INPUT float vGeFar;"); + } + if (cc_features.opt_ge_pixfog) { + append_line(fs_buf, &fs_len, "INPUT vec2 vGeFogP;"); +@@ -515,11 +547,15 @@ static struct ShaderProgram* gfx_opengl_create_and_load_new_shader(uint64_t shad + + if (cc_features.used_textures[0]) { + append_line(fs_buf, &fs_len, "uniform sampler2D uTex0;"); ++ if (gl_glsl_version < 130) ++ append_line(fs_buf, &fs_len, "uniform vec2 uTexSize0;"); + if (current_filter_mode == FILTER_THREE_POINT) + append_line(fs_buf, &fs_len, "uniform int three_point_filter0;"); + } + if (cc_features.used_textures[1]) { + append_line(fs_buf, &fs_len, "uniform sampler2D uTex1;"); ++ if (gl_glsl_version < 130) ++ append_line(fs_buf, &fs_len, "uniform vec2 uTexSize1;"); + if (current_filter_mode == FILTER_THREE_POINT) + append_line(fs_buf, &fs_len, "uniform int three_point_filter1;"); + } +@@ -528,8 +564,13 @@ static struct ShaderProgram* gfx_opengl_create_and_load_new_shader(uint64_t shad + append_line(fs_buf, &fs_len, "uniform float noise_scale;"); + + append_line(fs_buf, &fs_len, "float random(in vec3 value) {"); +- append_line(fs_buf, &fs_len, " float random = dot(sin(value), vec3(12.9898, 78.233, 37.719));"); +- append_line(fs_buf, &fs_len, " return fract(sin(random) * 143758.5453);"); ++ if (gl_glsl_version < 130) { ++ append_line(fs_buf, &fs_len, " float n = fract(dot(value.xy, vec2(0.06711056, 0.00583715)) + value.z * 0.618034);"); ++ append_line(fs_buf, &fs_len, " return fract(52.9829189 * n);"); ++ } else { ++ append_line(fs_buf, &fs_len, " float random = dot(sin(value), vec3(12.9898, 78.233, 37.719));"); ++ append_line(fs_buf, &fs_len, " return fract(sin(random) * 143758.5453);"); ++ } + append_line(fs_buf, &fs_len, "}"); + + if (current_filter_mode == FILTER_THREE_POINT) { +@@ -555,7 +596,7 @@ static struct ShaderProgram* gfx_opengl_create_and_load_new_shader(uint64_t shad + + append_line(fs_buf, &fs_len, " lowp vec4 cw = vec4(0.0);"); + append_line(fs_buf, &fs_len, " for (int i = 0; i < 16; ++i) {"); +- append_line(fs_buf, &fs_len, " vec2 xy = vec2(float(i & 3), float(i >> 2));"); ++ append_line(fs_buf, &fs_len, " vec2 xy = vec2(mod(float(i), 4.0), floor(float(i) / 4.0));"); + append_line(fs_buf, &fs_len, " lowp float w = 0.009947 - length(xy) * 0.001;"); + append_line(fs_buf, &fs_len, " vec2 scaled_uv = uv + (vec2(-1.5) + xy) / texSize;"); + +@@ -589,14 +630,20 @@ static struct ShaderProgram* gfx_opengl_create_and_load_new_shader(uint64_t shad + if (cc_features.opt_ge_farclip) { + /* GE far clip: fragment past the projection far plane - the console + * clips fogless geometry there. */ +- append_line(fs_buf, &fs_len, " if (vGeZw.x > vGeZw.y) discard;"); ++ if (gl_glsl_version < 130) ++ append_line(fs_buf, &fs_len, " if (vGeFar < 0.0) discard;"); ++ else ++ append_line(fs_buf, &fs_len, " if (vGeZw.x > vGeZw.y) discard;"); + } + + for (int i = 0; i < 2; i++) { + if (cc_features.used_textures[i]) { + bool s = cc_features.clamp[i][0], t = cc_features.clamp[i][1]; + +- fs_len += sprintf(fs_buf + fs_len, " vec2 texSize%d = vec2(textureSize(uTex%d, 0));\n", i, i); ++ if (gl_glsl_version < 130) ++ fs_len += sprintf(fs_buf + fs_len, " vec2 texSize%d = uTexSize%d;\n", i, i); ++ else ++ fs_len += sprintf(fs_buf + fs_len, " vec2 texSize%d = vec2(textureSize(uTex%d, 0));\n", i, i); + + /* GE sky/water per-pixel divide: S/W and T/W by 1/W at this pixel, + * as the RDP does (the old CPU grid only approximated it). q is +@@ -858,6 +905,9 @@ static struct ShaderProgram* gfx_opengl_create_and_load_new_shader(uint64_t shad + prg->noise_scale_location = glGetUniformLocation(shader_program, "noise_scale"); + prg->three_point_filter_locations[0] = glGetUniformLocation(shader_program, "three_point_filter0"); + prg->three_point_filter_locations[1] = glGetUniformLocation(shader_program, "three_point_filter1"); ++ prg->tex_size_locations[0] = glGetUniformLocation(shader_program, "uTexSize0"); ++ prg->tex_size_locations[1] = glGetUniformLocation(shader_program, "uTexSize1"); ++ prg->tex_size_pushed[0][0] = prg->tex_size_pushed[1][0] = -1.0f; + + gfx_opengl_load_shader(prg); + +@@ -1001,7 +1051,12 @@ static void gfx_opengl_upload_texture(const uint8_t* rgba32_buf, uint32_t width, + } + g_GfxUpDrainUs = portProfNow() - up_t; + up_t += g_GfxUpDrainUs; ++#ifdef USE_GLES2 ++ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, rgba32_buf); ++#else + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, rgba32_buf); ++#endif ++ gl_set_tex_size(current_texture_ids[last_selected_tile], width, height); + g_GfxUpTexUs = portProfNow() - up_t; + up_t += g_GfxUpTexUs; + /* a fresh level 0 invalidates any older chain on this object; the N64 +@@ -1053,7 +1108,11 @@ static uint32_t gfx_cm_to_opengl(uint32_t val) { + switch (val) { + case 0x10: /* GE_TX_BORDER (gfx_pc.cpp): a grown font glyph - outside the + * texture is GL's default border colour, transparent black */ ++#ifdef USE_GLES2 ++ return GL_CLAMP_TO_EDGE; ++#else + return GL_CLAMP_TO_BORDER; ++#endif + case G_TX_NOMIRROR | G_TX_CLAMP: + return GL_CLAMP_TO_EDGE; + case G_TX_MIRROR | G_TX_WRAP: +@@ -1069,6 +1128,16 @@ static uint32_t gfx_cm_to_opengl(uint32_t val) { + extern "C" int ge_sky_tri_active; /* gfx_pc: inside an RDP-triangle (sky/water) draw */ + extern "C" int ge_mip_active; /* gfx_pc: this sampler serves a G_TL_LOD draw - minify through mips */ + ++static bool gl_can_mip(GLuint id) { ++ if (gl_npot) { ++ return true; ++ } ++ float sz[2]; ++ gl_tex_size_of(id, sz); ++ const uint32_t w = (uint32_t)sz[0], h = (uint32_t)sz[1]; ++ return (w & (w - 1)) == 0 && (h & (h - 1)) == 0; ++} ++ + static void gfx_opengl_set_sampler_parameters(int tile, bool linear_filter, uint32_t cms, uint32_t cmt) { + const GLint filter = linear_filter && (current_filter_mode == FILTER_LINEAR) ? GL_LINEAR : GL_NEAREST; + /* THIS is the value the draw actually wants - gfx_pc computes it per draw +@@ -1103,7 +1172,7 @@ static void gfx_opengl_set_sampler_parameters(int tile, bool linear_filter, uint + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, gfx_cm_to_opengl(cmt)); + return; + } +- if (ge_mip_active && !ge_sky_tri_active) { ++ if (ge_mip_active && !ge_sky_tri_active && gl_can_mip(current_texture_ids[tile])) { + /* GE N64 mipmaps: the RDP walked a mip chain for this draw, so give GL + * one (once per upload, box-filtered like GE's own builder) and minify + * through it to avoid moire. Bilerp becomes trilinear and point / +@@ -1138,7 +1207,7 @@ static void gfx_opengl_set_sampler_parameters(int tile, bool linear_filter, uint + const char* e = getenv("GE_SKY_NOMIP"); + skynomip = (e != NULL) && (e[0] != '0'); + } +- if (skynomip) { ++ if (skynomip || !gl_can_mip(current_texture_ids[tile])) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter); + } else { + glGenerateMipmap(GL_TEXTURE_2D); +@@ -1283,6 +1352,24 @@ static void gfx_opengl_set_use_alpha(bool use_alpha, bool modulate) { + * room decals keep the one-sided test. GE_DEC_CLIP=0 = old behaviour, + * GE_DEC_TOL= (default 8). */ + extern float gfx_ge_dec_b, gfx_ge_dec_d; ++static void gl_stream_vertices(const float* data, size_t len) { ++#ifdef USE_GLES2 ++ struct ShaderProgram* prg = gl_current_prg; ++ glBindBuffer(GL_ARRAY_BUFFER, 0); ++ size_t pos = 0; ++ for (int i = 0; i < prg->num_attribs; i++) { ++ if (prg->attrib_locations[i] >= 0) { ++ glVertexAttribPointer(prg->attrib_locations[i], prg->attrib_sizes[i], GL_FLOAT, GL_FALSE, ++ prg->num_floats * sizeof(float), data + pos); ++ } ++ pos += prg->attrib_sizes[i]; ++ } ++ (void)len; ++#else ++ glBufferData(GL_ARRAY_BUFFER, sizeof(float) * len, data, GL_STREAM_DRAW); ++#endif ++} ++ + static void gfx_opengl_draw_triangles(float buf_vbo[], size_t buf_vbo_len, size_t buf_vbo_num_tris) { + // printf("flushing %d tris\n", buf_vbo_num_tris); + static int clip = -1; +@@ -1294,8 +1381,11 @@ static void gfx_opengl_draw_triangles(float buf_vbo[], size_t buf_vbo_len, size_ + if (e != NULL && atof(e) > 0.0) tol = (float)atof(e); + } + gl_ret_restore(); /* after a retained draw: the stream VBO + this program's arrays again */ ++ if (gl_current_prg != nullptr) { ++ gl_sync_tex_size(gl_current_prg->tex_size_locations, gl_current_prg->tex_size_pushed); ++ } + if (!clip || !ge_dec_draw || gfx_ge_dec_b >= 0.0f || buf_vbo_num_tris == 0) { +- glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buf_vbo_len, buf_vbo, GL_STREAM_DRAW); ++ gl_stream_vertices(buf_vbo, buf_vbo_len); + glDrawArrays(GL_TRIANGLES, 0, 3 * buf_vbo_num_tris); + return; + } +@@ -1326,14 +1416,14 @@ static void gfx_opengl_draw_triangles(float buf_vbo[], size_t buf_vbo_len, size_ + glDisable(GL_POLYGON_OFFSET_FILL); + glStencilFunc(GL_ALWAYS, 1, 0xFF); + glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); +- glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buf_vbo_len, pushed.data(), GL_STREAM_DRAW); ++ gl_stream_vertices(pushed.data(), buf_vbo_len); + glDrawArrays(GL_TRIANGLES, 0, nv); + /* 2. draw */ + glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + gfx_opengl_set_depth_mode(ge_dm_args[0], ge_dm_args[1], ge_dm_args[2], ge_dm_args[3], ge_dm_zmode); + glStencilFunc(GL_EQUAL, 1, 0xFF); + glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); +- glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buf_vbo_len, buf_vbo, GL_STREAM_DRAW); ++ gl_stream_vertices(buf_vbo, buf_vbo_len); + glDrawArrays(GL_TRIANGLES, 0, nv); + /* 3. clear */ + glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); +@@ -1490,7 +1580,11 @@ static void gfx_opengl_init_extensions(void) { + } + + static void gfx_opengl_init(void) { ++#ifdef USE_GLES2 ++ if (!gladLoadGLES2Loader(gl_load_proc) || glGetString == NULL || glEnable == NULL) { ++#else + if (!gladLoadGLLoader(gl_load_proc) || glGetString == NULL || glEnable == NULL) { ++#endif + sysFatalError("Could not load OpenGL.\nReported SDL error: %s", SDL_GetError()); + } + +@@ -1509,13 +1603,22 @@ static void gfx_opengl_init(void) { + // name the GPU (iGPU vs dGPU is the first question on any fps report) + gfx_opengl_log_info(); + +- if (GLVersion.major < 2 || (GLVersion.major == 2 && GLVersion.minor < 1)) { ++ if (!gl_es && (GLVersion.major < 2 || (GLVersion.major == 2 && GLVersion.minor < 1))) { + const char *ver = (const char *)glGetString(GL_VERSION); + sysFatalError("Could not load OpenGL 2.1.\nReported version: %d.%d (%s)", + GLVersion.major, GLVersion.minor, ver ? ver : "unknown"); + } + +- if (!gfx_opengl_supports_shaders()) { ++#ifdef USE_GLES2 ++ // framebuffer effects need blits and multisampling: everything draws to the screen ++ gfx_framebuffers_enabled = false; ++ { ++ const char *ext = (const char *)glGetString(GL_EXTENSIONS); ++ gl_npot = ext && strstr(ext, "GL_OES_texture_npot"); ++ sysLogPrintf(LOG_NOTE, "GL: OES_texture_npot: %s", gl_npot ? "yes" : "no"); ++ } ++#endif ++ if (!gl_es && !gfx_opengl_supports_shaders()) { + sysLogPrintf(LOG_WARNING, "GL: GLSL 1.30 may be unsupported"); + // maybe replace this with sysFatalError, though the GLSL compiler will cause that later anyway + } +@@ -1552,12 +1655,16 @@ static void gfx_opengl_init(void) { + } + snprintf(gl_glsl_version_str, sizeof(gl_glsl_version_str), "%d core", gl_glsl_version); + } ++#ifdef USE_GLES2 ++ gl_glsl_version = 100; ++ snprintf(gl_glsl_version_str, sizeof(gl_glsl_version_str), "100"); ++#endif + sysLogPrintf(LOG_NOTE, "GL: using GLSL version %s", gl_glsl_version_str); + + glGenBuffers(1, &opengl_vbo); + glBindBuffer(GL_ARRAY_BUFFER, opengl_vbo); + +- if (gl_core_profile || gl_es) { ++ if (gl_core_profile || (gl_es && glGenVertexArrays != NULL)) { + // warn user that funny things can happen + sysLogPrintf(LOG_WARNING, "GL: using core profile or ES, watch out for errors"); + // core/es will explode if we don't use a VAO for our VBO +@@ -1747,6 +1854,11 @@ static void gfx_opengl_update_framebuffer_parameters(int fb_id, uint32_t width, + } + + bool gfx_opengl_start_draw_to_framebuffer(int fb_id, float noise_scale) { ++#ifdef USE_GLES2 ++ if (!gfx_framebuffers_enabled && noise_scale != 0.0f) { ++ current_noise_scale = 1.0f / noise_scale; ++ } ++#endif + if (gfx_framebuffers_enabled && fb_id < (int)framebuffers.size()) { + Framebuffer& fb = framebuffers[fb_id]; + if (noise_scale != 0.0f) { +@@ -1962,6 +2074,11 @@ void gfx_opengl_copy_framebuffer(int fb_dst, int fb_src, int left, int top, bool + } + + void gfx_opengl_set_texture_filter(FilteringMode mode) { ++#ifdef USE_GLES2 ++ if (mode == FILTER_THREE_POINT) { ++ mode = FILTER_LINEAR; ++ } ++#endif + current_filter_mode = mode; + } + +@@ -2033,6 +2150,8 @@ struct GlRetainedProgram { + int num_attribs = 0; + GLint u_mats, u_mats1, u_fixup, u_fogp, u_fogsel, u_fogrgb, u_decal, u_light, u_shade, u_kind, u_prim, u_env, u_lod; + GLint frame_count_location, noise_scale_location, three_point_filter_locations[2]; ++ GLint tex_size_locations[2] = { -1, -1 }; ++ float tex_size_pushed[2][2] = { { -1.0f, -1.0f }, { -1.0f, -1.0f } }; + /* uniform value cache: a program object keeps its uniforms between binds, + * so a retained draw uploads only what changed since this program's last + * one (the per-draw GL call count is the PC's cost, not the triangles) */ +@@ -2132,6 +2251,8 @@ static GlRetainedProgram* gl_ret_program_get(struct ShaderProgram* prg) { + } + if (cc.opt_ge_farclip || cc.opt_ge_pixfog) { + append_line(vs_buf, &vs_len, "OUTPUT vec2 vGeZw;"); ++ if (gl_glsl_version < 130) ++ append_line(vs_buf, &vs_len, "OUTPUT float vGeFar;"); + } + if (cc.opt_ge_pixfog) { + append_line(vs_buf, &vs_len, "INPUT vec2 aGeFogP;"); +@@ -2210,13 +2331,15 @@ static GlRetainedProgram* gl_ret_program_get(struct ShaderProgram* prg) { + } + if (cc.opt_ge_farclip || cc.opt_ge_pixfog) { + append_line(vs_buf, &vs_len, " vGeZw = clip.zw;"); ++ if (gl_glsl_version < 130) ++ append_line(vs_buf, &vs_len, " vGeFar = clip.w - clip.z;"); + } + if (cc.opt_ge_pixfog) { + append_line(vs_buf, &vs_len, " vGeFogP = uFogP.xy * 255.0;"); /* the frame's registers, not the captured pair */ + } + append_line(vs_buf, &vs_len, " gl_Position = clip;"); + if (!GLAD_GL_ARB_depth_clamp) { +- append_line(vs_buf, &vs_len, " gl_Position.z *= 0.3f;"); ++ append_line(vs_buf, &vs_len, " gl_Position.z *= 0.3;"); + } + append_line(vs_buf, &vs_len, "}"); + vs_buf[vs_len] = '\0'; +@@ -2314,6 +2437,8 @@ static GlRetainedProgram* gl_ret_program_get(struct ShaderProgram* prg) { + rp.noise_scale_location = glGetUniformLocation(program, "noise_scale"); + rp.three_point_filter_locations[0] = glGetUniformLocation(program, "three_point_filter0"); + rp.three_point_filter_locations[1] = glGetUniformLocation(program, "three_point_filter1"); ++ rp.tex_size_locations[0] = glGetUniformLocation(program, "uTexSize0"); ++ rp.tex_size_locations[1] = glGetUniformLocation(program, "uTexSize1"); + /* back to the interpreter's program: the caller expects it current */ + if (gl_current_prg != nullptr) { + glUseProgram(gl_current_prg->opengl_program_id); +@@ -2593,9 +2718,9 @@ static void gl_ret_draw(int desc, const uint16_t* idx, uint32_t nidx, const floa + glUniform1iv(rp->u_kind, d.prg->num_inputs, kinds); + } + } +- if (rp->frame_count_location >= 0 && rp->c_frame_count != (GLint)frame_count) { +- rp->c_frame_count = (GLint)frame_count; +- glUniform1i(rp->frame_count_location, frame_count); ++ if (rp->frame_count_location >= 0 && rp->c_frame_count != GL_FRAME_COUNT) { ++ rp->c_frame_count = GL_FRAME_COUNT; ++ glUniform1i(rp->frame_count_location, GL_FRAME_COUNT); + } + if (rp->noise_scale_location >= 0 && rp->c_noise != current_noise_scale) { + rp->c_noise = current_noise_scale; +@@ -2607,6 +2732,7 @@ static void gl_ret_draw(int desc, const uint16_t* idx, uint32_t nidx, const floa + glUniform1i(rp->three_point_filter_locations[t], current_textures_linear_filter[t]); + } + } ++ gl_sync_tex_size(rp->tex_size_locations, rp->tex_size_pushed); + rp->c_valid = true; + /* Backface cull on the GPU: front = COUNTER-clockwise in GL's y-up window + * space, verified against a cull-off reference. The clockwise reading of +@@ -2676,6 +2802,20 @@ extern "C" void gfx_opengl_retained_stats(unsigned* draws, unsigned* tris, unsig + gl_ret_dbg_draws = gl_ret_dbg_tris = 0; + } + ++static void gl_sync_tex_size(const GLint loc[2], float pushed[2][2]) { ++ for (int t = 0; t < 2; t++) { ++ if (loc[t] >= 0) { ++ float sz[2]; ++ gl_tex_size_of(current_texture_ids[t], sz); ++ if (pushed[t][0] != sz[0] || pushed[t][1] != sz[1]) { ++ pushed[t][0] = sz[0]; ++ pushed[t][1] = sz[1]; ++ glUniform2f(loc[t], sz[0], sz[1]); ++ } ++ } ++ } ++} ++ + static struct ShaderProgram* gl_current_prg_set(struct ShaderProgram* prg) { + gl_current_prg = prg; + return prg; +diff --git a/port/fast3d/gfx_sdl2.cpp b/port/fast3d/gfx_sdl2.cpp +index 52a8146..841b240 100644 +--- a/port/fast3d/gfx_sdl2.cpp ++++ b/port/fast3d/gfx_sdl2.cpp +@@ -325,7 +325,11 @@ static void gfx_sdl_init(const struct GfxWindowInitSettings *set) { + } + + // we will unhide the window once the GL context is successfully created ++#ifdef USE_GLES2 ++ Uint32 flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL; ++#else + Uint32 flags = SDL_WINDOW_HIDDEN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL; ++#endif + + // if fullscreen was requested, start the window in fullscreen right away + if (set->fullscreen) { +@@ -383,6 +387,12 @@ static void gfx_sdl_init(const struct GfxWindowInitSettings *set) { + + // ideally we need 3.0 compat + // if that doesn't work, try 3.2 core in case we're on mac, 2.1 compat as a last resort ++#ifdef USE_GLES2 ++ static u32 glver[][3] = { ++ { 0, 0, 0 }, // for command line override ++ { 2, 0, SDL_GL_CONTEXT_PROFILE_ES }, ++ }; ++#else + static u32 glver[][3] = { + { 0, 0, 0 }, // for command line override + { 3, 0, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY }, // 3.0: default, has all the features required +@@ -391,6 +401,7 @@ static void gfx_sdl_init(const struct GfxWindowInitSettings *set) { + { 3, 0, SDL_GL_CONTEXT_PROFILE_ES }, // es3: don't really support ES properly, but we can try + { 2, 1, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY }, // 2.1: absolute last resort, will still require GLSL130 as an extension + }; ++#endif + + u32 verstart = 1; + const u32 verend = sizeof(glver) / sizeof(*glver); +@@ -794,7 +805,21 @@ static void gfx_sdl_maybe_screenshot(void) { + uint8_t *px = (uint8_t *)SDL_calloc(1, padded * h); + if (!px) return; + glPixelStorei(GL_PACK_ALIGNMENT, 1); ++#ifdef USE_GLES2 ++ { ++ uint8_t *rgba = (uint8_t *)SDL_malloc((size_t)w * h * 4); ++ if (!rgba) { SDL_free(px); return; } ++ glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, rgba); ++ for (size_t i = 0; i < (size_t)w * h; i++) { ++ px[i * 3 + 0] = rgba[i * 4 + 0]; ++ px[i * 3 + 1] = rgba[i * 4 + 1]; ++ px[i * 3 + 2] = rgba[i * 4 + 2]; ++ } ++ SDL_free(rgba); ++ } ++#else + glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, px); ++#endif + /* repack in place bottom-up rows into padded stride, RGB->BGR */ + for (int y = h - 1; y >= 0; y--) { + uint8_t *src = px + (size_t)y * stride; +diff --git a/port/src/main.c b/port/src/main.c +index 71ff41d..145b875 100644 +--- a/port/src/main.c ++++ b/port/src/main.c +@@ -514,6 +514,36 @@ static void portArmWatchpoints(void) + } + #else + #include ++#if defined(__arm__) ++#include ++#include ++#include ++#include ++extern char __executable_start[], etext[]; ++static void portCrashHandlerArm(int sig, siginfo_t *si, void *ucv) ++{ ++ const ucontext_t *uc = (const ucontext_t *) ucv; ++ const struct sigcontext *m = &uc->uc_mcontext; ++ const unsigned long *sp = (const unsigned long *) m->arm_sp; ++ int i, k = 0; ++ ++ fprintf(stderr, "\nge: fatal signal %d (thread %ld) at pc 0x%08lx lr 0x%08lx sp 0x%08lx, fault address %p\n", ++ sig, (long) syscall(SYS_gettid), m->arm_pc, m->arm_lr, m->arm_sp, si->si_addr); ++ fprintf(stderr, "ge: r0 %08lx r1 %08lx r2 %08lx r3 %08lx r4 %08lx r5 %08lx r6 %08lx r7 %08lx\n", ++ m->arm_r0, m->arm_r1, m->arm_r2, m->arm_r3, m->arm_r4, m->arm_r5, m->arm_r6, m->arm_r7); ++ fprintf(stderr, "ge: r8 %08lx r9 %08lx r10 %08lx fp %08lx ip %08lx\nge: return addresses on the stack:", ++ m->arm_r8, m->arm_r9, m->arm_r10, m->arm_fp, m->arm_ip); ++ for (i = 0; i < 512 && k < 24; i++) { ++ if (sp[i] >= (unsigned long) __executable_start && sp[i] < (unsigned long) etext) { ++ fprintf(stderr, " %08lx", sp[i]); ++ k++; ++ } ++ } ++ fprintf(stderr, "\n"); ++ fflush(NULL); ++ _exit(128 + sig); ++} ++#endif + + /* Bring-up crash handler: print a raw backtrace (addresses decode with + * addr2line -e build_pc/ge) so crashes are diagnosable without gdb. */ +@@ -793,6 +823,18 @@ int main(int argc, char **argv) + #endif + signal(SIGFPE, portCrashHandler); + signal(SIGILL, portCrashHandler); ++#if defined(__arm__) && !defined(_WIN32) ++ { ++ struct sigaction sa; ++ memset(&sa, 0, sizeof(sa)); ++ sa.sa_sigaction = portCrashHandlerArm; ++ sa.sa_flags = SA_SIGINFO; ++ sigaction(SIGSEGV, &sa, NULL); ++ sigaction(SIGBUS, &sa, NULL); ++ sigaction(SIGILL, &sa, NULL); ++ sigaction(SIGFPE, &sa, NULL); ++ } ++#endif + #ifdef _WIN32 + /* GE_STALLTEST=1: park the main thread here forever so the stall + * watchdog's boot-grace path + loader-lock-free module naming can be +diff --git a/port/src/video.c b/port/src/video.c +index b883b42..8dcb2fa 100644 +--- a/port/src/video.c ++++ b/port/src/video.c +@@ -71,7 +71,11 @@ static int s_CfgWidescreen = 1; /* 0 Stretch, 1 Wide (widen FOV to the win + /* [display] render_thread: -1 auto (on when tickhz != 60), 0 off, 1 on; GE_RENDERTHREAD + * overrides. Re-applied at the next frame boundary when it or the tick changes + * (see portRenderThreadFollowTick). */ ++#ifdef USE_GLES2 ++static int s_CfgRenderThread = 1; ++#else + static int s_CfgRenderThread = -1; ++#endif + static int s_CfgAdzy = 0; /* [display] adzy: Siberian Special Forces + snow cuff */ + static int s_CfgUnlockAll = 0; /* [display] unlock_all: every mission/difficulty/cheat available */ + static int s_CfgPausePillars = 0; /* [display] pause_pillars: animated 4:3 pillarbox while the watch is up */ +@@ -4904,6 +4908,7 @@ s32 videoInit(void) + s_CfgTriHoist = (e[0] != '0'); + gfx_tri_hoist = s_CfgTriHoist ? 1u : 0u; + } ++ portRoomCacheSetMode(s_CfgRoomCache); + portConLogf("ge: video: room_cache=%d tri_hoist=%d\n", s_CfgRoomCache, s_CfgTriHoist); + } + { /* [display] hw_mipmaps: N64 mip chains on G_TL_LOD draws (reduces Low Res +diff --git a/src/game/stan.c b/src/game/stan.c +index df375ec..b323780 100644 +--- a/src/game/stan.c ++++ b/src/game/stan.c +@@ -163,7 +163,7 @@ const char aStanlinelog[] = "-stanlinelog"; + // forward declarations + + s32 stanIsSpecialBit1Set(StandTile *arg0, struct StandTileLocusCallbackRecord* arg1); +-s32 stanCheckLinkedSpecialTile(StandTile *tile, s32 pointIdx, s32 arg2, s32 arg3, s32 arg4, s32 *outFlags); ++s32 stanCheckLinkedSpecialTile(StandTile *tile, s32 pointIdx, f32 arg2, f32 arg3, f32 arg4, s32 *outFlags); + s32 sub_GAME_7F0B21B0(StandTile **tileStack, f32 target_x, f32 target_z, f32 radius, s32 *rooms, s32 *count_rtn, s32 bufMax); + f32 getShortest2dDispToInfTripleEdge(StandTile *tile, s32 start3index, f32 p_x, f32 p_z); + StanCollisionResult sub_GAME_7F0B1DDC(struct StandTile**, f32, f32, f32, standTileLocusCallback_A_t, standTileLocusCallback_B_t, standTileLocusCallback_C_t, struct StandTileLocusCallbackRecord*); +@@ -2716,7 +2716,7 @@ s32 stanIsSpecialBit1Set(StandTile *arg0, struct StandTileLocusCallbackRecord *a + /** + * Address: 7F0B2274 + */ +-s32 stanCheckLinkedSpecialTile(StandTile *tile, s32 pointIdx, s32 arg2, s32 arg3, s32 arg4, s32 *outFlags) ++s32 stanCheckLinkedSpecialTile(StandTile *tile, s32 pointIdx, f32 arg2, f32 arg3, f32 arg4, s32 *outFlags) + { + u16 link; + StandTile *target; +diff --git a/tools/gamecontrollerdefault.txt b/tools/gamecontrollerdefault.txt +index a7d777e..8f5ee5a 100644 +--- a/tools/gamecontrollerdefault.txt ++++ b/tools/gamecontrollerdefault.txt +@@ -79,6 +79,8 @@ + # The N64-adapter layouts below are not paired: an N64 pad has only N64 + # controls, so its Standard and its Pro would be the same line. + ++RetroStone2 | name=RetroStoneOS Gamepad, n64 | stick_x=leftx+; stick_y=lefty-; a=a; b=b; z=righttrigger,x; r=rightshoulder,y; l=leftshoulder,lefttrigger; start=start; c_up=dpup; c_down=dpdown; c_left=dpleft; c_right=dpright ++ + NSO N64 (BT) | name=Nintendo N64 Controller, n64 | stick_x=leftx+; stick_y=lefty-; a=a; b=b; z=lefttrigger; start=start; l=leftshoulder; r=rightshoulder; c_up=y; c_down=righttrigger; c_left=x; c_right=back; dpad_up=dpup; dpad_down=dpdown; dpad_left=dpleft; dpad_right=dpright + + 8BitDo 64 (DInput) | name=8BitDo 64, n64 | stick_x=leftx+; stick_y=lefty-; a=a; b=b; z=lefttrigger,righttrigger; start=start; l=leftshoulder; r=rightshoulder; c_up=b15; c_down=b16; c_left=b18; c_right=b19; dpad_up=dpup; dpad_down=dpdown; dpad_left=dpleft; dpad_right=dpright diff --git a/ports/sm64/README.md b/ports/sm64/README.md new file mode 100644 index 0000000..56427ff --- /dev/null +++ b/ports/sm64/README.md @@ -0,0 +1,83 @@ +# Super Mario 64 on the RetroStone2 (native, built from your own ROM) + +This folder builds [sm64-port](https://github.com/sm64-port/sm64-port) (the PC port of the Super Mario 64 +decompilation) for RetroStoneOS, where it runs as a **native game**: ARM code with the Mali-400 GPU (GLES2), no N64 +emulator (docs/native-games.md). + +**Nothing from the game is in this repository, in the OS images or in the System updates.** The build takes the +game's data from **your own ROM**, on your PC, and the result is yours alone: copy it to your own SD card, never +publish it (not in a release, an update, a fork or a download link). + +## What you need + +* A PC with Linux or WSL (Ubuntu), the usual build tools (`build-essential`, `git`, `python3`) and a built + RetroStoneOS tree for the RetroStone2 with SDL2 (`retrostone2_release_defconfig`; `~/rsos/output` or + `RSOS_OUTPUT=`). +* Your Super Mario 64 ROM, **US** version, `.z64` byte order (SHA-1 `9bef1128717f958171a4afac3ed78ee2bb4e86ce`). +* A RetroStoneOS with "Native games" on the console (it brings SDL2). + +## Build + +```sh +ports/sm64/build-sm64.sh ~/baserom.us.z64 ~/sm64-retrostone2 +``` + +It clones sm64-port at a fixed commit into `~/rsos/sm64-work`, applies `retrostone2.patch` and adds +`controller_rsos.c`, builds the asset tools for the PC and the game for the console (`TARGET_LINUX_KMSDRM=1`, +the RetroStoneOS cross compiler), and writes: + +``` +~/sm64-retrostone2/roms/native/Super Mario 64.sh +~/sm64-retrostone2/roms/native/sm64/sm64.us +``` + +## Install + +Put the console's SD card in the PC and copy the `roms` folder onto the **RETROSTONE** partition (it merges with +the `roms` folder already there), or use the menu's USB import. In the menu: **Native games > Super Mario 64**. + +## Controls + +The buttons are **the same as the N64 emulator** (parallel_n64), so Mario plays the same natively and emulated, +and the N64 button settings are global: Mario follows the remap you make for N64 in the emulator's in-game menu +(`rsos/remaps/n64.ini` on the card; `n64-cz.ini` when "C/Z buttons fitted" is on) and the N64 core option +**Independent C-button Controls**. + +| RetroStone2 | N64 (default) | N64 (Independent C-button Controls on) | +|---|---|---| +| B (bottom) | A | A | +| Y (left) | B | B | +| L2 | Z | Z | +| L1 / R1 | L / R | C-left / C-right | +| A (right) / X (top) | (with R2: C-right / C-up) | C-down / C-up | +| R2 | hold: B, Y, A, X become C-down, C-left, C-right, C-up | R | +| Select | | L | +| Start | Start | Start | +| Analog stick (Pro), or the D-pad | the stick | the stick | + +For Super Mario 64, **Independent C-button Controls** is the comfortable one (L1/R1 turn the camera, R2 is R): +in any N64 game, open the in-game menu, Core options, turn it on and choose **Save for all games**; both the +emulator and native Mario use it from then on. ("Save for this game" keeps it to that one ROM only.) Mario reads +these settings when it starts. + +**Select + Start** goes back to the menu at once, as in the emulators (the save file is written whenever the game +saves). A USB pad works too (SDL: bottom = A, left = B, the +shoulders = Z/R, the right stick = C buttons). + +Saves (`sm64_save_file.bin`) and settings (`sm64config.txt`) stay in `roms/native/sm64/`. The game saves on its +own (each star); quitting or the power key never loses a saved star. + +## What the patch changes in sm64-port + +* `TARGET_LINUX_KMSDRM=1`: SDL2 on KMS/DRM with a GLES2 context (`#version 100` shaders with + `precision mediump float`), ALSA, no X11/PulseAudio/Wii U adapter, no `-march=native`; `CROSS_PC` (the + compiler of the game only, the asset tools keep the PC's) and `SDL2_CONFIG`. +* `controller_rsos.c`: the console's three input devices (buttons, shoulder buttons, analog stick) read + together from `/dev/input`; `controller_sdl` leaves them alone and keeps USB pads. +* `tools/armips.cpp`: `` for newer host compilers. + +## Status + +**Works on a RetroStone2 Pro**: full speed, it looks great. The analog stick moves Mario on the Pro; the D-pad +moves him whenever the stick is centred or not fitted. If something goes wrong, the game's messages are in +`rsos/logs/boot/game.log` on the SD card. diff --git a/ports/sm64/Super Mario 64.sh b/ports/sm64/Super Mario 64.sh new file mode 100644 index 0000000..96068ce --- /dev/null +++ b/ports/sm64/Super Mario 64.sh @@ -0,0 +1,8 @@ +#!/bin/sh +# Super Mario 64 (sm64-port, built from your own ROM by ports/sm64/build-sm64.sh). +# Saves (sm64_save_file.bin) and settings (sm64config.txt) stay in sm64/. +cd sm64 || exit 1 +if [ -x ./sm64.us ]; then + exec ./sm64.us +fi +exec /lib/ld-linux-armhf.so.3 ./sm64.us diff --git a/ports/sm64/build-sm64.sh b/ports/sm64/build-sm64.sh new file mode 100755 index 0000000..64deba0 --- /dev/null +++ b/ports/sm64/build-sm64.sh @@ -0,0 +1,67 @@ +#!/bin/bash +# Builds Super Mario 64 (sm64-port) for RetroStoneOS from YOUR OWN ROM, on the +# PC (Linux/WSL), as a native game for the SD card (docs/native-games.md). +# +# ports/sm64/build-sm64.sh [output folder] +# +# Needs a built RetroStoneOS tree with SDL2 (the cross compiler and the +# staging libraries): ~/rsos/output, or RSOS_OUTPUT=. The sm64-port +# source is cloned at a fixed commit into ~/rsos/sm64-work (RSOS_SM64_WORK) +# and patched (retrostone2.patch, controller_rsos.c). +# +# The result contains the game's data, taken from your ROM: keep it for +# yourself. Never put it in a release, an update or a repository. +# +# Output (default ./sm64-retrostone2): roms/native/Super Mario 64.sh and +# roms/native/sm64/sm64.us. Copy the "roms" folder onto the SD card's +# RETROSTONE partition (it merges with the roms folder there). +set -euo pipefail + +SM64_REPO=https://github.com/sm64-port/sm64-port.git +SM64_COMMIT=2b17d08 # "Fix GCC 14 build on MinGW" +US_SHA1=9bef1128717f958171a4afac3ed78ee2bb4e86ce + +here=$(cd "$(dirname "$0")" && pwd) +rom=${1:-} +out=${2:-$PWD/sm64-retrostone2} +O=${RSOS_OUTPUT:-$HOME/rsos/output} +W=${RSOS_SM64_WORK:-$HOME/rsos/sm64-work} + +die() { echo "build-sm64: $*" >&2; exit 1; } + +[ -n "$rom" ] || die "usage: $0 [output folder]" +[ -f "$rom" ] || die "$rom: no such file" +rom=$(cd "$(dirname "$rom")" && pwd)/$(basename "$rom") +case "$out" in /*) ;; *) out=$PWD/$out ;; esac +sum=$(sha1sum "$rom" | cut -d' ' -f1) +[ "$sum" = "$US_SHA1" ] || die "$rom is not the US Super Mario 64 ROM in .z64 (big-endian) order (SHA-1 $sum)" +[ -x "$O/host/bin/arm-linux-gcc" ] || die "no cross compiler in $O/host/bin (build RetroStoneOS first)" +SDL2_CONFIG=$O/staging/usr/bin/sdl2-config +[ -x "$SDL2_CONFIG" ] || die "no SDL2 in $O/staging (build RetroStoneOS with BR2_PACKAGE_SDL2)" + +if [ ! -d "$W/.git" ]; then + git clone -q "$SM64_REPO" "$W" +fi +cd "$W" +git fetch -q origin 2> /dev/null || true +# a clean tree at the fixed commit, then our changes (the extracted assets +# and the build folder stay: they are ignored by git) +git checkout -q -f "$SM64_COMMIT" +git clean -q -f -- src tools Makefile +git apply "$here/retrostone2.patch" +cp "$here/controller_rsos.c" "$here/controller_rsos.h" src/pc/controller/ +cp "$rom" baserom.us.z64 + +# the asset tools for this PC (with its own compiler), then the game for the +# console (CROSS_PC: the game's compiler only) +make -C tools -j"$(nproc)" all-except-recomp +make -j"$(nproc)" VERSION=us TARGET_LINUX_KMSDRM=1 CROSS_PC="$O/host/bin/arm-linux-" SDL2_CONFIG="$SDL2_CONFIG" + +file build/us_pc/sm64.us | grep -q 'ARM' || die "build/us_pc/sm64.us is not an ARM program" +mkdir -p "$out/roms/native/sm64" +"$O/host/bin/arm-linux-strip" -o "$out/roms/native/sm64/sm64.us" build/us_pc/sm64.us +install -m 0644 "$here/Super Mario 64.sh" "$out/roms/native/Super Mario 64.sh" +echo +echo "Done: $out/roms" +echo "Copy that \"roms\" folder onto the SD card's RETROSTONE partition, then in the menu:" +echo "Native games > Super Mario 64. Select + Start quits." diff --git a/ports/sm64/controller_rsos.c b/ports/sm64/controller_rsos.c new file mode 100644 index 0000000..d65c038 --- /dev/null +++ b/ports/sm64/controller_rsos.c @@ -0,0 +1,411 @@ +/* + * controller_rsos.c - the RetroStone2's built-in controls for sm64-port + * (RetroStoneOS native games, ports/sm64). + * + * The console's controls are three evdev devices: "RetroStone2 Buttons" + * (face buttons, D-pad, Start/Select), "RetroStone2 Shoulder Buttons" (L1, + * R1, L2, R2) and the optional analog stick ("analog-stick"). They are read + * here together, straight from /dev/input; controller_sdl leaves them + * alone (it would see three separate pads) and keeps USB pads. + * + * The buttons follow the N64 emulator (parallel_n64), so Mario plays the + * same natively and emulated, and the N64 button settings are global: + * 1. physical button -> RetroPad, as the menu's input layer does + * (bottom = B, right = A, top = X, left = Y, C/Z = L3/R3); + * 2. the N64 remap made in the emulator's in-game menu, in the same files + * and order (/data/rsos/remaps/n64[-cz].ini, then the shipped one in + * /usr/share/rsos/remaps; -cz first when "C/Z buttons fitted" is on); + * 3. RetroPad -> N64 as parallel_n64 maps it, following its core option + * "Independent C-button Controls" (parallel-n64-alt-map, from + * /data/rsos/coreopts/parallel_n64.ini or the shipped defaults): + * off (default): B = A, Y = B, L2 = Z, L = L, R = R, Start; + * R2 held: A = C-right, Y = C-left, B = C-down, + * X = C-up (the core's "C buttons mode") + * on: B = A, Y = B, L2 = Z, R2 = R, Select = L, Start, + * R = C-right, L = C-left, A = C-down, X = C-up + * The analog stick (Pro) moves Mario; the D-pad does too while the stick is + * centred or not fitted (Super Mario 64 has no use for the N64 D-pad). + * Select+Start stays the menu's: held, it quits the game. + */ +#if defined(__linux__) && defined(TARGET_LINUX_KMSDRM) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "controller_api.h" +#include "controller_rsos.h" + +#define MAX_DEVS 8 +#define STICK_DEADZONE 0.15f /* of the half range */ +#define DATA "/data/rsos" +#define SHIP "/usr/share/rsos" + +/* RetroPad ids, in the menu's order (input.h enum input_btn) */ +enum { RP_B, RP_Y, RP_SELECT, RP_START, RP_UP, RP_DOWN, RP_LEFT, RP_RIGHT, + RP_A, RP_X, RP_L, RP_R, RP_L2, RP_R2, RP_L3, RP_R3, RP_NUM }; + +static const char *const rp_names[RP_NUM] = { + "b", "y", "select", "start", "up", "down", "left", "right", + "a", "x", "l", "r", "l2", "r2", "l3", "r3", +}; + +/* the built-in buttons, as the menu's input layer maps them */ +static const struct { int code, rp; } builtin_keys[] = { + { BTN_SOUTH, RP_B }, { BTN_EAST, RP_A }, { BTN_NORTH, RP_X }, { BTN_WEST, RP_Y }, + { BTN_TL, RP_L }, { BTN_TR, RP_R }, { BTN_TL2, RP_L2 }, { BTN_TR2, RP_R2 }, + { BTN_SELECT, RP_SELECT }, { BTN_START, RP_START }, { BTN_C, RP_L3 }, { BTN_Z, RP_R3 }, + { BTN_DPAD_UP, RP_UP }, { BTN_DPAD_DOWN, RP_DOWN }, { BTN_DPAD_LEFT, RP_LEFT }, + { BTN_DPAD_RIGHT, RP_RIGHT }, +}; + +struct rsos_dev { + int fd; + bool has_stick; + struct input_absinfo ax, ay; +}; + +static struct rsos_dev devs[MAX_DEVS]; +static int ndevs; +static bool keys[KEY_MAX + 1]; +static int abs_x, abs_y; +static unsigned char remap[RP_NUM]; /* physical RetroPad id -> RetroPad id, 0xff = none */ +static bool alt_map; + +/* ------------------------------------------------------------- ini files */ + +static char *trim(char *s) { + char *e; + + while (isspace((unsigned char)*s)) { + s++; + } + e = s + strlen(s); + while (e > s && isspace((unsigned char)e[-1])) { + *--e = 0; + } + return s; +} + +/* calls fn(section, key, value, user) for every key = value line; false if + * the file cannot be read */ +static bool ini_each(const char *path, void (*fn)(const char *, const char *, const char *, void *), + void *user) { + FILE *f = fopen(path, "r"); + char line[512], section[64] = ""; + + if (f == NULL) { + return false; + } + while (fgets(line, sizeof(line), f) != NULL) { + char *c, *k, *v, *eq; + + if ((c = strchr(line, ';')) != NULL) *c = 0; + if ((c = strchr(line, '#')) != NULL) *c = 0; + k = trim(line); + if (k[0] == '[') { + snprintf(section, sizeof(section), "%s", k); + continue; + } + if ((eq = strchr(k, '=')) == NULL) { + continue; + } + *eq = 0; + v = trim(eq + 1); + k = trim(k); + if (v[0] == '"' && strlen(v) >= 2 && v[strlen(v) - 1] == '"') { + v[strlen(v) - 1] = 0; + v++; + } + fn(section, k, v, user); + } + fclose(f); + return true; +} + +static int rp_id(const char *name) { + for (int i = 0; i < RP_NUM; i++) { + if (!strcasecmp(name, rp_names[i])) { + return i; + } + } + if (!strcasecmp(name, "l1")) return RP_L; + if (!strcasecmp(name, "r1")) return RP_R; + return -1; +} + +static void remap_line(const char *section, const char *k, const char *v, void *user) { + int from = rp_id(k), to = rp_id(v); + + (void)user; + if (strcmp(section, "[remap]") != 0 && section[0] != 0) { + return; /* [options]: dpad_to_analog is always on here */ + } + if (from >= 0 && (to >= 0 || !strcasecmp(v, "none"))) { + remap[from] = to >= 0 ? (unsigned char)to : 0xff; + } +} + +static void flag_line(const char *section, const char *k, const char *v, void *user) { + const char **want = user; + + (void)section; + if (!strcmp(k, want[0])) { + want[1] = (!strcmp(v, "1") || !strcasecmp(v, "true") || !strcasecmp(v, "yes") || + !strcasecmp(v, "on") || !strcasecmp(v, "enabled")) ? "1" : "0"; + } +} + +/* "1"/"0" for key in the first file that has it, NULL if none does */ +static const char *ini_flag(const char *key, const char *const *paths, int n) { + static const char *want[2]; + + for (int i = 0; i < n; i++) { + want[0] = key; + want[1] = NULL; + if (ini_each(paths[i], flag_line, want) && want[1] != NULL) { + return want[1]; + } + } + return NULL; +} + +/* the emulator's N64 button settings (see the top of this file) */ +static void load_n64_settings(void) { + static const char *const settings[] = { DATA "/settings.ini" }; + static const char *const coreopts[] = { DATA "/coreopts/parallel_n64.ini", SHIP "/coreopts/parallel_n64.ini" }; + const char *cz = ini_flag("cz_buttons", settings, 1); + const char *am = ini_flag("parallel-n64-alt-map", coreopts, 2); + char cand[4][128]; + int n = 0; + + for (int i = 0; i < RP_NUM; i++) { + remap[i] = (unsigned char)i; + } + if (cz != NULL && cz[0] == '1') { + snprintf(cand[n++], sizeof(cand[0]), DATA "/remaps/n64-cz.ini"); + } + snprintf(cand[n++], sizeof(cand[0]), DATA "/remaps/n64.ini"); + if (cz != NULL && cz[0] == '1') { + snprintf(cand[n++], sizeof(cand[0]), SHIP "/remaps/n64-cz.ini"); + } + snprintf(cand[n++], sizeof(cand[0]), SHIP "/remaps/n64.ini"); + for (int i = 0; i < n; i++) { + if (ini_each(cand[i], remap_line, NULL)) { + fprintf(stderr, "controller_rsos: N64 remap %s\n", cand[i]); + break; + } + } + alt_map = am != NULL && am[0] == '1'; + fprintf(stderr, "controller_rsos: independent C buttons %s\n", alt_map ? "on" : "off"); +} + +/* ------------------------------------------------------------- devices */ + +static void controller_rsos_init(void) { + DIR *d = opendir("/dev/input"); + struct dirent *de; + + load_n64_settings(); + if (d == NULL) { + return; + } + while ((de = readdir(d)) != NULL && ndevs < MAX_DEVS) { + char path[300], name[128] = ""; + unsigned long absbits[(ABS_MAX + 8 * sizeof(long)) / (8 * sizeof(long))] = { 0 }; + int fd; + + if (strncmp(de->d_name, "event", 5) != 0) { + continue; + } + snprintf(path, sizeof(path), "/dev/input/%s", de->d_name); + fd = open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC); + if (fd < 0) { + continue; + } + /* the buttons are "RetroStone2 ...", the stick (adc-joystick) is + * named after its device tree node, as in the menu's board.ini */ + if (ioctl(fd, EVIOCGNAME(sizeof(name)), name) < 0 || + (strcmp(name, "analog-stick") != 0 && + (strncmp(name, "RetroStone2", 11) != 0 || strstr(name, "Brightness") != NULL))) { + close(fd); + continue; + } + devs[ndevs].fd = fd; + ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbits)), absbits); + if ((absbits[ABS_X / (8 * sizeof(long))] >> (ABS_X % (8 * sizeof(long)))) & 1) { + devs[ndevs].has_stick = ioctl(fd, EVIOCGABS(ABS_X), &devs[ndevs].ax) == 0 && + ioctl(fd, EVIOCGABS(ABS_Y), &devs[ndevs].ay) == 0 && + devs[ndevs].ax.maximum != devs[ndevs].ax.minimum && + devs[ndevs].ay.maximum != devs[ndevs].ay.minimum; + if (devs[ndevs].has_stick) { + abs_x = devs[ndevs].ax.value; + abs_y = devs[ndevs].ay.value; + } + } + fprintf(stderr, "controller_rsos: %s (%s)%s\n", path, name, + devs[ndevs].has_stick ? ", analog stick" : ""); + ndevs++; + } + closedir(d); +} + +static bool axis_in_range(int v, const struct input_absinfo *a, bool near_centre) { + int lo = a->minimum < a->maximum ? a->minimum : a->maximum; + int hi = a->minimum < a->maximum ? a->maximum : a->minimum; + + if (near_centre) { + return abs(v - (lo + (hi - lo) / 2)) <= (hi - lo) / 4; + } + return v >= lo && v <= hi; +} + +/* + * Fitted or not, as the menu decides (input.c): a reading out of range means + * no stick (the ADC inputs float above it); fitted again only once both axes + * read near the centre (floating inputs can wander into the range near an + * edge and would hold a direction). + */ +static bool stick_fitted(const struct rsos_dev *sd) { + static bool fitted; + + if (!axis_in_range(abs_x, &sd->ax, false) || !axis_in_range(abs_y, &sd->ay, false)) { + if (fitted) { + fprintf(stderr, "controller_rsos: analog stick reads %d, %d: not fitted\n", abs_x, abs_y); + } + fitted = false; + } else if (!fitted && axis_in_range(abs_x, &sd->ax, true) && axis_in_range(abs_y, &sd->ay, true)) { + fprintf(stderr, "controller_rsos: analog stick fitted (%d, %d)\n", abs_x, abs_y); + fitted = true; + } + return fitted; +} + +/* -1..1 from an axis, 0 in the dead zone */ +static float stick_axis(int v, const struct input_absinfo *a) { + int lo = a->minimum < a->maximum ? a->minimum : a->maximum; + int hi = a->minimum < a->maximum ? a->maximum : a->minimum; + float half = (hi - lo) / 2.0f, f; + + if (half <= 0) { + return 0; + } + f = (v - (lo + half)) / half; + if (f > -STICK_DEADZONE && f < STICK_DEADZONE) { + return 0; + } + return f; +} + +static void controller_rsos_read(OSContPad *pad) { + const struct rsos_dev *sd = NULL; + struct input_event ev; + bool rp[RP_NUM] = { false }; + int dx, dy; + + for (int i = 0; i < ndevs; i++) { + while (read(devs[i].fd, &ev, sizeof(ev)) == sizeof(ev)) { + if (ev.type == EV_KEY && ev.code <= KEY_MAX) { + keys[ev.code] = ev.value != 0; + } else if (ev.type == EV_ABS && ev.code == ABS_X) { + abs_x = ev.value; + } else if (ev.type == EV_ABS && ev.code == ABS_Y) { + abs_y = ev.value; + } + } + if (devs[i].has_stick) { + sd = &devs[i]; + } + } + + /* Select + Start quits at once, as in the console's emulators (the + * physical buttons, whatever the remap). The save file is written as + * soon as the game saves, so nothing is lost. */ + { + static bool start_was; + bool start = keys[BTN_START]; + + if (keys[BTN_SELECT] && start && !start_was) { + fprintf(stderr, "controller_rsos: Select+Start: quitting\n"); + _exit(0); + } + start_was = start; + } + + /* physical -> RetroPad -> the N64 remap */ + for (size_t i = 0; i < sizeof(builtin_keys) / sizeof(builtin_keys[0]); i++) { + unsigned char to = remap[builtin_keys[i].rp]; + + if (keys[builtin_keys[i].code] && to != 0xff) { + rp[to] = true; + } + } + + /* RetroPad -> N64, as parallel_n64 */ + if (rp[RP_START]) pad->button |= START_BUTTON; + if (rp[RP_L2]) pad->button |= Z_TRIG; + if (alt_map) { + if (rp[RP_B]) pad->button |= A_BUTTON; + if (rp[RP_Y]) pad->button |= B_BUTTON; + if (rp[RP_R]) pad->button |= R_CBUTTONS; + if (rp[RP_L]) pad->button |= L_CBUTTONS; + if (rp[RP_A]) pad->button |= D_CBUTTONS; + if (rp[RP_X]) pad->button |= U_CBUTTONS; + if (rp[RP_R2]) pad->button |= R_TRIG; + if (rp[RP_SELECT]) pad->button |= L_TRIG; + } else { + if (rp[RP_R]) pad->button |= R_TRIG; + if (rp[RP_L]) pad->button |= L_TRIG; + if (rp[RP_R2]) { + if (rp[RP_A]) pad->button |= R_CBUTTONS; + if (rp[RP_Y]) pad->button |= L_CBUTTONS; + if (rp[RP_B]) pad->button |= D_CBUTTONS; + if (rp[RP_X]) pad->button |= U_CBUTTONS; + } else { + if (rp[RP_B]) pad->button |= A_BUTTON; + if (rp[RP_Y]) pad->button |= B_BUTTON; + } + } + + /* the analog stick, when fitted and moved */ + if (sd != NULL && stick_fitted(sd)) { + float fx = stick_axis(abs_x, &sd->ax), fy = stick_axis(abs_y, &sd->ay); + + if (fx != 0 || fy != 0) { + int sx = (int)(fx * 80), sy = (int)(-fy * 80); + + if (abs(sx) > abs(pad->stick_x) || abs(sy) > abs(pad->stick_y)) { + pad->stick_x = sx; + pad->stick_y = sy; + } + return; + } + } + /* else the D-pad steers (the remapped one, like the emulator's "D-pad + * to analog"): full tilt, 56 on a diagonal (80 / sqrt 2) */ + dx = (rp[RP_RIGHT] ? 1 : 0) - (rp[RP_LEFT] ? 1 : 0); + dy = (rp[RP_UP] ? 1 : 0) - (rp[RP_DOWN] ? 1 : 0); + if (dx != 0 || dy != 0) { + int m = dx != 0 && dy != 0 ? 56 : 80; + + pad->stick_x = dx * m; + pad->stick_y = dy * m; + } +} + +struct ControllerAPI controller_rsos = { + controller_rsos_init, + controller_rsos_read +}; + +#endif diff --git a/ports/sm64/controller_rsos.h b/ports/sm64/controller_rsos.h new file mode 100644 index 0000000..7d33b6d --- /dev/null +++ b/ports/sm64/controller_rsos.h @@ -0,0 +1,8 @@ +#ifndef CONTROLLER_RSOS_H +#define CONTROLLER_RSOS_H + +#include "controller_api.h" + +extern struct ControllerAPI controller_rsos; + +#endif diff --git a/ports/sm64/retrostone2.patch b/ports/sm64/retrostone2.patch new file mode 100644 index 0000000..5a0944f --- /dev/null +++ b/ports/sm64/retrostone2.patch @@ -0,0 +1,254 @@ +diff --git a/Makefile b/Makefile +index cfac1e8..529d7e1 100644 +--- a/Makefile ++++ b/Makefile +@@ -19,6 +19,11 @@ DEFINES := + TARGET_N64 ?= 0 + # Build for Emscripten/WebGL + TARGET_WEB ?= 0 ++# Build for RetroStoneOS (SDL2 KMS/DRM + GLES2 + ALSA, cross-compiled: ++# CROSS_PC=arm-linux- SDL2_CONFIG=) ++TARGET_LINUX_KMSDRM ?= 0 ++CROSS_PC ?= ++SDL2_CONFIG ?= sdl2-config + # Compiler to use (ido or gcc) + + +@@ -314,6 +319,14 @@ include Makefile.split + LEVEL_C_FILES := $(wildcard levels/*/leveldata.c) $(wildcard levels/*/script.c) $(wildcard levels/*/geo.c) + C_FILES := $(foreach dir,$(SRC_DIRS),$(wildcard $(dir)/*.c)) $(LEVEL_C_FILES) + CXX_FILES := $(foreach dir,$(SRC_DIRS),$(wildcard $(dir)/*.cpp)) ++ifeq ($(TARGET_LINUX_KMSDRM),1) ++ # RetroStoneOS (RetroStone2): SDL2 on KMS/DRM with GLES2, ALSA; no X11, ++ # PulseAudio or Wii U adapter ++ C_FILES := $(filter-out src/pc/audio/audio_pulse.c src/pc/controller/controller_wup.c \ ++ src/pc/controller/wup.c src/pc/gfx/gfx_glx.c,$(C_FILES)) ++ CXX_FILES := $(filter-out src/pc/gfx/gfx_direct3d11.cpp src/pc/gfx/gfx_direct3d12.cpp \ ++ src/pc/gfx/gfx_direct3d_common.cpp src/pc/gfx/gfx_dxgi.cpp src/pc/audio/audio_wasapi.cpp,$(CXX_FILES)) ++endif + S_FILES := $(foreach dir,$(SRC_DIRS),$(wildcard $(dir)/*.s)) + ULTRA_C_FILES := $(foreach dir,$(ULTRA_SRC_DIRS),$(wildcard $(dir)/*.c)) + GODDARD_C_FILES := $(foreach dir,$(GODDARD_SRC_DIRS),$(wildcard $(dir)/*.c)) +@@ -458,8 +471,8 @@ else # TARGET_N64 + + AS := as + ifneq ($(TARGET_WEB),1) +- CC := gcc +- CXX := g++ ++ CC := $(CROSS_PC)gcc ++ CXX := $(CROSS_PC)g++ + else + CC := emcc + endif +@@ -477,7 +490,10 @@ ifeq ($(TARGET_WINDOWS),1) + PLATFORM_CFLAGS := -DTARGET_WINDOWS + PLATFORM_LDFLAGS := -lm -lxinput9_1_0 -lole32 -no-pie -mwindows + endif +-ifeq ($(TARGET_LINUX),1) ++ifeq ($(TARGET_LINUX_KMSDRM),1) ++ PLATFORM_CFLAGS := -DTARGET_LINUX -DTARGET_LINUX_KMSDRM ++ PLATFORM_LDFLAGS := -lm -lpthread -lasound ++else ifeq ($(TARGET_LINUX),1) + PLATFORM_CFLAGS := -DTARGET_LINUX `pkg-config --cflags libusb-1.0` + PLATFORM_LDFLAGS := -lm -lpthread `pkg-config --libs libusb-1.0` -lasound -lpulse -no-pie + endif +@@ -496,7 +512,10 @@ ifeq ($(ENABLE_OPENGL),1) + GFX_CFLAGS += $(shell sdl2-config --cflags) -DGLEW_STATIC + GFX_LDFLAGS += $(shell sdl2-config --libs) -lglew32 -lopengl32 -lwinmm -limm32 -lversion -loleaut32 -lsetupapi + endif +- ifeq ($(TARGET_LINUX),1) ++ ifeq ($(TARGET_LINUX_KMSDRM),1) ++ GFX_CFLAGS += $(shell $(SDL2_CONFIG) --cflags) ++ GFX_LDFLAGS += $(shell $(SDL2_CONFIG) --libs) -lEGL -lGLESv2 ++ else ifeq ($(TARGET_LINUX),1) + GFX_CFLAGS += $(shell sdl2-config --cflags) + GFX_LDFLAGS += -lGL $(shell sdl2-config --libs) -lX11 -lXrandr + endif +@@ -517,7 +536,12 @@ endif + GFX_CFLAGS += -DWIDESCREEN + + CC_CHECK := $(CC) -fsyntax-only -fsigned-char -Wall -Wextra -Wno-format-security -D_LANGUAGE_C $(DEF_INC_CFLAGS) $(PLATFORM_CFLAGS) $(GFX_CFLAGS) ++ifeq ($(TARGET_LINUX_KMSDRM),1) ++# the cross compiler's own CPU flags (Cortex-A7), not the build machine's ++CFLAGS := $(OPT_FLAGS) -D_LANGUAGE_C $(DEF_INC_CFLAGS) $(PLATFORM_CFLAGS) $(GFX_CFLAGS) -fno-strict-aliasing -fwrapv ++else + CFLAGS := $(OPT_FLAGS) -D_LANGUAGE_C $(DEF_INC_CFLAGS) $(PLATFORM_CFLAGS) $(GFX_CFLAGS) -fno-strict-aliasing -fwrapv -march=native ++endif + + ASFLAGS := -I include -I $(BUILD_DIR) $(foreach d,$(DEFINES),--defsym $(d)) + +diff --git a/src/game/memory.c b/src/game/memory.c +index 36ceff3..9b91338 100644 +--- a/src/game/memory.c ++++ b/src/game/memory.c +@@ -518,7 +518,9 @@ void alloc_only_pool_clear(struct AllocOnlyPool *pool) { + + void *alloc_only_pool_alloc(struct AllocOnlyPool *pool, s32 size) { + u8 *addr; +- u32 s = size; ++ /* every block 8-byte aligned, like the block header above: on 32-bit ++ * ARM a float store to a misaligned address is a fatal SIGBUS */ ++ u32 s = ALIGN8(size); + if (pool->lastBlockSize - pool->lastBlockNextPos < s) { + struct AllocOnlyPoolBlock *block; + u32 nextSize = pool->lastBlockSize * 2; +diff --git a/src/pc/audio/audio_pulse.h b/src/pc/audio/audio_pulse.h +index c4d7e4b..7fbae7a 100644 +--- a/src/pc/audio/audio_pulse.h ++++ b/src/pc/audio/audio_pulse.h +@@ -3,7 +3,7 @@ + + #include "../compat.h" + +-#if defined(__linux__) || defined(__BSD__) ++#if (defined(__linux__) || defined(__BSD__)) && !defined(TARGET_LINUX_KMSDRM) + extern struct AudioAPI audio_pulse; + #define HAVE_PULSE_AUDIO 1 + #else +diff --git a/src/pc/controller/controller_entry_point.c b/src/pc/controller/controller_entry_point.c +index f86cf0d..7de45c1 100644 +--- a/src/pc/controller/controller_entry_point.c ++++ b/src/pc/controller/controller_entry_point.c +@@ -12,9 +12,12 @@ + #include "controller_sdl.h" + #endif + +-#ifdef __linux__ ++#if defined(__linux__) && !defined(TARGET_LINUX_KMSDRM) + #include "controller_wup.h" + #endif ++#ifdef TARGET_LINUX_KMSDRM ++#include "controller_rsos.h" ++#endif + + static struct ControllerAPI *controller_implementations[] = { + &controller_recorded_tas, +@@ -23,8 +26,11 @@ static struct ControllerAPI *controller_implementations[] = { + #else + &controller_sdl, + #endif +-#ifdef __linux__ ++#if defined(__linux__) && !defined(TARGET_LINUX_KMSDRM) + &controller_wup, ++#endif ++#ifdef TARGET_LINUX_KMSDRM ++ &controller_rsos, + #endif + &controller_keyboard, + }; +diff --git a/src/pc/controller/controller_sdl.c b/src/pc/controller/controller_sdl.c +index f6880e7..1674531 100644 +--- a/src/pc/controller/controller_sdl.c ++++ b/src/pc/controller/controller_sdl.c +@@ -4,6 +4,7 @@ + #include + #include + #include ++#include + + #include + +@@ -38,6 +39,13 @@ static void controller_sdl_read(OSContPad *pad) { + } + if (sdl_cntrl == NULL) { + for (int i = 0; i < SDL_NumJoysticks(); i++) { ++#ifdef TARGET_LINUX_KMSDRM ++ /* the built-in controls: controller_rsos reads them together */ ++ if (SDL_JoystickNameForIndex(i) != NULL && ++ strncmp(SDL_JoystickNameForIndex(i), "RetroStone2", 11) == 0) { ++ continue; ++ } ++#endif + if (SDL_IsGameController(i)) { + sdl_cntrl = SDL_GameControllerOpen(i); + if (sdl_cntrl != NULL) { +diff --git a/src/pc/gfx/gfx_glx.c b/src/pc/gfx/gfx_glx.c +index 9d2743e..182b682 100644 +--- a/src/pc/gfx/gfx_glx.c ++++ b/src/pc/gfx/gfx_glx.c +@@ -1,6 +1,6 @@ + #include "../compat.h" + +-#if defined(__linux__) || defined(__BSD__) ++#if (defined(__linux__) && !defined(TARGET_LINUX_KMSDRM)) || defined(__BSD__) + #include + #include + #include +diff --git a/src/pc/gfx/gfx_opengl.c b/src/pc/gfx/gfx_opengl.c +index 7bc9745..8d40dfb 100644 +--- a/src/pc/gfx/gfx_opengl.c ++++ b/src/pc/gfx/gfx_opengl.c +@@ -175,7 +175,11 @@ static struct ShaderProgram *gfx_opengl_create_and_load_new_shader(uint32_t shad + size_t num_floats = 4; + + // Vertex shader ++#ifdef TARGET_LINUX_KMSDRM ++ append_line(vs_buf, &vs_len, "#version 100"); ++#else + append_line(vs_buf, &vs_len, "#version 110"); ++#endif + append_line(vs_buf, &vs_len, "attribute vec4 aVtxPos;"); + if (cc_features.used_textures[0] || cc_features.used_textures[1]) { + append_line(vs_buf, &vs_len, "attribute vec2 aTexCoord;"); +@@ -206,8 +210,12 @@ static struct ShaderProgram *gfx_opengl_create_and_load_new_shader(uint32_t shad + append_line(vs_buf, &vs_len, "}"); + + // Fragment shader ++#ifdef TARGET_LINUX_KMSDRM ++ append_line(fs_buf, &fs_len, "#version 100"); ++ append_line(fs_buf, &fs_len, "precision mediump float;"); ++#else + append_line(fs_buf, &fs_len, "#version 110"); +- //append_line(fs_buf, &fs_len, "precision mediump float;"); ++#endif + if (cc_features.used_textures[0] || cc_features.used_textures[1]) { + append_line(fs_buf, &fs_len, "varying vec2 vTexCoord;"); + } +diff --git a/src/pc/gfx/gfx_sdl2.c b/src/pc/gfx/gfx_sdl2.c +index 4fd5c43..9b2a1a2 100644 +--- a/src/pc/gfx/gfx_sdl2.c ++++ b/src/pc/gfx/gfx_sdl2.c +@@ -1,6 +1,6 @@ + #include "../compat.h" + +-#if !defined(__linux__) && !defined(__BSD__) && defined(ENABLE_OPENGL) ++#if ((!defined(__linux__) && !defined(__BSD__)) || defined(TARGET_LINUX_KMSDRM)) && defined(ENABLE_OPENGL) + + #ifdef __MINGW32__ + #define FOR_WINDOWS 1 +@@ -155,6 +155,13 @@ int test_vsync(void) { + static void gfx_sdl_init(const char *game_name, bool start_in_fullscreen) { + SDL_Init(SDL_INIT_VIDEO); + ++#ifdef TARGET_LINUX_KMSDRM ++ /* GLES2 on the Mali-400 (Mesa lima), the screen's own mode, no cursor */ ++ SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); ++ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); ++ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); ++ SDL_ShowCursor(SDL_DISABLE); ++#endif + SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); + +diff --git a/src/pc/pc_main.c b/src/pc/pc_main.c +index 89aa1fa..380f27c 100644 +--- a/src/pc/pc_main.c ++++ b/src/pc/pc_main.c +@@ -166,7 +166,7 @@ void main_func(void) { + wm_api = &gfx_dxgi_api; + #elif defined(ENABLE_OPENGL) + rendering_api = &gfx_opengl_api; +- #if defined(__linux__) || defined(__BSD__) ++ #if (defined(__linux__) && !defined(TARGET_LINUX_KMSDRM)) || defined(__BSD__) + wm_api = &gfx_glx; + #else + wm_api = &gfx_sdl; +diff --git a/tools/armips.cpp b/tools/armips.cpp +index 2e26cf9..ef434a8 100644 +--- a/tools/armips.cpp ++++ b/tools/armips.cpp +@@ -1,3 +1,4 @@ ++#include + // armips assembler v0.11 + // https://github.com/Kingcom/armips/ + // To simplify compilation, all files have been concatenated into one. diff --git a/ports/soh/.gitattributes b/ports/soh/.gitattributes new file mode 100644 index 0000000..589b54d --- /dev/null +++ b/ports/soh/.gitattributes @@ -0,0 +1,2 @@ +# the patches carry CRLF lines of their targets (libultraship shaders): byte for byte +*.patch -text diff --git a/ports/soh/Ocarina of Time.layout b/ports/soh/Ocarina of Time.layout new file mode 100644 index 0000000..b6dfcb2 --- /dev/null +++ b/ports/soh/Ocarina of Time.layout @@ -0,0 +1,10 @@ +# N64 pad layout for this port: which SDL element the game reads for each N64 function, +# so a real N64 pad plays like the built-in buttons do here. Used when an N64 pad is +# plugged in (Settings > Controls); see docs/native-games.md, "Layouts". +# Functions: a b z l r start cup cdown cleft cright dpup dpdown dpleft dpright ("none" drops one). +# Left alone, an N64 pad is: a=a b=b z=lefttrigger l=leftshoulder r=rightshoulder +# (+ a copy of r on the right trigger), C buttons on the right stick, D-pad on the hat. +# Ocarina of Time: the built-in R1/L1 are C-right and C-up here, so N64 R is the right trigger +# and N64 L is Back (what the built-in buttons use). +r = righttrigger +l = back diff --git a/ports/soh/Ocarina of Time.sh b/ports/soh/Ocarina of Time.sh new file mode 100644 index 0000000..753b79e --- /dev/null +++ b/ports/soh/Ocarina of Time.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# The Legend of Zelda: Ocarina of Time (Ship of Harkinian), built from your own ROM by +# ports/soh/build-soh.sh. The game data (oot.o2r, soh.o2r), settings and saves stay in soh/. +cd soh || exit 1 +export SHIP_HOME="$PWD" +# Opus, OpusFile and SDL2_net, copied next to the game for a RetroStoneOS without them +export LD_LIBRARY_PATH="$PWD/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" +# The built-in controls as one standard gamepad (rsos-gamepad); SDL then +# ignores the raw button devices. It runs in the +# game's process group: the menu stops it with the game. +if [ -x /usr/bin/rsos-gamepad ]; then + SDL_GAMECONTROLLERCONFIG="$(/usr/bin/rsos-gamepad --print-mapping)" + export SDL_GAMECONTROLLERCONFIG + export SDL_GAMECONTROLLER_IGNORE_DEVICES=0x0001/0x0001 + /usr/bin/rsos-gamepad & + usleep 300000 +fi +if [ -x ./soh.elf ]; then + exec ./soh.elf +fi +exec /lib/ld-linux-armhf.so.3 ./soh.elf diff --git a/ports/soh/README.md b/ports/soh/README.md new file mode 100644 index 0000000..60b70a9 --- /dev/null +++ b/ports/soh/README.md @@ -0,0 +1,83 @@ +# The Legend of Zelda: Ocarina of Time (Ship of Harkinian) on the RetroStone2 + +[Ship of Harkinian](https://github.com/HarbourMasters/Shipwright) is the PC port of the Ocarina of Time +decompilation, built on HarbourMasters' [libultraship](https://github.com/Kenix3/libultraship), like Star Fox 64 +([../starship](../starship/README.md)). This folder adds the same OpenGL ES 2.0 mode to Ship of Harkinian 9.3.1's +libultraship and builds the game for the console as a native game (docs/native-games.md). + +**Nothing from the game is in this repository, the OS images or the updates.** The game's data comes from **your +own ROM** on your PC and stays yours. Tested with the N64 NTSC 1.2 ROM; the other versions Ship of Harkinian 9.3.1 +supports should work the same. `.z64`, `.v64` and `.n64` byte orders are all fine. + +## Build + +```sh +ports/soh/build-soh.sh ~/"Ocarina of Time (U) (V1.2).z64" ~/my-ports +``` + +It clones Ship of Harkinian at 9.3.1 into `~/rsos/soh-work`, applies `soh.patch` and `libultraship-gles2.patch`, +builds the asset tools (Torch) for the PC and makes `oot.o2r` from the ROM and `soh.o2r` (which carries the +patched shaders), builds the game for the console (`USE_GLES2`, the RetroStoneOS cross compiler), then writes: + +``` +~/my-ports/roms/native/Ocarina of Time.sh +~/my-ports/roms/native/soh/ soh.elf, oot.o2r, soh.o2r, gamecontrollerdb.txt, lib/, assets/ +``` + +Copy the `roms` folder onto the SD card's **RETROSTONE** partition; in the menu: **Native games > Ocarina of +Time**. Settings and saves stay in `roms/native/soh/` (`SHIP_HOME`). Hold **Select + Start** for a second to go +back to the menu. + +The console needs a RetroStoneOS with Native games and `rsos-gamepad`. Opus, OpusFile and SDL2_net are in the +RetroStone2 configs too; `build-soh.sh` also copies them into `soh/lib/` for a RetroStoneOS that doesn't have them. + +## Controls + +`rsos-gamepad` makes the built-in controls one SDL gamepad, by position. By the labels on the console: + +| RetroStone2 | N64 | +|---|---| +| B (bottom) / A (right) | A / B | +| X (top) / Y (left) / R1 | C-down / C-left / C-right | +| L2 / R2 | Z / R | +| L1 | L | +| Start | Start | +| Analog stick (Pro) | the stick | +| D-pad | the D-pad | + +The console has no right stick, so the C buttons go on X, Y and R1 (the default with `USE_GLES2`). C-up is free: +set it in Ship of Harkinian's own controller settings if you want it. Without an analog stick, map the stick's +directions to the D-pad there too (only tried on a Pro, which has the stick). + +## What the patches change + +**The GLES2 mode** (as for Starship): an OpenGL ES 2.0 context, GLSL ES 1.00 shaders, unsized texture formats, +packed depth+stencil or 16-bit depth, no multisampling or vertex array objects, framebuffer copies through +`glCopyTexSubImage2D`, depth reads reported as "far", and shader errors printed before aborting. + +**32-bit ARM and the Mali-400**, found on the console: +* Textures whose data lives below `0x10000000` were taken for unresolved N64 segment addresses and dropped. That + is always the heap on 32-bit ARM, so menus, titles and the HUD showed leftover pictures. Textures from the + game's archives are always valid now, and on 32-bit any mapped address is. +* In 2-cycle mode the shader samples a texture slot the combiner leaves unsized: the slot gets the used one's size. +* Draws with a primitive depth (the pause screen, parts of the HUD) wrote `gl_FragDepth`, which GLSL ES 1.00 + doesn't have: the depth goes into the vertices instead. +* Mesa hands a deleted texture's name out again at once; the texture binding cache forgets it. +* `mixer.c`'s NEON code uses AArch64-only intrinsics: their ARMv7 equivalents. +* `audio_load.c` cleared 8 bytes of a 4-byte array (glibc's `_FORTIFY_SOURCE` stopped the game). +* Torch's command line reads the ROM into memory first (9.3.1's `Extract()` signature). + +**Speed** (measured with a CPU profile on the console, where the game's main thread is the limit): vertices go to +the driver as client-side arrays instead of a new buffer object per draw (lima made one each time); assets named +by hash or by a path string are kept once resolved instead of going through the resource manager on every draw +(not when the archives hold alternate assets, which are reloaded as new objects); the texture address check uses +`mincore` instead of `dladdr`. + +**Other**: a failed sound start no longer saves "null" as the audio backend for every later start; the crash +handler ends the game with `_exit()`, so a crash returns to the menu at once. + +## Status + +**Works on a RetroStone2 Pro**: title screen, menus, 3D, sound, saves and the pause screen, with a little slowdown +in busy places. The game's messages are in `rsos/logs/boot/game.log` on the SD card, and Ship of Harkinian's +own log in `roms/native/soh/logs/`. diff --git a/ports/soh/build-soh.sh b/ports/soh/build-soh.sh new file mode 100755 index 0000000..f578195 --- /dev/null +++ b/ports/soh/build-soh.sh @@ -0,0 +1,119 @@ +#!/bin/bash +# Builds The Legend of Zelda: Ocarina of Time (Ship of Harkinian) for RetroStoneOS +# from YOUR OWN ROM, on the PC (Linux/WSL), as a native game for the SD card +# (docs/native-games.md). +# +# ports/soh/build-soh.sh [output folder] +# +# Needs a built RetroStoneOS tree for the RetroStone2 with SDL2 and the port +# libraries (the RetroStone2 configs): ~/rsos/output, or RSOS_OUTPUT=; +# cmake, ninja, python3 and a C++ compiler for the PC (Torch, the asset +# extractor, runs here). Ship of Harkinian is cloned at a fixed release into +# ~/rsos/soh-work (RSOS_SOH_WORK) and patched (soh.patch, +# libultraship-gles2.patch). +# +# The result contains the game's data, taken from your ROM: keep it for +# yourself. Never put it in a release, an update or a repository. +# +# Output (default ./soh-retrostone2): roms/native/Ocarina of Time.sh and +# roms/native/soh/. Copy the "roms" folder onto the SD card's RETROSTONE +# partition (it merges with the roms folder there). +set -euo pipefail + +REPO=https://github.com/HarbourMasters/Shipwright.git +COMMIT=f0599f96f8d442f26d0fa1c5cedafddacd56633f # 9.3.1, libultraship da6daf1 + +here=$(cd "$(dirname "$0")" && pwd) +rom=${1:-} +out=${2:-$PWD/soh-retrostone2} +O=${RSOS_OUTPUT:-$HOME/rsos/output} +W=${RSOS_SOH_WORK:-$HOME/rsos/soh-work} + +die() { echo "build-soh: $*" >&2; exit 1; } + +[ -n "$rom" ] || die "usage: $0 [output folder]" +[ -f "$rom" ] || die "$rom: no such file" +rom=$(cd "$(dirname "$rom")" && pwd)/$(basename "$rom") +case "$out" in /*) ;; *) out=$PWD/$out ;; esac +[ -x "$O/host/bin/arm-linux-gcc" ] || die "no cross compiler in $O/host/bin (build RetroStoneOS first)" +# libopus, libopusfile and libSDL2_net are also copied next to the game, for consoles +# whose RetroStoneOS does not have them yet +LIBS="libSDL2.so libzip.so libtinyxml2.so libspdlog.so libvorbisfile.so libopus.so.0 libopusfile.so.0 libSDL2_net-2.0.so.0" +for lib in $LIBS; do + [ -e "$O/staging/usr/lib/$lib" ] || die "$lib is not in $O/staging (build RetroStoneOS with the RetroStone2 configs)" +done +TOOLCHAIN=$O/host/share/buildroot/toolchainfile.cmake + +# only the fixed commit (the whole history is large) +if [ ! -d "$W/.git" ]; then + git init -q "$W" + git -C "$W" remote add origin "$REPO" +fi +cd "$W" +git fetch -q --depth 1 origin "$COMMIT" +# a clean tree at the fixed commit, then our changes (the build folders and the +# ROM are ignored by git and stay) +git checkout -q -f "$COMMIT" +git submodule update -q --init --recursive --force --depth 1 +git -C libultraship checkout -q -f . +git apply "$here/soh.patch" +git -C libultraship apply "$here/libultraship-gles2.patch" + +# the ROM, in .z64 byte order (Torch reads that one only) +mkdir -p rsos-rom +rm -f rsos-rom/* +python3 - "$rom" rsos-rom/oot.z64 << 'EOF' || die "$rom is not an N64 ROM" +import sys +data = bytearray(open(sys.argv[1], 'rb').read()) +head = bytes(data[:4]) +if head == b'\x37\x80\x40\x12': # .v64: 16-bit words swapped + data[0::2], data[1::2] = data[1::2], data[0::2] +elif head == b'\x40\x12\x37\x80': # .n64: 32-bit words reversed + for i in range(0, len(data) - 3, 4): + data[i:i + 4] = data[i:i + 4][::-1] +elif head != b'\x80\x37\x12\x40': + sys.exit(1) +open(sys.argv[2], 'wb').write(data) +EOF + +# Torch for this PC: oot.o2r (or oot-mq.o2r) from the ROM, and soh.o2r, which carries +# libultraship's (patched) shaders +cmake -S . -B build-tools -G Ninja -DSOH_TOOLS_ONLY=ON -DCMAKE_BUILD_TYPE=Release \ + -DSOH_ROM_PATH="$W/rsos-rom" +cmake --build build-tools --target ExtractAssets +cmake --build build-tools --target GenerateSohOtr +ls build-tools/soh/oot*.o2r > /dev/null 2>&1 || + die "no oot.o2r: $rom is not an Ocarina of Time ROM that Ship of Harkinian supports" + +# the game for the console. CMAKE_SYSTEM_NAME Linux: Buildroot's toolchain file names +# it "Buildroot", which skips the Linux parts of SoH and libultraship. SDL2_net's CMake +# file (made by autotools) points at the PC's /usr: a copy pointing at the staging folder. +C=$W/build-gles2-cmake/SDL2_net +mkdir -p "$C" +sed -e "s#^set(exec_prefix \"/usr\")#set(exec_prefix \"$O/staging/usr\")#" \ + -e "s#^get_filename_component(prefix .*#set(prefix \"$O/staging/usr\")#" \ + "$O/staging/usr/lib/cmake/SDL2_net/sdl2_net-config.cmake" > "$C/sdl2_net-config.cmake" +cp "$O/staging/usr/lib/cmake/SDL2_net/sdl2_net-config-version.cmake" "$C/" +cmake -S . -B build-gles2 -G Ninja -DCMAKE_BUILD_TYPE=Release -DUSE_OPENGLES=ON -DUSE_GLES2=ON \ + -DNON_PORTABLE=OFF -DSDL2_net_DIR="$C" -DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN" -DCMAKE_SYSTEM_NAME=Linux +cmake --build build-gles2 --target soh + +file build-gles2/soh/soh.elf | grep -q 'ARM' || die "build-gles2/soh/soh.elf is not an ARM program" +S=$out/roms/native/soh +mkdir -p "$S/lib" "$S/assets" +"$O/host/bin/arm-linux-strip" -o "$S/soh.elf" build-gles2/soh/soh.elf +cp build-tools/soh/oot*.o2r build-tools/soh/soh.o2r "$S/" +[ -f build-gles2/gamecontrollerdb.txt ] && cp build-gles2/gamecontrollerdb.txt "$S/" +for lib in libopus.so.0 libopusfile.so.0 libSDL2_net-2.0.so.0; do + cp -L "$O/staging/usr/lib/$lib" "$S/lib/" + "$O/host/bin/arm-linux-strip" "$S/lib/$lib" +done +# SoH quits at start without an assets/ folder next to the program; it reads it only to +# make oot.o2r on the console, which this script does on the PC instead +printf 'Ship of Harkinian checks that this folder exists. oot.o2r is made on the PC\n(ports/soh/build-soh.sh), so the extraction files are not needed here.\n' \ + > "$S/assets/README.txt" +install -m 0644 "$here/Ocarina of Time.sh" "$out/roms/native/Ocarina of Time.sh" +echo +echo "Done: $out/roms" +echo "Copy that \"roms\" folder onto the SD card's RETROSTONE partition, then in the menu:" +echo "Native games > Ocarina of Time. Hold Select + Start to quit." diff --git a/ports/soh/libultraship-gles2.patch b/ports/soh/libultraship-gles2.patch new file mode 100644 index 0000000..bb83d9e --- /dev/null +++ b/ports/soh/libultraship-gles2.patch @@ -0,0 +1,786 @@ +diff --git a/cmake/dependencies/linux.cmake b/cmake/dependencies/linux.cmake +index 02301f1..8e231e1 100644 +--- a/cmake/dependencies/linux.cmake ++++ b/cmake/dependencies/linux.cmake +@@ -2,7 +2,10 @@ + find_package(SDL2 REQUIRED) + target_link_libraries(ImGui PUBLIC SDL2::SDL2) + +-if (USE_OPENGLES) ++if (USE_GLES2) ++ target_link_libraries(ImGui PUBLIC GLESv2) ++ add_compile_definitions(IMGUI_IMPL_OPENGL_ES2) ++elseif (USE_OPENGLES) + target_link_libraries(ImGui PUBLIC ${OPENGL_GLESv2_LIBRARY}) + add_compile_definitions(IMGUI_IMPL_OPENGL_ES3) + else() +diff --git a/include/fast/backends/gfx_opengl.h b/include/fast/backends/gfx_opengl.h +index af24c70..efdf5c5 100644 +--- a/include/fast/backends/gfx_opengl.h ++++ b/include/fast/backends/gfx_opengl.h +@@ -16,6 +16,10 @@ + #elif __APPLE__ + #include + #include ++#elif defined(USE_GLES2) ++#include ++#include ++#include + #elif USE_OPENGLES + #include + #include +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index 45989b6..0209da4 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -11,6 +11,11 @@ find_package(Python3 REQUIRED COMPONENTS Interpreter) + + set(INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../include) + option(USE_OPENGLES "Enable GLES3" OFF) ++# OpenGL ES 2.0 (Mali-400 and other GLES2-only GPUs); implies USE_OPENGLES ++option(USE_GLES2 "Enable GLES2" OFF) ++if (USE_GLES2) ++ set(USE_OPENGLES ON) ++endif() + option(GFX_DEBUG_DISASSEMBLER "Enable libgfxd" OFF) + + if (CMAKE_SYSTEM_NAME STREQUAL "Windows") +@@ -208,6 +213,7 @@ else() + $<$>:NDEBUG> + SPDLOG_ACTIVE_LEVEL=${SPDLOG_MIN_CUTOFF} + $<$:USE_OPENGLES> ++ $<$:USE_GLES2> + $<$:GFX_DEBUG_DISASSEMBLER> + ) + endif() +diff --git a/src/fast/Fast3dGui.cpp b/src/fast/Fast3dGui.cpp +index 237a502..8c939c0 100644 +--- a/src/fast/Fast3dGui.cpp ++++ b/src/fast/Fast3dGui.cpp +@@ -146,6 +146,8 @@ void Fast3dGui::ImGuiBackendInit() { + case WindowBackend::FAST3D_SDL_OPENGL: + #ifdef __APPLE__ + ImGui_ImplOpenGL3_Init("#version 410 core"); ++#elif defined(USE_GLES2) ++ ImGui_ImplOpenGL3_Init("#version 100"); + #elif USE_OPENGLES + ImGui_ImplOpenGL3_Init("#version 300 es"); + #else +diff --git a/src/fast/backends/gfx_opengl.cpp b/src/fast/backends/gfx_opengl.cpp +index ad9b1dd..2f6e080 100644 +--- a/src/fast/backends/gfx_opengl.cpp ++++ b/src/fast/backends/gfx_opengl.cpp +@@ -27,6 +27,52 @@ + #include "fast/interpreter.h" + #include "ship/config/ConsoleVariable.h" + ++// a texture was bound outside SelectTexture(): its cache no longer says what is bound ++#define FORGET_TEXTURE_BINDINGS() do { mLastActiveTexture = -1; for (GLuint& bound : mLastBoundTextures) bound = (GLuint)-1; } while (0) ++ ++#include ++ ++#ifdef USE_GLES2 ++/* ++ * OpenGL ES 2.0: no sized texture formats, no multisampling, no blits and no ++ * depth reads. Multisampling stays off (mMaxMsaaLevel 1), so the multisample ++ * calls below are never reached; CopyFramebuffer and GetPixelDepth have their ++ * own GLES2 versions. Depth: packed depth+stencil when the driver has ++ * GL_OES_packed_depth_stencil, else a 16-bit depth buffer. ++ */ ++#define GL_RGB8 GL_RGB ++#define GL_RGBA8 GL_RGBA ++#define GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8_OES ++#define GL_DEPTH_STENCIL GL_DEPTH_STENCIL_OES ++#define GL_UNSIGNED_INT_24_8 GL_UNSIGNED_INT_24_8_OES ++#define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER ++#define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER ++#define glBlitFramebuffer(...) ((void)0) ++#define glReadBuffer(b) ((void)0) ++#define glRenderbufferStorageMultisample(target, samples, format, w, h) glRenderbufferStorage(target, format, w, h) ++static bool sPackedDepthStencil = true; ++#endif ++ ++namespace Fast { ++static void RenderbufferDepthStorage(GLsizei width, GLsizei height) { ++#ifdef USE_GLES2 ++ glRenderbufferStorage(GL_RENDERBUFFER, sPackedDepthStencil ? GL_DEPTH24_STENCIL8_OES : GL_DEPTH_COMPONENT16, ++ width, height); ++#else ++ glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); ++#endif ++} ++ ++static void FramebufferDepthAttach(GLuint rb) { ++#ifdef USE_GLES2 ++ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb); ++ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, sPackedDepthStencil ? rb : 0); ++#else ++ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb); ++#endif ++} ++} // namespace Fast ++ + namespace Fast { + int GfxRenderingAPIOGL::GetMaxTextureSize() { + GLint max_texture_size; +@@ -42,7 +88,17 @@ GfxClipParameters GfxRenderingAPIOGL::GetClipParameters() { + return { false, mFrameBuffers[mCurrentFrameBuffer].invertY }; + } + +-static void VertexArraySetAttribs(ShaderProgram* prg) { ++#ifdef USE_GLES2 ++static ShaderProgram* sClientArrayProgram; ++static const float* sClientArrayBase; ++#endif ++ ++static void VertexArraySetAttribs(ShaderProgram* prg, const float* clientArray = nullptr) { ++#ifdef USE_GLES2 ++ if (clientArray == nullptr) { ++ sClientArrayProgram = nullptr; // set for a buffer object: the next draw sets them again ++ } ++#endif + size_t numFloats = prg->numFloats; + size_t pos = 0; + +@@ -50,7 +106,9 @@ static void VertexArraySetAttribs(ShaderProgram* prg) { + if (prg->attribLocations[i] >= 0) { + glEnableVertexAttribArray(prg->attribLocations[i]); + glVertexAttribPointer(prg->attribLocations[i], prg->attribSizes[i], GL_FLOAT, GL_FALSE, +- numFloats * sizeof(float), (void*)(pos * sizeof(float))); ++ numFloats * sizeof(float), ++ clientArray != nullptr ? (const void*)(clientArray + pos) ++ : (const void*)(pos * sizeof(float))); + } + pos += prg->attribSizes[i]; + } +@@ -285,13 +343,23 @@ std::string GfxRenderingAPIOGL::BuildFsShader(const CCFeatures& cc_features) { + { "attr", "in" }, + { "opengles", false }, + { "core_opengl", true }, ++ { "gles2", false }, + { "texture", "texture" }, + { "vOutColor", "vOutColor" }, ++#elif defined(USE_GLES2) ++ { "GLSL_VERSION", "#version 100\nprecision mediump float;" }, ++ { "attr", "varying" }, ++ { "opengles", false }, ++ { "core_opengl", false }, ++ { "gles2", true }, ++ { "texture", "texture2D" }, ++ { "vOutColor", "gl_FragColor" }, + #elif defined(USE_OPENGLES) + { "GLSL_VERSION", "#version 300 es\nprecision mediump float;" }, + { "attr", "in" }, + { "opengles", true }, + { "core_opengl", false }, ++ { "gles2", false }, + { "texture", "texture" }, + { "vOutColor", "vOutColor" }, + #else +@@ -299,6 +367,7 @@ std::string GfxRenderingAPIOGL::BuildFsShader(const CCFeatures& cc_features) { + { "attr", "varying" }, + { "opengles", false }, + { "core_opengl", false }, ++ { "gles2", false }, + { "texture", "texture2D" }, + { "vOutColor", "gl_FragColor" }, + #endif +@@ -356,6 +425,11 @@ static std::string BuildVsShader(const CCFeatures& cc_features) { + { "attr", "in" }, + { "out", "out" }, + { "opengles", false } ++#elif defined(USE_GLES2) ++ { "GLSL_VERSION", "#version 100" }, ++ { "attr", "attribute" }, ++ { "out", "varying" }, ++ { "opengles", false } + #elif defined(USE_OPENGLES) + { "GLSL_VERSION", "#version 300 es" }, + { "attr", "in" }, +@@ -420,9 +494,8 @@ ShaderProgram* GfxRenderingAPIOGL::CreateAndLoadNewShader(uint64_t shader_id0, u + GLint max_length = 0; + glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &max_length); + char error_log[1024]; +- // fprintf(stderr, "Vertex shader compilation failed\n"); +- glGetShaderInfoLog(vertex_shader, max_length, &max_length, &error_log[0]); +- // fprintf(stderr, "%s\n", &error_log[0]); ++ glGetShaderInfoLog(vertex_shader, sizeof(error_log), nullptr, error_log); ++ fprintf(stderr, "Vertex shader compilation failed:\n%s\n%s\n", error_log, vs_buf.c_str()); + abort(); + } + +@@ -434,9 +507,8 @@ ShaderProgram* GfxRenderingAPIOGL::CreateAndLoadNewShader(uint64_t shader_id0, u + GLint max_length = 0; + glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &max_length); + char error_log[1024]; +- fprintf(stderr, "Fragment shader compilation failed\n"); +- glGetShaderInfoLog(fragment_shader, max_length, &max_length, &error_log[0]); +- fprintf(stderr, "%s\n", &error_log[0]); ++ glGetShaderInfoLog(fragment_shader, sizeof(error_log), nullptr, error_log); ++ fprintf(stderr, "Fragment shader compilation failed:\n%s\n%s\n", error_log, fs_buf.c_str()); + abort(); + } + +@@ -559,6 +631,7 @@ GLuint GfxRenderingAPIOGL::NewTexture() { + + void GfxRenderingAPIOGL::DeleteTexture(uint32_t texID) { + glDeleteTextures(1, &texID); ++ FORGET_TEXTURE_BINDINGS(); // deleting unbinds it, and the name comes back with the next texture + } + + void GfxRenderingAPIOGL::SelectTexture(int tile, GLuint texture_id) { +@@ -583,7 +656,9 @@ void GfxRenderingAPIOGL::UploadTexture(const uint8_t* rgba32_buf, uint32_t width + textures[mCurrentTextureIds[mCurrentTile]].height = height; + } + +-#ifdef USE_OPENGLES ++#ifdef USE_GLES2 ++#define GL_MIRROR_CLAMP_TO_EDGE GL_MIRRORED_REPEAT ++#elif defined(USE_OPENGLES) + #define GL_MIRROR_CLAMP_TO_EDGE 0x8743 + #endif + +@@ -703,7 +778,17 @@ void GfxRenderingAPIOGL::DrawTriangles(float buf_vbo[], size_t buf_vbo_len, size + SetPerDrawUniforms(); + + // printf("flushing %d tris\n", buf_vbo_num_tris); ++#ifdef USE_GLES2 ++ // the pointers stay valid until the program changes or ImGui draws (after the frame) ++ if (mCurrentShaderProgram != sClientArrayProgram || buf_vbo != sClientArrayBase) { ++ glBindBuffer(GL_ARRAY_BUFFER, 0); ++ VertexArraySetAttribs(mCurrentShaderProgram, buf_vbo); ++ sClientArrayProgram = mCurrentShaderProgram; ++ sClientArrayBase = buf_vbo; ++ } ++#else + glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buf_vbo_len, buf_vbo, GL_STREAM_DRAW); ++#endif + glDrawArrays(GL_TRIANGLES, 0, 3 * buf_vbo_num_tris); + } + +@@ -715,7 +800,16 @@ void GfxRenderingAPIOGL::Init() { + glGenBuffers(1, &mOpenglVbo); + glBindBuffer(GL_ARRAY_BUFFER, mOpenglVbo); + +-#if defined(__APPLE__) || defined(USE_OPENGLES) ++#ifdef USE_GLES2 ++ { ++ const char* ext = (const char*)glGetString(GL_EXTENSIONS); ++ ++ sPackedDepthStencil = ext != nullptr && strstr(ext, "GL_OES_packed_depth_stencil") != nullptr; ++ SPDLOG_INFO("OpenGL ES 2.0: {} ({}), depth buffer {}", (const char*)glGetString(GL_RENDERER), ++ (const char*)glGetString(GL_VERSION), sPackedDepthStencil ? "24-bit + stencil" : "16-bit"); ++ } ++#endif ++#if defined(__APPLE__) || (defined(USE_OPENGLES) && !defined(USE_GLES2)) + glGenVertexArrays(1, &mOpenglVao); + glBindVertexArray(mOpenglVao); + #endif +@@ -730,17 +824,21 @@ void GfxRenderingAPIOGL::Init() { + + glGenRenderbuffers(1, &mPixelDepthRb); + glBindRenderbuffer(GL_RENDERBUFFER, mPixelDepthRb); +- glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 1, 1); ++ RenderbufferDepthStorage(1, 1); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + + glGenFramebuffers(1, &mPixelDepthFb); + glBindFramebuffer(GL_FRAMEBUFFER, mPixelDepthFb); +- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mPixelDepthRb); ++ FramebufferDepthAttach(mPixelDepthRb); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + + mPixelDepthRbSize = 1; + ++#ifdef USE_GLES2 ++ mMaxMsaaLevel = 1; ++#else + glGetIntegerv(GL_MAX_SAMPLES, &mMaxMsaaLevel); ++#endif + } + + void GfxRenderingAPIOGL::OnResize() { +@@ -748,6 +846,9 @@ void GfxRenderingAPIOGL::OnResize() { + + void GfxRenderingAPIOGL::StartFrame() { + mFrameCount++; ++#ifdef USE_GLES2 ++ sClientArrayProgram = nullptr; // ImGui drew with its own arrays ++#endif + } + + void GfxRenderingAPIOGL::EndFrame() { +@@ -764,7 +865,12 @@ int GfxRenderingAPIOGL::CreateFramebuffer() { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); ++#ifdef USE_GLES2 ++ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); ++ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); ++#endif + glBindTexture(GL_TEXTURE_2D, 0); ++ FORGET_TEXTURE_BINDINGS(); + + GLuint clrbufMsaa; + glGenRenderbuffers(1, &clrbufMsaa); +@@ -772,7 +878,7 @@ int GfxRenderingAPIOGL::CreateFramebuffer() { + GLuint rbo; + glGenRenderbuffers(1, &rbo); + glBindRenderbuffer(GL_RENDERBUFFER, rbo); +- glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 1, 1); ++ RenderbufferDepthStorage(1, 1); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + + GLuint fbo; +@@ -806,6 +912,7 @@ void GfxRenderingAPIOGL::UpdateFramebufferParameters(int fb_id, uint32_t width, + glBindTexture(GL_TEXTURE_2D, fb.clrbuf); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); + glBindTexture(GL_TEXTURE_2D, 0); ++ FORGET_TEXTURE_BINDINGS(); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb.clrbuf, 0); + } else { + glBindRenderbuffer(GL_RENDERBUFFER, fb.clrbufMsaa); +@@ -819,7 +926,7 @@ void GfxRenderingAPIOGL::UpdateFramebufferParameters(int fb_id, uint32_t width, + (fb.width != width || fb.height != height || fb.msaa_level != msaa_level || !fb.has_depth_buffer)) { + glBindRenderbuffer(GL_RENDERBUFFER, fb.rbo); + if (msaa_level <= 1) { +- glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); ++ RenderbufferDepthStorage(width, height); + } else { + glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa_level, GL_DEPTH24_STENCIL8, width, height); + } +@@ -827,9 +934,9 @@ void GfxRenderingAPIOGL::UpdateFramebufferParameters(int fb_id, uint32_t width, + } + + if (!fb.has_depth_buffer && has_depth_buffer) { +- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fb.rbo); ++ FramebufferDepthAttach(fb.rbo); + } else if (fb.has_depth_buffer && !has_depth_buffer) { +- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0); ++ FramebufferDepthAttach(0); + } + } + +@@ -932,6 +1039,35 @@ void GfxRenderingAPIOGL::CopyFramebuffer(int fb_dst_id, int fb_src_id, int srcX0 + FramebufferOGL src = mFrameBuffers[fb_src_id]; + const FramebufferOGL& dst = mFrameBuffers[fb_dst_id]; + ++#ifdef USE_GLES2 ++ // No blits: copy into the destination's colour texture, unscaled and in the ++ // same orientation only (G_COPYFB effects; Starship does not use them). ++ if (fb_dst_id == 0 || srcX1 - srcX0 != dstX1 - dstX0 || srcY1 - srcY0 != dstY1 - dstY0 || ++ src.invertY != dst.invertY) { ++ static bool warned; ++ if (!warned) { ++ SPDLOG_WARN("GLES2: scaled, flipped or on-screen framebuffer copies are not supported"); ++ warned = true; ++ } ++ return; ++ } ++ // OpenGL's origin is the bottom left, as in the blit path below ++ if (!src.invertY) { ++ int h = srcY1 - srcY0; ++ srcY1 = src.height - srcY0; ++ srcY0 = srcY1 - h; ++ } ++ glDisable(GL_SCISSOR_TEST); ++ glBindFramebuffer(GL_FRAMEBUFFER, src.fbo); ++ glActiveTexture(GL_TEXTURE0); ++ glBindTexture(GL_TEXTURE_2D, dst.clrbuf); ++ glCopyTexSubImage2D(GL_TEXTURE_2D, 0, dstX0, dstY0, srcX0, srcY0, srcX1 - srcX0, srcY1 - srcY0); ++ glBindFramebuffer(GL_FRAMEBUFFER, mFrameBuffers[mCurrentFrameBuffer].fbo); ++ glEnable(GL_SCISSOR_TEST); ++ FORGET_TEXTURE_BINDINGS(); ++ return; ++#endif ++ + // Adjust y values for non-inverted source frame buffers because opengl uses bottom left for origin + if (!src.invertY) { + int temp = srcY1 - srcY0; +@@ -1024,6 +1160,14 @@ std::unordered_map, uint16_t, hash_pair_ff> + GfxRenderingAPIOGL::GetPixelDepth(int fb_id, const std::set>& coordinates) { + std::unordered_map, uint16_t, hash_pair_ff> res; + ++#ifdef USE_GLES2 ++ // GLES2 cannot read the depth buffer: every point is reported at the far plane ++ for (const auto& coord : coordinates) { ++ res.emplace(coord, 0xFFFC); ++ } ++ return res; ++#endif ++ + FramebufferOGL& fb = mFrameBuffers[fb_id]; + + // When looking up one value and the framebuffer is single-sampled, we can read pixels directly +@@ -1045,8 +1189,8 @@ GfxRenderingAPIOGL::GetPixelDepth(int fb_id, const std::set + #ifndef _WIN32 + #include ++#include ++#include + #endif + + #include +@@ -134,6 +136,46 @@ void GfxSetInstance(std::shared_ptr gfx) { + // N64 prim_depth is 15-bit (0 near, 0x7FFF far). + static constexpr float N64_PRIM_DEPTH_MAX = 32767.0f; + ++// Alternate ("alt/") assets are unloaded and loaded again as new objects; with any in the ++// archives, nothing is kept (decided once: archives are added at start only) ++static bool NoAltAssetFiles() { ++ static const bool none = ++ Ship::Context::GetRawInstance()->GetResourceManager()->GetArchiveManager()->ListFiles("alt/*")->empty(); ++ return none; ++} ++ ++static std::unordered_map> sHashResourceCache; ++ ++// texture paths named by pointer: kept per pointer, checked against a copy of the path ++struct ResolvedPath { ++ std::string path; ++ std::shared_ptr res; ++}; ++static std::unordered_map sPathResourceCache; ++ ++static std::shared_ptr CachedResourceByHash(uint64_t hash) { ++ if (!NoAltAssetFiles()) { ++ return Ship::Context::GetRawInstance()->GetResourceManager()->LoadResource(hash); ++ } ++ auto it = sHashResourceCache.find(hash); ++ if (it != sHashResourceCache.end()) { ++ return it->second; ++ } ++ auto res = Ship::Context::GetRawInstance()->GetResourceManager()->LoadResource(hash); ++ if (res != nullptr) { ++ if (sHashResourceCache.size() >= 4096) { ++ sHashResourceCache.clear(); ++ } ++ sHashResourceCache.emplace(hash, res); ++ } ++ return res; ++} ++ ++static void* CachedResourceRawPointer(uint64_t hash) { ++ auto res = CachedResourceByHash(hash); ++ return res != nullptr ? res->GetRawPointer() : nullptr; ++} ++ + void Interpreter::Flush() { + if (mBufVboLen > 0) { + mRapi->SetCurrentPrimDepth((float)mRdp->prim_depth / N64_PRIM_DEPTH_MAX); +@@ -458,7 +500,21 @@ std::shared_ptr Interpreter::ResolveResourceCached(const char* + return nullptr; + } + if (!mResolvedResourceCacheEnabled) { +- return Ship::Context::GetRawInstance()->GetResourceManager()->LoadResourceProcess(path); ++ if (!NoAltAssetFiles()) { ++ return Ship::Context::GetRawInstance()->GetResourceManager()->LoadResourceProcess(path); ++ } ++ auto found = sPathResourceCache.find(path); ++ if (found != sPathResourceCache.end() && found->second.path == path) { ++ return found->second.res; ++ } ++ auto res = Ship::Context::GetRawInstance()->GetResourceManager()->LoadResourceProcess(path); ++ if (res != nullptr) { ++ if (sPathResourceCache.size() >= 4096) { ++ sPathResourceCache.clear(); ++ } ++ sPathResourceCache[path] = { path, res }; ++ } ++ return res; + } + auto it = mResolvedResourceCache.find(path); + if (it != mResolvedResourceCache.end()) { +@@ -481,6 +537,8 @@ void Interpreter::TextureCacheClear() { + mTextureCache.map.clear(); + mTextureCache.lru.clear(); + mResolvedResourceCache.clear(); ++ sHashResourceCache.clear(); ++ sPathResourceCache.clear(); + // Pre-allocate buckets so the map never rehashes during normal operation. + // Rehashing invalidates all iterators, including those stored in LRU entries. + mTextureCache.map.reserve(TEXTURE_CACHE_MAX_SIZE); +@@ -1912,9 +1970,11 @@ void Interpreter::GfxSpTri1(uint8_t vtx1_idx, uint8_t vtx2_idx, uint8_t vtx3_idx + if (use_grayscale) { + cc_options |= SHADER_OPT(GRAYSCALE); + } ++#ifndef USE_GLES2 + if (use_prim_depth) { + cc_options |= SHADER_OPT(PRIM_DEPTH); + } ++#endif + + if (!mShaderStack.empty()) { + cc_options |= (mShaderStack.top() << SHADER_ID_SHIFT); +@@ -1942,8 +2002,9 @@ void Interpreter::GfxSpTri1(uint8_t vtx1_idx, uint8_t vtx2_idx, uint8_t vtx3_idx + ColorCombiner* comb = LookupOrCreateColorCombiner(key); + + uint32_t tm = 0; +- uint32_t tex_width[2], tex_height[2], tex_width2[2], tex_height2[2]; +- uint32_t effective_tile[2]; ++ uint32_t tex_width[2] = { 1, 1 }, tex_height[2] = { 1, 1 }, tex_width2[2] = { 1, 1 }, ++ tex_height2[2] = { 1, 1 }; ++ uint32_t effective_tile[2] = { mRdp->first_tile_index, mRdp->first_tile_index }; + + for (int i = 0; i < 2; i++) { + uint32_t tile = mRdp->first_tile_index + i; +@@ -2075,6 +2136,15 @@ void Interpreter::GfxSpTri1(uint8_t vtx1_idx, uint8_t vtx2_idx, uint8_t vtx3_idx + } + } + ++ for (int i = 0; i < 2; i++) { ++ if (!comb->usedTextures[i] && comb->usedTextures[i ^ 1]) { ++ tex_width[i] = tex_width[i ^ 1]; ++ tex_height[i] = tex_height[i ^ 1]; ++ tex_width2[i] = tex_width2[i ^ 1]; ++ tex_height2[i] = tex_height2[i ^ 1]; ++ } ++ } ++ + struct ShaderProgram* prg = comb->prg[tm]; + if (prg == NULL) { + comb->prg[tm] = prg = +@@ -2100,6 +2170,11 @@ void Interpreter::GfxSpTri1(uint8_t vtx1_idx, uint8_t vtx2_idx, uint8_t vtx3_idx + + for (int i = 0; i < 3; i++) { + float z = v_arr[i]->z, w = v_arr[i]->w; ++#ifdef USE_GLES2 ++ if (use_prim_depth) { ++ z = ((float)mRdp->prim_depth / N64_PRIM_DEPTH_MAX * 2.0f - 1.0f) * w; ++ } ++#endif + if (clip_parameters.z_is_from_0_to_1) { + z = (z + w) / 2.0f; + } +@@ -3419,7 +3494,7 @@ bool gfx_mtx_otr_handler_custom_f3dex2(F3DGfx** cmd0) { + + const uint64_t hash = ((uint64_t)cmd->words.w0 << 32) + cmd->words.w1; + const int32_t* mtx = +- (const int32_t*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ (const int32_t*)CachedResourceRawPointer(hash); + + if (mtx != NULL) { + Interpreter* gfx = mInstance.lock().get(); +@@ -3438,7 +3513,7 @@ bool gfx_mtx_otr_handler_custom_f3d(F3DGfx** cmd0) { + + const uint64_t hash = ((uint64_t)cmd->words.w0 << 32) + cmd->words.w1; + const int32_t* mtx = +- (const int32_t*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ (const int32_t*)CachedResourceRawPointer(hash); + if (mtx != nullptr) { + cmd--; + gfx->GfxSpMatrix(C0(16, 8), mtx); +@@ -3505,10 +3580,10 @@ bool gfx_movemem_handler_otr(F3DGfx** cmd0) { + + if (ucode_handler_index == ucode_f3dex2) { + gfx->GfxSpMovememF3dex2(index, offset, +- Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash)); ++ CachedResourceRawPointer(hash)); + } else { + auto light = +- (Fast::LightEntry*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ (Fast::LightEntry*)CachedResourceRawPointer(hash); + uintptr_t data = (uintptr_t)&light->Ambient; + gfx->GfxSpMovememF3d(index, offset, (void*)(data + (hasOffset == 1 ? 0x8 : 0))); + } +@@ -3649,7 +3724,7 @@ bool gfx_vtx_hash_handler_custom(F3DGfx** cmd0) { + gfx->GfxSpVertex(C0(12, 8), C0(1, 7) - C0(12, 8), (F3DVtx*)offset); + (*cmd0)++; + } else { +- F3DVtx* vtx = (F3DVtx*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ F3DVtx* vtx = (F3DVtx*)CachedResourceRawPointer(hash); + + if (vtx != NULL) { + vtx = (F3DVtx*)((char*)vtx + offset); +@@ -3741,7 +3816,7 @@ bool gfx_dl_otr_hash_handler_custom(F3DGfx** cmd0) { + + uint64_t hash = ((uint64_t)(*cmd0)->words.w0 << 32) + (*cmd0)->words.w1; + +- F3DGfx* gfx = (F3DGfx*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ F3DGfx* gfx = (F3DGfx*)CachedResourceRawPointer(hash); + + if (gfx != 0) { + g_exec_stack.call(cmd, gfx); +@@ -3799,7 +3874,7 @@ bool gfx_branch_z_otr_handler_f3dex2(F3DGfx** cmd0) { + (gfx->mRsp->extra_geometry_mode & G_EX_ALWAYS_EXECUTE_BRANCH) != 0) { + uint64_t hash = ((uint64_t)(*cmd0)->words.w0 << 32) + (*cmd0)->words.w1; + +- F3DGfx* gfx = (F3DGfx*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ F3DGfx* gfx = (F3DGfx*)CachedResourceRawPointer(hash); + + if (gfx != 0) { + (*cmd0) = gfx; +@@ -3989,9 +4064,17 @@ static bool IsValidResolvedAddress(uintptr_t addr) { + reinterpret_cast(addr), &module) != 0; + #else + // For non-Windows platforms, check whether the address belongs to a loaded object. ++#if UINTPTR_MAX <= 0xFFFFFFFFu ++ // 32-bit: the heap and mappings live below 0x10000000 as well; a mapped page is a real address. ++ // mincore is one cheap system call (dladdr searched symbol tables: 3% of the CPU time on an A20). ++ static const uintptr_t pageSize = (uintptr_t)sysconf(_SC_PAGESIZE); ++ unsigned char resident; ++ return mincore(reinterpret_cast(addr & ~(pageSize - 1)), 1, &resident) == 0; ++#else + Dl_info info; + return dladdr(reinterpret_cast(addr), &info) != 0; + #endif ++#endif + } + + bool gfx_set_timg_handler_rdp(F3DGfx** cmd0) { +@@ -4006,6 +4089,7 @@ bool gfx_set_timg_handler_rdp(F3DGfx** cmd0) { + // from the resource, but raw textures would leave them at 0. + rawTexMetdata.h_byte_scale = 1; + rawTexMetdata.v_pixel_scale = 1; ++ bool fromResource = false; + + if ((i & 1) != 1) { + if (gfx_check_image_signature(imgData) == 1) { +@@ -4025,10 +4109,11 @@ bool gfx_set_timg_handler_rdp(F3DGfx** cmd0) { + rawTexMetdata.v_pixel_scale = tex->VPixelScale; + rawTexMetdata.type = tex->Type; + rawTexMetdata.resource = tex; ++ fromResource = true; + } + } + +- if (!IsValidResolvedAddress(i)) { ++ if (!fromResource && !IsValidResolvedAddress(i)) { + return false; + } + +@@ -4053,8 +4138,7 @@ bool gfx_set_timg_otr_hash_handler_custom(F3DGfx** cmd0) { + } + + std::shared_ptr texture = std::static_pointer_cast( +- Ship::Context::GetRawInstance()->GetResourceManager()->LoadResourceProcess( +- Ship::Context::GetRawInstance()->GetResourceManager()->GetArchiveManager()->HashToCString(hash))); ++ CachedResourceByHash(hash)); + if (texture != nullptr) { + texFlags = texture->Flags; + rawTexMetadata.width = texture->Width; +diff --git a/src/fast/shaders/opengl/default.shader.glsl b/src/fast/shaders/opengl/default.shader.glsl +index 1fe86aa..ff45672 100644 +--- a/src/fast/shaders/opengl/default.shader.glsl ++++ b/src/fast/shaders/opengl/default.shader.glsl +@@ -134,14 +134,18 @@ + + float random(in vec3 value) { + float random = dot(sin(value), vec3(12.9898, 78.233, 37.719)); ++ @if(gles2) ++ return fract(sin(random) * 43758.5453); ++ @else + return fract(sin(random) * 143758.5453); ++ @end + } + + vec4 fromLinear(vec4 linearRGB){ + bvec3 cutoff = lessThan(linearRGB.rgb, vec3(0.0031308)); + vec3 higher = vec3(1.055)*pow(linearRGB.rgb, vec3(1.0/2.4)) - vec3(0.055); + vec3 lower = linearRGB.rgb * vec3(12.92); +- return vec4(mix(higher, lower, cutoff), linearRGB.a); ++ return vec4(mix(higher, lower, vec3(cutoff)), linearRGB.a); + } + + vec4 filter3point(in sampler2D tex, in vec2 texCoord, in vec2 texSize) { +@@ -187,7 +191,9 @@ + vec4 texVal@{i} = hookTexture2D(@{i}, uTex@{i}, vTexCoordAdj@{i}, texSize@{i}); + + @if(o_masks[i]) +- @if(opengles) ++ @if(gles2) ++ vec2 maskSize@{i} = texSize@{i}; ++ @elseif(opengles) + vec2 maskSize@{i} = vec2(textureSize(uTexMask@{i}, 0)); + @else + vec2 maskSize@{i} = textureSize(uTexMask@{i}, 0); +diff --git a/src/libultraship/controller/controldevice/controller/mapping/ControllerDefaultMappings.cpp b/src/libultraship/controller/controldevice/controller/mapping/ControllerDefaultMappings.cpp +index c431c34..35f66b2 100644 +--- a/src/libultraship/controller/controldevice/controller/mapping/ControllerDefaultMappings.cpp ++++ b/src/libultraship/controller/controldevice/controller/mapping/ControllerDefaultMappings.cpp +@@ -80,6 +80,11 @@ void ControllerDefaultMappings::SetDefaultSDLButtonToButtonMappings( + { BTN_DDOWN, { SDL_CONTROLLER_BUTTON_DPAD_DOWN } }, + { BTN_DLEFT, { SDL_CONTROLLER_BUTTON_DPAD_LEFT } }, + { BTN_DRIGHT, { SDL_CONTROLLER_BUTTON_DPAD_RIGHT } }, ++#ifdef USE_GLES2 ++ { BTN_CDOWN, { SDL_CONTROLLER_BUTTON_Y } }, ++ { BTN_CLEFT, { SDL_CONTROLLER_BUTTON_X } }, ++ { BTN_CRIGHT, { SDL_CONTROLLER_BUTTON_RIGHTSHOULDER } }, ++#endif + }); + } + +diff --git a/src/ship/audio/Audio.cpp b/src/ship/audio/Audio.cpp +index 8cc5b12..604a30c 100644 +--- a/src/ship/audio/Audio.cpp ++++ b/src/ship/audio/Audio.cpp +@@ -36,8 +36,11 @@ void Audio::InitAudioPlayer() { + + if (mAudioPlayer && !mAudioPlayer->Init()) { + // Failed to initialize system audio player. +- // Fallback to Null if the native system player does not work. +- SetCurrentAudioBackend(AudioBackend::NUL); ++ // Fallback to Null if the native system player does not work: for this run only, ++ // the saved backend stays and the next start tries it again ++ mAudioBackend = AudioBackend::NUL; ++ mAudioPlayer = std::make_shared(this->mAudioSettings); ++ mAudioPlayer->Init(); + } + } + +diff --git a/src/ship/debug/CrashHandler.cpp b/src/ship/debug/CrashHandler.cpp +index 56abfcb..b15b228 100644 +--- a/src/ship/debug/CrashHandler.cpp ++++ b/src/ship/debug/CrashHandler.cpp +@@ -2,6 +2,9 @@ + #include "ship/utils/StringHelper.h" + #include "ship/debug/CrashHandler.h" + #include "ship/Context.h" ++#ifndef _WIN32 ++#include // _exit ++#endif + + #ifdef _WIN32 + #include +@@ -201,7 +204,7 @@ static void ErrorHandler(int sig, siginfo_t* sigInfo, void* data) { + + Context::GetRawInstance()->GetLogger()->flush(); + spdlog::shutdown(); +- exit(1); ++ _exit(128 + sig); + } + + static void ShutdownHandler(int sig, siginfo_t* sigInfo, void* data) { diff --git a/ports/soh/soh.patch b/ports/soh/soh.patch new file mode 100644 index 0000000..7f99145 --- /dev/null +++ b/ports/soh/soh.patch @@ -0,0 +1,126 @@ +diff --git a/soh/assets/tools/torch-cli/main.cpp b/soh/assets/tools/torch-cli/main.cpp +index bc2a3d14..44fb4cea 100644 +--- a/soh/assets/tools/torch-cli/main.cpp ++++ b/soh/assets/tools/torch-cli/main.cpp +@@ -1,3 +1,6 @@ ++#include ++#include ++#include + // Build-time ROM extraction, for the ExtractAssets target and anything else that needs an + // archive without launching the game. + // +@@ -98,7 +101,9 @@ int main(int argc, char** argv) { + + for (const auto& rom : roms) { + // A fresh extraction per ROM; torch names the archive from config.yml. +- const std::string archive = SohTorch::Extract(rom, src, dest, version, nullptr); ++ std::ifstream romFile(rom, std::ios::binary); ++ std::vector romData((std::istreambuf_iterator(romFile)), std::istreambuf_iterator()); ++ const std::string archive = SohTorch::Extract(std::move(romData), src, dest, version, nullptr); + if (archive.empty()) { + fprintf(stderr, "failed to extract %s\n", rom.c_str()); + return 1; +diff --git a/soh/soh/ResourceManagerHelpers.cpp b/soh/soh/ResourceManagerHelpers.cpp +index 69a482f6..12b24bb6 100644 +--- a/soh/soh/ResourceManagerHelpers.cpp ++++ b/soh/soh/ResourceManagerHelpers.cpp +@@ -9,6 +9,23 @@ + + #include "ResourceManagerHelpers.h" + #include "OTRGlobals.h" ++#include ++#include ++#include ++ ++static bool NoAltAssetFiles() { ++ static const bool none = ++ Ship::Context::GetRawInstance()->GetResourceManager()->GetArchiveManager()->ListFiles("alt/*")->empty(); ++ return none; ++} ++ ++struct ResolvedByName { ++ std::string path; ++ bool mq; ++ std::shared_ptr res; ++}; ++static std::unordered_map sResolvedByName; ++static std::mutex sResolvedByNameMutex; + #include "cvar_prefixes.h" + #include "Enhancements/enhancementTypes.h" + #include "Enhancements/randomizer/dungeon.h" +@@ -267,20 +284,37 @@ extern "C" bool ResourceMgr_IsAltAssetsEnabled() { + // Unloads a resource if an alternate version exists when alt assets are enabled + // The resource is only removed from the internal cache to prevent it from used in the next resource lookup + extern "C" void ResourceMgr_UnloadOriginalWhenAltExists(const char* resName) { +- if (ResourceMgr_IsAltAssetsEnabled() && ResourceMgr_FileAltExists((char*)resName)) { ++ if (!NoAltAssetFiles() && ResourceMgr_IsAltAssetsEnabled() && ResourceMgr_FileAltExists((char*)resName)) { + ResourceMgr_UnloadResource((char*)resName); + } + } + + std::shared_ptr ResourceMgr_GetResourceByNameHandlingMQ(const char* path) { ++ const bool mq = ResourceMgr_IsGameMasterQuest(); ++ const bool keep = path != nullptr && NoAltAssetFiles(); ++ if (keep) { ++ std::lock_guard lock(sResolvedByNameMutex); ++ auto it = sResolvedByName.find(path); ++ if (it != sResolvedByName.end() && it->second.mq == mq && it->second.path == path) { ++ return it->second.res; ++ } ++ } + std::string Path = path; +- if (ResourceMgr_IsGameMasterQuest()) { ++ if (mq) { + size_t pos = 0; + if ((pos = Path.find("/nonmq/", 0)) != std::string::npos) { + Path.replace(pos, 7, "/mq/"); + } + } +- return Ship::Context::GetRawInstance()->GetResourceManager()->LoadResource(Path.c_str()); ++ auto res = Ship::Context::GetRawInstance()->GetResourceManager()->LoadResource(Path.c_str()); ++ if (keep && res != nullptr) { ++ std::lock_guard lock(sResolvedByNameMutex); ++ if (sResolvedByName.size() >= 4096) { ++ sResolvedByName.clear(); ++ } ++ sResolvedByName[path] = { path, mq, res }; ++ } ++ return res; + } + + extern "C" char* ResourceMgr_GetResourceDataByNameHandlingMQ(const char* path) { +diff --git a/soh/soh/mixer.c b/soh/soh/mixer.c +index 303a977d..aebbe568 100644 +--- a/soh/soh/mixer.c ++++ b/soh/soh/mixer.c +@@ -748,11 +748,11 @@ void aMixImplNEON(uint16_t count, int16_t gain, uint16_t in_addr, uint16_t out_a + int16x8_t outLoVec2 = vcombine_s16(outLoVec, outLoVec); + int16x4_t inLoVec = vget_low_s16(inVec); + int16x8_t inLoVec2 = vcombine_s16(inLoVec, inLoVec); +- int32x4_t outX7fffHiVec = vmull_high_n_s16(outVec, 0x7FFF); +- int32x4_t outX7fffLoVec = vmull_high_n_s16(outLoVec2, 0x7FFF); ++ int32x4_t outX7fffHiVec = vmull_n_s16(vget_high_s16(outVec), 0x7FFF); ++ int32x4_t outX7fffLoVec = vmull_n_s16(vget_high_s16(outLoVec2), 0x7FFF); + +- int32x4_t inGainLoVec = vmull_high_s16(inLoVec2, gainVec); +- int32x4_t inGainHiVec = vmull_high_s16(inVec, gainVec); ++ int32x4_t inGainLoVec = vmull_s16(vget_high_s16(inLoVec2), vget_high_s16(gainVec)); ++ int32x4_t inGainHiVec = vmull_s16(vget_high_s16(inVec), vget_high_s16(gainVec)); + int32x4_t addVecLo = vaddq_s32(outX7fffLoVec, inGainLoVec); + int32x4_t addVecHi = vaddq_s32(outX7fffHiVec, inGainHiVec); + addVecHi = vaddq_s32(addVecHi, x4000Vec); +diff --git a/soh/src/code/audio_load.c b/soh/src/code/audio_load.c +index d7de0389..00814510 100644 +--- a/soh/src/code/audio_load.c ++++ b/soh/src/code/audio_load.c +@@ -1252,8 +1252,8 @@ void AudioLoad_Init(void* heap, size_t heapSize) { + gAudioContext.resetTimer = 0; + + memset(&gAudioContext, 0, sizeof(gAudioContext)); +- memset(gAudioContext.seqToPlay, 0, 8); +- memset(gAudioContext.seqReplaced, 0, 8); ++ memset(gAudioContext.seqToPlay, 0, sizeof(gAudioContext.seqToPlay)); ++ memset(gAudioContext.seqReplaced, 0, sizeof(gAudioContext.seqReplaced)); + + switch (osTvType) { + case OS_TV_PAL: diff --git a/ports/spaghettikart/.gitattributes b/ports/spaghettikart/.gitattributes new file mode 100644 index 0000000..ec1ffa8 --- /dev/null +++ b/ports/spaghettikart/.gitattributes @@ -0,0 +1 @@ +*.patch -text diff --git a/ports/spaghettikart/Mario Kart 64.layout b/ports/spaghettikart/Mario Kart 64.layout new file mode 100644 index 0000000..60c7a3c --- /dev/null +++ b/ports/spaghettikart/Mario Kart 64.layout @@ -0,0 +1,8 @@ +# N64 pad layout for this port: which SDL element the game reads for each N64 function, +# so a real N64 pad plays like the built-in buttons do here. Used when an N64 pad is +# plugged in (Settings > Controls); see docs/native-games.md, "Layouts". +# Functions: a b z l r start cup cdown cleft cright dpup dpdown dpleft dpright ("none" drops one). +# Left alone, an N64 pad is: a=a b=b z=lefttrigger l=leftshoulder r=rightshoulder +# (+ a copy of r on the right trigger), C buttons on the right stick, D-pad on the hat. +# Mario Kart 64: C-left is Y here. +cleft = y diff --git a/ports/spaghettikart/Mario Kart 64.sh b/ports/spaghettikart/Mario Kart 64.sh new file mode 100644 index 0000000..c5341ba --- /dev/null +++ b/ports/spaghettikart/Mario Kart 64.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# Mario Kart 64 (SpaghettiKart), built from your own ROM by ports/spaghettikart/build-spaghettikart.sh. +# The game data (mk64.o2r, spaghetti.o2r), settings and saves stay in spaghettikart/. +cd spaghettikart || exit 1 +export SHIP_HOME="$PWD" +# The built-in controls as one standard gamepad (rsos-gamepad); SDL then +# ignores the raw button devices. It runs in the +# game's process group: the menu stops it with the game. +if [ -x /usr/bin/rsos-gamepad ]; then + SDL_GAMECONTROLLERCONFIG="$(/usr/bin/rsos-gamepad --print-mapping)" + export SDL_GAMECONTROLLERCONFIG + export SDL_GAMECONTROLLER_IGNORE_DEVICES=0x0001/0x0001 + /usr/bin/rsos-gamepad & + usleep 300000 +fi +if [ -x ./Spaghettify ]; then + exec ./Spaghettify +fi +exec /lib/ld-linux-armhf.so.3 ./Spaghettify diff --git a/ports/spaghettikart/README.md b/ports/spaghettikart/README.md new file mode 100644 index 0000000..bcf84cf --- /dev/null +++ b/ports/spaghettikart/README.md @@ -0,0 +1,81 @@ +# Mario Kart 64 (SpaghettiKart) on the RetroStone2 + +[SpaghettiKart](https://github.com/HarbourMasters/SpaghettiKart) is the PC port of the Mario Kart 64 +decompilation, built on HarbourMasters' [libultraship](https://github.com/Kenix3/libultraship), like Star Fox 64 +and Ocarina of Time ([../starship](../starship/README.md), [../soh](../soh/README.md)). This folder adds the same +OpenGL ES 2.0 mode to SpaghettiKart's libultraship and builds the game for the console as a native game +(docs/native-games.md). + +**Nothing from the game is in this repository, the OS images or the updates.** The game's data comes from **your +own ROM** on your PC and stays yours. SpaghettiKart takes one ROM only: **Mario Kart 64 (US)**, SHA-1 +`579c48e211ae952530ffc8738709f078d5dd215e` in `.z64` order (`.v64` and `.n64` dumps are converted). A modified +dump (`[h]`, `[t]`, `[f]` in its name) has another checksum and is refused. + +## Build + +```sh +ports/spaghettikart/build-spaghettikart.sh ~/"Mario Kart 64 (U).z64" ~/my-ports +``` + +It fetches SpaghettiKart at a fixed commit into `~/rsos/spaghettikart-work`, applies `spaghettikart.patch` and +`libultraship-gles2.patch`, builds the game for the console (`USE_GLES2`, the RetroStoneOS cross compiler) and +Torch for the PC, which makes `mk64.o2r` from the ROM and `spaghetti.o2r` (with the patched shaders), then +writes: + +``` +~/my-ports/roms/native/Mario Kart 64.sh +~/my-ports/roms/native/spaghettikart/ Spaghettify, mk64.o2r, spaghetti.o2r, config.yml, yamls/, meta/ +``` + +Copy the `roms` folder onto the SD card's **RETROSTONE** partition; in the menu: **Native games > Mario Kart +64**. Settings and saves stay in `roms/native/spaghettikart/` (`SHIP_HOME`). Hold **Select + Start** for a +second to go back to the menu. The console needs a RetroStoneOS with Native games, the port libraries and +`rsos-gamepad`. + +## Controls + +Through `rsos-gamepad` (by position), by the labels on the console. They are the defaults of a GLES2 build, set +on the first start and changeable in the game's menu afterwards: + +| RetroStone2 | N64 | +|---|---| +| B (bottom) | A (accelerate) | +| A (right) | B (brake) | +| Y (left) or L2 | Z (item) | +| R1 or R2 | R (hop, drift) | +| L1 | L | +| X (top) | C-left | +| Start | Start | +| Analog stick (Pro), D-pad | steering, the D-pad | + +## What the patches change + +* **`libultraship-gles2.patch`**: Ship of Harkinian's GLES2 patch ([../soh](../soh/README.md): the OpenGL ES 2.0 + mode, the 32-bit ARM and Mali-400 fixes, the speed work), carried over to SpaghettiKart's libultraship + (`60c9bb7`, 25 commits before Ship of Harkinian's). This older libultraship dropped every texture address + below `0x10000000` on Linux, which on 32-bit ARM is the heap: the same fix applies. Also backported from newer + libultraship (`766a6bad`): SIGTERM no longer calls `exit()` inside the signal handler, whose destructors + deadlocked. The menu quits a native game with SIGTERM, so every quit hung until the menu killed the game; it + now quits at once. One speed change measured on the console: loading a texture that is already bound no longer + ends the draw call (Mario Kart reloads its textures between every few triangles, and on the Mali-400 each draw + call costs ~0.1 ms of CPU). +* **`spaghettikart.patch`**, SpaghettiKart's own code, for GLES2 builds (`USE_GLES2`, now passed to the game too): + * the GLES2 changes in its own copy of the shaders (packed into `spaghetti.o2r`); + * no screen readback every race frame: it copied the screen to a 320x240 framebuffer and read it back to the + CPU (`glReadPixels`, the CPU waits for the GPU) on every track, for the jumbotrons of Luigi Raceway and Wario + Stadium. GLES2 cannot make that copy (the screen is flipped), so their screens are black, made and uploaded + once instead of six texture uploads a frame; + * first start: linear texture filtering (one sample instead of three-point's three); + * the controls above; + * Toad's Turnpike (an upstream bug): the finish line was placed with `xOrientation`, which is only set when the + race is set up, after the track is made. On the first race after starting the game it was 0 and a pole stood + in the road; it now uses the mirror mode chosen in the menu, as Wario Stadium does. +* **`build-spaghettikart.sh`** builds with `-O3 -funsafe-math-optimizations` instead of Buildroot's `-O2`: GCC uses + NEON for float math on 32-bit ARM only with unsafe math, and libultraship's vertex and triangle work is the + busiest code. + +## Status + +**Works** on the RetroStone2: races, menus, sound, saves, quitting to the menu. Mostly 30 fps; busy places are +CPU-bound by the number of draw calls (measured 190-260 a frame before the draw-call change). Building `mk64.o2r` +logs one "Failed to process" per track for its last packed display list: an empty end marker that nothing uses. diff --git a/ports/spaghettikart/build-spaghettikart.sh b/ports/spaghettikart/build-spaghettikart.sh new file mode 100755 index 0000000..d02e853 --- /dev/null +++ b/ports/spaghettikart/build-spaghettikart.sh @@ -0,0 +1,99 @@ +#!/bin/bash +# Builds Mario Kart 64 (SpaghettiKart) for RetroStoneOS from YOUR OWN ROM, on the PC +# (Linux/WSL), as a native game for the SD card (docs/native-games.md). +# +# ports/spaghettikart/build-spaghettikart.sh [output folder] +# +# Needs a built RetroStoneOS tree for the RetroStone2 with SDL2 and the port +# libraries (the RetroStone2 configs): ~/rsos/output, or RSOS_OUTPUT=; cmake, +# ninja, python3 and a C++ compiler for the PC (Torch, the asset extractor, runs here). +# SpaghettiKart is fetched at a fixed commit into ~/rsos/spaghettikart-work +# (RSOS_SPAGHETTIKART_WORK) and patched (spaghettikart.patch, libultraship-gles2.patch). +# +# The result contains the game's data, taken from your ROM: keep it for +# yourself. Never put it in a release, an update or a repository. +# +# Output (default ./spaghettikart-retrostone2): roms/native/Mario Kart 64.sh and +# roms/native/spaghettikart/. Copy the "roms" folder onto the SD card's RETROSTONE +# partition (it merges with the roms folder there). +set -euo pipefail + +REPO=https://github.com/HarbourMasters/SpaghettiKart.git +COMMIT=ce0f9358f0505bbdeb76b1aff7a25556cda3fdef # libultraship 60c9bb7, Torch 2d474dd +ROM_SHA1=579c48e211ae952530ffc8738709f078d5dd215e # Mario Kart 64 (US), .z64 order + +here=$(cd "$(dirname "$0")" && pwd) +rom=${1:-} +out=${2:-$PWD/spaghettikart-retrostone2} +O=${RSOS_OUTPUT:-$HOME/rsos/output} +W=${RSOS_SPAGHETTIKART_WORK:-$HOME/rsos/spaghettikart-work} + +die() { echo "build-spaghettikart: $*" >&2; exit 1; } + +[ -n "$rom" ] || die "usage: $0 [output folder]" +[ -f "$rom" ] || die "$rom: no such file" +rom=$(cd "$(dirname "$rom")" && pwd)/$(basename "$rom") +case "$out" in /*) ;; *) out=$PWD/$out ;; esac +[ -x "$O/host/bin/arm-linux-gcc" ] || die "no cross compiler in $O/host/bin (build RetroStoneOS first)" +for lib in libSDL2.so libzip.so libtinyxml2.so libspdlog.so libvorbisfile.so; do + [ -e "$O/staging/usr/lib/$lib" ] || die "$lib is not in $O/staging (build RetroStoneOS with the RetroStone2 configs)" +done +TOOLCHAIN=$O/host/share/buildroot/toolchainfile.cmake + +# only the fixed commit (the whole history is large) +if [ ! -d "$W/.git" ]; then + git init -q "$W" + git -C "$W" remote add origin "$REPO" +fi +cd "$W" +git fetch -q --depth 1 origin "$COMMIT" +# a clean tree at the fixed commit, then our changes (the build folder, the +# ROM and the .o2r files are ignored by git and stay) +git checkout -q -f "$COMMIT" +git submodule update -q --init --force --depth 1 libultraship torch +git -C libultraship checkout -q -f . +git apply "$here/spaghettikart.patch" +git -C libultraship apply "$here/libultraship-gles2.patch" + +# the ROM, in .z64 byte order, as baserom.us.z64 (the only one SpaghettiKart takes) +python3 - "$rom" baserom.us.z64 << 'EOF' || die "$rom is not an N64 ROM" +import sys +data = bytearray(open(sys.argv[1], 'rb').read()) +head = bytes(data[:4]) +if head == b'\x37\x80\x40\x12': # .v64: 16-bit words swapped + data[0::2], data[1::2] = data[1::2], data[0::2] +elif head == b'\x40\x12\x37\x80': # .n64: 32-bit words reversed + for i in range(0, len(data) - 3, 4): + data[i:i + 4] = data[i:i + 4][::-1] +elif head != b'\x80\x37\x12\x40': + sys.exit(1) +open(sys.argv[2], 'wb').write(data) +EOF +sum=$(sha1sum baserom.us.z64 | cut -d' ' -f1) +[ "$sum" = "$ROM_SHA1" ] || + die "$rom is not the Mario Kart 64 (US) ROM SpaghettiKart takes (SHA-1 $sum in .z64 order, needs $ROM_SHA1; a modified dump such as [h] or [t] does not work)" + +# the game for the console. CMAKE_SYSTEM_NAME Linux: Buildroot's toolchain file names it +# "Buildroot", which skips libultraship's Linux parts. Torch is built for this PC (its own +# sub-build) and makes mk64.o2r from the ROM and spaghetti.o2r (with the patched shaders). +# Release flags: Buildroot's toolchain file builds with -O2, and GCC uses NEON for float math on +# 32-bit ARM only with unsafe math; libultraship's vertex and triangle work is the busiest code. +fast="-O3 -DNDEBUG -fno-math-errno -funsafe-math-optimizations" +cmake -S . -B build-gles2 -G Ninja -DCMAKE_BUILD_TYPE=Release -DUSE_OPENGLES=ON -DUSE_GLES2=ON \ + -DCMAKE_C_FLAGS_RELEASE="$fast" -DCMAKE_CXX_FLAGS_RELEASE="$fast" \ + -DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN" -DCMAKE_SYSTEM_NAME=Linux +cmake --build build-gles2 --target Spaghettify +cmake --build build-gles2 --target ExtractAssets + +file build-gles2/Spaghettify | grep -q 'ARM' || die "build-gles2/Spaghettify is not an ARM program" +S=$out/roms/native/spaghettikart +mkdir -p "$S" +"$O/host/bin/arm-linux-strip" -o "$S/Spaghettify" build-gles2/Spaghettify +cp build-gles2/mk64.o2r build-gles2/spaghetti.o2r "$S/" +cp -r build-gles2/config.yml build-gles2/yamls build-gles2/meta "$S/" +[ -f build-gles2/gamecontrollerdb.txt ] && cp build-gles2/gamecontrollerdb.txt "$S/" +install -m 0644 "$here/Mario Kart 64.sh" "$out/roms/native/Mario Kart 64.sh" +echo +echo "Done: $out/roms" +echo "Copy that \"roms\" folder onto the SD card's RETROSTONE partition, then in the menu:" +echo "Native games > Mario Kart 64. Hold Select + Start to quit." diff --git a/ports/spaghettikart/libultraship-gles2.patch b/ports/spaghettikart/libultraship-gles2.patch new file mode 100644 index 0000000..bc7521f --- /dev/null +++ b/ports/spaghettikart/libultraship-gles2.patch @@ -0,0 +1,872 @@ +diff --git a/cmake/dependencies/linux.cmake b/cmake/dependencies/linux.cmake +index 02301f1..8e231e1 100644 +--- a/cmake/dependencies/linux.cmake ++++ b/cmake/dependencies/linux.cmake +@@ -2,7 +2,10 @@ + find_package(SDL2 REQUIRED) + target_link_libraries(ImGui PUBLIC SDL2::SDL2) + +-if (USE_OPENGLES) ++if (USE_GLES2) ++ target_link_libraries(ImGui PUBLIC GLESv2) ++ add_compile_definitions(IMGUI_IMPL_OPENGL_ES2) ++elseif (USE_OPENGLES) + target_link_libraries(ImGui PUBLIC ${OPENGL_GLESv2_LIBRARY}) + add_compile_definitions(IMGUI_IMPL_OPENGL_ES3) + else() +diff --git a/include/fast/backends/gfx_opengl.h b/include/fast/backends/gfx_opengl.h +index af24c70..efdf5c5 100644 +--- a/include/fast/backends/gfx_opengl.h ++++ b/include/fast/backends/gfx_opengl.h +@@ -16,6 +16,10 @@ + #elif __APPLE__ + #include + #include ++#elif defined(USE_GLES2) ++#include ++#include ++#include + #elif USE_OPENGLES + #include + #include +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index 45989b6..0209da4 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -11,6 +11,11 @@ find_package(Python3 REQUIRED COMPONENTS Interpreter) + + set(INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../include) + option(USE_OPENGLES "Enable GLES3" OFF) ++# OpenGL ES 2.0 (Mali-400 and other GLES2-only GPUs); implies USE_OPENGLES ++option(USE_GLES2 "Enable GLES2" OFF) ++if (USE_GLES2) ++ set(USE_OPENGLES ON) ++endif() + option(GFX_DEBUG_DISASSEMBLER "Enable libgfxd" OFF) + + if (CMAKE_SYSTEM_NAME STREQUAL "Windows") +@@ -208,6 +213,7 @@ else() + $<$>:NDEBUG> + SPDLOG_ACTIVE_LEVEL=${SPDLOG_MIN_CUTOFF} + $<$:USE_OPENGLES> ++ $<$:USE_GLES2> + $<$:GFX_DEBUG_DISASSEMBLER> + ) + endif() +diff --git a/src/fast/Fast3dGui.cpp b/src/fast/Fast3dGui.cpp +index 237a502..8c939c0 100644 +--- a/src/fast/Fast3dGui.cpp ++++ b/src/fast/Fast3dGui.cpp +@@ -146,6 +146,8 @@ void Fast3dGui::ImGuiBackendInit() { + case WindowBackend::FAST3D_SDL_OPENGL: + #ifdef __APPLE__ + ImGui_ImplOpenGL3_Init("#version 410 core"); ++#elif defined(USE_GLES2) ++ ImGui_ImplOpenGL3_Init("#version 100"); + #elif USE_OPENGLES + ImGui_ImplOpenGL3_Init("#version 300 es"); + #else +diff --git a/src/fast/backends/gfx_opengl.cpp b/src/fast/backends/gfx_opengl.cpp +index ad9b1dd..2f6e080 100644 +--- a/src/fast/backends/gfx_opengl.cpp ++++ b/src/fast/backends/gfx_opengl.cpp +@@ -27,6 +27,52 @@ + #include "fast/interpreter.h" + #include "ship/config/ConsoleVariable.h" + ++// a texture was bound outside SelectTexture(): its cache no longer says what is bound ++#define FORGET_TEXTURE_BINDINGS() do { mLastActiveTexture = -1; for (GLuint& bound : mLastBoundTextures) bound = (GLuint)-1; } while (0) ++ ++#include ++ ++#ifdef USE_GLES2 ++/* ++ * OpenGL ES 2.0: no sized texture formats, no multisampling, no blits and no ++ * depth reads. Multisampling stays off (mMaxMsaaLevel 1), so the multisample ++ * calls below are never reached; CopyFramebuffer and GetPixelDepth have their ++ * own GLES2 versions. Depth: packed depth+stencil when the driver has ++ * GL_OES_packed_depth_stencil, else a 16-bit depth buffer. ++ */ ++#define GL_RGB8 GL_RGB ++#define GL_RGBA8 GL_RGBA ++#define GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8_OES ++#define GL_DEPTH_STENCIL GL_DEPTH_STENCIL_OES ++#define GL_UNSIGNED_INT_24_8 GL_UNSIGNED_INT_24_8_OES ++#define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER ++#define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER ++#define glBlitFramebuffer(...) ((void)0) ++#define glReadBuffer(b) ((void)0) ++#define glRenderbufferStorageMultisample(target, samples, format, w, h) glRenderbufferStorage(target, format, w, h) ++static bool sPackedDepthStencil = true; ++#endif ++ ++namespace Fast { ++static void RenderbufferDepthStorage(GLsizei width, GLsizei height) { ++#ifdef USE_GLES2 ++ glRenderbufferStorage(GL_RENDERBUFFER, sPackedDepthStencil ? GL_DEPTH24_STENCIL8_OES : GL_DEPTH_COMPONENT16, ++ width, height); ++#else ++ glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); ++#endif ++} ++ ++static void FramebufferDepthAttach(GLuint rb) { ++#ifdef USE_GLES2 ++ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb); ++ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, sPackedDepthStencil ? rb : 0); ++#else ++ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb); ++#endif ++} ++} // namespace Fast ++ + namespace Fast { + int GfxRenderingAPIOGL::GetMaxTextureSize() { + GLint max_texture_size; +@@ -42,7 +88,17 @@ GfxClipParameters GfxRenderingAPIOGL::GetClipParameters() { + return { false, mFrameBuffers[mCurrentFrameBuffer].invertY }; + } + +-static void VertexArraySetAttribs(ShaderProgram* prg) { ++#ifdef USE_GLES2 ++static ShaderProgram* sClientArrayProgram; ++static const float* sClientArrayBase; ++#endif ++ ++static void VertexArraySetAttribs(ShaderProgram* prg, const float* clientArray = nullptr) { ++#ifdef USE_GLES2 ++ if (clientArray == nullptr) { ++ sClientArrayProgram = nullptr; // set for a buffer object: the next draw sets them again ++ } ++#endif + size_t numFloats = prg->numFloats; + size_t pos = 0; + +@@ -50,7 +106,9 @@ static void VertexArraySetAttribs(ShaderProgram* prg) { + if (prg->attribLocations[i] >= 0) { + glEnableVertexAttribArray(prg->attribLocations[i]); + glVertexAttribPointer(prg->attribLocations[i], prg->attribSizes[i], GL_FLOAT, GL_FALSE, +- numFloats * sizeof(float), (void*)(pos * sizeof(float))); ++ numFloats * sizeof(float), ++ clientArray != nullptr ? (const void*)(clientArray + pos) ++ : (const void*)(pos * sizeof(float))); + } + pos += prg->attribSizes[i]; + } +@@ -285,13 +343,23 @@ std::string GfxRenderingAPIOGL::BuildFsShader(const CCFeatures& cc_features) { + { "attr", "in" }, + { "opengles", false }, + { "core_opengl", true }, ++ { "gles2", false }, + { "texture", "texture" }, + { "vOutColor", "vOutColor" }, ++#elif defined(USE_GLES2) ++ { "GLSL_VERSION", "#version 100\nprecision mediump float;" }, ++ { "attr", "varying" }, ++ { "opengles", false }, ++ { "core_opengl", false }, ++ { "gles2", true }, ++ { "texture", "texture2D" }, ++ { "vOutColor", "gl_FragColor" }, + #elif defined(USE_OPENGLES) + { "GLSL_VERSION", "#version 300 es\nprecision mediump float;" }, + { "attr", "in" }, + { "opengles", true }, + { "core_opengl", false }, ++ { "gles2", false }, + { "texture", "texture" }, + { "vOutColor", "vOutColor" }, + #else +@@ -299,6 +367,7 @@ std::string GfxRenderingAPIOGL::BuildFsShader(const CCFeatures& cc_features) { + { "attr", "varying" }, + { "opengles", false }, + { "core_opengl", false }, ++ { "gles2", false }, + { "texture", "texture2D" }, + { "vOutColor", "gl_FragColor" }, + #endif +@@ -356,6 +425,11 @@ static std::string BuildVsShader(const CCFeatures& cc_features) { + { "attr", "in" }, + { "out", "out" }, + { "opengles", false } ++#elif defined(USE_GLES2) ++ { "GLSL_VERSION", "#version 100" }, ++ { "attr", "attribute" }, ++ { "out", "varying" }, ++ { "opengles", false } + #elif defined(USE_OPENGLES) + { "GLSL_VERSION", "#version 300 es" }, + { "attr", "in" }, +@@ -420,9 +494,8 @@ ShaderProgram* GfxRenderingAPIOGL::CreateAndLoadNewShader(uint64_t shader_id0, u + GLint max_length = 0; + glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &max_length); + char error_log[1024]; +- // fprintf(stderr, "Vertex shader compilation failed\n"); +- glGetShaderInfoLog(vertex_shader, max_length, &max_length, &error_log[0]); +- // fprintf(stderr, "%s\n", &error_log[0]); ++ glGetShaderInfoLog(vertex_shader, sizeof(error_log), nullptr, error_log); ++ fprintf(stderr, "Vertex shader compilation failed:\n%s\n%s\n", error_log, vs_buf.c_str()); + abort(); + } + +@@ -434,9 +507,8 @@ ShaderProgram* GfxRenderingAPIOGL::CreateAndLoadNewShader(uint64_t shader_id0, u + GLint max_length = 0; + glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &max_length); + char error_log[1024]; +- fprintf(stderr, "Fragment shader compilation failed\n"); +- glGetShaderInfoLog(fragment_shader, max_length, &max_length, &error_log[0]); +- fprintf(stderr, "%s\n", &error_log[0]); ++ glGetShaderInfoLog(fragment_shader, sizeof(error_log), nullptr, error_log); ++ fprintf(stderr, "Fragment shader compilation failed:\n%s\n%s\n", error_log, fs_buf.c_str()); + abort(); + } + +@@ -559,6 +631,7 @@ GLuint GfxRenderingAPIOGL::NewTexture() { + + void GfxRenderingAPIOGL::DeleteTexture(uint32_t texID) { + glDeleteTextures(1, &texID); ++ FORGET_TEXTURE_BINDINGS(); // deleting unbinds it, and the name comes back with the next texture + } + + void GfxRenderingAPIOGL::SelectTexture(int tile, GLuint texture_id) { +@@ -583,7 +656,9 @@ void GfxRenderingAPIOGL::UploadTexture(const uint8_t* rgba32_buf, uint32_t width + textures[mCurrentTextureIds[mCurrentTile]].height = height; + } + +-#ifdef USE_OPENGLES ++#ifdef USE_GLES2 ++#define GL_MIRROR_CLAMP_TO_EDGE GL_MIRRORED_REPEAT ++#elif defined(USE_OPENGLES) + #define GL_MIRROR_CLAMP_TO_EDGE 0x8743 + #endif + +@@ -703,7 +778,17 @@ void GfxRenderingAPIOGL::DrawTriangles(float buf_vbo[], size_t buf_vbo_len, size + SetPerDrawUniforms(); + + // printf("flushing %d tris\n", buf_vbo_num_tris); ++#ifdef USE_GLES2 ++ // the pointers stay valid until the program changes or ImGui draws (after the frame) ++ if (mCurrentShaderProgram != sClientArrayProgram || buf_vbo != sClientArrayBase) { ++ glBindBuffer(GL_ARRAY_BUFFER, 0); ++ VertexArraySetAttribs(mCurrentShaderProgram, buf_vbo); ++ sClientArrayProgram = mCurrentShaderProgram; ++ sClientArrayBase = buf_vbo; ++ } ++#else + glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buf_vbo_len, buf_vbo, GL_STREAM_DRAW); ++#endif + glDrawArrays(GL_TRIANGLES, 0, 3 * buf_vbo_num_tris); + } + +@@ -715,7 +800,16 @@ void GfxRenderingAPIOGL::Init() { + glGenBuffers(1, &mOpenglVbo); + glBindBuffer(GL_ARRAY_BUFFER, mOpenglVbo); + +-#if defined(__APPLE__) || defined(USE_OPENGLES) ++#ifdef USE_GLES2 ++ { ++ const char* ext = (const char*)glGetString(GL_EXTENSIONS); ++ ++ sPackedDepthStencil = ext != nullptr && strstr(ext, "GL_OES_packed_depth_stencil") != nullptr; ++ SPDLOG_INFO("OpenGL ES 2.0: {} ({}), depth buffer {}", (const char*)glGetString(GL_RENDERER), ++ (const char*)glGetString(GL_VERSION), sPackedDepthStencil ? "24-bit + stencil" : "16-bit"); ++ } ++#endif ++#if defined(__APPLE__) || (defined(USE_OPENGLES) && !defined(USE_GLES2)) + glGenVertexArrays(1, &mOpenglVao); + glBindVertexArray(mOpenglVao); + #endif +@@ -730,17 +824,21 @@ void GfxRenderingAPIOGL::Init() { + + glGenRenderbuffers(1, &mPixelDepthRb); + glBindRenderbuffer(GL_RENDERBUFFER, mPixelDepthRb); +- glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 1, 1); ++ RenderbufferDepthStorage(1, 1); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + + glGenFramebuffers(1, &mPixelDepthFb); + glBindFramebuffer(GL_FRAMEBUFFER, mPixelDepthFb); +- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mPixelDepthRb); ++ FramebufferDepthAttach(mPixelDepthRb); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + + mPixelDepthRbSize = 1; + ++#ifdef USE_GLES2 ++ mMaxMsaaLevel = 1; ++#else + glGetIntegerv(GL_MAX_SAMPLES, &mMaxMsaaLevel); ++#endif + } + + void GfxRenderingAPIOGL::OnResize() { +@@ -748,6 +846,9 @@ void GfxRenderingAPIOGL::OnResize() { + + void GfxRenderingAPIOGL::StartFrame() { + mFrameCount++; ++#ifdef USE_GLES2 ++ sClientArrayProgram = nullptr; // ImGui drew with its own arrays ++#endif + } + + void GfxRenderingAPIOGL::EndFrame() { +@@ -764,7 +865,12 @@ int GfxRenderingAPIOGL::CreateFramebuffer() { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); ++#ifdef USE_GLES2 ++ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); ++ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); ++#endif + glBindTexture(GL_TEXTURE_2D, 0); ++ FORGET_TEXTURE_BINDINGS(); + + GLuint clrbufMsaa; + glGenRenderbuffers(1, &clrbufMsaa); +@@ -772,7 +878,7 @@ int GfxRenderingAPIOGL::CreateFramebuffer() { + GLuint rbo; + glGenRenderbuffers(1, &rbo); + glBindRenderbuffer(GL_RENDERBUFFER, rbo); +- glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 1, 1); ++ RenderbufferDepthStorage(1, 1); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + + GLuint fbo; +@@ -806,6 +912,7 @@ void GfxRenderingAPIOGL::UpdateFramebufferParameters(int fb_id, uint32_t width, + glBindTexture(GL_TEXTURE_2D, fb.clrbuf); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); + glBindTexture(GL_TEXTURE_2D, 0); ++ FORGET_TEXTURE_BINDINGS(); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb.clrbuf, 0); + } else { + glBindRenderbuffer(GL_RENDERBUFFER, fb.clrbufMsaa); +@@ -819,7 +926,7 @@ void GfxRenderingAPIOGL::UpdateFramebufferParameters(int fb_id, uint32_t width, + (fb.width != width || fb.height != height || fb.msaa_level != msaa_level || !fb.has_depth_buffer)) { + glBindRenderbuffer(GL_RENDERBUFFER, fb.rbo); + if (msaa_level <= 1) { +- glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); ++ RenderbufferDepthStorage(width, height); + } else { + glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa_level, GL_DEPTH24_STENCIL8, width, height); + } +@@ -827,9 +934,9 @@ void GfxRenderingAPIOGL::UpdateFramebufferParameters(int fb_id, uint32_t width, + } + + if (!fb.has_depth_buffer && has_depth_buffer) { +- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fb.rbo); ++ FramebufferDepthAttach(fb.rbo); + } else if (fb.has_depth_buffer && !has_depth_buffer) { +- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0); ++ FramebufferDepthAttach(0); + } + } + +@@ -932,6 +1039,35 @@ void GfxRenderingAPIOGL::CopyFramebuffer(int fb_dst_id, int fb_src_id, int srcX0 + FramebufferOGL src = mFrameBuffers[fb_src_id]; + const FramebufferOGL& dst = mFrameBuffers[fb_dst_id]; + ++#ifdef USE_GLES2 ++ // No blits: copy into the destination's colour texture, unscaled and in the ++ // same orientation only (G_COPYFB effects; Starship does not use them). ++ if (fb_dst_id == 0 || srcX1 - srcX0 != dstX1 - dstX0 || srcY1 - srcY0 != dstY1 - dstY0 || ++ src.invertY != dst.invertY) { ++ static bool warned; ++ if (!warned) { ++ SPDLOG_WARN("GLES2: scaled, flipped or on-screen framebuffer copies are not supported"); ++ warned = true; ++ } ++ return; ++ } ++ // OpenGL's origin is the bottom left, as in the blit path below ++ if (!src.invertY) { ++ int h = srcY1 - srcY0; ++ srcY1 = src.height - srcY0; ++ srcY0 = srcY1 - h; ++ } ++ glDisable(GL_SCISSOR_TEST); ++ glBindFramebuffer(GL_FRAMEBUFFER, src.fbo); ++ glActiveTexture(GL_TEXTURE0); ++ glBindTexture(GL_TEXTURE_2D, dst.clrbuf); ++ glCopyTexSubImage2D(GL_TEXTURE_2D, 0, dstX0, dstY0, srcX0, srcY0, srcX1 - srcX0, srcY1 - srcY0); ++ glBindFramebuffer(GL_FRAMEBUFFER, mFrameBuffers[mCurrentFrameBuffer].fbo); ++ glEnable(GL_SCISSOR_TEST); ++ FORGET_TEXTURE_BINDINGS(); ++ return; ++#endif ++ + // Adjust y values for non-inverted source frame buffers because opengl uses bottom left for origin + if (!src.invertY) { + int temp = srcY1 - srcY0; +@@ -1024,6 +1160,14 @@ std::unordered_map, uint16_t, hash_pair_ff> + GfxRenderingAPIOGL::GetPixelDepth(int fb_id, const std::set>& coordinates) { + std::unordered_map, uint16_t, hash_pair_ff> res; + ++#ifdef USE_GLES2 ++ // GLES2 cannot read the depth buffer: every point is reported at the far plane ++ for (const auto& coord : coordinates) { ++ res.emplace(coord, 0xFFFC); ++ } ++ return res; ++#endif ++ + FramebufferOGL& fb = mFrameBuffers[fb_id]; + + // When looking up one value and the framebuffer is single-sampled, we can read pixels directly +@@ -1045,8 +1189,8 @@ GfxRenderingAPIOGL::GetPixelDepth(int fb_id, const std::set + #include + #include ++#ifndef _WIN32 ++#include ++#include ++#include ++#endif + + #include + #include +@@ -131,6 +136,64 @@ void GfxSetInstance(std::shared_ptr gfx) { + // N64 prim_depth is 15-bit (0 near, 0x7FFF far). + static constexpr float N64_PRIM_DEPTH_MAX = 32767.0f; + ++// Alternate ("alt/") assets are unloaded and loaded again as new objects; with any in the ++// archives, nothing is kept (decided once: archives are added at start only) ++static bool NoAltAssetFiles() { ++ static const bool none = ++ Ship::Context::GetRawInstance()->GetResourceManager()->GetArchiveManager()->ListFiles("alt/*")->empty(); ++ return none; ++} ++ ++static std::unordered_map> sHashResourceCache; ++ ++// texture paths named by pointer: kept per pointer, checked against a copy of the path ++struct ResolvedPath { ++ std::string path; ++ std::shared_ptr res; ++}; ++static std::unordered_map sPathResourceCache; ++ ++static std::shared_ptr CachedResourceByHash(uint64_t hash) { ++ if (!NoAltAssetFiles()) { ++ return Ship::Context::GetRawInstance()->GetResourceManager()->LoadResource(hash); ++ } ++ auto it = sHashResourceCache.find(hash); ++ if (it != sHashResourceCache.end()) { ++ return it->second; ++ } ++ auto res = Ship::Context::GetRawInstance()->GetResourceManager()->LoadResource(hash); ++ if (res != nullptr) { ++ if (sHashResourceCache.size() >= 4096) { ++ sHashResourceCache.clear(); ++ } ++ sHashResourceCache.emplace(hash, res); ++ } ++ return res; ++} ++ ++static std::shared_ptr CachedResourceByPath(const char* path) { ++ if (!NoAltAssetFiles()) { ++ return Ship::Context::GetRawInstance()->GetResourceManager()->LoadResourceProcess(path); ++ } ++ auto found = sPathResourceCache.find(path); ++ if (found != sPathResourceCache.end() && found->second.path == path) { ++ return found->second.res; ++ } ++ auto res = Ship::Context::GetRawInstance()->GetResourceManager()->LoadResourceProcess(path); ++ if (res != nullptr) { ++ if (sPathResourceCache.size() >= 4096) { ++ sPathResourceCache.clear(); ++ } ++ sPathResourceCache[path] = { path, res }; ++ } ++ return res; ++} ++ ++static void* CachedResourceRawPointer(uint64_t hash) { ++ auto res = CachedResourceByHash(hash); ++ return res != nullptr ? res->GetRawPointer() : nullptr; ++} ++ + void Interpreter::Flush() { + if (mBufVboLen > 0) { + mRapi->SetCurrentPrimDepth((float)mRdp->prim_depth / N64_PRIM_DEPTH_MAX); +@@ -447,6 +510,8 @@ void Interpreter::TextureCacheClear() { + } + mTextureCache.map.clear(); + mTextureCache.lru.clear(); ++ sHashResourceCache.clear(); ++ sPathResourceCache.clear(); + // Pre-allocate buckets so the map never rehashes during normal operation. + // Rehashing invalidates all iterators, including those stored in LRU entries. + mTextureCache.map.reserve(TEXTURE_CACHE_MAX_SIZE); +@@ -1242,6 +1307,7 @@ void Interpreter::ImportTexture(int i, int tile, bool importReplacement) { + if (fbIt != mFbTextures.end()) { + Flush(); + mRapi->SelectTextureFb(fbIt->second); ++ mRenderingState.mTextures[i] = nullptr; + mRdp->textures_changed[i] = false; + return; + } +@@ -1285,6 +1351,15 @@ void Interpreter::ImportTexture(int i, int tile, bool importReplacement) { + key = { origAddr, {}, fmt, siz, paletteIndex, origSizeBytes }; + } + ++ // The texture already bound to this slot: the triangles so far can keep going (selected ++ // again in case the backend lost its bindings) ++ if (!importReplacement && mRenderingState.mTextures[i] != nullptr && ++ mRenderingState.mTextures[i]->first == key) { ++ mRapi->SelectTexture(i, mRenderingState.mTextures[i]->second.texture_id); ++ return; ++ } ++ Flush(); ++ + if (TextureCacheLookup(i, key)) { + return; + } +@@ -1886,9 +1961,11 @@ void Interpreter::GfxSpTri1(uint8_t vtx1_idx, uint8_t vtx2_idx, uint8_t vtx3_idx + if (use_grayscale) { + cc_options |= SHADER_OPT(GRAYSCALE); + } ++#ifndef USE_GLES2 + if (use_prim_depth) { + cc_options |= SHADER_OPT(PRIM_DEPTH); + } ++#endif + + if (!mShaderStack.empty()) { + cc_options |= (mShaderStack.top() << SHADER_ID_SHIFT); +@@ -1916,8 +1993,9 @@ void Interpreter::GfxSpTri1(uint8_t vtx1_idx, uint8_t vtx2_idx, uint8_t vtx3_idx + ColorCombiner* comb = LookupOrCreateColorCombiner(key); + + uint32_t tm = 0; +- uint32_t tex_width[2], tex_height[2], tex_width2[2], tex_height2[2]; +- uint32_t effective_tile[2]; ++ uint32_t tex_width[2] = { 1, 1 }, tex_height[2] = { 1, 1 }, tex_width2[2] = { 1, 1 }, ++ tex_height2[2] = { 1, 1 }; ++ uint32_t effective_tile[2] = { mRdp->first_tile_index, mRdp->first_tile_index }; + + for (int i = 0; i < 2; i++) { + uint32_t tile = mRdp->first_tile_index + i; +@@ -1930,12 +2008,13 @@ void Interpreter::GfxSpTri1(uint8_t vtx1_idx, uint8_t vtx2_idx, uint8_t vtx3_idx + + if (comb->usedTextures[i]) { + if (mRdp->textures_changed[i]) { +- Flush(); +- ImportTexture(i, tile, false); ++ ImportTexture(i, tile, false); // flushes if the texture changes + if (mRdp->loaded_texture[i].masked) { ++ Flush(); + ImportTextureMask(SHADER_FIRST_MASK_TEXTURE + i, tile); + } + if (mRdp->loaded_texture[i].blended) { ++ Flush(); + ImportTexture(SHADER_FIRST_REPLACEMENT_TEXTURE + i, tile, true); + } + mRdp->textures_changed[i] = false; +@@ -2044,6 +2123,15 @@ void Interpreter::GfxSpTri1(uint8_t vtx1_idx, uint8_t vtx2_idx, uint8_t vtx3_idx + } + } + ++ for (int i = 0; i < 2; i++) { ++ if (!comb->usedTextures[i] && comb->usedTextures[i ^ 1]) { ++ tex_width[i] = tex_width[i ^ 1]; ++ tex_height[i] = tex_height[i ^ 1]; ++ tex_width2[i] = tex_width2[i ^ 1]; ++ tex_height2[i] = tex_height2[i ^ 1]; ++ } ++ } ++ + struct ShaderProgram* prg = comb->prg[tm]; + if (prg == NULL) { + comb->prg[tm] = prg = +@@ -2069,6 +2157,11 @@ void Interpreter::GfxSpTri1(uint8_t vtx1_idx, uint8_t vtx2_idx, uint8_t vtx3_idx + + for (int i = 0; i < 3; i++) { + float z = v_arr[i]->z, w = v_arr[i]->w; ++#ifdef USE_GLES2 ++ if (use_prim_depth) { ++ z = ((float)mRdp->prim_depth / N64_PRIM_DEPTH_MAX * 2.0f - 1.0f) * w; ++ } ++#endif + if (clip_parameters.z_is_from_0_to_1) { + z = (z + w) / 2.0f; + } +@@ -3382,7 +3475,7 @@ bool gfx_mtx_otr_handler_custom_f3dex2(F3DGfx** cmd0) { + + const uint64_t hash = ((uint64_t)cmd->words.w0 << 32) + cmd->words.w1; + const int32_t* mtx = +- (const int32_t*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ (const int32_t*)CachedResourceRawPointer(hash); + + if (mtx != NULL) { + Interpreter* gfx = mInstance.lock().get(); +@@ -3401,7 +3494,7 @@ bool gfx_mtx_otr_handler_custom_f3d(F3DGfx** cmd0) { + + const uint64_t hash = ((uint64_t)cmd->words.w0 << 32) + cmd->words.w1; + const int32_t* mtx = +- (const int32_t*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ (const int32_t*)CachedResourceRawPointer(hash); + if (mtx != nullptr) { + cmd--; + gfx->GfxSpMatrix(C0(16, 8), mtx); +@@ -3468,10 +3561,10 @@ bool gfx_movemem_handler_otr(F3DGfx** cmd0) { + + if (ucode_handler_index == ucode_f3dex2) { + gfx->GfxSpMovememF3dex2(index, offset, +- Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash)); ++ CachedResourceRawPointer(hash)); + } else { + auto light = +- (Fast::LightEntry*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ (Fast::LightEntry*)CachedResourceRawPointer(hash); + uintptr_t data = (uintptr_t)&light->Ambient; + gfx->GfxSpMovememF3d(index, offset, (void*)(data + (hasOffset == 1 ? 0x8 : 0))); + } +@@ -3610,7 +3703,7 @@ bool gfx_vtx_hash_handler_custom(F3DGfx** cmd0) { + gfx->GfxSpVertex(C0(12, 8), C0(1, 7) - C0(12, 8), (F3DVtx*)offset); + (*cmd0)++; + } else { +- F3DVtx* vtx = (F3DVtx*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ F3DVtx* vtx = (F3DVtx*)CachedResourceRawPointer(hash); + + if (vtx != NULL) { + vtx = (F3DVtx*)((char*)vtx + offset); +@@ -3702,7 +3795,7 @@ bool gfx_dl_otr_hash_handler_custom(F3DGfx** cmd0) { + + uint64_t hash = ((uint64_t)(*cmd0)->words.w0 << 32) + (*cmd0)->words.w1; + +- F3DGfx* gfx = (F3DGfx*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ F3DGfx* gfx = (F3DGfx*)CachedResourceRawPointer(hash); + + if (gfx != 0) { + g_exec_stack.call(cmd, gfx); +@@ -3760,7 +3853,7 @@ bool gfx_branch_z_otr_handler_f3dex2(F3DGfx** cmd0) { + (gfx->mRsp->extra_geometry_mode & G_EX_ALWAYS_EXECUTE_BRANCH) != 0) { + uint64_t hash = ((uint64_t)(*cmd0)->words.w0 << 32) + (*cmd0)->words.w1; + +- F3DGfx* gfx = (F3DGfx*)Ship::Context::GetRawInstance()->GetResourceManager()->GetResourceRawPointer(hash); ++ F3DGfx* gfx = (F3DGfx*)CachedResourceRawPointer(hash); + + if (gfx != 0) { + (*cmd0) = gfx; +@@ -3934,6 +4027,35 @@ bool gfx_othermode_h_handler_f3d(F3DGfx** cmd0) { + return false; + } + ++// A resolved address still in the N64 segmented range (<= 0x0FFFFFFF) usually means SegAddr ++// failed to resolve it (segment not set up). Keep it only if it belongs to a loaded module, ++// where it's a real low pointer (e.g. a static TLUT) rather than an unresolved segment addr. ++static bool IsValidResolvedAddress(uintptr_t addr) { ++ if (addr > 0x0FFFFFFF) { ++ return true; ++ } ++ ++ // Still in the N64 segmented range, but might be a false positive (a real low pointer). ++#ifdef _WIN32 ++ // For Windows, check whether the address belongs to a dll. ++ HMODULE module = nullptr; ++ return GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, ++ reinterpret_cast(addr), &module) != 0; ++#else ++ // For non-Windows platforms, check whether the address belongs to a loaded object. ++#if UINTPTR_MAX <= 0xFFFFFFFFu ++ // 32-bit: the heap and mappings live below 0x10000000 as well; a mapped page is a real address. ++ // mincore is one cheap system call (dladdr searched symbol tables: 3% of the CPU time on an A20). ++ static const uintptr_t pageSize = (uintptr_t)sysconf(_SC_PAGESIZE); ++ unsigned char resident; ++ return mincore(reinterpret_cast(addr & ~(pageSize - 1)), 1, &resident) == 0; ++#else ++ Dl_info info; ++ return dladdr(reinterpret_cast(addr), &info) != 0; ++#endif ++#endif ++} ++ + bool gfx_set_timg_handler_rdp(F3DGfx** cmd0) { + Interpreter* gfx = mInstance.lock().get(); + F3DGfx* cmd = *cmd0; +@@ -3946,11 +4068,12 @@ bool gfx_set_timg_handler_rdp(F3DGfx** cmd0) { + // from the resource, but raw textures would leave them at 0. + rawTexMetdata.h_byte_scale = 1; + rawTexMetdata.v_pixel_scale = 1; ++ bool fromResource = false; + + if ((i & 1) != 1) { + if (gfx_check_image_signature(imgData) == 1) { +- std::shared_ptr tex = std::static_pointer_cast( +- Ship::Context::GetRawInstance()->GetResourceManager()->LoadResourceProcess(imgData)); ++ std::shared_ptr tex = ++ std::static_pointer_cast(CachedResourceByPath(imgData)); + + if (tex == nullptr) { + (*cmd0)++; +@@ -3965,26 +4088,13 @@ bool gfx_set_timg_handler_rdp(F3DGfx** cmd0) { + rawTexMetdata.v_pixel_scale = tex->VPixelScale; + rawTexMetdata.type = tex->Type; + rawTexMetdata.resource = tex; ++ fromResource = true; + } + } + +- // If the resolved address is still in the N64 segmented range, SegAddr +- // failed to resolve it (segment not set up). Skip to avoid dereferencing +- // invalid memory. +- // For Windows, also check if the address is not from a dll because this validation returns a false positive caused +- // by how the virtual memory is allocated. +-#ifdef _WIN32 +- HMODULE module = nullptr; +- if (i <= 0x0FFFFFFF && +- !(GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, +- reinterpret_cast(i), &module))) { +- return false; +- } +-#else +- if (i <= 0x0FFFFFFF) { ++ if (!fromResource && !IsValidResolvedAddress(i)) { + return false; + } +-#endif + + gfx->GfxDpSetTextureImage(C0(21, 3), C0(19, 2), C0(0, 12) + 1, imgData, texFlags, rawTexMetdata, (void*)i); + +@@ -4007,8 +4117,7 @@ bool gfx_set_timg_otr_hash_handler_custom(F3DGfx** cmd0) { + } + + std::shared_ptr texture = std::static_pointer_cast( +- Ship::Context::GetRawInstance()->GetResourceManager()->LoadResourceProcess( +- Ship::Context::GetRawInstance()->GetResourceManager()->GetArchiveManager()->HashToCString(hash))); ++ CachedResourceByHash(hash)); + if (texture != nullptr) { + texFlags = texture->Flags; + rawTexMetadata.width = texture->Width; +diff --git a/src/fast/shaders/opengl/default.shader.glsl b/src/fast/shaders/opengl/default.shader.glsl +index 1fe86aa..ff45672 100644 +--- a/src/fast/shaders/opengl/default.shader.glsl ++++ b/src/fast/shaders/opengl/default.shader.glsl +@@ -134,14 +134,18 @@ + + float random(in vec3 value) { + float random = dot(sin(value), vec3(12.9898, 78.233, 37.719)); ++ @if(gles2) ++ return fract(sin(random) * 43758.5453); ++ @else + return fract(sin(random) * 143758.5453); ++ @end + } + + vec4 fromLinear(vec4 linearRGB){ + bvec3 cutoff = lessThan(linearRGB.rgb, vec3(0.0031308)); + vec3 higher = vec3(1.055)*pow(linearRGB.rgb, vec3(1.0/2.4)) - vec3(0.055); + vec3 lower = linearRGB.rgb * vec3(12.92); +- return vec4(mix(higher, lower, cutoff), linearRGB.a); ++ return vec4(mix(higher, lower, vec3(cutoff)), linearRGB.a); + } + + vec4 filter3point(in sampler2D tex, in vec2 texCoord, in vec2 texSize) { +@@ -187,7 +191,9 @@ + vec4 texVal@{i} = hookTexture2D(@{i}, uTex@{i}, vTexCoordAdj@{i}, texSize@{i}); + + @if(o_masks[i]) +- @if(opengles) ++ @if(gles2) ++ vec2 maskSize@{i} = texSize@{i}; ++ @elseif(opengles) + vec2 maskSize@{i} = vec2(textureSize(uTexMask@{i}, 0)); + @else + vec2 maskSize@{i} = textureSize(uTexMask@{i}, 0); +diff --git a/src/libultraship/controller/controldevice/controller/mapping/ControllerDefaultMappings.cpp b/src/libultraship/controller/controldevice/controller/mapping/ControllerDefaultMappings.cpp +index c431c34..35f66b2 100644 +--- a/src/libultraship/controller/controldevice/controller/mapping/ControllerDefaultMappings.cpp ++++ b/src/libultraship/controller/controldevice/controller/mapping/ControllerDefaultMappings.cpp +@@ -80,6 +80,11 @@ void ControllerDefaultMappings::SetDefaultSDLButtonToButtonMappings( + { BTN_DDOWN, { SDL_CONTROLLER_BUTTON_DPAD_DOWN } }, + { BTN_DLEFT, { SDL_CONTROLLER_BUTTON_DPAD_LEFT } }, + { BTN_DRIGHT, { SDL_CONTROLLER_BUTTON_DPAD_RIGHT } }, ++#ifdef USE_GLES2 ++ { BTN_CDOWN, { SDL_CONTROLLER_BUTTON_Y } }, ++ { BTN_CLEFT, { SDL_CONTROLLER_BUTTON_X } }, ++ { BTN_CRIGHT, { SDL_CONTROLLER_BUTTON_RIGHTSHOULDER } }, ++#endif + }); + } + +diff --git a/src/ship/audio/Audio.cpp b/src/ship/audio/Audio.cpp +index 8cc5b12..604a30c 100644 +--- a/src/ship/audio/Audio.cpp ++++ b/src/ship/audio/Audio.cpp +@@ -36,8 +36,11 @@ void Audio::InitAudioPlayer() { + + if (mAudioPlayer && !mAudioPlayer->Init()) { + // Failed to initialize system audio player. +- // Fallback to Null if the native system player does not work. +- SetCurrentAudioBackend(AudioBackend::NUL); ++ // Fallback to Null if the native system player does not work: for this run only, ++ // the saved backend stays and the next start tries it again ++ mAudioBackend = AudioBackend::NUL; ++ mAudioPlayer = std::make_shared(this->mAudioSettings); ++ mAudioPlayer->Init(); + } + } + +diff --git a/src/ship/debug/CrashHandler.cpp b/src/ship/debug/CrashHandler.cpp +index 39d76be..c4cec84 100644 +--- a/src/ship/debug/CrashHandler.cpp ++++ b/src/ship/debug/CrashHandler.cpp +@@ -2,6 +2,9 @@ + #include "ship/utils/StringHelper.h" + #include "ship/debug/CrashHandler.h" + #include "ship/Context.h" ++#ifndef _WIN32 ++#include // _exit ++#endif + + #ifdef _WIN32 + #include +@@ -199,11 +202,13 @@ static void ErrorHandler(int sig, siginfo_t* sigInfo, void* data) { + + Context::GetRawInstance()->GetLogger()->flush(); + spdlog::shutdown(); +- exit(1); ++ _exit(128 + sig); + } + + static void ShutdownHandler(int sig, siginfo_t* sigInfo, void* data) { +- exit(1); ++ SDL_Event event; ++ event.type = SDL_QUIT; ++ SDL_PushEvent(&event); + } + + #elif _WIN32 diff --git a/ports/spaghettikart/spaghettikart.patch b/ports/spaghettikart/spaghettikart.patch new file mode 100644 index 0000000..d0dfdbf --- /dev/null +++ b/ports/spaghettikart/spaghettikart.patch @@ -0,0 +1,215 @@ +diff --git a/assets/shaders/opengl/default.shader.glsl b/assets/shaders/opengl/default.shader.glsl +index 5e0f93f..046207d 100644 +--- a/assets/shaders/opengl/default.shader.glsl ++++ b/assets/shaders/opengl/default.shader.glsl +@@ -130,14 +130,18 @@ + + float random(in vec3 value) { + float random = dot(sin(value), vec3(12.9898, 78.233, 37.719)); ++ @if(gles2) ++ return fract(sin(random) * 43758.5453); ++ @else + return fract(sin(random) * 143758.5453); ++ @end + } + + vec4 fromLinear(vec4 linearRGB){ + bvec3 cutoff = lessThan(linearRGB.rgb, vec3(0.0031308)); + vec3 higher = vec3(1.055)*pow(linearRGB.rgb, vec3(1.0/2.4)) - vec3(0.055); + vec3 lower = linearRGB.rgb * vec3(12.92); +- return vec4(mix(higher, lower, cutoff), linearRGB.a); ++ return vec4(mix(higher, lower, vec3(cutoff)), linearRGB.a); + } + + vec4 filter3point(in sampler2D tex, in vec2 texCoord, in vec2 texSize) { +@@ -183,7 +187,9 @@ + vec4 texVal@{i} = hookTexture2D(@{i}, uTex@{i}, vTexCoordAdj@{i}, texSize@{i}); + + @if(o_masks[i]) +- @if(opengles) ++ @if(gles2) ++ vec2 maskSize@{i} = texSize@{i}; ++ @elseif(opengles) + vec2 maskSize@{i} = vec2(textureSize(uTexMask@{i}, 0)); + @else + vec2 maskSize@{i} = textureSize(uTexMask@{i}, 0); +diff --git a/cmake/SetFlags.cmake b/cmake/SetFlags.cmake +index 44bfce2..eeef3d2 100644 +--- a/cmake/SetFlags.cmake ++++ b/cmake/SetFlags.cmake +@@ -116,6 +116,7 @@ target_compile_definitions(${PROJECT_NAME} PRIVATE + NDEBUG + VERSION_US=1 + "$<$:USE_OPENGLES>" ++ "$<$:USE_GLES2>" + ENABLE_RUMBLE=1 + F3DEX_GBI=1 + _LANGUAGE_C +diff --git a/src/engine/tracks/LuigiRaceway.cpp b/src/engine/tracks/LuigiRaceway.cpp +index 70127e1..de5cf79 100644 +--- a/src/engine/tracks/LuigiRaceway.cpp ++++ b/src/engine/tracks/LuigiRaceway.cpp +@@ -256,12 +256,32 @@ void LuigiRaceway::Draw(ScreenContext* arg0) { + // Invalidate Jumbotron textures so they update each frame + // This could be more efficient if we exposed the non-opcode based invalidation to be called + // inside copy_framebuffers_port ++#ifdef USE_GLES2 ++ static const void* sJumbotronBlankedFor; ++ if (sJumbotronBlankedFor != this) { ++ for (const char* tex : { gTexture68272C, gTexture682928, gTexture682B24, gTexture682D20, gTexture682F1C, gTexture683118 }) { ++ u8* px = (u8*) LOAD_ASSET_RAW(tex); ++ for (int k = 0; k < 64 * 32; k++) { // RGBA16, big-endian: opaque black ++ px[2 * k] = 0x00; ++ px[2 * k + 1] = 0x01; ++ } ++ } ++ gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture68272C); ++ gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture682928); ++ gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture682B24); ++ gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture682D20); ++ gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture682F1C); ++ gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture683118); ++ sJumbotronBlankedFor = this; ++ } ++#else + gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture68272C); + gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture682928); + gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture682B24); + gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture682D20); + gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture682F1C); + gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture683118); ++#endif + + if (func_80290C20(arg0->camera) == 1) { + gDPSetCombineMode(gDisplayListHead++, G_CC_SHADE, G_CC_SHADE); +@@ -304,8 +324,10 @@ void LuigiRaceway::Draw(ScreenContext* arg0) { + * The jumbo television screen used to be split into six sections to fit into the n64's texture size + * restrictions It isn't split into six sections anymore + */ ++#ifndef USE_GLES2 + CopyJumbotron(D_800DC5DC, D_800DC5E0, currentScreenSection, + (u16*) gPortFramebuffers[prevFrame]); ++#endif + } + } + +diff --git a/src/engine/tracks/ToadsTurnpike.cpp b/src/engine/tracks/ToadsTurnpike.cpp +index 3952927..d26b726 100644 +--- a/src/engine/tracks/ToadsTurnpike.cpp ++++ b/src/engine/tracks/ToadsTurnpike.cpp +@@ -105,7 +105,7 @@ ToadsTurnpike::ToadsTurnpike() { + mCloudType = CloudType::STARS; + + FVector finish; +- finish.x = -38.0f * xOrientation; ++ finish.x = (gIsMirrorMode != 0) ? 38.0f : -38.0f; + finish.y = (f32) (0 - 15); + finish.z = 16; + +diff --git a/src/engine/tracks/WarioStadium.cpp b/src/engine/tracks/WarioStadium.cpp +index 99e672e..af040fc 100644 +--- a/src/engine/tracks/WarioStadium.cpp ++++ b/src/engine/tracks/WarioStadium.cpp +@@ -236,12 +236,32 @@ void WarioStadium::Draw(ScreenContext* arg0) { + // Invalidate Jumbotron textures so they update each frame + // This could be more efficient if we exposed the non-opcode based invalidation to be called + // inside copy_framebuffers_port ++#ifdef USE_GLES2 ++ static const void* sJumbotronBlankedFor; ++ if (sJumbotronBlankedFor != this) { ++ for (const char* tex : { gTexture68272C, gTexture682928, gTexture682B24, gTexture682D20, gTexture682F1C, gTexture683118 }) { ++ u8* px = (u8*) LOAD_ASSET_RAW(tex); ++ for (int k = 0; k < 64 * 32; k++) { // RGBA16, big-endian: opaque black ++ px[2 * k] = 0x00; ++ px[2 * k + 1] = 0x01; ++ } ++ } ++ gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture68272C); ++ gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture682928); ++ gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture682B24); ++ gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture682D20); ++ gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture682F1C); ++ gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture683118); ++ sJumbotronBlankedFor = this; ++ } ++#else + gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture68272C); + gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture682928); + gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture682B24); + gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture682D20); + gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture682F1C); + gSPInvalidateTexCache(gDisplayListHead++, (uintptr_t) gTexture683118); ++#endif + + if (func_80290C20(arg0->camera) == 1) { + gDPSetCombineMode(gDisplayListHead++, G_CC_SHADE, G_CC_SHADE); +@@ -281,7 +301,9 @@ void WarioStadium::Draw(ScreenContext* arg0) { + * The jumbo television screen used to be split into six sections to fit into the n64's texture size + * restrictions It isn't split into six sections anymore + */ ++#ifndef USE_GLES2 + CopyJumbotron(D_800DC5DC, D_800DC5E0, currentScreenSection, (u16*) gPortFramebuffers[prevFrame]); ++#endif + } + } + +diff --git a/src/main.c b/src/main.c +index 1bdbee6..12896a5 100644 +--- a/src/main.c ++++ b/src/main.c +@@ -804,7 +804,9 @@ void race_logic_loop(void) { + // Copies after all the main rendering is complete. This is accurate to hardware. + // This means things like jumbotron will have the pause menu rendered in it. + // To avoid that, this line can be moved above func_800591B4. ++#ifndef USE_GLES2 + FB_WriteFramebufferSliceToCPU(&gDisplayListHead, gPortFramebuffers[sRenderingFramebuffer], true); ++#endif + gDPFullSync(gDisplayListHead++); + gSPEndDisplayList(gDisplayListHead++); + +diff --git a/src/port/Engine.cpp b/src/port/Engine.cpp +index 23036ad..d03a40e 100644 +--- a/src/port/Engine.cpp ++++ b/src/port/Engine.cpp +@@ -96,6 +96,13 @@ GameEngine::GameEngine() { + this->context->InitConfiguration(); // without this line InitConsoleVariables fails at Config::Reload() + this->context->InitConsoleVariables(); // without this line the controldeck constructor failes in + // ShipDeviceIndexMappingManager::UpdateControllerNamesFromConfig() ++#ifdef USE_GLES2 ++ if (!CVarGetInteger("gGles2DefaultsApplied", 0)) { ++ CVarSetInteger("gTextureFilter", 1); // FILTER_LINEAR ++ CVarSetInteger("gGles2DefaultsApplied", 1); ++ CVarSave(); ++ } ++#endif + + auto defaultMappings = std::make_shared( + // KeyboardKeyToButtonMappings +@@ -127,10 +134,17 @@ GameEngine::GameEngine() { + // SDLButtonToButtonMappings + std::unordered_map>{ + { BTN_A, { SDL_CONTROLLER_BUTTON_A } }, ++#ifdef USE_GLES2 ++ { BTN_B, { SDL_CONTROLLER_BUTTON_B } }, ++ { BTN_Z, { SDL_CONTROLLER_BUTTON_X } }, ++ { BTN_START, { SDL_CONTROLLER_BUTTON_START } }, ++ { BTN_CLEFT, { SDL_CONTROLLER_BUTTON_Y } }, ++#else + { BTN_B, { SDL_CONTROLLER_BUTTON_X } }, + { BTN_START, { SDL_CONTROLLER_BUTTON_START } }, + { BTN_CLEFT, { SDL_CONTROLLER_BUTTON_Y } }, + { BTN_CDOWN, { SDL_CONTROLLER_BUTTON_B } }, ++#endif + { BTN_DUP, { SDL_CONTROLLER_BUTTON_DPAD_UP } }, + { BTN_DDOWN, { SDL_CONTROLLER_BUTTON_DPAD_DOWN } }, + { BTN_DLEFT, { SDL_CONTROLLER_BUTTON_DPAD_LEFT } }, +@@ -145,6 +159,9 @@ GameEngine::GameEngine() { + { BTN_R, { { SDL_CONTROLLER_AXIS_TRIGGERRIGHT, 1 } } }, + { BTN_Z, { { SDL_CONTROLLER_AXIS_TRIGGERLEFT, 1 } } }, + { BTN_CUP, { { SDL_CONTROLLER_AXIS_RIGHTY, -1 } } }, ++#ifdef USE_GLES2 ++ { BTN_CDOWN, { { SDL_CONTROLLER_AXIS_RIGHTY, 1 } } }, ++#endif + { BTN_CRIGHT, { { SDL_CONTROLLER_AXIS_RIGHTX, 1 } } } + }, + // SDLAxisDirectionToAxisDirectionMappings - use built-in LUS defaults diff --git a/ports/starship/README.md b/ports/starship/README.md new file mode 100644 index 0000000..ef3bc5b --- /dev/null +++ b/ports/starship/README.md @@ -0,0 +1,71 @@ +# Star Fox 64 (Starship) on the RetroStone2 + +[Starship](https://github.com/HarbourMasters/Starship) is the PC port of the Star Fox 64 decompilation, built on +HarbourMasters' [libultraship](https://github.com/Kenix3/libultraship). libultraship draws with OpenGL 3.0 or +OpenGL ES 3.0; the RetroStone2's Mali-400 only has **OpenGL ES 2.0**. This folder adds an OpenGL ES 2.0 mode to +libultraship (`USE_GLES2`) and builds Starship for the console as a native game (docs/native-games.md). + +**Nothing from the game is in this repository, the OS images or the updates.** As for Super Mario 64, the game's +data comes from **your own ROM** on your PC (Star Fox 64 US 1.1, `.z64`, SHA-1 +`09f0d105f476b00efa5303a3ebc42e60a7753b7a`) and stays yours. + +## Status + +| Step | | +|---|---| +| GLES2 renderer (`libultraship-gles2.patch`) | written | +| Cross-build for the RetroStone2 (32-bit ARM) | **builds** (Starship `3322643f`, libultraship `eaaf9d0`, Torch `cd92cc0`) | +| Game data from the ROM (`sf64.o2r`) and the port archive (`starship.o2r`) | **built** on a PC | +| Libraries in the OS (Ogg/Vorbis, libzip, tinyxml2, spdlog, fmt) | in the RetroStone2 configs | +| The built-in controls | `rsos-gamepad`: the three devices as one standard SDL gamepad, started by the launch script | +| Build script for the SD card folder | `build-starship.sh` | +| Run on a RetroStone2 | **runs** (RetroStone2 Pro); some slowdown in busy scenes | + +Starship's libultraship still uses **SDL2** (only libultraship's newest code moved to SDL3), so no SDL3 is needed. + +## What the GLES2 mode changes + +* **Context**: asks SDL for an OpenGL ES 2.0 context (Mesa's lima would otherwise give desktop OpenGL 2.1). +* **Shaders**: GLSL ES 1.00 (`attribute`/`varying`, `texture2D`, `gl_FragColor`, `precision mediump float`); + `textureSize()` replaced by the texture's size for masks; `mix(..., bvec3)` written with `vec3()`; the noise + constant kept below 65504 (Mali-400 fragment shaders have 16-bit floats only). Both copies of the shader + templates: libultraship's and Starship's own `port/shaders` (packed into `starship.o2r`). +* **Framebuffers**: unsized texture formats, packed depth+stencil when the driver has + `GL_OES_packed_depth_stencil` (else 16-bit depth), clamp-to-edge on the screen-sized colour textures (GLES2 has + no repeat on non-power-of-two textures), no multisampling, no vertex array object. +* **What GLES2 cannot do**: framebuffer blits (copies go through `glCopyTexSubImage2D`, unscaled only) and depth + reads (reported as "far"). Starship uses neither; only libultraship's debug window does. +* A shader that fails to compile now prints the compiler's message and the shader before aborting. + +## Other fixes in the patches + +* **First start** (GLES2 builds): the cheap settings once, still changeable in the menu: the game's own frame + rate (no interpolated frames), 320x240 rendering, bilinear filtering, no MSAA, no "press F1" hint. +* **Crash with frame interpolation off** ("Original", 20 FPS): the game turned recording back on in the middle + of a frame and crashed in `FrameInterpolation_RecordMatrixPop`; recording now only resumes in a frame that + started it. +* **Handheld controls**: Select + Start quits at once; Start skips any level intro (`gSkipAnyIntro`). +* **Crash handler**: `_exit()` instead of `exit()` in the signal handlers, so a crash or a quit ends the game at + once (exit status 128 + signal) instead of hanging on a frozen picture. + +## Build + +```sh +ports/starship/build-starship.sh ~/"Star Fox 64 (U) (V1.1).z64" ~/my-ports +``` + +It clones Starship at the fixed commit into `~/rsos/starship-work`, applies `starship.patch` and +`libultraship-gles2.patch`, checks that the ROM is one Starship supports, builds the game for the console +(`USE_GLES2`, the RetroStoneOS cross compiler), builds Torch for the PC and makes `sf64.o2r` from the ROM and +`starship.o2r`, then writes: + +``` +~/my-ports/roms/native/Star Fox 64.sh +~/my-ports/roms/native/starship/ Starship, sf64.o2r, starship.o2r, gamecontrollerdb.txt +``` + +Copy the `roms` folder onto the SD card's **RETROSTONE** partition; in the menu: **Native games > Star Fox 64**. +Settings and saves stay in `roms/native/starship/` (`SHIP_HOME`). **Select + Start** quits at once, as in the +emulators. **Start** skips a level's opening scene, also on a planet not cleared yet (the N64 game allows it only +after a clear; the `gSkipAnyIntro` setting at 0 in `starship.cfg.json` brings that back). +The console needs a RetroStoneOS with Native games, the port libraries and `rsos-gamepad`. diff --git a/ports/starship/Star Fox 64.layout b/ports/starship/Star Fox 64.layout new file mode 100644 index 0000000..567cb4a --- /dev/null +++ b/ports/starship/Star Fox 64.layout @@ -0,0 +1,13 @@ +# N64 pad layout for this port: which SDL element the game reads for each N64 function, +# so a real N64 pad plays like the built-in buttons do here. Used when an N64 pad is +# plugged in (Settings > Controls); see docs/native-games.md, "Layouts". +# Functions: a b z l r start cup cdown cleft cright dpup dpdown dpleft dpright ("none" drops one). +# Left alone, an N64 pad is: a=a b=b z=lefttrigger l=leftshoulder r=rightshoulder +# (+ a copy of r on the right trigger), C buttons on the right stick, D-pad on the hat. +# Star Fox 64: B is X, Z is the left shoulder, C-down is B, C-left is Y, no L. +b = x +z = leftshoulder +l = none +r = rightshoulder +cdown = b +cleft = y diff --git a/ports/starship/Star Fox 64.sh b/ports/starship/Star Fox 64.sh new file mode 100644 index 0000000..ba9ecf6 --- /dev/null +++ b/ports/starship/Star Fox 64.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# Star Fox 64 (Starship), built from your own ROM by ports/starship/build-starship.sh. +# The game data (sf64.o2r), settings and saves stay in starship/. +cd starship || exit 1 +export SHIP_HOME="$PWD" +# The built-in controls as one standard gamepad (rsos-gamepad); SDL then +# ignores the raw button devices. It runs in the +# game's process group: the menu stops it with the game. +if [ -x /usr/bin/rsos-gamepad ]; then + SDL_GAMECONTROLLERCONFIG="$(/usr/bin/rsos-gamepad --print-mapping)" + export SDL_GAMECONTROLLERCONFIG + export SDL_GAMECONTROLLER_IGNORE_DEVICES=0x0001/0x0001 + /usr/bin/rsos-gamepad & + usleep 300000 +fi +if [ -x ./Starship ]; then + exec ./Starship +fi +exec /lib/ld-linux-armhf.so.3 ./Starship diff --git a/ports/starship/build-starship.sh b/ports/starship/build-starship.sh new file mode 100755 index 0000000..662eaa8 --- /dev/null +++ b/ports/starship/build-starship.sh @@ -0,0 +1,76 @@ +#!/bin/bash +# Builds Star Fox 64 (Starship) for RetroStoneOS from YOUR OWN ROM, on the PC +# (Linux/WSL), as a native game for the SD card (docs/native-games.md). +# +# ports/starship/build-starship.sh [output folder] +# +# Needs a built RetroStoneOS tree for the RetroStone2 with SDL2 and the port +# libraries (the RetroStone2 configs): ~/rsos/output, or RSOS_OUTPUT=; cmake, +# ninja and a C++ compiler for the PC (Torch, the asset extractor, runs here). +# Starship is cloned at a fixed commit into ~/rsos/starship-work +# (RSOS_STARSHIP_WORK) and patched (starship.patch, libultraship-gles2.patch). +# +# The result contains the game's data, taken from your ROM: keep it for +# yourself. Never put it in a release, an update or a repository. +# +# Output (default ./starship-retrostone2): roms/native/Star Fox 64.sh and +# roms/native/starship/. Copy the "roms" folder onto the SD card's +# RETROSTONE partition (it merges with the roms folder there). +set -euo pipefail + +REPO=https://github.com/HarbourMasters/Starship.git +COMMIT=3322643f0bbf80d2f8f7e1c0d2c4c578515f6c90 # libultraship eaaf9d0, Torch cd92cc0 + +here=$(cd "$(dirname "$0")" && pwd) +rom=${1:-} +out=${2:-$PWD/starship-retrostone2} +O=${RSOS_OUTPUT:-$HOME/rsos/output} +W=${RSOS_STARSHIP_WORK:-$HOME/rsos/starship-work} + +die() { echo "build-starship: $*" >&2; exit 1; } + +[ -n "$rom" ] || die "usage: $0 [output folder]" +[ -f "$rom" ] || die "$rom: no such file" +rom=$(cd "$(dirname "$rom")" && pwd)/$(basename "$rom") +case "$out" in /*) ;; *) out=$PWD/$out ;; esac +[ -x "$O/host/bin/arm-linux-gcc" ] || die "no cross compiler in $O/host/bin (build RetroStoneOS first)" +for lib in libSDL2.so libzip.so libtinyxml2.so libspdlog.so libvorbisfile.so; do + [ -e "$O/staging/usr/lib/$lib" ] || die "$lib is not in $O/staging (build RetroStoneOS with the RetroStone2 configs)" +done +TOOLCHAIN=$O/host/share/buildroot/toolchainfile.cmake + +if [ ! -d "$W/.git" ]; then + git clone -q "$REPO" "$W" +fi +cd "$W" +git fetch -q origin 2> /dev/null || true +# a clean tree at the fixed commit, then our changes (the build folder, the +# ROM and the .o2r files are ignored by git and stay) +git checkout -q -f "$COMMIT" +git submodule update -q --init --recursive --force +git -C libultraship checkout -q -f . +git apply "$here/starship.patch" +git -C libultraship apply "$here/libultraship-gles2.patch" + +# the ROM: a supported Star Fox 64 (its SHA-1 is a key of config.yml) +sum=$(sha1sum "$rom" | cut -d' ' -f1) +grep -q "^$sum:" config.yml || die "$rom is not a Star Fox 64 ROM that Starship supports, in .z64 order (SHA-1 $sum)" +cp "$rom" baserom.z64 + +# the game for the console, then Torch for this PC and the two archives +cmake -S . -B build-gles2 -G Ninja -DCMAKE_BUILD_TYPE=Release -DUSE_OPENGLES=ON -DUSE_GLES2=ON \ + -DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN" +cmake --build build-gles2 --target Starship +cmake --build build-gles2 --target ExtractAssets +cmake --build build-gles2 --target GeneratePortO2R + +file build-gles2/Starship | grep -q 'ARM' || die "build-gles2/Starship is not an ARM program" +mkdir -p "$out/roms/native/starship" +"$O/host/bin/arm-linux-strip" -o "$out/roms/native/starship/Starship" build-gles2/Starship +cp build-gles2/sf64.o2r build-gles2/starship.o2r "$out/roms/native/starship/" +[ -f build-gles2/gamecontrollerdb.txt ] && cp build-gles2/gamecontrollerdb.txt "$out/roms/native/starship/" +install -m 0644 "$here/Star Fox 64.sh" "$out/roms/native/Star Fox 64.sh" +echo +echo "Done: $out/roms" +echo "Copy that \"roms\" folder onto the SD card's RETROSTONE partition, then in the menu:" +echo "Native games > Star Fox 64. Select + Start quits." diff --git a/ports/starship/libultraship-gles2.patch b/ports/starship/libultraship-gles2.patch new file mode 100644 index 0000000..9af49eb --- /dev/null +++ b/ports/starship/libultraship-gles2.patch @@ -0,0 +1,426 @@ +diff --git a/cmake/dependencies/linux.cmake b/cmake/dependencies/linux.cmake +index 02301f13..8e231e1b 100644 +--- a/cmake/dependencies/linux.cmake ++++ b/cmake/dependencies/linux.cmake +@@ -2,7 +2,10 @@ + find_package(SDL2 REQUIRED) + target_link_libraries(ImGui PUBLIC SDL2::SDL2) + +-if (USE_OPENGLES) ++if (USE_GLES2) ++ target_link_libraries(ImGui PUBLIC GLESv2) ++ add_compile_definitions(IMGUI_IMPL_OPENGL_ES2) ++elseif (USE_OPENGLES) + target_link_libraries(ImGui PUBLIC ${OPENGL_GLESv2_LIBRARY}) + add_compile_definitions(IMGUI_IMPL_OPENGL_ES3) + else() +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index db92a29a..1675a88e 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -8,6 +8,11 @@ set_property(TARGET libultraship PROPERTY C_STANDARD 11) + + set(INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../include) + option(USE_OPENGLES "Enable GLES3" OFF) ++# OpenGL ES 2.0 (Mali-400 and other GLES2-only GPUs); implies USE_OPENGLES ++option(USE_GLES2 "Enable GLES2" OFF) ++if (USE_GLES2) ++ set(USE_OPENGLES ON) ++endif() + option(GFX_DEBUG_DISASSEMBLER "Enable libgfxd" OFF) + + if (CMAKE_SYSTEM_NAME STREQUAL "Windows") +@@ -286,6 +291,7 @@ else() + $<$:SPDLOG_ACTIVE_LEVEL=0> + $<$>:SPDLOG_ACTIVE_LEVEL=1> + $<$:USE_OPENGLES> ++ $<$:USE_GLES2> + $<$:GFX_DEBUG_DISASSEMBLER> + ) + endif() +diff --git a/src/debug/CrashHandler.cpp b/src/debug/CrashHandler.cpp +index 5f2256ac..df5179a7 100644 +--- a/src/debug/CrashHandler.cpp ++++ b/src/debug/CrashHandler.cpp +@@ -2,6 +2,9 @@ + #include "utils/StringHelper.h" + #include "CrashHandler.h" + #include "Context.h" ++#ifndef _WIN32 ++#include // _exit ++#endif + + #ifdef _WIN32 + #include +@@ -199,11 +202,11 @@ static void ErrorHandler(int sig, siginfo_t* sigInfo, void* data) { + + Context::GetInstance()->GetLogger()->flush(); + spdlog::shutdown(); +- exit(1); ++ _exit(128 + sig); + } + + static void ShutdownHandler(int sig, siginfo_t* sigInfo, void* data) { +- exit(1); ++ _exit(128 + sig); + } + + #elif _WIN32 +diff --git a/src/graphic/Fast3D/backends/gfx_opengl.cpp b/src/graphic/Fast3D/backends/gfx_opengl.cpp +index 097e2e86..4074598d 100644 +--- a/src/graphic/Fast3D/backends/gfx_opengl.cpp ++++ b/src/graphic/Fast3D/backends/gfx_opengl.cpp +@@ -27,6 +27,49 @@ + #include "../interpreter.h" + #include + ++#include ++ ++#ifdef USE_GLES2 ++/* ++ * OpenGL ES 2.0: no sized texture formats, no multisampling, no blits and no ++ * depth reads. Multisampling stays off (mMaxMsaaLevel 1), so the multisample ++ * calls below are never reached; CopyFramebuffer and GetPixelDepth have their ++ * own GLES2 versions. Depth: packed depth+stencil when the driver has ++ * GL_OES_packed_depth_stencil, else a 16-bit depth buffer. ++ */ ++#define GL_RGB8 GL_RGB ++#define GL_RGBA8 GL_RGBA ++#define GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8_OES ++#define GL_DEPTH_STENCIL GL_DEPTH_STENCIL_OES ++#define GL_UNSIGNED_INT_24_8 GL_UNSIGNED_INT_24_8_OES ++#define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER ++#define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER ++#define glBlitFramebuffer(...) ((void)0) ++#define glReadBuffer(b) ((void)0) ++#define glRenderbufferStorageMultisample(target, samples, format, w, h) glRenderbufferStorage(target, format, w, h) ++static bool sPackedDepthStencil = true; ++#endif ++ ++namespace Fast { ++static void RenderbufferDepthStorage(GLsizei width, GLsizei height) { ++#ifdef USE_GLES2 ++ glRenderbufferStorage(GL_RENDERBUFFER, sPackedDepthStencil ? GL_DEPTH24_STENCIL8_OES : GL_DEPTH_COMPONENT16, ++ width, height); ++#else ++ glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); ++#endif ++} ++ ++static void FramebufferDepthAttach(GLuint rb) { ++#ifdef USE_GLES2 ++ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb); ++ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, sPackedDepthStencil ? rb : 0); ++#else ++ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb); ++#endif ++} ++} // namespace Fast ++ + namespace Fast { + int GfxRenderingAPIOGL::GetMaxTextureSize() { + GLint max_texture_size; +@@ -273,13 +316,23 @@ std::string GfxRenderingAPIOGL::BuildFsShader(const CCFeatures& cc_features) { + { "attr", "in" }, + { "opengles", false }, + { "core_opengl", true }, ++ { "gles2", false }, + { "texture", "texture" }, + { "vOutColor", "vOutColor" }, ++#elif defined(USE_GLES2) ++ { "GLSL_VERSION", "#version 100\nprecision mediump float;" }, ++ { "attr", "varying" }, ++ { "opengles", false }, ++ { "core_opengl", false }, ++ { "gles2", true }, ++ { "texture", "texture2D" }, ++ { "vOutColor", "gl_FragColor" }, + #elif defined(USE_OPENGLES) + { "GLSL_VERSION", "#version 300 es\nprecision mediump float;" }, + { "attr", "in" }, + { "opengles", true }, + { "core_opengl", false }, ++ { "gles2", false }, + { "texture", "texture" }, + { "vOutColor", "vOutColor" }, + #else +@@ -287,6 +340,7 @@ std::string GfxRenderingAPIOGL::BuildFsShader(const CCFeatures& cc_features) { + { "attr", "varying" }, + { "opengles", false }, + { "core_opengl", false }, ++ { "gles2", false }, + { "texture", "texture2D" }, + { "vOutColor", "gl_FragColor" }, + #endif +@@ -336,6 +390,11 @@ static std::string BuildVsShader(const CCFeatures& cc_features) { + { "attr", "in" }, + { "out", "out" }, + { "opengles", false } ++#elif defined(USE_GLES2) ++ { "GLSL_VERSION", "#version 100" }, ++ { "attr", "attribute" }, ++ { "out", "varying" }, ++ { "opengles", false } + #elif defined(USE_OPENGLES) + { "GLSL_VERSION", "#version 300 es" }, + { "attr", "in" }, +@@ -389,9 +448,8 @@ ShaderProgram* GfxRenderingAPIOGL::CreateAndLoadNewShader(uint64_t shader_id0, u + GLint max_length = 0; + glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &max_length); + char error_log[1024]; +- // fprintf(stderr, "Vertex shader compilation failed\n"); +- glGetShaderInfoLog(vertex_shader, max_length, &max_length, &error_log[0]); +- // fprintf(stderr, "%s\n", &error_log[0]); ++ glGetShaderInfoLog(vertex_shader, sizeof(error_log), nullptr, error_log); ++ fprintf(stderr, "Vertex shader compilation failed:\n%s\n%s\n", error_log, vs_buf.c_str()); + abort(); + } + +@@ -403,9 +461,8 @@ ShaderProgram* GfxRenderingAPIOGL::CreateAndLoadNewShader(uint64_t shader_id0, u + GLint max_length = 0; + glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &max_length); + char error_log[1024]; +- fprintf(stderr, "Fragment shader compilation failed\n"); +- glGetShaderInfoLog(fragment_shader, max_length, &max_length, &error_log[0]); +- fprintf(stderr, "%s\n", &error_log[0]); ++ glGetShaderInfoLog(fragment_shader, sizeof(error_log), nullptr, error_log); ++ fprintf(stderr, "Fragment shader compilation failed:\n%s\n%s\n", error_log, fs_buf.c_str()); + abort(); + } + +@@ -541,7 +598,9 @@ void GfxRenderingAPIOGL::UploadTexture(const uint8_t* rgba32_buf, uint32_t width + textures[mCurrentTextureIds[mCurrentTile]].height = height; + } + +-#ifdef USE_OPENGLES ++#ifdef USE_GLES2 ++#define GL_MIRROR_CLAMP_TO_EDGE GL_MIRRORED_REPEAT ++#elif defined(USE_OPENGLES) + #define GL_MIRROR_CLAMP_TO_EDGE 0x8743 + #endif + +@@ -659,7 +718,16 @@ void GfxRenderingAPIOGL::Init() { + glGenBuffers(1, &mOpenglVbo); + glBindBuffer(GL_ARRAY_BUFFER, mOpenglVbo); + +-#if defined(__APPLE__) || defined(USE_OPENGLES) ++#ifdef USE_GLES2 ++ { ++ const char* ext = (const char*)glGetString(GL_EXTENSIONS); ++ ++ sPackedDepthStencil = ext != nullptr && strstr(ext, "GL_OES_packed_depth_stencil") != nullptr; ++ SPDLOG_INFO("OpenGL ES 2.0: {} ({}), depth buffer {}", (const char*)glGetString(GL_RENDERER), ++ (const char*)glGetString(GL_VERSION), sPackedDepthStencil ? "24-bit + stencil" : "16-bit"); ++ } ++#endif ++#if defined(__APPLE__) || (defined(USE_OPENGLES) && !defined(USE_GLES2)) + glGenVertexArrays(1, &mOpenglVao); + glBindVertexArray(mOpenglVao); + #endif +@@ -674,17 +742,21 @@ void GfxRenderingAPIOGL::Init() { + + glGenRenderbuffers(1, &mPixelDepthRb); + glBindRenderbuffer(GL_RENDERBUFFER, mPixelDepthRb); +- glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 1, 1); ++ RenderbufferDepthStorage(1, 1); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + + glGenFramebuffers(1, &mPixelDepthFb); + glBindFramebuffer(GL_FRAMEBUFFER, mPixelDepthFb); +- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mPixelDepthRb); ++ FramebufferDepthAttach(mPixelDepthRb); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + + mPixelDepthRbSize = 1; + ++#ifdef USE_GLES2 ++ mMaxMsaaLevel = 1; ++#else + glGetIntegerv(GL_MAX_SAMPLES, &mMaxMsaaLevel); ++#endif + } + + void GfxRenderingAPIOGL::OnResize() { +@@ -708,6 +780,10 @@ int GfxRenderingAPIOGL::CreateFramebuffer() { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); ++#ifdef USE_GLES2 ++ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); ++ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); ++#endif + glBindTexture(GL_TEXTURE_2D, 0); + + GLuint clrbufMsaa; +@@ -716,7 +792,7 @@ int GfxRenderingAPIOGL::CreateFramebuffer() { + GLuint rbo; + glGenRenderbuffers(1, &rbo); + glBindRenderbuffer(GL_RENDERBUFFER, rbo); +- glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 1, 1); ++ RenderbufferDepthStorage(1, 1); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + + GLuint fbo; +@@ -763,7 +839,7 @@ void GfxRenderingAPIOGL::UpdateFramebufferParameters(int fb_id, uint32_t width, + (fb.width != width || fb.height != height || fb.msaa_level != msaa_level || !fb.has_depth_buffer)) { + glBindRenderbuffer(GL_RENDERBUFFER, fb.rbo); + if (msaa_level <= 1) { +- glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); ++ RenderbufferDepthStorage(width, height); + } else { + glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa_level, GL_DEPTH24_STENCIL8, width, height); + } +@@ -771,9 +847,9 @@ void GfxRenderingAPIOGL::UpdateFramebufferParameters(int fb_id, uint32_t width, + } + + if (!fb.has_depth_buffer && has_depth_buffer) { +- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fb.rbo); ++ FramebufferDepthAttach(fb.rbo); + } else if (fb.has_depth_buffer && !has_depth_buffer) { +- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0); ++ FramebufferDepthAttach(0); + } + } + +@@ -838,6 +914,34 @@ void GfxRenderingAPIOGL::CopyFramebuffer(int fb_dst_id, int fb_src_id, int srcX0 + FramebufferOGL src = mFrameBuffers[fb_src_id]; + const FramebufferOGL& dst = mFrameBuffers[fb_dst_id]; + ++#ifdef USE_GLES2 ++ // No blits: copy into the destination's colour texture, unscaled and in the ++ // same orientation only (G_COPYFB effects; Starship does not use them). ++ if (fb_dst_id == 0 || srcX1 - srcX0 != dstX1 - dstX0 || srcY1 - srcY0 != dstY1 - dstY0 || ++ src.invertY != dst.invertY) { ++ static bool warned; ++ if (!warned) { ++ SPDLOG_WARN("GLES2: scaled, flipped or on-screen framebuffer copies are not supported"); ++ warned = true; ++ } ++ return; ++ } ++ // OpenGL's origin is the bottom left, as in the blit path below ++ if (!src.invertY) { ++ int h = srcY1 - srcY0; ++ srcY1 = src.height - srcY0; ++ srcY0 = srcY1 - h; ++ } ++ glDisable(GL_SCISSOR_TEST); ++ glBindFramebuffer(GL_FRAMEBUFFER, src.fbo); ++ glActiveTexture(GL_TEXTURE0); ++ glBindTexture(GL_TEXTURE_2D, dst.clrbuf); ++ glCopyTexSubImage2D(GL_TEXTURE_2D, 0, dstX0, dstY0, srcX0, srcY0, srcX1 - srcX0, srcY1 - srcY0); ++ glBindFramebuffer(GL_FRAMEBUFFER, mFrameBuffers[mCurrentFrameBuffer].fbo); ++ glEnable(GL_SCISSOR_TEST); ++ return; ++#endif ++ + // Adjust y values for non-inverted source frame buffers because opengl uses bottom left for origin + if (!src.invertY) { + int temp = srcY1 - srcY0; +@@ -909,6 +1013,14 @@ std::unordered_map, uint16_t, hash_pair_ff> + GfxRenderingAPIOGL::GetPixelDepth(int fb_id, const std::set>& coordinates) { + std::unordered_map, uint16_t, hash_pair_ff> res; + ++#ifdef USE_GLES2 ++ // GLES2 cannot read the depth buffer: every point is reported at the far plane ++ for (const auto& coord : coordinates) { ++ res.emplace(coord, 0xFFFC); ++ } ++ return res; ++#endif ++ + FramebufferOGL& fb = mFrameBuffers[fb_id]; + + // When looking up one value and the framebuffer is single-sampled, we can read pixels directly +@@ -930,8 +1042,8 @@ GfxRenderingAPIOGL::GetPixelDepth(int fb_id, const std::set + #include ++#elif defined(USE_GLES2) ++#include ++#include ++#include + #elif USE_OPENGLES + #include + #include +diff --git a/src/graphic/Fast3D/backends/gfx_sdl2.cpp b/src/graphic/Fast3D/backends/gfx_sdl2.cpp +index 1387e280..6a62bb8b 100644 +--- a/src/graphic/Fast3D/backends/gfx_sdl2.cpp ++++ b/src/graphic/Fast3D/backends/gfx_sdl2.cpp +@@ -343,6 +343,13 @@ void GfxWindowBackendSDL2::Init(const char* gameName, const char* gfxApiName, bo + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); + #endif ++#if defined(USE_GLES2) ++ // an OpenGL ES 2.0 context (without it, Mesa drivers such as lima give ++ // desktop OpenGL 2.1, whose GLSL 1.20 compiles none of our shaders) ++ SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); ++ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); ++ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); ++#endif + + #ifdef _WIN32 + // Use high-resolution mTimer by default on Windows 10 (so that NtSetTimerResolution (...) hacks are not needed) +diff --git a/src/graphic/Fast3D/shaders/opengl/default.shader.fs b/src/graphic/Fast3D/shaders/opengl/default.shader.fs +index 404caae6..f9b5dd43 100644 +--- a/src/graphic/Fast3D/shaders/opengl/default.shader.fs ++++ b/src/graphic/Fast3D/shaders/opengl/default.shader.fs +@@ -53,14 +53,18 @@ uniform int texture_filtering[2]; + + float random(in vec3 value) { + float random = dot(sin(value), vec3(12.9898, 78.233, 37.719)); ++@if(gles2) ++ return fract(sin(random) * 43758.5453); ++@else + return fract(sin(random) * 143758.5453); ++@end + } + + vec4 fromLinear(vec4 linearRGB){ + bvec3 cutoff = lessThan(linearRGB.rgb, vec3(0.0031308)); + vec3 higher = vec3(1.055)*pow(linearRGB.rgb, vec3(1.0/2.4)) - vec3(0.055); + vec3 lower = linearRGB.rgb * vec3(12.92); +- return vec4(mix(higher, lower, cutoff), linearRGB.a); ++ return vec4(mix(higher, lower, vec3(cutoff)), linearRGB.a); + } + + vec4 filter3point(in sampler2D tex, in vec2 texCoord, in vec2 texSize) { +@@ -106,7 +110,9 @@ void main() { + vec4 texVal@{i} = hookTexture2D(@{i}, uTex@{i}, vTexCoordAdj@{i}, texSize@{i}); + + @if(o_masks[i]) +- @if(opengles) ++ @if(gles2) ++ vec2 maskSize@{i} = texSize@{i}; ++ @elseif(opengles) + vec2 maskSize@{i} = vec2(textureSize(uTexMask@{i}, 0)); + @else + vec2 maskSize@{i} = textureSize(uTexMask@{i}, 0); +diff --git a/src/window/gui/Gui.cpp b/src/window/gui/Gui.cpp +index 953d4514..9df16003 100644 +--- a/src/window/gui/Gui.cpp ++++ b/src/window/gui/Gui.cpp +@@ -220,6 +220,8 @@ void Gui::ImGuiBackendInit() { + case WindowBackend::FAST3D_SDL_OPENGL: + #ifdef __APPLE__ + ImGui_ImplOpenGL3_Init("#version 410 core"); ++#elif defined(USE_GLES2) ++ ImGui_ImplOpenGL3_Init("#version 100"); + #elif USE_OPENGLES + ImGui_ImplOpenGL3_Init("#version 300 es"); + #else diff --git a/ports/starship/starship.patch b/ports/starship/starship.patch new file mode 100644 index 0000000..1029220 --- /dev/null +++ b/ports/starship/starship.patch @@ -0,0 +1,187 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 2b872a44..22a361f1 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -114,9 +114,13 @@ add_compile_definitions( + ) + + # Find necessary libraries +-if (UNIX AND NOT APPLE) ++if (UNIX AND NOT APPLE AND NOT USE_GLES2) + find_package(OpenGL REQUIRED) + endif() ++# the game knows it is a GLES2 build too (its first-start settings, Engine.cpp) ++if (USE_GLES2) ++add_compile_definitions(USE_GLES2) ++endif() + + configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/properties.h.in ${CMAKE_CURRENT_SOURCE_DIR}/properties.h @ONLY) + +diff --git a/port/shaders/opengl/default.shader.fs b/port/shaders/opengl/default.shader.fs +index 404caae6..f9b5dd43 100644 +--- a/port/shaders/opengl/default.shader.fs ++++ b/port/shaders/opengl/default.shader.fs +@@ -53,14 +53,18 @@ uniform int texture_filtering[2]; + + float random(in vec3 value) { + float random = dot(sin(value), vec3(12.9898, 78.233, 37.719)); ++@if(gles2) ++ return fract(sin(random) * 43758.5453); ++@else + return fract(sin(random) * 143758.5453); ++@end + } + + vec4 fromLinear(vec4 linearRGB){ + bvec3 cutoff = lessThan(linearRGB.rgb, vec3(0.0031308)); + vec3 higher = vec3(1.055)*pow(linearRGB.rgb, vec3(1.0/2.4)) - vec3(0.055); + vec3 lower = linearRGB.rgb * vec3(12.92); +- return vec4(mix(higher, lower, cutoff), linearRGB.a); ++ return vec4(mix(higher, lower, vec3(cutoff)), linearRGB.a); + } + + vec4 filter3point(in sampler2D tex, in vec2 texCoord, in vec2 texSize) { +@@ -106,7 +110,9 @@ void main() { + vec4 texVal@{i} = hookTexture2D(@{i}, uTex@{i}, vTexCoordAdj@{i}, texSize@{i}); + + @if(o_masks[i]) +- @if(opengles) ++ @if(gles2) ++ vec2 maskSize@{i} = texSize@{i}; ++ @elseif(opengles) + vec2 maskSize@{i} = vec2(textureSize(uTexMask@{i}, 0)); + @else + vec2 maskSize@{i} = textureSize(uTexMask@{i}, 0); +diff --git a/src/engine/fox_play.c b/src/engine/fox_play.c +index c11c9dd6..d0e192a5 100644 +--- a/src/engine/fox_play.c ++++ b/src/engine/fox_play.c +@@ -7172,7 +7172,8 @@ void Play_Main(void) { + + if ((gControllerPress[gMainController].button & START_BUTTON) && + (gPlayer[0].state == PLAYERSTATE_LEVEL_INTRO) && +- gSaveFile.save.data.planet[sSaveSlotFromLevel[gCurrentLevel]].normalClear) { ++ (gSaveFile.save.data.planet[sSaveSlotFromLevel[gCurrentLevel]].normalClear || ++ CVarGetInteger("gSkipAnyIntro", 1))) { + Audio_ClearVoice(); + Audio_SetEnvSfxReverb(0); + Play_ClearObjectData(); +diff --git a/src/port/Engine.cpp b/src/port/Engine.cpp +index bc0ccb1f..a2323027 100644 +--- a/src/port/Engine.cpp ++++ b/src/port/Engine.cpp +@@ -1,4 +1,7 @@ + #include "Engine.h" ++#ifdef USE_GLES2 ++#include // _exit ++#endif + #include "ui/ImguiUI.h" + #include "StringHelper.h" + +@@ -128,6 +131,17 @@ GameEngine::GameEngine() { + this->context->InitConfiguration(); // without this line InitConsoleVariables fails at Config::Reload() + this->context->InitConsoleVariables(); // without this line the controldeck constructor failes in + // ShipDeviceIndexMappingManager::UpdateControllerNamesFromConfig() ++#ifdef USE_GLES2 ++ if (!CVarGetInteger("gGles2DefaultsApplied", 0)) { ++ CVarSetInteger("gInterpolationFPS", 20); // the game's own frame rate: no extra frames ++ CVarSetInteger("gLowResMode", 1); // render at 320x240 (N64 mode), scaled to the screen ++ CVarSetInteger("gTextureFilter", 1); // FILTER_LINEAR: one hardware sample, not three-point ++ CVarSetInteger("gMSAAValue", 1); ++ CVarSetInteger("gHideMenuHint", 1); // no F1 key on a handheld ++ CVarSetInteger("gGles2DefaultsApplied", 1); ++ CVarSave(); ++ } ++#endif + + auto defaultMappings = std::make_shared( + // KeyboardKeyToButtonMappings - use built-in LUS defaults +@@ -318,6 +332,27 @@ void GameEngine::Destroy() { + + void GameEngine::StartFrame() const { + using Ship::KbScancode; ++#ifdef USE_GLES2 ++ { ++ static bool startWasDown; ++ bool back = false, start = false; ++ ++ for (int i = 0; i < SDL_NumJoysticks(); i++) { ++ SDL_GameController* pad = SDL_GameControllerFromInstanceID(SDL_JoystickGetDeviceInstanceID(i)); ++ ++ if (pad != nullptr) { ++ back |= SDL_GameControllerGetButton(pad, SDL_CONTROLLER_BUTTON_BACK) != 0; ++ start |= SDL_GameControllerGetButton(pad, SDL_CONTROLLER_BUTTON_START) != 0; ++ } ++ } ++ if (back && start && !startWasDown) { ++ SPDLOG_INFO("Select+Start: quitting"); ++ this->context->GetLogger()->flush(); ++ _exit(0); ++ } ++ startWasDown = start; ++ } ++#endif + const int32_t dwScancode = this->context->GetWindow()->GetLastScancode(); + this->context->GetWindow()->SetLastScancode(-1); + +diff --git a/src/port/interpolation/FrameInterpolation.cpp b/src/port/interpolation/FrameInterpolation.cpp +index 8d6c31ce..e0d55170 100644 +--- a/src/port/interpolation/FrameInterpolation.cpp ++++ b/src/port/interpolation/FrameInterpolation.cpp +@@ -164,6 +164,7 @@ struct Recording { + }; + + bool is_recording; ++bool frame_recording; // StartRecord turned recording on for this frame + vector current_path; + uint32_t camera_epoch; + uint32_t previous_camera_epoch; +@@ -416,7 +417,7 @@ bool camera_interpolation = true; + + void FrameInterpolation_ShouldInterpolateFrame(bool shouldInterpolate) { + // camera_interpolation = shouldInterpolate; +- is_recording = shouldInterpolate; ++ is_recording = shouldInterpolate && frame_recording; + } + + void FrameInterpolation_StartRecord(void) { +@@ -424,6 +425,7 @@ void FrameInterpolation_StartRecord(void) { + current_recording = {}; + current_path.clear(); + current_path.push_back(¤t_recording.root_path); ++ frame_recording = false; + if (!camera_interpolation) { + // default to interpolating + camera_interpolation = true; +@@ -432,6 +434,7 @@ void FrameInterpolation_StartRecord(void) { + } + if (GameEngine::GetInterpolationFPS() != 20) { + is_recording = true; ++ frame_recording = true; + } + } + +@@ -456,7 +459,9 @@ void FrameInterpolation_RecordCloseChild(void) { + if (has_inv_actor_mtx && current_path.size() == inv_actor_mtx_path_index) { + has_inv_actor_mtx = false; + } +- current_path.pop_back(); ++ if (current_path.size() > 1) { ++ current_path.pop_back(); ++ } + } + + void FrameInterpolation_DontInterpolateCamera(void) { +diff --git a/src/port/ui/ImguiUI.cpp b/src/port/ui/ImguiUI.cpp +index 5874ac2a..c4af2d96 100644 +--- a/src/port/ui/ImguiUI.cpp ++++ b/src/port/ui/ImguiUI.cpp +@@ -45,7 +45,7 @@ void SetupGuiElements() { + mGameMenuBar = std::make_shared("gOpenMenuBar", CVarGetInteger("gOpenMenuBar", 0)); + gui->SetMenuBar(mGameMenuBar); + +- if (gui->GetMenuBar() && !gui->GetMenuBar()->IsVisible()) { ++ if (gui->GetMenuBar() && !gui->GetMenuBar()->IsVisible() && !CVarGetInteger("gHideMenuHint", 0)) { + #if defined(__SWITCH__) || defined(__WIIU__) + Notification::Emit({ .message = "Press - to access enhancements menu", .remainingTime = 10.0f }); + #else diff --git a/scripts/store/make-catalog.py b/scripts/store/make-catalog.py new file mode 100644 index 0000000..e0832a6 --- /dev/null +++ b/scripts/store/make-catalog.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Build and sign the store catalog (docs/store-design.md). + + make-catalog.py --entries store/entries --base-url https://host -o out/ [--key store.key] [--mkupdate rsos-mkupdate] + +Every entries/*.json describes one game: the catalog fields (id, name, system, version, author, license, +source, desc, kind, file | launcher, arch, cover) plus "payload": the local file to publish +(a ROM, or a ustar archive for kind tar/native). size, sha256, unpacked and url are filled in here. +Output: out/catalog.json, out/catalog.json.sig (with --key), and the payload files copied to out/files/. +An entry without a licence or a source URL is refused: the store only carries redistributable content. +""" +import argparse, hashlib, json, os, shutil, subprocess, sys, tarfile + +REQUIRED = ["id", "name", "system", "version", "author", "license", "source", "desc", "kind", "payload"] + + +def sha256_file(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for b in iter(lambda: f.read(1 << 20), b""): + h.update(b) + return h.hexdigest() + + +def unpacked_size(path): + """Sum of the file sizes of a tar (plain, or .tar.zst with Python 3.14's tarfile).""" + total = 0 + with tarfile.open(path) as t: + for m in t: + if not (m.isfile() or m.isdir()): + raise SystemExit(f"{path}: {m.name} is not a plain file or folder") + if m.name.startswith("/") or ".." in m.name.split("/"): + raise SystemExit(f"{path}: unsafe name {m.name}") + if m.isfile(): + total += m.size + return total + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--entries", required=True) + ap.add_argument("--base-url", required=True) + ap.add_argument("-o", "--out", required=True) + ap.add_argument("--key") + ap.add_argument("--key-env") + ap.add_argument("--mkupdate", default="rsos-mkupdate") + a = ap.parse_args() + + os.makedirs(os.path.join(a.out, "files"), exist_ok=True) + entries, ids = [], set() + for fn in sorted(os.listdir(a.entries)): + if not fn.endswith(".json"): + continue + d = json.load(open(os.path.join(a.entries, fn), encoding="utf-8")) + for k in REQUIRED: + if not d.get(k): + raise SystemExit(f"{fn}: missing {k}") + if d["id"] in ids: + raise SystemExit(f"{fn}: duplicate id {d['id']}") + ids.add(d["id"]) + if d["kind"] not in ("rom", "tar", "native", "port"): + raise SystemExit(f"{fn}: bad kind") + if d["kind"] == "rom" and not d.get("file"): + raise SystemExit(f"{fn}: a rom needs file") + if d["kind"] == "native" and not (d.get("launcher") and d.get("arch")): + raise SystemExit(f"{fn}: native needs launcher and arch") + if d["kind"] == "port" and not (d.get("arch") and d.get("rom") and d["rom"].get("sha1") and d["rom"].get("mode")): + raise SystemExit(f"{fn}: a port needs arch and a rom block (sha1, mode)") + src = os.path.join(os.path.dirname(os.path.abspath(os.path.join(a.entries, fn))), d.pop("payload")) + base = os.path.basename(src) + shutil.copyfile(src, os.path.join(a.out, "files", base)) + d["size"] = os.path.getsize(src) + d["sha256"] = sha256_file(src) + d["unpacked"] = unpacked_size(src) if d["kind"] in ("tar", "native", "port") else d["size"] + d["url"] = a.base_url.rstrip("/") + "/files/" + base + entries.append(d) + + cat = {"format": 1, "entries": entries} + path = os.path.join(a.out, "catalog.json") + with open(path, "w", encoding="utf-8", newline="\n") as f: + json.dump(cat, f, ensure_ascii=False, indent=1, sort_keys=True) + f.write("\n") + print(f"{path}: {len(entries)} entries") + if a.key or a.key_env: + cmd = [a.mkupdate, "signfile"] + cmd += ["-s", a.key] if a.key else ["--key-env", a.key_env] + cmd += ["-o", path + ".sig", path] + subprocess.check_call(cmd) + + +if __name__ == "__main__": + sys.exit(main())