From ab40ecfa25402acdd003ef0bbe583985373f31ad Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 07:06:13 +0000 Subject: [PATCH 1/3] Add late tick start option to cut input lag Mario Kart Wii reads the controller at the start of each tick, works about a millisecond, then sleeps until the next retrace before drawing. The read sits unused for most of a frame. With "Late tick start" on, the runtime holds each tick until shortly before that retrace (slowest recent work + 2 ms margin, min 3 ms), so the read lands next to the draw. Retraces the game sees are unchanged. A missed retrace widens the margin by 2 ms (up to 8), decaying slowly. Off by default. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VhnFEjD4PRZpc41Fm7dazZ --- runtime/cmake/PlatformTests.cmake | 7 ++ runtime/include/hle_stubs.h | 5 ++ runtime/include/late_tick_start.h | 36 ++++++++++ runtime/include/runtime_config.h | 12 ++++ runtime/src/hle/gx/gx_stubs.cpp | 2 + runtime/src/hle/os/os_sleep.cpp | 1 + runtime/src/hle/vi.cpp | 74 ++++++++++++++++++- runtime/src/late_tick_start.cpp | 50 +++++++++++++ runtime/src/settings_overlay.cpp | 10 +++ runtime/tests/late_tick_start_tests.cpp | 96 +++++++++++++++++++++++++ 10 files changed, 290 insertions(+), 3 deletions(-) create mode 100644 runtime/include/late_tick_start.h create mode 100644 runtime/src/late_tick_start.cpp create mode 100644 runtime/tests/late_tick_start_tests.cpp diff --git a/runtime/cmake/PlatformTests.cmake b/runtime/cmake/PlatformTests.cmake index 52fac38a4..d390cf969 100644 --- a/runtime/cmake/PlatformTests.cmake +++ b/runtime/cmake/PlatformTests.cmake @@ -296,6 +296,13 @@ target_compile_features(mkw_motion_trick_tests PRIVATE cxx_std_17) target_compile_options(mkw_motion_trick_tests PRIVATE $<$>:-ffast-math>) add_test(NAME mkw_motion_trick_tests COMMAND mkw_motion_trick_tests) +add_executable(mkw_late_tick_start_tests + "${MKW_TEST_RUNTIME_DIR}/tests/late_tick_start_tests.cpp" + "${MKW_TEST_RUNTIME_DIR}/src/late_tick_start.cpp") +target_include_directories(mkw_late_tick_start_tests PRIVATE "${MKW_TEST_RUNTIME_DIR}/include") +target_compile_features(mkw_late_tick_start_tests PRIVATE cxx_std_20) +add_test(NAME mkw_late_tick_start_tests COMMAND mkw_late_tick_start_tests) + # The emulated Bluetooth controller is pure host code. add_executable(mkw_bluetooth_controller_tests "${MKW_TEST_RUNTIME_DIR}/tests/bluetooth_controller_tests.cpp" diff --git a/runtime/include/hle_stubs.h b/runtime/include/hle_stubs.h index e3ba17534..c20bbaef7 100644 --- a/runtime/include/hle_stubs.h +++ b/runtime/include/hle_stubs.h @@ -16,6 +16,11 @@ void VI_HLE_WaitForNextRetracePoll(); // to the VI retrace boundary, pre-warm the next frame). paceToRetrace is true // for the GXCopyDisp producer path and false for retrace-context presents. void VI_HLE_PresentFrame(bool presentedXfb, bool paceToRetrace); +// Late tick start (see late_tick_start.h): hold each tick until shortly before the retrace it waits for. +void VI_HLE_SetLateTickStart(bool enabled); +// GXDrawDone reports the drawing thread; OSSleepThread reports every guest wait. +void VI_HLE_NoteDrawThread(); +void VI_HLE_NoteGuestWait(); bool VI_HLE_IsAdvancingRetrace(); void VI_HLE_SetXfbReady(uint32_t xfbAddr); // Called by GXCopyDisp to signal EFB→XFB copy void Audio_HLE_Tick(CpuContext* ctx, uint32_t deltaMicros); diff --git a/runtime/include/late_tick_start.h b/runtime/include/late_tick_start.h new file mode 100644 index 000000000..81c21ab76 --- /dev/null +++ b/runtime/include/late_tick_start.h @@ -0,0 +1,36 @@ +#pragma once + +#include + +// Late tick start. Mario Kart Wii reads the controller at the start of each tick, works about a +// millisecond, then sleeps until the next retrace before it draws, so the controller read sits +// unused for most of an interval. Holding each tick until shortly before that retrace moves the +// read next to the draw. The game still sees exactly the same retraces. +namespace LateTickStart { + +// How long before the next retrace the tick should start: the slowest recent work before the wait, +// plus a 2 ms margin and any miss penalty; at least 3 ms, at most the interval less 2 ms. +// 0 = don't hold. +uint64_t LeadNanos(double workP99Ms, double missPenaltyMs, uint64_t intervalNanos); + +// A frame that missed its retrace adds 2 ms of room (up to 8); every frame on time takes 0.05 off. +double NextMissPenalty(double currentMs, bool missedRetrace); + +// Tick start -> the drawing thread's first wait, over the last 60 ticks. +class WorkMeter { +public: + void OnTickStart(uint64_t ns); + void OnWaitStart(uint64_t ns); + // Rounds up, so with the full window it is the slowest tick but one. False until 10 ticks. + bool P99(double& ms) const; + +private: + static constexpr int kWindow = 60; + double m_samples[kWindow]{}; + int m_count = 0; + int m_write = 0; + uint64_t m_tickStart = 0; + bool m_measured = true; +}; + +} // namespace LateTickStart diff --git a/runtime/include/runtime_config.h b/runtime/include/runtime_config.h index d88ac372e..249108297 100644 --- a/runtime/include/runtime_config.h +++ b/runtime/include/runtime_config.h @@ -54,6 +54,7 @@ struct RuntimeUserConfig { std::optional textureReplacements; std::optional textureDumps; std::optional showFps; + std::optional lateTickStart; std::optional disabledPostProcessingPaths; std::optional audioVolume; std::optional audioMusicVolume; @@ -490,6 +491,7 @@ inline RuntimeUserConfig ParseConfigDocument(const toml::value& document) { config.gxWorker = FindConfigValue(document, "video", "gx_worker"); config.disableCopyFilter = FindConfigValue(document, "video", "disable_copy_filter"); config.showFps = FindConfigValue(document, "video", "show_fps"); + config.lateTickStart = FindConfigValue(document, "video", "late_tick_start"); config.textureReplacements = FindConfigValue(document, "video", "texture_replacements"); config.textureDumps = FindConfigValue(document, "video", "texture_dumps"); if (auto value = FindConfigUint(document, "video", "disabled_post_processing_paths"); @@ -722,6 +724,11 @@ inline bool SetShowFps(bool value) { return WriteSetting("video", "show_fps", value ? "true" : "false"); } +inline bool SetLateTickStart(bool value) { + Mutable().lateTickStart = value; + return WriteSetting("video", "late_tick_start", value ? "true" : "false"); +} + inline bool SetDisabledPostProcessingPaths(uint32_t value) { Mutable().disabledPostProcessingPaths = value; std::ostringstream formatted; @@ -1053,6 +1060,11 @@ inline bool ShowFps(bool fallback = true) { return Get().showFps.value_or(fallback); } +// Start each game tick shortly before the retrace it waits for, so the controller is read later. +inline bool LateTickStart(bool fallback = false) { + return Get().lateTickStart.value_or(fallback); +} + inline bool TextureReplacements(bool fallback = false) { return Get().textureReplacements.value_or(fallback); } diff --git a/runtime/src/hle/gx/gx_stubs.cpp b/runtime/src/hle/gx/gx_stubs.cpp index edbafdc4d..a765b0732 100644 --- a/runtime/src/hle/gx/gx_stubs.cpp +++ b/runtime/src/hle/gx/gx_stubs.cpp @@ -1,5 +1,6 @@ #include "gx_internal.h" #include "runtime_log.h" +#include "hle_stubs.h" extern "C" void __GXSetSUTexRegs(); @@ -46,6 +47,7 @@ extern "C" void GX__FinishInterruptHandler_8016ed94() { PPC_NATIVE_OVERRIDE_VOID(8016ed94, GX__FinishInterruptHandler_8016ed94, (), ()); extern "C" void GX__DrawDone_8016eab0() { + VI_HLE_NoteDrawThread(); GX_SYNC_INLINE(); try { Memory::Write8(kGxDrawDoneFlagAddr, 0); } catch (...) {} GXDrawDone(); GX__FinishInterruptHandler_8016ed94(); diff --git a/runtime/src/hle/os/os_sleep.cpp b/runtime/src/hle/os/os_sleep.cpp index 5a66c029a..aab6d32fa 100644 --- a/runtime/src/hle/os/os_sleep.cpp +++ b/runtime/src/hle/os/os_sleep.cpp @@ -393,6 +393,7 @@ void ReportUnparkableSleep(uint32_t queuePtr, uint32_t thread) extern "C" void OSSleepThread_HLE_801aa9b8(CpuContext* ctx) { CpuContext* cpu = ctx ? ctx : &GetPersistentCpuContext(); + VI_HLE_NoteGuestWait(); const uint32_t queuePtr = cpu->gpr[3]; if (queuePtr == 0) { diff --git a/runtime/src/hle/vi.cpp b/runtime/src/hle/vi.cpp index cd236a977..d9ee965f7 100644 --- a/runtime/src/hle/vi.cpp +++ b/runtime/src/hle/vi.cpp @@ -9,6 +9,7 @@ #include "platform/host_platform.h" #include "runtime_log.h" #include "perf_stats.h" +#include "late_tick_start.h" #include @@ -489,7 +490,8 @@ uint64_t s_lastPresentAnchorNanos = 0; // Sleeps to the same VI retrace boundary VIWaitForRetrace targets, servicing alarms every 1 ms so audio // DMA and timers keep running, then delivers that retrace so guest logic starts exactly on the grid. -void PaceToRetraceBoundary(Clock::time_point deadline) { +// Holds the producer until `deadline` while keeping alarms and audio serviced. +void HoldUntil(Clock::time_point deadline) { constexpr auto kServiceSlice = 1ms; for (;;) { const auto now = Clock::now(); @@ -509,14 +511,71 @@ void PaceToRetraceBoundary(Clock::time_point deadline) { SleepPreciselyUntil(deadline, true, kFinalSpinWindow); break; } +} + +void PaceToRetraceBoundary(Clock::time_point deadline) { + HoldUntil(deadline); VI_HLE_ProcessRetracesDeferred(1); } +std::atomic s_lateTickStart{false}; +std::atomic s_drawThread{0}; +std::mutex s_lateTickMutex; +LateTickStart::WorkMeter s_lateTickWork; +double s_lateTickMissPenaltyMs = 0.0; + +uint64_t SteadyNanos() { + return static_cast( + std::chrono::duration_cast(Clock::now().time_since_epoch()).count()); +} + +uint32_t CurrentGuestThread() { + return Fiber::GuestFiberManager::IsInitialized() ? Fiber::GuestFiberManager::GetCurrentGuestThread() : 0; +} + +// Starts the next tick late enough that its controller read lands shortly before the retrace the +// game will wait for. `intervalNanos`/`retracesElapsed` describe the frame just sealed. +void HoldForLateTickStart(uint64_t intervalNanos, uint32_t retracesElapsed) { + double workP99Ms = 0.0; + bool haveWork = false; + { + std::lock_guard lock(s_lateTickMutex); + s_lateTickMissPenaltyMs = LateTickStart::NextMissPenalty(s_lateTickMissPenaltyMs, retracesElapsed >= 2); + haveWork = s_lateTickWork.P99(workP99Ms); + } + const uint64_t lead = haveWork ? LateTickStart::LeadNanos(workP99Ms, s_lateTickMissPenaltyMs, intervalNanos) : 0; + if (lead == 0) { + return; + } + Clock::time_point nextRetrace; + { + std::lock_guard lock(g_viMutex); + nextRetrace = g_vi.lastRetrace + g_vi.retraceInterval; + } + const auto holdUntil = nextRetrace - std::chrono::nanoseconds(lead); + if (holdUntil > Clock::now()) { + HoldUntil(holdUntil); + } +} + } // namespace // Single owner of the Aurora frame presentation sequence: seals the active frame, optionally paces the // producer to the VI retrace boundary, and pre-warms the next frame. Paced from GXCopyDisp; unpaced for // the retrace-context black/boot present path in AdvanceRetrace. +void VI_HLE_SetLateTickStart(bool enabled) { s_lateTickStart.store(enabled, std::memory_order_relaxed); } + +void VI_HLE_NoteDrawThread() { s_drawThread.store(CurrentGuestThread(), std::memory_order_relaxed); } + +void VI_HLE_NoteGuestWait() { + const uint32_t thread = CurrentGuestThread(); + if (thread == 0 || thread != s_drawThread.load(std::memory_order_relaxed)) { + return; + } + std::lock_guard lock(s_lateTickMutex); + s_lateTickWork.OnWaitStart(SteadyNanos()); +} + void VI_HLE_PresentFrame(bool presentedXfb, bool paceToRetrace) { if (s_presentSequenceActive.exchange(true, std::memory_order_acq_rel)) { return; @@ -526,9 +585,10 @@ void VI_HLE_PresentFrame(bool presentedXfb, bool paceToRetrace) { } sequenceGuard; Clock::time_point paceDeadline{}; bool paceThisFrame = false; + uint64_t intervalNanos = 0; + uint32_t retracesElapsed = 0; if (paceToRetrace) { uint64_t baseNanos = 0; - uint64_t intervalNanos = 0; uint32_t retraceCount = 0; { std::lock_guard lock(g_viMutex); @@ -548,7 +608,7 @@ void VI_HLE_PresentFrame(bool presentedXfb, bool paceToRetrace) { // immediately: hardware would quantize down to the next vblank here, // but free-running late frames matches the previous pacer and keeps a // heavy scene at e.g. 50 fps instead of hard 30. - const uint32_t retracesElapsed = retraceCount - s_lastPacedRetraceCount; + retracesElapsed = retraceCount - s_lastPacedRetraceCount; paceThisFrame = retracesElapsed == 0; s_lastPacedRetraceCount = retraceCount; // aurora_report_producer_paced needs a different signal than the pace-wait above: the guest @@ -585,6 +645,14 @@ void VI_HLE_PresentFrame(bool presentedXfb, bool paceToRetrace) { std::lock_guard lock(g_viMutex); s_lastPacedRetraceCount = g_vi.retraceCount; } + if (paceToRetrace && s_lateTickStart.load(std::memory_order_relaxed)) { + HoldForLateTickStart(intervalNanos, retracesElapsed); + } + { + // The next tick starts here. + std::lock_guard lock(s_lateTickMutex); + s_lateTickWork.OnTickStart(SteadyNanos()); + } settings_overlay::AdvancePresentedFrame(); PerfStats::OnFramePresented(); g_auroraFrameActive.store(false, std::memory_order_release); diff --git a/runtime/src/late_tick_start.cpp b/runtime/src/late_tick_start.cpp new file mode 100644 index 000000000..bdfa0570d --- /dev/null +++ b/runtime/src/late_tick_start.cpp @@ -0,0 +1,50 @@ +#include "late_tick_start.h" + +#include +#include + +namespace LateTickStart { + +uint64_t LeadNanos(double workP99Ms, double missPenaltyMs, uint64_t intervalNanos) { + constexpr double kMarginMs = 2.0; + constexpr uint64_t kFloorNanos = 3'000'000; + constexpr uint64_t kHeadroomNanos = 2'000'000; + if (intervalNanos <= kFloorNanos + kHeadroomNanos) { + return 0; + } + const double leadMs = workP99Ms + missPenaltyMs + kMarginMs; + const uint64_t lead = leadMs > 0.0 ? static_cast(leadMs * 1e6 + 0.5) : 0; + return std::clamp(lead, kFloorNanos, intervalNanos - kHeadroomNanos); +} + +double NextMissPenalty(double currentMs, bool missedRetrace) { + return missedRetrace ? std::min(currentMs + 2.0, 8.0) : std::max(currentMs - 0.05, 0.0); +} + +void WorkMeter::OnTickStart(uint64_t ns) { + m_tickStart = ns; + m_measured = false; +} + +void WorkMeter::OnWaitStart(uint64_t ns) { + if (m_measured || ns < m_tickStart) { + return; + } + m_measured = true; + m_samples[m_write] = static_cast(ns - m_tickStart) / 1e6; + m_write = (m_write + 1) % kWindow; + m_count = std::min(m_count + 1, kWindow); +} + +bool WorkMeter::P99(double& ms) const { + if (m_count < 10) { + return false; + } + double sorted[kWindow]; + std::copy(m_samples, m_samples + m_count, sorted); + std::sort(sorted, sorted + m_count); + ms = sorted[static_cast(std::ceil((m_count - 1) * 0.99))]; + return true; +} + +} // namespace LateTickStart diff --git a/runtime/src/settings_overlay.cpp b/runtime/src/settings_overlay.cpp index 6efe7e31b..e095cfc8a 100644 --- a/runtime/src/settings_overlay.cpp +++ b/runtime/src/settings_overlay.cpp @@ -114,6 +114,7 @@ bool g_skipUnreadyPipelines = RuntimeConfigFile::SkipUnreadyPipelines(true); bool g_vsync = RuntimeConfigFile::Vsync(); bool g_disableCopyFilter = RuntimeConfigFile::DisableCopyFilter(true); bool g_showFps = RuntimeConfigFile::ShowFps(true); +bool g_lateTickStart = RuntimeConfigFile::LateTickStart(false); bool g_forceAspect = RuntimeConfigFile::ForceAspectEnabled(); bool g_widescreen = RuntimeConfigFile::WidescreenEnabled(true); #if defined(__APPLE__) @@ -1290,6 +1291,14 @@ void DrawGraphicsSettings() { if (ImGui::Checkbox("Show FPS", &g_showFps)) { RuntimeConfigFile::SetShowFps(g_showFps); } + if (ImGui::Checkbox("Late tick start (lower input lag)", &g_lateTickStart)) { + VI_HLE_SetLateTickStart(g_lateTickStart); + RuntimeConfigFile::SetLateTickStart(g_lateTickStart); + } + ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + 380.0f); + ImGui::TextDisabled("Starts each game tick just before the game needs your input, so it shows up about " + "12 ms sooner. Turn it off if you see stutter."); + ImGui::PopTextWrapPos(); ImGui::Separator(); ImGui::Text("Graphics API: %s", GraphicsApiDisplayName()); } @@ -1642,6 +1651,7 @@ void InitializeRuntimeSettings() noexcept { g_displayMode = static_cast(aurora_get_display_mode()); aurora_set_disable_copy_filter(g_disableCopyFilter); aurora_set_skip_unready_pipelines(g_skipUnreadyPipelines); + VI_HLE_SetLateTickStart(g_lateTickStart); g_strapInputAccepted.store(false, std::memory_order_relaxed); g_startupDismissFrame.store(UINT64_MAX, std::memory_order_relaxed); g_bootShadersReady.store(false, std::memory_order_relaxed); diff --git a/runtime/tests/late_tick_start_tests.cpp b/runtime/tests/late_tick_start_tests.cpp new file mode 100644 index 000000000..279b9cb7b --- /dev/null +++ b/runtime/tests/late_tick_start_tests.cpp @@ -0,0 +1,96 @@ +#include "late_tick_start.h" + +#include +#include +#include + +namespace { + +int g_failures = 0; +constexpr uint64_t kUs = 1'000; +constexpr uint64_t kMs = 1'000'000; +constexpr uint64_t kInterval = 16'666 * kUs; + +void Check(bool ok, const std::string& what) { + if (!ok) { + std::printf(" FAIL: %s\n", what.c_str()); + ++g_failures; + } +} + +bool Near(double actual, double expected) { return std::abs(actual - expected) < 1e-6; } + +void LeadCoversTheWorkWithAMargin() { + using LateTickStart::LeadNanos; + Check(LeadNanos(1.2, 0.0, kInterval) == 3'200 * kUs, "lead = work + 2 ms"); + Check(LeadNanos(0.1, 0.0, kInterval) == 3'000 * kUs, "lead floor is 3 ms"); + Check(LeadNanos(20.0, 0.0, kInterval) == kInterval - 2'000 * kUs, "lead ceiling is the interval less 2 ms"); + Check(LeadNanos(1.2, 2.0, kInterval) == 5'200 * kUs, "a miss penalty widens the lead"); + Check(LeadNanos(1.0, 0.0, 0) == 0, "no interval, no hold"); +} + +void MissPenaltyGrowsFastAndDecaysSlowly() { + using LateTickStart::NextMissPenalty; + Check(Near(NextMissPenalty(0.0, true), 2.0), "a missed retrace adds 2 ms"); + Check(Near(NextMissPenalty(7.0, true), 8.0), "the penalty stops at 8 ms"); + Check(Near(NextMissPenalty(2.0, false), 1.95), "each frame on time takes 0.05 ms off"); + Check(Near(NextMissPenalty(0.01, false), 0.0), "it never goes negative"); +} + +void MeterTimesTickStartToTheFirstWait() { + LateTickStart::WorkMeter meter; + double p99 = 0.0; + for (uint64_t tick = 0; tick < 9; ++tick) { + const uint64_t start = tick * kInterval; + meter.OnTickStart(start); + meter.OnWaitStart(start + 1 * kMs); + meter.OnWaitStart(start + 9 * kMs); // later waits in the same tick don't count + } + Check(!meter.P99(p99), "fewer than 10 ticks give no estimate"); + meter.OnTickStart(9 * kInterval); + meter.OnWaitStart(9 * kInterval + 1 * kMs); + Check(meter.P99(p99) && Near(p99, 1.0), "ten 1 ms ticks give 1 ms"); +} + +void MeterUsesTheRecentSlowTicks() { + LateTickStart::WorkMeter meter; + double p99 = 0.0; + // 100 ticks: one slow 5 ms tick among 1 ms ones. The window keeps the newest 60. + for (uint64_t tick = 0; tick < 100; ++tick) { + const uint64_t start = tick * kInterval; + meter.OnTickStart(start); + meter.OnWaitStart(start + (tick == 90 ? 5 : 1) * kMs); + } + Check(meter.P99(p99) && Near(p99, 5.0), "a recent slow tick sets the p99"); + for (uint64_t tick = 100; tick < 200; ++tick) { + const uint64_t start = tick * kInterval; + meter.OnTickStart(start); + meter.OnWaitStart(start + 1 * kMs); + } + Check(meter.P99(p99) && Near(p99, 1.0), "it ages out of the window"); +} + +void TickWithoutAWaitIsNotMeasured() { + LateTickStart::WorkMeter meter; + double p99 = 0.0; + for (uint64_t tick = 0; tick < 20; ++tick) { + meter.OnTickStart(tick * kInterval); + } + Check(!meter.P99(p99), "a game that never waits gives no estimate, so nothing is held"); +} + +} // namespace + +int main() { + LeadCoversTheWorkWithAMargin(); + MissPenaltyGrowsFastAndDecaysSlowly(); + MeterTimesTickStartToTheFirstWait(); + MeterUsesTheRecentSlowTicks(); + TickWithoutAWaitIsNotMeasured(); + if (g_failures != 0) { + std::printf("late_tick_start_tests: %d failure(s)\n", g_failures); + return 1; + } + std::printf("late_tick_start_tests: all passed\n"); + return 0; +} From cbbb8c5ed8762214a5323dc60e1403dd9137565e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 17:21:37 +0000 Subject: [PATCH 2/3] Fix macOS build and address review comments - settings_overlay.cpp: include hle_stubs.h for VI_HLE_SetLateTickStart. Windows' unity build picked the declaration up from a neighbouring file; the macOS compile audit builds each file on its own. - os_sleep.cpp: note the drawing thread's wait only once the sleep is accepted. A refused sleep returns to the game's retry loop, so noting it earlier recorded the work as shorter than it was. - vi.cpp: read the retrace interval together with the next retrace, after pacing may have committed a new one (50/60 Hz switch), instead of using the interval from before pacing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VhnFEjD4PRZpc41Fm7dazZ --- runtime/src/hle/os/os_sleep.cpp | 4 +++- runtime/src/hle/vi.cpp | 19 +++++++++++++------ runtime/src/settings_overlay.cpp | 1 + 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/runtime/src/hle/os/os_sleep.cpp b/runtime/src/hle/os/os_sleep.cpp index aab6d32fa..1a6cee19a 100644 --- a/runtime/src/hle/os/os_sleep.cpp +++ b/runtime/src/hle/os/os_sleep.cpp @@ -393,7 +393,6 @@ void ReportUnparkableSleep(uint32_t queuePtr, uint32_t thread) extern "C" void OSSleepThread_HLE_801aa9b8(CpuContext* ctx) { CpuContext* cpu = ctx ? ctx : &GetPersistentCpuContext(); - VI_HLE_NoteGuestWait(); const uint32_t queuePtr = cpu->gpr[3]; if (queuePtr == 0) { @@ -437,6 +436,9 @@ extern "C" void OSSleepThread_HLE_801aa9b8(CpuContext* ctx) return; } + // The sleep goes ahead: late tick start times the drawing thread's work up to here. + VI_HLE_NoteGuestWait(); + // Mark thread as WAITING ::Memory::Write16(currentThread + 0x2C8u, 4); diff --git a/runtime/src/hle/vi.cpp b/runtime/src/hle/vi.cpp index d9ee965f7..2062bb700 100644 --- a/runtime/src/hle/vi.cpp +++ b/runtime/src/hle/vi.cpp @@ -534,8 +534,8 @@ uint32_t CurrentGuestThread() { } // Starts the next tick late enough that its controller read lands shortly before the retrace the -// game will wait for. `intervalNanos`/`retracesElapsed` describe the frame just sealed. -void HoldForLateTickStart(uint64_t intervalNanos, uint32_t retracesElapsed) { +// game will wait for. `retracesElapsed` describes the frame just sealed. +void HoldForLateTickStart(uint32_t retracesElapsed) { double workP99Ms = 0.0; bool haveWork = false; { @@ -543,14 +543,21 @@ void HoldForLateTickStart(uint64_t intervalNanos, uint32_t retracesElapsed) { s_lateTickMissPenaltyMs = LateTickStart::NextMissPenalty(s_lateTickMissPenaltyMs, retracesElapsed >= 2); haveWork = s_lateTickWork.P99(workP99Ms); } - const uint64_t lead = haveWork ? LateTickStart::LeadNanos(workP99Ms, s_lateTickMissPenaltyMs, intervalNanos) : 0; - if (lead == 0) { + if (!haveWork) { return; } + // Read after pacing: it may just have committed a new interval (50/60 Hz switch). Clock::time_point nextRetrace; + uint64_t intervalNanos = 0; { std::lock_guard lock(g_viMutex); nextRetrace = g_vi.lastRetrace + g_vi.retraceInterval; + intervalNanos = static_cast( + std::chrono::duration_cast(g_vi.retraceInterval).count()); + } + const uint64_t lead = LateTickStart::LeadNanos(workP99Ms, s_lateTickMissPenaltyMs, intervalNanos); + if (lead == 0) { + return; } const auto holdUntil = nextRetrace - std::chrono::nanoseconds(lead); if (holdUntil > Clock::now()) { @@ -585,10 +592,10 @@ void VI_HLE_PresentFrame(bool presentedXfb, bool paceToRetrace) { } sequenceGuard; Clock::time_point paceDeadline{}; bool paceThisFrame = false; - uint64_t intervalNanos = 0; uint32_t retracesElapsed = 0; if (paceToRetrace) { uint64_t baseNanos = 0; + uint64_t intervalNanos = 0; uint32_t retraceCount = 0; { std::lock_guard lock(g_viMutex); @@ -646,7 +653,7 @@ void VI_HLE_PresentFrame(bool presentedXfb, bool paceToRetrace) { s_lastPacedRetraceCount = g_vi.retraceCount; } if (paceToRetrace && s_lateTickStart.load(std::memory_order_relaxed)) { - HoldForLateTickStart(intervalNanos, retracesElapsed); + HoldForLateTickStart(retracesElapsed); } { // The next tick starts here. diff --git a/runtime/src/settings_overlay.cpp b/runtime/src/settings_overlay.cpp index e095cfc8a..07e077c13 100644 --- a/runtime/src/settings_overlay.cpp +++ b/runtime/src/settings_overlay.cpp @@ -7,6 +7,7 @@ #include "input_bindings.h" #include "motion_trick.h" #include "game_graphics_options.h" +#include "hle_stubs.h" #include "music_attenuation.h" #include "runtime_config.h" #include "runtime_log.h" From 5acbc8ebaa4571de5e55ed1e8b6e0c7886aec419 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 17:29:49 +0000 Subject: [PATCH 3/3] CI: build mkw_late_tick_start_tests in the macOS job The macOS job builds a fixed list of test targets, then runs every registered test. The new test wasn't on the list, so ctest reported it "Not Run" and exited with code 8. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VhnFEjD4PRZpc41Fm7dazZ --- .github/workflows/build.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f0b582342..09c7f6061 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -119,6 +119,7 @@ jobs: mkw_input_expr_tests \ mkw_motion_trick_tests \ mkw_bluetooth_controller_tests \ + mkw_late_tick_start_tests \ mkw_macos_native_compile \ mkw_macos_context_abi_tests \ mkw_macos_host_context_tests \