diff --git a/CHANGELOG.md b/CHANGELOG.md index 374b36d..3415907 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,15 @@ +## 1.0.4 (12/11/2026) + +- GP 2: the brake goes back through this play's menu screens to change a class, character, kart, cup, course or round. **Brake goes back** is on by default in the Game tab and can be turned off. +- Going back skips the photo screen and stops working once the gas confirms a choice on the current screen. Menu history resets when a race starts. This feature is disabled in linked play and does not apply to GP 1. + +- Added a live Performance page and an optional overlay (F7, rebindable in Controls): frame times, drops, hitches, computer CPU usage, GPU textures, sound queue and scene information. No profile recording or stack sampling is included. + +### Known issues + +- Graphics fixes remain outstanding: reported Yoshi Park 2 Trick House flicker, widescreen HUD/banner and screen-effect distortions, and the macOS GP 2 rainbow fade. Solid-white highlights still need confirmation against the existing texture fix. +- Brake-back is GP 2 only and disabled in linked play. Return to title and Restart race are not included. + ## 1.0.3 (7/11/2026) - Fixed the periodic freezes in linked races: the cabinets now keep in step (a cabinet runs a fraction of a percent faster or slower to follow the one that leads the race), and one that falls a frame behind catches up without freezing the race diff --git a/CMakeLists.txt b/CMakeLists.txt index dfb551d..ee85079 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.25) -project(OpenGP VERSION 1.0.3 LANGUAGES C CXX) +project(OpenGP VERSION 1.0.4 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/cmake/game_sources.cmake b/cmake/game_sources.cmake index 85eab87..b155457 100644 --- a/cmake/game_sources.cmake +++ b/cmake/game_sources.cmake @@ -2,5 +2,5 @@ # game's own patches.cpp and status.cpp: one list for the source build # (games/CMakeLists.txt) and the installer package (cmake/package.cmake, which # writes it into package.toml for the installer). Names in games/common/. -set(OPENGP_GAME_COMMON_SOURCES main.cpp arcade.cpp cabinet.cpp camera_use.cpp game_log.cpp link_pace.cpp sdk_hle.cpp) +set(OPENGP_GAME_COMMON_SOURCES main.cpp arcade.cpp cabinet.cpp camera_use.cpp game_log.cpp link_pace.cpp menu_back.cpp sdk_hle.cpp) set(OPENGP_GAME_OWN_SOURCES patches.cpp status.cpp) diff --git a/docs/playing.md b/docs/playing.md index 9708c1f..a4f7aad 100644 --- a/docs/playing.md +++ b/docs/playing.md @@ -53,6 +53,9 @@ ask first. | Controls | The keys, buttons and axes for each control; steering speed, dead zones, force feedback | | Camera | The webcam (or the test pattern) the game takes your photo with | | Linked cabinets | This cabinet's number and the link over the local network | +| Performance | Live frame times, drops, CPU and GPU usage, audio queue; optional F7 overlay | + +The [performance display](profiling.md) keeps its measurements in memory and does not record a profile. The settings are the launcher's: the launcher's Settings edit the same file. The camera and the link settings take effect when the game next starts; the page says so while a change waits. @@ -247,6 +250,19 @@ it as well. Every connected device works at once. Keys and d-pad steer gradually (a keyboard cannot hold the wheel half-way); sticks and wheels steer directly. +### Going back in the menus + +On a cabinet, a choice can't be undone: once the class or the character is chosen, the game goes +on to the next screen. In OpenGP, the **brake** goes back a screen, from character select on: to +the class from the character, to the character (or the kart, with a Mario Card) from the cup or +course, to the cup from the round, to the round from the items. The photo screen is skipped on +the way back. Once you have pressed the gas on a screen, it goes on as usual. + +It doesn't work in a linked game, where the cabinets' menus keep in step, and it doesn't change the +class screen (hold the VS cancel button there for Time Attack, as on a cabinet). Turn it off with +**Brake goes back** (Game tab) or `brake_goes_back = false` in `settings.toml`. Only in Mario +Kart Arcade GP 2 for now. + ### Changing them In the menu's Settings, on the **Controls** page, choose the keyboard, gamepads or wheels and other diff --git a/docs/profiling.md b/docs/profiling.md new file mode 100644 index 0000000..e63d30d --- /dev/null +++ b/docs/profiling.md @@ -0,0 +1,22 @@ +# Performance information + +Open the in-game settings and choose **Performance** to see live frame times, +frame drops and hitches, computer CPU usage, GPU texture usage, audio queue +health and the current scene. The graph holds the last 120 active frames. + +Press **F7** to show or hide the performance overlay while playing, or use the +**Performance overlay** switch on that page. The shortcut can be rebound to a +keyboard key, gamepad button or pedal axis in **Controls > Performance** +(`profile_overlay` in `user/controls.toml`). Controllers have no default binding. +Use `--profile-overlay` to show it from startup. + +These are live measurements held in memory. This release does not include +profile recording, stack sampling, event logs, marks or profiler frame captures. +The private development profiler retains those tools. Ordinary screenshots and +crash reports are unchanged. + +Frame times are wall-clock measurements. Busy time subtracts idle and renderer +waits and is an estimate. GPU texture memory is estimated from game texture +dimensions and mip levels, not total GPU memory. Hitches and dropped retraces +exclude paused/menu intervals and the first frame after resuming. CPU use is +for the whole computer and may be unavailable on some systems. diff --git a/games/common/main.cpp b/games/common/main.cpp index dfadd9e..908642d 100644 --- a/games/common/main.cpp +++ b/games/common/main.cpp @@ -10,6 +10,7 @@ #include "cabinet.h" #include "camera_use.h" #include "game_log.h" +#include "menu_back.h" #include "status.h" #include "ppc_recomp_shared.h" @@ -28,5 +29,6 @@ int main(int argc, char** argv) { game.set_cabinet = cabinet::set; game.status = game_status::read; game.link_error = game_status::link_error; + game.set_menu_back = menu_back::set; return app::run(game, argc, argv); } diff --git a/games/common/menu_back.cpp b/games/common/menu_back.cpp new file mode 100644 index 0000000..119cfac --- /dev/null +++ b/games/common/menu_back.cpp @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "menu_back.h" + +#include +#include +#include + +#include "ppc/memory.h" + +namespace menu_back { + +namespace { + +std::mutex g_mutex; +std::function g_back, g_decide; + +// Only the game's thread runs the menus. +struct State { + gekko::u32 screen = ~0u; // the screen of the last update + std::vector stops; // this play's screens that going back returns to + bool armed = false; // the brake was up since the screen started + bool decided = false; // the gas was pressed on this screen +} g_state; + +constexpr gekko::u32 kStay = ~0u; // an update's -1 + +bool has(std::span list, gekko::u32 v) { return std::find(list.begin(), list.end(), v) != list.end(); } + +} // namespace + +void set(std::function back, std::function decide) { + std::lock_guard lock(g_mutex); + g_back = std::move(back); + g_decide = std::move(decide); +} + +void forget() { + g_state.stops.clear(); + g_state.screen = ~0u; +} + +gekko::u32 after_update(const gekko::u8* base, const Menus& menus, gekko::u32 next) { + State& s = g_state; + const gekko::u32 screen = ppc::load_be(base + menus.scene); + if (screen != s.screen) { + s.screen = screen; + s.armed = s.decided = false; + if (has(menus.starts, screen)) s.stops.clear(); + if (has(menus.stops, screen)) { + // Back to a screen already in this play (going back): forget the ones after it. + if (auto it = std::find(s.stops.begin(), s.stops.end(), screen); it != s.stops.end()) + s.stops.erase(it + 1, s.stops.end()); + else + s.stops.push_back(screen); + } + } + if (!has(menus.back, screen)) return next; + + bool back = false, decide = false; + { + std::lock_guard lock(g_mutex); + back = g_back && g_back(); + decide = g_decide && g_decide(); + } + // A screen that has been decided is on its way to the next one. + if (decide) s.decided = true; + // A brake held from the last screen doesn't go back again. + if (!back) s.armed = true; + if (next != kStay || s.decided || !s.armed || !back) return next; + + // The screen before this one (this one is the last stop, unless it isn't + // a stop itself). + const std::size_t last = s.stops.size() - (!s.stops.empty() && s.stops.back() == screen ? 1 : 0); + if (last == 0) return next; + s.armed = false; + return s.stops[last - 1]; +} + +} // namespace menu_back diff --git a/games/common/menu_back.h b/games/common/menu_back.h new file mode 100644 index 0000000..8e9e1c3 --- /dev/null +++ b/games/common/menu_back.h @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// +// Going back through the menus. On a cabinet a play can't go back: once the +// class or the character is chosen it stays chosen. OpenGP lets the brake +// pedal (the "Cancel" of the games' own name entry) go back a screen, from +// the character on: the character, the kart, the cup, the course or round, +// the items. +// +// The games' menus are one dispatcher (GP 2's MenuScene_Dispatch) that calls +// the current screen's update each frame. The update returns the next +// screen's number, or -1 to stay; the dispatcher then deletes the screen and +// makes the one with that number, which sets the scene number +// (g_currentSceneState) as it starts. Going back is the update returning the +// previous screen's number. +// +// Not in a linked game: the cabinets' menus keep in step with each other. +#pragma once + +#include +#include + +#include "gekko/types.h" +#include "ppc/context.h" + +namespace menu_back { + +// What the launcher tells the games, while they run (any thread may call). +// `back` is whether going back is wanted now (the brake pressed, the setting +// on, the game not linked); `decide` whether the gas (the games' "Decide") is. +void set(std::function back, std::function decide); + +struct Menus { + gekko::u32 scene; // g_currentSceneState + std::span starts; // the screens a play starts from (going back forgets the last play's) + std::span stops; // the screens going back returns to, in order + std::span back; // the screens that go back +}; + +// Whether a screen update that returned `next` should go back instead, and +// to where: call it after the update of each screen in `menus`. Returns the +// screen to go to, or `next`. +gekko::u32 after_update(const gekko::u8* base, const Menus& menus, gekko::u32 next); + +// A race starts: the menus after it (the next round's, after "Continue?") +// don't go back to this play's. +void forget(); + +} // namespace menu_back diff --git a/games/mkgp2/patches.cpp b/games/mkgp2/patches.cpp index ce28441..51d1409 100644 --- a/games/mkgp2/patches.cpp +++ b/games/mkgp2/patches.cpp @@ -8,6 +8,7 @@ #include "cabinet.h" #include "camera_use.h" #include "link_pace.h" +#include "menu_back.h" #include "ppc_recomp_shared.h" #include "sdk_hle.h" #include "widescreen.h" @@ -122,4 +123,38 @@ PPC_FUNC(fn_80138184) { __imp__fn_80138184(ctx, base); } +// A race starts: going back in the menus after it stays in its play. +PPC_FUNC(RaceScene_Init) { + menu_back::forget(); + __imp__RaceScene_Init(ctx, base); +} + +// Going back through the menus (menu_back.h). The screens' numbers: 0x09 the +// Mario Card, 0x0B the class, 0x0D the character, 0x0F the kart (with a +// card), 0x13 the photo, 0x15 the cup, 0x17 and 0x19 the course, 0x1B the +// round, 0x21 and 0x22 the items (with a card). +namespace { +constexpr gekko::u32 kStarts[] = {0x09}; +constexpr gekko::u32 kStops[] = {0x0B, 0x0D, 0x0F, 0x15, 0x17, 0x19, 0x1B, 0x21, 0x22}; +constexpr gekko::u32 kBack[] = {0x0D, 0x0F, 0x13, 0x15, 0x17, 0x19, 0x1B, 0x21, 0x22}; +constexpr menu_back::Menus kMenus{0x806CED74, kStarts, kStops, kBack}; +} // namespace + +#define MENU_SCREEN_UPDATE(name) \ + PPC_FUNC(name) { \ + __imp__##name(ctx, base); \ + ctx.gpr[3] = menu_back::after_update(base, kMenus, ctx.gpr[3]); \ + } +MENU_SCREEN_UPDATE(fn_801BA498) // the Mario Card +MENU_SCREEN_UPDATE(clFlowClass_Update) +MENU_SCREEN_UPDATE(clFlowChara_Update) +MENU_SCREEN_UPDATE(clFlowKart_Update) +MENU_SCREEN_UPDATE(FrameSelection_Update) // the photo +MENU_SCREEN_UPDATE(clFlowCup_Update) +MENU_SCREEN_UPDATE(clFlowCourse_Update) +MENU_SCREEN_UPDATE(clFlowRound_Update) +MENU_SCREEN_UPDATE(clFlowItem_Update) +MENU_SCREEN_UPDATE(clFlowItemSelect_Update) +#undef MENU_SCREEN_UPDATE + } // namespace guest diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 65a4c0f..46c80c7 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -52,7 +52,6 @@ add_library(opengp_machine STATIC os/crash.cpp os/notice.cpp os/printf.cpp - os/profiler.cpp os/reboot.cpp os/thread_priority.cpp os/threads.cpp @@ -167,7 +166,7 @@ target_link_libraries(opengp_app PRIVATE opengp_warnings) target_compile_definitions(opengp_app PRIVATE OPENGP_VERSION="${PROJECT_VERSION}") if(OPENGP_BUILD_VIDEO) - target_sources(opengp_app PRIVATE app/menu.cpp app/menu_theme.cpp app/menu_widgets.cpp) + target_sources(opengp_app PRIVATE app/menu.cpp app/menu_theme.cpp app/menu_widgets.cpp app/profiler.cpp) target_link_libraries(opengp_app PUBLIC opengp_video opengp_input opengp_audio opengp_webcam imgui) target_compile_definitions(opengp_app PRIVATE OPENGP_VIDEO) # The menu's typeface (thirdparty/fonts/mplus-rounded-1c), embedded. diff --git a/runtime/app/launcher.cpp b/runtime/app/launcher.cpp index 0f9be14..0d85a82 100644 --- a/runtime/app/launcher.cpp +++ b/runtime/app/launcher.cpp @@ -38,7 +38,6 @@ #include "os/crash.h" #include "os/notice.h" #include "os/printf.h" -#include "os/profiler.h" #include "os/reboot.h" #include "os/thread_priority.h" #include "os/verbose.h" @@ -51,6 +50,7 @@ #include #include "app/menu.h" +#include "app/profiler.h" #include "audio/host.h" #include "camera/webcam.h" #include "input/host.h" @@ -69,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] [--verbose] [--version]\n"; + " [--camera off|webcam|test] [--cabinet 1-4] [--lan] [--profile-overlay] [--verbose] [--version]\n"; struct Options { std::vector args; // as given, for restarts (without --reboot and --frame-offset) @@ -80,6 +80,7 @@ struct Options { std::string user_dir; // UTF-8 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 profile_overlay = false; bool game_log = false; // print the game's debug messages std::set screenshots; u64 screenshot_every = 0; @@ -125,6 +126,7 @@ int parse_options(const std::vector& args, Options& o) { else if (a == "--scale" && has_value) o.scale = static_cast(std::clamp(std::atoi(argv[++i]), 1, 8)); else if (a == "--screenshot" && has_value) o.screenshots.insert(std::strtoull(argv[++i], nullptr, 10)); else if (a == "--screenshot-every" && has_value) o.screenshot_every = std::strtoull(argv[++i], nullptr, 10); + else if (a == "--profile-overlay") o.profile_overlay = true; else if (a == "--headless") o.headless = true; else if (a == "--test-menu") o.test_menu = true; else if (a == "--no-video") o.use_video = false; @@ -650,6 +652,11 @@ int run(const Game& game, int argc, char** argv) { }); } g_network = &machine.network(); + static std::atomic brake_goes_back{settings.brake_goes_back}; + if (game.set_menu_back) { + game.set_menu_back([] { return brake_goes_back.load() && !machine.network().linked() && machine.controls().brake >= 0.5f; }, + [] { return machine.controls().gas >= 0.5f; }); + } machine.gpu().frontend().set_widescreen(widescreen_side(settings.aspect, 0, 0)); static audio::WavWriter wav; @@ -735,7 +742,6 @@ int run(const Game& game, int argc, char** argv) { auto watch_for_hangs = [&user_dir, &header] { app::start_hang_watch(machine, names, user_dir / "hang-report.txt", header); }; - os::start_profiler_from_env(); 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; @@ -865,6 +871,7 @@ int run(const Game& game, int argc, char** argv) { if (g_audio_out && settings.volume != applied.volume) g_audio_out->set_volume(static_cast(settings.volume) / 100.0f); if (game.set_free_play && settings.free_play != applied.free_play) game.set_free_play(machine.base(), settings.free_play); if (settings.card != applied.card) machine.cards().hold(settings.card); + brake_goes_back = settings.brake_goes_back; machine.gpu().frontend().set_widescreen(widescreen_side(settings.aspect, pw, ph)); renderer.set_scale(internal_scale(settings.internal_resolution, ph)); applied = settings; @@ -914,6 +921,17 @@ int run(const Game& game, int argc, char** argv) { model.camera_info = camera_info; model.webcams = [] { return camera::Webcam::names(); }; model.quit = [&quit] { quit("quit from the menu"); }; + Profiler profiler; + bool profiler_overlay = o.profile_overlay; + if (use_menu) menu.set_profiler_overlay(profiler_overlay); + model.overlay = profiler_overlay; + model.toggle_overlay = [&] { + profiler_overlay = !profiler_overlay; + model.overlay = profiler_overlay; + if (use_menu) menu.set_profiler_overlay(profiler_overlay); + }; + auto next_performance_status = std::chrono::steady_clock::now(); + GameStatus performance_status; // Even frame pacing: the retraces that say when to show each frame, and // when the last one was shown (steady clock, ns). hw::ViDevice* const vi = machine.hardware().device(); @@ -1013,6 +1031,8 @@ int run(const Game& game, int argc, char** argv) { machine.set_controls(menu.is_open() ? triforce::Controls{} : controls); // A paused game's wheel forces stop too. host_input.set_outputs(paused ? triforce::Outputs{} : machine.outputs()); + const u32 actions = host_input.take_profiler_actions(); + if (!menu.is_open() && (actions & input::HostInput::kProfilerOverlay)) model.toggle_overlay(); } settings.card = applied.card = machine.cards().held(); // the game may have given the player a new card apply_settings(); @@ -1090,7 +1110,8 @@ int run(const Game& game, int argc, char** argv) { const auto render_start = std::chrono::steady_clock::now(); os::g_main_activity.set("drawing a frame"); renderer.render(*frame, shoot ? &shot : nullptr, !paced); - g_render_ns.fetch_add(elapsed_ns(render_start)); + const u64 render_ns = elapsed_ns(render_start); + g_render_ns.fetch_add(render_ns); if (paced) { // After the last frame's retrace too: one frame a retrace. const u64 due = vi->next_retrace_ns(std::max(frame->finished_ns, shown_ns)); @@ -1100,6 +1121,34 @@ int run(const Game& game, int argc, char** argv) { if (frame->xfb) { g_rendered.fetch_add(1); last_present = std::chrono::steady_clock::now(); + if (last_present >= next_performance_status) { + next_performance_status = last_present + std::chrono::seconds(1); + if (game.status) game.status(machine.base(), &performance_status); + profiler.sample_system_cpu(); + } + Profiler::FrameInfo info; + info.finished_ns = frame->finished_ns; + info.present_ns = static_cast(std::chrono::duration_cast( + last_present.time_since_epoch()).count()); + info.retrace = vi ? vi->retrace_count() : 0; + info.idle_ns = machine.threads().idle_ns(); + const auto& counters = machine.gpu().frontend().stats(); + info.wait_ns = counters.wait_ns.load(std::memory_order_relaxed) + + counters.readback_ns.load(std::memory_order_relaxed); + info.render_ns = render_ns; + info.active = !paused && !menu.is_open(); + if (g_audio_out) { + info.audio_ms = g_audio_out->queue_ms(); + info.audio_underruns = g_audio_out->underruns(); + } + info.textures = renderer.live_textures(); + info.pipelines = renderer.live_pipelines(); + info.texture_bytes = renderer.live_texture_bytes(); + info.scene = performance_status.activity; + if (!performance_status.mode.empty()) info.scene += " · " + performance_status.mode; + info.course = performance_status.course; + profiler.on_frame(info); + model.profile = profiler.live(); } queue.give_back(std::move(frame)); if (shoot && shot.width) { diff --git a/runtime/app/launcher.h b/runtime/app/launcher.h index 85668e1..8d9a384 100644 --- a/runtime/app/launcher.h +++ b/runtime/app/launcher.h @@ -55,6 +55,9 @@ struct Game { // Whether the game has stopped because it lost its link to the other // cabinets, read from guest memory while the game runs. std::function link_error; + // Going back through the game's menus: `back` says whether the player wants + // to go back now, `decide` whether they are pressing the games' "Decide". + std::function back, std::function decide)> set_menu_back; }; // Runs the game; returns the process exit code. diff --git a/runtime/app/menu.cpp b/runtime/app/menu.cpp index c872ccf..53d2d0c 100644 --- a/runtime/app/menu.cpp +++ b/runtime/app/menu.cpp @@ -36,7 +36,7 @@ constexpr float kNoticeIn = 0.15f, kNoticeOut = 0.2f; // seconds constexpr float kFadeIn = 0.15f; // the menu's, seconds -const char* const kPageNames[] = {"Game", "Video", "Sound", "Controls", "Camera", "Linked cabinets"}; +const char* const kPageNames[] = {"Game", "Video", "Sound", "Controls", "Camera", "Linked cabinets", "Performance"}; // The keyboard keys bound to pause ("P / Pause"; with `first`, "P"), or "" // if none. @@ -51,6 +51,20 @@ std::string pause_keys(const MenuModel& m, bool first = false) { return keys; } +// The first keyboard (or else gamepad) key bound to one of the profiler's +// controls, for its page and overlay ("F7"), or "" if none. +std::string profiler_key(const MenuModel& m, const char* control) { + if (!m.input) return ""; + for (const auto kind : {input::HostInput::DeviceKind::Keyboard, input::HostInput::DeviceKind::Gamepad}) { + for (std::size_t c = input::HostInput::kProfilerFirst; c < input::HostInput::kControlCount; ++c) { + if (std::string_view(input::HostInput::control_name(c)) != control) continue; + const std::vector labels = m.input->binding_labels(kind, c); + if (!labels.empty()) return labels.front(); + } + } + return ""; +} + // 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. @@ -246,7 +260,7 @@ void Menu::notify(std::string message, NoticeKind kind) { if (notices_.size() > 4) notices_.erase(notices_.begin()); } -bool Menu::visible() const { return open_ || paused_ || !notices_.empty(); } +bool Menu::visible() const { return open_ || paused_ || overlay_ || !notices_.empty(); } void Menu::apply_scale(float scale) { theme::apply_style(ImGui::GetStyle(), scale); @@ -344,6 +358,7 @@ void Menu::update(MenuModel& m) { } else { popup_was_open_ = false; if (paused_) draw_paused(m); + if (overlay_) draw_profiler_overlay(m); } draw_notices(); ImGui::Render(); @@ -455,6 +470,7 @@ void Menu::draw_settings(MenuModel& m) { ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(px(10), px(4))); for (int i = 0; i < kPageCount; ++i) { if (i == static_cast(Page::Controls) && !m.input) continue; + if (i == static_cast(Page::Profiler) && !m.toggle_overlay) continue; if (w::nav_item(kPageNames[i], static_cast(page_) == i)) set_page(static_cast(i), m, GImGui->NavCursorVisible); } ImGui::PopStyleVar(); @@ -536,6 +552,9 @@ void Menu::draw_page(MenuModel& m) { break; case Page::Camera: page_camera(m); break; case Page::Link: page_link(m); break; + case Page::Profiler: + if (m.toggle_overlay) page_profiler(m); + break; } } @@ -585,6 +604,10 @@ void Menu::page_game(MenuModel& m) { 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("Menus"); + w::row_toggle({"Brake goes back", "Press the brake to go back a screen, to choose another class, character or course (no effect in VS races).", !m.linked}, + &s.brake_goes_back); + w::section("Discord"); const char* discord_help = s.rich_presence && !m.discord ? "Discord isn't running on this computer." : "Show what you are playing in Discord."; @@ -647,9 +670,9 @@ void Menu::page_controls(MenuModel& m) { // The cabinet's controls and what drives each. const float label_w = px(150), chip_h = px(30); - for (std::size_t control = 0; control < input::HostInput::kControlCount; ++control) { + auto binding_row = [&](std::size_t control) { // Keys cannot hold the wheel half-way: they steer with "steer left/right". - if (kind == Kind::Keyboard && input::HostInput::control_is_axis(control)) continue; + if (kind == Kind::Keyboard && input::HostInput::control_is_axis(control)) return; ImGui::PushID(static_cast(control)); const ImVec2 start = ImGui::GetCursorPos(); { @@ -694,7 +717,13 @@ void Menu::page_controls(MenuModel& m) { } } ImGui::PopID(); - } + }; + for (std::size_t control = 0; control < input::HostInput::kCabinetControlCount; ++control) binding_row(control); + + w::divider(); + w::section("Performance", "OpenGP's own: they work while playing, not in the menu."); + for (std::size_t control = input::HostInput::kProfilerFirst; control < input::HostInput::kControlCount; ++control) + binding_row(control); w::divider(); if (kind == Kind::Keyboard) { @@ -808,6 +837,41 @@ void Menu::page_link(MenuModel& m) { // ---- Confirmations ---------------------------------------------------------------------------- +// Live information only: no recording, captures or file output. +void Menu::page_profiler(MenuModel& m) { + const Profiler::LiveStats& p = m.profile; + char text[256]; + w::section("Live performance"); + std::snprintf(text, sizeof(text), "%.1f fps · game %.1f ms · busy %.1f ms · p99 %.1f ms", + static_cast(p.fps), static_cast(p.guest_ms), static_cast(p.busy_ms), + static_cast(p.p99_ms)); + w::row_text({"Frame times", "Recent game frames; busy time excludes idle and renderer waits."}, text); + std::snprintf(text, sizeof(text), "%llu drops · %llu hitches", static_cast(p.drops), + static_cast(p.hitches)); + w::row_text({"Drops", "Retraces without a new frame; hitches are frames much longer than the recent median."}, text); + if (p.system_cpu >= 0) std::snprintf(text, sizeof(text), "%.0f%%", static_cast(p.system_cpu)); + else std::snprintf(text, sizeof(text), "unavailable"); + w::row_text({"Computer CPU", "The whole computer's CPU use."}, text); + std::snprintf(text, sizeof(text), "%u textures, %.0f MB · %u pipelines", p.textures, p.texture_mb, p.pipelines); + w::row_text({"GPU", "Game textures and pipelines in use; texture memory is an estimate."}, text); + std::snprintf(text, sizeof(text), "%.0f ms queued · %llu underruns", static_cast(p.audio_ms), + static_cast(p.audio_underruns)); + w::row_text({"Sound", "An underrun is a gap in the output queue."}, text); + if (!p.scene.empty() || !p.course.empty()) { + const std::string where = p.scene + (p.course.empty() ? "" : " · " + p.course); + w::row_text({"Scene", ""}, where.c_str()); + } + w::gap(6); + take_focus(); + if (m.toggle_overlay) { + bool overlay = m.overlay; + std::string help = "Show live information over the game."; + const std::string key = profiler_key(m, "profile_overlay"); + if (!key.empty()) help += " " + key + " shows and hides it."; + if (w::row_toggle({"Performance overlay", help.c_str()}, &overlay)) m.toggle_overlay(); + } +} + void Menu::draw_confirm(MenuModel& m) { const char* const kId = "##confirm"; if (confirm_ == Confirm::None) { @@ -960,6 +1024,92 @@ void Menu::draw_paused(MenuModel& m) { } } +// The live numbers over the game, while it plays: frame times and a graph, +// drops and hitches, and the computer's load. +void Menu::draw_profiler_overlay(MenuModel& m) { + const Profiler::LiveStats& p = m.profile; + const ImGuiIO& io = ImGui::GetIO(); + ImDrawList* dl = ImGui::GetForegroundDrawList(); + const float margin = px(14), pad = px(12), graph_h = px(38); + const float width = std::min(px(336), io.DisplaySize.x - 2 * margin); + + std::string keys; + auto add_key = [&](const char* control, const char* what) { + const std::string key = profiler_key(m, control); + if (!key.empty()) keys += (keys.empty() ? "" : " · ") + key + " " + what; + }; + add_key("profile_overlay", "hide"); + const bool scene = !p.scene.empty() || !p.course.empty(); + const int lines = 5 + (scene ? 1 : 0) + (keys.empty() ? 0 : 1); + const float height = pad * 2 + static_cast(lines) * px(18) + graph_h + px(6); + + const ImVec2 min(margin, margin), max(min.x + width, min.y + height); + dl->AddRectFilled(min, max, theme::alpha(theme::kAsphaltDeep, 0.82f), px(10)); + dl->AddRect(min, max, theme::alpha(theme::kLine, 0.9f), px(10), 0, 1.0f); + + float y = min.y + pad; + auto line = [&](const char* text, float size, ImU32 colour, theme::Weight weight = theme::Weight::Regular) { + theme::push_font(weight, size); + dl->AddText(ImGui::GetFont(), ImGui::GetFontSize(), ImVec2(min.x + pad, y), colour, text); + y += px(18); + theme::pop_font(); + }; + + line("Performance", theme::kBody, theme::kChalk, theme::Weight::Bold); + + char text[200]; + if (p.fps > 0) + std::snprintf(text, sizeof(text), "%.1f fps · frame %.1f ms · busy %.1f · p99 %.1f", static_cast(p.fps), + static_cast(p.guest_ms), static_cast(p.busy_ms), static_cast(p.p99_ms)); + else + std::snprintf(text, sizeof(text), "frame %.1f ms · busy %.1f ms · p99 %.1f ms", static_cast(p.guest_ms), + static_cast(p.busy_ms), static_cast(p.p99_ms)); + line(text, theme::kBody, theme::kChalk); + + // The last frames' game times: a line at 16.7 ms (one frame a retrace). + { + const float x = min.x + pad, w = width - 2 * pad; + dl->AddRectFilled(ImVec2(x, y), ImVec2(x + w, y + graph_h), theme::alpha(theme::kBlack, 0.35f), px(4)); + float top = 33.4f; + for (const float v : p.graph) top = std::max(top, v); + const float unit = graph_h / top; + const float target = y + graph_h - 16.683f * unit; + dl->AddLine(ImVec2(x, target), ImVec2(x + w, target), theme::alpha(theme::kGreen, 0.45f), 1.0f); + if (p.graph.size() > 1) { + std::vector points; + points.reserve(p.graph.size()); + const float dx = w / static_cast(p.graph.size() - 1); + for (std::size_t i = 0; i < p.graph.size(); ++i) + points.emplace_back(x + dx * static_cast(i), y + graph_h - std::min(p.graph[i], top) * unit); + dl->AddPolyline(points.data(), static_cast(points.size()), + p.p99_ms > 20.0f ? theme::kMarquee : theme::kBlue, 0, px(1.5f)); + } + y += graph_h + px(6); + } + + if (p.system_cpu >= 0) + std::snprintf(text, sizeof(text), "Drops %llu · hitches %llu · CPU %.0f%%", + static_cast(p.drops), static_cast(p.hitches), + static_cast(p.system_cpu)); + else + std::snprintf(text, sizeof(text), "Drops %llu · hitches %llu", + static_cast(p.drops), static_cast(p.hitches)); + line(text, theme::kBody, theme::kDim); + + std::snprintf(text, sizeof(text), "%u textures (%.0f MB) · %u pipelines · audio %.0f ms", p.textures, p.texture_mb, + p.pipelines, static_cast(p.audio_ms)); + line(text, theme::kBody, theme::kDim); + + std::snprintf(text, sizeof(text), "%llu audio underruns", static_cast(p.audio_underruns)); + line(text, theme::kBody, p.audio_underruns ? theme::kMarquee : theme::kDim); + + if (scene) { + const std::string where = p.scene + (p.course.empty() ? "" : " · " + p.course); + line(where.c_str(), theme::kBody, theme::kChalk); + } + if (!keys.empty()) line(keys.c_str(), theme::kSmall, theme::kFaint); +} + void Menu::draw_notices() { const auto now = Clock::now(); std::erase_if(notices_, [&](const Notice& n) { return n.until <= now; }); diff --git a/runtime/app/menu.h b/runtime/app/menu.h index 1f6af86..17c3453 100644 --- a/runtime/app/menu.h +++ b/runtime/app/menu.h @@ -15,6 +15,7 @@ #include #include +#include "app/profiler.h" #include "app/settings.h" #include "input/host.h" #include "triforce/card_folder.h" @@ -41,6 +42,10 @@ struct MenuModel { bool restart_needed = false; // a camera or link setting differs from the running one std::function quit; std::function test_menu; // restarts into the game's test menu (if it has one) + // Live performance information, kept in memory only. + Profiler::LiveStats profile; + bool overlay = false; + std::function toggle_overlay; }; // A notice's kind: information, or a problem (a save that failed). @@ -69,7 +74,11 @@ class Menu final : public video::Overlay { // Shows that the game is paused (while the menu is closed). void set_paused(bool paused) { paused_ = paused; } - // Whether there is anything to draw (the menu, a notice, or "Paused"). + // Shows the live profiler overlay over the game while the menu is closed. + void set_profiler_overlay(bool on) { overlay_ = on; } + + // Whether there is anything to draw (the menu, a notice, "Paused", or the + // profiler's overlay). bool visible() const; // Lays the menu out for the next presented frame. @@ -82,8 +91,8 @@ class Menu final : public video::Overlay { private: using Clock = std::chrono::steady_clock; enum class Screen { Card, Settings }; - enum class Page { Game, Video, Sound, Controls, Camera, Link }; - static constexpr int kPageCount = 6; + enum class Page { Game, Video, Sound, Controls, Camera, Link, Profiler }; + static constexpr int kPageCount = 7; enum class Confirm { None, Quit, TestMenu, RestoreDefaults }; struct Notice { std::string text; @@ -108,9 +117,11 @@ class Menu final : public video::Overlay { void page_controls(MenuModel& m); void page_camera(MenuModel& m); void page_link(MenuModel& m); + void page_profiler(MenuModel& m); void draw_confirm(MenuModel& m); void draw_hints(bool pages); void draw_paused(MenuModel& m); + void draw_profiler_overlay(MenuModel& m); void draw_notices(); std::vector webcams_; // listed when the webcam list opens @@ -120,6 +131,7 @@ class Menu final : public video::Overlay { bool initialised_ = false; bool open_ = false; bool paused_ = false; + bool overlay_ = false; // the live profiler overlay, while the menu is closed bool focus_window_ = false; // focus the screen's window on its next frame bool focus_item_ = false; // focus the screen's first widget on its next frame bool show_focus_ = true; // ... with its ring showing diff --git a/runtime/app/profiler.cpp b/runtime/app/profiler.cpp new file mode 100644 index 0000000..38dce01 --- /dev/null +++ b/runtime/app/profiler.cpp @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "app/profiler.h" + +#include +#include + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#elif defined(__APPLE__) +#include +#else +#include +#endif + +namespace app { +using gekko::u64; + +namespace { +u64 delta(u64 now, u64 before) { return now >= before ? now - before : 0; } +float ms(u64 ns) { return static_cast(static_cast(ns) * 1e-6); } + +bool cpu_counters(u64& total, u64& idle) { +#ifdef _WIN32 + FILETIME i{}, k{}, u{}; + if (!GetSystemTimes(&i, &k, &u)) return false; + auto value = [](const FILETIME& t) { return (u64{t.dwHighDateTime} << 32) | t.dwLowDateTime; }; + idle = value(i); + total = value(k) + value(u); // kernel includes idle +#elif defined(__APPLE__) + host_cpu_load_info_data_t ticks{}; + mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT; + const mach_port_t host = mach_host_self(); + const kern_return_t result = host_statistics(host, HOST_CPU_LOAD_INFO, + reinterpret_cast(&ticks), &count); + mach_port_deallocate(mach_task_self(), host); + if (result != KERN_SUCCESS) return false; + total = 0; + for (const auto tick : ticks.cpu_ticks) total += tick; + idle = ticks.cpu_ticks[CPU_STATE_IDLE]; +#else + std::ifstream file("/proc/stat"); + std::string name; + u64 user = 0, nice = 0, system = 0, waiting = 0, irq = 0, softirq = 0, steal = 0; + if (!(file >> name >> user >> nice >> system >> idle >> waiting >> irq >> softirq >> steal) || name != "cpu") + return false; + idle += waiting; + total = user + nice + system + idle + irq + softirq + steal; +#endif + return true; +} +} // namespace + +void Profiler::sample_system_cpu() { + u64 total = 0, idle = 0; + if (!cpu_counters(total, idle)) { + live_.system_cpu = -1; + have_cpu_ = false; + return; + } + if (have_cpu_ && total > cpu_total_ && idle >= cpu_idle_) { + const double busy = 1.0 - static_cast(idle - cpu_idle_) / static_cast(total - cpu_total_); + live_.system_cpu = static_cast(std::clamp(busy * 100.0, 0.0, 100.0)); + } + cpu_total_ = total; + cpu_idle_ = idle; + have_cpu_ = true; +} + +void Profiler::on_frame(const FrameInfo& f) { + auto& l = live_; + l.render_ms = ms(f.render_ns); + l.audio_ms = static_cast(f.audio_ms); + l.audio_underruns = f.audio_underruns; + l.textures = f.textures; + l.pipelines = f.pipelines; + l.texture_mb = static_cast(f.texture_bytes) / (1024.0 * 1024.0); + l.scene = f.scene; + l.course = f.course; + + // A paused/menu interval, first frame, or reset cannot be a gameplay hitch. + const bool steady = have_last_ && f.active && last_.active && + f.finished_ns > last_.finished_ns && f.present_ns > last_.present_ns; + if (steady) { + const u64 guest = f.finished_ns - last_.finished_ns; + const u64 present = f.present_ns - last_.present_ns; + const u64 idle = std::min(guest, delta(f.idle_ns, last_.idle_ns)); + const u64 wait = std::min(guest - idle, delta(f.wait_ns, last_.wait_ns)); + l.guest_ms = ms(guest); + l.busy_ms = ms(guest - idle - wait); + l.present_ms = ms(present); + + float expected = 16.683f; + if (l.graph.size() >= 30) { + auto sorted = l.graph; + const auto middle = sorted.begin() + static_cast(sorted.size() / 2); + std::nth_element(sorted.begin(), middle, sorted.end()); + expected = *middle; + } + const float slow = std::max(expected * 1.5f, expected + 8.0f); + if (l.guest_ms > slow || l.present_ms > slow) ++l.hitches; + if (f.retrace > last_.retrace) l.drops += f.retrace - last_.retrace - 1; + l.graph.push_back(l.guest_ms); + if (l.graph.size() > 120) l.graph.erase(l.graph.begin()); + auto sorted = l.graph; + const auto index = static_cast(0.99 * static_cast(sorted.size() - 1)); + std::nth_element(sorted.begin(), sorted.begin() + static_cast(index), sorted.end()); + l.p99_ms = sorted[index]; + present_average_ns_ = present_average_ns_ > 0 ? present_average_ns_ * 0.9 + static_cast(present) * 0.1 + : static_cast(present); + l.fps = static_cast(1e9 / present_average_ns_); + } + last_ = f; + have_last_ = true; +} + +} // namespace app diff --git a/runtime/app/profiler.h b/runtime/app/profiler.h new file mode 100644 index 0000000..7a98a22 --- /dev/null +++ b/runtime/app/profiler.h @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Live performance information. A bounded history in memory, with no recording, +// stack sampling, captures, worker threads or file output. Called by the render thread. +#pragma once + +#include +#include + +#include "gekko/types.h" + +namespace app { + +class Profiler { + public: + struct FrameInfo { + gekko::u64 finished_ns = 0, present_ns = 0, retrace = 0; + gekko::u64 idle_ns = 0, wait_ns = 0; // cumulative counters + gekko::u64 render_ns = 0; + bool active = true; + double audio_ms = 0; + gekko::u64 audio_underruns = 0, texture_bytes = 0; + gekko::u32 textures = 0, pipelines = 0; + std::string scene, course; + }; + struct LiveStats { + gekko::u64 hitches = 0, drops = 0; + float fps = 0, guest_ms = 0, busy_ms = 0, present_ms = 0, p99_ms = 0, render_ms = 0; + float system_cpu = -1; // whole computer, percent; negative when unavailable + float audio_ms = 0; + gekko::u64 audio_underruns = 0; + gekko::u32 textures = 0, pipelines = 0; + double texture_mb = 0; + std::string scene, course; + std::vector graph; // at most 120 active frames, oldest first + }; + + void on_frame(const FrameInfo& info); + // Poll at most once per second. Reads operating-system CPU counters only. + void sample_system_cpu(); + const LiveStats& live() const { return live_; } + + private: + LiveStats live_; + FrameInfo last_; + bool have_last_ = false, have_cpu_ = false; + double present_average_ns_ = 0; + gekko::u64 cpu_total_ = 0, cpu_idle_ = 0; +}; + +} // namespace app diff --git a/runtime/app/settings.cpp b/runtime/app/settings.cpp index 494219f..0f1193b 100644 --- a/runtime/app/settings.cpp +++ b/runtime/app/settings.cpp @@ -125,6 +125,7 @@ bool load_settings(const std::string& path, Settings* settings, std::string* err s.free_play = game["free_play"].value_or(s.free_play); 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.brake_goes_back = game["brake_goes_back"].value_or(s.brake_goes_back); 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"]; @@ -180,6 +181,10 @@ bool save_settings(const std::string& path, const Settings& s, std::string* erro "# Pause the game while the menu is open, and while its window is in the background.\n" "pause_in_menu = " << (s.pause_in_menu ? "true" : "false") << "\npause_in_background = " << (s.pause_in_background ? "true" : "false") + << "\n" + "# The brake goes back a screen in the game's menus (not in a linked game).\n" + "brake_goes_back = " + << (s.brake_goes_back ? "true" : "false") << "\n" "# The Mario Card you hold (user/cards//.bin), or \"\" for none.\n" "card = " diff --git a/runtime/app/settings.h b/runtime/app/settings.h index c520b0c..5ae159d 100644 --- a/runtime/app/settings.h +++ b/runtime/app/settings.h @@ -44,6 +44,7 @@ struct Settings { bool free_play = false; 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 + bool brake_goes_back = true; // the brake goes back a screen in the game's menus (not linked) 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) diff --git a/runtime/gx/frontend.h b/runtime/gx/frontend.h index 68c2fee..7bdae00 100644 --- a/runtime/gx/frontend.h +++ b/runtime/gx/frontend.h @@ -51,7 +51,11 @@ class Frontend { void set_output(FrameOutput* output) { output_ = output; } // Waits while the output is too far behind (see FrameOutput::wait_for_room). void wait_for_output() { - if (output_) output_->wait_for_room(); + if (!output_) return; + const auto start = std::chrono::steady_clock::now(); + output_->wait_for_room(); + stats_.wait_ns.fetch_add(static_cast(std::chrono::duration_cast( + std::chrono::steady_clock::now() - start).count()), std::memory_order_relaxed); } // Widescreen: widens the EFB by `side` pixels on the left and right, from @@ -90,7 +94,7 @@ class Frontend { // texture and transform times. struct Stats { std::atomic draw_ns{0}, state_ns{0}, texture_ns{0}, transform_ns{0}, vertices{0}; - std::atomic readback_ns{0}, readbacks{0}; // EFB reads that waited for the renderer + std::atomic wait_ns{0}, readback_ns{0}, readbacks{0}; // EFB reads that waited for the renderer }; const Stats& stats() const { return stats_; } diff --git a/runtime/hw/vi.h b/runtime/hw/vi.h index ee23997..25bc137 100644 --- a/runtime/hw/vi.h +++ b/runtime/hw/vi.h @@ -12,6 +12,7 @@ #pragma once #include +#include #include "hw/hardware.h" @@ -26,7 +27,7 @@ class ViDevice : public Device { // Physical address of the XFB (top field) the display shows. u32 xfb_address() const; - u64 retrace_count() const { return retraces_; } + u64 retrace_count() const { return retraces_.load(std::memory_order_relaxed); } // The host's steady clock (in nanoseconds) at the first retrace after // `after_ns`: DI0's or DI1's interrupt, both of which the SDK counts as a // retrace (one a field, 59.94 a second). The display shows the XFB the game @@ -50,7 +51,7 @@ class ViDevice : public Device { std::array regs_{}; u64 origin_ = 0; // time base at the start of frame 0 std::array events_{}; - u64 retraces_ = 0; + std::atomic retraces_{0}; }; } // namespace hw diff --git a/runtime/input/host.cpp b/runtime/input/host.cpp index d256eea..acaf7f2 100644 --- a/runtime/input/host.cpp +++ b/runtime/input/host.cpp @@ -58,6 +58,8 @@ constexpr const char* kDefaultConfig = R"(# OpenGP controls. Delete this file to # # "pause" is OpenGP's, not the cabinet's: it freezes the game until pressed # again. +# +# "profile_overlay" shows live performance information (F7 by default). [keyboard] steer_left = ["Left", "A"] @@ -71,6 +73,7 @@ coin = ["5", "C"] service = ["F1"] test = ["F2"] pause = ["P", "Pause"] +profile_overlay = ["F7"] [gamepad] steer = ["leftx"] @@ -82,6 +85,8 @@ item = ["a", "rightshoulder"] cancel = ["b", "leftshoulder"] start = ["start"] coin = ["back"] +# Add a button here to show performance information from a controller. +profile_overlay = [] deadzone = 0.12 [joystick] @@ -94,6 +99,7 @@ item = ["button0"] cancel = ["button1"] start = ["button9"] coin = [] +profile_overlay = [] deadzone = 0.0 [steering] @@ -131,14 +137,17 @@ enum Control : std::size_t { kTest, kService, kPause, // OpenGP's, not the cabinet's + kProfileOverlay, kControlCount }; constexpr std::array kControlNames = { - "steer", "steer_left", "steer_right", "gas", "brake", "item", "cancel", "start", "coin", "test", "service", "pause"}; + "steer", "steer_left", "steer_right", "gas", "brake", "item", "cancel", "start", "coin", "test", "service", "pause", + "profile_overlay"}; constexpr std::array kControlLabels = { - "Steering", "Steer left", "Steer right", "Gas", "Brake", "Item button", "Cancel button", - "Start", "Coin", "Test", "Service", "Pause"}; + "Steering", "Steer left", "Steer right", "Gas", "Brake", "Item button", "Cancel button", "Start", "Coin", "Test", + "Service", "Pause", "Performance overlay"}; static_assert(kControlCount == HostInput::kControlCount); +static_assert(kProfileOverlay == HostInput::kProfilerFirst); // The bindings of one kind of device. struct Bindings { @@ -447,6 +456,8 @@ struct HostInput::Impl { 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 bool pause_pressed = false; // pressed since take_pause_press() + u32 profiler_held = 0; // the profiler's controls' inputs, at the last poll + u32 profiler_pressed = 0; // ... pressed since take_profiler_actions() std::chrono::steady_clock::time_point last_poll = std::chrono::steady_clock::now(); triforce::Outputs outputs; std::chrono::steady_clock::time_point last_play{}; @@ -590,10 +601,21 @@ void HostInput::handle_event(const SDL_Event& e) { if (e.type == SDL_EVENT_JOYSTICK_ADDED) impl_->open(e.jdevice.which); else if (e.type == SDL_EVENT_JOYSTICK_REMOVED) impl_->close(e.jdevice.which); // Pause keys go by their key presses, which a poll can miss if they are - // quick (the game's controls are held). + // quick (the game's controls are held). The profiler's actions are quick + // presses too: a key, or a button on a controller. + auto press = [&](const Bindings& b, Source::Kind kind, int index) { + for (std::size_t c = kProfilerFirst; c < kControlCount; ++c) + for (const Source& s : b.sources[c]) + if (s.kind == kind && s.index == index) impl_->profiler_pressed |= 1u << (c - kProfilerFirst); + }; if (e.type == SDL_EVENT_KEY_DOWN && !e.key.repeat) { for (const Source& s : impl_->config.keyboard.sources[kPause]) if (s.kind == Source::Kind::Key && s.index == static_cast(e.key.scancode)) impl_->pause_pressed = true; + press(impl_->config.keyboard, Source::Kind::Key, e.key.scancode); + } else if (e.type == SDL_EVENT_GAMEPAD_BUTTON_DOWN) { + press(impl_->config.gamepad, Source::Kind::PadButton, e.gbutton.button); + } else if (e.type == SDL_EVENT_JOYSTICK_BUTTON_DOWN) { + press(impl_->config.joystick, Source::Kind::JoyButton, e.jbutton.button); } } @@ -785,9 +807,26 @@ triforce::Controls HostInput::poll() { const bool pause = amount[kPause] > 0.5f; if (pause && !m.pause_held) m.pause_pressed = true; m.pause_held = pause; + + // The profiler's actions, from held keys, buttons and axes. Like the pause + // control, their quick key and button presses are also caught by + // handle_event(); here they are seen as edges, so holding one does not + // repeat it. While an input is being chosen for a control (the menu's + // capture), what is pressed is for the capture: no action. + u32 profiler = 0; + for (std::size_t c = kProfilerFirst; c < kControlCount; ++c) + if (amount[c] > 0.5f) profiler |= 1u << (c - kProfilerFirst); + if (!m.capture.active) m.profiler_pressed |= profiler & ~m.profiler_held; + m.profiler_held = profiler; return c; } +u32 HostInput::take_profiler_actions() { + const u32 actions = impl_->profiler_pressed; + impl_->profiler_pressed = 0; + return actions; +} + bool HostInput::take_pause_press() { const bool pressed = impl_->pause_pressed; impl_->pause_pressed = false; diff --git a/runtime/input/host.h b/runtime/input/host.h index f37c447..0416f0c 100644 --- a/runtime/input/host.h +++ b/runtime/input/host.h @@ -51,13 +51,20 @@ class HostInput { // reads them. bool take_pause_press(); + // Live performance overlay, bound like the cabinet's controls. + enum ProfilerAction : u32 { kProfilerOverlay = 1u << 0 }; + u32 take_profiler_actions(); + // Plays the cabinet's outputs (wheel forces) on the devices. void set_outputs(const triforce::Outputs& outputs); // ---- Seeing and changing the bindings (the menu) ---- enum class DeviceKind { Keyboard, Gamepad, Joystick }; - static constexpr std::size_t kControlCount = 12; + // The cabinet's controls come first, then the profiler's. + static constexpr std::size_t kCabinetControlCount = 12; + static constexpr std::size_t kProfilerFirst = kCabinetControlCount; + static constexpr std::size_t kControlCount = 13; // A control's name in the file ("gas") and in the menu ("Gas"). static const char* control_name(std::size_t control); static const char* control_label(std::size_t control); diff --git a/runtime/os/threads.cpp b/runtime/os/threads.cpp index 2ca1286..2bf5023 100644 --- a/runtime/os/threads.cpp +++ b/runtime/os/threads.cpp @@ -2,7 +2,9 @@ #include "os/threads.h" +#include #include +#include #include #include "os/crash.h" @@ -113,7 +115,12 @@ void ThreadManager::idle(ppc::Context& ctx) { const u64 delivered = exceptions_delivered_.load(std::memory_order_relaxed); if (delivered == idle_seen_) { ++idle_waits_; + const auto start = std::chrono::steady_clock::now(); hw_.wait_for_interrupt(4); + idle_ns_.fetch_add(static_cast(std::chrono::duration_cast( + std::chrono::steady_clock::now() - start) + .count()), + std::memory_order_relaxed); service_interrupts(ctx); } idle_seen_ = exceptions_delivered_.load(std::memory_order_relaxed); diff --git a/runtime/os/threads.h b/runtime/os/threads.h index d9cb489..a99ea99 100644 --- a/runtime/os/threads.h +++ b/runtime/os/threads.h @@ -80,8 +80,10 @@ class ThreadManager { // with ExceptionReturn (for profiling). u64 exceptions_delivered() const { return exceptions_delivered_.load(std::memory_order_relaxed); } u64 exception_returns() const { return exception_returns_.load(std::memory_order_relaxed); } - // How often the idle loop has waited for an interrupt (for diagnostics). + // How often the idle loop has waited for an interrupt, and for how long in + // all (ns): the time the game had nothing to do (for diagnostics). u64 idle_waits() const { return idle_waits_.load(std::memory_order_relaxed); } + u64 idle_ns() const { return idle_ns_.load(std::memory_order_relaxed); } // The registers of the thread holding the CPU, and its host thread's // number (for diagnostics: they change while it runs). const ppc::Context* running_context(int* id); @@ -107,7 +109,7 @@ class ThreadManager { HostThread* running_ = nullptr; std::vector> threads_; std::unordered_map owners_; // only touched by the thread holding the CPU - std::atomic exceptions_delivered_{0}, exception_returns_{0}, idle_waits_{0}; + std::atomic exceptions_delivered_{0}, exception_returns_{0}, idle_waits_{0}, idle_ns_{0}; u64 idle_seen_ = 0; // exceptions_delivered_ when the idle hook last returned }; diff --git a/runtime/video/renderer.cpp b/runtime/video/renderer.cpp index d638bc8..d757232 100644 --- a/runtime/video/renderer.cpp +++ b/runtime/video/renderer.cpp @@ -157,6 +157,18 @@ Renderer::~Renderer() { const char* Renderer::driver() const { return device_ ? SDL_GetGPUDeviceDriver(device_) : "none"; } +u64 Renderer::live_texture_bytes() const { + u64 bytes = 0; + for (const auto& [handle, t] : textures_) { + for (u32 l = 0, w = t.width, h = t.height; l < std::max(t.levels, 1u); ++l) { + bytes += u64{w} * h * 4; + w = std::max(1u, w / 2); + h = std::max(1u, h / 2); + } + } + return bytes; +} + SDL_GPUShader* Renderer::shader(const ShaderCode& code, bool fragment, u32 samplers, u32 uniforms) { SDL_GPUShaderCreateInfo info{}; if (msl_) { diff --git a/runtime/video/renderer.h b/runtime/video/renderer.h index bb027ff..e50afce 100644 --- a/runtime/video/renderer.h +++ b/runtime/video/renderer.h @@ -127,6 +127,9 @@ class Renderer { void render(const gx::Frame& frame, Image* capture = nullptr, bool present = true); const char* driver() const; + u32 live_textures() const { return static_cast(textures_.size()); } + u32 live_pipelines() const { return static_cast(tev_pipelines_.size() + clear_pipelines_.size()); } + u64 live_texture_bytes() const; private: struct Texture { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index cb8b399..03cd8fb 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -70,6 +70,16 @@ add_executable(test_settings test_settings.cpp) target_link_libraries(test_settings PRIVATE opengp_settings doctest opengp_warnings) add_test(NAME settings COMMAND test_settings) +add_executable(test_performance test_performance.cpp ../runtime/app/profiler.cpp) +target_include_directories(test_performance PRIVATE ../runtime) +target_link_libraries(test_performance PRIVATE gekko_isa doctest opengp_warnings) +add_test(NAME performance COMMAND test_performance) + +add_executable(test_menu_back test_menu_back.cpp ../games/common/menu_back.cpp) +target_include_directories(test_menu_back PRIVATE ../games/common) +target_link_libraries(test_menu_back PRIVATE ppc_runtime doctest opengp_warnings) +add_test(NAME menu_back COMMAND test_menu_back) + if(TARGET opengp_input) add_executable(test_controls test_controls.cpp) target_link_libraries(test_controls PRIVATE opengp_input doctest opengp_warnings) diff --git a/tests/test_controls.cpp b/tests/test_controls.cpp index b34f6ac..e67d759 100644 --- a/tests/test_controls.cpp +++ b/tests/test_controls.cpp @@ -50,6 +50,35 @@ TEST_CASE("the defaults are written the first time and read back") { CHECK(in.bindings(Kind::Joystick, control("steer")) == Names{"axis0"}); } +TEST_CASE("performance overlay defaults survive an older controls file without recording actions") { + const fs::path path = temp_file("old-performance.toml"); + std::ofstream(path) << "[keyboard]\ngas = [\"W\"]\n"; + HostInput in; + std::string error; + REQUIRE(in.load(path.string(), &error)); + CHECK(in.bindings(Kind::Keyboard, control("profile_overlay")) == Names{"F7"}); + for (std::size_t c = 0; c < HostInput::kControlCount; ++c) { + CHECK(std::string(HostInput::control_name(c)) != "profile_toggle"); + CHECK(std::string(HostInput::control_name(c)) != "profile_mark"); + CHECK(std::string(HostInput::control_name(c)) != "profile_capture"); + } + SDL_Event e{}; + e.type = SDL_EVENT_KEY_DOWN; + e.key.scancode = SDL_SCANCODE_F7; + in.handle_event(e); + CHECK(in.take_profiler_actions() == HostInput::kProfilerOverlay); + CHECK(in.take_profiler_actions() == 0); + e.key.repeat = true; + in.handle_event(e); + CHECK(in.take_profiler_actions() == 0); + e.key.repeat = false; + for (const auto key : {SDL_SCANCODE_F8, SDL_SCANCODE_F9, SDL_SCANCODE_F10}) { + e.key.scancode = key; + in.handle_event(e); + CHECK(in.take_profiler_actions() == 0); + } +} + TEST_CASE("changed bindings survive saving") { const fs::path path = temp_file("changed.toml"); std::ofstream(path) << "[keyboard]\ngas = [\"Left Shift\"]\n[joystick]\ngas = [\"-axis2\"]\nbrake = [\"axis1+\", \"hat0up\"]\n"; diff --git a/tests/test_menu_back.cpp b/tests/test_menu_back.cpp new file mode 100644 index 0000000..1dadebd --- /dev/null +++ b/tests/test_menu_back.cpp @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Local staging validation: synthetic scene memory, no game data. +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include +#include "menu_back.h" +#include "ppc/memory.h" + +namespace { +constexpr gekko::u32 stay = ~0u; +constexpr gekko::u32 starts[] = {0x09}; +constexpr gekko::u32 stops[] = {0x0B, 0x0D, 0x0F, 0x15, 0x17, 0x19, 0x1B, 0x21, 0x22}; +constexpr gekko::u32 back_screens[] = {0x0D, 0x0F, 0x13, 0x15, 0x17, 0x19, 0x1B, 0x21, 0x22}; +constexpr menu_back::Menus menus{0, starts, stops, back_screens}; +struct Play { + gekko::u8 memory[4]{}; + bool brake = false, gas = false; + Play() { + menu_back::forget(); + menu_back::set([this] { return brake; }, [this] { return gas; }); + } + ~Play() { menu_back::set({}, {}); } + gekko::u32 frame(gekko::u32 screen, gekko::u32 next = stay) { + ppc::store_be(memory, screen); + return menu_back::after_update(memory, menus, next); + } +}; +} + +TEST_CASE("fresh brake returns character to class, but class cannot go back") { + Play p; + CHECK(p.frame(0x0B) == stay); + CHECK(p.frame(0x0D) == stay); + p.brake = true; + CHECK(p.frame(0x0D) == 0x0B); + CHECK(p.frame(0x0B) == stay); +} + +TEST_CASE("held brake cannot back through multiple screens") { + Play p; + p.frame(0x0B); p.frame(0x0D); p.frame(0x15); + p.brake = true; + CHECK(p.frame(0x15) == 0x0D); + CHECK(p.frame(0x0D) == stay); + p.brake = false; + CHECK(p.frame(0x0D) == stay); + p.brake = true; + CHECK(p.frame(0x0D) == 0x0B); +} + +TEST_CASE("photo is skipped as a return destination") { + Play p; + p.frame(0x0B); p.frame(0x0D); p.frame(0x13); p.frame(0x15); + p.brake = true; + CHECK(p.frame(0x15) == 0x0D); +} + +TEST_CASE("card kart and round history is retained in order") { + Play p; + p.frame(0x0B); p.frame(0x0D); p.frame(0x0F); p.frame(0x13); p.frame(0x15); + p.brake = true; + CHECK(p.frame(0x15) == 0x0F); + p.brake = false; + p.frame(0x0F); p.frame(0x15); p.frame(0x1B); p.frame(0x21); + p.brake = true; + CHECK(p.frame(0x21) == 0x1B); +} + +TEST_CASE("gas latches confirmation until a different screen") { + Play p; + p.frame(0x0B); p.frame(0x0D); + p.gas = true; + CHECK(p.frame(0x0D) == stay); + p.gas = false; p.brake = true; + CHECK(p.frame(0x0D) == stay); + p.brake = false; + p.frame(0x15); + p.brake = true; + CHECK(p.frame(0x15) == 0x0D); +} + +TEST_CASE("simultaneous gas and brake confirms rather than returning") { + Play p; + p.frame(0x0B); p.frame(0x0D); + p.brake = p.gas = true; + CHECK(p.frame(0x0D) == stay); +} + +TEST_CASE("normal forward transitions take priority") { + Play p; + p.frame(0x0B); p.frame(0x0D); + p.brake = true; + CHECK(p.frame(0x0D, 0x13) == 0x13); +} + +TEST_CASE("race start and new play discard earlier history") { + Play p; + p.frame(0x0B); p.frame(0x0D); p.frame(0x15); p.frame(0x1B); + menu_back::forget(); + p.frame(0x1B); + p.brake = true; + CHECK(p.frame(0x1B) == stay); + p.brake = false; + p.frame(0x09); p.frame(0x0D); + p.brake = true; + CHECK(p.frame(0x0D) == stay); +} + +TEST_CASE("absent callbacks cannot trigger back") { + Play p; + p.frame(0x0B); p.frame(0x0D); + menu_back::set({}, {}); + p.brake = true; + CHECK(p.frame(0x0D) == stay); +} diff --git a/tests/test_performance.cpp b/tests/test_performance.cpp new file mode 100644 index 0000000..6f242ef --- /dev/null +++ b/tests/test_performance.cpp @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include + +#include "app/profiler.h" + +using app::Profiler; + +TEST_CASE("live timings exclude idle and waits and retain only 120 frames") { + Profiler p; + Profiler::FrameInfo f; + f.active = true; + for (int i = 0; i < 300; ++i) { + f.finished_ns += 16'000'000; + f.present_ns += 20'000'000; + f.idle_ns += 3'000'000; + f.wait_ns += 2'000'000; + ++f.retrace; + p.on_frame(f); + } + const auto& live = p.live(); + CHECK(live.fps == doctest::Approx(50)); + CHECK(live.guest_ms == doctest::Approx(16)); + CHECK(live.busy_ms == doctest::Approx(11)); + CHECK(live.p99_ms == doctest::Approx(16)); + CHECK(live.graph.size() == 120); + CHECK(live.hitches == 0); + CHECK(live.drops == 0); +} + +TEST_CASE("first frame, pause and resume do not create hitches or dropped frames") { + Profiler p; + Profiler::FrameInfo f; + f.finished_ns = f.present_ns = 1'000'000'000; + f.retrace = 60; + p.on_frame(f); + CHECK(p.live().graph.empty()); + f.active = false; + f.finished_ns = f.present_ns = 10'000'000'000; + f.retrace = 600; + p.on_frame(f); + f.active = true; + f.finished_ns = f.present_ns = 20'000'000'000; + f.retrace = 1200; + p.on_frame(f); + CHECK(p.live().hitches == 0); + CHECK(p.live().drops == 0); + f.finished_ns += 50'000'000; + f.present_ns += 50'000'000; + f.retrace += 3; + p.on_frame(f); + CHECK(p.live().hitches == 1); + CHECK(p.live().drops == 2); +} + +TEST_CASE("counter resets and overlapping wait totals cannot underflow busy time") { + Profiler p; + Profiler::FrameInfo f; + f.finished_ns = f.present_ns = 100'000'000; + f.idle_ns = f.wait_ns = 50'000'000; + p.on_frame(f); + f.finished_ns += 16'000'000; + f.present_ns += 16'000'000; + f.idle_ns = f.wait_ns = 0; + p.on_frame(f); + CHECK(p.live().busy_ms == doctest::Approx(16)); + f.finished_ns += 16'000'000; + f.present_ns += 16'000'000; + f.idle_ns = f.wait_ns = 25'000'000; + p.on_frame(f); + CHECK(p.live().busy_ms == 0); +} + +TEST_CASE("resource and scene information updates even while paused") { + Profiler p; + Profiler::FrameInfo f; + f.active = false; + f.textures = 10; + f.pipelines = 4; + f.texture_bytes = 2 * 1024 * 1024; + f.audio_ms = 32; + f.audio_underruns = 2; + f.scene = "Racing"; + f.course = "Test course"; + p.on_frame(f); + CHECK(p.live().textures == 10); + CHECK(p.live().pipelines == 4); + CHECK(p.live().texture_mb == 2); + CHECK(p.live().audio_ms == 32); + CHECK(p.live().audio_underruns == 2); + CHECK(p.live().scene == "Racing"); + CHECK(p.live().course == "Test course"); +}