diff --git a/CHANGELOG.md b/CHANGELOG.md index bc8cdee..88e7c2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,30 @@ +## 1.0.2 + +- The command-line installer is now called `opengp-cli`, so it is no longer mistaken for the way to install OpenGP +- The menu no longer shows your full folder path: an **Open folder** button opens the card or controls folder instead +- Plainer names and help text in the menu's settings, These now match the settings text from the launcher +- Aspect ratio and resolution choices now name their sizes (16:9, 1080p, 4K and so on) +- Gamepads without a Guide button (or where Steam takes it) open the menu with **Back** and **Start** held together +- Key bindings now show the correct key labels on non-US keyboards +- Fixed the default window size on high-DPI displays +- Removed debug spam from the console (use `--verbose` to restore pre 1.0.2 behaviour) +- Added a first-run hint for inserting a coin and opening the menu +- Improved wheel and pedal precision +- Fixed pedals reading as half-pressed until they were first moved +- Fixed pedals binding to the wrong axis half when bound before they were first moved +- The webcam no longer switches on at start-up: the game's camera check gets a picture without it +- Fixed the first photo coming out darker than intended +- Fixed audio drifting out of sync after changing the audio device +- Fixed occasional audio stutter +- Fixed a small periodic stutter on 60 and 120 Hz displays + +### Known issues + +- Races need most of a CPU core: a PC busy with something else (another game) can drop below + 60 fps. +- Linked races can still freeze for a moment now and then; this is being fixed for 1.0.3. +- 1.0.2 cabinets link with 1.0.1 ones, but not with 1.0.0, run 1.0.1 or newer on every cabinet. + ## 1.0.1 (2/11/2026) - A new in-game menu in the OpenGP launcher's look: a pause card, with the settings in a dialog @@ -39,4 +66,4 @@ - Races need most of a CPU core: a PC busy with something else (another game) can drop below 60 fps. -- 1.0.1 cabinets can't link with 1.0.0 or 0.4.0 ones: run the same version on every cabinet. + diff --git a/CMakeLists.txt b/CMakeLists.txt index 64573b2..49e8093 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.25) -project(OpenGP VERSION 1.0.1 LANGUAGES C CXX) +project(OpenGP VERSION 1.0.2 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/README.md b/README.md index 8247a1f..dc2f419 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ your GGPE02.iso ─extract─> main.dol ─decomp-toolkit─> symbols.txt | Input | `runtime/input/` | Keyboard, gamepads and wheels (SDL3) mapped onto the cabinet's controls, force feedback, scripted input | | App | `runtime/app/` | Command line, settings, window, the in-game menu (Dear ImGui) | | Games | `games/` | Per-game manifest, symbol maps, recompiler config and patches (`mkgp1`, `mkgp2`); what both share in `common/` (their `main()`, SDK replacements, the arcade library's free play and test-menu restart) | -| Installer | `tools/installer/` | Builds the games on the player's machine from the installer package: the library the package's launcher uses, and `opengp-install` (see [docs/packaging.md](docs/packaging.md)) | +| Installer | `tools/installer/` | Builds the games on the player's machine from the installer package: the library the package's launcher uses, and `opengp-cli` (see [docs/packaging.md](docs/packaging.md)) | | Scripts | `tools/*.py`, `tools/devshell.ps1` | Game setup (extract and verify `main.dol`), naming functions (SDK signatures, the GP 2 decomp, matching functions between the games), Windows build shell | | Tests | `tests/` | Decoder, known-answer semantics and differential tests (interpreter vs recompiled code), and tests of the hardware, renderer front end, settings, input, link, paths, the installer and crash reports | @@ -61,7 +61,7 @@ The code is held to the same checks as any other: Download the launcher package for Windows, Linux or macOS (Apple Silicon) from the releases, unpack it and open `OpenGP`, the launcher. Add your disc image of each game: OpenGP builds the games on your machine from your images, then plays them (see [docs/packaging.md](docs/packaging.md) and -[docs/playing.md](docs/playing.md)). On the command line, `opengp-install` builds them the same way. +[docs/playing.md](docs/playing.md)). On the command line, `opengp-cli` builds them the same way. ## Building diff --git a/docs/architecture.md b/docs/architecture.md index e1d78c0..0bea214 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -396,7 +396,7 @@ Releases ship everything but the games: the runtime as static libraries with its recompiler (inside the installer) and the games' own files. The installer checks the player's image, recompiles its `main.dol`, compiles the result with a C++ compiler (llvm-mingw on Windows, the system's on Linux and macOS) and links it with the runtime. It is a library: the program players -open, `OpenGP` (from opengp-launcher), builds the games with it, and so does `opengp-install`, its +open, `OpenGP` (from opengp-launcher), builds the games with it, and so does `opengp-cli`, its command-line program. See [packaging.md](packaging.md). ### Reboots (`runtime/os/reboot.h`) diff --git a/docs/building.md b/docs/building.md index 5ded4b4..c5d4440 100644 --- a/docs/building.md +++ b/docs/building.md @@ -76,7 +76,7 @@ build//games/mkgp2/opengp-mkgp2 [--iso PATH] [--user-dir PATH] [--timeou [--headless] [--no-video] [--screenshot FRAME]... [--screenshot-every N] [--input SCRIPT] [--input-file PATH] [--free-play] [--test-menu] [--no-audio] [--volume PERCENT] [--audio-dump PATH] [--game-log] - [--camera off|webcam|test] [--cabinet 1-4] [--lan] + [--camera off|webcam|test] [--cabinet 1-4] [--lan] [--verbose] ``` `opengp-mkgp1` (Mario Kart Arcade GP, in `build//games/mkgp1/`) takes the same options. `--version` prints the @@ -85,9 +85,11 @@ version and the game. Controls and playing are covered in [playing.md](playing.md). `opengp-mkgp2` finds the image in `ISO/` or `private/` (or takes `--iso`), boots it and runs the -game in a window (Vulkan, or Metal on macOS, through SDL3's GPU API). It prints: -- the game's `OSReport` output; -- a status line every `--status` seconds (default 5; 0 for none): retraces, frames and draws so +game in a window (Vulkan, or Metal on macOS, through SDL3's GPU API). It prints a short summary at +start-up, what happens (a card, a gamepad, a restart) and problems. With `--verbose` it also prints: +- the game's `OSReport` output, the hardware's unhandled accesses and first register accesses, and + the DSP's microcode; +- a status line every `--status` seconds (default 5 with `--verbose`, else none; 0 for none): retraces, frames and draws so far, guest threads, pending interrupts, the sound output's queue (its length, and how often it ran dry or overflowed), and each guest thread's call stack when call tracing is on. @@ -112,6 +114,7 @@ options that change them do so for that run only. | `--volume PERCENT` | Sound volume, 0-100 (default 100) | | `--audio-dump PATH` | Also write the sound to a WAV file (works headless too) | | `--game-log` | Print the game's own debug messages (see [triforce.md](triforce.md#the-games-debug-messages-milestone-10)) | +| `--verbose` | Print what is only for working on OpenGP: the SDK's messages, hardware accesses, a status line every 5 s | | `--camera SOURCE` | The camera's pictures: `off`, `webcam` or `test` (colour bars; see [playing.md](playing.md#the-camera)) | | `--cabinet N` | This cabinet's number for linking, 1-4 (see [playing.md](playing.md#linked-cabinets)) | | `--lan` | Link with cabinets on the local network too | diff --git a/docs/packaging.md b/docs/packaging.md index 7c73a34..ad51d3e 100644 --- a/docs/packaging.md +++ b/docs/packaging.md @@ -78,17 +78,17 @@ Update every linked cabinet: cabinets on different versions of OpenGP may not li ### On the command line -`opengp-install` (`opengp-install.exe`), next to OpenGP, is the same installer for the command +`opengp-cli` (`opengp-cli.exe`), next to OpenGP, is the same installer for the command line. It builds each game from the images you give it, or without any, from the images the games were built from before, then those in `ISO/`. On Windows you can also drop an image on -`opengp-install.exe`. If it finds no image for a game, it skips that game and builds the other. +`opengp-cli.exe`. If it finds no image for a game, it skips that game and builds the other. When you run it again, it rebuilds only the games that an earlier version of the package built. -`--force` rebuilds every game. If you move an image, give `opengp-install` its new path (or drop it -on `opengp-install.exe`), and the game uses it from then on. +`--force` rebuilds every game. If you move an image, give `opengp-cli` its new path (or drop it +on `opengp-cli.exe`), and the game uses it from then on. ``` -opengp-install [IMAGE...] [--force] [--jobs N] [--cxx COMPILER] [--keep-build] +opengp-cli [IMAGE...] [--force] [--jobs N] [--cxx COMPILER] [--keep-build] ``` - `--jobs N` compiles N files at a time. The default is one per CPU thread. @@ -143,7 +143,7 @@ OpenGP[.exe] the launcher, which players open (OpenGP.app on macOS, w qt/, qt.conf the Qt the launcher uses, on Windows and Linux. On Windows, Qt's DLLs are next to OpenGP.exe, with Microsoft's Visual C++ runtime and Direct3D shader compilers (d3dcompiler_47.dll, dxcompiler.dll and dxil.dll) -opengp-install[.exe] the installer, for the command line +opengp-cli[.exe] the installer, for the command line sdk/package.toml the version, the pinned compiler, compile and link settings sdk/include/ the runtime's headers sdk/lib/ the runtime as static libraries, with SDL3 and Dear ImGui @@ -224,7 +224,7 @@ cmake --install build/launcher --prefix $PWD/out/OpenGP-linux-x64 # or -wind ``` To try a package build, open its launcher, for example `out/OpenGP-windows-x64/OpenGP.exe`, or run -its installer, `opengp-install`, with an image. +its installer, `opengp-cli`, with an image. Some settings must change together: - CI builds the runtime with the llvm-mingw release that `cmake/package.cmake` pins, and the diff --git a/docs/playing.md b/docs/playing.md index 0e00fb5..528d343 100644 --- a/docs/playing.md +++ b/docs/playing.md @@ -8,7 +8,7 @@ details. - **From the installer package**: unpack it, open `OpenGP` (the launcher) and add your disc image of each game. It builds each game you have an image of, once, and then plays it; see - [packaging.md](packaging.md). On the command line, `opengp-install` builds them the same way. + [packaging.md](packaging.md). On the command line, `opengp-cli` builds them the same way. The games, `opengp-mkgp2` and `opengp-mkgp1`, then sit next to OpenGP. - **From source**: see [building.md](building.md) and [game-files.md](game-files.md). @@ -20,7 +20,8 @@ way, and everything on this page applies to both. The games behave like the arcade cabinet: insert a coin and press start; in the menus, steer to choose and step on the gas pedal to decide. Turn on free play in the menu (Esc), or start the -game with `--free-play`, to play without coins ("Step on gas pedal to start"). +game with `--free-play`, to play without coins ("Step on gas pedal to start"). The first time a +game starts, a hint says which keys put in a coin, start and open the menu. ```sh opengp-mkgp2 --free-play # in the installer package's folder @@ -32,14 +33,14 @@ the card keeps your progress (Mario Coins, titles, unlocked characters). See [Ma ## The menu -**Esc** (or a gamepad's guide button) opens the menu over the game: **Resume**, **Settings**, +**Esc** (or a gamepad's guide button, or **Back** and **Start** held together) opens the menu over the game: **Resume**, **Settings**, **Test menu** (the game's own, for operators: it restarts the game) and **Quit**. The game pauses while the menu is open and gets no controls (turn off **Pause while this menu is open** in Settings, on the Game page, to keep it running). The menu works with the keyboard, a gamepad or the mouse: the arrows (or the d-pad and left stick) move, **Enter** (or **A**) selects, and **Esc** (or **B**) goes back one step, out to the game -from the first one; the guide button closes the menu from anywhere. In Settings, **Page Up** and +from the first one; the guide button (or Back + Start) closes the menu from anywhere. In Settings, **Page Up** and **Page Down** (or **LB** and **RB**) change pages, and **Left** and **Right** change the chosen row's value without opening a list. Quitting, the test menu and restoring the default controls ask first. @@ -112,10 +113,18 @@ even_pacing` in `user/settings.toml`), OpenGP holds each frame until the game's cabinet's display does, so the frames come evenly spaced. It costs about half a frame (8 ms) of delay, and matters most in fullscreen with FreeSync or G-Sync. +### 60 Hz and 120 Hz displays + +The game's clock is NTSC's 59.94 Hz, a little slower than a 60 Hz display: at real speed one +frame in a thousand would be shown twice, a small hitch every 17 seconds. With vsync on, on a +display within half a percent of 60 Hz or a multiple of it, OpenGP runs the game 0.1% faster to +match it (the console says so); the sound speeds up the same, which no one hears. Linked races +run at real speed. + ## Mario Cards Cards are saved in `user/cards/GGPE01/` (GP) and `user/cards/GGPE02/` (GP 2), one file per card -(`Card 1.bin`, ...). In the menu's Game tab you choose the card you hold: you insert it when the +(`Card 1.bin`, ...); **Open folder**, under the card list, opens that folder. In the menu's Game tab you choose the card you hold: you insert it when the game asks for your card, and the game takes it back at the end. **New card** gives you a blank one (answer **No** to "Do you have Mario Card?", then buy a card, and it is saved under that name); **No card** plays without one. A card the game gives you is yours to hold from then on, so you can keep a card per player. Files can be @@ -141,9 +150,11 @@ there is no webcam, the game runs without its camera and says so on the console. `webcam` (the webcam's name, `""` for the first), and `--camera off|webcam|test` sets it for one run. -The webcam is on only while the game uses it: while your photo is taken, for a moment as the game -starts (it checks its camera), and on the test menu's camera page. Its light goes off a few -seconds later. If the webcam can't be opened then (another program is using it, say), the photo +The webcam is on only while the game uses it: while your photo is taken and on the test menu's +camera page (the game's camera check at start-up gets a grey picture, without the webcam). Its +light goes off a few seconds later. Its first moment's pictures, dark while it adjusts to the +room's light, are left out, and in a dim room the picture is brightened (the cabinet had its own +light). If the webcam can't be opened then (another program is using it, say), the photo is grey and the console says why. ## Linked cabinets @@ -223,7 +234,7 @@ it as well. | Start | Enter, 1 | Start | | Coin | 5, C | Back | | Service / test | F1 / F2 | | -| Menu | Esc | Guide | +| Menu | Esc | Guide, Back + Start | | Pause | P, Pause | | | Fullscreen | F11, Alt+Enter | | | Screenshot | F12 | | @@ -246,7 +257,7 @@ at all is kept as `controls.toml.bad` and the default controls are used. Each co ```toml [keyboard] -gas = ["Up", "W", "Left Shift"] # SDL key names +gas = ["Up", "W", "Left Shift"] # SDL key names, by their place on a US keyboard [gamepad] item = ["a", "x"] # SDL gamepad button names @@ -257,6 +268,9 @@ gas = ["-axis2"] # a pedal that reads highest when released brake = ["-axis3"] ``` +The file names keys by where they are on a US keyboard, so it works with any layout; the menu +shows them as your keyboard's layout prints them (`W` on an AZERTY keyboard shows as **Z**). + Axes: `axis2` is the whole axis, `axis2+` and `axis2-` are one half of it, and a leading `-` turns it around. The file itself lists every name. diff --git a/games/common/sdk_hle.cpp b/games/common/sdk_hle.cpp index 055a24d..94f1f23 100644 --- a/games/common/sdk_hle.cpp +++ b/games/common/sdk_hle.cpp @@ -17,6 +17,7 @@ #include "os/printf.h" #include "os/reboot.h" #include "os/threads.h" +#include "os/verbose.h" #include "ppc/memory.h" #include "ppc_recomp_shared.h" @@ -42,8 +43,10 @@ gekko::u8* ram(gekko::u8* base, gekko::u32 address, gekko::u32 size) { namespace guest { -// OSReport(const char* fmt, ...): print to the host console. +// OSReport(const char* fmt, ...): print to the host console with --verbose +// (the SDK's start-up banners and the like: nothing a player needs). PPC_FUNC(OSReport) { + if (!os::verbose()) return; std::string text = os::format_guest(ctx, base, ctx.gpr[3], 4); if (text.empty() || text.back() != '\n') text += '\n'; std::fputs(("[OSReport] " + os::sjis_to_utf8(text)).c_str(), stdout); diff --git a/runtime/app/launcher.cpp b/runtime/app/launcher.cpp index 7f7dde7..ccabdd9 100644 --- a/runtime/app/launcher.cpp +++ b/runtime/app/launcher.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -17,6 +18,7 @@ #include #include #include +#include #include #include @@ -39,6 +41,7 @@ #include "os/profiler.h" #include "os/reboot.h" #include "os/thread_priority.h" +#include "os/verbose.h" #include "ppc/hooks.h" #include "ppc/trace.h" @@ -66,7 +69,7 @@ constexpr const char* kUsage = " [--headless] [--no-video] [--screenshot FRAME]... [--screenshot-every N]\n" " [--input SCRIPT] [--input-file PATH] [--free-play] [--test-menu]\n" " [--no-audio] [--volume PERCENT] [--audio-dump PATH] [--game-log]\n" - " [--camera off|webcam|test] [--cabinet 1-4] [--lan] [--version]\n"; + " [--camera off|webcam|test] [--cabinet 1-4] [--lan] [--verbose] [--version]\n"; struct Options { std::vector args; // as given, for restarts (without --reboot and --frame-offset) @@ -75,7 +78,7 @@ struct Options { bool test_menu = false; // start in the game's test menu std::string image; std::string user_dir; // UTF-8 - int timeout_s = -1, status_s = 5; + int timeout_s = -1, status_s = -1; // status: -1 is every 5 s with --verbose, else none bool headless = false, use_video = true, use_audio = true; bool game_log = false; // print the game's debug messages std::set screenshots; @@ -131,6 +134,7 @@ int parse_options(const std::vector& args, Options& o) { else if (a == "--audio-dump" && has_value) o.audio_dump = argv[++i]; else if (a == "--no-audio") o.use_audio = false; else if (a == "--game-log") o.game_log = true; + else if (a == "--verbose") os::g_verbose = true; else if (a == "--volume" && has_value) o.volume = std::clamp(std::atoi(argv[++i]), 0, 100); else if (a == "--lan") o.lan = true; else if (a == "--cabinet" && has_value) { @@ -188,6 +192,87 @@ void apply_options(const Options& o, Settings& s) { if (o.lan) s.lan = *o.lan; } +// The window's size in settings.toml is in units of the display's scale (as +// Windows' display settings count it), so the default 1280 x 720 is the same +// size on a 4K display at 200% as on a 1080p one at 100%. This is how many of +// SDL's window units one of them is: the display's scale where SDL's window +// sizes are pixels (Windows, X11), 1 where they are already scaled (macOS, +// Wayland). +float window_units(SDL_Window* window) { + const float display = SDL_GetWindowDisplayScale(window); + const float density = SDL_GetWindowPixelDensity(window); + if (!(display > 0.0f) || !(density > 0.0f)) return 1.0f; + return display / density; +} + +// Sizes a new (hidden) window from the settings for its display, no larger +// than the display's usable area, and centres it. +void size_window(SDL_Window* window, int width, int height) { + const float units = window_units(window); + float w = std::round(static_cast(width) * units), h = std::round(static_cast(height) * units); + SDL_Rect usable; + if (SDL_GetDisplayUsableBounds(SDL_GetDisplayForWindow(window), &usable) && usable.w > 0 && usable.h > 0) { + // Room for the title bar and borders. + const float fit = std::min({1.0f, usable.w * 0.95f / w, usable.h * 0.9f / h}); + w = std::round(w * fit); + h = std::round(h * fit); + } + SDL_SetWindowSize(window, static_cast(w), static_cast(h)); + SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); +} + +// The machine's clock rate for the window's display (Hardware::set_clock_rate): +// the game's retraces come at 59.94 Hz, NTSC's rate. On a display whose +// refresh is within half a percent of a multiple of it (60 Hz, 120 Hz), with +// vsync on, the machine runs that much faster so that each of its frames +// gets the same number of refreshes: at real time, one frame in 1000 is shown +// twice on a 60 Hz display (a hitch every 16.7 seconds). The sound speeds up +// the same 0.1%, which no one hears. Otherwise (other rates, variable +// refresh, no vsync), and in a linked race, real time. +double display_clock_rate(SDL_Window* window, bool vsync) { + if (!window || !vsync) return 1.0; + const SDL_DisplayMode* mode = SDL_GetCurrentDisplayMode(SDL_GetDisplayForWindow(window)); + if (!mode) return 1.0; + const double hz = mode->refresh_rate_numerator > 0 && mode->refresh_rate_denominator > 0 + ? static_cast(mode->refresh_rate_numerator) / mode->refresh_rate_denominator + : static_cast(mode->refresh_rate); + constexpr double kGameHz = 2.0 * static_cast(hw::kTimebaseHz) / static_cast(hw::ViDevice::kTicksPerFrame); + for (int k = 1; k <= 4; ++k) { + const double rate = hz / (k * kGameHz); + if (std::fabs(rate - 1.0) <= 0.005) return rate; + } + return 1.0; +} + +// The hint a new player gets once, a few seconds after the game starts: how +// to open the menu and put in a coin (by their own bindings). +std::string first_run_hint(const input::HostInput* in, bool free_play) { + using Kind = input::HostInput::DeviceKind; + auto labels = [in](Kind kind, std::string_view control) -> std::vector { + if (!in) return {}; + for (std::size_t c = 0; c < input::HostInput::kControlCount; ++c) + if (control == input::HostInput::control_name(c)) return in->binding_labels(kind, c); + return {}; + }; + auto first = [&](Kind kind, std::string_view control) -> std::string { + const std::vector l = labels(kind, control); + return l.empty() ? "" : l.front(); + }; + // The coin key: C when it is bound (easier to find than 5), else the first. + const std::vector coin_keys = labels(Kind::Keyboard, "coin"); + std::string coin = coin_keys.empty() ? "" : coin_keys.front(); + for (const std::string& k : coin_keys) + if (k == "C") coin = k; + // The gamepad's buttons, when they are still the defaults. + const bool pad_coin = first(Kind::Gamepad, "coin") == "back"; + const bool pad_menu = pad_coin && first(Kind::Gamepad, "start") == "start"; + std::string text = "Welcome to OpenGP. Use Escape on keyboard"; + text += pad_menu ? " or Back + Start on gamepad to open the menu." : " to open the menu."; + if (!free_play && !coin.empty()) text += " Use " + coin + (pad_coin ? " or Back" : "") + " to insert a coin."; + text += " Have fun!"; + return text; +} + // What to save: the settings file's values, except those changed (in the // menu, or by resizing the window) since start-up. Command-line options stay // out of the file. @@ -207,6 +292,7 @@ Settings settings_to_save(const Settings& file, const Settings& start, const Set OPENGP_KEEP_CHANGE(pause_in_menu); OPENGP_KEEP_CHANGE(pause_in_background); OPENGP_KEEP_CHANGE(card); + OPENGP_KEEP_CHANGE(first_run_hint); OPENGP_KEEP_CHANGE(camera); OPENGP_KEEP_CHANGE(webcam); OPENGP_KEEP_CHANGE(rich_presence); @@ -485,7 +571,7 @@ int run(const Game& game, int argc, char** argv) { "image in the ISO folder next to OpenGP."); return start_failed(std::string("No disc image of ") + game.title + " (" + game.id + ") found. Put it in the ISO folder next to OpenGP, or start the game with --iso PATH. If " - "you moved it, add it again in OpenGP (or give it to opengp-install) so the game knows " + "you moved it, add it again in OpenGP (or give it to opengp-cli) so the game knows " "where it is."); } if (!check_image(game, o.image)) return 1; @@ -609,9 +695,11 @@ int run(const Game& game, int argc, char** argv) { static_cast(machine.exception_returns())); #ifdef OPENGP_VIDEO if (g_audio_out) - std::fprintf(out, " audio: queue %.0f ms, %llu underruns, %llu overflows\n", g_audio_out->queue_ms(), + std::fprintf(out, " audio: queue %.0f ms (target %.0f), %llu underruns, %llu overflows, %llu resyncs\n", + g_audio_out->queue_ms(), g_audio_out->target_ms(), static_cast(g_audio_out->underruns()), - static_cast(g_audio_out->overflows())); + static_cast(g_audio_out->overflows()), + static_cast(g_audio_out->resyncs())); #endif for (ppc::TraceStack* s : ppc::trace_all_stacks()) { const auto frames = ppc::trace_snapshot(*s); @@ -649,7 +737,7 @@ int run(const Game& game, int argc, char** argv) { }; os::start_profiler_from_env(); - std::thread([timeout_s = o.timeout_s, status_s = o.status_s, print_status] { + std::thread([timeout_s = o.timeout_s, status_s = o.status_s >= 0 ? o.status_s : os::verbose() ? 5 : 0, print_status] { using clock = std::chrono::steady_clock; const auto deadline = timeout_s > 0 ? clock::now() + std::chrono::seconds(timeout_s) : clock::time_point::max(); for (;;) { @@ -682,9 +770,11 @@ int run(const Game& game, int argc, char** argv) { if (!o.headless) { const std::string title = std::string("OpenGP - ") + game.title; window = SDL_CreateWindow(title.c_str(), settings.window_width, settings.window_height, - SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY | + SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_HIDDEN | (settings.fullscreen ? SDL_WINDOW_FULLSCREEN : 0)); if (!window) return start_failed(std::string("Could not create a window: ") + SDL_GetError()); + size_window(window, settings.window_width, settings.window_height); + SDL_ShowWindow(window); } static video::Renderer renderer; if (!renderer.init(window, internal_scale(settings.internal_resolution, 0), &error)) { @@ -781,6 +871,22 @@ int run(const Game& game, int argc, char** argv) { applied_width = pw, applied_height = ph; }; apply_settings(); + // The machine's clock follows the display (display_clock_rate), looked at + // again every second: the window may move to another display, vsync may + // be turned off, a link may start. + auto next_clock_check = std::chrono::steady_clock::now(); + auto match_display = [&] { + const auto now = std::chrono::steady_clock::now(); + if (now < next_clock_check) return; + next_clock_check = now + std::chrono::seconds(1); + const double rate = machine.network().linked() ? 1.0 : display_clock_rate(window, settings.vsync); + if (std::fabs(rate - machine.hardware().clock_rate()) < 1e-7) return; + machine.hardware().set_clock_rate(rate); + const SDL_DisplayMode* mode = window ? SDL_GetCurrentDisplayMode(SDL_GetDisplayForWindow(window)) : nullptr; + std::fprintf(stderr, "[video] the game's clock runs at %.3f%% to match the display (%d/%d, %.3f Hz)\n", + rate * 100.0, mode ? mode->refresh_rate_numerator : 0, mode ? mode->refresh_rate_denominator : 0, + mode ? static_cast(mode->refresh_rate) : 0.0); + }; const fs::path shot_dir = user_dir / "screenshots"; bool shot_requested = false; @@ -824,6 +930,11 @@ int run(const Game& game, int argc, char** argv) { } if (use_menu) { for (const std::string& notice : os::take_player_notices()) menu.notify(notice, NoticeKind::Problem); + // Once the game has started (about 10 s: its device checks). + if (settings.first_run_hint && machine.gpu().frames() >= 600 && !menu.is_open()) { + settings.first_run_hint = applied.first_run_hint = false; + menu.notify(first_run_hint(use_input ? &host_input : nullptr, settings.free_play)); + } // The settings are saved when the menu closes, whatever closed it // (Esc, the Guide button, or its Resume button). if (menu_was_open && !menu.is_open()) save(); @@ -837,10 +948,9 @@ int run(const Game& game, int argc, char** argv) { case SDL_EVENT_WINDOW_RESIZED: // Remember the window's size (not the fullscreen or maximised one). if (window && !(SDL_GetWindowFlags(window) & (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_MAXIMIZED))) { - settings.window_width = e.window.data1; - settings.window_height = e.window.data2; - applied.window_width = e.window.data1; - applied.window_height = e.window.data2; + const float units = window_units(window); + settings.window_width = applied.window_width = static_cast(std::lround(e.window.data1 / units)); + settings.window_height = applied.window_height = static_cast(std::lround(e.window.data2 / units)); } break; case SDL_EVENT_WINDOW_ENTER_FULLSCREEN: settings.fullscreen = applied.fullscreen = true; break; @@ -890,7 +1000,7 @@ int run(const Game& game, int argc, char** argv) { triforce::Controls controls = host_input.poll(); if (release_guard) { const bool held = controls.test || controls.service || controls.coin || controls.start || controls.item || - controls.cancel || controls.gas > 16 || controls.brake > 16; + controls.cancel || controls.gas > 0.0625f || controls.brake > 0.0625f; if (held) controls = triforce::Controls{}; else release_guard = false; } @@ -900,6 +1010,7 @@ int run(const Game& game, int argc, char** argv) { } settings.card = applied.card = machine.cards().held(); // the game may have given the player a new card apply_settings(); + match_display(); if (!settings.rich_presence || !game.status || !(window || log_discord)) { rich_presence.reset(); } else if (const auto now = std::chrono::steady_clock::now(); now >= next_status) { diff --git a/runtime/app/launcher.h b/runtime/app/launcher.h index e9bf7e0..85668e1 100644 --- a/runtime/app/launcher.h +++ b/runtime/app/launcher.h @@ -11,7 +11,7 @@ // [--headless] [--no-video] [--screenshot FRAME]... [--screenshot-every N] // [--input SCRIPT] [--input-file PATH] [--free-play] [--test-menu] // [--no-audio] [--volume PERCENT] [--audio-dump PATH] [--game-log] -// [--camera off|webcam|test] [--cabinet 1-4] [--lan] [--version] +// [--camera off|webcam|test] [--cabinet 1-4] [--lan] [--verbose] [--version] // // Options override user/settings.toml for one run (see docs/building.md). #pragma once diff --git a/runtime/app/menu.cpp b/runtime/app/menu.cpp index ee5a3bd..c872ccf 100644 --- a/runtime/app/menu.cpp +++ b/runtime/app/menu.cpp @@ -12,11 +12,13 @@ #include #include #include +#include #include #include #include "app/menu_theme.h" #include "app/menu_widgets.h" +#include "os/utf8.h" namespace app { @@ -43,12 +45,42 @@ std::string pause_keys(const MenuModel& m, bool first = false) { std::string keys; for (std::size_t c = 0; c < input::HostInput::kControlCount; ++c) { if (std::string_view(input::HostInput::control_name(c)) != "pause") continue; - for (const std::string& key : m.input->bindings(input::HostInput::DeviceKind::Keyboard, c)) + for (const std::string& key : m.input->binding_labels(input::HostInput::DeviceKind::Keyboard, c)) if (keys.empty() || !first) keys += (keys.empty() ? "" : " / ") + key; } return keys; } +// Opens a folder (UTF-8) in the system's file manager, making it first if +// needed. The menu shows a button for this rather than the folder's path, +// which would show the player's user name on screen and in screenshots. +bool open_folder(const std::string& folder) { + std::error_code ec; + const std::filesystem::path path = std::filesystem::absolute(os::utf8_path(folder), ec); + if (ec) return false; + std::filesystem::create_directories(path, ec); +#ifdef _WIN32 + // ShellExecute (SDL_OpenURL on Windows) opens a plain path; a file:// URL + // with non-ASCII characters is read in the wrong code page. + const std::string url = os::utf8(path.lexically_normal().make_preferred()); +#else + // A file:// URL, with everything but unreserved characters and '/' + // percent-encoded (macOS needs a valid URL). + std::string url = "file://"; + for (const unsigned char c : os::utf8(path.lexically_normal())) { + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || + c == '.' || c == '~' || c == '/') { + url += static_cast(c); + } else { + char hex[4]; + std::snprintf(hex, sizeof hex, "%%%02X", c); + url += hex; + } + } +#endif + return SDL_OpenURL(url.c_str()); +} + // Whether the last navigation came from a gamepad (the hints show its buttons). bool using_gamepad() { return GImGui->NavInputSource == ImGuiInputSource_Gamepad; } @@ -151,6 +183,9 @@ void Menu::set_open(bool open) { screen_ = Screen::Card; confirm_ = Confirm::None; open_t_ = 0.0f; + // Information (the first-run hint) would cover the menu: the player has + // found it. Problems stay up. + std::erase_if(notices_, [](const Notice& n) { return n.kind == NoticeKind::Info; }); focus_window_ = focus_item_ = show_focus_ = true; } else { if (input_ && input_->capturing()) input_->cancel_capture(); @@ -161,9 +196,19 @@ void Menu::set_open(bool open) { bool Menu::handle_event(const SDL_Event& e) { if (!initialised_) return false; // Esc opens the menu; once it is open it goes back a level (update()). - // The guide button always opens or closes it. + // The guide button, or Back + Start held together (input/menu_chord.h), + // always opens or closes it. const bool esc = e.type == SDL_EVENT_KEY_DOWN && e.key.key == SDLK_ESCAPE && !e.key.repeat; - const bool guide = e.type == SDL_EVENT_GAMEPAD_BUTTON_DOWN && e.gbutton.button == SDL_GAMEPAD_BUTTON_GUIDE; + bool guide = false; + if (e.type == SDL_EVENT_GAMEPAD_BUTTON_DOWN) { + const auto button = static_cast(e.gbutton.button); + guide = button == SDL_GAMEPAD_BUTTON_GUIDE; + if (button == SDL_GAMEPAD_BUTTON_BACK || button == SDL_GAMEPAD_BUTTON_START) { + SDL_Gamepad* pad = SDL_GetGamepadFromID(e.gbutton.which); + const auto other = button == SDL_GAMEPAD_BUTTON_BACK ? SDL_GAMEPAD_BUTTON_START : SDL_GAMEPAD_BUTTON_BACK; + guide |= pad && SDL_GetGamepadButton(pad, other); + } + } if (guide || (esc && !open_)) { set_open(!open_); return true; @@ -531,50 +576,47 @@ void Menu::page_game(MenuModel& m) { cards.hold(name); s.card = name; } - const std::string where = "Cards are saved in " + cards.dir(); - ImGui::Indent(px(12)); - w::text_wrapped(where.c_str(), theme::kHelp, theme::kDim); - ImGui::Unindent(px(12)); + if (w::row_button({"Card files", "Each card is a file you can copy, back up or share."}, "Open folder")) + open_folder(cards.dir()); w::section("Pause"); - const std::string keys = pause_keys(m); - const std::string pause_help = m.linked ? "A linked game can't pause." : keys.empty() ? "" : keys + " pauses and resumes the game."; - w::row_toggle({"Pause while this menu is open", m.linked ? "A linked game can't pause." : "", !m.linked}, &s.pause_in_menu); - w::row_toggle({"Pause when the window is in the background", pause_help.c_str(), !m.linked}, &s.pause_in_background); + w::row_toggle({"Pause while the menu is open", "Pause the game while the in-game menu is open (no effect in VS races).", !m.linked}, + &s.pause_in_menu); + w::row_toggle({"Pause when unfocused", "Pause the game when it's in the background (no effect in VS races).", !m.linked}, + &s.pause_in_background); w::section("Discord"); - const char* discord_help = !s.rich_presence ? "" : m.discord ? "On your Discord profile: the game, character, cup, course and place." - : "Discord isn't running on this computer."; - w::row_toggle({"Show what you're playing", discord_help}, &s.rich_presence); + const char* discord_help = s.rich_presence && !m.discord ? "Discord isn't running on this computer." + : "Show what you are playing in Discord."; + w::row_toggle({"Discord Rich Presence", discord_help}, &s.rich_presence); w::section("Arcade"); - w::row_toggle({"Free play", "Play without coins."}, &s.free_play); + w::row_toggle({"Free play", "Enables Free Play mode."}, &s.free_play); } void Menu::page_video(MenuModel& m) { Settings& s = *m.settings; - if (w::row_toggle({"Full screen", "F11 or Alt+Enter switches too."}, &s.fullscreen)) {} + if (w::row_toggle({"Full screen", "F11 or Alt+Enter switches in the game too."}, &s.fullscreen)) {} take_focus(); - static const std::vector kAspects = {"Fit the window", "4:3 (original)", "16:9", "16:10", "21:9"}; + static const std::vector kAspects = {"Auto", "4:3 (Original)", "16:9 (Widescreen)", "16:10", "21:9 (Ultrawide)"}; static constexpr AspectRatio kAspectValues[] = {AspectRatio::Auto, AspectRatio::Original, AspectRatio::Wide16x9, AspectRatio::Wide16x10, AspectRatio::Wide21x9}; int aspect = 0; for (int i = 0; i < 5; ++i) if (kAspectValues[i] == s.aspect) aspect = i; - if (w::row_choice({"Aspect ratio", "Widescreen expands the view; some 2D elements keep their shape, some stretch to fit."}, &aspect, kAspects)) + if (w::row_choice({"Aspect ratio", "Set the aspect ratio of the game."}, &aspect, kAspects)) s.aspect = kAspectValues[aspect]; - std::vector resolutions; - resolutions.push_back("Match the window"); - for (u32 scale = 1; scale <= video::Renderer::kMaxScale; ++scale) - resolutions.push_back(std::to_string(scale) + "x (" + std::to_string(640 * scale) + "x" + std::to_string(480 * scale) + ")"); + static_assert(video::Renderer::kMaxScale == 8, "one name per scale"); + static const std::vector resolutions = { + "Auto", "1\xC3\x97 (Original)", "2\xC3\x97 (720p)", "3\xC3\x97 (1080p)", "4\xC3\x97 (1440p)", "5\xC3\x97", "6\xC3\x97 (4K)", "7\xC3\x97", "8\xC3\x97 (5K)"}; int resolution = static_cast(std::min(s.internal_resolution, video::Renderer::kMaxScale)); - if (w::row_choice({"Resolution", "How sharply the game draws, as a multiple of the cabinet's own."}, &resolution, resolutions)) + if (w::row_choice({"Resolution", "How sharply the game draws, as a multiple of the cabinet's 640\xC3\x97" "528."}, &resolution, resolutions)) s.internal_resolution = static_cast(resolution); - w::row_toggle({"VSync", "Waits for the display's refresh: no tearing."}, &s.vsync); - w::row_toggle({"Even frame pacing", "Shows each frame on the game's own 60 Hz tick, as the cabinet's display does: evenly spaced, so smoother with FreeSync or G-Sync, and about half a frame later."}, &s.even_pacing); + w::row_toggle({"VSync", "Lock the frame rate to your monitor. May cause input delay and screen tearing."}, &s.vsync); + w::row_toggle({"Frame pacing (experimental)", "Syncs frame times to those of the original cabinet: smoother with FreeSync or G-Sync, but adds a slight delay."}, &s.even_pacing); w::row_text({"Renderer", ""}, m.video_info.c_str()); } @@ -619,7 +661,7 @@ void Menu::page_controls(MenuModel& m) { } const float chips_x = start.x + px(12) + label_w; ImGui::SetCursorPos(ImVec2(chips_x, start.y)); - const std::vector names = in.bindings(kind, control); + const std::vector names = in.binding_labels(kind, control); bool first = true; auto place = [&](float width) { if (!first) { @@ -657,28 +699,22 @@ void Menu::page_controls(MenuModel& m) { w::divider(); if (kind == Kind::Keyboard) { float speed = in.steer_speed(); - if (w::row_slider({"Turn speed", "How fast keys turn the wheel, in full turns a second."}, &speed, 0.5f, 10.0f, 0.5f, "%.1f")) + if (w::row_slider({"Steering speed", "How fast keys turn the wheel. Simulates analogue steering."}, &speed, 0.5f, 10.0f, 0.5f, "%.1f")) in.set_steer_speed(speed); } else { float deadzone = in.deadzone(kind) * 100.0f; - if (w::row_slider({"Stick dead zone", "How far a stick or wheel moves before the game reads it."}, &deadzone, 0, 50, 1, "%.0f%%")) + if (w::row_slider({"Dead zone", "How far a stick or wheel moves before the game reads the input."}, &deadzone, 0, 50, 1, "%.0f%%")) in.set_deadzone(kind, deadzone / 100.0f); float strength = in.force_feedback() * 100.0f; - if (w::row_slider({"Force feedback", "Wheels get the road's forces; gamepads rumble when they are strong."}, &strength, 0, 200, 5, "%.0f%%")) + if (w::row_slider({"Force feedback", "Adjusts rumble intensity."}, &strength, 0, 200, 5, "%.0f%%")) in.set_force_feedback(strength / 100.0f); } bool background = in.background_input(); - if (w::row_toggle({"Use the controls in the background too", - input::HostInput::background_keyboard() - ? "Every OpenGP window reacts, active or not: for driving several copies at once." - : "Gamepads reach every OpenGP window, active or not (the keyboard only the active one)."}, - &background)) + if (w::row_toggle({"Background input", "Allows the game to be controlled while the window is not in focus."}, &background)) in.set_background_input(background); - if (w::row_button({"Bindings", "Every device goes back to OpenGP's defaults."}, "Restore defaults")) confirm_ = Confirm::RestoreDefaults; - const std::string where = "Saved in " + in.path(); - ImGui::Indent(px(12)); - w::text_wrapped(where.c_str(), theme::kHelp, theme::kDim); - ImGui::Unindent(px(12)); + if (w::row_button({"Bindings", "Every device goes back to OpenGP's defaults."}, "Restore the defaults")) confirm_ = Confirm::RestoreDefaults; + if (w::row_button({"Controls file", "Your bindings are kept in controls.toml."}, "Open folder")) + open_folder(os::utf8(os::utf8_path(in.path()).parent_path())); } void Menu::page_camera(MenuModel& m) { @@ -687,12 +723,12 @@ void Menu::page_camera(MenuModel& m) { w::info_box("Changes take effect when the game restarts."); w::gap(4); } - static const std::vector kSources = {"Off", "Webcam", "Test pattern"}; + static const std::vector kSources = {"Disabled", "Enabled", "Colour bars (test)"}; static constexpr CameraSource kSourceValues[] = {CameraSource::Off, CameraSource::Webcam, CameraSource::TestPattern}; int source = 0; for (int i = 0; i < 3; ++i) if (kSourceValues[i] == s.camera) source = i; - if (w::row_choice({"Photos from", "The game takes your photo for your character."}, &source, kSources)) s.camera = kSourceValues[source]; + if (w::row_choice({"Camera", "Enable or disable the camera."}, &source, kSources)) s.camera = kSourceValues[source]; take_focus(); if (s.camera == CameraSource::Webcam) { std::vector names; @@ -718,11 +754,11 @@ void Menu::page_link(MenuModel& m) { w::info_box("Changes take effect when the game restarts."); w::gap(4); } - static const std::vector kNumbers = {"The game's setting", "1", "2", "3", "4"}; + static const std::vector kNumbers = {"Use Machine Value (test menu)", "1", "2", "3", "4"}; int cabinet = std::clamp(s.cabinet, 0, 4); if (w::row_choice({"Cabinet number", "Give each OpenGP its own number, 1 to 4."}, &cabinet, kNumbers)) s.cabinet = cabinet; take_focus(); - w::row_toggle({"Link over the local network", "With copies of OpenGP on other computers, not just this one."}, &s.lan); + w::row_toggle({"Link using LAN", "Automatically links cabinets using copies of OpenGP on your local network."}, &s.lan); // Who it sees, with a dot: green linked, blue looking, red trouble. std::string linked, found; diff --git a/runtime/app/settings.cpp b/runtime/app/settings.cpp index ef6843f..494219f 100644 --- a/runtime/app/settings.cpp +++ b/runtime/app/settings.cpp @@ -126,6 +126,7 @@ bool load_settings(const std::string& path, Settings* settings, std::string* err s.pause_in_menu = game["pause_in_menu"].value_or(s.pause_in_menu); s.pause_in_background = game["pause_in_background"].value_or(s.pause_in_background); s.card = game["card"].value_or(s.card); + s.first_run_hint = game["first_run_hint"].value_or(s.first_run_hint); const auto camera = root["camera"]; if (const auto source = camera["source"].value(); source && !parse_camera(*source, &s.camera)) warn("unknown camera source \"" + *source + "\" (kept " + camera_name(s.camera) + ")"); @@ -148,7 +149,7 @@ bool save_settings(const std::string& path, const Settings& s, std::string* erro "fullscreen = " << (s.fullscreen ? "true" : "false") << "\n" - "# The window's size when not fullscreen.\n" + "# The window's size when not fullscreen, at 100% display scale (it grows with the scale).\n" "window_width = " << s.window_width << "\nwindow_height = " << s.window_height << "\n" @@ -183,6 +184,10 @@ bool save_settings(const std::string& path, const Settings& s, std::string* erro "# The Mario Card you hold (user/cards//.bin), or \"\" for none.\n" "card = " << quoted(s.card) + << "\n" + "# Show the hint about coins and the menu the next time the game starts.\n" + "first_run_hint = " + << (s.first_run_hint ? "true" : "false") << "\n" "\n" "[camera]\n" diff --git a/runtime/app/settings.h b/runtime/app/settings.h index 224fdc8..c520b0c 100644 --- a/runtime/app/settings.h +++ b/runtime/app/settings.h @@ -31,7 +31,7 @@ enum class CameraSource : u8 { struct Settings { // [video] bool fullscreen = false; - int window_width = 1280, window_height = 720; // the window's size when not fullscreen + int window_width = 1280, window_height = 720; // the window's size when not fullscreen, at 100% display scale AspectRatio aspect = AspectRatio::Auto; u32 internal_resolution = 0; // 0: from the window's size, else 1 to 8 times 640x528 bool vsync = true; @@ -45,6 +45,7 @@ struct Settings { bool pause_in_menu = true; // the game pauses while the menu is open bool pause_in_background = false; // ... and while its window is not the active one std::string card = "Card 1"; // the Mario Card the player holds (a file in user/cards/); "" for none + bool first_run_hint = true; // show the hint about coins and the menu (once, then false) // [camera] (read at start-up: changes take effect when the game restarts) CameraSource camera = CameraSource::Off; diff --git a/runtime/audio/host.cpp b/runtime/audio/host.cpp index 0f398d6..a785e3a 100644 --- a/runtime/audio/host.cpp +++ b/runtime/audio/host.cpp @@ -11,10 +11,18 @@ namespace audio { namespace { -// Queue length (measured as each 5 ms buffer arrives) to hold, and the most -// to allow before dropping samples, in milliseconds. +// Queue length (measured as each 5 ms buffer arrives) to hold at least, and +// at most; what each underrun adds; how far above the target the queue may +// stay before it is brought back; and the most to allow before dropping +// samples. In milliseconds. constexpr double kTargetMs = 30; -constexpr double kMaxMs = 150; +constexpr double kMaxTargetMs = 80; +constexpr double kUnderrunStepMs = 10; +constexpr double kResyncMs = 60; +constexpr double kMaxMs = 200; +// How often to look at the device's buffer again (it changes with the +// device), in pushes of about 5 ms. +constexpr u32 kDeviceCheckPushes = 200; // Largest speed-up or slow-down used to hold the target (0.5%: inaudible). constexpr double kMaxRatioChange = 0.005; @@ -39,10 +47,19 @@ bool HostOutput::init(float volume, std::string* error) { SDL_SetAudioStreamGain(stream_, std::clamp(volume, 0.0f, 1.0f)); const char* name = SDL_GetAudioDeviceName(SDL_GetAudioStreamDevice(stream_)); device_name_ = name ? name : "default device"; + update_target(); SDL_ResumeAudioStreamDevice(stream_); return true; } +void HostOutput::update_target() { + SDL_AudioSpec spec{}; + int frames = 0; + if (SDL_GetAudioDeviceFormat(SDL_GetAudioStreamDevice(stream_), &spec, &frames) && spec.freq > 0 && frames > 0) + device_ms_ = 2000.0 * frames / spec.freq; + target_ms_.store(std::min(std::max(kTargetMs, device_ms_) + underrun_ms_, kMaxTargetMs)); +} + void HostOutput::set_volume(float volume) { if (stream_) SDL_SetAudioStreamGain(stream_, std::clamp(volume, 0.0f, 1.0f)); } @@ -60,26 +77,49 @@ void HostOutput::push(const s16* samples, u32 frames, u32 rate) { SDL_SetAudioStreamFormat(stream_, &spec, nullptr); rate_ = rate; } + if (++pushes_ >= kDeviceCheckPushes) { + pushes_ = 0; + update_target(); + } + const double target = target_ms_.load(); const double ms_per_byte = 1000.0 / (4.0 * rate); double queued_ms = SDL_GetAudioStreamQueued(stream_) * ms_per_byte; if (queued_ms < 1) { - // Starting, or ran dry: rebuild the queue with silence. - const std::vector silence(static_cast(kTargetMs * rate / 1000) * 2, 0); - SDL_PutAudioStreamData(stream_, silence.data(), static_cast(silence.size() * sizeof(s16))); - queued_ms = queued_avg_ms_ = kTargetMs; - if (started_) underruns_.fetch_add(1); + // Starting, or ran dry: rebuild the queue with silence, a little longer + // after each time it runs dry. + if (started_) { + underruns_.fetch_add(1); + underrun_ms_ = std::min(underrun_ms_ + kUnderrunStepMs, kMaxTargetMs); + update_target(); + } started_ = true; + resyncing_ = false; + const double fill = target_ms_.load(); + const std::vector silence(static_cast(fill * rate / 1000) * 2, 0); + SDL_PutAudioStreamData(stream_, silence.data(), static_cast(silence.size() * sizeof(s16))); + queued_ms = queued_avg_ms_ = fill; } else if (queued_ms > kMaxMs) { overflows_.fetch_add(1); return; // far behind: drop + } else if (resyncing_ || queued_avg_ms_ > target + kResyncMs) { + // Far too long for a while (the device stalled): drop until it is back + // at the target, a short skip rather than the sound running late. + if (!resyncing_) resyncs_.fetch_add(1); + resyncing_ = queued_ms > target; + if (resyncing_) { + queued_avg_ms_ = queued_ms; + queue_ms_.store(queued_ms); + return; + } + queued_avg_ms_ = queued_ms; } SDL_PutAudioStreamData(stream_, samples, static_cast(frames * 4)); // Drain faster when the queue is long, slower when it is short. queued_avg_ms_ += (queued_ms - queued_avg_ms_) * 0.05; queue_ms_.store(queued_avg_ms_); - const double error = (queued_avg_ms_ - kTargetMs) / kTargetMs; + const double error = (queued_avg_ms_ - target) / target; const double ratio = 1.0 + std::clamp(error * 0.01, -kMaxRatioChange, kMaxRatioChange); SDL_SetAudioStreamFrequencyRatio(stream_, static_cast(ratio)); } diff --git a/runtime/audio/host.h b/runtime/audio/host.h index e7a39ee..f065769 100644 --- a/runtime/audio/host.h +++ b/runtime/audio/host.h @@ -6,7 +6,11 @@ // base, which follows the host clock), but the sound card has its own clock, // and the samples arrive in 5 ms bursts. A short queue absorbs the bursts; its // length is held near a target by resampling slightly faster or slower, and -// it is refilled with silence if it ever runs dry. +// it is refilled with silence if it ever runs dry. The target suits the +// device (twice its buffer, at least 30 ms) and grows a little each time the +// queue runs dry, up to 80 ms. When the queue is far too long (the device +// stalled, as while the system switches to another one), new samples are +// dropped until it is back at the target, rather than playing late. #pragma once #include @@ -45,16 +49,23 @@ class HostOutput { // dropped), and its length in milliseconds. u64 underruns() const { return underruns_.load(); } u64 overflows() const { return overflows_.load(); } + u64 resyncs() const { return resyncs_.load(); } double queue_ms() const { return queue_ms_.load(); } + double target_ms() const { return target_ms_.load(); } private: SDL_AudioStream* stream_ = nullptr; std::string device_name_; u32 rate_ = 0; double queued_avg_ms_ = 0; + double device_ms_ = 0; // the queue the device itself needs: twice its buffer + double underrun_ms_ = 0; // added to the target by underruns + u32 pushes_ = 0; // since the device's buffer was last looked at bool started_ = false; - std::atomic underruns_{0}, overflows_{0}; - std::atomic queue_ms_{0}; + bool resyncing_ = false; // dropping samples until the queue is back at the target + std::atomic underruns_{0}, overflows_{0}, resyncs_{0}; + std::atomic queue_ms_{0}, target_ms_{30}; + void update_target(); }; } // namespace audio diff --git a/runtime/camera/exposure.h b/runtime/camera/exposure.h new file mode 100644 index 0000000..93e3481 --- /dev/null +++ b/runtime/camera/exposure.h @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// +// A webcam's brightness, for the player's photo. +// +// Warmup: a webcam's first frames after it is switched on are dark or +// flickering while its automatic exposure settles (a fraction of a second to +// a second or two). Warmup says when the frames can be shown: once their +// brightness has stayed steady for a few frames, or after kMaxWait whatever +// it does, counted from the first frame (opening a webcam can itself take a +// while). Until then the camera sends a grey picture, as before the first +// frame, so a warm-up frame never becomes a player's photo. +// +// AutoGain: the cabinet's camera had its own light; a webcam in a dim room +// gives an almost black picture. AutoGain brightens a dark picture towards a +// normal brightness, at most kMaxGain times, changing gradually from frame to +// frame so that the picture does not flicker. A picture that is bright enough +// is left as it is. +#pragma once + +#include +#include +#include +#include + +#include "gekko/types.h" + +namespace camera { + +// The mean brightness (0-255) of an RGB24 picture, from a sample of its pixels. +inline double mean_brightness(const gekko::u8* rgb, std::size_t pixels) { + if (pixels == 0) return 0.0; + const std::size_t step = pixels > 4096 ? pixels / 4096 : 1; + double sum = 0.0; + std::size_t n = 0; + for (std::size_t i = 0; i < pixels; i += step, ++n) { + const gekko::u8* p = rgb + i * 3; + sum += 0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]; + } + return sum / static_cast(n); +} + +class Warmup { + public: + using Clock = std::chrono::steady_clock; + static constexpr auto kMinWait = std::chrono::milliseconds(250); + static constexpr auto kMaxWait = std::chrono::seconds(2); + static constexpr int kSteadyFrames = 3; // in a row + static constexpr double kSteadyChange = 3; // most a frame's mean brightness (0-255) may change + + // The webcam has just been switched on. + void start() { + first_ = true; + settled_ = false; + steady_ = 0; + last_mean_ = -1.0; + } + + // A frame came, with this mean brightness (0-255). True if it may be shown + // (and every one after it, until start() again). + bool frame(double mean, Clock::time_point now) { + if (settled_) return true; + if (first_) { + first_ = false; + first_frame_ = now; + } + const auto age = now - first_frame_; + if (last_mean_ >= 0.0 && std::fabs(mean - last_mean_) <= kSteadyChange) ++steady_; + else steady_ = 0; + last_mean_ = mean; + settled_ = (age >= kMinWait && steady_ >= kSteadyFrames) || age >= kMaxWait; + return settled_; + } + + private: + Clock::time_point first_frame_{}; + bool first_ = true; + bool settled_ = false; + int steady_ = 0; + double last_mean_ = -1.0; +}; + +class AutoGain { + public: + static constexpr double kTarget = 100; // the mean brightness (0-255) to bring a dark picture up to + static constexpr double kMaxGain = 6; + static constexpr double kSmoothing = 0.15; // how much of the way to the new gain each frame goes + + void reset() { gain_ = -1.0; } + + // Brightens an RGB24 picture of `pixels` pixels in place, given its mean + // brightness. Returns the gain used. + double apply(gekko::u8* rgb, std::size_t pixels, double mean) { + const double wanted = std::clamp(kTarget / std::max(mean, 1.0), 1.0, kMaxGain); + gain_ = gain_ < 0.0 ? wanted : gain_ + (wanted - gain_) * kSmoothing; + if (gain_ <= 1.01) return 1.0; + const auto g = static_cast(std::lround(gain_ * 256.0)); + for (std::size_t i = 0; i < pixels * 3; ++i) rgb[i] = static_cast(std::min(rgb[i] * g >> 8, 255)); + return gain_; + } + + private: + double gain_ = -1.0; +}; + +} // namespace camera diff --git a/runtime/camera/webcam.cpp b/runtime/camera/webcam.cpp index bb0b0be..00d9c9d 100644 --- a/runtime/camera/webcam.cpp +++ b/runtime/camera/webcam.cpp @@ -10,6 +10,8 @@ #include #include +#include "camera/exposure.h" + #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN @@ -132,6 +134,12 @@ bool Webcam::choose(const std::string& name, std::string* error) { bool Webcam::picture(u8* rgb) { std::lock_guard lock(mutex_); + // The game's start-up check asks for one picture, and a grey one does: + // the webcam stays off until the game asks again (a photo, the test menu). + if (!asked_before_) { + asked_before_ = true; + return false; + } asked_ = std::chrono::steady_clock::now(); if (!on_) { on_ = true; @@ -169,6 +177,9 @@ void Webcam::run() { } SDL_Camera* camera = denied ? nullptr : open(); bool first = true; + Warmup warmup; + warmup.start(); + AutoGain gain; for (;;) { { std::lock_guard lock(mutex_); @@ -198,6 +209,11 @@ void Webcam::run() { if (!converted) continue; crop_and_scale(converted, picture.data()); SDL_DestroySurface(converted); + // Not while its exposure settles, and brightened in a dim room + // (exposure.h). + const double mean = mean_brightness(picture.data(), kPictureSize / 3); + if (!warmup.frame(mean, Warmup::Clock::now())) continue; + gain.apply(picture.data(), kPictureSize / 3, mean); { std::lock_guard lock(mutex_); latest_ = picture; diff --git a/runtime/camera/webcam.h b/runtime/camera/webcam.h index 4a21dfe..1a3c0b6 100644 --- a/runtime/camera/webcam.h +++ b/runtime/camera/webcam.h @@ -1,12 +1,14 @@ // SPDX-License-Identifier: GPL-3.0-or-later // // A webcam as the camera's picture source, through SDL3's camera API. The -// webcam is on only while the game asks for pictures (its start-up check, the -// player's photo, the test menu's camera page): the first request turns it on, -// and it goes off a few seconds after the last. While it is on, a thread takes -// its frames as they come and keeps the newest, cropped to 4:3 around its -// centre and scaled down to 320x240. Until its first frame comes (a fraction -// of a second) there is no picture, and the camera sends a grey one. +// webcam is on only while the game asks for pictures (the player's photo, the +// test menu's camera page): a request turns it on, and it goes off a few +// seconds after the last. The game's start-up check asks once, and gets a grey +// picture without the webcam. While it is on, a thread takes its frames as +// they come and keeps the newest, cropped to 4:3 around its centre and scaled +// down to 320x240, brightened if the room is dim. Until its exposure has +// settled (exposure.h; a fraction of a second to two seconds) there is no +// picture, and the camera sends a grey one. // // Some systems ask the player first (macOS): until they allow it, and if they // don't, there are no pictures. @@ -57,6 +59,7 @@ class Webcam final : public Source { bool on_ = false; std::chrono::steady_clock::time_point asked_; // the game's latest request std::vector latest_; // kPictureSize bytes once there is a picture + bool asked_before_ = false; // the game has asked for a picture this run }; } // namespace camera diff --git a/runtime/hw/dsp.cpp b/runtime/hw/dsp.cpp index 8bcd1a6..2593b16 100644 --- a/runtime/hw/dsp.cpp +++ b/runtime/hw/dsp.cpp @@ -10,6 +10,7 @@ #include "dsp/ax.h" #include "hw/ai.h" +#include "os/verbose.h" namespace hw { @@ -69,7 +70,7 @@ class TaskUcode : public DspUcode { using DspUcode::DspUcode; void initialize() override { dsp_.push_mail(DSP_INIT, true); } void handle_mail(u32 mail) override { - if (logged_ < 32) { + if (logged_ < 32 && os::verbose()) { std::fprintf(stderr, "[dsp] ucode %08X: mail %08X (not emulated)\n", crc(), mail); ++logged_; } @@ -144,7 +145,8 @@ void DspDevice::boot_ucode(u32 ram_address, u32 length, u32 imem_address, u32 dm const u8* code = hw_.ram(ram_address, length); const u32 crc = code ? hash_ector(code, length) : 0; auto ucode = make_ucode(crc); - std::fprintf(stderr, "[dsp] booting ucode: crc %08X (%s), %u bytes from %08X (imem %04X, dmem %u, pc %04X)\n", + if (os::verbose()) + std::fprintf(stderr, "[dsp] booting ucode: crc %08X (%s), %u bytes from %08X (imem %04X, dmem %u, pc %04X)\n", crc, ucode->name(), length, ram_address, imem_address, dmem_length, start_pc); set_ucode(std::move(ucode)); } @@ -162,7 +164,7 @@ void DspDevice::swap_ucode(u32 crc) { } if (!last_ucode_) last_ucode_ = std::move(retired_ucode_); ucode_ = make_ucode(crc); - std::fprintf(stderr, "[dsp] switching to ucode %08X (%s)\n", crc, ucode_->name()); + if (os::verbose()) std::fprintf(stderr, "[dsp] switching to ucode %08X (%s)\n", crc, ucode_->name()); ucode_->initialize(); } diff --git a/runtime/hw/hardware.cpp b/runtime/hw/hardware.cpp index 33a10a9..0871cc5 100644 --- a/runtime/hw/hardware.cpp +++ b/runtime/hw/hardware.cpp @@ -7,10 +7,12 @@ #include #include +#include #include #include #include "os/thread_priority.h" +#include "os/verbose.h" #include "ppc/hooks.h" #include "ppc/memory.h" #include "ppc/trace.h" @@ -112,7 +114,7 @@ class PiDevice : public Device { // ---- RegisterFile ---------------------------------------------------------------------------- void RegisterFile::log(const char* kind, u32 offset, u32 value, u32 size) { - if (logged_ >= log_limit_) return; + if (logged_ >= log_limit_ || !os::verbose()) return; ++logged_; // With call tracing enabled, name the guest function making the access. char caller[32] = ""; @@ -169,9 +171,66 @@ u8* Hardware::ram(u32 addr, u32 size) const { return base_ + (ppc::MEM1_CACHED | phys); } -u64 Hardware::host_ticks() const { +namespace { + +u64 steady_now_ns() { const auto now = std::chrono::steady_clock::now().time_since_epoch(); - return ns_to_ticks(static_cast(std::chrono::duration_cast(now).count())); + return static_cast(std::chrono::duration_cast(now).count()); +} + +} // namespace + +Hardware::ClockMap Hardware::clock() const { + for (;;) { + const u32 seq = clock_seq_.load(std::memory_order_acquire); + if (seq & 1) continue; + ClockMap c; + c.anchor_ns = clock_anchor_ns_.load(std::memory_order_relaxed); + c.anchor_ticks = clock_anchor_ticks_.load(std::memory_order_relaxed); + c.rate = clock_rate_.load(std::memory_order_relaxed); + std::atomic_thread_fence(std::memory_order_acquire); + if (clock_seq_.load(std::memory_order_relaxed) == seq) return c; + } +} + +u64 Hardware::ticks_at(u64 steady_ns) const { + const ClockMap c = clock(); + if (c.rate == 1.0) return ns_to_ticks(steady_ns) - ns_to_ticks(c.anchor_ns) + c.anchor_ticks; + if (steady_ns >= c.anchor_ns) + return c.anchor_ticks + ns_to_ticks(static_cast(std::llround(static_cast(steady_ns - c.anchor_ns) * c.rate))); + return c.anchor_ticks - ns_to_ticks(static_cast(std::llround(static_cast(c.anchor_ns - steady_ns) * c.rate))); +} + +u64 Hardware::ns_at_ticks(u64 ticks) const { + const ClockMap c = clock(); + u64 ns; + if (c.rate == 1.0) { + ns = ppc::ticks_to_ns_up(ticks - c.anchor_ticks + ns_to_ticks(c.anchor_ns)); + } else if (ticks >= c.anchor_ticks) { + ns = c.anchor_ns + static_cast(std::ceil(static_cast(ppc::ticks_to_ns_up(ticks - c.anchor_ticks)) / c.rate)); + } else { + ns = c.anchor_ns - static_cast(static_cast(ppc::ticks_to_ns(c.anchor_ticks - ticks)) / c.rate); + } + // Rounding: the first nanosecond whose ticks reach `ticks`. + while (ticks_at(ns) < ticks) ++ns; + while (ns > 0 && ticks_at(ns - 1) >= ticks) --ns; + return ns; +} + +u64 Hardware::host_ticks() const { return ticks_at(steady_now_ns()); } + +void Hardware::set_clock_rate(double rate) { + if (!(rate > 0.9 && rate < 1.1)) rate = 1.0; + std::lock_guard lock(mutex_); + const u64 now = steady_now_ns(); + const u64 ticks = ticks_at(now); + clock_seq_.fetch_add(1, std::memory_order_relaxed); + std::atomic_thread_fence(std::memory_order_release); + clock_anchor_ns_.store(now, std::memory_order_relaxed); + clock_anchor_ticks_.store(ticks, std::memory_order_relaxed); + clock_rate_.store(rate, std::memory_order_relaxed); + clock_seq_.fetch_add(1, std::memory_order_release); + wake_timer(); // timed events are due at other host times now } u64 Hardware::clock_ticks() const { @@ -181,11 +240,11 @@ u64 Hardware::clock_ticks() const { u64 Hardware::timebase() const { return clock_ticks() - tb_origin_; } -u64 Hardware::timebase_at(u64 steady_ns) const { return ns_to_ticks(steady_ns) - tb_origin_; } +u64 Hardware::timebase_at(u64 steady_ns) const { return ticks_at(steady_ns) - tb_origin_; } // Rounded up, so that timebase_at(steady_ns_at(tb)) == tb. u64 Hardware::steady_ns_at(u64 timebase) const { - return ppc::ticks_to_ns_up(timebase + tb_origin_); + return ns_at_ticks(timebase + tb_origin_); } void Hardware::set_timebase(u64 value) { @@ -386,7 +445,7 @@ u32 Hardware::mmio_read(u32 addr, u32 size) { const u32 off = addr - kIoBase; for (const Mapping& m : mappings_) if (off >= m.base && off < m.base + m.size) return m.device->read(off - m.base, size); - std::fprintf(stderr, "[hw] unmapped read%u %08X\n", size * 8, addr); + if (os::verbose()) std::fprintf(stderr, "[hw] unmapped read%u %08X\n", size * 8, addr); return 0; } @@ -403,7 +462,7 @@ void Hardware::mmio_write(u32 addr, u32 value, u32 size) { return; } } - std::fprintf(stderr, "[hw] unmapped write%u %08X = %08X\n", size * 8, addr, value); + if (os::verbose()) std::fprintf(stderr, "[hw] unmapped write%u %08X = %08X\n", size * 8, addr, value); } // The gather pipe is only ever written by the thread running guest code, and diff --git a/runtime/hw/hardware.h b/runtime/hw/hardware.h index a7a5432..12b2b70 100644 --- a/runtime/hw/hardware.h +++ b/runtime/hw/hardware.h @@ -117,6 +117,13 @@ class Hardware { u64 steady_ns_at(u64 timebase) const; u32 decrementer() const; void set_decrementer(u32 value); + // How fast the machine's clock runs against the host's: 1 is real time. + // The launcher sets it a little above 1 (0.1%) so that the game's 59.94 Hz + // retraces line up with a 60 Hz display's refreshes (a display frame would + // otherwise be shown twice every 16.7 seconds). The time base carries on + // from where it is: no jump. Thread-safe. + void set_clock_rate(double rate); + double clock_rate() const { return clock_rate_.load(std::memory_order_relaxed); } // --- Pause -------------------------------------------------------------------------- // Freezes the machine: the time base and decrementer stop, timed events @@ -156,6 +163,9 @@ class Hardware { void timer_loop(); u64 host_ticks() const; u64 clock_ticks() const; // host_ticks(), or when it stopped while paused + // The machine's clock in host ticks at a time of the steady clock, and back. + u64 ticks_at(u64 steady_ns) const; + u64 ns_at_ticks(u64 ticks) const; // the first nanosecond at or after u8* base_; u32 mem1_size_; @@ -178,6 +188,17 @@ class Hardware { // Time base: tb = host_ticks - tb_origin_ (+ guest adjustments, and time // spent paused) u64 tb_origin_ = 0; + // The clock's rate: from the steady clock's anchor_ns on, it runs at + // `rate`, starting from anchor_ticks. Read without a lock. + struct ClockMap { + u64 anchor_ns = 0; + u64 anchor_ticks = 0; + double rate = 1.0; + }; + ClockMap clock() const; + std::atomic clock_seq_{0}; // odd while set_clock_rate() changes the three below + std::atomic clock_anchor_ns_{0}, clock_anchor_ticks_{0}; + std::atomic clock_rate_{1.0}; std::atomic paused_at_{0}; // host ticks when paused; 0 when running std::condition_variable_any pause_cv_; // Decrementer: value `dec_value_` written at time base `dec_written_`. diff --git a/runtime/input/host.cpp b/runtime/input/host.cpp index 9c3fa20..d256eea 100644 --- a/runtime/input/host.cpp +++ b/runtime/input/host.cpp @@ -14,6 +14,7 @@ #include #include +#include "input/menu_chord.h" #include "os/atomic_file.h" #ifdef _WIN32 @@ -408,6 +409,9 @@ float apply_deadzone(float v, float deadzone) { } // namespace +// A capture's baseline for an axis that hasn't reported yet (outside -32768..32767). +constexpr int kUnknownAxis = 1 << 20; + struct HostInput::Impl { struct Device { SDL_Gamepad* gamepad = nullptr; @@ -422,6 +426,7 @@ struct HostInput::Impl { Config config; std::string path; + MenuChord menu_chord; bool dirty = false; // bindings changed since load() or save() bool keep_file = false; // the file could not be read nor set aside: never overwritten @@ -437,7 +442,7 @@ struct HostInput::Impl { bool active = false; DeviceKind kind = DeviceKind::Keyboard; std::size_t control = 0; - std::map> axes; // where each axis was at the start + std::map> axes; // where each axis was at the start, or kUnknownAxis } capture; float digital_steer = 0.0f; // -1..1, keys and buttons turn it gradually bool pause_held = false; // the pause control's buttons and axes, at the last poll @@ -497,8 +502,17 @@ struct HostInput::Impl { if (s.invert) v = -v; return apply_deadzone(v, deadzone); } + // Whether a joystick axis has reported where it is. Until a device sends + // its first report SDL reads every axis as 0, the middle: a pedal that + // rests at one end would read half pressed until it was first moved. + static bool reported(const Source& s, const Device* d) { + if (s.kind != Source::Kind::JoyAxis || !d || !d->joystick) return true; + Sint16 initial = 0; + return SDL_GetJoystickAxisInitialState(d->joystick, s.index, &initial); + } // As a pedal or button: 0..1. static float amount(const Source& s, const Device* d, float deadzone) { + if (!reported(s, d)) return 0.0f; // at rest, wherever that is float v = raw(s, d); if (!is_axis(s)) return v; if (s.invert) v = -v; @@ -746,9 +760,9 @@ triforce::Controls HostInput::poll() { const float steer = std::clamp(steer_axis + m.digital_steer, -1.0f, 1.0f); triforce::Controls c; - c.steering = static_cast(std::lround(128.0f + steer * 127.0f)); - c.gas = static_cast(std::lround(amount[kGas] * 255.0f)); - c.brake = static_cast(std::lround(amount[kBrake] * 255.0f)); + c.steering = steer; + c.gas = amount[kGas]; + c.brake = amount[kBrake]; c.item = amount[kItem] > 0.5f; c.cancel = amount[kCancel] > 0.5f; c.start = amount[kStart] > 0.5f; @@ -756,6 +770,18 @@ triforce::Controls HostInput::poll() { c.test = amount[kTest] > 0.5f; c.service = amount[kService] > 0.5f; + // Back + Start opens the menu (see menu_chord.h): the first of the two is + // held back from the game for a moment. + bool half = false, both = false; + for (const auto& [id, d] : m.devices) { + if (!d.gamepad) continue; + const bool back = SDL_GetGamepadButton(d.gamepad, SDL_GAMEPAD_BUTTON_BACK); + const bool start = SDL_GetGamepadButton(d.gamepad, SDL_GAMEPAD_BUTTON_START); + both |= back && start; + half |= back != start; + } + m.menu_chord.filter(half, both, now, &c); + const bool pause = amount[kPause] > 0.5f; if (pause && !m.pause_held) m.pause_pressed = true; m.pause_held = pause; @@ -785,6 +811,24 @@ std::vector HostInput::bindings(DeviceKind kind, std::size_t contro return names; } +std::vector HostInput::binding_labels(DeviceKind kind, std::size_t control) const { + std::vector names; + if (control >= kControlCount) return names; + for (const Source& source : impl_->bindings(kind).sources[control]) { + std::string name; + if (source.kind == Source::Kind::Key) { + // As in key events: Latin letters on non-Latin layouts and the digits on + // a French number row (SDL_HINT_KEYCODE_OPTIONS), which is what the key + // caps of a game's controls are usually called by. + const SDL_Keycode key = SDL_GetKeyFromScancode(static_cast(source.index), SDL_KMOD_NONE, true); + if (key == SDLK_RETURN) name = "Enter"; // as most keyboards print it (SDL says Return) + else if (const char* n = SDL_GetKeyName(key)) name = n; + } + names.push_back(name.empty() ? source_name(source) : name); + } + return names; +} + void HostInput::remove_binding(DeviceKind kind, std::size_t control, std::size_t index) { if (control >= kControlCount) return; auto& sources = impl_->bindings(kind).sources[control]; @@ -801,11 +845,17 @@ void HostInput::start_capture(DeviceKind kind, std::size_t control) { m.capture.kind = kind; m.capture.control = control; for (const auto& [id, d] : m.devices) { - std::vector& axes = m.capture.axes[id]; + std::vector& axes = m.capture.axes[id]; if (d.gamepad) { for (int a = 0; a < SDL_GAMEPAD_AXIS_COUNT; ++a) axes.push_back(SDL_GetGamepadAxis(d.gamepad, static_cast(a))); } else { - for (int a = 0; a < SDL_GetNumJoystickAxes(d.joystick); ++a) axes.push_back(SDL_GetJoystickAxis(d.joystick, a)); + // An axis that hasn't reported yet reads 0 whatever its position: its + // first report sets where it rests (see capture_event). + for (int a = 0; a < SDL_GetNumJoystickAxes(d.joystick); ++a) { + Sint16 initial = 0; + axes.push_back(SDL_GetJoystickAxisInitialState(d.joystick, a, &initial) ? SDL_GetJoystickAxis(d.joystick, a) + : kUnknownAxis); + } } } } @@ -885,6 +935,11 @@ bool HostInput::capture_event(const SDL_Event& e) { } case SDL_EVENT_JOYSTICK_AXIS_MOTION: { if (kind != DeviceKind::Joystick || is_gamepad(e.jaxis.which)) return kind == DeviceKind::Joystick; + if (baseline(e.jaxis.which, e.jaxis.axis) == kUnknownAxis) { + // The axis's first report: where it rests, not a movement. + m.capture.axes[e.jaxis.which][e.jaxis.axis] = e.jaxis.value; + return true; + } const int base = baseline(e.jaxis.which, e.jaxis.axis); const int moved = e.jaxis.value - base; if (std::abs(moved) < kMoved) return true; diff --git a/runtime/input/host.h b/runtime/input/host.h index 0c29c75..f37c447 100644 --- a/runtime/input/host.h +++ b/runtime/input/host.h @@ -67,6 +67,10 @@ class HostInput { // A control's inputs on one kind of device, named as in the file. std::vector bindings(DeviceKind kind, std::size_t control) const; + // The same, named for the player: keys as the keyboard's layout prints them + // (the file keeps the key's place, so "Q" on a QWERTY keyboard shows as "A" + // on an AZERTY one). + std::vector binding_labels(DeviceKind kind, std::size_t control) const; void remove_binding(DeviceKind kind, std::size_t control, std::size_t index); // Waits for the next input of that kind (a key, a button, a hat, or an // axis moved well away from where it was) and adds it to the control. diff --git a/runtime/input/menu_chord.h b/runtime/input/menu_chord.h new file mode 100644 index 0000000..a35b6c9 --- /dev/null +++ b/runtime/input/menu_chord.h @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// +// Back + Start held together on a gamepad open the menu (for pads without a +// Guide button, or where Steam or the system takes it). By default Back is +// the coin and Start is start, and a player never presses both buttons at +// exactly the same moment, so the first one's press is held back from the +// game for a moment: if the other follows, it was the chord and the game +// never sees either; if not, the game gets the press a little late (a tap +// shorter than the wait is replayed, so none is lost). +#pragma once + +#include + +#include "triforce/io_ports.h" + +namespace input { + +class MenuChord { + public: + using Clock = std::chrono::steady_clock; + // How long the first button is held back, waiting for the second. + static constexpr auto kWait = std::chrono::milliseconds(120); + // How many polls a replayed tap lasts (one frame each). + static constexpr int kReplayPolls = 3; + + // `half`: some gamepad has one of Back and Start down; `both`: some gamepad + // has both. Changes `c`, the controls about to go to the game. + void filter(bool half, bool both, Clock::time_point now, triforce::Controls* c) { + if (both || chord_seen_) { + // The chord (the menu opens), and until the buttons are all released. + chord_seen_ = both || half; + waiting_ = false; + replay_ = 0; + c->coin = c->start = false; + return; + } + if (half) { + if (!waiting_) { + waiting_ = true; + since_ = now; + held_coin_ = held_start_ = false; + } + if (now - since_ < kWait) { + held_coin_ |= c->coin; + held_start_ |= c->start; + c->coin = c->start = false; + } + return; + } + if (waiting_ && now - since_ < kWait && (held_coin_ || held_start_)) replay_ = kReplayPolls; + waiting_ = false; + if (replay_ > 0) { + --replay_; + c->coin |= held_coin_; + c->start |= held_start_; + } + } + + private: + bool waiting_ = false, chord_seen_ = false; + Clock::time_point since_{}; + bool held_coin_ = false, held_start_ = false; + int replay_ = 0; +}; + +} // namespace input diff --git a/runtime/input/script.cpp b/runtime/input/script.cpp index 446dc7c..3c45687 100644 --- a/runtime/input/script.cpp +++ b/runtime/input/script.cpp @@ -121,9 +121,10 @@ void Script::apply(u64 frame, triforce::Controls& c) const { c.cancel |= b.cancel; c.test |= b.test; c.service |= b.service; - if (e.steering) c.steering = *e.steering; - if (e.gas) c.gas = *e.gas; - if (e.brake) c.brake = *e.brake; + // 0-255 as on the cabinet's 8-bit scale, 128 straight ahead. + if (e.steering) c.steering = std::clamp((static_cast(*e.steering) - 128.0f) / 127.0f, -1.0f, 1.0f); + if (e.gas) c.gas = static_cast(*e.gas) / 255.0f; + if (e.brake) c.brake = static_cast(*e.brake) / 255.0f; } } diff --git a/runtime/os/verbose.h b/runtime/os/verbose.h new file mode 100644 index 0000000..8f6fae6 --- /dev/null +++ b/runtime/os/verbose.h @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// +// Whether to print what is only for working on OpenGP (--verbose): the +// games' SDK messages (OSReport), the hardware's register and unhandled +// accesses, the DSP's microcode, and a status line every 5 seconds. A player's +// console shows only the start-up summary, what happens (a card, a gamepad, +// a restart) and problems. +#pragma once + +#include + +namespace os { + +inline std::atomic g_verbose{false}; + +inline bool verbose() { return g_verbose.load(std::memory_order_relaxed); } + +} // namespace os diff --git a/runtime/ppc/hooks.cpp b/runtime/ppc/hooks.cpp index 16810d9..df35563 100644 --- a/runtime/ppc/hooks.cpp +++ b/runtime/ppc/hooks.cpp @@ -7,6 +7,7 @@ #include #include +#include "os/verbose.h" #include "ppc/timebase.h" namespace ppc { @@ -21,12 +22,12 @@ u64 host_ticks() { } u32 default_mmio_read(u32 addr, u32 size) { - std::fprintf(stderr, "[ppc] unhandled MMIO read%u @ %08X\n", size * 8, addr); + if (os::verbose()) std::fprintf(stderr, "[ppc] unhandled MMIO read%u @ %08X\n", size * 8, addr); return 0; } void default_mmio_write(u32 addr, u32 value, u32 size) { - std::fprintf(stderr, "[ppc] unhandled MMIO write%u @ %08X = %08X\n", size * 8, addr, value); + if (os::verbose()) std::fprintf(stderr, "[ppc] unhandled MMIO write%u @ %08X = %08X\n", size * 8, addr, value); } void default_gather_pipe_write(const u8* bytes, u32 size) { diff --git a/runtime/triforce/io_ports.h b/runtime/triforce/io_ports.h index af9710c..f869f3e 100644 --- a/runtime/triforce/io_ports.h +++ b/runtime/triforce/io_ports.h @@ -23,8 +23,10 @@ using namespace gekko; struct Controls { bool test = false, service = false, coin = false; bool start = false, item = false, cancel = false; - u8 steering = 0x80; - u8 gas = 0, brake = 0; + // At full precision: the cabinet's analog inputs are 16-bit, and a wheel + // or pedal of 10 bits or more would lose steps at 8. + float steering = 0.0f; // -1 (full left) to 1 (full right) + float gas = 0.0f, brake = 0.0f; // 0 (released) to 1 }; using ControlsSource = std::function; diff --git a/runtime/triforce/mkgp.cpp b/runtime/triforce/mkgp.cpp index c0087e7..84c1047 100644 --- a/runtime/triforce/mkgp.cpp +++ b/runtime/triforce/mkgp.cpp @@ -6,6 +6,7 @@ #include "triforce/mkgp.h" #include +#include #include #include @@ -77,9 +78,12 @@ void MkgpIOAdapter::update(IOPorts& ports) { // its rest position to 0x4000 further. Scale the controls to exactly that, // with a little to spare, so that all of their travel is used. const auto analog = ports.analog_inputs(); - const int steer = (c.steering - 0x80) * 0x5200 / 0x7F; - analog[0] = static_cast(std::clamp(0x8000 + steer, 0, 0xFFFF)); - auto pedal = [](u8 v) { return static_cast(v ? 0x800 + v * 0x4100 / 0xFF : 0); }; + const long steer = std::lround(std::clamp(c.steering, -1.0f, 1.0f) * 0x5200); + analog[0] = static_cast(std::clamp(0x8000L + steer, 0L, 0xFFFFL)); + auto pedal = [](float v) { + v = std::clamp(v, 0.0f, 1.0f); + return static_cast(v > 0.0f ? 0x800 + std::lround(v * 0x4100) : 0); + }; analog[1] = pedal(c.gas); analog[2] = pedal(c.brake); } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 8e2b933..cb8b399 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -76,6 +76,12 @@ if(TARGET opengp_input) add_test(NAME controls COMMAND test_controls) endif() +if(TARGET opengp_audio) + add_executable(test_audio test_audio.cpp) + target_link_libraries(test_audio PRIVATE opengp_audio doctest opengp_warnings) + add_test(NAME audio COMMAND test_audio) +endif() + add_executable(test_camera test_camera.cpp) target_link_libraries(test_camera PRIVATE opengp_machine doctest opengp_warnings) add_test(NAME camera COMMAND test_camera) diff --git a/tests/test_audio.cpp b/tests/test_audio.cpp new file mode 100644 index 0000000..b5c8d87 --- /dev/null +++ b/tests/test_audio.cpp @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// +// The sound output's queue (runtime/audio/host.h), on SDL's dummy audio +// driver, which plays in real time without a sound card. + +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include + +#include + +#include +#include +#include +#include + +#include "audio/host.h" + +namespace { + +using namespace std::chrono_literals; +using Clock = std::chrono::steady_clock; + +// Pushes 5 ms bursts in real time for `duration`, as the game does. +void play(audio::HostOutput& out, std::chrono::milliseconds duration) { + constexpr gekko::u32 kRate = 32000, kFrames = kRate / 200; + const std::vector burst(kFrames * 2, 0); + const auto end = Clock::now() + duration; + auto next = Clock::now(); + while (Clock::now() < end) { + out.push(burst.data(), kFrames, kRate); + next += 5ms; + std::this_thread::sleep_until(next); + } +} + +bool open(audio::HostOutput& out) { + SDL_SetHint(SDL_HINT_AUDIO_DRIVER, "dummy"); + std::string error; + if (!out.init(0.0f, &error)) { + MESSAGE("no dummy audio driver: " << error); + return false; + } + return true; +} + +} // namespace + +TEST_CASE("after the device stalls, the sound catches up at once instead of running late") { + audio::HostOutput out; + if (!open(out)) return; + play(out, 500ms); + const double target = out.target_ms(); + CHECK(target >= 30.0); + CHECK(out.queue_ms() < target + 30.0); + + // The device stops taking samples for a while (as while the system + // switches to another device): the queue fills up. + out.set_paused(true); + play(out, 400ms); + out.set_paused(false); + // Within a second it is back near the target (the old controller, at 0.5% + // faster, took about 20 seconds). + play(out, 1000ms); + CHECK(out.resyncs() >= 1); + CHECK(out.queue_ms() < target + 30.0); +} diff --git a/tests/test_camera.cpp b/tests/test_camera.cpp index 1889937..8bd30dd 100644 --- a/tests/test_camera.cpp +++ b/tests/test_camera.cpp @@ -6,7 +6,9 @@ #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include +#include #include +#include #include #include #include @@ -15,6 +17,7 @@ #include "camera/jpeg.h" #include "camera/namcam.h" +#include "camera/exposure.h" #include "triforce/network.h" using namespace gekko; @@ -212,3 +215,61 @@ TEST_CASE("InetAddr answers in network byte order") { CHECK(bytes[2] == 29); CHECK(bytes[3] == 104); } + +// ---- A webcam's warm-up and brightness ---- + +TEST_CASE("a webcam's frames show once their brightness is steady") { + using namespace std::chrono_literals; + camera::Warmup w; + w.start(); + const auto t0 = camera::Warmup::Clock::now(); // the first frame + // Bright, then dark while the exposure adjusts: not yet. + CHECK_FALSE(w.frame(34, t0)); + CHECK_FALSE(w.frame(7, t0 + 33ms)); + CHECK_FALSE(w.frame(40, t0 + 66ms)); + CHECK_FALSE(w.frame(90, t0 + 100ms)); + // Steady, but too soon after the first frame. + CHECK_FALSE(w.frame(91, t0 + 133ms)); + CHECK_FALSE(w.frame(92, t0 + 166ms)); + CHECK_FALSE(w.frame(91, t0 + 200ms)); + CHECK_FALSE(w.frame(92, t0 + 233ms)); + // Steady and old enough. + CHECK(w.frame(91, t0 + 266ms)); + CHECK(w.frame(10, t0 + 300ms)); // and from then on, whatever the picture +} + +TEST_CASE("a webcam that never settles shows two seconds after its first frame") { + using namespace std::chrono_literals; + camera::Warmup w; + w.start(); + const auto t0 = camera::Warmup::Clock::now() + 5s; // opening it took a while + CHECK_FALSE(w.frame(10, t0)); + CHECK_FALSE(w.frame(60, t0 + 1500ms)); + CHECK(w.frame(110, t0 + 2s)); +} + +TEST_CASE("mean brightness") { + std::vector rgb(320 * 240 * 3, 200); + CHECK(camera::mean_brightness(rgb.data(), 320 * 240) == doctest::Approx(200.0)); + std::fill(rgb.begin(), rgb.end(), u8{0}); + CHECK(camera::mean_brightness(rgb.data(), 320 * 240) == doctest::Approx(0.0)); +} + +TEST_CASE("a dim picture is brightened, gradually, and a bright one is left alone") { + constexpr std::size_t kPixels = 320 * 240; + camera::AutoGain gain; + std::vector rgb(kPixels * 3, 20); + // The first frame takes the gain it needs at once: 100 / 20 = 5. + CHECK(gain.apply(rgb.data(), kPixels, 20) == doctest::Approx(5.0)); + CHECK(rgb[0] == 100); + // Very dark: at most 6 times, approached gradually. + std::fill(rgb.begin(), rgb.end(), u8{2}); + const double g = gain.apply(rgb.data(), kPixels, 2); + CHECK(g > 5.0); + CHECK(g < 6.0); + // Bright enough: unchanged once the gain has come down. + camera::AutoGain fresh; + std::fill(rgb.begin(), rgb.end(), u8{150}); + CHECK(fresh.apply(rgb.data(), kPixels, 150) == doctest::Approx(1.0)); + CHECK(rgb[0] == 150); +} diff --git a/tests/test_controls.cpp b/tests/test_controls.cpp index 13fee4f..b34f6ac 100644 --- a/tests/test_controls.cpp +++ b/tests/test_controls.cpp @@ -140,3 +140,77 @@ TEST_CASE("a bad entry costs only itself, and a broken file is kept aside") { CHECK(fs::exists(fs::path(broken.string() + ".bad"))); CHECK(again.bindings(Kind::Keyboard, control("gas")) == Names{"Up", "W"}); } + +// ---- Pedals (an SDL virtual joystick) ---- + +namespace { + +// A virtual joystick with three axes and no buttons (a set of pedals). +struct VirtualPedals { + SDL_JoystickID id = 0; + SDL_Joystick* joystick = nullptr; + VirtualPedals() { + SDL_VirtualJoystickDesc desc; + SDL_INIT_INTERFACE(&desc); + desc.type = SDL_JOYSTICK_TYPE_UNKNOWN; + desc.naxes = 3; + desc.name = "OpenGP test pedals"; + id = SDL_AttachVirtualJoystick(&desc); + if (id) joystick = SDL_OpenJoystick(id); + } + ~VirtualPedals() { + if (joystick) SDL_CloseJoystick(joystick); + if (id) SDL_DetachVirtualJoystick(id); + } + void set(int axis, Sint16 value) { SDL_SetJoystickVirtualAxis(joystick, axis, value); } +}; + +void pump(HostInput& in) { + SDL_UpdateJoysticks(); + SDL_Event e; + while (SDL_PollEvent(&e)) { + if (in.capturing() && in.capture_event(e)) continue; + in.handle_event(e); + } +} + +} // namespace + +TEST_CASE("a pedal reads released until it reports, and binds the right way round") { + const fs::path path = temp_file("pedals.toml"); + std::ofstream(path) << "[keyboard]\ngas = []\nbrake = []\n[joystick]\ngas = [\"-axis2\"]\n"; + HostInput in; + std::string error; + REQUIRE_MESSAGE(in.load(path.string(), &error), error); + if (!in.init(&error)) { + MESSAGE("no joystick support here: " << error); + return; + } + VirtualPedals pedals; + REQUIRE(pedals.joystick); + pump(in); + // No report yet: SDL reads 0, half way, but the pedal is released. + CHECK(in.poll().gas == 0.0f); + // Released, resting at the top ("-axis2"), then pressed all the way. + pedals.set(2, 32767); + pump(in); + CHECK(in.poll().gas == doctest::Approx(0.0f)); + pedals.set(2, -32768); + pump(in); + CHECK(in.poll().gas == doctest::Approx(1.0f)); + + // Binding the brake from the menu, on pedals that haven't reported yet: + // axis 1 rests at the top. Its first report sets where it rests; pressing + // it then binds the whole axis, turned around. + VirtualPedals fresh; + REQUIRE(fresh.joystick); + pump(in); + in.start_capture(Kind::Joystick, control("brake")); + fresh.set(1, 32767); + pump(in); + CHECK(in.capturing()); // a first report is not a press + fresh.set(1, -32768); + pump(in); + CHECK_FALSE(in.capturing()); + CHECK(in.bindings(Kind::Joystick, control("brake")) == Names{"-axis1"}); +} diff --git a/tests/test_input.cpp b/tests/test_input.cpp index 40cbdc4..95d5a9b 100644 --- a/tests/test_input.cpp +++ b/tests/test_input.cpp @@ -5,6 +5,9 @@ #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include +#include + +#include "input/menu_chord.h" #include "input/script.h" using input::Script; @@ -18,6 +21,10 @@ Controls at(const Script& s, gekko::u64 frame) { return c; } +// The analog controls on the scripts' 0-255 scale. +int steer(const Controls& c) { return static_cast(std::lround(128.0f + c.steering * 127.0f)); } +int pedal(float v) { return static_cast(std::lround(v * 255.0f)); } + } // namespace TEST_CASE("buttons are held for the default duration") { @@ -37,23 +44,24 @@ TEST_CASE("ranges, relative times and analog values") { REQUIRE(s.parse("100 start; +50 item\n+0-20 gas=255 steer=0x10, brake=7 # comment\n1000-2000 steer=200", &error)); CHECK(at(s, 100).start); CHECK(at(s, 150).item); - CHECK(at(s, 150).gas == 255); - CHECK(at(s, 169).steering == 0x10); - CHECK(at(s, 169).brake == 7); - CHECK(at(s, 170).gas == 0); - CHECK(at(s, 170).steering == 0x80); - CHECK(at(s, 1999).steering == 200); - CHECK(at(s, 2000).steering == 0x80); + CHECK(pedal(at(s, 150).gas) == 255); + CHECK(steer(at(s, 169)) == 0x10); + CHECK(pedal(at(s, 169).brake) == 7); + CHECK(pedal(at(s, 170).gas) == 0); + CHECK(steer(at(s, 170)) == 0x80); + CHECK(steer(at(s, 1999)) == 200); + CHECK(steer(at(s, 2000)) == 0x80); + CHECK(at(s, 170).steering == 0.0f); // straight ahead exactly } TEST_CASE("later events win for analog values; buttons combine") { Script s; std::string error; REQUIRE(s.parse("0-100 gas=10 item; 50-60 gas=20 start", &error)); - CHECK(at(s, 55).gas == 20); + CHECK(pedal(at(s, 55).gas) == 20); CHECK(at(s, 55).item); CHECK(at(s, 55).start); - CHECK(at(s, 70).gas == 10); + CHECK(pedal(at(s, 70).gas) == 10); } TEST_CASE("the player's controls show through") { @@ -61,12 +69,12 @@ TEST_CASE("the player's controls show through") { std::string error; REQUIRE(s.parse("10 coin", &error)); Controls c; - c.gas = 99; + c.gas = 0.5f; c.item = true; s.apply(10, c); CHECK(c.coin); CHECK(c.item); - CHECK(c.gas == 99); + CHECK(c.gas == 0.5f); } TEST_CASE("errors leave the script unchanged") { @@ -82,3 +90,64 @@ TEST_CASE("errors leave the script unchanged") { CHECK_FALSE(at(s, 20).start); CHECK(s.end() == 10 + Script::kDefaultDuration); } + +// ---- Back + Start opens the menu ---- + +namespace { + +using input::MenuChord; +using namespace std::chrono_literals; + +struct ChordRun { + MenuChord chord; + MenuChord::Clock::time_point now{}; + Controls poll(bool back, bool start, bool coin, bool start_control) { + Controls c; + c.coin = coin; + c.start = start_control; + chord.filter(back != start, back && start, now, &c); + now += 16ms; + return c; + } +}; + +} // namespace + +TEST_CASE("Back then Start opens the menu without a coin") { + ChordRun r; + CHECK_FALSE(r.poll(true, false, true, false).coin); // Back: the coin is held back + CHECK_FALSE(r.poll(true, false, true, false).coin); + const Controls both = r.poll(true, true, true, true); // the chord + CHECK_FALSE(both.coin); + CHECK_FALSE(both.start); + CHECK_FALSE(r.poll(false, true, false, true).start); // still nothing until all released + CHECK_FALSE(r.poll(false, false, false, false).coin); + CHECK_FALSE(r.poll(false, false, false, false).coin); // no replay of the held-back coin +} + +TEST_CASE("a quick tap of Back still inserts a coin") { + ChordRun r; + CHECK_FALSE(r.poll(true, false, true, false).coin); + CHECK(r.poll(false, false, false, false).coin); // replayed + CHECK(r.poll(false, false, false, false).coin); + CHECK(r.poll(false, false, false, false).coin); + CHECK_FALSE(r.poll(false, false, false, false).coin); +} + +TEST_CASE("holding Back alone reaches the game after the wait") { + ChordRun r; + bool seen = false; + for (int i = 0; i < 12; ++i) seen |= r.poll(true, false, true, false).coin; + CHECK(seen); + CHECK(r.poll(true, false, true, false).coin); // and stays down while held +} + +TEST_CASE("other controls are never held back") { + ChordRun r; + Controls c; + c.item = true; + c.gas = 0.8f; + r.chord.filter(true, false, r.now, &c); + CHECK(c.item); + CHECK(c.gas == 0.8f); +} diff --git a/tests/test_pause.cpp b/tests/test_pause.cpp index 8229ba9..bdbaba9 100644 --- a/tests/test_pause.cpp +++ b/tests/test_pause.cpp @@ -143,3 +143,45 @@ TEST_CASE("the time base can be set while paused") { h.set_paused(false); CHECK(h.timebase() - 12345 < ms_ticks(25)); } + +// ---- The clock's rate (matching a 60 Hz display) ---- + +TEST_CASE("a faster clock carries on from where it was, at its new rate") { + Rig r; + const u64 before = r.hw->timebase(); + r.hw->set_clock_rate(1.001001); + const u64 after = r.hw->timebase(); + CHECK(after >= before); + CHECK(after - before < ms_ticks(5)); // no jump + + // Over half a second of the host's clock, the time base runs 0.1% faster. + const auto t0 = std::chrono::steady_clock::now(); + const u64 tb0 = r.hw->timebase(); + std::this_thread::sleep_for(500ms); + const u64 tb1 = r.hw->timebase(); + const double host_s = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + const double ratio = static_cast(tb1 - tb0) / (host_s * static_cast(hw::kTimebaseHz)); + CHECK(ratio == doctest::Approx(1.001001).epsilon(0.0005)); + + // Host times and time base values convert both ways. + const u64 now_ns = static_cast( + std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count()); + for (const u64 tb : {r.hw->timebase_at(now_ns), r.hw->timebase_at(now_ns) + 12345, r.hw->timebase_at(now_ns) - 999}) { + const u64 ns = r.hw->steady_ns_at(tb); + CHECK(r.hw->timebase_at(ns) == tb); + CHECK(r.hw->timebase_at(ns - 1) < tb); + } + + // Back to real time, still without a jump. + const u64 fast = r.hw->timebase(); + r.hw->set_clock_rate(1.0); + const u64 slow = r.hw->timebase(); + CHECK(slow >= fast); + CHECK(slow - fast < ms_ticks(5)); +} + +TEST_CASE("a clock rate far from real time is refused") { + Rig r; + r.hw->set_clock_rate(2.0); + CHECK(r.hw->clock_rate() == 1.0); +} diff --git a/tools/installer/CMakeLists.txt b/tools/installer/CMakeLists.txt index e51b96d..908904e 100644 --- a/tools/installer/CMakeLists.txt +++ b/tools/installer/CMakeLists.txt @@ -1,6 +1,6 @@ # The installer: builds the games on the player's machine (see installer.h). # A library, which the launcher (OpenGP-dev/opengp-launcher) uses too, and the -# command-line program, opengp-install. In a package, OpenGP is the launcher. +# command-line program, opengp-cli. In a package, OpenGP is the launcher. add_library(opengp_installer_lib STATIC installer.cpp process.cpp sha256.cpp) # Included as "installer/installer.h" (this folder's process.h must not hide # the system's ). @@ -11,4 +11,4 @@ target_link_libraries(opengp_installer_lib add_executable(opengp_installer main.cpp) target_link_libraries(opengp_installer PRIVATE opengp_installer_lib opengp_warnings) -set_target_properties(opengp_installer PROPERTIES OUTPUT_NAME opengp-install) +set_target_properties(opengp_installer PROPERTIES OUTPUT_NAME opengp-cli) diff --git a/tools/installer/ISO-README.txt b/tools/installer/ISO-README.txt index 1133b89..35fca97 100644 --- a/tools/installer/ISO-README.txt +++ b/tools/installer/ISO-README.txt @@ -6,7 +6,7 @@ add them in OpenGP from wherever they are. Either game on its own is fine. OpenGP builds each game from its image on your computer; the images are not part of OpenGP, and nothing from them leaves your -computer. On the command line, opengp-install builds them the same way. +computer. On the command line, opengp-cli builds them the same way. A compressed image (.rvz, .gcz, .wia, .ciso) must be converted to .iso first: in Dolphin, right-click the game, choose Convert File and pick ISO. See diff --git a/tools/installer/installer.h b/tools/installer/installer.h index e1829d2..41abe08 100644 --- a/tools/installer/installer.h +++ b/tools/installer/installer.h @@ -7,7 +7,7 @@ // // The package (see docs/packaging.md): // OpenGP[.exe] the launcher, which uses this library (OpenGP.app on macOS) -// opengp-install[.exe] this library's command-line program +// opengp-cli[.exe] this library's command-line program // sdk/package.toml version, compiler and linker settings // sdk/include/ the runtime's headers // sdk/lib/ the runtime, as static libraries diff --git a/tools/installer/main.cpp b/tools/installer/main.cpp index 54852c6..141035c 100644 --- a/tools/installer/main.cpp +++ b/tools/installer/main.cpp @@ -3,13 +3,13 @@ // OpenGP's installer for the command line (see installer.h): builds the games // from the player's disc images, as the launcher (the package's OpenGP) does. // -// opengp-install [IMAGE...] [--force] [--jobs N] [--cxx COMPILER] [--keep-build] +// opengp-cli [IMAGE...] [--force] [--jobs N] [--cxx COMPILER] [--keep-build] // // Without images it uses the images each game was built from before, then // those in ISO/ and private/ next to it. Each game is built on its own: a // missing image only skips that game. Games already built by this version // are skipped unless --force is given. On Windows an image can be dropped on -// opengp-install.exe. +// opengp-cli.exe. #include #include @@ -31,14 +31,14 @@ namespace { constexpr const char* kUsage = - "usage: opengp-install [IMAGE...] [--force] [--jobs N] [--cxx COMPILER]\n" + "usage: opengp-cli [IMAGE...] [--force] [--jobs N] [--cxx COMPILER]\n" " [--keep-build]\n" "\n" "Builds the games from your disc images (.iso / .gcm). Without images, it uses\n" "the ones the games were built from before, then those in ISO/ and private/.\n" "OpenGP, the launcher next to it, does the same in a window.\n"; -// When opengp-install.exe was started from Explorer (a double click, or an +// When opengp-cli.exe was started from Explorer (a double click, or an // image dropped on it), its console closes when it exits: wait for a key first. void pause_if_own_console() { #ifdef _WIN32 @@ -113,7 +113,7 @@ int run(const std::vector& args) { } if (found.empty()) { std::printf( - "\nPut your disc images in the ISO folder next to opengp-install, or drop one on it (see ISO/README.txt).\n"); + "\nPut your disc images in the ISO folder next to opengp-cli, or drop one on it (see ISO/README.txt).\n"); return 1; } diff --git a/tools/installer/process.cpp b/tools/installer/process.cpp index f7cbc9b..aa24553 100644 --- a/tools/installer/process.cpp +++ b/tools/installer/process.cpp @@ -126,7 +126,16 @@ ProcessResult run_process(const std::vector& args, const std::strin posix_spawn_file_actions_addopen(&actions, 0, "/dev/null", O_RDONLY, 0); posix_spawn_file_actions_adddup2(&actions, fds[1], 1); posix_spawn_file_actions_adddup2(&actions, fds[1], 2); + // macOS 26 deprecates the _np name for POSIX 2024's addchdir, but the + // packages run on macOS 13 and later, which have only the _np one. +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#endif if (!cwd.empty()) posix_spawn_file_actions_addchdir_np(&actions, cwd.c_str()); +#if defined(__clang__) +#pragma clang diagnostic pop +#endif std::vector argv; for (const std::string& a : args) argv.push_back(const_cast(a.c_str())); argv.push_back(nullptr);