diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d6433bb..eb35a33 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -11,7 +11,7 @@ jobs: name: MSVC x64 runs-on: windows-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - name: Configure # No -G: CMake picks the newest Visual Studio on the runner image. @@ -21,6 +21,9 @@ jobs: - name: Build run: cmake --build build --config Release + - name: Run anchor regression tests + run: ctest --test-dir build -C Release --output-on-failure + - name: Stage the release layout run: cmake --install build --config Release --prefix stage/RemoteMouseFix-win-x64 @@ -28,7 +31,7 @@ jobs: run: Copy-Item build/bin/Release/MouseLookProbe.exe stage/RemoteMouseFix-win-x64/MouseLookProbe.exe - name: Upload the build output - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: RemoteMouseFix-win-x64 path: stage/RemoteMouseFix-win-x64 diff --git a/CHANGELOG.md b/CHANGELOG.md index 573593e..2e58270 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,20 @@ correction is still experimental. ## [Unreleased] +### Fixed + +- Require repeated, observed game recenter events before intercepting hidden-cursor + mouse input. Hidden/no-warp mode now passes through (MouseLookProbe B). + Recheck each hold and correction-mode change, keep the 16ms timer unchanged. + Regression cases cover no-warp, false-stable cursor and true warp evidence. + +- Relearn a relocated game warp anchor only after repeated unexplained + recenter events; do not trust the former onset-jump/stable-sample shortcut. + On significant relocation, discard queued smoothing movement from the + old coordinate system. Revoke the warp gate after 300 ms of sustained + off-anchor readings to avoid indefinite suppression. +- Add no-warp and recenter-evidence regressions (run in CI). + ### Added - A/B profile enables the optional 250 ms `## TIMING` summary for incoming deltas, diff --git a/CMakeLists.txt b/CMakeLists.txt index 1bfa8c3..cd2357c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -26,6 +26,7 @@ if(CMAKE_SIZEOF_VOID_P AND NOT CMAKE_SIZEOF_VOID_P EQUAL 8) message(FATAL_ERROR "RemoteMouseFix currently supports x64 only (got ${CMAKE_SIZEOF_VOID_P}-byte pointers).") endif() +include(CTest) option(RMF_BUILD_PROBE "Build MouseLookProbe, the stand-in game used to test the correction" ON) configure_file(cmake/Version.h.in "${CMAKE_BINARY_DIR}/generated/rmf/Version.h" @ONLY) @@ -103,6 +104,16 @@ if(RMF_BUILD_PROBE) target_link_libraries(MouseLookProbe PRIVATE user32 gdi32 shell32) endif() +if(BUILD_TESTING) + add_executable(RecentWarpAnchorTests tests/RecentWarpAnchorTests.cpp) + rmf_apply_common_settings(RecentWarpAnchorTests) + add_test(NAME RecentWarpAnchorTests COMMAND RecentWarpAnchorTests) + + add_executable(WarpEvidenceTests tests/WarpEvidenceTests.cpp) + rmf_apply_common_settings(WarpEvidenceTests) + add_test(NAME WarpEvidenceTests COMMAND WarpEvidenceTests) +endif() + # What an unpacked release looks like: the two launchers, the programs, README and # LICENSE at the top, everything else in a folder of its own. install(TARGETS RemoteMouseFix InputEchoCheck RUNTIME DESTINATION .) diff --git a/docs/diagnostics.md b/docs/diagnostics.md index 01d5b8a..0780f2b 100644 --- a/docs/diagnostics.md +++ b/docs/diagnostics.md @@ -99,9 +99,11 @@ events, which is why it is polled: - `cursor=HIDDEN` / `SHOWN` bracket the phase in which the game holds the mouse. The game's cursor warp itself uses `SetCursorPos` and is **invisible** in the event stream; it shows up only as `cursor_at` here. -- `anchor-learned` is written when a hidden phase ends and one cursor position clearly - dominated its samples (at least 5 hits and 20%). The anchor is stored as a client offset, - so it follows the window when it moves. +- `warp-evidence confirmed` requires repeated unexplained away-then-back + cursor motion correlated with distinct remote input events. Only then is + `anchor-learned` written and mouse-move suppression armed for that hidden + phase. The anchor is stored as a client offset, so it follows the window. + Without evidence, remote events pass through unchanged. - `clip=CONFINED` means `ClipCursor` is active. WoW 3.3.5a does not use it. - `focus-left-target` names the new foreground process. No input from it is recorded. @@ -302,3 +304,61 @@ to 50 files of 8 MiB in `logs-ab/` and still deletes the oldest matching files. Before repeating tests, copy important captures into a separate folder that does not contain the `remotemousefix-*.log` rotation target. Preserve the raw timestamps, and do not commit session logs to Git. + +## Warp-evidence gate: hidden cursor without recenter (mode B) + +**Safety requirement:** A hidden cursor alone is not sufficient to intercept +remote mouse input. The prior heuristic would suppress every injected move in +MouseLookProbe mode B and then fail the anchor gate: measured 1,661 suppressed +moves, five applied corrections, 1,476 off-anchor timer skips and a maximum +5.48 s pending age. The 16 ms high-resolution timer was not at fault. + +Now the hook passes injected moves through untouched **until** the state +sampler observes multiple unexplained returns to the same interior cursor +point, while a series of distinct remote inputs aims elsewhere. Evidence +must include at least two observed away-then-back transitions, five distinct +remote events, remote travel of at least 60 px and an 80 ms observation span. +Window/desktop edges and locations recently affected by our own SendInput are +excluded. Mere stillness or a jump when the cursor first hides never qualifies. +After a confirmed recenter event, correction may begin for that hold only. +Evidence and permission are reset on hold end, target focus loss or mode change. + +A successful classification logs `## STATE warp-evidence confirmed`. +Without this line, no mouse move should be tagged `DROP` in mode B. +For mode C, expect the line followed by `anchor-learned`, actual +`APPLY` and `OWN` movements, and continued 16 ms smoothing. +This is a conservative heuristic, **not** a direct Win32 notification that a +game called SetCursorPos; if samples cannot establish a warp, the fix +intentionally leaves the input alone. Do not weaken this behavior to make +a missed recenter look like a successful correction. + +Run all Probe modes over TeamViewer with Fix OFF and ON. Confirm mode B has +no suppressed moves and normal free cursor movement and that mode C still +acquires a warp and rotates smoothly. Finish with a WoW Start-Playing.cmd smoke +test and verify emergency OFF. These runtime tests are required before merging. + +## Verified-anchor recovery + +If a game changes its recenter position while a hidden-cursor hold is active, +the sampler must **observe new unexplained return events** at the new point. +The same multi-event proof used for initial classification applies again; +an initially hidden cursor, position jump or a stable coordinate alone cannot +authorize an anchor. Candidate positions that coincide with our recent +`SendInput` output are ignored, along with a 160 ms quiet period after output. + +A validated relocation logs `## STATE warp-evidence confirmed` and +`anchor-learned`. If the new client-relative anchor differs from the old +one by more than the configured tolerance, the main message loop discards +smoothing movement queued against the previous anchor and logs +`## SMOOTH RESET reason=anchor-relearned`. The sampler never sends input. + +An anchor classified in one hold is **never reused as proof** in the next +hold. Until genuine recenter behavior is observed again, events pass through. +A temporary loss of correction is safer than suppressing cursor movements +in a game with no warp. If the sampled cursor remains outside an already +verified anchor for more than 300 ms (excluding recent own output), the +classification is revoked, pending movement is discarded, and input passes +through again (`## STATE warp-evidence revoked`). Runtime verification must include moving the WoW +window before the next hold, all Probe A/B/C modes, loss of target focus, +the OFF/relative modes and emergency-off. + diff --git a/include/rmf/MouseHook.h b/include/rmf/MouseHook.h index 7702bdf..1c0f342 100644 --- a/include/rmf/MouseHook.h +++ b/include/rmf/MouseHook.h @@ -28,6 +28,16 @@ class MouseHook { // Learned warp anchor, as an offset inside the target client area so it survives // the window being moved. std::atomic anchorValid {false}; + // Explicitly armed only after multiple observed, unexplained recenter + // events. Hidden cursor without warp MUST pass through (Probe mode B). + std::atomic warpVerified {false}; + + // Single hook writer; odd/even version makes the last external injected + // move an atomic snapshot for the state sampler, without a lock or I/O. + std::atomic remoteVersion {0}; + std::atomic remoteX {0}; + std::atomic remoteY {0}; + std::atomic remoteMs {0}; std::atomic anchorOffsetX {0}; std::atomic anchorOffsetY {0}; }; diff --git a/include/rmf/RecentWarpAnchor.h b/include/rmf/RecentWarpAnchor.h new file mode 100644 index 0000000..5c7b9d8 --- /dev/null +++ b/include/rmf/RecentWarpAnchor.h @@ -0,0 +1,79 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace rmf { + +// Recent sampler readings only. This is NOT proof of a game warp on its own: +// a motionless remote cursor can also produce a stable position. +// Callers must independently establish a cursor-recenter transition. +class RecentWarpAnchor { +public: + void Reset() { + count_ = 0; + next_ = 0; + observedOwnCount_ = 0; + } + + // Keep only samples collected during a quiet interval without our SendInput + // output. OWN cursor locations are not independent evidence of a game warp. + // Returns true only when the sample was admitted to the consensus window. + bool Observe(POINT point, std::uint64_t ownCount, POINT lastOwnTarget, + std::uint64_t nowMs, std::uint64_t lastOwnOutputMs) { + const bool outputChanged = ownCount != observedOwnCount_; + observedOwnCount_ = ownCount; + const bool recentlyOutput = lastOwnOutputMs != 0 && + (nowMs < lastOwnOutputMs || nowMs - lastOwnOutputMs < 160); + const bool atOwnTarget = ownCount != 0 && + std::labs(point.x - lastOwnTarget.x) <= 2 && + std::labs(point.y - lastOwnTarget.y) <= 2; + if (outputChanged || recentlyOutput || atOwnTarget) { + ClearSamples(); + return false; + } + Add(point); + return true; + } + + void Add(POINT point) { + samples_[next_] = point; + next_ = (next_ + 1) % samples_.size(); + if (count_ < samples_.size()) ++count_; + } + + bool Stable(POINT& result, unsigned& hits, unsigned& total) const { + hits = 0; + total = static_cast(count_); + if (count_ < 8) return false; + + for (std::size_t i = 0; i < count_; ++i) { + unsigned matches = 0; + for (std::size_t j = 0; j < count_; ++j) { + if (samples_[i].x == samples_[j].x && + samples_[i].y == samples_[j].y) ++matches; + } + if (matches > hits) { + hits = matches; + result = samples_[i]; + } + } + return hits >= 8 && hits * 100u >= total * 75u; + } + +private: + void ClearSamples() { + count_ = 0; + next_ = 0; + } + + std::array samples_ {}; + std::size_t count_ = 0; + std::size_t next_ = 0; + std::uint64_t observedOwnCount_ = 0; +}; + +} // namespace rmf diff --git a/include/rmf/WarpEvidence.h b/include/rmf/WarpEvidence.h new file mode 100644 index 0000000..1dd0843 --- /dev/null +++ b/include/rmf/WarpEvidence.h @@ -0,0 +1,148 @@ +#pragma once + +#include + +#include +#include +#include + +namespace rmf { + +// Only a *repeated unexplained return* toward one interior location constitutes +// evidence that a hidden cursor is being recentered by the game. A hidden or +// motionless cursor alone is not evidence (MouseLookProbe mode B). +struct RemotePointerSample { + POINT point {0, 0}; + std::uint64_t serial = 0; + std::uint64_t tickMs = 0; +}; + +class WarpEvidence { +public: + void Reset() { + candidates_ = {}; + havePrevious_ = false; + observedOwnCount_ = 0; + } + + bool Observe(POINT cursor, RECT client, RECT desktop, RemotePointerSample remote, + std::uint64_t nowMs, std::uint64_t ownCount, + POINT lastOwnTarget, std::uint64_t lastOwnOutputMs, + bool ownOutputInHold, POINT& confirmed, unsigned& returns) { + const bool ownChanged = ownCount != observedOwnCount_; + observedOwnCount_ = ownCount; + const bool recentOwn = ownOutputInHold && lastOwnOutputMs != 0 && + (nowMs < lastOwnOutputMs || nowMs - lastOwnOutputMs < 160); + const bool ownTarget = ownOutputInHold && + Close(cursor, lastOwnTarget, 2); + const bool recentlyRemote = remote.serial != 0 && + remote.tickMs <= nowMs && nowMs - remote.tickMs <= 80; + const bool interior = Inside(cursor, client, 24) && + Inside(cursor, desktop, 24); + + // If our own SendInput might explain this position, the complete + // hypothesis is tainted. Do not resume an old count later. + if (ownChanged || recentOwn || ownTarget) { + ClearCandidates(); + } + + bool verified = false; + if (!ownChanged && !recentOwn && !ownTarget && + recentlyRemote && interior && Far(cursor, remote.point, 45)) { + Candidate* slot = nullptr; + for (Candidate& candidate : candidates_) { + if (candidate.active && nowMs >= candidate.lastMs && + nowMs - candidate.lastMs <= 280 && + Close(candidate.anchor, cursor, 3)) { + slot = &candidate; + break; + } + } + if (!slot) { + for (Candidate& candidate : candidates_) { + if (!candidate.active || nowMs < candidate.lastMs || + nowMs - candidate.lastMs > 280) { + slot = &candidate; + break; + } + } + } + if (!slot) { + slot = &candidates_[0]; + for (Candidate& candidate : candidates_) { + if (candidate.lastMs < slot->lastMs) slot = &candidate; + } + } + const bool same = slot->active && nowMs >= slot->lastMs && + nowMs - slot->lastMs <= 280 && + Close(slot->anchor, cursor, 3); + + if (!same) { + *slot = Candidate{}; + slot->active = true; + slot->anchor = cursor; + slot->firstMs = nowMs; + slot->firstRemote = remote.point; + } + + if (remote.serial != slot->lastSerial) { + slot->lastSerial = remote.serial; + slot->lastMs = nowMs; + ++slot->hits; + if (Far(slot->firstRemote, remote.point, 60)) { + slot->remoteMoved = true; + } + // This is the critical distinction from a stationary cursor: + // we must actually SEE the cursor away from this same point, + // then back while the latest remote input aims elsewhere. + if (havePrevious_ && Far(previousCursor_, slot->anchor, 45)) { + ++slot->returns; + } + if (!slot->reported && slot->hits >= 5 && slot->returns >= 2 && + slot->remoteMoved && nowMs - slot->firstMs >= 80) { + slot->reported = true; + confirmed = slot->anchor; + returns = slot->returns; + verified = true; + } + } + } + + previousCursor_ = cursor; + havePrevious_ = true; + return verified; + } + +private: + struct Candidate { + bool active = false; + bool reported = false; + bool remoteMoved = false; + POINT anchor {0, 0}; + POINT firstRemote {0, 0}; + std::uint64_t firstMs = 0; + std::uint64_t lastMs = 0; + std::uint64_t lastSerial = 0; + unsigned hits = 0; + unsigned returns = 0; + }; + + static bool Close(POINT a, POINT b, long delta) { + return std::labs(a.x - b.x) <= delta && std::labs(a.y - b.y) <= delta; + } + static bool Far(POINT a, POINT b, long delta) { + return std::labs(a.x - b.x) >= delta || std::labs(a.y - b.y) >= delta; + } + static bool Inside(POINT p, RECT rect, long margin) { + return p.x >= rect.left + margin && p.x < rect.right - margin && + p.y >= rect.top + margin && p.y < rect.bottom - margin; + } + void ClearCandidates() { candidates_ = {}; } + + std::array candidates_ {}; + POINT previousCursor_ {0, 0}; + bool havePrevious_ = false; + std::uint64_t observedOwnCount_ = 0; +}; + +} // namespace rmf diff --git a/src/MouseHook.cpp b/src/MouseHook.cpp index 054dfb2..ddb369c 100644 --- a/src/MouseHook.cpp +++ b/src/MouseHook.cpp @@ -106,6 +106,16 @@ LRESULT CALLBACK MouseHook::HookProc(int nCode, WPARAM wParam, LPARAM lParam) { // position is the anchor, not the remote pointer, and would fake a delta. if (kind == EventKind::Move && injected && !own) { if (mode != CorrectionMode::Off && cursorHidden) { + // Observe all remote input BEFORE deciding to withhold it. Until a + // genuine recenter is established the event must reach the game. + filter.remoteVersion.fetch_add(1, std::memory_order_seq_cst); // odd + filter.remoteX.store(info->pt.x, std::memory_order_seq_cst); + filter.remoteY.store(info->pt.y, std::memory_order_seq_cst); + filter.remoteMs.store(GetTickCount64(), std::memory_order_seq_cst); + filter.remoteVersion.fetch_add(1, std::memory_order_seq_cst); // even + } + if (mode != CorrectionMode::Off && cursorHidden && + filter.warpVerified.load(std::memory_order_acquire)) { if (g_tracking.valid) { remoteDx = info->pt.x - g_tracking.last.x; remoteDy = info->pt.y - g_tracking.last.y; diff --git a/src/main.cpp b/src/main.cpp index b9b6092..5a86d7d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -26,6 +26,7 @@ #include "rmf/Logger.h" #include "rmf/MouseHook.h" #include "rmf/ProcessInfo.h" +#include "rmf/WarpEvidence.h" #include "rmf/StateSampler.h" #include "rmf/StatusView.h" #include "rmf/WinCompat.h" @@ -530,22 +531,43 @@ int main() { std::atomic targetInForeground {false}; std::atomic cursorHeldByTarget {false}; - // Sampler thread only. - rmf::AnchorLearner anchorLearner; - bool holdPhaseOpen = false; - RECT holdPhaseClient {0, 0, 0, 0}; - ULONGLONG hiddenSince = 0; + // Sampler thread only. A hidden cursor is NOT proof of a game warp. + rmf::WarpEvidence warpEvidence; + // Relearning changes the reference for outstanding smoothing steps: main thread + // discards the stale backlog before emitting another corrected move. + std::atomic anchorRevision {0}; + // Published only after successful absolute SendInput. Used solely by the + // sampler to exclude our own cursor destinations from warp learning. + std::atomic lastOwnTargetX {0}; + std::atomic lastOwnTargetY {0}; + std::atomic lastOwnOutputMs {0}; + std::uint64_t ownCountAtHoldStart = 0; // sampler thread only + bool holdPhaseOpen = false; + ULONGLONG hiddenSince = 0; + ULONGLONG offAnchorSince = 0; std::uint32_t hiddenGeneration = 0; + const RECT virtualDesktop { + GetSystemMetrics(SM_XVIRTUALSCREEN), + GetSystemMetrics(SM_YVIRTUALSCREEN), + GetSystemMetrics(SM_XVIRTUALSCREEN) + GetSystemMetrics(SM_CXVIRTUALSCREEN), + GetSystemMetrics(SM_YVIRTUALSCREEN) + GetSystemMetrics(SM_CYVIRTUALSCREEN)}; auto publishAnchor = [&](POINT anchor, unsigned hits, unsigned total, RECT client) { const long offsetX = anchor.x - client.left; const long offsetY = anchor.y - client.top; - const bool changed = !filter.anchorValid.load() || - filter.anchorOffsetX.load() != offsetX || - filter.anchorOffsetY.load() != offsetY; - filter.anchorOffsetX.store(offsetX); - filter.anchorOffsetY.store(offsetY); - filter.anchorValid.store(true); + const bool hadAnchor = filter.anchorValid.load(std::memory_order_relaxed); + const long previousX = filter.anchorOffsetX.load(std::memory_order_relaxed); + const long previousY = filter.anchorOffsetY.load(std::memory_order_relaxed); + const bool changed = !hadAnchor || previousX != offsetX || previousY != offsetY; + const bool relocated = hadAnchor && + (std::labs(previousX - offsetX) > cfg.anchorTolerancePx || + std::labs(previousY - offsetY) > cfg.anchorTolerancePx); + // Make the two coordinate stores appear as one valid anchor to the main loop. + filter.anchorValid.store(false, std::memory_order_release); + filter.anchorOffsetX.store(offsetX, std::memory_order_relaxed); + filter.anchorOffsetY.store(offsetY, std::memory_order_relaxed); + filter.anchorValid.store(true, std::memory_order_release); + if (relocated) anchorRevision.fetch_add(1, std::memory_order_release); if (changed && cfg.logStateChanges) { LogLine(Format(L"## STATE anchor-learned=(%ld,%ld) client_offset=(%ld,%ld) hits=%u/%u", anchor.x, anchor.y, offsetX, offsetY, hits, total)); @@ -580,49 +602,122 @@ int main() { LogLine(rmf::FormatStateLine(prev, now, samplerNames.NameForPid(now.foregroundPid))); }, [&](const rmf::StateSampler::Snapshot& now) { - const bool holding = targetInForeground.load() && !now.cursorVisible; + const bool holding = targetInForeground.load(std::memory_order_relaxed) && + !now.cursorVisible; cursorHeldByTarget.store(holding, std::memory_order_relaxed); - if (holding) { - const ULONGLONG tick = GetTickCount64(); - const std::uint32_t generation = correction.generation.load(); - if (!holdPhaseOpen || generation != hiddenGeneration) { - // The watchdog clock starts with the hold, or with the latest mode - // change, so re-enabling during a long hold does not trip at once. - hiddenSince = tick; - hiddenGeneration = generation; + if (!holding) { + if (holdPhaseOpen) { + filter.warpVerified.store(false, std::memory_order_release); + filter.anchorValid.store(false, std::memory_order_release); + warpEvidence.Reset(); + offAnchorSince = 0; + holdPhaseOpen = false; } - holdPhaseOpen = true; - holdPhaseClient = now.clientScreenRect; - anchorLearner.Add(now.cursorPos); - - POINT liveAnchor {}; - unsigned liveHits = 0, liveTotal = 0; - if (!filter.anchorValid.load(std::memory_order_relaxed) && - anchorLearner.Estimate(liveAnchor, liveHits, liveTotal)) { - publishAnchor(liveAnchor, liveHits, liveTotal, now.clientScreenRect); + return; + } + + const ULONGLONG tick = GetTickCount64(); + const std::uint32_t generation = + correction.generation.load(std::memory_order_acquire); + if (!holdPhaseOpen || generation != hiddenGeneration) { + // New hidden hold or new correction mode: never reuse an old + // game's warp classification, even in the same target window. + filter.warpVerified.store(false, std::memory_order_release); + filter.anchorValid.store(false, std::memory_order_release); + warpEvidence.Reset(); + hiddenSince = tick; + offAnchorSince = 0; + hiddenGeneration = generation; + ownCountAtHoldStart = correction.applied.load(std::memory_order_acquire); + } + holdPhaseOpen = true; + + // A seqlock snapshot of the most recent non-own injected move. The + // hook never waits for the sampler, and only writes this telemetry + // while the foreground target holds a hidden cursor. + rmf::RemotePointerSample remote {}; + const auto version1 = filter.remoteVersion.load(std::memory_order_seq_cst); + if ((version1 & 1u) == 0 && version1 != 0) { + const POINT point { + filter.remoteX.load(std::memory_order_seq_cst), + filter.remoteY.load(std::memory_order_seq_cst)}; + const auto remoteMs = filter.remoteMs.load(std::memory_order_seq_cst); + const auto version2 = filter.remoteVersion.load(std::memory_order_seq_cst); + if (version1 == version2 && remoteMs >= hiddenSince) { + remote.point = point; + remote.tickMs = remoteMs; + remote.serial = version2 / 2u; } + } - if (cfg.watchdogMaxHiddenMs > 0 && - correction.Mode() != rmf::CorrectionMode::Off && - tick - hiddenSince > cfg.watchdogMaxHiddenMs) { - tripWatchdog(Format(L"cursor hidden continuously for more than %u ms", - cfg.watchdogMaxHiddenMs)); + const auto ownCount = correction.applied.load(std::memory_order_acquire); + const POINT lastOwnTarget { + lastOwnTargetX.load(std::memory_order_relaxed), + lastOwnTargetY.load(std::memory_order_relaxed)}; + POINT verifiedAnchor {}; + unsigned observedReturns = 0; + if (correction.Mode() != rmf::CorrectionMode::Off && + warpEvidence.Observe( + now.cursorPos, now.clientScreenRect, virtualDesktop, remote, + tick, ownCount, lastOwnTarget, + lastOwnOutputMs.load(std::memory_order_acquire), + ownCount != ownCountAtHoldStart, + verifiedAnchor, observedReturns)) { + const bool wasVerified = + filter.warpVerified.load(std::memory_order_acquire); + if (cfg.logStateChanges) { + LogLine(Format( + L"## STATE warp-evidence confirmed anchor=(%ld,%ld) " + L"returns=%u remote_serial=%llu previous_verified=%ls", + verifiedAnchor.x, verifiedAnchor.y, observedReturns, + static_cast(remote.serial), + wasVerified ? L"yes" : L"no")); } - return; + publishAnchor(verifiedAnchor, observedReturns, observedReturns, + now.clientScreenRect); + filter.warpVerified.store(true, std::memory_order_release); + offAnchorSince = 0; } - if (!holdPhaseOpen) { - return; + // A verified game may stop warping or move its anchor mid-hold. + // Never suppress indefinitely when the actual cursor remains far + // from the learned point with no recent own SendInput explaining it. + if (filter.warpVerified.load(std::memory_order_acquire) && + filter.anchorValid.load(std::memory_order_acquire)) { + const long expectedX = now.clientScreenRect.left + + filter.anchorOffsetX.load(std::memory_order_relaxed); + const long expectedY = now.clientScreenRect.top + + filter.anchorOffsetY.load(std::memory_order_relaxed); + const auto ownMs = lastOwnOutputMs.load(std::memory_order_acquire); + const bool recentOwn = ownCount != ownCountAtHoldStart && + ownMs != 0 && (tick < ownMs || tick - ownMs < 160); + const bool offAnchor = + std::labs(now.cursorPos.x - expectedX) > cfg.anchorTolerancePx || + std::labs(now.cursorPos.y - expectedY) > cfg.anchorTolerancePx; + if (!offAnchor || recentOwn) { + offAnchorSince = 0; + } else if (offAnchorSince == 0) { + offAnchorSince = tick; + } else if (tick - offAnchorSince >= 300) { + filter.warpVerified.store(false, std::memory_order_release); + filter.anchorValid.store(false, std::memory_order_release); + warpEvidence.Reset(); + anchorRevision.fetch_add(1, std::memory_order_release); + offAnchorSince = 0; + if (cfg.logStateChanges) { + LogLine(L"## STATE warp-evidence revoked: off-anchor >300ms; " + L"remote moves now pass through"); + } + } } - holdPhaseOpen = false; - POINT anchor {}; - unsigned hits = 0, total = 0; - if (!anchorLearner.Finish(anchor, hits, total)) { - return; + if (cfg.watchdogMaxHiddenMs > 0 && + correction.Mode() != rmf::CorrectionMode::Off && + tick - hiddenSince > cfg.watchdogMaxHiddenMs) { + tripWatchdog(Format(L"cursor hidden continuously for more than %u ms", + cfg.watchdogMaxHiddenMs)); } - publishAnchor(anchor, hits, total, holdPhaseClient); }); // ---- mode switching (message-loop thread only) ------------------------------------ @@ -637,6 +732,9 @@ int main() { return; } const rmf::CorrectionMode previous = correction.SetMode(target); + // Even an already verified warp must be re-established after a mode change. + // The sampler will also clear the anchor on the next generation transition. + filter.warpVerified.store(false, std::memory_order_release); consecutiveOutputFailures = 0; if (target != rmf::CorrectionMode::Off) { // Switching a mode back on clears the last stop, so the panel stops showing a @@ -896,6 +994,7 @@ int main() { // must stay responsive. It also executes the correction output posted by the hook. long long smoothPendingX = 0; long long smoothPendingY = 0; + std::uint32_t lastAnchorRevision = anchorRevision.load(std::memory_order_acquire); // Opt-in A/B diagnostics. These counters belong to the message-loop thread; the // mouse hook does no additional work and logging is limited to one summary per 250 ms. @@ -953,7 +1052,12 @@ int main() { } if (ok) { - correction.applied.fetch_add(1, std::memory_order_relaxed); + if (mode == rmf::CorrectionMode::Absolute) { + lastOwnTargetX.store(target.x, std::memory_order_relaxed); + lastOwnTargetY.store(target.y, std::memory_order_relaxed); + lastOwnOutputMs.store(GetTickCount64(), std::memory_order_release); + } + correction.applied.fetch_add(1, std::memory_order_release); consecutiveOutputFailures = 0; const std::int64_t pending = correction.pendingEcho.fetch_add(1) + 1; if (pending > static_cast(cfg.watchdogMaxUnechoed)) { @@ -986,9 +1090,22 @@ int main() { break; } + const auto observedRevision = anchorRevision.load(std::memory_order_acquire); + if (observedRevision != lastAnchorRevision) { + lastAnchorRevision = observedRevision; + if (smoothPendingX || smoothPendingY) { + LogLine(Format(L"## SMOOTH RESET reason=anchor-relearned discarded=(%+lld,%+lld)", + smoothPendingX, smoothPendingY)); + } + smoothPendingX = 0; + smoothPendingY = 0; + timingPendingSinceMs = 0; + } + if (msg.message == kMsgApplyDelta) { const rmf::CorrectionMode mode = correction.Mode(); - if (mode == rmf::CorrectionMode::Off) { + if (mode == rmf::CorrectionMode::Off || + !filter.warpVerified.load(std::memory_order_acquire)) { smoothPendingX = 0; smoothPendingY = 0; continue; // switched off after the hook posted: drop quietly @@ -1072,7 +1189,8 @@ int main() { } } if (correction.Mode() != rmf::CorrectionMode::Absolute || - !cursorHeldByTarget.load(std::memory_order_relaxed)) { + !cursorHeldByTarget.load(std::memory_order_relaxed) || + !filter.warpVerified.load(std::memory_order_acquire)) { smoothPendingX = 0; smoothPendingY = 0; continue; diff --git a/tests/RecentWarpAnchorTests.cpp b/tests/RecentWarpAnchorTests.cpp new file mode 100644 index 0000000..e1a55f8 --- /dev/null +++ b/tests/RecentWarpAnchorTests.cpp @@ -0,0 +1,110 @@ +#include "rmf/RecentWarpAnchor.h" + +#include + +namespace { + +POINT At(long x, long y) { return POINT{x, y}; } + +void Check(bool ok) { if (!ok) std::abort(); } + +void TestInsufficientSamples() { + rmf::RecentWarpAnchor tracker; + POINT anchor {}; + unsigned hits = 0, total = 0; + for (int i = 0; i < 7; ++i) tracker.Add(At(380, 330)); + Check(!tracker.Stable(anchor, hits, total)); + Check(total == 7); +} + +void TestStableGameWarp() { + rmf::RecentWarpAnchor tracker; + POINT anchor {}; + unsigned hits = 0, total = 0; + for (int i = 0; i < 9; ++i) tracker.Add(At(380, 330)); + for (int i = 0; i < 3; ++i) tracker.Add(At(390 + i, 335)); + Check(tracker.Stable(anchor, hits, total)); + Check(anchor.x == 380 && anchor.y == 330); + Check(hits == 9 && total == 12); +} + +void TestScatteredRemoteSamplesRejected() { + rmf::RecentWarpAnchor tracker; + POINT anchor {}; + unsigned hits = 0, total = 0; + for (int i = 0; i < 12; ++i) tracker.Add(At(380 + i, 330)); + Check(!tracker.Stable(anchor, hits, total)); +} + +void TestStaleHistoryExpires() { + rmf::RecentWarpAnchor tracker; + POINT anchor {}; + unsigned hits = 0, total = 0; + for (int i = 0; i < 12; ++i) tracker.Add(At(380, 330)); + for (int i = 0; i < 12; ++i) tracker.Add(At(537, 276)); + Check(tracker.Stable(anchor, hits, total)); + Check(anchor.x == 537 && anchor.y == 276); + Check(hits == 12 && total == 12); + tracker.Reset(); + Check(!tracker.Stable(anchor, hits, total)); +} + +void TestOwnCorrectionTargetNeverBecomesAnchor() { + rmf::RecentWarpAnchor tracker; + POINT candidate {}; + unsigned hits = 0, total = 0; + const POINT ownTarget = At(922, 568); // 20 px from the real warp (942,568) + for (std::uint64_t t = 1000; t < 1600; t += 10) { + Check(!tracker.Observe(ownTarget, 1, ownTarget, t, 900)); + } + Check(!tracker.Stable(candidate, hits, total)); +} + +void TestRecentOutputQuarantinesSamples() { + rmf::RecentWarpAnchor tracker; + POINT candidate {}; + unsigned hits = 0, total = 0; + const POINT gameWarp = At(847, 573); + const POINT ownTarget = At(922, 568); + // Even a perfectly stable candidate is rejected while outputs continue. + for (std::uint64_t t = 1000; t < 1150; t += 10) { + Check(!tracker.Observe(gameWarp, 5, ownTarget, t, 1000)); + } + Check(!tracker.Stable(candidate, hits, total)); + // Once the output is quiet, the *different* true recenter may be learned. + for (std::uint64_t t = 1170; t < 1290; t += 10) { + Check(tracker.Observe(gameWarp, 5, ownTarget, t, 1000)); + } + Check(tracker.Stable(candidate, hits, total)); + Check(candidate.x == 847 && candidate.y == 573); +} + +void TestOutputWhileCollectingClearsOldConsensus() { + rmf::RecentWarpAnchor tracker; + POINT candidate {}; + unsigned hits = 0, total = 0; + const POINT gameWarp = At(847, 573); + const POINT ownTarget = At(922, 568); + for (std::uint64_t t = 1200; t < 1270; t += 10) + tracker.Observe(gameWarp, 2, ownTarget, t, 1000); + Check(!tracker.Stable(candidate, hits, total)); + Check(!tracker.Observe(ownTarget, 3, ownTarget, 1270, 1270)); + Check(!tracker.Stable(candidate, hits, total)); + for (std::uint64_t t = 1440; t < 1560; t += 10) + tracker.Observe(gameWarp, 3, ownTarget, t, 1270); + Check(tracker.Stable(candidate, hits, total)); + Check(candidate.x == 847); +} + +} // namespace + +int main() { + TestInsufficientSamples(); + TestStableGameWarp(); + TestScatteredRemoteSamplesRejected(); + TestStaleHistoryExpires(); + TestOwnCorrectionTargetNeverBecomesAnchor(); + TestRecentOutputQuarantinesSamples(); + TestOutputWhileCollectingClearsOldConsensus(); + return 0; +} diff --git a/tests/WarpEvidenceTests.cpp b/tests/WarpEvidenceTests.cpp new file mode 100644 index 0000000..b39fd5d --- /dev/null +++ b/tests/WarpEvidenceTests.cpp @@ -0,0 +1,119 @@ +#include "rmf/WarpEvidence.h" + +#include +#include + +namespace { +constexpr RECT kClient {100, 100, 1100, 800}; +constexpr RECT kScreen {0, 0, 1920, 1080}; + +void Check(bool ok) { if (!ok) std::abort(); } +POINT P(long x, long y) { return POINT{x, y}; } + +bool Step(rmf::WarpEvidence& detector, POINT cursor, POINT remote, unsigned seq, + std::uint64_t ms, std::uint64_t own = 0, + POINT lastOwn = POINT{0, 0}, std::uint64_t lastOwnMs = 0, + bool ownInHold = false) { + POINT verified {}; + unsigned returns = 0; + return detector.Observe(cursor, kClient, kScreen, + rmf::RemotePointerSample{remote, seq, ms}, ms, + own, lastOwn, lastOwnMs, ownInHold, verified, returns); +} + +void TestHiddenNoWarpInputPasses() { + rmf::WarpEvidence detector; + for (unsigned i = 1; i < 200; ++i) { + const POINT cursor = P(300 + static_cast(i * 2), + 300 + static_cast(i % 10)); + Check(!Step(detector, cursor, cursor, i, 1000 + i * 16)); + } +} + +void TestStationaryNoWarpDoesNotProveRecenter() { + rmf::WarpEvidence detector; + // Cursor remains inside the client even as the remote updates. A naive + // 5/5 stable-anchor learner incorrectly accepted this in Probe B. + for (unsigned i = 1; i < 35; ++i) { + Check(!Step(detector, P(500, 450), + P(600 + static_cast(i * 3), 650), + i, 1000 + i * 16)); + } +} + +void TestIntentionalReturnWithRemoteToSamePointDoesNotCount() { + rmf::WarpEvidence detector; + // Moving the cursor back manually is a remote event, NOT a hidden game warp. + for (unsigned i = 1; i < 60; ++i) { + const POINT cursor = i % 2 == 0 ? P(500, 450) : P(700, 450); + Check(!Step(detector, cursor, cursor, i, 1000 + i * 16)); + } +} + +void TestRepeatedUnexplainedWarpArmsGate() { + rmf::WarpEvidence detector; + const POINT anchor = P(500, 450); + Check(!Step(detector, anchor, P(650, 450), 1, 1000)); + Check(!Step(detector, P(660, 450), P(660, 450), 2, 1020)); + Check(!Step(detector, anchor, P(720, 450), 3, 1040)); + Check(!Step(detector, P(730, 450), P(730, 450), 4, 1060)); + Check(!Step(detector, anchor, P(790, 450), 5, 1080)); + Check(!Step(detector, anchor, P(810, 450), 6, 1100)); + Check(Step(detector, anchor, P(850, 450), 7, 1120)); + // Once confirmed, the same candidate isn't announced every sample. + Check(!Step(detector, anchor, P(870, 450), 8, 1140)); +} + +void TestOwnOutputCannotManufactureWarp() { + rmf::WarpEvidence detector; + const POINT anchor = P(500, 450); + for (unsigned i = 1; i <= 50; ++i) { + const POINT c = i % 2 == 0 ? anchor : P(650, 450); + Check(!Step(detector, c, P(900, 450), i, 1000 + i * 16, + i, anchor, 1000 + i * 16, true)); + } +} + +void TestScreenBoundaryDoesNotCount() { + rmf::WarpEvidence detector; + const POINT pinned = P(5, 450); + for (unsigned i = 1; i <= 80; ++i) { + Check(!Step(detector, pinned, P(800 + static_cast(i), 450), + i, 1000 + i * 16)); + } +} + +void TestResetRequiresFreshEvidence() { + rmf::WarpEvidence detector; + const POINT anchor = P(500, 450); + Step(detector, anchor, P(650, 450), 1, 1000); + Step(detector, P(660, 450), P(660, 450), 2, 1020); + Step(detector, anchor, P(720, 450), 3, 1040); + detector.Reset(); + Check(!Step(detector, anchor, P(800, 450), 4, 1060)); + Check(!Step(detector, anchor, P(820, 450), 5, 1080)); + Check(!Step(detector, anchor, P(840, 450), 6, 1100)); +} + +void TestOwnQuietInterval() { + rmf::WarpEvidence detector; + const POINT anchor = P(500, 450); + const POINT ownTarget = P(520, 450); + for (unsigned i = 1; i <= 8; ++i) { + Check(!Step(detector, anchor, P(700 + i * 10, 450), i, + 1000 + i * 16, 3, ownTarget, 1000, true)); + } +} +} // namespace + +int main() { + TestHiddenNoWarpInputPasses(); + TestStationaryNoWarpDoesNotProveRecenter(); + TestIntentionalReturnWithRemoteToSamePointDoesNotCount(); + TestRepeatedUnexplainedWarpArmsGate(); + TestOwnOutputCannotManufactureWarp(); + TestScreenBoundaryDoesNotCount(); + TestResetRequiresFreshEvidence(); + TestOwnQuietInterval(); + return 0; +}