diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index f42a4588..e4c2ab4b 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -6,3 +6,6 @@ d6690f6da8690bdaf79ab898f10e5cee69f6ef07 19f198b4649be95368092085588875d99398ad49 # Put adjacent using-declarations in canonical order 32f98f5a664ecf2bc6f02e3793f917e29052d01d + +# Format the v1.0.16 first-party source and tooling. +09a432f99d30b54e16bb5a7ed029fa8a245df390 diff --git a/CHANGELOG.md b/CHANGELOG.md index d4ef89a4..f8743ebf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,69 @@ # DKR-R changelog +## 1.0.16 + +- Add Speedrunning, ranked verification, replay theatre, prepared ghosts, + automatic splits, overall standings, record history, review and hosted videos. +- Add public lobbies and portal activity. Improve direct inputs, host handover, + spectator recovery and rollback presentation. +- Add independent Cloud Saves, the save indicator and a redesigned Save Manager. +- Add Badge Gallery, compact Play settings and Speedrunning loading transitions. +- Integrate contributor work on custom levels, checkpoint capacity, controllers, + water, road wheels, relay, build tooling and tests. +- Allow rollback self-tests to race a Track Lab course and report the number + of checkpoints loaded. +- See the [release notes](docs/releases/1.0.16/RELEASE-NOTES.txt) for details. + +## 1.0.16 playtest 5 — 2026-11-25 + +- Browse Achievements in the Badge Gallery with search, filters and individual + badge details. +- Use the standard launcher tabs in Save Manager. Progress shows every editing + tool, including the Max Out actions. Files groups transfer and recovery tools. + +## 1.0.16 playtest 4 — 2026-11-25 + +- Put Adventure slots beside the editor in Save Manager for both Vanilla and + Modded saves. Keep Progress, Unlocks, Records and Files in a single workspace. +- Keep Apply Changes and Discard Changes visible while the editor scrolls. + Vanilla and Modded saves keep separate drafts, backups and Cloud Saves slots. + +## 1.0.16 playtest 3 — 2026-11-24 + +- Give Speedrunning Options its own tab under Runs. Arrange related settings + across the available width and show HUD changes over an Ancient Lake + gameplay screenshot. +- Enable Cloud Saves for signed-in players. The Play tab can turn sync on or + off beside the active save. Select the cloud icon to sync and check its status. +- Use the cloud save when devices diverge and keep the replaced copy in local + save history. A device can upload progress made from the current cloud save. +- Refresh Cloud Saves before a new Online lobby chooses its save. Sync again + when returning to the launcher, including hosted progress in an open lobby. +- Show a brief Saving Progress indicator after a game save. Send changes to + cloud-synced saves in the background once the local write succeeds. +- Give Session Mods its own Adventure save and sync it separately from Vanilla. + Existing Adventure progress stays in the Vanilla save. + +## 1.0.16 playtest 1 — 2026-11-17 + +- Bring our online work onto the latest contributor code. Keep the upstream + source layout, cross-platform compatibility checks, relay support, shutdown + fixes, settings work and Track Lab improvements. +- Send racers' inputs directly to one another when that route is available. + Keep the host route for recovery. Spectators stay outside the racing input + path, including in a full lobby with four racers and eight spectators. +- Show a suggested host from measured connections. Let the host offer ownership + to another member without closing the lobby. The new host must accept, and + every member must finish the transfer before the next game starts. Controller + seats and the original online save owner stay the same. +- Keep usable pictures during ordinary rollback corrections and measure input + lateness against forward progress. Auto delay also takes replay cost into + account, to avoid repeatedly removing the delay that a slower machine needs. +- Mark window-matched resolution as recommended. Keep explicit rendering + preferences and the existing launcher layout. +- Keep the Linux Wayland fallback and package closure checks. Fix Windows test + portability for long cache paths, separate temporary drives and path separators. + ## 1.0.15 — 2026-11-08 - Replace the added Player Select footer with native colourful names for selected diff --git a/README.md b/README.md index 38b900dd..147d946a 100644 --- a/README.md +++ b/README.md @@ -4,31 +4,18 @@ [Join our Discord](https://discord.com/invite/AMWfXdBjNP) · [Open the Mod Library](https://positron-portal.com/dkr-r/) · [Downloads](https://github.com/ThatGuyMcd/DKR-R/releases) -## DKR-R v1.0.15 +## DKR-R v1.0.16 -I've spent quite a bit of time working through DKR-R Online since v1.0.14. -This update improves late-input recovery, reduces some of the rollback CPU work -and gives spectators buffered confirmed playback. Hosts can now change the -prediction window and input delay from the lobby or in-game overlay too. +Start a Speedrunning attempt, watch a replay or race a ghost from Play. Browse +public lobbies, suggest a host and hand over the lobby without closing it. +Cloud Saves can sync Vanilla, Modded and Online Adventure independently. +Save Manager keeps slots beside the editor, and Achievements opens the Badge +Gallery. -There's also automatic cleanup for old downloads and caches, a tidier Play page -with Start Game always within reach, and custom character names that fit Player -Select. File dialogs run in a separate helper, and crash reports keep more useful -diagnostic information. The unresolved startup/gameplay crashes are recorded in -the [crash reporting guide](docs/CRASH_REPORTING.md#remaining-crash-investigations). - -Your saves, mods and settings can stay. Use matching complete v1.0.15 packages -on every machine in an online lobby. See the [full release notes](docs/PUBLIC-1.0.15-NOTES.txt) -and [changelog](CHANGELOG.md) for everything since v1.0.14. - -Online waits are reduced, not eliminated. Very slow connections can still run -out of prediction history. The reported missing vanilla online car textures and -other racers' road wheels remain under investigation. Physical Steam Deck Wi-Fi -and separate-machine acceptance remain necessary; see [validation](RELEASE-VALIDATION.md). - -DKR-R is a native static recompilation of Diddy Kong Racing. Bring your own -legally obtained **US v1.0 or US Rev A/v1.1 ROM**. No ROM or extracted game -assets are supplied. +Use matching builds for online play. Bring your own legally obtained +**US v1.0 or US Rev A/v1.1 ROM**. See the [release notes](docs/releases/1.0.16/RELEASE-NOTES.txt), +[documentation index](docs/DOCUMENTATION-1.0.16.md) and +[validation record](RELEASE-VALIDATION.md). ## Get started @@ -51,10 +38,11 @@ There is no bundled revision-conversion data. See [ROM setup](docs/ROM_SETUP.md) ## Play and the overlay **Escape**, **F1** or controller **Back/View** opens the overlay. It uses the same -pages as the launcher. **Play** contains Achievements, Session mods and Save -Manager. Turn Session mods OFF for your next vanilla session without changing -any individual mod selections. Ordinary offline mods still share your personal -Adventure; online and development saves keep separate owners. +pages as the launcher. **Play** contains Achievements, **Speedrunning**, +**Session Mods** and Save Manager. Turn **Session Mods** off to play Vanilla +Adventure or on to play Modded Adventure. Each has its own save slots, balloons +and unlocks. Online and development saves are stored separately. See the +[Speedrunning guide](docs/SPEEDRUNNING.md) and [Saves](docs/SAVES.md). Start Game stays in a compact bar at the bottom while the page scrolls above it. It starts selected when a ROM is ready, and you can move away with the controller @@ -112,8 +100,11 @@ and correction work. Spectators never supply racing inputs; loading and catching up can take longer than the initial 1.5-second playback-buffer target. See [Online](docs/ONLINE_MULTIPLAYER.md), [public lobbies](docs/PUBLIC_LOBBIES.md) -and [spectators](docs/SPECTATORS.md). Gameplay uses the admitted peer transport; -the website handles discovery and accounts. Host migration is not available. +and [spectators](docs/SPECTATORS.md). Gameplay uses the admitted peer transport. +The website handles discovery and accounts. In a supported waiting lobby, the +host can offer ownership to another connected player. Everyone stays in the +lobby once the new host accepts and the transfer completes. If the current host +disconnects before a transfer completes, the lobby closes. ## Free mods and authoring @@ -158,7 +149,7 @@ controls. Saves, ROMs and installed content are kept. See [Storage](docs/STORAGE ## Documentation and contributing -- [All current guides](docs/README.md), [release notes](docs/PUBLIC-1.0.15-NOTES.txt) +- [All current guides](docs/README.md), [release notes](docs/releases/1.0.16/RELEASE-NOTES.txt) and [known limitations/validation](RELEASE-VALIDATION.md). - [Troubleshooting](docs/TROUBLESHOOTING.md), [building](docs/BUILDING.md), [development](docs/DEVELOPMENT.md) and [contributing](CONTRIBUTING.md). diff --git a/RELEASE-VALIDATION.md b/RELEASE-VALIDATION.md index 37d24514..f75502a4 100644 --- a/RELEASE-VALIDATION.md +++ b/RELEASE-VALIDATION.md @@ -1,4 +1,18 @@ -# v1.0.15 release preparation — 8 November 2026 +# Release validation + +## v1.0.16 local review + +The candidate includes the contributor history through upstream commit 669b916 +and the local integration changes. The local release handoff records its exact +commit, build and updater evidence, package hashes and remaining device checks. +Only publish from the approved release commit after the compatibility review, +platform qualification and signature verification are complete. + +The checkpoint contract changed upstream. Verify both US revisions and use +matched v1.0.16 packages to test online. Retest replay verification and Cloud +Saves against isolated test storage before drawing conclusions about this build. + +## v1.0.15 release preparation — 8 November 2026 This records local preparation since the public `Version1.0.14` release at `fbae505f9fe2dae63d3a351aa3a82da2b4e7dae1`. No push, tag, upload, draft or diff --git a/VERSION b/VERSION index a9707166..b668c3b2 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.0.15 +1.0.16 diff --git a/architecture/online-identity-inputs.json b/architecture/online-identity-inputs.json index c982a75b..6e9ca003 100644 --- a/architecture/online-identity-inputs.json +++ b/architecture/online-identity-inputs.json @@ -72,8 +72,8 @@ "reason": "online identity changed to cfc1d8e0d92c" }, "runtime-recomp/guest-hooks/hooks.toml": { - "sha256": "6644a6c981a6c94e64ae462784031a7082c3b70dd4bf1c1d1d78a955ea389d28", - "reason": "Camera payload hooks added to hooks.toml: funcs and owned payload output unchanged, camera kernel output differs only by the road-wheel scope calls" + "sha256": "b0fe0d2efb0dac427a22bbd17ce7c0ec036831592d7bde6f18da36b1f1758dde", + "reason": "online identity changed to cfc1d8e0d92c" }, "runtime-recomp/legacy-character-menu.v77.recomp-fragment.json": { "sha256": "82db39e16f1e30eff1851d74eaf443cd962a2b65517d95f531f4cc0924357ce0", @@ -280,12 +280,12 @@ "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." }, "runtime-recomp/src/game/netplay/experimental_presentation.cpp": { - "sha256": "66c93e26eedbea8826cb15c063b72f5bc507cfe3686736ff4e0c7cec27f4438e", - "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." + "sha256": "43db182ddc6589b23af5582778acf57463d85e647144705f7c89f2a6675401d1", + "reason": "online identity changed to cfc1d8e0d92c" }, "runtime-recomp/src/game/netplay/experimental_presentation.hpp": { - "sha256": "dbd26ed84319448054da4be0f49c277391dee838b40e67f5654f54eb9066c955", - "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." + "sha256": "6752a3cbfd1b6a4635b06377deabb2ffca70500dbc5f567fd244a74c517af6d6", + "reason": "online identity changed to cfc1d8e0d92c" }, "runtime-recomp/src/game/netplay/experimental_process.cpp": { "sha256": "ebbfba4aa3f500c843dcedacb2f15bf605b8c8abe4e9f83224ab5aff6b549a31", @@ -316,8 +316,8 @@ "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." }, "runtime-recomp/src/game/netplay/experimental_runtime.cpp": { - "sha256": "770acd6c9bbe19ca8f3e609ba3a130cc7409e5298fa1237368c59e5a7cb9056d", - "reason": "The self-test's [check][course] line also logs how many checkpoints the race loaded; nothing peers simulate or send changes." + "sha256": "a9028bf0eb17d727e5513310d612bc6e0d056fcdb5b6dd0c2f1c374ac06c562e", + "reason": "PR #195 adds the checkpoint count to the opt-in rollback self-test log. The integrated race simulation and peer protocol are unchanged by that logging." }, "runtime-recomp/src/game/netplay/experimental_runtime.hpp": { "sha256": "e2bd584098e45af7e67b6198f650d18a204d3b57be6bbe3214639e3abe73598c", @@ -384,32 +384,32 @@ "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." }, "runtime-recomp/src/game/party_runtime.cpp": { - "sha256": "0eb45b3483dabebd0e0ae6b98e6fed67ae8593dd5bfdaa40ed899db38893a8fc", - "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." + "sha256": "bc72a11cf8e128929e60184a90f3e028600b28ec005f8501ccdadaf582b0ebeb", + "reason": "online identity changed to cfc1d8e0d92c" }, "runtime-recomp/src/game/party_runtime.hpp": { "sha256": "f71d5b873f71fd24000c43833171967fa40860468f2ee6f50367ac1c1c60b404", "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." }, "runtime-recomp/src/game/runtime_save_routing.cpp": { - "sha256": "837917b9ede8d0f9cadd86edaa325da50c7e88a6c34242758f18228112737890", - "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." + "sha256": "5ff3de1c1cec5b401b5a83348845621690e839922617a44681fc4323c9e0a297", + "reason": "online identity changed to cfc1d8e0d92c" }, "runtime-recomp/src/game/runtime_save_routing.hpp": { - "sha256": "cb3ae802050f29e38def0d42c60c01345be2cc46a515a95e9c50d49a06cf6879", - "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." + "sha256": "ede6f9dbaaefa85a66b795434290d996563380b3292612e33680fe891ff956ea", + "reason": "online identity changed to cfc1d8e0d92c" }, "runtime-recomp/src/game/save_manager.cpp": { - "sha256": "e9f129814e79576fd2369c19734d83aeff04c979068ce2cf204998f3e278f662", - "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." + "sha256": "60d25e04c6448653efb0d5c902106988d32ef14de7a022063afc80f43288d3b3", + "reason": "online identity changed to cfc1d8e0d92c The release formatting pass preserved the source tokens." }, "runtime-recomp/src/game/save_manager.hpp": { - "sha256": "c004fb91343bebc9afb2361f4d4988cd28603ff94830d98daf2f01542053801c", - "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." + "sha256": "937f75bd9c991a6bd1c3e0eb3c14bf05e4f79e9f0df1f496d9463d5b93a12e11", + "reason": "online identity changed to cfc1d8e0d92c The release formatting pass preserved the source tokens." }, "runtime-recomp/src/game/save_storage.hpp": { - "sha256": "ca3a5457b5f7a6341473661e10a662fa590f64bf240053648a4a120a7838bc78", - "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." + "sha256": "927931ba173914c442f62ef4e0bb414538f4b1923e122ea4e2789d91bf2f8702", + "reason": "online identity changed to cfc1d8e0d92c The release formatting pass preserved the source tokens." }, "runtime-recomp/src/game/track_select_draw_guest.h": { "sha256": "053e11b284c433b88b19470534003519ad3d16bc3e625ce4bcc2b5f4f172041e", @@ -499,6 +499,10 @@ "sha256": "e4bf2f3fc699742f73ad2ac84445e0651b480bef53f26675454a7090d91ef7d2", "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." }, + "runtime-recomp/symbols/time_trial_symbols.toml": { + "sha256": "cff8034acdb874dc87e28432e557d98845d72e66d97a6c136106817cdb3a89e2", + "reason": "online identity changed to cfc1d8e0d92c" + }, "runtime-recomp/symbols/title_text_symbols.toml": { "sha256": "e0ae1ea2c67d97949bfc3b51776fa7b874b1fac2d63d5351d2897a8a5103b354", "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." @@ -556,8 +560,8 @@ "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." }, "runtime-recomp/tests/replay_probe/probe_driver.cpp": { - "sha256": "bc027b5aa7fbe082d863be3ace06fc7e89fac76639919abe6d2b546565fabeaa", - "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." + "sha256": "a4940cce66a8fee0169797085c2fc0d391211c8035d4cfa11f68b3c5832b5288", + "reason": "online identity changed to cfc1d8e0d92c" }, "runtime-recomp/tests/replay_probe/probe_driver.hpp": { "sha256": "630fb96603ea6f9d3abc2a6554c63d1acbaa43b5dc741e767df06a2d154660f6", @@ -700,8 +704,8 @@ "reason": "Recorded before per-input reasons existed; earlier reasons are in the git history of this file." }, "scripts/generate_replay_probe.py": { - "sha256": "93cc61c967eb0e854332ca15bd34d5e139bed2a4b673e8b04d953461951d9df1", - "reason": "The boss-finish and shadow hooks apply only to offline funcs payloads and return for frozen online resources or owned bootstrap. The owned hook set is identical to main for both revisions, and probe behavior and recomp policies are unchanged. Track Lab retains the runtime limit of 60 checkpoints." + "sha256": "c3187ba130104c8046625c72dfe3ed360c0241900579f35d5fdcf4c656be3d26", + "reason": "The reviewed native input digest entries admit the existing local Pak save notification and offline replay presentation. The checked ROM-derived payload hashes and inherited checkpoint contract are unchanged by this pin update. Updated the native audit to follow token-identical source formatting." }, "scripts/generate_revision_policy.py": { "sha256": "bafbefad41542e00b6c5ec13b02acde69dda7f48e34025f46d92d028da6427b9", diff --git a/docs/ACHIEVEMENTS.md b/docs/ACHIEVEMENTS.md index 7df5ef8b..83b3a86b 100644 --- a/docs/ACHIEVEMENTS.md +++ b/docs/ACHIEVEMENTS.md @@ -20,6 +20,11 @@ changes status filters. Search has an on-screen keyboard. Settings controls notification position, size, duration, sound and motion. Earned goals show a rounded notification and optional chime. +The Badge Gallery presents your collection in a grid. Search by goal, filter +by category or status, and sort by collection order, recent unlocks or progress. +Open a badge for its criteria and pin it to track the goal. **Settings** contains +notification controls and collection backup and recovery. + ## Progress and existing saves Progress lives in `achievements/progress-v1.json` in your active user-data diff --git a/docs/BUILDING.md b/docs/BUILDING.md index ace28663..be417961 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -1,4 +1,4 @@ -# Building DKR-R v1.0.15 +# Building DKR-R v1.0.16 The tree is the release: the memory, render, scheduler handoff and vehicle repairs, the playtest 4 fixes for mod joining, offline copies, race starts and @@ -7,7 +7,7 @@ vehicles, achievements, texture tools and the SDK/Store/save/presentation work are all source here. `VERSION` and the compiled release value are `1.0.15`. Prepare the ROM-derived inputs (below), then build the tree. -The v1.0.15 build set and exact static checks are in +The release build set and static checks are in [release validation](../RELEASE-VALIDATION.md). Source build commands for Apple remain below; no new Apple package was built in this pass. @@ -85,9 +85,8 @@ local profiles out of source control. ## Release packages [Releasing](RELEASING.md) is the runbook: tag, prepare, `scripts/release/build.py` -per platform, package, evidence, finalize, sign and seal. **Until C5 lands, -`finalize.py` refuses every release from this tree**: 15 of the checks v1.0.11 -required are pending in `scripts/release/required_checks.toml`. +per platform, package, evidence, finalize, sign and seal. The finalizer requires +all checks in the release registry to pass on each desktop target. Keep evidence and new outputs outside the repository. Linux packaging must produce both AppImages; Steam Deck copies the exact x86_64 payload. @@ -216,7 +215,7 @@ check those on an iPhone or iPad before distributing a release. Use the reviewed Linux ARM64 toolchain/sysroot and separate compiled outputs. Compose both normal and owned payloads above, with matching -visual-model inputs, then configure through the v1.0.15 release overlay. +visual-model inputs, then use the Linux release preset with the ARM64 toolchain. The older [ARM recipes](history/ARM-PLATFORM-PREVIEW.md) describe the initial cross-build setup; their preview versions and results stay historical. diff --git a/docs/DOCUMENTATION-1.0.16.md b/docs/DOCUMENTATION-1.0.16.md new file mode 100644 index 00000000..86ec694e --- /dev/null +++ b/docs/DOCUMENTATION-1.0.16.md @@ -0,0 +1,15 @@ +# DKR-R v1.0.16 documentation + +- [Release notes](releases/1.0.16/RELEASE-NOTES.txt) and the + [changelog](../CHANGELOG.md) cover the changes since v1.0.15. +- [Speedrunning](SPEEDRUNNING.md) covers runs, points, splits, replays, ghosts, + Discord linking, reviews and videos. +- [Online](ONLINE_MULTIPLAYER.md), [cross-architecture play](CROSS-ARCHITECTURE.md) + and [Track Lab](CUSTOM_TRACKS.md) cover networking and custom levels. +- [Saves and Cloud Saves](SAVES.md), [Achievements](ACHIEVEMENTS.md) and the + [launcher guide](LAUNCHER.md) explain the new controls. +- [Platforms](PLATFORMS.md), [updates](UPDATES.md), [building](BUILDING.md) + and [releasing](RELEASING.md) cover requirements and recovery. + +The [validation record](../RELEASE-VALIDATION.md) distinguishes automated +checks, emulation and actual-device testing. diff --git a/docs/LAUNCHER.md b/docs/LAUNCHER.md index f1b22f5a..5f56ffae 100644 --- a/docs/LAUNCHER.md +++ b/docs/LAUNCHER.md @@ -17,9 +17,10 @@ in both modes, including Textures and its legacy ROM installation notice. **Ready to race** is centred within its part of the Play card. The save summary has a small three-light indicator: green for Vanilla, amber for Modded and blue for Online. The label says **Using** for the running game and **Next** before -launch. Ordinary offline mods still use your shared personal Adventure; the -amber label says so. Online and isolated development progress use their own -saves, and the preview follows the running save owner. +launch. **Session Mods** selects Vanilla Adventure when off and Modded +Adventure when on. Each has separate progress and its own Cloud Saves slot. +Online and development progress use separate saves. The preview follows the +running save while you play. Use **Sidebar navigation**, just above the divider and Restart button, to choose **LB / RB** or **D-pad**. In D-pad mode, Up and Down change sidebar pages @@ -113,7 +114,7 @@ has Export, Capture and My Dumps tabs; switching tabs does not cancel an active job. See [Textures](TEXTURE_PACKS.md). CRT filters are in **Graphics > HUD & effects**. -**Play > Achievements** shows 94 local goals, filters, pinned goals, +**Play > Achievements** opens the Badge Gallery with 94 local goals, filters, pinned goals, notification settings and progress import/export. It needs no account. See [Achievements](ACHIEVEMENTS.md). @@ -127,6 +128,12 @@ updates and the support summary above the credits. Support actions can open or export logs/crash information; review private paths and lobby details before sharing. Extra Save Location/Connection Details/Reflection Details disclosures have been removed. Detailed instructions live in the repository docs instead. +### Speedrunning + +Open **Speedrunning** from Play. Top Players opens first. **Runs** contains Run, +Replays, My Submitted Runs and Options. Moderators and admins also see Review +Runs. See [Speedrunning](SPEEDRUNNING.md). + ## Page layout and movement Play keeps the ROM controls on the left and the offline launch options on the diff --git a/docs/MOD_LIBRARY_WEBSITE.md b/docs/MOD_LIBRARY_WEBSITE.md index 44db0e7b..a70896d1 100644 --- a/docs/MOD_LIBRARY_WEBSITE.md +++ b/docs/MOD_LIBRARY_WEBSITE.md @@ -15,7 +15,8 @@ Use Python 3.11+ and Node.js 24+ on Windows or Linux. On Windows substitute ```sh npm install --prefix build/library-community-tools --no-save --ignore-scripts --package-lock=false esbuild@0.28.2 jsdom@29.1.1 python3 services/library-workflow/build.py community --output build/library-community-release/stage --baseline build/mod-library-community-20261029/baseline --archive build/library-community-release/DKR-R-website-update.zip -node runtime-recomp/tests/mod_library_community_tests.cjs build/library-workflow-d1-runtime/node_modules/miniflare build/library-community-tools/node_modules/jsdom +npm ci --prefix services/test-tools --ignore-scripts +node runtime-recomp/tests/mod_library_community_tests.cjs services/test-tools/node_modules/miniflare build/library-community-tools/node_modules/jsdom python3 scripts/check.py --suite guard,tooling ``` @@ -87,3 +88,46 @@ and a 60 ms stagger capped after eight groups. Featured mods crossfade every Reduced-motion preferences disable entrances and automatic rotation by default. The companion picker keeps checked inputs mounted while filtering so existing draft/preview serialization includes selections outside the visible results. + +## Online and ranked replay review + +The Online page at `#online` reads `GET /v1/online/public`. The private +directory Worker creates the projection from the same live account leases and +room list as the launcher. This endpoint never forwards a browser credential +or a private room. The browser polls every 30 seconds while visible. A missing +count is shown as unavailable, and an available count of zero is shown as zero. + +The Online card shows currently connected unique accounts against the number +of active accounts that have signed in through the shared library sign-in. +People with several launcher instances count once. Live public lobby, racer +and spectator totals only include publicly listed lobbies. + +Player activity has 7-day, 30-day and All-time views. Each view shows the +peak and days with activity. The recent views also show the busiest hour, new +sign-ups and daily peaks. All time keeps the first timestamp of the lifetime +peak, the total active days and a lifetime history chart. The chart groups peaks by month at first and by year once activity spans more than 12 months. Activity history starts when the directory Worker starts collecting +it. Date buckets are UTC and peak times display in the visitor's time zone. + +Copy a public lobby link and choose **Find lobby from website** under **Public +lobbies** in the updated launcher. The link selects a room from the current +signed-in launcher list. The existing host, compatibility, mod and slot checks +still govern requests to join or spectate. + +Leaderboards at `#leaderboards` use the existing library account. The flow is +**Sign in → attach replay → check the detected event and recorded time → Post +run**. My runs tracks the upload, independent verification and review. Only +published verified PBs count on each board. The website is staged with no +qualified boards or upload access by default. + +The launcher and in-game overlay use the same Leaderboards page. Open it +next to Achievements on Play. Its category tabs, track cards and rankings +read the public website API. Post a run opens the signed-in website flow. +The launcher keeps the last successful catalogue in memory for the session. + +Custom tracks are discovered automatically from the live catalogue, including +newly published releases. A board identifies an exact release and the server +checks the catalogue's verified SHA-256. Publish a new board after qualifying a +new release. Previous eligible versions stay available under their own boards. + +See [Ranked replay review](notes/2026-11-22-ranked-replay-review.md) for the +replay format, open qualification work and checks before opening submissions. diff --git a/docs/ONLINE_MULTIPLAYER.md b/docs/ONLINE_MULTIPLAYER.md index 003ff035..471a552f 100644 --- a/docs/ONLINE_MULTIPLAYER.md +++ b/docs/ONLINE_MULTIPLAYER.md @@ -1,12 +1,13 @@ -# DKR-R Online — v1.0.15 +# DKR-R Online — v1.0.16 Open **DKR-R Online** in the existing launcher. Public/Friends browsing, Private/Public hosting, Discord sign-in and a total online count sit alongside -the existing lobby controls. There is no separate website page to use. +the existing lobby controls. The [public lobby guide](PUBLIC_LOBBIES.md) also +explains discovery and player activity on the portal. Races and minigames support up to four racing ports; Adventure supports two racers. A spectator-capable lobby can also have eight spectators. Everyone -needs a compatible complete v1.0.15 package, supported original ROM revision, +needs a matching complete v1.0.16 package, supported original ROM revision, admitted gameplay rules and verified session mods. Keep `assets` and private workers with the installation. @@ -35,6 +36,14 @@ on several launchers counts once; a crash or sleeping device can remain counted until its lease expires, normally within 60 seconds. **Disconnect Online** removes this instance. See [public lobbies and privacy](PUBLIC_LOBBIES.md). +## Public lobbies and changing host + +The portal shows public lobbies and recorded player activity. Use the lobby's +measurements to compare hosts. The current host offers ownership to a member, +who accepts before the transfer completes. The original Online save owner +and racer seats remain assigned. Racers can exchange live inputs directly +with host-path recovery. A lobby supports four racers and eight spectators. + ## Profile, pictures and friends Open **Online Profile** for your shared display name, picture and account @@ -212,7 +221,11 @@ the previous repeated zero-byte catch-up/start loop is repaired. A spectator leaving does not end the race. Loss of a required racer returns the match safely to the lobby rather than continuing with a missing input -owner. Closing the host closes the room. There is no host migration. +owner. In a lobby with host handover enabled, the host can offer ownership to +another connected player while the room is waiting. The successor must accept +and all connected members must complete the transfer before the next match can +start. The original Online Adventure save stays with its owner. If the current +host leaves or disconnects before the transfer completes, the room closes. If the directory is unavailable, already admitted native peers can still ready, check the connection, start, race, return or leave. Discovery and new diff --git a/docs/PLATFORMS.md b/docs/PLATFORMS.md index aa32e1be..b619d8e1 100644 --- a/docs/PLATFORMS.md +++ b/docs/PLATFORMS.md @@ -1,4 +1,4 @@ -# DKR-R v1.0.15 platforms +# DKR-R v1.0.16 platforms Keep each complete package together, including helpers, assets and notices. The [release validation record](../RELEASE-VALIDATION.md) records what was @@ -6,19 +6,19 @@ actually built, tested under emulation and checked on hardware. | Platform | Release download / status | Requirements and scope | | --- | --- | --- | -| Windows x64 | `DKR-R-1.0.15-Windows-x64.zip` | Windows 10 or newer with a compatible graphics driver. Extract the full ZIP and use its top-level launcher. | -| Linux x86_64 | `DKR-R-1.0.15-Linux-x86_64.AppImage` | Compatible Vulkan driver and the recorded glibc/C++ runtime floors. Make the AppImage executable. | -| Steam Deck | `DKR-R-1.0.15-SteamDeck-x86_64.AppImage` | Identical application payload to Linux x86_64. Test Gaming Mode and Desktop Mode separately. | -| Linux ARM64 | `DKR-R-1.0.15-Linux-aarch64.AppImage` | 64-bit ARM Linux, Vulkan and the recorded system-library floors. QEMU CPU tests do not qualify a physical GPU. | -| macOS Apple Silicon | No v1.0.15 download | Source/host checks remain useful; the integrated Rollback backend is gated on Apple. Older signed/notarised releases retain their original scope. | -| macOS Intel | No v1.0.15 download | Host checks are separate from a complete game build and public packaging qualification. | -| iOS ARM64 | No v1.0.15 download | Device-adapter compilation is separate from a signed, runnable and device-tested IPA. | -| Android ARM64 | No v1.0.15 download | Current Android releases remain unsupported because performance is not good enough across devices. Historical APKs keep their original version/signing identity. | -| Windows ARM64 / 32-bit targets | No qualified v1.0.15 download | A recognised updater platform name does not establish a supported game build. | +| Windows x64 | `DKR-R-1.0.16-Windows-x64.zip` | Windows 10 or newer with a compatible graphics driver. Extract the full ZIP and use its top-level launcher. | +| Linux x86_64 | `DKR-R-1.0.16-Linux-x86_64.AppImage` | Compatible Vulkan driver and the recorded glibc/C++ runtime floors. Make the AppImage executable. | +| Steam Deck | `DKR-R-1.0.16-SteamDeck-x86_64.AppImage` | Identical application payload to Linux x86_64. Test Gaming Mode and Desktop Mode separately. | +| Linux ARM64 | `DKR-R-1.0.16-Linux-aarch64.AppImage` | 64-bit ARM Linux, Vulkan and the recorded system-library floors. QEMU CPU tests do not qualify a physical GPU. | +| macOS Apple Silicon | No v1.0.16 download | Source and host checks are separate from packaging and device acceptance. Older signed/notarised releases retain their original scope. | +| macOS Intel | No v1.0.16 download | Host checks are separate from a complete game build and public packaging qualification. | +| iOS ARM64 | No v1.0.16 download | Device-adapter compilation is separate from a signed, runnable and device-tested IPA. | +| Android ARM64 | No v1.0.16 download | Current Android releases remain unsupported because performance is not good enough across devices. Historical APKs keep their original version/signing identity. | +| Windows ARM64 / 32-bit targets | No qualified v1.0.16 download | A recognised updater platform name does not establish a supported game build. | An AppImage does not replace the system graphics driver, glibc or C++ runtime. -ELF inspection of both final v1.0.15 Linux packages confirms glibc 2.38 and -GLIBCXX_3.4.32 as the required floors, with no missing non-system dependencies. Older +The release pipeline checks both Linux packages for glibc 2.38, +GLIBCXX_3.4.32 and dependency closure. See the validation record for results. Older distributions may need a compatible source build. Required non-system linked libraries are bundled; the desktop/audio/font stack must still be available. @@ -27,7 +27,7 @@ software fallback remains. The log identifies the SDL renderer and, for OpenGL, the rasterizer. llvmpipe/softpipe indicates software graphics; it is not evidence of Steam Deck AMD hardware acceleration. See [launcher performance](TROUBLESHOOTING.md#linux-and-steam-deck-launcher-performance). -Both supported US ROM revisions are linked into the application. Online still +Both supported US ROM revisions are linked into the application. Ranked uploads require an eligible x86_64 client. Online still checks architecture, build, floating-point mode, ROM and session content. Two downloads for different architectures are not a promise of unrestricted cross-play. diff --git a/docs/PUBLIC-1.0.16-playtest.1-NOTES.txt b/docs/PUBLIC-1.0.16-playtest.1-NOTES.txt new file mode 100644 index 00000000..e51857c0 --- /dev/null +++ b/docs/PUBLIC-1.0.16-playtest.1-NOTES.txt @@ -0,0 +1,22 @@ +DKR-R v1.0.16 playtest 1 + +This is a testing build. It brings our latest online work together with the +changes that have landed from other contributors since v1.0.15. + +Racers can send inputs directly to each other, while the host still handles +recovery. Spectators stay outside that input path. You can also offer the host +role to someone else in the lobby without making everyone leave and rejoin. +They have to accept, and the transfer has to finish before starting the game. +Your controller seat and the owner of the online save stay the same. + +There are further changes to online picture handling and Auto input delay to +help with the frame dips we saw on Steam Deck. Please test both a normal session +and a full lobby, and keep the runtime logs if anything goes wrong. + +The launcher layout is unchanged. The contributor work on cross-platform play, +relay connections, shutdown, Track Lab and the rest of the folded source tree +is included. This does not add a new hosted relay service. + +Use matching builds for testing. No release or service update has been published +as part of preparing these files. See docs/notes/2026-11-17-upstream-integration.md +for the exact source and verification record. diff --git a/docs/SAVES.md b/docs/SAVES.md index 6de060b2..b2a47b71 100644 --- a/docs/SAVES.md +++ b/docs/SAVES.md @@ -1,29 +1,54 @@ # Saves and Save Manager -Your normal Adventure now stays with you when you change mods. There is one -personal save with three slots, not a new playthrough for every mod list. -Online and development progress still have their own owners. +## Vanilla and Modded Adventure -## Your personal Adventure +In **Play**, turn **Session Mods** off to play Vanilla Adventure or on to play +Modded Adventure. Each has three Adventure slots with independent balloons, +unlocks and built-in course records. All ordinary offline mod sets share the +same Modded Adventure. Your existing Adventure stays in Vanilla. Modded starts +with empty slots on first use. -Normal play, character mods, custom tracks and ordinary Custom Magic Codes use -the same personal 512-byte EEPROM. Installing a .dkrmap must not change the -stock EEPROM layout. Added-course records are stored in a separate companion -file, so extra tracks cannot shift your initials or balloon totals. +Cloud Saves syncs each Adventure independently. Sign in with the same Discord +account and enable Cloud Saves on both devices. Online Adventure, custom-course +records and Controller Paks have their own sync entries. Older saves under `saves/mods//` are kept for recovery. They are not automatically combined. Open **Save Manager > Backups & Recovery**, inspect the copy you want and confirm the restore. The previous personal save is backed up first. Do not delete the old folders to tidy your profile. +## Automatic Cloud Saves + +Enable **Cloud Saves** beside the active save on Play. Select the cloud status +icon for a manual sync. The client checks the cloud copy before online hosting +and offline play, when returning to the launcher, and after a successful +gameplay save. While a write completes, the game briefly shows **Saving Progress**. + +An upload uses the cloud revision the device last synced from. If the copies +diverge, the cloud copy takes priority and the replaced local image is backed +up under **Backups & Recovery**. The switch controls this device's sync. +Disable it before testing changes in an isolated profile. + ## Save Manager -- **Personal save:** manage the three Adventure slots, shared unlocks and records. +Select a slot from the Adventure list to open its editor. **Progress** shows +initials, balloons, Trophy Races, amulets, keys and course progress. Use +**Max Out This Save** or **Max Out This Slot** at the top of Progress. +**Unlocks** and **Files** sit alongside Progress. **Apply Changes** and +**Discard Changes** stay visible while the editor scrolls. + + +- **Vanilla Save:** manage the Vanilla Adventure slots, progress and unlocks. +- **Modded Save:** manage the Modded Adventure slots, progress and unlocks. - **Edit progress:** choose the intended slot before changing progress. Max Out and unlock actions save after confirmation. Manual edits need Apply Changes. -- **Transfer & Paks:** import/export saves, Controller Paks and supported bundles. +- **Transfer & Paks:** a bundle includes the selected Adventure and any shared + custom-course records and Controller Paks. Import an older bundle from the + Adventure tab where you want its progress to go. +- **Reset Save:** reset the selected Adventure's slots, unlocks and built-in + records. The shared custom-course records and Controller Paks are kept. - **Online:** inspect the host's separate Adventure and choose progress for hosting. -- **Backups & Recovery:** find older mod-set saves, history and recovery copies. +- **Backups & Recovery:** find older saves and choose Vanilla or Modded as the restore destination. - **Development:** tools such as the Dev Menu use isolated development progress. Writes are checked by reading the saved bytes back. A draft opened before @@ -53,8 +78,9 @@ the application. Android uses private app storage; use its export controls. Portable mode takes effect on the next application launch. It selects another location; it does not silently move saves, mods or settings. A config override can also select another profile. Check the selected location before assuming -progress has disappeared. Personal desktop EEPROM is `saves/dkr.us.v77.bin`; -both supported US revisions use the compatible stock layout. +progress has disappeared. Vanilla uses `saves/dkr.us.v77.bin` and Modded +uses `saves/modded/dkr.us.v77.bin`. Both supported US revisions use the +compatible stock EEPROM layout. Back up your data before updating. To recover, export and inspect the surviving copy first, then restore it deliberately. No editor can recreate progress when @@ -75,10 +101,9 @@ gameplay progress. See [Achievements](ACHIEVEMENTS.md) and [Spectators](SPECTATO Open Save Manager from **Play > Save Manager**. The three-light summary in Play describes Vanilla, Modded or Online, with Using for a running session and Next -for the next launch. A modded label does not create a separate offline save: ordinary -offline mods still share personal Adventure. The accepted route is frozen until -the running game/lobby releases it. Session mods changes the next content set -without changing individual selections, copying progress or deleting saves. +for the next launch. The save chosen at launch stays active until the game +or lobby ends. Session Mods changes the save and content for the next offline +launch while preserving your individual mod selections. Save Manager keeps its pending-changes bar against the panel edges while the editor scrolls. Discard and Apply retain their existing backup and conflict diff --git a/docs/SPEEDRUNNING.md b/docs/SPEEDRUNNING.md new file mode 100644 index 00000000..50aee7a8 --- /dev/null +++ b/docs/SPEEDRUNNING.md @@ -0,0 +1,54 @@ +# Speedrunning in DKR-R + +Open **Play > Speedrunning**. **Top Players** shows overall points, published +personal bests and world records. Open a player to see their results or select +**How points work**. **Vanilla Tracks**, **Custom Tracks** and **Full Game** +open the boards. Under **View Times**, the record history shows each holder, +their time and how long the record stood. + +## Race and submit + +Choose **Runs > Run**, then a course, vehicle and racer or a Challenge Run. +Select **Start Run**. The same recording flow supports practice and eligible +leaderboard attempts. You can race offline and keep visual texture packs +enabled. Use your own US v1.0 or US Rev A/v1.1 ROM. + +After finishing, look for **Post to Leaderboard** in Last Run or under +**Runs > Replays**. The action appears for an eligible PB that you have not +submitted. Sign in with Discord to post. A local run can be linked to one +account where the service enables local claims. Downloaded replays remain +credited to their original runner. + +**My Submitted Runs** in the launcher and **My Runs** on the website show +status and submissions left. Each account has 25 submissions in a rolling +24-hour period. A slot reopens 24 hours after that submission. Intake can +also pause while the review queue is full. + +## Challenge Runs and custom courses + +Adventure routes such as Any% begin without a save and trigger the intro. +Tracks Mode categories use a separate completed setup to unlock the required +courses. Each ruleset defines its starting state, splits and finish. Automatic +splits can compare with your PB or the board record. The T.T. Amulet category +excludes wrong warps. + +Practise installed custom courses from Runs. Posting requires the exact +released course and an eligible board for that vehicle. Intake also depends +on the category, verifier and platform. Ranked submissions currently require +an eligible x86_64 client. + +## Replays, ghosts and moderation + +Watch replays in-engine. Use the timeline, frame-step buttons, speed control +and optional controller display. **Runs > Options** changes the overlays and +replay retention. **Race Ghost** records a new attempt with the ghost's racer. +Prepared ghosts can be raced after download. Watching keeps the recorded racer. + +Moderators and admins review verified runs. Launcher reviewers can watch the +in-engine replay while the hosted video renders. Website review needs a playable +video when hosted video review is enabled. The leaderboard host renders the +video. Players can close DKR-R after upload. The website bell shows submission +status changes and unread review items. + +See the [launcher guide](LAUNCHER.md) and +[release notes](releases/1.0.16/RELEASE-NOTES.txt). diff --git a/docs/UPDATES.md b/docs/UPDATES.md index eae280d8..15aca746 100644 --- a/docs/UPDATES.md +++ b/docs/UPDATES.md @@ -1,13 +1,13 @@ # DKR-R updates -## Updating to v1.0.15 +## Updating to v1.0.16 Use **Check for updates** in Play or About DKR-R. Choose **Download update**, then **Install update and restart** after playing. Startup checks can be turned off, a version can be skipped, and beta/playtest releases are optional. Stable releases are the default. A failed check does not stop offline play. -v1.0.15 has Windows x64, Linux x86_64 and Linux ARM64 update packages. Steam +v1.0.16 has Windows x64, Linux x86_64 and Linux ARM64 update packages. Steam Deck uses the Linux x86_64 package. Android, macOS and iOS are excluded from this release. Android releases are no longer supported. Older installations on excluded platforms must not be pointed at a different platform's download. @@ -55,14 +55,13 @@ DKR-R-Updater --recover Recovery checks the signed manifest and the exact recorded backup. It does not search other folders or delete user data. Do not remove the only backup. Older Android/Apple builds retain their own installer and distribution rules; -there is no new APK, app bundle or IPA in the v1.0.15 set. +there is no new APK, app bundle or IPA in the v1.0.16 set. ## Preparing the release update files The exact filenames are **DKR-R-update.json** and **DKR-R-update.sig**. Upload -both beside the final downloads. The stable tag is **Version1.0.15**, and must -match the manifest. The source commit must contain all accepted Patch Pipeline -layers and the final release metadata. +both beside the final downloads. The stable tag is **Version1.0.16**, and must +match the manifest. The source commit must contain the reviewed first-party source, pinned build inputs and final release metadata. The manifest records each package's version, size, SHA256, platform and minimum OS requirements. Windows also has a complete file table and the package's @@ -94,7 +93,7 @@ replacing already published assets. Publishing makes the update discoverable. ## Checks before rollout -Run the updater signing/tooling and native updater tests. Check a v1.0.14 notice, +Run the updater signing/tooling and native updater tests. Check a v1.0.15 notice, download, install and restart on actual Windows/Linux installations, including portable data and Unicode paths. Keep interrupted-download/install recovery, corrupt signatures/packages, locked files, multiple instances, read-only folders diff --git a/docs/notes/2026-11-10-issue-45-wayland.md b/docs/notes/2026-11-10-issue-45-wayland.md new file mode 100644 index 00000000..fb0a2e73 --- /dev/null +++ b/docs/notes/2026-11-10-issue-45-wayland.md @@ -0,0 +1,71 @@ +# Issue #45: missing Wayland client in Linux AppImages + +The original report concerns v1.0.4 on Batocera 43.1. Its follow-up confirms +v1.0.5-beta.12 also fails and that adding Ubuntu Noble's Wayland client resolves +startup. Inspection of the retained published v1.0.15 payload shows the same +omission: cursor/EGL libraries are present, but `libwayland-client.so.0` is not. + +The existing dependency audit classifies the client as a host library, following +the upstream AppImage exclusion list. That makes the missing library an admitted +host requirement rather than a failed packaging check. Upstream excludes it +because an older bundled client can conflict with newer Mesa drivers. Simply +putting an old client into the global library directory would trade one failure +for another. + +The fix installs a private fallback in `usr/lib/dkr-r/wayland-fallback`, refreshes +cursor/EGL from the matching target sysroot and includes the Wayland copyright +notice. The AppRun shell entry probes the cursor dependency with the normal +search path. A resolvable host client stays in use; otherwise the private client +is added. No graphics driver is bundled or replaced. The isolated file-dialog +helper keeps its existing host desktop stack and environment policy. +Only the fallback directory is added to the inherited runtime search path when +needed. Its own RUNPATH resolves bundled dependencies, so this does not expose +every AppImage library globally to host graphics drivers. + +Both the generic shell packager and retained release package pipeline invoke +the shared first-party installer. Static inspection requires the private client, +correct ELF architecture/SONAME, matching AppRun and copyright notice, and rejects +a global client override. Cross packaging requires a target sysroot; it cannot +silently copy the build host's x64 client into an ARM64 package. + +Contributor regressions cover the old omission, architecture/SONAME failures, +sysroot selection, notices, global overrides and escaping source links. Runtime +qualification uses an isolated filesystem containing the actual packaged game +and only explicitly selected host libraries. Its missing-client and host-present +cases distinguish a working fallback from a test accidentally using the build +machine's library. This is not physical Batocera or ARM graphics acceptance. + +The v1.0.15 tag, published downloads and signed updater files remain unchanged. +Local test AppImages reuse the released runtime; only packaging changes. The +fix needs a future release version when distributed publicly. No GitHub issue +comment or closure is part of this local investigation. + +Verification on 10 November 2026: + +- Both final x64 and ARM64 AppImages passed archive readback and the complete + ELF dependency audit. Their game executables and online identities match the + released v1.0.15 payload byte for byte. Dependency floors remain glibc 2.38 + and GLIBCXX 3.4.32. +- In an isolated Linux filesystem without a host Wayland client, the old package + fails with the reported loader error. The corrected AppRun passes the runtime's + Controller Pak round-trip/backup test using the private fallback. Restoring + the host client makes it take priority. Loader traces confirm both choices. +- The final x64 AppImage also extracted and launched itself in that filesystem, + with a real mounted proc filesystem, and passed the same test. ARM64's actual + image payload passed through QEMU with eager symbol binding and the private + fallback. These are loader/CPU checks, not physical GPU acceptance. +- The final x64 image passed US v1.0 manual-launch and US v1.1 skip-launcher + startup checks under Xvfb/software Vulkan, including the manual fade handover. +- Windows host checks passed 173/173. Linux passed 172/173; the regression + harness hit its existing subprocess timeout on the mounted Windows checkout. + Its unchanged 25 cases passed on native Linux storage. The final 12 Wayland + tooling cases passed separately on both Windows and Linux. +- Guard, tooling, metadata, source-asset scans and the applicable pre-commit + checks passed. No protected/generated sources or dependency submodules changed. + +The reporter's Batocera hardware still needs to confirm startup and rendering +with the fixed image before calling that platform accepted. + +Sources: [issue and confirmed workaround](https://github.com/ThatGuyMcd/DKR-R/issues/45#issuecomment-5984441330), +[upstream exclusion and Mesa rationale](https://github.com/AppImageCommunity/pkg2appimage/blob/master/excludelist), +[upstream fallback precedent](https://github.com/musescore/MuseScore/pull/24128). diff --git a/docs/notes/2026-11-14-network-host-handover.md b/docs/notes/2026-11-14-network-host-handover.md new file mode 100644 index 00000000..060de2a2 --- /dev/null +++ b/docs/notes/2026-11-14-network-host-handover.md @@ -0,0 +1,53 @@ +# Networking and host handover work + +This work is on `codex/network-host-handover`, above the issue 45 packaging repair. It has not been published or deployed. + +The implementation adds authenticated direct input paths between racing members. The current host still relays and repairs inputs, and remains the authority for membership, scene transitions and confirmation. Eight spectators remain outside the four-racer input mesh. Introduced peer keys grant input delivery privileges only; the receiver still checks the current controller lease and input owner. + +Planned host handover runs in the waiting lobby, including after returning from a race. It does not provide crash failover or move authority during a live simulation. The candidate must accept. All connected members must prepare the same session snapshot and prove their successor routes before commit. Controller ports remain unchanged. Lost commit acknowledgements hold race start; they never restore the former host after commit. The former host coordinates release and retransmission until everyone has installed the new authority. + +The original persistent save owner stays separate from the networking host. A successor receives the shared online EEPROM, controller Paks and custom records in memory and retains a match-scoped online session bank. It must not replace its personal Adventure or unrelated online save. Pair-key inventory is sent privately to the successor; other members receive only its digest. + +The candidate checks its own local consent, even when acceptance is relayed by the former host. Departed-member pair keys are wiped before constructing another transfer inventory, and clients release their retired introduced routes. Pair encryption counters survive role changes. Private direct-connect invitations are not copied into the directory-code field. + +Connection probes use the realtime input lane. After installing the new role, the successor clears old heartbeat measurements and proves fresh round trips to every racer before acknowledging activation. The old coordinator publishes completion only after that proof. This retains the existing race-start connection check and avoids announcing readiness before an immediate Start request can pass it. + +Optional racer-route recovery is separate from the authority connection. An introduced racer cannot replace the host bootstrap or invitation code, and a failing optional route cannot trigger the client's host reconnect. Host changes also need the manual clock reference and shared menu input policy to follow the successor's existing controller port. Ordinary racing input keeps the original controller assignments. A spectator host leaves the game's shared menu controller on the first racing port. + +Public lobby handover also requires an atomic ownership operation on the existing directory. Its account and instance checks must agree with the already admitted native successor. The existing room ID and membership survive the transfer. The directory feature is capability gated, so an older deployed service cannot silently produce a partially transferred public lobby. No new player software or third-party service is required. The matching existing backend update still needs deployment review after preparation and testing. + +## Validation + +- Local exported API, service binding and SQLite Durable Object: 205 checks passed, including four racing slots and eight spectator slots, matching candidate consent, another instance of the same account, altered state digests, repeated commit acknowledgement, sequential handovers, a spectator accepting hosting and the former host leaving. +- The ROM-free host build completed. The full Linux CTest run passed 173 of 174 tests; its regression harness timed out. The same regression harness passed on Windows with native CMake and Git (25 tests, one skipped). Four targeted networking CTests passed after restoring the frozen interfaces. +- Native Windows and Linux tests passed sequential transfers to a racer and then a spectator, with four racing slots and eight spectators, unchanged controller leases and unchanged save ownership. The delayed variant passed with 375 ms delivery delay in each direction, jitter, 200 ms spikes, periodic realtime packet loss and a 128 KiB Pak preserved at every member. These tests use actual DirectSession sockets and encryption with synthetic save data. They do not run a guest ROM. The successor must pass the existing start connection check immediately when completion is reported. The tests then run the actual synchronized countdown after injecting a stale pre-roster start receipt. +- The pattern guard and checksum-pinned-file checks passed. The full Windows guard/tooling suite passed after selecting native CMake and Git. The installed pre-commit checks passed. +- Windows and Linux game builds passed. The disposable-profile qualification hook waits for all twelve members, transfers to the racer on controller port one and starts the normal game afterward. Early actual Quick Join runs exposed missing route aliases, stale start receipts and an immediate Start request racing the new host's heartbeat proof. Each now has a regression test. Normal UI sessions still require the candidate's consent. + +These are local test results, not physical Steam Deck or intercontinental gameplay measurements. Actual nonempty-mod handover followed by another mod download still needs a guest-game check; native transfer tests cover verified cache promotion separately. + +### Actual game qualification + +- R17, paced Quick Join admission: twelve real game processes, four racers and eight spectators, transferred hosting to the second racing port and entered a normal race. All twelve exited successfully. All four racers recorded zero race input-wait time. +- R17, paced admission with 375 ms common receive delay in each direction, 25 ms jitter, 200 ms spikes and periodic realtime/replica loss: all twelve completed. A slow spectator also received 1,000 ms delay and 1,000 ms spikes. Racer input waits were limited to the first roughly 75 race frames; their total measured waits were 35.739, 96.532, 0 and 497.598 ms. These are application-delivery impairments on every route, not measured WAN RTT or a wire shaper. +- R20, simultaneous admission after separating authority recovery: all twelve real Quick Join game processes completed host transfer and racing. All four racers recorded zero race input waits. Its old spectator counter included menu simulation, so it is not used as proof of sustained race playback. +- R21/R23 failed before commit and preserved the original host. Tracing found that an authorized Quick Join reservation could exist without a peer object; renaming that route for the successor then failed. R24 repairs the reservation alias and its release bookkeeping. Native coverage checks alias collisions and repeated reservation release. +- R24 then exposed a descriptor accepted before the new roster arrived. Repeating the descriptor did not refresh the client's cached roster receipt. R26 revalidates the receipt when roster or shared-save identity changes; its native test completes the real countdown after injecting that order of events. +- R27 removes unsent obsolete observer checkpoint chunks and confirmed-frame batches when replacing a spectator transfer. It preserves current-transfer data, other recipients, other games, exact input repair and live controls. Spectators also retain an already approved checkpoint decode when receiving the matching release, instead of requesting the same baseline again. +- R27 Windows burst-admission stress: all twelve processes exited zero after handover and a normal race. Each racer had 375 ms common receive delay, 25 ms jitter, 200 ms spike windows and periodic realtime/replica loss. One spectator had 1,000 ms delay and 1,000 ms spikes. Racing input-wait totals were 0 / 101.286 / 0 / 0 ms; the only nonzero sample was the first race interval, around frame 84. Every later reported interval was zero for all four racers. This is not an absolute zero-wait claim. +- The R27 spectator acceptance check requires at least 300 additional simulated frames between two samples from the actual race epoch. All eight passed the Windows stress run; their observed race deltas ranged from 623 to 800 frames. Earlier runs checked a cumulative menu-plus-race counter and are excluded from this stronger result. +- R27 mixed-platform functional run: a Linux AppImage succeeded the original Windows host, all twelve completed handover, all four entered a race, and all eight spectators advanced by 1,303-1,627 additional race frames. The first report parser rejected an interleaved log token; the saved logs were recovered with numeric-field parsing. All workers recorded clean retirement. The repeat passed with all twelve exit codes zero, no reported rollback failures, and spectator race deltas of 1,298-1,629 frames. Exit codes are saved before parsing the runtime logs. +- The latest full ROM-free Linux host run again passed 173/174 checks, with two child commands timing out in the regression harness under WSL/NTFS. The unchanged regression harness passed its 25 cases (one skipped) on native Windows. Windows guard/tooling and installed pre-commit checks passed. The host-port menu routing policy tests passed for all four possible host ports, shared menus, ordinary racing, unassigned ports and nested construction contexts. + +The mixed-platform run is functional evidence only. WSL's monotonic clock ran about nine percent away from its raw clock and native Windows time. This Codex process had no Administrator token, so the previously authorized VM time-service lease could not be used. No time service was changed or paused. Linux rendering in this fixture uses Xvfb/lavapipe, not Steam Deck hardware. Its timing and frame-rate totals are excluded. + +Both R27 packages passed the full source/binary release packaging audit. Their rollback build IDs agree on Windows and Linux for both supported ROM revisions. They are private test artifacts, not published releases: + +- Windows ZIP SHA-256: `04efe5372c3e09a4dc1b3f3a7a188e32098a038b5a21b4f712de546e2100c7aa`. +- Linux AppImage SHA-256: `2f006943fd61bc3316671ed19fbf1ba2ea35366e4f5525ef7cc6796131e91632`. + +The directory bundle and its 205 checks are prepared locally. It has not been deployed. Public-lobby ownership transfer remains safely unavailable on the old directory until the matching backend is deployed. Private Quick Join handover is covered by the actual-game tests above. No repository changes have been pushed. + +## Steam Deck follow-up + +The source review, captured Deck logs and follow-up repair are recorded in `2026-11-14-steam-deck-online-frame-pacing.md`. The logs show expensive correction and frequent queue rejection with zero recorded input waits. The approved repair is being qualified as v1.0.16 Playtest 1. GPU duration and device power/temperature were not captured, so physical Deck acceptance is still required. diff --git a/docs/notes/2026-11-14-playtest-notes.txt b/docs/notes/2026-11-14-playtest-notes.txt new file mode 100644 index 00000000..895f395d --- /dev/null +++ b/docs/notes/2026-11-14-playtest-notes.txt @@ -0,0 +1,36 @@ +DKR-R v1.0.16 Playtest 1 + +This is a test build for the next online update. Please use the same playtest +on every PC and Steam Deck in the lobby. + +ONLINE FRAME PACING +- Fixed Auto measuring late input against a rewound frame during rollback. +- Auto now considers the cost of correction bursts as well as sustained CPU + load, with separate thresholds for increasing and reducing protective delay. +- Ordinary corrections can keep queued pictures from before the changed frame. + Changed pictures still get rejected, and scene/resource changes keep their + full retirement and GPU completion checks. +- Automatic - match window is marked as the recommended resolution choice. + Existing settings and explicitly selected higher resolutions are preserved. + +HOST HANDOVER AND FULL LOBBIES +- Adds authenticated direct input connections between racers. The host's + existing relay and input repair remain available. +- Hosts can offer ownership to another member while waiting in the lobby, + including after returning from a race. The new host must accept. +- Controller slots and the original online save owner survive the transfer. +- Spectators stay outside the racing input mesh and use buffered playback. +- Fixes route reservations, starting-grid acknowledgements and redundant + spectator checkpoint requests found during full-lobby testing. + +TESTING +This is a playtest, not the final v1.0.16 release. Physical Steam Deck frame +pacing still needs checking with the same mods and settings as the affected +session. Internet latency still affects response time; this build cannot +guarantee zero waits or 60 FPS under every connection and graphics setting. + +Private Quick Join host transfer is included. Public-lobby host transfer also +needs the matching update on the existing lobby directory. That backend update +has not been deployed as part of this local playtest build. + +Nothing in this package includes a game ROM. Existing personal saves are kept. diff --git a/docs/notes/2026-11-14-steam-deck-online-frame-pacing.md b/docs/notes/2026-11-14-steam-deck-online-frame-pacing.md new file mode 100644 index 00000000..a1e40a15 --- /dev/null +++ b/docs/notes/2026-11-14-steam-deck-online-frame-pacing.md @@ -0,0 +1,111 @@ +# Steam Deck online frame-rate investigation + +The report concerns public v1.0.15: a Steam Deck host showed severe frame-rate dips, but audio continued and there were no reported waits for inputs. The owner subsequently confirmed two racers and no spectators. Spectator streaming and twelve-member lobby load therefore cannot explain that particular session. The supplied logs establish the view, resolution and active mods below; power settings remain unconfirmed. This is separate from the earlier standalone launcher software-renderer repair. + +## What the current code does + +The party simulation runs at 30 Hz. The renderer can produce interpolated pictures at a higher rate. Those are different clocks and budgets; a 30 Hz simulation result does not prove 60 FPS presentation. + +Late input can trigger correction without exhausting prediction history. In that case the input-wait counter can stay at zero. The driver restores a retained state, replays the affected ticks, and captures and hashes a checkpoint after each executed tick. The current ordinary vanilla state is about 17 MB. The direct snapshot pool already avoids a second full-state copy and paged-store assembly when the state fits its bounded memory budget. + +`PartyRuntime` publishes a replacement picture only when correction has finished and no scene boundary is pending. This prevents exposing a half-corrected timeline. A correction taking several expensive ticks can therefore hold the last completed image while confirmed audio keeps playing. The renderer's immutable snapshot leases already let ordinary correction proceed without waiting for a GPU drain; that earlier repair must not be removed. Water asset residency also already distinguishes real asset-scene changes from rollback identity, so a correction is not by itself proof that water assets are being rebuilt. + +Replay is serviced in bounded slices, at most four pulses or four milliseconds between ticks. A single guest tick is not preemptible, so a four-millisecond slice limit does not guarantee a four-millisecond maximum correction cost. Automatic input delay already receives executed-step and replay-cost reports. It raises protective input lead under sustained replay pressure and keeps each published input immutable. Increasing lead trades some response latency for less speculative work; increasing prediction history alone does not remove replay cost. + +## Local evidence + +The R27 full-lobby Windows stress run completed with four racers and eight spectators after host transfer. It recorded only one nonzero race input-wait interval, totaling 101.286 ms on one racer; all later reported intervals were zero for every racer. This establishes that the network-wait problem and visible frame pacing must be assessed separately. It does not establish a 60 FPS lock. + +A separate four-process Windows run used the audited R27 runtime, fresh disposable profiles, the actual game, four racers, no spectators, the Modern Vulkan renderer, a requested 60 Hz presentation rate, Automatic input delay and a fourteen-frame prediction window. All four processes exited zero and entered the race. All four reported zero racing network-input wait. The host's last race performance sample recorded 143 corrections and 259 replayed ticks over roughly 1,849 simulation frames, with a largest correction of four frames. The other racers recorded 8-11 corrections. + +One settled host interval recorded approximately 2.36 ms for state capture, 1.79 ms for hashing and 6.83 ms for the guest/audio tick, before the separate picture-publication and renderer work. The party pacing sample recorded an 11.38 ms mean executed-step cost and a 20.39 ms maximum. These are wall-time stage observations with four applications sharing one Windows PC, not Steam Deck measurements or independent additive GPU timings. + +The existing timing reporter can run on both rendering and simulation threads, with separate report windows over shared counters. Their windows overlap. Summing their interval counts would double-count work, so the investigation uses individual intervals rather than claiming aggregate FPS or a CPU percentage from their sum. Presentation intervals are CPU observations and are not a GPU timestamp or physical scanout measurement. + +An additional four-player impaired-delivery profiling attempt did not enter gameplay. Its disposable CLI automation requested Start before all two-way connection proofs were ready, then kept its local `started` flag set after the asynchronous start request was rejected. It never retried. The normal launcher permits another Start attempt. This attempt exited with code 5 and is excluded from frame-rate evidence; it does not demonstrate a gameplay slowdown or override the successful full-lobby handover runs. The automation needs retry-aware state handling before using that entry point for further startup impairment comparisons. + +The mixed Windows/AppImage test is functional evidence only. Its Linux VM clock is skewed and its renderer explicitly uses lavapipe. Neither its FPS nor its software rasterizer says anything about the physical Deck's active driver. + +## Two-racer follow-up + +After the owner confirmed two racers and no spectators, two additional ordinary-startup runs used the same audited R27 Windows binary, one host and one client, no spectators, no mods, Modern Vulkan, My racer fullscreen, a requested 60 Hz refresh rate and a fourteen-frame prediction window. Both members entered a normal race and exited zero in each run, with no reported rollback failure. This is two applications on one Windows GPU, not a physical Deck test or a fresh measurement of the public v1.0.15 binary. + +With normal delivery, both racers recorded zero network-input waiting. The host's final performance report recorded 161 corrections, 480 replayed ticks and a largest correction of four frames over roughly 2,417 race frames. The client recorded zero corrections and zero replayed ticks. Nevertheless, that client's last rendering report had long intervals: approximately 29.89 ms mean display-list processing wall time and 21.59 ms mean presented-frame interval, with a 100 ms histogram upper bound at the 99th percentile. Processing wall time can include waiting and backpressure; it is not a GPU-duration measurement. This is reason to inspect rendering and presentation independently of rollback, not proof of the Deck's bottleneck. + +The impaired run applied 375 ms receive delay, 25 ms jitter, 200 ms spike windows and periodic realtime/replica loss to each member. Logged receive instrumentation verified that the delay was active. These are application-delivery impairments, not measured internet RTT. Host/client whole-race input-wait totals were 753.841 / 607.391 ms, so this run does not meet an absolute zero-wait criterion. The final reported pacing samples had zero input wait. The final host/client correction counts were 155 / 146, with 765 / 405 replayed ticks and largest corrections of 14 / 5 frames. Automatic local input lead ended at 7 / 9 frames. That is a material response-latency trade-off and does not justify increasing delay blindly. + +The impaired run's last presentation intervals averaged about 17.9 / 17.7 ms, with 99th-percentile histogram upper bounds of 66 / 50 ms. These are not locked-60 results. The normal and impaired runs did not follow identical camera positions and trajectories, and share one PC's GPU, so their renderer means must not be presented as an improvement caused by adding latency. + +An earlier two-player warm-up experiment temporarily paused one thread of its own disposable host process while connecting the client. It did not reach a race and recorded a heartbeat disconnect, so it is excluded. Its thread was resumed and both processes retired. The accepted runs above use ordinary process startup without thread suspension. Logs and per-process exit codes for all attempts are retained outside the repository. + +## Captured Deck session, received 14 November + +The owner supplied `dkrr steamdeck logs.zip`. The latest `runtime.log` contains launcher activity only. The last online session is in `runtime-previous.log`, with a ZIP modification time of 14 November at 00:35:58. It contains one two-racer host runtime and multiple scene epochs/races. Earlier history files include older sessions and are not substituted for this one. The archive and extracted raw logs are retained outside the repository. + +The ELF build ID is `5c2394d9a4e89c26d560172e700b2682c6f50217`. It matches the retained public v1.0.15 Linux executable exactly by GNU build ID. Gamescope reports an old `1.0.14` AppImage filename, but the version banner and binary identity identify v1.0.15; the filename alone is not evidence of an old runtime. + +The session used the actual AMD Custom GPU 0405 / RADV VANGOGH Vulkan driver. The standalone launcher also reported accelerated OpenGL with the AMD rasterizer. This was not the earlier launcher software-renderer problem. Gamescope and RT64 requested a 60 Hz presentation rate. + +The internal render size was 1920x1200 and the output window 1600x1000, with scale 5 and downsample 1. Most racing pictures used My racer fullscreen; menus and shared scenes used the shared view. Mods were active, including three code packages. The serialized world was 18,119,892 bytes, and the log confirms the direct full-image checkpoint store was already active: `direct=1`, retaining 398,638,296 bytes within a 398,703,160-byte budget. Reimplementing that earlier optimization would not repair this session. + +There are 393 pacing samples and 388 presentation timing samples. Every pacing sample records zero network-input waiting, zero presentation-drain waiting and zero measured long scheduling gap. That supports the owner's report of no input-wait pauses. It does not prove that the GPU was idle or that the device was never throttled; no GPU-duration, clock, power or temperature trace was supplied. + +Host route RTT samples after owned startup have a median of 142 ms, a 95th percentile of 148 ms and a maximum of 477 ms. The nearby route sample during the worst rendering interval was 141 ms with empty realtime, authority, control and checkpoint queues. That interval does not look like an exhausted input window or a bulk download saturating the link. + +One particularly bad five-second interval in epoch 107 contains: + +| Measurement | Recorded value | +| --- | --- | +| Network-input waiting | 0 microseconds | +| Executed ticks, including replay | 253 | +| Replayed ticks | 104 | +| Time executing replayed ticks | 1,753.443 ms | +| Mean executed-step cost | 13.529 ms | +| Reported presentation rate | 29.77 FPS over 5.005 seconds | +| 95th/99th presentation interval bucket | Above 100 ms | +| Newly tagged pictures | 158 | +| Accepted queued pictures | 76 | +| Rejected queued pictures | 82 | + +The last three numbers are differences between consecutive reports at raw log lines 16604 and 16671. In the renderer report, the field named `retired` is `present_gate::Statistics::rejected`. It counts queue-admission rejection, not ordinary successful resource reclamation. Rejections can include generation retirement, expired leases or slot-identity mismatch; the log does not distinguish all causes. The code's conservative generation invalidation during correction is a concrete candidate for avoidable rejection. It must not be bypassed wholesale. + +The very large percentile number `18446744073709551615` is the histogram's overflow bucket. It means an interval exceeded 100 ms, not an actual multi-century pause. Across the session, 128 presentation reports have a 99th-percentile overflow bucket; nine also have a 95th-percentile overflow bucket. These are repeated visible hitches, not just a low overall average. Other samples, including the final shared scene, return to approximately 60 reported FPS. + +The pacing samples record about 206.6 seconds of replay execution and 10,553 replayed ticks over the session. Five-second samples straddle scene boundaries, so those interval sums should not be equated exactly with each epoch's last cumulative counter. Detailed per-stage rollback profiling was not enabled. The evidence identifies expensive correction and interrupted presentation, but does not split the Deck's replay cost into guest execution, capture and hashing or establish the GPU's share of every slow frame. + +## Reproduced Auto measurement problem + +The source review found a specific timing error. `LiveDelay::pulse` retains a monotonic `clock_frontier_` but also updates `frame_` to the current execution cursor. That cursor moves backwards during correction. `LiveDelay::arrival` measures lateness against `frame_`, so fresh input arriving during replay can be classified as on time even though it is behind the furthest simulated frame. + +A small external diagnostic linked the actual `DKROnlineStabilityCore` and reproduced the calculation without a ROM or networking: + +1. Execute to frame 100 in one epoch. +2. Rewind execution to frame 90. +3. Receive twelve fresh latest-input samples for frame 95. +4. Read the ordinary delay report. + +The report gives twelve samples, zero lateness and zero owner lateness at the 90th percentile. Against the retained live frontier, these samples are five frames late. This is a reproduced undercount in the current calculation. The device log does not expose the individual replay cursor and arrival pair, so it does not prove how many of its samples were affected. + +The current policy also primarily responds to sustained work ratios and reduces protective lead after a short stable interval. The device trace repeatedly shows low/zero configured lead and frequent corrections without input waits. Correcting the lateness reference is a more precise first step than increasing everyone's delay or just increasing prediction history. + +## Repair and validation plan + +1. Measure fresh input lateness against the monotonic simulation frontier in the same epoch. Keep exact historical repairs excluded from fresh jitter measurements. Add regression coverage for input arriving during a rewind, future input, returning to frame zero in a new scene, duplicate/repair batches and per-owner isolation. Do not change packet layout, final input values or the shared simulation clock. +2. Review correction retirement separately from real scene/resource retirement. An immutable queued picture strictly before the first corrected frame can still describe an unaffected past frame. Explore retaining that eligibility while rejecting the corrected frame and all later affected pictures. Preserve full invalidation for resource/scene changes, exact queue-slot identities, GPU completion fences and bounded snapshot storage. Add delayed-consumer and repeated-rewind tests before changing eligibility. +3. Measure correction burst duration as well as sustained replay load before tuning Auto. Aim to prevent repeated catch-up bursts with the smallest necessary per-owner lead. Avoid learning false stability while the driver is rewound, and avoid oscillating between zero lead and repeated corrections. Do not merely redraw a frozen image more often to inflate FPS counters. +4. Verify the Gamescope/window resolution choice and the automatic render-size policy. The observed internal size has 44 percent more pixels than the output window. Offer a clear device/window-native automatic choice while preserving explicitly selected supersampling resolutions. Resolution is an additional load factor here, not a proven sole cause. +5. Requalify unchanged simulation/save results, correction boundaries, two-racer play, four racers plus eight spectators, late packets/loss and the renderer's actual presentation intervals. Build audited Windows and AppImage test packages. The physical Deck must then verify the improvement with the same mods and graphics settings; local desktop/WSL results cannot certify a 60 FPS lock on it. + +The initial investigation reproduced the timing error without changing production behavior. R27 remains the earlier network/host-handover baseline. The approved repair is prepared separately as v1.0.16 Playtest 1. + +## Approved repair + +Fresh arrivals and delay reports now use the monotonic frontier, including while execution is rewound. Exact historical repairs and local input remain excluded from delivery jitter. The existing 96-byte delay protocol is unchanged. Regression checks cover rewind, future input, a new epoch, per-owner samples and repair exclusion. + +Auto estimates forward tick cost from existing reports after subtracting measured replay work. Repeated expensive corrections can raise an owner's protective lead even below the old sustained-work threshold. Separate growth and reduction thresholds retain that protection while correction remains costly. Quiet or inexpensive replay does not by itself request extra delay. This estimates correction pressure; it does not measure GPU duration or promise a fixed rendering rate. + +Ordinary independent CPU correction retains an immutable picture only if it precedes every subsequent affected frame. Invalidated pictures cannot become eligible again after another rewind. Scene/resource retirement still invalidates every picture. Exact queue identities, previously admitted GPU work, epoch retirement and the four-image memory limit remain enforced. The new lifetime records hold weak references, never more image RAM, and do not acquire a last strong reference under the domain lock. + +The presentation implementation is integrated through the existing checked Patch Pipeline and authored `online_presentation` module. The checksum-pinned presentation base files and retained capsule remain unchanged. A staged production-library test passed 48 queue-picture checks, including a consumer delayed at actual admission, repeated corrections, slot-identity rejection and full retirement. Final packaged-game results are separate from this test. + +Window-matched automatic resolution is labelled as recommended. Existing settings and explicit higher resolutions are preserved. Display policy checks cover the captured 1600x1000 output, its old 1920x1200 integer render size, and a native 1280x800 window. diff --git a/docs/notes/2026-11-17-upstream-integration.md b/docs/notes/2026-11-17-upstream-integration.md new file mode 100644 index 00000000..0cc31841 --- /dev/null +++ b/docs/notes/2026-11-17-upstream-integration.md @@ -0,0 +1,126 @@ +# Contributor sync and v1.0.16 playtest + +The integration starts from upstream `adfd02e377d3eba6736a40682d5e3e95422b3560`, +including the 131 commits after the public v1.0.15 tag. The earlier local work +was based on `f1c0c3581e517c720499b15444a0139dc6ea1b70` and an uncommitted tree. +Both are retained in the recovery bundle, along with an exact authored-file +archive. Restoring that backup reproduced all 3,071 recorded file hashes. + +## How the work was combined + +Upstream is the base. None of its commits were reverted or replaced with an +older release layer. Our additional changes live in the maintained first-party +modules, with the old networking changes ported by behavior rather than by +copying an old DirectSession over the new one. + +- Keep upstream's cross-architecture manifest matching, state checks, named + guest hooks, symbol tables and GuestCallContext conversions. +- Keep its relay owner/glue, reliable checkpoint path, deferred session logs, + close/wakeup fixes, TLS changes, settings codecs and Track Lab work. +- Add authenticated direct racer inputs, consented waiting-lobby host handover, + cached-mod promotion and transfer of verified session state. Preserve the + local architecture, original save owner and existing controller leases. +- Version the optional session-links capability. Older local playtests retain + ordinary host delivery and cannot begin the newer handover. +- Keep usable immutable pictures during ordinary correction, without relaxing + scene/resource retirement or the four-image memory limit. Keep replay-cost + protection in Auto delay and use forward progress for late-input samples. +- Keep the existing launcher layout. The rejected resolution-dependent redesign + has not been restored. +- Keep the maintained Wayland wrapper and architecture/closure checks. The old + helper and old first-party build layers have not been restored. + +The shipped v1.0.15 rollback identities remain unchanged. The compatibility +reason is recorded by `scripts/identity_guard.py` in the ordinary input record. +New optional control extensions do not change the simulation input format; +default menu ownership is unchanged. A transferred menu owner is agreed by all +capable members before a new owned world is constructed. + +## Verification and build notes + +The combined Windows host run passed all 214 tests. The final Linux host preset +also configured, built and passed all 214 tests after resuming the paused build. +The installed pre-commit checks passed for the integration changes. A separate native +four-racer/eight-spectator test passed sequential handovers to a racer and a +spectator, including mixed-architecture metadata, preserved seats/save owner, +and a synchronized start. Its impaired run added 375 ms one-way delay, 25 ms +jitter, 200 ms spikes and loss of every 97th disposable packet, and also passed. + +Local directory tests passed 95 ordinary-lobby and 101 running-spectator checks. +The native/profile integration passed 107 checks with synthetic identities. +These tests used no deployed service or real player credentials. + +Windows portability fixes retain the checks: use extended paths for deep cache +fixtures, keep relative executable tests on the interpreter's drive, normalize +schema paths, compare review text with universal newlines, encode the iOS bundle +entry point's executable mode explicitly, and use native paths for the local +esbuild and CMake command construction. CMake warning checks ignore line wraps +caused by different checkout and temporary-directory lengths. + +The clean Linux baseline and the first combined Linux run both exposed the +same regression-harness timeout. Git status on the NTFS source checkout took +23.14 seconds; the test's outer timeout is 20 seconds. Linux verification moves +to a normal Linux checkout instead of increasing or disabling that deadline. + +Both Release builds completed. Windows passed all 243 Release tests, and Linux +passed all 243 in a normal Linux checkout. The prepared-input lock check passed +all ten inputs on both systems against the unchanged upstream lock. The private +generator suite also passed all 53 tests. The cached-mod handover fixture passed +37 checks using the real mod worker, including a fresh download from the promoted +host and rejection of a damaged cache. + +The actual Windows game was tested with twelve separate processes: four racers +and eight spectators. All twelve completed host handover and reached the race. +The ordinary run recorded no racing input waits. The impaired run injected +375 ms of outgoing delivery delay, 25 ms jitter, 200 ms spikes and loss of every +97th disposable packet. The last spectator also had 1,000 ms delay and spikes. +All twelve completed this run too. Each racer recorded 2.38 to 2.66 seconds of +input waiting in the first two race pacing samples, then zero across the next +23 samples. This is injected application delivery delay on one Windows PC, +not twelve physical machines or a measured intercontinental connection. + +An earlier 90-second run ended while the spectators were still receiving the +new scene checkpoint. Diagnostics confirmed that delivery was progressing. +The complete 180-second run passed without changing the admission protocol or +increasing its background bandwidth allowance. That allowance protects racing +traffic, but eight spectators can still take a long time to receive a new scene. +This remains a known limit; passing this test does not mean instant spectator +scene loading or a guaranteed frame rate under every network condition. + +## Testing packages + +The Windows ZIP and x86_64 AppImage are built as `1.0.16-playtest.1`. Their +archive readback checks match every staged file, with no missing or changed +payloads. The package scans passed the version, feature, frozen identity and +private-data checks. Receipts, checksums and test logs stay outside the source +tree in the integration workspace. + +The packaged Windows runtime passed its install-layout check. The actual +AppImage extracted and ran its settings round-trip check successfully. The +Linux library audit inspected 100 ELF files and found no missing dependencies +outside the documented host-library policy. The AppDir closure check also +passed, including the file picker that deliberately uses host GTK libraries. +This AppImage requires glibc 2.38 or newer; its C++ runtime needs GLIBCXX 3.4.32. +These checks do not replace testing the package on a physical Steam Deck. + +## Local checkout and recovery + +The combined branch in `C:/DKRPort` is `codex/upstream-integrated-v1016`. +The original branch is retained as `codex/network-host-handover`, with an extra +preservation ref and a named stash for its uncommitted files. The recovery +bundle and exact file archive remain outside the repository under +`D:/DiddykongWorkFolder/DKR-R-Upstream-Integration-20261117/recovery/`. +All 3,071 recorded file hashes and the original status were checked again +before switching branches; none had changed. + +Old dependency and build caches are preserved under +`C:/DKRPort-pre-integration-20261117/`. The current `extern` directory is a local +junction to the verified pinned checkouts in the integration workspace on D:. +The verified Release build trees are also on D:, rather than reusing the old +build caches. Neither path is a source or release-package dependency for other +users: fresh checkouts use the maintained bootstrap and prepare scripts. + +Nothing has been pushed, published, signed for the updater or deployed. Public +directory ownership transfer remains capability-gated until its matching +service update is deliberately deployed. Physical Steam Deck acceptance is +separate from local Windows/WSL functional testing. diff --git a/docs/notes/2026-11-22-adventure-custom-replay-playtest.md b/docs/notes/2026-11-22-adventure-custom-replay-playtest.md new file mode 100644 index 00000000..96785c93 --- /dev/null +++ b/docs/notes/2026-11-22-adventure-custom-replay-playtest.md @@ -0,0 +1,67 @@ +# Adventure and installed track replay playtest + +## Recording in the launcher + +Select a US v1.1 ROM in Play. Open Leaderboards, choose Full Game, and +select Practice under Any%, 100%, or All Trophy Races. The timer starts +when the fresh Adventure reaches the central hub. It continues through +travel, races, menus and cutscenes after that point. The game checks the +final Wizpig victory, the 100% checklist, or the fourth Adventure gold +cup depending on the category. These sessions start with a blank memory +save and disable the usual game content, Magic Codes and save writes. + +Open Custom Tracks and scroll to Installed tracks to practice a compatible +three-lap, standalone .dkrmap. The session freezes the selected track, +excluding the rest of the local mod collection. The replay identifies the +track by its ID and a digest of the ordered gameplay assets. It loads the +level assigned to that package in the new session. The available vehicles +come from the track's authored header. + +Completed practice runs go in the local speedruns folder. Use the Replay +Theatre for Time Trials. The command-line verifier can check Adventure runs +from a fresh profile. For a custom track, pass its exact .dkrmap directory +with `--track-package`. For a full Adventure run, pass a `--timeout` in +seconds greater than the run's playback duration. + +## Leaderboards + +The launcher and overlay share the website's category order, track search, +world/vehicle/status filters, course-wide rankings, racer and vehicle +filters, lap and race views, pagination, and replay downloads. The launcher +also offers Watch, local practice and Replay Theatre. My runs follows the +signed-in account. Review runs uses the existing moderator API and role +checks. The Windows layout capture covers 1920×1080 and 1280×800. + +## Verification + +The Windows ZIP and Linux AppImage replayed the same Ancient Lake DS car +recording to 4,908 race ticks (1:21.800). Both reproduced the three lap +splits and all five gameplay checkpoints. The verifier rejected a changed +track package before playback and rejected changed inputs in the race. +The sample came from the ordinary installed Track Lab archive. The +automated driver produced the recording and a separate run verified it. + +On Windows, all three Adventure categories reached a fresh hub at update +869 and rejected an unearned finish. The Linux AppImage also reproduced +the Any% start and rejected the unearned finish. The clock matched at +update 1,800, but the gameplay hash varied between runs. A diagnostic +Windows/Linux pair matched when comparing RNG, Adventure state, racer +motion and animation separately. A subsequent run from the delivered +Windows package diverged from a previously measured prefix. That +intermittent divergence blocks ranking before qualification of complete +Adventure runs. + +All 215 host checks, the replay verifier tests and the ranked API tests +passed. The broader tooling check reports the same two Android patch +fixture errors in the integration checkout. + +## Submission gate + +The new formats are local practice formats. The public API and the +production verifier still use the existing qualified Time Trial rules. +A public custom board also needs the native content digest bound to the +published release, retrieval of the exact package by the verifier, and +signed attempt and moderation tests for that release. Battle maps and +legacy patch-based tracks need their own rules. Each Adventure category +needs a complete replay that reaches its genuine objective and repeats +on an independent verifier before enabling uploads. diff --git a/docs/notes/2026-11-22-adventure-rng-qualification.md b/docs/notes/2026-11-22-adventure-rng-qualification.md new file mode 100644 index 00000000..597c6bc6 --- /dev/null +++ b/docs/notes/2026-11-22-adventure-rng-qualification.md @@ -0,0 +1,89 @@ +# Adventure RNG and Time Trial qualification + +The intermittent replay divergence began just after entering a fresh +Adventure hub. Taj's ambience chose random timers based on the audio +channel mask. Wheel effects and visual particle emitters could also draw +from the gameplay stream. Adventure replay ruleset `adventure-us80-3` +uses the existing presentation RNG for those calls. The gameplay +checkpoints still include the gameplay seed, racer motion and Adventure +progress. Earlier practice replays keep their original rules. + +## Hub verification + +Four Windows and four Linux playbacks reached the clean hub at update +869 and independently produced the same gameplay checkpoint at update +1,800. The inputs exercised the opening of all three categories. +The packaged Windows build and Linux AppImage also matched both +checkpoints through 3,600 updates with steering and acceleration after +entering the hub. Both rejected the replay when the input ended before +the objective. The staged submission test rejected those same signed +inputs before moderation. + +Both builds reproduced the existing Ancient Lake car replay. The host +suite passed all 215 tests. The broader tooling suite still reports two +pre-existing Android patch fixture failures. + +## Recording complete qualification runs + +Use a US v1.1 ROM with the Adventure RNG playtest. In the launcher select +**Play → Leaderboards → Full Game**. Select **Practice** in the category +to start with a clean Adventure save. Capture a complete `.dkrreplay` +for each objective. + +- **Any%** ends on the final Wizpig win in Future Fun Land. +- **100%** needs 47 balloons, all four keys, both full amulets and four + gold trophy cups before the final Wizpig win. +- **All Trophy Races** ends after the fourth gold cup in Adventure. + +An independent runtime must reproduce the objective, input checkpoints +and exact finish. Use the staged Worker test with a completed practice +replay. + +```text +node services/online-directory/tests/adventure_ranked_api.cjs BUNDLE RUNTIME ROM PRACTICE_REPLAY +``` + +It issues a local attempt, keeps the recorded controller bytes, reads the +archived replay back, and requires a native engine proof before it can +check moderator approval and the replay download in staging. Without a +replay argument it checks only the API contract. + +Verify each of the same captures independently with the Linux AppImage +using `scripts/verify_time_trial.py` with `--xvfb` and +`--isolate-network`. Compare the finish, clock ticks and every +checkpoint with the proof from Windows. + +Full-game submissions remain closed pending all three completed proofs. + +## Time Trial boards + +Each new board opened after Windows verified a signed replay through all +three laps, rejected altered controls and passed moderator review in +staging. The live-pinned Linux verifier independently reproduced the +finish, lap splits and all gameplay checkpoints. + +| Course | Vehicle | +| --- | --- | +| Ancient Lake | Plane | +| Boulder Canyon | Hovercraft | +| Everfrost Peak | Plane | +| Fossil Canyon DS | Car | +| Frosty Village | Car | +| Greenwood Village | Car | +| Haunted Woods | Car | +| Hot Top Volcano | Hovercraft | +| Pirate Lagoon | Hovercraft | +| Snowball Valley | Car | +| Spacedust Alley | Car | +| Splashdown Pass | Car | +| Star City | Plane | +| Treasure Caves | Car | +| Windmill Plains | Car | + +The public catalogue now has 32 boards. It covers 20 of the 47 retail +course and vehicle combinations, with additional racer boards and three +custom boards. The two new custom boards bind the exact current Mod +Library releases. A new package revision needs its own qualification. +The automated practice +driver did not finish Crescent Island car, Darkmoon Caverns hovercraft, +Spaceport Alpha plane or Walrus Cove car in this pass. diff --git a/docs/notes/2026-11-22-ancient-lake-playtest.md b/docs/notes/2026-11-22-ancient-lake-playtest.md new file mode 100644 index 00000000..facc3223 --- /dev/null +++ b/docs/notes/2026-11-22-ancient-lake-playtest.md @@ -0,0 +1,24 @@ +# Ancient Lake replay playtest + +## Play and watch + +1. Add or select a US v1.1 Game Pak in **Play**. +2. Open **Leaderboards** from the Ready to Race card and keep **Vanilla Tracks** selected. +3. Choose **Practice** to race Ancient Lake with Diddy and the car. The overlay shows the running clock and last lap. Finish all three laps to save a replay. +4. Choose **Watch last replay** for the completed attempt, or **Open replay** to play the supplied `Ancient-Lake.dkrreplay`. Playback starts the real track and feeds the recorded controller inputs into the engine. The launcher displays the result when playback finishes. + +Practice uses a blank, in-memory save and no gameplay mods. Completing or leaving a practice run preserves your normal save and mod selections. Finished runs are stored in the profile's `speedruns` folder. These playtest replays are local practice files, so the public upload form does not accept them. + +## Qualification + +The packaged replay was recorded on Windows x64 using the retail Time Trial timer and the local test driver. It completed in **1:21.666**. The cumulative splits were **0:28.233**, **0:54.966**, and **1:21.666**. Fresh Windows and Linux x86_64 runs reproduced all **2,534** simulation updates, **4,900** race-clock ticks, and all five gameplay and random-state checkpoints. A copy with altered throttle inputs failed at the first checkpoint. A real Steam Deck hardware check is separate from the Linux software-renderer result. + +The replay comprises a bounded manifest and one effective pad sample per simulation update. A pad sample is four bytes, holding the buttons and two stick axes. The game consumes 30 simulation updates per second and scores in 60 Hz units. The initial seed comes from the Time Trial profile. Audio, HUD and other presentation code use their own random stream during the attempt. + +`scripts/verify_time_trial.py` runs the native verifier in a fresh local profile, requires a successful engine finish and reports the input file digest, recomputed clock and checkpoint hashes. It accepts a local runtime and a legally obtained US v1.1 ROM. On Linux, use `--xvfb` to verify with a local virtual display and software Vulkan. + +## Release gates + +The playtest covers Ancient Lake, one vehicle and one racer. The independent verifier covers this rules profile. Public ranking still needs account-bound attempts and native verification connected to the submission queue, followed by the moderation pilot. Other courses, ROM revisions, custom releases and the full-game categories need their own qualification. Replay playback currently runs at normal speed from the start. + +The local API test checks that deleting a runner removes their records immediately and queues the private replay for deletion. It also checks that storage cleanup retries after a failure, and that deleting a moderator preserves other players' published times. diff --git a/docs/notes/2026-11-22-ranked-replay-expansion.md b/docs/notes/2026-11-22-ranked-replay-expansion.md new file mode 100644 index 00000000..6e0d6e81 --- /dev/null +++ b/docs/notes/2026-11-22-ranked-replay-expansion.md @@ -0,0 +1,73 @@ +# Ranked replay expansion + +## Retail Time Trial + +The local launcher can select any of the 20 retail Time Trial courses and +the 47 course and vehicle combinations used by the retail save records. +The recording keeps its selected racer. Ancient Lake in the car retains +its original format and board IDs. Other combinations bind the course and +vehicle into a versioned replay and confirm them against the loaded race. + +A new board requires an independently reproduced race. Verify the same +recording against the Windows build and pinned Linux verifier, compare the +finish, lap splits, input digest and gameplay checkpoints, and confirm that +a replay with altered controls fails. Register a board for its specific +course, vehicle and racer after this check. Returning an attempt ticket from +the API is separate from verifying that player's replay and moderator approval. + +### Local proof + +Windows and the Linux AppImage reproduced the same Fossil Canyon car +fixture: 3,946 updates, 7,724 race-clock ticks (2:08.733), 2,534 best-lap +ticks, three lap splits and seven matching gameplay checkpoints. +The native verifier rejected altered input at checkpoint 600. The local +submission test issued an attempt ticket, queued the authentic recording, +verified it in the Windows package, and confirmed that it appeared on the +leaderboard after staff approval. The published replay matched the submitted +bytes. The expanded Windows package also verified the original Ancient Lake +recording. A separate Ancient Lake hovercraft smoke test confirmed the vehicle +loaded and reached checkpoint 600. Hovercraft needs a full-race proof. + +The packages are local playtests. The public submission service still +accepts the existing Ancient Lake car qualification. + +## Adventure + +Any%, 100% and All Trophy Races need a full-session format. The recorder +must include the inputs consumed in menus, during races and between levels. +Start from an isolated new Adventure save and define the exact timer start +and finish event for each category. Recent checkpoints should include RNG, +game mode, course, player state and Adventure progress from the engine. + +The existing Time Trial input hook skips menu frames. Adventure needs the +regular `input_update` call in the game thread, with the separate boot sample +kept out of the run clock. Capture the exact step rate and verify checkpoints +before and after level loads. + +For Any%, reproduce the final Wizpig victory in Future Fun Land. The retail +boss finish path records it only for first place, and the separate central +island victory cannot count. For 100%, require that victory, the 47 balloons, +the four world keys, both complete amulets and first place in the four cups. +For All Trophy Races, watch the Adventure rankings menu write the fourth +first-place cup. A bronze or silver trophy and a cup won in Tracks mode +cannot count. Derive elapsed time and progress from the clean simulation. + +The verifier now renews the active job claim and advertises its health while +a replay is running. The local API tests confirm renewal, reclaim after +expiry, and rejection of old claims. Full sessions still need a streaming +input format, separate job and archive limits, and isolated playback that +can run while short Time Trials remain eligible for verification. + +## Custom tracks + +Pin each ranked board to the exact track release and a digest of the +simulation content. Independently install that release in a fresh +verifier profile, admit only that track, and derive the map ID after loading +the track. Runtime map IDs for installed custom tracks are local assignments +and can differ across installations. + +Test native racing maps and legacy patch-based tracks separately. Battle maps +have different finish conditions from Time Trial. A locally installed track +with no identical downloadable release needs a way to supply that exact +package to the verifier before it can accept public records. A changed upload +creates a separate qualification for the new release. diff --git a/docs/notes/2026-11-22-ranked-replay-review.md b/docs/notes/2026-11-22-ranked-replay-review.md new file mode 100644 index 00000000..c1524512 --- /dev/null +++ b/docs/notes/2026-11-22-ranked-replay-review.md @@ -0,0 +1,89 @@ +# Ranked replay review + +## What to review + +- **Online** shows the launcher's active-account count and public rooms. Test a + private and a public room and check whether copying a link identifies the + intended room in the launcher. Selecting the room asks for the normal host + approval. +- **Leaderboards** has Vanilla Tracks, Custom Tracks and Full Game. Tracks + appear from the library as soon as the listing has a published release. + Ranked results require a qualified board for that exact version. +- **Post a run** uses the existing library account and attachment flow. The file + fills in the board and recorded time. Submissions and their private replays go + into the same queue whether uploaded in the browser or by an authenticated + client. A queued time has no public rank. +- **My runs** shows submission state and staff feedback. **Review runs** gives + authorised staff the replay and verified time. A reviewer can publish or + reject an independently verified run. The route does not accept a claimed + verifier result from the reviewer or player. + +## Time Trial rules for qualification + +Start with solo offline US Time Trial. Board identity includes the game +engine, rules revision, track, exact release hash where applicable, category +and legal vehicle. Use separate boards for completed races and best laps when +the engine can derive both from a completed run. Start, split, finish and lap +durations come from the guest race clock. + +Use an isolated game profile with the normal retail racer and vehicle for the +board. Other Custom Magic Codes, retail Magic Codes, cheats, dev tools, +save or state injection, macros, scripted inputs and timing adjustments are +disallowed. Reject a run that changes a gameplay setting or pauses the clock +during the attempt. The verifier checks the resulting simulation and allowed +settings. Replaying an input stream cannot establish whether it came from a +person, so human moderation remains part of the workflow. + +The ranked Magic Code must only expose approved timer and run actions. The +runtime owns the locked profile, inputs and eligibility. Graphics choices are +separate from gameplay settings. Qualify each revision, OS and architecture +combination for tick and state parity before combining scores. Pixel comparison +requires a separately fixed renderer, assets, camera, viewport and output +format. + +## Replay and trust boundary + +The preview format starts with ASCII `DKRREPL1` and a little-endian 32-bit +manifest byte length. It then holds a UTF-8 JSON manifest and four bytes per +applied controller tick, with the 16-bit button bitset in little-endian order +and signed X and Y axes. The manifest names the board, engine digest, ruleset, +release digest, ROM revision, platform, architecture, tick count, recorded +race clock, initial RNG seed, ordered splits and state digests at 600-tick +intervals and on the last tick. The browser and API share format validation. +The manifest is untrusted. The one MiB limit applies to the Time Trial preview +format. Full-game runs need a separately qualified larger format. + +Only the independent verifier may set `verified_ticks`, `verifier_digest` +and `verified` after reproducing the run from a trusted clean start and +checking every required event, RNG transition and state digest. The public +Worker has no verifier-writes endpoint. D1 stores the queue and decisions. +R2 objects are private and served by the authorised download route. Neither +the replay format nor the published object includes a ROM or a guest snapshot. + +## Before opening ranked submissions + +The runtime recorder, ranked Magic Code, split overlay, playback controls and +independent verifier are still required. The existing owned-engine probe is +for private snapshots and rollback testing. First prove a completed legal +vanilla Time Trial from inputs alone on Windows and Linux, then qualify one +native custom track release. Compare applied input, engine checkpoints, splits +and completion. Verify renderer parity separately. Add Adventure categories +such as Any%, 100% and All Trophy Races after equivalent coverage. + +Keep `SPEEDRUN_UPLOADS_ENABLED` unset until that qualification is complete. +Configure a private `SPEEDRUN_REPLAYS` R2 binding during the ranked pilot. +Run the additive speedrun D1 migration and check the acceptance, privacy and +review cases in staging. The Online page and read-only track catalogue can +be reviewed independently of ranked uploads. + +## Staging review + +The review package contains website and Worker sources plus screenshots from +a local test. The screenshot times and lobbies are fixtures. The package's +rollback sources are the base checkout used to build the review. Collect the +actual deployed website files, Worker revisions and a D1 backup before rollout. +Keep the current Cloudflare settings and bindings. The directory Worker must +understand the public projection before the public API and website use it. + +Use the existing documented deployment commands only after review. No +production changes are required to run the local tests. diff --git a/docs/notes/2026-11-22-ranked-theatre-playtest.md b/docs/notes/2026-11-22-ranked-theatre-playtest.md new file mode 100644 index 00000000..7921719e --- /dev/null +++ b/docs/notes/2026-11-22-ranked-theatre-playtest.md @@ -0,0 +1,143 @@ +# Ancient Lake ranked and Replay Theatre playtest + +Use the US v1.1 ROM you already have. The pilot runs Ancient Lake in the stock +car, solo, for three laps. It uses a fresh in-memory save and a fixed starting +seed. The profile's mods and Magic Codes are disabled for the attempt. + +In **Play > Leaderboards**, choose a stock **Racer**, then select **Practice** +or **Start ranked run**. Ranked times are grouped by racer. Finish all three +laps and allow seven seconds for the replay to capture the finish sequence. +Use **Post last run** or choose your completed file with **Post a run**. +Open **My runs** to check the submission and watch your uploaded replay. A +single approved replay counts for both **Full race** and **Best lap** for its +racer. The recorded time and splits stop at the finish line. Staff review +still applies before a time is public. + +The attempt is bound to its account, board and ruleset. A replay contains the +inputs delivered to the game and gameplay checkpoints. The verifier runs +the game with its own clean profile, compares the checkpoints and takes the +time from the reproduced race. This checks repeatability of the recorded +inputs. Moderators can also review playback. + +## Run the local pilot + +The local test server uses disposable accounts, storage and a loopback-only +address. Close it with Ctrl+C when finished. It needs Node.js, Python, a +fresh launcher profile directory, the rebuilt game executable and your own +US v1.1 ROM. On Linux pass `--xvfb` to run the verifier on a separate display. + +```sh +python services/online-directory/build.py --output build/local-ranked-worker +node services/online-directory/run_local_ranked.cjs --bundle build/local-ranked-worker --runtime --rom --jobs --profile +``` + +Start the game executable with `--config `. Add the same +ROM in Play if the profile has no ROM selected. After a verified run has been +reviewed, enter `publish ` in the local test server console. Published +rows have a **Watch** button when a launcher profile is active. + +For the automated verifier proof, replace `--profile ` +with `--fixture `. This wraps a known input +fixture in a disposable test ticket. It verifies and publishes the original +and checks that changed inputs are rejected. The script uses separate +processes and profiles for verification. + +## Replay Theatre + +In **My replays**, select **Watch** beside a local recording or download. +**Open replay folder** opens the `speedruns` folder in the active launcher +profile. Use **Open replay** for a `.dkrreplay` saved elsewhere, or select +**Watch** on a published result. Older replay files still open and end at +their recorded finish. + +Use the timeline, lap starts and **Finish** to skip through a replay. The +frame buttons move one recorded simulation update at a time. Space, Escape +and controller Start play or pause. Comma steps back and period steps +forward. Select **Exit** to return to the launcher. **Inputs** shows the +recorded stick and buttons. The speed choices are 0.5x, 1x and 2x. You can +change the target, cancel the seek, or choose whether playback resumes on +arrival. + +Replay Theatre prepares a temporary local frame index once each time a +replay is opened. The **Preparing replay** counter and the thin timeline +bar show how far that pass has reached. Playback can start while the index +is being built. Click or drag backwards or forwards through prepared +footage to display a frame without rerunning the race. An unprepared target +opens when it becomes available. **Finish** skips to the crossing, and the +timeline extends through any recorded finish sequence. + +Shared replays contain inputs and verification hashes. The Theatre uses the +racer in the recording, with Diddy implied for the original Diddy-only files. +The presentation index lives locally and is removed on normal exit. + +## Earlier local test results + +The original Ancient Lake fixture reproduced all 2,534 updates and five +gameplay checkpoints on Windows and Linux. Its full race time was 1:21.666 +and its best lap was 0:26.700. The local ranked test uploaded the fixture, +rejected altered inputs and required moderation before listing the valid +result on either board. + +At 1280x800, Replay Theatre paused, stepped from frame 49 to 50 and back to +49 and displayed the recorded controls. The timeline jumped to frame 934, +Lap 2 jumped back to frame 931 and Start rewound to frame 1. Linux tests ran +using Xvfb on WSL. + +## Earlier replay library playtest results + +A Pipsy practice recording crossed at simulation update 2,501 and played to +update 2,711 in the Linux AppImage. The Windows verifier accepted the official +race time of 1:20.566 and best lap of 0:26.233. A disposable local leaderboard +placed the run on Pipsy's full race and best lap boards after moderation and +rejected the altered-input fixture. + +The original 1:01.700 Ancient Lake replay still plays. In the 1280x800 Linux +test, Escape paused in the Theatre and playback stepped back from frame 874 +to 873 using checkpoint 870 in about 0.3 seconds. Jumps to frames 859 and +494 required exact reloads. The replay then reached update 1,935 with the +original finish and all gameplay checkpoints verified. + +The host CTest run passed 213 of 214 checks. The regression harness timed +out on the Windows-mounted checkout and passed all 25 tests from the native +Linux filesystem. The separate tooling check reports two existing Android +patch fixture failures. The guard and ranked API checks passed. + +## Whole-run scrubbing checks + +On Windows, the original Ancient Lake replay verified its 1:01.700 finish. +The Theatre presented both backward and forward jumps within the same race, +including frame 748 back to 84 and frame 204 forward to 998. A conflicting +racer option did not change the recorded Diddy. At 1280x800 on Linux, the +same replay verified all 1,935 frames and jumped from frame 1,800 back to 415 +in about 130 ms and forward to 1,154 in about 170 ms. In the packaged +AppImage, dragging the timeline while paused showed Pipsy move from frame +138 to 31 before the mouse button was released. The current Linux host +suite passed all 214 checks. The separate Windows tooling suite still reports two +existing Android patch fixture failures. + +## Agenda + +- Add **Download replay** and **Race ghost** to published leaderboard runs. + Also let players race a compatible file from **My replays**, so a saved + ghost can be used offline. +- Start with Ancient Lake Time Trial. Require the recorded route, vehicle, + and compatible rules and track release. Prepare the opponent from the + recording's inputs, with its recorded racer and timing. +- Render the ghost as a non-interacting opponent. Keep collisions, pickups, + the player's timer and save progress independent. Compare splits against + the ghost and qualify competition with a ghost before enabling it in ranked + attempts. + +### Website notifications + +The website bell appears between Moderation and Sign in or the account name. Signed-out +visitors can use it to sign in. Signed-in players see changes to their own +mod and ranked-run submissions, with a link to the relevant status page. +Moderators and admins also see mod submissions and independently verified +runs that are ready for review. Players have no access to the staff queue. + +The service records a single event per committed status change and stores read state per +account across devices. The bell shows an unread count and opens a list +with timestamps, status, and Mark all as read. Give reviewers the current +queue state when they follow a notification, including items already handled +by another moderator. The tests cover deduplication, moderation role changes, cross-device read state and deletion. The bell is also checked on narrow screens. diff --git a/docs/notes/2026-11-22-ranked-verification.md b/docs/notes/2026-11-22-ranked-verification.md new file mode 100644 index 00000000..f2c34fdd --- /dev/null +++ b/docs/notes/2026-11-22-ranked-verification.md @@ -0,0 +1,79 @@ +# Ranked replay verification playtest + +## Playtest builds + +Use the v1.0.16-playtest.1 Ranked Replay Verification Windows ZIP or Linux +AppImage with a US v1.1 ROM. In Play, open Leaderboards to practice or submit a +recording on a qualified board. The local Replay Theatre can open Time Trial +recordings, including the post-race tail. Adventure replays use linear in-game +playback while long-run verification is in testing. + +For Ancient Lake DS, install the current release through the Mod Library. +Select the installed track in Leaderboards and use Diddy in the car. For +Fossil Canyon, select Diddy and the car under Vanilla Tracks. Posting a result +queues it for independent replay. A moderator or admin reviews the verified +result before it appears in the public ranking. + +## Public boards + +The portal accepts Diddy Time Trial submissions for these newly qualified +selections. + +| Track | Vehicle | +| --- | --- | +| Ancient Lake | Hovercraft | +| Ancient Lake DS, current Mod Library release | Car | +| Fossil Canyon | Car and hovercraft | +| Hot Top Volcano | Plane | +| Jungle Falls | Car | +| Whale Bay | Hovercraft | + +The public verifier uses the existing Linux service and the same encrypted +replay storage as the previous ranked pilot. The previously queued Ancient +Lake run independently verified at 3,664 race-clock ticks and moved to +staff review. + +## Evidence + +- Ancient Lake DS, Diddy and car, reproduced 4,908 race-clock ticks (1:21.800) + on Windows and Linux. Staging used the exact published Mod Library ZIP. The + test covered the signed attempt, download and package hash, independent + replay, altered-input rejection, staff-only publication and replay download. +- Fossil Canyon, Diddy and car, reproduced 7,724 race-clock ticks (2:08.733) + on Windows and Linux. The staged submission checked the race and lap + rankings, rejected altered inputs, and downloaded the original replay after + staff approval. +- Ancient Lake hovercraft and Jungle Falls car, both with Diddy, reproduced + 5,084 and 5,626 race-clock ticks respectively on Windows and Linux. Both + passed staged attempt, altered-input rejection and moderator publication. +- Fossil Canyon hovercraft, Whale Bay hovercraft and Hot Top Volcano plane + passed the same checks at 7,498, 5,598 and 8,650 race-clock ticks. +- The Windows launcher navigation checks captured Play, track lists, results + and Full Game layouts at desktop size and 1280×800. +- The live verifier's account home was hidden by its service, and Mesa could + exhaust its thread limit. Each replay now gets a private writable home and + bounded software renderer threads. The updated pinned AppImage reproduced + the queued Ancient Lake run's finish and four gameplay checkpoints using + the production service restrictions. The recorded post-race frames were + preserved while the result was attested at the earlier finish tick. +- All 215 host tests passed, along with the pattern and identity guards. + The broader tooling suite still reports two existing Android patch fixture + failures. + +## Qualification still in progress + +Any%, 100% and All Trophy Races have separate native finish conditions and a +separate verification queue. The new checkpoint format captures all three +axes of racer position and velocity. Repeated Adventure inputs reached the +same hub and produced matching motion and save progress, while the gameplay +RNG first diverged four updates after hub entry in the traced run. One +playback consumed an extra random draw on that update and caught up five +updates later. The staging API test confirms role and proof checks. +Full-game submissions stay closed pending repeatable native playback +of a complete run in each category. + +Additional vanilla track and vehicle pairs have complete test recordings. +Public qualification is applied only to pairs that pass independent +playback and the ranked submission path. Legacy patch tracks and battle +maps need their own competition rules and evidence. + diff --git a/docs/notes/2026-11-22-time-trial-qualification.md b/docs/notes/2026-11-22-time-trial-qualification.md new file mode 100644 index 00000000..6a51ffbf --- /dev/null +++ b/docs/notes/2026-11-22-time-trial-qualification.md @@ -0,0 +1,71 @@ +# Additional Time Trial qualification + +Each public board requires an exact three-lap replay, signed submission +and moderator approval in staging, rejection of altered inputs, and +matching finish time, lap splits and checkpoints on the pinned Linux +verifier. An automated drive runs in practice and its time does not go +on the public leaderboard. + +## Retail loop sections + +Walrus Cove and Darkmoon Caverns use a temporary retail vehicle mode +for loops. The verifier treated that mode as a change of vehicle. +It now accepts the loop mode on those courses when the original vehicle +recorded by the game still matches the attempt. The selected course, +racer, base vehicle and gameplay checkpoint requirements still apply. + +The old executable rejected the same Walrus Cove replay at update 315 +for car and at update 333 for hovercraft. Both complete captures passed +the staged Windows submission and altered-input tests on the rebuilt +game. The rebuilt Linux AppImage reproduced the car's nine checkpoints +and 9,600-tick finish, and the hovercraft's eight checkpoints and +9,254-tick finish. + +The public verifier uses the previous pinned package. Both Walrus Cove +boards remain closed pending qualification against a live verifier that +can reproduce the loop sections. + +## Boards opened in this pass + +The public catalogue now has 54 boards, including five custom boards. +The 49 retail boards cover 40 of the 47 course and vehicle pairings. +Racer variants account for the additional retail boards. + +| Course | New vehicles | +| --- | --- | +| Crescent Island | Car (Pipsy), hovercraft | +| Everfrost Peak | Car, hovercraft | +| Fossil Canyon | Plane | +| Frosty Village | Hovercraft, plane | +| Greenwood Village | Hovercraft | +| Haunted Woods | Hovercraft | +| Jungle Falls | Hovercraft, plane | +| Snowball Valley | Hovercraft | +| Spacedust Alley | Hovercraft, plane | +| Spaceport Alpha | Plane (Pipsy) | +| Star City | Car, hovercraft | +| Treasure Caves | Hovercraft | +| Windmill Plains | Hovercraft, plane | +| Luigi's Raceway | Car | +| Sherbet Land | Hovercraft | + +Some Windows moves from the temporary proof filename failed after +the Linux verification had finished. Publication checked the complete +proof JSON against the pinned runtime digest, replay bytes, splits and +checkpoints in either filename. + +## Remaining retail pairings + +| Course | Vehicles | Status | +| --- | --- | --- | +| Walrus Cove | Car, hovercraft | Both verified on the rebuilt packages | +| Darkmoon Caverns | Car, hovercraft | Need completed three-lap replays | +| Spaceport Alpha | Car, hovercraft | Need completed three-lap replays | +| Treasure Caves | Plane | Needs a completed three-lap replay | + +The other custom car attempts in this pass did not yield a full +recording. Those were Mario Circuit, MSUSA Chicago, Royal Raceway, +Toad's Turnpike and Wario Stadium. + +The source guard and all 215 host tests passed. Both playtest +packages match their recorded SHA-256 checksums. diff --git a/docs/notes/2026-11-23-replay-video-playtest.md b/docs/notes/2026-11-23-replay-video-playtest.md new file mode 100644 index 00000000..bb7c3c59 --- /dev/null +++ b/docs/notes/2026-11-23-replay-video-playtest.md @@ -0,0 +1,89 @@ +# Replay and video playtest + +## Test scope + +- The local portal runs on loopback with a disposable leaderboard database and object buckets. Its Ancient Lake entry is copied from the existing verified result. No production services are used by these tests. +- The original Ancient Lake replay reproduced a 1:01.066 finish, a 0:19.566 best lap, and all four recorded gameplay checkpoints on the rebuilt Windows runtime and the Linux AppImage. +- A separate test used the same controller input bytes with a ticket issued to a disposable local account. The verifier accepted those inputs and rejected an altered recording. The verified result went through the local moderation path. +- The AppImage opened Ancient Lake through the launcher and used all 1,916 downloaded ghost samples without preparing the replay again. The shared splash stayed visible during the renderer change. The replay and ghost downloads stayed outside My Replays. +- The two Walrus Cove loop recordings reproduced their complete checkpoints on Windows. The car finished in 2:40.000 and the hovercraft in 2:34.233. +- Treasure Caves (plane, 1:39.400) and MSUSA Chicago (car, 2:38.500) matched on a Windows build and on Linux, including the replay digest, lap splits, and final checkpoint. The local portal uses the exact Mod Library release and track hashes for MSUSA Chicago. +- The portal and launcher show the eleven Full Game categories from the supplied LiveSplit templates. The stage labels and route order come from the templates. The templates do not provide engine events or proof that a category can verify end to end. +- The cold Adventure path uses an isolated, uninitialised EEPROM image. The AppImage reproduced the native new-save intro. Existing Adventure replay versions retain their original boot behaviour. + +## Local video workflow + +Run `services/online-directory/render_ranked_video.py` as a dedicated unprivileged Linux user with Python, Xvfb, libX11, xauth, xdotool and FFmpeg available. Supply `--runtime`, `--rom`, `--replay` and a new `--output` directory. Custom tracks also require `--track-package` pointing to the exact recorded track package. The job creates its own display in a private network namespace. The runtime sends the RT64 presentations and their matching 48 kHz stereo interval for each replay update over a private local socket. The export highlights buttons and moves the N64 stick using the inputs from the same recorded update. The Replay Theatre spinner and transport controls stay in the interactive viewer. + +The job writes `verified.mp4` and `proof.json` after checking the engine result against the replay clock, finish update and checkpoints. The queue leases each verified Time Trial once and retries failed captures. The portal checks the object's replay digest and serves a seekable MP4 after moderation publishes the run. + +The original 30 Hz Ancient Lake video had 2,126 authored frames and ran for 1:10.867. Picture and audio both start at zero, and the first race picture appears at 0.067 seconds. Edge played and sought through the local copy. Nineteen frame samples, including consecutive frames at two A-button transitions, matched the replay. The controller goes neutral during the finish tail. + +## Outstanding + +- Full-length native recordings for Full Game qualification and personal best and leaderboard split comparisons. The native v5 Adventure recorder now writes splits triggered by gameplay milestones. The verifier independently regenerates them and checks the result before moderation. +- Qualification of the remaining course and vehicle pairs with incomplete recordings and of custom track releases with no complete proof. +- Full Game video rendering, which needs the long-session path rather than the Time Trial frame archive. + +## Native video cadence and texture packs + +- Website video capture reads each RT64 swap before the next swap can replace it. The + private capture socket carries 60 Hz pictures and one 48 kHz PCM block per 30 Hz + replay update. The encoder keeps both RT64 pictures during motion and repeats + the authored image for transitions that supply a single picture. Check native + paired pictures during the timed race as well as the output frame rate. + The local Ancient Lake export produced two distinct RT64 pictures for every + one of its 1,832 timed updates and reproduced the original 1:01.066 finish. + Deploy the matching runtime and exporter together because the capture protocol changed. +- The planned website render profile retains a pinned copy of Sr.gu's HD pack, + 0.00 LOD bias, generated mipmaps and 16x anisotropic filtering. Keep these + settings separate from the submitter's graphics choices. Use Ancient Lake to + compare a native 60 Hz capture against the old blended preview. +- Allow the packs enabled in Graphics for live vanilla, custom-track, Ghost and + Full Game runs. Keep them in the renderer's visual settings so gameplay + mods, custom Magic Codes and unqualified track packages remain subject to the + existing ranked rules. Honour the existing Modern presentation and pack + priority rules. Keep the verifier's simulation independent of installed packs. +- Qualify the live texture change by comparing the inputs, splits, finish and + gameplay checkpoint hashes with and without a pack. Include a custom track, + a ghost run and a Full Game attempt, and confirm both US ROM revisions can + verify evidence produced with the pack enabled. + + +## Remaining work and public video backfill + +The native cadence is verified locally. The public video worker still needs the +matching Linux runtime and exporter, plus a managed render profile that loads +the pinned Sr.gu v0.2.8 pack with mip generation and sampling enabled, LOD bias +at 0.00 and 16x anisotropic filtering. Test 1080p60 as the standard Time Trial +output and keep the existing adaptive encoding and size limit for long Full +Game runs. Check a vanilla replay, a custom track with its exact package, and a +Full Game replay with its split panel before switching the public worker. + +Re-render every existing public run video. Count and deduplicate the published +video assets in D1 by run ID and source replay digest at the start of the +backfill. The public racing and lap lists show personal bests, so the inventory +needs to include older published videos still available by their run links. + +1. Record each current video digest and length, run ID, replay digest, ROM + revision, credited runner and any exact custom track package required. + Process the inventory in a resumable batch alongside the normal video queue. + Keep moderation jobs ahead of the backfill. +2. Reproduce the verified finish, splits and gameplay checkpoints before + staging each replacement. Check the RT64 cadence, widescreen presentation, + audio sync, N64 input viewer, DKR-R intro, outro and watermark, and racer + credit. For Full Game videos, check the split panel and controller placement. +3. Upload the replacement as a separate digest-named archive to the existing + FTPS storage. Check the staged video and seek ranges, then update its + current video reference only if the source replay and prior video still + match the inventory. Keep the same public run link and preserve its leaderboard + entry, replay and ghost. Retain the previous archive until the playback audit + passes so an individual replacement can be rolled back. +4. Audit every inventory row and report replaced, skipped and failed videos. + Leave the current video available for any run that needs replay compatibility + work or another render attempt. + +The in-game pack policy above is a separate launcher change. Cloud Saves are +also pending. Implement opt-in sync through the existing Discord login for +Offline, Modded and persistent Online saves. Test revision conflicts, offline +recovery and safe imports across Windows and Steam Deck before rollout. diff --git a/docs/releases/1.0.16-playtest.1/RELEASE-NOTES.txt b/docs/releases/1.0.16-playtest.1/RELEASE-NOTES.txt new file mode 100644 index 00000000..e51857c0 --- /dev/null +++ b/docs/releases/1.0.16-playtest.1/RELEASE-NOTES.txt @@ -0,0 +1,22 @@ +DKR-R v1.0.16 playtest 1 + +This is a testing build. It brings our latest online work together with the +changes that have landed from other contributors since v1.0.15. + +Racers can send inputs directly to each other, while the host still handles +recovery. Spectators stay outside that input path. You can also offer the host +role to someone else in the lobby without making everyone leave and rejoin. +They have to accept, and the transfer has to finish before starting the game. +Your controller seat and the owner of the online save stay the same. + +There are further changes to online picture handling and Auto input delay to +help with the frame dips we saw on Steam Deck. Please test both a normal session +and a full lobby, and keep the runtime logs if anything goes wrong. + +The launcher layout is unchanged. The contributor work on cross-platform play, +relay connections, shutdown, Track Lab and the rest of the folded source tree +is included. This does not add a new hosted relay service. + +Use matching builds for testing. No release or service update has been published +as part of preparing these files. See docs/notes/2026-11-17-upstream-integration.md +for the exact source and verification record. diff --git a/docs/releases/1.0.16-playtest.1/UPDATER.txt b/docs/releases/1.0.16-playtest.1/UPDATER.txt new file mode 100644 index 00000000..a4e07721 --- /dev/null +++ b/docs/releases/1.0.16-playtest.1/UPDATER.txt @@ -0,0 +1,5 @@ +DKR-R v1.0.16 playtest 1 + +Testing build with the latest contributor changes, direct racer input links, +host handover and further online frame pacing work. Keep your runtime logs if +you run into a problem. This build has not been published to the updater. diff --git a/docs/releases/1.0.16/RELEASE-NOTES.txt b/docs/releases/1.0.16/RELEASE-NOTES.txt new file mode 100644 index 00000000..38980c6b --- /dev/null +++ b/docs/releases/1.0.16/RELEASE-NOTES.txt @@ -0,0 +1,67 @@ +DKR-R v1.0.16 +Changes since v1.0.15 + +Speedrunning +- Open Speedrunning from Play. Top Players shows points, published personal + bests and world records. Open a player to view their results. Track cards + show leaders by vehicle for Full Race and Best Lap. View Times includes a + timeline with each record holder and how long their time stood. +- Use Runs > Run to start a Time Trial or Challenge Run. Practice and ranked + attempts share Start Run. Race Ghost records an attempt with the ghost's + racer. Visual texture packs stay enabled. +- Sign in with Discord to submit. Eligible local runs can be linked once to an + account. My Submitted Runs shows review status and the next slot to reopen + in the rolling 24-hour window. +- Replays offers scrubbing, frame steps, playback speed, recorded inputs and + prepared ghosts. Playback keeps the recorded racer. Manage local recordings + and overlay preferences from the launcher. +- Challenge Runs include Any%, 100%, Glitchless, All Bosses, All Minigames, + All Trophy Races and its ordered variants, Car%, Hover%, Plane%, and + T.T. Amulet without wrong warps. Automatic splits follow route milestones. + Check the launcher and board for enabled submission routes. +- Moderators and admins review verified runs. Hosted videos show player + credit, controller inputs and Challenge Run splits. Rendering can continue + after upload. The portal bell reports submission and review updates. + +Online +- Browse public lobbies and recorded player activity on the portal. Use + connection measurements to compare hosts. A host can offer ownership to + another member without closing the lobby. Seats and save ownership persist. +- Racers send inputs directly when available, with the host path available + for recovery. A lobby supports four racers and eight spectators. Spectators + buffer confirmed frames independently. +- Rollback presentation retains pictures through brief corrections, and + automatic delay accounts for forward progress and replay cost. +- Upstream improves relay and shutdown behavior, controller binding recovery, + custom boss races and checkpoint capacity. Use matching builds online. + +Cloud Saves and the launcher +- Sign in with Discord and enable Cloud Saves beside the active save on Play. + The cloud icon reports sync status and runs a manual sync when selected. +- Vanilla, Modded and Online Adventure sync independently. Session Mods + chooses the Modded Adventure. Existing personal progress stays in Vanilla. + Development saves are separate. +- Cloud Saves refresh around launching, hosting and returning to the launcher. + Successful game writes show Saving Progress and queue a sync. If copies + diverge, the cloud copy takes priority and local recovery keeps the old copy. +- Save Manager puts the slots beside the editor. Progress shows all editing + tools and Max Out actions. Files groups transfer and recovery. +- Badge Gallery adds search, filters, badge details and pinning. The launcher + and overlay use padded dialogs, compact Play settings and Speedrunning + loading transitions. + +Graphics and modding +- Replay widescreen HUD uses fit-to-window. Website videos capture up to + 1080p at 60 fps where the category permits, with a host render profile. +- Contributor work includes water caustics and vehicle spray, road wheels, + Track Lab challenge/boss/hub support, SDK schema documentation, generated + symbols and build tooling. The rollback self-test also accepts a Track Lab + course and reports the number of checkpoints it loaded. + +Extract the complete Windows ZIP and use DKR-R.exe. On Linux or Steam Deck +make the AppImage executable. Keep your profile and supply your own US v1.0 +or US Rev A/v1.1 ROM. Some legacy mod patches require US v1.0. Desktop targets +are Windows x64, Linux x86_64 and Linux ARM64. Steam Deck uses Linux x86_64. +Ranked uploads require an eligible x86_64 build. + +Contributors include Steve Whittaker, ThatGuyMcd and leite-matheus. diff --git a/docs/releases/1.0.16/UPDATER.txt b/docs/releases/1.0.16/UPDATER.txt new file mode 100644 index 00000000..d038de48 --- /dev/null +++ b/docs/releases/1.0.16/UPDATER.txt @@ -0,0 +1,11 @@ +DKR-R v1.0.16 updater assets + +Version1.0.16 must identify the exact source commit used for the desktop +packages. Steam Deck is an exact copy of Linux x86_64 and shares its update +entry. Finalize the Windows x64, Linux x86_64 and Linux ARM64 builds and +qualify the upgrade from v1.0.15. + +Use the existing trusted Ed25519 key to sign the exact DKR-R-update.json +bytes. Verify DKR-R-update.sig and the package hashes before staging the +draft release. Keep the key outside the repository, packages and logs. See +docs/RELEASING.md for the platform and updater checks. diff --git a/docs/releases/1.0.16/pages/RELEASE-README.md b/docs/releases/1.0.16/pages/RELEASE-README.md new file mode 100644 index 00000000..d95fc33e --- /dev/null +++ b/docs/releases/1.0.16/pages/RELEASE-README.md @@ -0,0 +1,18 @@ +# DKR-R v1.0.16 + +On Windows, extract the full ZIP and open **DKR-R.exe**. On Linux and Steam +Deck, make the AppImage executable and launch it. Keep the Windows launcher, +libexec, assets and licence notices together. + +Add your own legally obtained US v1.0 or US Rev A/v1.1 ROM in Play. Some legacy +mods still need US v1.0. Keep your existing profile and backups. For a portable +install, keep portable.txt and dkr-runtime-data with the application. + +Open **Speedrunning** for runs, replays and leaderboards. Use matching builds +for multiplayer. **Save Manager** edits separate Vanilla and Modded saves. +Sign in with Discord to enable **Cloud Saves** beside the active save. + +See RELEASE-NOTES.txt and the repository guides for requirements, compatibility, +recovery and validation. + +https://github.com/ThatGuyMcd/DKR-R diff --git a/packaging/RELEASE-README.md b/packaging/RELEASE-README.md index a6428fe6..d95fc33e 100644 --- a/packaging/RELEASE-README.md +++ b/packaging/RELEASE-README.md @@ -1,53 +1,18 @@ -# DKR-R v1.0.15 +# DKR-R v1.0.16 -Windows: extract the whole ZIP and run **DKR-R.exe**. Keep assets, libexec, -helpers and licence notices together. Linux/Steam Deck: make the AppImage -executable and launch it. Steam Deck uses the Linux x86_64 payload. +On Windows, extract the full ZIP and open **DKR-R.exe**. On Linux and Steam +Deck, make the AppImage executable and launch it. Keep the Windows launcher, +libexec, assets and licence notices together. -Add your own legally obtained US v1.0 or US Rev A/v1.1 ROM in Play. No ROM or -extracted game resources are supplied. Some legacy .xdelta mods require clean -US v1.0 to install; you can keep v1.1 selected for playing. +Add your own legally obtained US v1.0 or US Rev A/v1.1 ROM in Play. Some legacy +mods still need US v1.0. Keep your existing profile and backups. For a portable +install, keep portable.txt and dkr-runtime-data with the application. -Your existing profile, saves, mods and settings can stay. Ordinary offline mods -share personal Adventure. Online and development progress have separate owners. -Portable mode selects another data location; it does not move your profile. -Use matching complete v1.0.15 packages on every machine for online play. -Automatic delay and a larger prediction window can help with distant players. -Host settings can now be changed from the lobby and in-game Online overlay. -Prediction and input-delay changes apply live; capacity, menu and replay changes -made while playing wait until the lobby. The default prediction window is 14. -Spectators use buffered confirmed playback and never supply racing inputs. -Very slow connections can still exceed the prediction window and cause waits. -The reported missing vanilla online car textures/road wheels remain unresolved. +Open **Speedrunning** for runs, replays and leaderboards. Use matching builds +for multiplayer. **Save Manager** edits separate Vanilla and Modded saves. +Sign in with Discord to enable **Cloud Saves** beside the active save. -Play contains Achievements, Session mods and Save Manager. Session mods OFF -bypasses selected content for the next session without changing its selections. -Start Game stays visible at the bottom of Play while its settings scroll. -It is selected when Play opens with a ready ROM. The overlay keeps Return to -the Race in the same position. -The button is narrower and centred, and controller focus can move away normally. -The page background and Save Manager footer match the surrounding panel. -Skip launcher can be turned off again in the in-game Play overlay. Escape, F1 -or controller Back/View opens that overlay. - -The optional Analogue Acceleration & Braking mod must be imported and enabled -under Installed Mods > My mods > Custom Magic Codes. Open Details, select the -local player and apply/calibrate RT/LT driving. Standalone Look behind and CRT -controls are under Graphics > HUD & effects. - -Automatic crash reporting is opt-in. About DKR-R > Support changes the choice. -Raw dumps require separate consent and may contain personal information. -File dialogs use a private helper on Windows and Linux; keep that helper with -the installation. Improved fault diagnostics do not claim to fix the unresolved -Windows graphics-startup or Linux gameplay crashes. -Selected custom characters now have native colourful names above the upper row -or below the lower row, supporting up to four players. The new-save initials -keyboard also draws across widescreen views. -See RELEASE-NOTES.txt and the repository guides for details and known limits. - -Current release targets are Windows x64, Linux x86_64/ARM64 and Steam Deck. -Android is unsupported; macOS/iOS retain earlier downloads. Hardware performance -and controller feel require actual-device testing. The SDK/Modding Bible and -Track Lab authoring tools remain separate from the game installation. +See RELEASE-NOTES.txt and the repository guides for requirements, compatibility, +recovery and validation. https://github.com/ThatGuyMcd/DKR-R diff --git a/packaging/linux/dkr-port.appdata.xml b/packaging/linux/dkr-port.appdata.xml index 79d0310b..ec1921b7 100644 --- a/packaging/linux/dkr-port.appdata.xml +++ b/packaging/linux/dkr-port.appdata.xml @@ -16,6 +16,14 @@ + +

Speedrunning, public lobbies, host handover, Cloud Saves, Save Manager and Badge Gallery.

+
+

Achievement Badge Gallery and clearer Save Manager tools.

+

Save Manager keeps the Adventure slots beside the editor on Windows and Steam Deck.

+

Speedrunning Options has its own tab under Runs.

+

Rounded corners and more room around text and buttons in Launcher and in-game Overlay dialogs.

+

Combined upstream integration playtest with direct racer inputs, consented host handover, retained save ownership and lower-cost online picture correction.

Improved online input recovery, lower-cost checkpoints, buffered spectators and live host settings. Added storage cleanup, a pinned Play button, native custom-character names, isolated file dialogs and better crash diagnostics.

Online responsiveness and sync presentation, a unified launcher and overlay, analogue driving, controller feedback, automatic seasons, languages, display options and opt-in crash reporting.

Analogue acceleration and braking, standalone online Look behind and full CRT controls in Graphics.

diff --git a/patches/manifest.json b/patches/manifest.json index 2c00a6db..149c440f 100644 --- a/patches/manifest.json +++ b/patches/manifest.json @@ -238,6 +238,10 @@ { "path": "patches/rt64/0021-macos-runtime-msl-shaders.patch", "sha256": "2916492f9aefa6fccbe9bcf664ef30624f310f11be3f807305ce5ee819adf736" + }, + { + "path": "patches/rt64/0022-offline-replay-present-capture.patch", + "sha256": "d123d62b4a414657b7b31b91e3dfdbc7cc5ed9454821acdc932342ab6c02bac7" } ] }, diff --git a/patches/rt64/0022-offline-replay-present-capture.patch b/patches/rt64/0022-offline-replay-present-capture.patch new file mode 100644 index 00000000..a867600c --- /dev/null +++ b/patches/rt64/0022-offline-replay-present-capture.patch @@ -0,0 +1,155 @@ +diff --git a/src/hle/rt64_present_queue.cpp b/src/hle/rt64_present_queue.cpp +--- a/src/hle/rt64_present_queue.cpp ++++ b/src/hle/rt64_present_queue.cpp +@@ -96,6 +96,7 @@ + FramebufferManager &fbManager = ext.sharedResources->framebufferManager; + RenderTargetManager &targetManager = ext.sharedResources->renderTargetManager; + const bool usingMSAA = (targetManager.multisampling.sampleCount > 1); ++ const auto *capture = offlineCapture.load(std::memory_order_acquire); + hlslpp::float2 resolutionScale; + EnhancementConfiguration::Presentation::Mode presentationMode; + bool removeBlackBorders; +@@ -363,6 +364,16 @@ + inspector->draw(commandList); + } + ++ if (capture != nullptr) { ++ const uint32_t tag = capture->firstTag + i; ++ const int32_t width = static_cast(ext.swapChain->getWidth()); ++ const int32_t height = static_cast(ext.swapChain->getHeight()); ++ const RenderRect rect(width - 4, height - 4, width, height); ++ const RenderColor color((tag & 255U) / 255.0f, ((tag >> 8) & 255U) / 255.0f, ++ (0xA5U ^ (tag >> 16)) / 255.0f); ++ commandList->clearColor(0, color, &rect, 1); ++ } ++ + commandList->barriers(RenderBarrierStage::NONE, RenderTextureBarrier(swapChainTexture, RenderTextureLayout::PRESENT)); + commandList->end(); + const RenderCommandList *commandList = ext.presentGraphicsWorker->commandList.get(); +@@ -413,6 +424,9 @@ + if (swapChainValid && (framesToPresent > 1) && ((i + 1) < framesToPresent)) { + ext.sharedResources->totalInterpolatedPresentations.fetch_add( + 1, std::memory_order_relaxed); ++ } ++ if (swapChainValid && (capture != nullptr)) { ++ capture->presented(capture->context, static_cast(i)); + } + } + } +diff --git a/src/hle/rt64_present_queue.h b/src/hle/rt64_present_queue.h +--- a/src/hle/rt64_present_queue.h ++++ b/src/hle/rt64_present_queue.h +@@ -58,6 +58,14 @@ + VIHistory viHistory; + bool presentWaitEnabled = false; + ++ // A synchronous capture consumer reads each tagged swap before the next one can overwrite it. ++ struct OfflineCapture { ++ uint32_t firstTag; ++ void *context; ++ void (*presented)(void *context, uint32_t index); ++ }; ++ std::atomic offlineCapture{ nullptr }; ++ + PresentQueue(); + ~PresentQueue(); + void reset(); +diff --git a/src/hle/rt64_state.cpp b/src/hle/rt64_state.cpp +--- a/src/hle/rt64_state.cpp ++++ b/src/hle/rt64_state.cpp +@@ -1781,7 +1781,21 @@ + const bool presentEarly = !ext.presentQueue->viewRDRAM && (ext.enhancementConfig->presentation.mode == EnhancementConfiguration::Presentation::Mode::PresentEarly); + workload.earlyPresentApproved = false; + workload.earlyPresentColorAddress = 0; +- if (presentEarly && (workload.fbPairCount > 0)) { ++ if ((offlineCaptureVI != nullptr) && offlineCaptureVI->visible()) { ++ const VI &vi = *offlineCaptureVI; ++ for (int32_t f = workload.fbPairCount - 1; f >= 0; f--) { ++ const FramebufferPair &pair = workload.fbPairs[f]; ++ if ((pair.colorImage.address == vi.fbAddress()) && ++ (pair.colorImage.width == vi.fbSize().x) && (pair.colorImage.siz == vi.fbSiz()) && ++ pair.earlyPresentCandidate()) ++ { ++ workload.earlyPresentApproved = true; ++ workload.earlyPresentColorAddress = pair.colorImage.address; ++ break; ++ } ++ } ++ } ++ else if (presentEarly && (workload.fbPairCount > 0)) { + thread_local std::unordered_set approvalColorImageAddressSet; + approvalColorImageAddressSet.clear(); + +@@ -1963,7 +1977,11 @@ + // CPU changes directly to it and recreating them in the render thread at low resolution. + RenderWorker *worker = ext.framebufferGraphicsWorker; + Framebuffer *screenFb = framebufferManager.find(screenFbAddress); +- if (screenFb != nullptr) { ++ // The archived replay's matched framebuffer already contains this ++ // presentation. Live RDRAM belongs to the replay producer and ++ // must not overwrite the first RT64 target in the capture pair. ++ const bool replayColorTarget = (offlineCaptureVI != nullptr) && !present.colorImageAddresses.empty(); ++ if ((screenFb != nullptr) && !replayColorTarget) { + // Check compatibility of the high resolution framebuffer with the VI first. + // Ensure both the siz and width are the same. + if ((screenFbSize.x == screenFb->width) && (screenFbSiz == screenFb->siz)) { +diff --git a/src/hle/rt64_state.h b/src/hle/rt64_state.h +--- a/src/hle/rt64_state.h ++++ b/src/hle/rt64_state.h +@@ -148,6 +148,8 @@ + void fullSyncFramebufferPairTiles(Workload &workload, FramebufferPair &fbPair, uint32_t &loadOpCursor, uint32_t &rdpTileCursor); + void listProcessBegin(); + void listProcessEnd(); ++ // The replay archive owns its VI rather than deriving it from display history. ++ const VI *offlineCaptureVI = nullptr; + void updateScreen(const VI &newVI, bool fromEarlyPresent); + void updateMultisampling(); + void inspect(); +diff --git a/src/hle/rt64_workload_queue.cpp b/src/hle/rt64_workload_queue.cpp +--- a/src/hle/rt64_workload_queue.cpp ++++ b/src/hle/rt64_workload_queue.cpp +@@ -222,7 +222,8 @@ + workloadConfig.targetRate = ext.sharedResources->userConfig.refreshRateTarget; + + // Limit the target rate to the rate detected by the swap chain. +- if ((ext.sharedResources->swapChainRate > 0) && (workloadConfig.targetRate > ext.sharedResources->swapChainRate)) { ++ if ((ext.presentQueue->offlineCapture.load(std::memory_order_acquire) == nullptr) && ++ (ext.sharedResources->swapChainRate > 0) && (workloadConfig.targetRate > ext.sharedResources->swapChainRate)) { + workloadConfig.targetRate = ext.sharedResources->swapChainRate; + } + +@@ -916,6 +917,7 @@ + ElapsedTimer workloadTimer; + workloadProfiler.start(); + threadConfigurationUpdate(workload.viFbSize, workloadConfig); ++ const bool offlineCapture = ext.presentQueue->offlineCapture.load(std::memory_order_acquire) != nullptr; + + // FIXME: This is a very hacky way to find out if we need to advance the frame if the workload was paused for the first time. + if (!workload.paused || (!gameFrames[curFrameIndex].workloads.empty() && (gameFrames[curFrameIndex].workloads[0] != (uint32_t)processCursor))) { +@@ -1019,7 +1021,7 @@ + displayFrames = uint32_t((logicalTicks - displayTicks) / workload.viOriginalRate); + deltaTimeMs = 1.0f / float(workloadConfig.targetRate); + +- if ((displayFrames > 1) && frameReduction) { ++ if (!offlineCapture && (displayFrames > 1) && frameReduction) { + displayTicks += workload.viOriginalRate; + displayFrames--; + frameReduction = false; +@@ -1081,7 +1083,7 @@ + int64_t renderTimeTotalMicro = 0; + for (uint32_t frame = 0; (frame < displayFrames) && !skipWorkloadNow; frame++) { + // Evaluate if this frame should be skipped. Measure the current time and compare it to what frame is estimated should be have been rendered by now. +- if ((frame > 0) && (originalTimeMicro > 0)) { ++ if (!offlineCapture && (frame > 0) && (originalTimeMicro > 0)) { + const int64_t currentTimeMicro = workloadTimer.elapsedMicroseconds() - setupTimeMicro; + const int64_t expectedTimeMicro = frame * maxTimePerFrameMicro; + const int64_t measuredFrameMicro = renderTimeTotalMicro / framesRendered; +@@ -1147,7 +1149,7 @@ + if (generateInterpolatedFrames && (usingMSAA || (frame > 0))) { + { + std::scoped_lock cursorLock(cursorMutex); +- skipWorkloadNow = ((frame + 1) < displayFrames) && (writeCursor != threadCursor); ++ skipWorkloadNow = !offlineCapture && ((frame + 1) < displayFrames) && (writeCursor != threadCursor); + } + + { diff --git a/runtime-recomp/CMakeLists.txt b/runtime-recomp/CMakeLists.txt index 9a83bff5..302c2059 100644 --- a/runtime-recomp/CMakeLists.txt +++ b/runtime-recomp/CMakeLists.txt @@ -1207,6 +1207,7 @@ if(DKR_RUNTIME_BUILD_GENERATED OR DKR_RUNTIME_BUILD_RT64) endif() set(DKR_GAME_SOURCES src/game/runtime_code_mods.cpp + src/game/time_trial/session.cpp src/game/audio_equalizer.cpp # The policy's asset hooks call into these with or without RT64; the # table logic itself is DKRCustomTracksCore, via DKRLegacyModLaunch. @@ -1325,6 +1326,18 @@ if(DKR_RUNTIME_BUILD_GENERATED OR DKR_RUNTIME_BUILD_RT64) list(APPEND DKR_GAME_SOURCES src/android/android_platform.cpp src/android/mobile_ui.cpp) endif() add_library(DKRPortGameCore OBJECT ${DKR_GAME_SOURCES}) + if(TARGET file_to_c) + set(preview_source "${CMAKE_CURRENT_LIST_DIR}/assets/speedrunning/AncientLake.jpg") + set(preview_blob "${CMAKE_CURRENT_BINARY_DIR}/generated/speedrunning_hud_preview") + add_custom_command( + OUTPUT "${preview_blob}.c" "${preview_blob}.h" + COMMAND "${CMAKE_COMMAND}" -E make_directory "${CMAKE_CURRENT_BINARY_DIR}/generated" + COMMAND file_to_c "${preview_source}" SpeedrunningHudPreview "${preview_blob}.c" "${preview_blob}.h" + DEPENDS "${preview_source}" file_to_c + VERBATIM + ) + target_sources(DKRPortGameCore PRIVATE "${preview_blob}.c") + endif() dkr_guest_symbols(DKRPortGameCore) if(NOT DKR_RUNTIME_BUILD_GENERATED) # host-full-nogen compiles the shipped configuration, which always has @@ -3203,6 +3216,8 @@ if(BUILD_TESTING) target_include_directories(DKRSaveStorageTests PRIVATE "${CMAKE_CURRENT_LIST_DIR}/src/game") add_test(NAME DKRSaveStorage COMMAND DKRSaveStorageTests) + add_executable(DKRAdventureReplayRulesTests tests/adventure_replay_rules_tests.cpp) + add_test(NAME DKRAdventureReplayRules COMMAND DKRAdventureReplayRulesTests) add_executable(DKRSaveCodecTests tests/dkr_save_codec_tests.cpp src/game/dkr_save_codec.cpp) target_include_directories(DKRSaveCodecTests PRIVATE "${CMAKE_CURRENT_LIST_DIR}/src/game") add_test(NAME DKRSaveCodec COMMAND DKRSaveCodecTests) @@ -3588,6 +3603,10 @@ if(BUILD_TESTING) PASS_REGULAR_EXPRESSION "REGRESSION FAILURE: FIRST POST-LOAD RELEASE WAS DISCARDED" FAIL_REGULAR_EXPRESSION "regression checks passed" ) + # The synthetic multi-peer runs perform much more work under CPU emulation. + if(CMAKE_CROSSCOMPILING AND CMAKE_CROSSCOMPILING_EMULATOR) + set_tests_properties(DKRRaceReleaseChecks DKRRaceReleaseBeforeChecks PROPERTIES TIMEOUT 240) + endif() add_executable(DKRSpectatorAdmissionTests tests/spectator_admission_tests.cpp) # Negative control: the same fixture compiles the production resident music diff --git a/runtime-recomp/assets/speedrunning/AncientLake.jpg b/runtime-recomp/assets/speedrunning/AncientLake.jpg new file mode 100644 index 00000000..8d4e3828 Binary files /dev/null and b/runtime-recomp/assets/speedrunning/AncientLake.jpg differ diff --git a/runtime-recomp/cmake/PeerRelay.cmake b/runtime-recomp/cmake/PeerRelay.cmake index a0d94e9b..3c84a3eb 100644 --- a/runtime-recomp/cmake/PeerRelay.cmake +++ b/runtime-recomp/cmake/PeerRelay.cmake @@ -29,6 +29,9 @@ function(dkr_add_peer_relay) "${_dkr_relay_root}/src/game/netplay/peer_relay/live_datagram.cpp" "${_dkr_relay_root}/src/game/netplay/peer_relay/owner_glue.cpp" "${_dkr_relay_root}/src/game/netplay/peer_relay/transport.cpp" + "${_dkr_relay_root}/src/game/netplay/session_links/policy.cpp" + "${_dkr_relay_root}/src/game/netplay/session_links/registry.cpp" + "${_dkr_relay_root}/src/game/netplay/session_links/transport.cpp" ) target_compile_features(DKRPeerRelay PUBLIC cxx_std_20) target_include_directories(DKRPeerRelay PUBLIC "${_dkr_relay_root}/src/game") @@ -46,6 +49,25 @@ function(dkr_add_peer_relay) target_include_directories(DKRPeerRelay PRIVATE "${DKR_DEPENDENCIES_DIR}/libdatachannel/deps/json/include") endif() endif() + if(NOT TARGET DKRSessionLinksPolicyTests) + add_executable(DKRSessionLinksPolicyTests "${_dkr_relay_root}/tests/session_links_policy_tests.cpp") + target_link_libraries(DKRSessionLinksPolicyTests PRIVATE DKRPeerRelay DKRNetplayCore) + add_executable(DKRSessionLinksNativeTests "${_dkr_relay_root}/tests/session_links_native_tests.cpp") + target_link_libraries(DKRSessionLinksNativeTests PRIVATE DKRNetplayCore) + foreach(_test DKRSessionLinksPolicyTests DKRSessionLinksNativeTests) + if(MSVC) + target_compile_options(${_test} PRIVATE /UNDEBUG) + else() + target_compile_options(${_test} PRIVATE -UNDEBUG) + endif() + endforeach() + if(BUILD_TESTING) + add_test(NAME DKRSessionLinksPolicy COMMAND DKRSessionLinksPolicyTests) + add_test(NAME DKRSessionLinksNative COMMAND DKRSessionLinksNativeTests) + set_tests_properties(DKRSessionLinksPolicy DKRSessionLinksNative PROPERTIES LABELS "host;runtime") + set_tests_properties(DKRSessionLinksNative PROPERTIES TIMEOUT 180) + endif() + endif() if(NOT TARGET DKRLiveDatagramTests) add_executable(DKRLiveDatagramTests "${_dkr_relay_root}/tests/live_datagram_tests.cpp") target_link_libraries(DKRLiveDatagramTests PRIVATE DKRPeerRelay DKRNetplayCore) diff --git a/runtime-recomp/guest-hooks/hooks.toml b/runtime-recomp/guest-hooks/hooks.toml index 36bbc12e..01294266 100644 --- a/runtime-recomp/guest-hooks/hooks.toml +++ b/runtime-recomp/guest-hooks/hooks.toml @@ -4,6 +4,143 @@ # (scripts/camera_scene_kernel.py). Every hook applies exactly once per payload. schema = 1 +# Local Time Trial recording and playback have their own input cadence. +# These hooks are inert outside a prepared solo replay session. +[[hook]] +id = "time-trial-launch" +function = "mode_menu" +payloads = ["funcs"] +[[hook.edits]] +match = "dkr_custom_tracks_auto_boot(rdram, ctx);" +replace = """ +dkr_custom_tracks_auto_boot(rdram, ctx); + { extern void dkr_time_trial_launch(uint8_t*, recomp_context*); dkr_time_trial_launch(rdram, ctx); } +""" + +[[hook]] +id = "time-trial-vehicle" +function = "load_level_game" +payloads = ["funcs"] +entry = "extern void dkr_time_trial_load_course(uint8_t*, recomp_context*); dkr_time_trial_load_course(rdram, ctx);" + +[[hook]] +id = "time-trial-frame" +function = "main_game_loop" +payloads = ["funcs"] +entry = "extern int dkr_time_trial_frame_begin(uint8_t*, unsigned); { if (dkr_time_trial_frame_begin(rdram, {revision})) { return; } }" +returns = "extern void dkr_time_trial_frame_end(uint8_t*, unsigned); dkr_time_trial_frame_end(rdram, {revision});" + +[[hook]] +id = "full-game-tracks-menu" +function = "menu_track_select_init" +payloads = ["funcs"] +entry = "extern void dkr_full_game_tracks_menu(uint8_t*, unsigned); dkr_full_game_tracks_menu(rdram, {revision});" + +[[hook]] +id = "time-trial-input" +function = "input_update" +payloads = ["funcs"] +returns = "extern void dkr_time_trial_input(uint8_t*, unsigned); dkr_time_trial_input(rdram, {revision});" + +[[hook]] +id = "time-trial-pause-options" +function = "menu_pause_init" +payloads = ["funcs"] +returns = "extern void dkr_time_trial_pause_options(uint8_t*, unsigned); dkr_time_trial_pause_options(rdram, {revision});" + +[[hook]] +id = "time-trial-pause-entry" +function = "menu_pause_loop" +payloads = ["funcs"] +entry = "extern void dkr_time_trial_resume(uint8_t*, unsigned); dkr_time_trial_resume(rdram, {revision});" +returns = "extern void dkr_time_trial_pause_action(recomp_context*, unsigned); dkr_time_trial_pause_action(ctx, {revision});" + +# Local ghost practice borrows the stock translucent player-ghost object. +[[hook]] +id = "practice-ghost-mount" +function = "timetrial_init_player_ghost" +payloads = ["funcs"] +entry = "extern int dkr_practice_ghost_mount(uint8_t*, unsigned); if (dkr_practice_ghost_mount(rdram, {revision})) { ctx->r2 = 0; return; }" + +[[hook]] +id = "practice-ghost-spawned" +function = "timetrial_init_staff_ghost" +payloads = ["funcs"] +entry = "extern void dkr_practice_ghost_spawned(uint8_t*, unsigned); dkr_practice_ghost_spawned(rdram, {revision});" + +[[hook]] +id = "practice-ghost-pose" +function = "timetrial_ghost_read" +payloads = ["funcs"] +entry = "extern int dkr_practice_ghost_pose(uint8_t*, recomp_context*, unsigned); if (dkr_practice_ghost_pose(rdram, ctx, {revision})) return;" + +[[hook]] +id = "practice-ghost-minimap" +function = "hud_render_general" +payloads = ["funcs"] +[[hook.edits]] +match = "timetrial_player_ghost(rdram, ctx);" +replace = '''{ extern int dkr_practice_ghost_marker(int); + if (dkr_practice_ghost_marker(0)) timetrial_player_ghost(rdram, ctx); else ctx->r2 = 0; }''' +[[hook.edits]] +match = "timetrial_ghost_staff(rdram, ctx);" +replace = '''{ extern int dkr_practice_ghost_marker(int); + if (dkr_practice_ghost_marker(1)) timetrial_ghost_staff(rdram, ctx); else ctx->r2 = 0; }''' + +# A replay's mixer follows authored updates rather than host retraces. +[[hook]] +id = "theatre-audio-clock" +function = "__amMain" +payloads = ["funcs"] +[[hook.edits]] +match = "__amHandleFrameMsg(rdram, ctx);" +replace = '''{ extern int dkr_theatre_audio_begin(void); if (!dkr_theatre_audio_begin()) goto L_80002B20; } + __amHandleFrameMsg(rdram, ctx);''' +[[hook.edits]] +match = "__amHandleDoneMsg(rdram, ctx);" +replace = '''__amHandleDoneMsg(rdram, ctx); + { extern void dkr_theatre_audio_done(void); dkr_theatre_audio_done(); }''' + +# These rolls depend on the music channel mask and only set ambience timers. +[[hook]] +id = "adventure-parkwarden-music-rng" +function = "obj_loop_parkwarden" +payloads = ["funcs"] +[[hook.edits]] +match = '''rand_range(rdram, ctx); + goto after_91;''' +replace = '''{ extern void dkr_adventure_presentation_begin(void); extern void dkr_adventure_presentation_end(void); dkr_adventure_presentation_begin(); rand_range(rdram, ctx); dkr_adventure_presentation_end(); } + goto after_91;''' +[[hook.edits]] +match = '''rand_range(rdram, ctx); + goto after_93;''' +replace = '''{ extern void dkr_adventure_presentation_begin(void); extern void dkr_adventure_presentation_end(void); dkr_adventure_presentation_begin(); rand_range(rdram, ctx); dkr_adventure_presentation_end(); } + goto after_93;''' + +# The stock car rolls these bits only to enable visual wheel particles. +[[hook]] +id = "adventure-car-particle-mask-rng" +function = "func_8004F7F4" +payloads = ["funcs"] +[[hook.edits]] +match = '''rand_range(rdram, ctx); + goto after_30;''' +replace = '''{ extern void dkr_adventure_presentation_begin(void); extern void dkr_adventure_presentation_end(void); dkr_adventure_presentation_begin(); rand_range(rdram, ctx); dkr_adventure_presentation_end(); } + goto after_30;''' +[[hook.edits]] +match = '''rand_range(rdram, ctx); + goto after_31;''' +replace = '''{ extern void dkr_adventure_presentation_begin(void); extern void dkr_adventure_presentation_end(void); dkr_adventure_presentation_begin(); rand_range(rdram, ctx); dkr_adventure_presentation_end(); } + goto after_31;''' + +# Particle pools can change which visual draws are actually evaluated. +[[hook]] +id = "adventure-particle-emission-rng" +function = "obj_trigger_emitter" +payloads = ["funcs"] +entry = "extern void dkr_adventure_presentation_begin(void); dkr_adventure_presentation_begin();" +returns = "extern void dkr_adventure_presentation_end(void); dkr_adventure_presentation_end();" + # Achievements: observe the frame after each main loop pass (achievements). [[hook]] id = "achievements-observe" diff --git a/runtime-recomp/src/android/mobile_ui.cpp b/runtime-recomp/src/android/mobile_ui.cpp index b52a99cb..9c7f2890 100644 --- a/runtime-recomp/src/android/mobile_ui.cpp +++ b/runtime-recomp/src/android/mobile_ui.cpp @@ -3,6 +3,7 @@ #include "../game/runtime_ui.hpp" #include "imgui/imgui.h" #include "imgui/imgui_internal.h" +#include "../game/dialog_style.hpp" #include #if defined(__ANDROID__) && !defined(DKR_MOBILE_UI_TEST) #include @@ -626,7 +627,10 @@ void editor() { // expose controls beneath it. Gameplay remains blocked for its lifetime. ImGui::SetNextWindowPos({safe.x + std::max(0.0F, (safe.w - 340.0F) * .5F), safe.y}, ImGuiCond_Appearing); ImGui::SetNextWindowSize({std::min(340.0F, safe.w), std::min(330.0F, safe.h)}, ImGuiCond_Appearing); - ImGui::Begin("Touch layout - options", nullptr, ImGuiWindowFlags_NoSavedSettings); + if (!ui::begin_dialog_window("Touch layout - options", nullptr, ImGuiWindowFlags_NoSavedSettings)) { + ImGui::End(); + return; + } ImGui::TextWrapped("Drag a group. Collapse this sheet to reach covered controls."); if (ImGui::BeginCombo("Group", labels[selection])) { for (int i = 0; i < group_count; ++i) diff --git a/runtime-recomp/src/game/achievement_ui.inl b/runtime-recomp/src/game/achievement_ui.inl index 77d0ffb6..82f209a0 100644 --- a/runtime-recomp/src/game/achievement_ui.inl +++ b/runtime-recomp/src/game/achievement_ui.inl @@ -2,15 +2,16 @@ namespace ach = dkr::runtime::achievements; int g_achievement_filter = 0, g_achievement_sort = 0; std::string g_achievement_category, g_achievement_detail; std::array g_achievement_search{}; +bool g_achievement_reset_scroll = false; bool g_achievement_settings = false, g_achievement_reset = false, g_achievement_recognise = false; -bool g_achievement_focus_detail = false; std::string g_achievement_focus_row; -float g_achievement_return_scroll = 0; ach::Toast g_achievement_toast; double g_achievement_toast_started = 0; SDL_AudioDeviceID g_achievement_audio = 0; -void AchievementChime() { +void AchievementChime(float gain = 1.F) { + if (gain <= 0.F) + return; if (!g_achievement_audio) { SDL_AudioSpec wanted{}, actual{}; wanted.freq = 48000; @@ -23,7 +24,7 @@ void AchievementChime() { SDL_PauseAudioDevice(g_achievement_audio, 0); } std::vector samples(48000 * 2 * 3 / 5); - const float volume = .10F * dkr::runtime::audio::sound_effects_volume(); + const float volume = gain * .10F * dkr::runtime::audio::sound_effects_volume(); for (unsigned i = 0; i < samples.size() / 2; ++i) { const float t = float(i) / 48000.F; const float envelope = std::min(t * 90.F, 1.F) * std::exp(-6.F * t); @@ -189,81 +190,145 @@ void DrawAchievementPreferences(float width, const ach::View& state) { g_achievement_settings = false; return; } - PaddockGap(18); - DetailHeading("Notifications", width); + PaddockGap(14.F); + constexpr float gap = 12.F; + const bool side_by_side = width >= 640.F; + const float column = side_by_side ? (width - gap) * .5F : width; + const auto top = ImGui::GetCursorScreenPos(); + const auto paint = [](ImDrawList* draw, ImVec2 min, ImVec2 max) { + PaddockPanel(draw, min, max, {PaddockRound(10.F), PaddockRgb(0x0C293A), PaddockRgb(kSetBorder), 1.F}); + }; + + PaddockBox notifications(column, {14.F, 14.F}); + float inner = notifications.Inner(); + DetailHeading("Notifications", inner); auto p = state.preferences; bool changed = false; - changed |= SettingsCheck("##achievement-popups", "Show unlock notifications", &p.notifications, width); - changed |= SettingsCheck("##achievement-chime", "Play unlock sound", &p.sound, width); - changed |= SettingsCheck("##achievement-motion", "Reduce notification motion", &p.reduced_motion, width); - SettingsLabel("Position", width); - const char* positions[]{"Bottom centre", "Bottom right", "Top right"}; - ImGui::SetNextItemWidth(std::min(width, 300.F)); - changed |= ImGui::Combo("##achievement-position", &p.position, positions, 3); - SettingsLabel("Size", width); - ImGui::SetNextItemWidth(std::min(width, 360.F)); - changed |= ImGui::SliderFloat("##achievement-size", &p.scale, .7F, 1.6F, "%.1fx"); - SettingsLabel("Duration", width); - ImGui::SetNextItemWidth(std::min(width, 360.F)); - changed |= ImGui::SliderFloat("##achievement-duration", &p.duration, 2.F, 10.F, "%.0f seconds"); + changed |= SettingsCheck("##achievement-popups", "Show unlock notifications", &p.notifications, inner); + changed |= SettingsCheck("##achievement-chime", "Play unlock sound", &p.sound, inner); + changed |= SettingsCheck("##achievement-motion", "Reduce notification motion", &p.reduced_motion, inner); + changed |= SettingsDropdown("##achievement-position", "Position", &p.position, + {"Bottom centre", "Bottom right", "Top right"}, inner); + PaddockGap(8.F); + int scale = static_cast(std::lround(p.scale * 10.F)); + if (SettingsRange("##achievement-size", "Size", &scale, 7, 16, inner, [](int value) { + return SettingsRangeValue{std::to_string(value / 10) + "." + std::to_string(value % 10), "x"}; + })) { + p.scale = float(scale) / 10.F; + changed = true; + } + PaddockGap(8.F); + int duration = static_cast(std::lround(p.duration)); + if (SettingsRange("##achievement-duration", "Duration", &duration, 2, 10, inner, + [](int value) { return SettingsRangeValue{std::to_string(value), " seconds"}; })) { + p.duration = float(duration); + changed = true; + } if (changed) ach::preferences(p); + PaddockGap(8.F); if (SettingsButton("Preview notification")) ach::preview(); - PaddockGap(22); - DetailHeading("Your collection", width); + const float left_height = notifications.End(paint); + + ImGui::SetCursorScreenPos(side_by_side ? ImVec2{top.x + column + gap, top.y} + : ImVec2{top.x, top.y + left_height + gap}); + PaddockBox collection(column, {14.F, 14.F}); + inner = collection.Inner(); + DetailHeading("Your collection", inner); DetailText("Achievements stay separate from your game saves. Starting another adventure will not erase them.", - width); - DumpActionRow files(width); + inner); + DumpActionRow files(inner); if (files.Button("Export backup")) AchievementFileDialog(false); if (files.Button("Import backup")) AchievementFileDialog(true); if (files.Button("Recognise existing progress")) g_achievement_recognise = true; - PaddockGap(16); + PaddockGap(16.F); if (SettingsButton("Reset achievement collection")) g_achievement_reset = true; + collection.End(paint); + ImGui::SetCursorScreenPos({top.x, std::max(top.y + left_height, ImGui::GetItemRectMax().y)}); + ImGui::Dummy({width, 0.F}); PaddockGap(18); DetailText( "Challenge objectives inspired by Delmaru's Diddy Kong Racing achievement set. Local DKR-R implementation, wording and badge designs. Not connected to RetroAchievements.", width, kSetMuted); } -void DrawAchievementsPage(float width) { - const auto state = ach::view(); - const auto& definitions = ach::catalogue(); - DrawPageHeading("ACHIEVEMENTS"); - PaddockGap(8); - DetailText("Your challenges. Your collection.", width, kSetMuted, 12); - DetailHeading(std::to_string(state->unlocked) + " / 94 unlocked", width); - ImGui::ProgressBar(float(state->unlocked) / 94.F, {width, 7.F}, ""); - PaddockGap(14); - if (!state->error.empty()) - DetailText(state->error, width, 0xFFAB72); - else if (state->status != "Saved on this device") - DetailText(state->status, width, kSetMuted); - if (g_achievement_settings) { - DrawAchievementPreferences(width, *state); - } else if (!g_achievement_detail.empty()) { - const auto found = std::find_if(definitions.begin(), definitions.end(), - [](const auto& d) { return d.id == g_achievement_detail; }); - if (found == definitions.end()) { - g_achievement_detail.clear(); - return; - } +void AchievementProgressBar(float width, float progress) { + const auto at = ImGui::GetCursorScreenPos(); + auto* draw = ImGui::GetWindowDrawList(); + const auto end = ImVec2{at.x + width, at.y + 6.F}; + PaddockFill(draw, at, end, PaddockRound(3.F), PaddockCol(0x071B28)); + const float filled = width * std::clamp(progress, 0.F, 1.F); + if (filled > 0.F) + PaddockFill(draw, at, {at.x + filled, end.y}, PaddockRound(3.F), PaddockCol(kSetWarm)); + ImGui::Dummy({width, 6.F}); +} + +bool AchievementHasProgress(const ach::Definition& badge) { + return badge.target > 1 && badge.kind != ach::Kind::TimeTrial && badge.kind != ach::Kind::Developer; +} + +bool DrawAchievementGalleryCard(const ach::Definition& badge, const ach::Entry& entry, float width, float height, + bool pinned) { + ImGui::PushID(badge.id.c_str()); + if (g_achievement_focus_row == badge.id) { + ImGui::SetKeyboardFocusHere(); + g_achievement_focus_row.clear(); + } + const auto press = PaddockBeginPress("##badge", {width, height}); + auto* draw = ImGui::GetWindowDrawList(); + const bool active = ImGui::IsItemFocused() || press.hovered; + PaddockPanel(draw, press.min, press.max, + {PaddockRound(10.F), PaddockRgb(active ? 0x123C4E : 0x0C293A), + PaddockRgb(active ? kSetWarm : kSetBorder), 1.F}); + constexpr float pad = 11.F; + DrawAchievementBadge({press.min.x + pad, press.min.y + 8.F}, 36.F, AchievementBadge(badge), entry.unlocked); + const auto title = PaddockReading(16.F, true, 1.17F); + const auto meta = PaddockReading(13.F, false, 1.24F); + const float category_width = std::min(PaddockMeasure(meta, badge.category), width - 64.F); + PaddockTextAt(draw, meta, {press.max.x - pad - category_width, press.min.y + 14.F}, category_width + 0.5F, + badge.category, {PaddockRgb(kSetMuted)}); + PaddockTextAt(draw, title, {press.min.x + pad, press.min.y + 50.F}, width - 2.F * pad, badge.title, + {PaddockRgb(kSetText)}); + const bool progress = AchievementHasProgress(badge) && !entry.unlocked; + const std::string status = + entry.unlocked ? (entry.restored ? "Recognised" : "Unlocked") + : pinned ? "Pinned" + : progress ? std::to_string(std::clamp(entry.progress, 0, badge.target)) + " / " + std::to_string(badge.target) + : "Locked"; + PaddockTextAt(draw, meta, {press.min.x + 12.F, press.max.y - (progress ? 34.F : 25.F)}, width - 24.F, status, + {PaddockRgb(entry.unlocked ? 0x42D6BC + : pinned ? kSetWarm + : kSetMuted)}); + if (progress) { + const float y = press.max.y - 12.F; + const float fraction = std::clamp(float(entry.progress) / float(badge.target), 0.F, 1.F); + PaddockFill(draw, {press.min.x + 12.F, y}, {press.max.x - 12.F, y + 4.F}, PaddockRound(2.F), + PaddockCol(0x071B28)); + if (fraction > 0.F) + PaddockFill(draw, {press.min.x + 12.F, y}, {press.min.x + 12.F + (width - 24.F) * fraction, y + 4.F}, + PaddockRound(2.F), PaddockCol(kSetWarm)); + } + ImGui::PopID(); + return press.pressed; +} + +void DrawAchievementDetail(const ach::View& state, const std::vector& definitions) { + const auto found = std::ranges::find(definitions, g_achievement_detail, &ach::Definition::id); + if (found == definitions.end()) + return; + if (BeginSettingsDialog("##achievement-detail", found->title, 570.F, 0x0C293A)) { const auto index = std::size_t(found - definitions.begin()); - const auto& entry = state->entries[index]; - if (g_achievement_focus_detail) { - ImGui::SetKeyboardFocusHere(); - g_achievement_focus_detail = false; - } - if (SettingsButton("Back to achievements") || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)) { - g_achievement_focus_row = g_achievement_detail; - g_achievement_detail.clear(); - ImGui::SetScrollY(g_achievement_return_scroll); - } - PaddockGap(18); - DetailHeading(found->title, width); + const auto& entry = state.entries[index]; + const float width = SettingsDialogInner(); + const auto summary = ImGui::GetCursorScreenPos(); + DrawAchievementBadge(summary, 44.F, AchievementBadge(*found), entry.unlocked); + ImGui::SetCursorScreenPos({summary.x + 56.F, summary.y + 10.F}); + DetailText(found->category, width - 56.F, kSetWarm); + ImGui::SetCursorScreenPos({summary.x, summary.y + 51.F}); DetailText(found->description, width); DetailText(entry.unlocked ? (entry.restored ? "Recognised from existing progress" : entry.modded ? "Unlocked during modded play" @@ -291,14 +356,15 @@ void DrawAchievementsPage(float width) { char target[48]; std::snprintf(target, sizeof(target), "Target: %d:%02d.%02d", hundredths / 6000, (hundredths / 100) % 60, hundredths % 100); - DetailText(target, width); + constexpr const char* vehicles[]{"Car", "Hovercraft", "Plane"}; + DetailText(std::string(target) + " | " + vehicles[c->vehicle], width); } } else if (found->target > 1) { DetailText(std::to_string(entry.progress) + " / " + std::to_string(found->target), width); - ImGui::ProgressBar(float(entry.progress) / float(found->target), {width, 7.F}, ""); + AchievementProgressBar(width, float(entry.progress) / float(found->target)); } - if (!entry.unlocked && SettingsButton(state->pinned == found->id ? "Unpin goal" : "Pin goal")) - ach::pin(state->pinned == found->id ? "" : found->id); + if (!entry.unlocked && SettingsButton(state.pinned == found->id ? "Unpin goal" : "Pin goal")) + ach::pin(state.pinned == found->id ? "" : found->id); if (!entry.unlocked && found->restorable && entry.progress >= found->target) DetailText( "This milestone is already present in your save. Settings lets you recognise existing progress explicitly.", @@ -310,119 +376,208 @@ void DrawAchievementsPage(float width) { found->kind == ach::Kind::TimeTrial)) DetailText("Original course only. Custom courses and custom cups do not count for this goal.", width, kSetMuted); + PaddockGap(14.F); + if (SettingsButton("Back to gallery") || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)) { + g_achievement_focus_row = g_achievement_detail; + ImGui::CloseCurrentPopup(); + } + EndSettingsDialog(); + } +} + +void DrawAchievementGallery(float width, const ach::View& state, const std::vector& definitions) { + const auto pinned = std::ranges::find(definitions, state.pinned, &ach::Definition::id); + const std::string footer = + pinned == definitions.end() ? "Select a badge to see how to unlock it." : "Pinned goal: " + pinned->title; + const auto footer_type = PaddockReading(14.F, false, 1.35F); + const float footer_height = PaddockTextHeight(footer_type, footer, width); + const float height = std::max(112.F, PanelFooterBounds(ImGui::GetCurrentWindow()).Max.y - + ImGui::GetCursorScreenPos().y - footer_height - 24.F); + PaddockGap(10.F); + bool opened = false; + if (std::exchange(g_achievement_reset_scroll, false)) + ImGui::SetNextWindowScroll({-1.F, 0.F}); + if (ImGui::BeginChild("##badge-gallery", {width, height}, false, + ImGuiWindowFlags_NavFlattened | ImGuiWindowFlags_NoBackground)) { + LibraryNavigationScrollWindow(ImGui::GetCurrentWindow()); + std::vector entries; + const auto lower = [](std::string text) { + std::transform(text.begin(), text.end(), text.begin(), + [](unsigned char c) { return char(std::tolower(c)); }); + return text; + }; + const auto search = lower(g_achievement_search.data()); + for (unsigned i = 0; i < definitions.size(); ++i) { + const auto& badge = definitions[i]; + const auto& entry = state.entries[i]; + if ((g_achievement_filter == 1 && entry.unlocked) || (g_achievement_filter == 2 && !entry.unlocked) || + (!g_achievement_category.empty() && badge.category != g_achievement_category)) + continue; + if (search.empty() || + lower(badge.title + " " + badge.description + " " + badge.category).find(search) != std::string::npos) + entries.push_back(i); + } + if (g_achievement_sort == 1) { + std::stable_sort(entries.begin(), entries.end(), + [&](unsigned a, unsigned b) { return state.entries[a].when > state.entries[b].when; }); + } else if (g_achievement_sort == 2) { + const auto completion = [&](unsigned i) { + return state.entries[i].unlocked ? 1.F + : AchievementHasProgress(definitions[i]) + ? std::clamp(float(state.entries[i].progress) / float(definitions[i].target), 0.F, 1.F) + : 0.F; + }; + std::stable_sort(entries.begin(), entries.end(), + [&](unsigned a, unsigned b) { return completion(a) > completion(b); }); + } + constexpr float gap = 9.F; + const float available = ImGui::GetContentRegionAvail().x - 4.F; + const std::size_t columns = available >= 660.F ? 3U : available >= 420.F ? 2U : 1U; + const float card_width = std::floor((available - gap * float(columns - 1U)) / float(columns)); + const auto at = ImGui::GetCursorScreenPos(); + const auto title = PaddockReading(16.F, true, 1.17F); + float y = at.y; + for (std::size_t row = 0; row < entries.size(); row += columns) { + const auto end = std::min(row + columns, entries.size()); + float card_height = 109.F; + for (std::size_t index = row; index < end; ++index) { + const auto& badge = definitions[entries[index]]; + card_height = std::max(card_height, 87.F + PaddockTextHeight(title, badge.title, card_width - 22.F)); + } + for (std::size_t index = row; index < end; ++index) { + const unsigned id = entries[index]; + const auto& badge = definitions[id]; + ImGui::SetCursorScreenPos({at.x + float(index - row) * (card_width + gap), y}); + if (DrawAchievementGalleryCard(badge, state.entries[id], card_width, card_height, + state.pinned == badge.id)) { + g_achievement_detail = badge.id; + opened = true; + } + } + y += card_height + gap; + } + if (entries.empty()) + DetailText("No achievements match those filters.", available, kSetMuted); + } + ImGui::EndChild(); + PaddockGap(6.F); + PaddockText(footer_type, PaddockRgb(kSetMuted), footer, width); + if (opened) + ImGui::OpenPopup("##achievement-detail"); + DrawAchievementDetail(state, definitions); +} + +void DrawAchievementsPage(float width) { + const auto state = ach::view(); + const auto& definitions = ach::catalogue(); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0}); + const auto header = ImGui::GetCursorScreenPos(); + DrawPageHeading("ACHIEVEMENTS"); + const auto below = ImGui::GetCursorScreenPos(); + const float back_width = SettingsButtonWidth("Back to Play"); + if (width >= 440.F) + ImGui::SetCursorScreenPos({header.x + width - back_width, header.y + 11.F}); + if (PaddockTextLink("Back to Play")) + g_page_navigation_request = kPagePlay; + ImGui::SetCursorScreenPos({header.x, std::max(below.y, ImGui::GetItemRectMax().y) + 10.F}); + if (g_achievement_settings) { + DrawAchievementPreferences(width, *state); } else { - if (ImGui::IsKeyPressed(ImGuiKey_GamepadL1, false)) - g_achievement_filter = (g_achievement_filter + 2) % 3; - if (ImGui::IsKeyPressed(ImGuiKey_GamepadR1, false)) - g_achievement_filter = (g_achievement_filter + 1) % 3; - DumpActionRow actions(width); - for (int i = 0; i < 3; ++i) { - const char* labels[]{"All", "Locked", "Unlocked"}; - if (actions.Button(labels[i], false, - i == g_achievement_filter ? SettingsButtonTone::Selected : SettingsButtonTone::Plain)) - g_achievement_filter = i; + { + PaddockBox collection(width, {12.F, 10.F}); + const float inner = collection.Inner(); + const auto at = ImGui::GetCursorScreenPos(); + const auto text = + std::to_string(state->unlocked) + " / " + std::to_string(definitions.size()) + " unlocked"; + const auto type = PaddockReading(15.F, true, 1.22F); + const float text_width = PaddockMeasure(type, text) + 1.F; + PaddockText(type, PaddockRgb(kSetText), text, inner); + if (inner >= text_width + 112.F) { + ImGui::SetCursorScreenPos({at.x + text_width + 12.F, at.y + (type.line - 6.F) * .5F}); + AchievementProgressBar(inner - text_width - 12.F, float(state->unlocked) / float(definitions.size())); + ImGui::SetCursorScreenPos({at.x, at.y + type.line}); + ImGui::Dummy({inner, 0.F}); + } else { + PaddockGap(4.F); + AchievementProgressBar(inner, float(state->unlocked) / float(definitions.size())); + } + collection.End([](ImDrawList* draw, ImVec2 min, ImVec2 max) { + PaddockPanel(draw, min, max, {PaddockRound(10.F), PaddockRgb(0x0C293A), PaddockRgb(kSetBorder), 1.F}); + }); + } + if (!state->error.empty()) + DetailText(state->error, width, 0xFFAB72); + else if (state->status != "Saved on this device") + DetailText(state->status, width, kSetMuted); + PaddockGap(10.F); + const int previous_filter = g_achievement_filter; + if (!ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId)) { + if (ImGui::IsKeyPressed(ImGuiKey_GamepadL1, false)) + g_achievement_filter = (g_achievement_filter + 2) % 3; + if (ImGui::IsKeyPressed(ImGuiKey_GamepadR1, false)) + g_achievement_filter = (g_achievement_filter + 1) % 3; } - if (actions.Button("Settings")) + const auto tabs = ImGui::GetCursorScreenPos(); + const float settings_width = SettingsButtonWidth("Settings"); + const bool inline_settings = width >= 440.F; + const int filter = SettingsSectionSigns({"ALL", "LOCKED", "UNLOCKED"}, g_achievement_filter, + width - (inline_settings ? settings_width + 9.F : 0.F), true); + if (filter >= 0) + g_achievement_filter = filter; + g_achievement_reset_scroll |= previous_filter != g_achievement_filter; + const float after_tabs = ImGui::GetCursorScreenPos().y; + if (inline_settings) + ImGui::SetCursorScreenPos({tabs.x + width - settings_width, tabs.y}); + if (SettingsButton("Settings", settings_width)) g_achievement_settings = true; - PaddockGap(12); - ImGui::SetNextItemWidth(width >= 240.F ? width - 115.F : width); - ImGui::InputTextWithHint("##achievement-search", "Find an achievement...", g_achievement_search.data(), - g_achievement_search.size()); - if (width >= 240.F) - ImGui::SameLine(); - if (SettingsButton("Keyboard", 100.F)) + ImGui::SetCursorScreenPos({tabs.x, std::max(after_tabs, ImGui::GetItemRectMax().y) + 9.F}); + const bool wide = width >= 620.F; + constexpr float gap = 9.F; + const float field = wide ? std::clamp(width * .25F, 210.F, 240.F) : (width - gap) * .5F; + const float search_width = wide ? width - 2.F * (field + gap) : width; + const auto toolbar = ImGui::GetCursorScreenPos(); + SettingsLabel("Search achievements", search_width); + const auto search = PaddockSearch("achievements", g_achievement_search.data(), g_achievement_search.size(), + "Find an achievement...", search_width); + g_achievement_reset_scroll |= search == PaddockFieldResult::Edited; + if (search == PaddockFieldResult::GamepadActivated) { RequestCustomTextKeyboard("Find an achievement", g_achievement_search.data(), g_achievement_search.size(), [](const std::string& value) { std::snprintf(g_achievement_search.data(), g_achievement_search.size(), "%s", value.c_str()); + g_achievement_reset_scroll = true; }); - PaddockGap(10); - std::vector groups{"All categories"}; - for (const auto& d : definitions) - if (std::find(groups.begin(), groups.end(), d.category) == groups.end()) - groups.push_back(d.category); - ImGui::SetNextItemWidth(std::min(width, 260.F)); - if (ImGui::BeginCombo("##achievement-category", - g_achievement_category.empty() ? "All categories" : g_achievement_category.c_str())) { - for (unsigned i = 0; i < groups.size(); ++i) - if (ImGui::Selectable(groups[i].c_str(), g_achievement_category == groups[i])) - g_achievement_category = i ? groups[i] : ""; - ImGui::EndCombo(); - } - const char* sorts[]{"Collection order", "Recently unlocked", "Most progress"}; - ImGui::SetNextItemWidth(std::min(width, 260.F)); - ImGui::Combo("##achievement-sort", &g_achievement_sort, sorts, 3); - std::vector entries; - std::string search = g_achievement_search.data(); - std::transform(search.begin(), search.end(), search.begin(), - [](unsigned char c) { return char(std::tolower(c)); }); - for (unsigned i = 0; i < definitions.size(); ++i) { - const auto& d = definitions[i]; - const auto& e = state->entries[i]; - if ((g_achievement_filter == 1 && e.unlocked) || (g_achievement_filter == 2 && !e.unlocked) || - (!g_achievement_category.empty() && d.category != g_achievement_category)) - continue; - auto text = d.title + " " + d.description; - std::transform(text.begin(), text.end(), text.begin(), - [](unsigned char c) { return char(std::tolower(c)); }); - if (!search.empty() && text.find(search) == std::string::npos) - continue; - entries.push_back(i); } - if (g_achievement_sort) - std::stable_sort(entries.begin(), entries.end(), [&](unsigned a, unsigned b) { - return g_achievement_sort == 1 ? state->entries[a].when > state->entries[b].when - : double(state->entries[a].progress) / definitions[a].target > - double(state->entries[b].progress) / definitions[b].target; - }); - PaddockGap(12); - if (entries.empty()) - DetailText("No achievements match those filters.", width, kSetMuted); - const auto heading = PaddockReading(17.F, true, 1.3F), body = PaddockReading(14.F, false, 1.3F); - for (const auto index : entries) { - const auto& d = definitions[index]; - const auto& e = state->entries[index]; - ImGui::PushID(d.id.c_str()); - const float badge = 48.F, text_width = std::max(50.F, width - 88.F); - const auto wrapped = body.font->CalcTextSizeA(body.size, FLT_MAX, text_width, d.description.c_str()); - const auto title_size = heading.font->CalcTextSizeA(heading.size, FLT_MAX, text_width, d.title.c_str()); - const float height = std::max(90.F, title_size.y + wrapped.y + 43.F); - if (g_achievement_focus_row == d.id) { - ImGui::SetKeyboardFocusHere(); - g_achievement_focus_row.clear(); + const float search_bottom = ImGui::GetItemRectMax().y; + const float category_x = wide ? toolbar.x + search_width + gap : toolbar.x; + const float filters_y = wide ? toolbar.y : search_bottom + gap; + std::vector categories{{"All categories", {}, false}}; + int selected = 0; + for (const auto& badge : definitions) { + if (std::ranges::find(categories, badge.category, &SettingsChoice::label) == categories.end()) { + if (g_achievement_category == badge.category) + selected = static_cast(categories.size()); + categories.push_back({badge.category, {}, false}); } - const auto at = ImGui::GetCursorScreenPos(); - if (ImGui::Button("##open", {width, height})) { - g_achievement_detail = d.id; - g_achievement_return_scroll = ImGui::GetScrollY(); - g_achievement_focus_detail = true; - ImGui::SetScrollY(0); - } - auto* draw = ImGui::GetWindowDrawList(); - draw->AddRectFilled(at, {at.x + width, at.y + height}, PaddockRgb(0x10364A), 12); - draw->AddRect(at, {at.x + width, at.y + height}, - PaddockRgb(ImGui::IsItemFocused() || ImGui::IsItemHovered() ? 0xFFCB66 : 0x296B70), 12); - DrawAchievementBadge({at.x + 12, at.y + 14}, badge, AchievementBadge(d), e.unlocked); - const ImVec2 text{at.x + 74, at.y + 12}; - draw->AddText(heading.font, heading.size, text, PaddockRgb(0xFFF6DA), d.title.c_str(), nullptr, text_width); - draw->AddText(body.font, body.size, {text.x, text.y + title_size.y + 5}, PaddockRgb(0xB0C9CC), - d.description.c_str(), nullptr, text_width); - const std::string status = e.unlocked ? (e.restored ? "Recognised" : "Unlocked") - : e.progress > 0 ? std::to_string(e.progress) + " / " + std::to_string(d.target) - : "Locked"; - draw->AddText(body.font, body.size, {text.x, at.y + height - body.line - 8}, - PaddockRgb(e.unlocked ? 0x42D6BC : 0xB0C9CC), status.c_str()); - ImGui::PopID(); - PaddockGap(8); } - DetailText("A: Open B: Back LB / RB: Filter", width, kSetMuted); - } - if (!state->pinned.empty()) { - const auto found = - std::find_if(definitions.begin(), definitions.end(), [&](auto& d) { return d.id == state->pinned; }); - if (found != definitions.end()) - DetailText("Pinned: " + found->title, width, kSetMuted); + ImGui::SetCursorScreenPos({category_x, filters_y}); + ImGui::BeginGroup(); + if (SettingsDropdown("##achievement-category", "Category", &selected, categories, field, false, {}, 44.F)) { + g_achievement_category = selected ? categories[selected].label : ""; + g_achievement_reset_scroll = true; + } + ImGui::EndGroup(); + ImGui::SetCursorScreenPos({category_x + field + gap, filters_y}); + ImGui::BeginGroup(); + g_achievement_reset_scroll |= + SettingsDropdown("##achievement-sort", "Sort by", &g_achievement_sort, + {"Collection order", "Recently unlocked", "Most progress"}, field, false, {}, 44.F); + ImGui::EndGroup(); + ImGui::SetCursorScreenPos({toolbar.x, std::max(search_bottom, ImGui::GetItemRectMax().y)}); + ImGui::Dummy({width, 0.F}); + DrawAchievementGallery(width, *state, definitions); } + ImGui::PopStyleVar(); if (g_achievement_reset) { ImGui::OpenPopup("Reset achievements##confirm"); g_achievement_reset = false; diff --git a/runtime-recomp/src/game/cloud_saves/jobs.inl b/runtime-recomp/src/game/cloud_saves/jobs.inl new file mode 100644 index 00000000..5ebb86a6 --- /dev/null +++ b/runtime-recomp/src/game/cloud_saves/jobs.inl @@ -0,0 +1,26 @@ +std::string EnabledCloudSaveAccount() { + const auto profile = dkr::store::service().view(); + auto account = dkr::store::text(profile->user, "id", 160); + return account == profile->cloud_saves_account ? std::move(account) : std::string{}; +} + +bool RunCloudSaveSync(std::string account, dkr::cloud_saves::SyncScope scope = dkr::cloud_saves::SyncScope::All) { + return BeginSharedSaveJob( + [account = std::move(account), scope](std::string&) { + dkr::store::service().sync_cloud_saves(account, scope); + return true; + }, + "Cloud Saves checked. See Save Manager for details."); +} + +void ToggleCloudSaves(std::string account, bool enabled) { + BeginSharedSaveJob( + [account = std::move(account), enabled](std::string&) { + auto& service = dkr::store::service(); + service.set_cloud_saves(account, enabled); + if (enabled) + service.sync_cloud_saves(account); + return true; + }, + enabled ? "Cloud Saves enabled on this device." : "Cloud Saves paused on this device."); +} diff --git a/runtime-recomp/src/game/cloud_saves/play_ui.inl b/runtime-recomp/src/game/cloud_saves/play_ui.inl new file mode 100644 index 00000000..fcb148d0 --- /dev/null +++ b/runtime-recomp/src/game/cloud_saves/play_ui.inl @@ -0,0 +1,124 @@ +void DrawCloudStatusGlyph(ImDrawList* draw, ImVec2 centre, dkr::cloud_saves::SyncStatus status, bool enabled) { + using dkr::cloud_saves::SyncStatus; + const bool animate = !dkr::runtime::achievements::view()->preferences.reduced_motion; + const float phase = animate ? float(std::fmod(ImGui::GetTime(), 10.0)) * 6.2831853F : 0.F; + const auto point = [&](float x, float y) { return ImVec2{centre.x + x, centre.y + y}; }; + const unsigned colour = status == SyncStatus::Synced ? 0x5CE1B8 + : status == SyncStatus::Error ? 0xFFB366 + : status == SyncStatus::Unreachable ? 0x8EBDD3 + : enabled ? 0xB9E7F5 + : 0x829EAB; + const auto ink = PaddockCol(colour); + draw->PathLineTo(point(-7.F, 5.F)); + draw->PathBezierCubicCurveTo(point(-15.F, 5.F), point(-15.F, -5.F), point(-8.F, -5.F)); + draw->PathBezierCubicCurveTo(point(-5.F, -13.F), point(5.F, -12.F), point(8.F, -5.F)); + draw->PathBezierCubicCurveTo(point(15.F, -5.F), point(15.F, 5.F), point(8.F, 5.F)); + draw->PathStroke(ink, ImDrawFlags_Closed, 1.6F); + + const auto badge = point(8.F, 5.F); + if (status == SyncStatus::Unreachable) { + const float offset = std::sin(phase * 0.2F) * 1.8F; + const auto first = point(-11.F + offset, 9.F); + const auto last = point(11.F + offset, -10.F); + draw->AddLine(first, last, PaddockCol(0x0A2938), 4.F); + draw->AddLine(first, last, ink, 2.F); + } else if (status != SyncStatus::Idle) { + draw->AddCircleFilled(badge, 6.F, PaddockCol(0x0A2938)); + if (status == SyncStatus::Syncing) { + draw->PathArcTo(badge, 4.5F, phase, phase + 4.5F, 14); + draw->PathStroke(ink, 0, 1.7F); + } else if (status == SyncStatus::Error) { + const float radius = 4.8F + std::sin(phase * 0.2F) * 0.9F; + draw->AddCircle(badge, radius, ink, 16, 1.25F); + draw->AddLine(point(8.F, 2.3F), point(8.F, 5.3F), ink, 1.4F); + draw->AddCircleFilled(point(8.F, 7.2F), 0.8F, ink); + } else { + const ImVec2 tick[]{point(4.5F, 5.F), point(7.F, 7.4F), point(12.F, 2.3F)}; + draw->AddPolyline(tick, 3, ink, 0, 1.8F); + } + } +} + +void CloudControlTooltip(std::string_view action, std::string_view detail = {}) { + if (!ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) || action.empty()) + return; + const dkr::runtime::ui::ScopedDialogStyle style({12.F, 8.F}, 10.F); + ImGui::BeginTooltip(); + ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + 275.F); + ImGui::TextUnformatted(action.data(), action.data() + action.size()); + if (!detail.empty() && detail != action) + ImGui::TextUnformatted(detail.data(), detail.data() + detail.size()); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); +} + +constexpr float kPlayCloudControlHeight = 36.F; +constexpr float kPlayCloudGap = 6.F; +constexpr float kPlayCloudIconWidth = 42.F; + +float PlayCloudSwitchWidth() { + return std::ceil(PaddockMeasure(PaddockReading(13.F, true, 1.3F), dkr::localisation::source("Cloud Saves"))) + 61.F; +} + +void DrawPlayCloudSaves(float width, bool locked) { + using dkr::cloud_saves::SyncStatus; + auto& service = dkr::store::service(); + const auto view = service.view(); + const auto account = dkr::store::text(view->user, "id", 160); + const bool enabled = !account.empty() && view->cloud_saves_account == account; + const auto status = account.empty() ? SyncStatus::Idle : view->cloud_sync; + const bool busy = SharedSaveBusy() || status == SyncStatus::Syncing; + const bool blocked = locked || busy || view->signing_in; + const auto caption = dkr::localisation::source("Cloud Saves"); + const auto type = PaddockReading(13.F, true, 1.3F); + const bool inline_icon = width >= kPlayCloudIconWidth + kPlayCloudGap + 92.F; + const float switch_width = + std::min(width - (inline_icon ? kPlayCloudIconWidth + kPlayCloudGap : 0.F), PlayCloudSwitchWidth()); + + ImGui::BeginDisabled(blocked); + const auto toggle = PaddockBeginPress("##play-cloud-opt-in", {switch_width, kPlayCloudControlHeight}); + auto* draw = ImGui::GetWindowDrawList(); + draw->AddRectFilled(toggle.min, toggle.max, PaddockCol(toggle.hovered ? 0x153C4C : 0x0A2938), 8.F); + draw->AddRect(toggle.min, toggle.max, PaddockCol(0x375F71), 8.F); + const ImVec2 track{toggle.min.x + 10.F, toggle.min.y + 9.F}; + draw->AddRectFilled(track, {track.x + 34.F, track.y + 18.F}, PaddockCol(enabled ? 0x12B99B : 0x32576A), 9.F); + draw->AddCircleFilled({track.x + (enabled ? 25.F : 9.F), track.y + 9.F}, 6.5F, PaddockCol(0xFFF3C9), 16); + const auto label = PaddockEllipsize(type, caption, switch_width - 61.F); + PaddockDrawRun(draw, type, {toggle.min.x + 52.F, toggle.min.y + (kPlayCloudControlHeight - type.line) * 0.5F}, + PaddockCol(0xFFF6DA), label.data(), label.data() + label.size()); + PaddockEndPress(toggle, 8.F); + ImGui::EndDisabled(); + const char* toggle_hint = view->signing_in ? "Waiting for Discord sign-in." + : locked ? "Return to the launcher to change Cloud Saves." + : account.empty() ? "Sign in with Discord to enable Cloud Saves." + : enabled ? "Pause Cloud Saves on this device." + : "Enable Cloud Saves on this device."; + CloudControlTooltip(dkr::localisation::source(toggle_hint)); + if (toggle.pressed) { + if (account.empty()) + service.login(); + else + ToggleCloudSaves(account, !enabled); + } + + if (inline_icon) + ImGui::SameLine(0.F, kPlayCloudGap); + ImGui::BeginDisabled(blocked || !enabled); + const auto sync = + PaddockBeginPress("##play-cloud-sync", {std::min(width, kPlayCloudIconWidth), kPlayCloudControlHeight}); + draw->AddRectFilled(sync.min, sync.max, PaddockCol(sync.hovered ? 0x153C4C : 0x0A2938), 8.F); + draw->AddRect(sync.min, sync.max, PaddockCol(0x375F71), 8.F); + DrawCloudStatusGlyph(draw, {(sync.min.x + sync.max.x) * 0.5F, (sync.min.y + sync.max.y) * 0.5F}, status, enabled); + PaddockEndPress(sync, 8.F); + ImGui::EndDisabled(); + + const char* sync_hint = status == SyncStatus::Syncing ? "Syncing Cloud Saves..." + : locked ? "Return to the launcher to sync." + : busy ? "Waiting for the current save operation." + : enabled ? "Sync Cloud Saves now" + : "Enable Cloud Saves to sync."; + CloudControlTooltip(dkr::localisation::source(sync_hint), + account.empty() ? std::string_view{} : dkr::localisation::source(view->cloud_saves_status)); + if (sync.pressed) + RunCloudSaveSync(account); +} diff --git a/runtime-recomp/src/game/cloud_saves/progress.hpp b/runtime-recomp/src/game/cloud_saves/progress.hpp new file mode 100644 index 00000000..6a0d3774 --- /dev/null +++ b/runtime-recomp/src/game/cloud_saves/progress.hpp @@ -0,0 +1,107 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dkr::cloud_saves { +struct ProgressBatch { + unsigned account_generation; + std::set slots; +}; + +class ProgressWrites { + public: + using Clock = std::chrono::steady_clock; + using Routes = std::vector>; + + void configure(Routes next) { + std::scoped_lock lock(mutex_); + routes_ = std::move(next); + pending_.clear(); + } + void gameplay(bool active) { + std::scoped_lock lock(mutex_); + gameplay_ = active; + if (!active) { + toast_until_ = 0; + next_toast_ = {}; + } + } + void account(std::optional generation) { + std::scoped_lock lock(mutex_); + if (generation == account_) + return; + account_ = generation; + pending_.clear(); + retry_at_ = {}; + changed_.notify_all(); + } + void committed(const std::filesystem::path& path, Clock::time_point now = Clock::now()) { + std::scoped_lock lock(mutex_); + if (!gameplay_) + return; + if (now >= next_toast_) { + toast_until_ = milliseconds(now + std::chrono::milliseconds(850)); + next_toast_ = now + std::chrono::milliseconds(1050); + } + if (account_) { + for (const auto& [candidate, slot] : routes_) { + if (candidate == path) { + pending_.insert(slot); + changed_.notify_one(); + break; + } + } + } + } + bool visible(Clock::time_point now = Clock::now()) const { + return milliseconds(now) < toast_until_.load(); + } + std::optional take(std::stop_token stop) { + std::unique_lock lock(mutex_); + while (!stop.stop_requested()) { + if (!changed_.wait(lock, stop, [&] { return account_ && !pending_.empty(); })) + break; + const auto account = account_; + if (changed_.wait_until(lock, stop, retry_at_, [&] { return account_ != account; })) + continue; + if (!stop.stop_requested()) + return ProgressBatch{*account, std::exchange(pending_, {})}; + } + return std::nullopt; + } + void retry(const ProgressBatch& batch) { + std::scoped_lock lock(mutex_); + if (account_ != batch.account_generation) + return; + pending_.insert(batch.slots.begin(), batch.slots.end()); + retry_at_ = Clock::now() + std::chrono::seconds(5); + changed_.notify_one(); + } + + private: + static std::int64_t milliseconds(Clock::time_point time) { + return std::chrono::duration_cast(time.time_since_epoch()).count(); + } + + std::mutex mutex_; + std::condition_variable_any changed_; + Routes routes_; + std::set pending_; + std::optional account_; + Clock::time_point retry_at_, next_toast_; + std::atomic toast_until_{0}; + bool gameplay_ = false; +}; + +inline ProgressWrites progress_writes; +} // namespace dkr::cloud_saves diff --git a/runtime-recomp/src/game/cloud_saves/sync.hpp b/runtime-recomp/src/game/cloud_saves/sync.hpp new file mode 100644 index 00000000..f75c831b --- /dev/null +++ b/runtime-recomp/src/game/cloud_saves/sync.hpp @@ -0,0 +1,29 @@ +#pragma once +#include + +namespace dkr::cloud_saves { +enum class Action { None, Upload, Download, Defer }; +enum class SyncScope { All, PublishHostedOnline, PublishProgress }; +enum class SyncStatus { Idle, Syncing, Synced, Error, Unreachable }; + +constexpr SyncStatus sync_failure(bool transport_failed, unsigned http_status) { + const bool unavailable = (http_status >= 502 && http_status <= 504) || (http_status >= 521 && http_status <= 524); + return transport_failed || unavailable ? SyncStatus::Unreachable : SyncStatus::Error; +} + +constexpr bool includes_slot(SyncScope scope, std::string_view key) { + return scope != SyncScope::PublishHostedOnline || key.starts_with("online-"); +} + +constexpr Action next_action(std::string_view local, std::string_view cloud, std::string_view common, + SyncScope scope = SyncScope::All) { + if (local == cloud) + return Action::None; + // A missing cloud slot can be seeded. Existing cloud progress can be + // advanced only from the copy this device last synchronized. + if (!local.empty() && (cloud.empty() || cloud == common)) + return Action::Upload; + // Publish-only syncs leave a running game or an agreed lobby seed intact. + return scope == SyncScope::All ? Action::Download : Action::Defer; +} +} // namespace dkr::cloud_saves \ No newline at end of file diff --git a/runtime-recomp/src/game/cloud_saves/ui.inl b/runtime-recomp/src/game/cloud_saves/ui.inl new file mode 100644 index 00000000..c0a3b6be --- /dev/null +++ b/runtime-recomp/src/game/cloud_saves/ui.inl @@ -0,0 +1,27 @@ +void DrawCloudSaves(float width, bool locked) { + auto& service = dkr::store::service(); + const auto view = service.view(); + const auto account = dkr::store::text(view->user, "id", 160); + if (account.empty()) { + SavesNote("Sign in with Discord to sync saves between your devices.", width); + if (SavesRaceButton("SIGN IN WITH DISCORD", 0, SavesTone::Primary, locked || view->signing_in)) + service.login(); + return; + } + const bool enabled = view->cloud_saves_account == account; + SavesNote( + "Existing cloud saves take priority. Progress made from a synced save is uploaded when its cloud copy is current.", + width); + PaddockGap(12); + if (SavesRaceButton(enabled ? "PAUSE CLOUD SAVES" : "ENABLE CLOUD SAVES", 0, + enabled ? SavesTone::Plain : SavesTone::Primary, locked)) { + ToggleCloudSaves(account, !enabled); + } + if (!enabled) + return; + PaddockGap(12); + if (SavesRaceButton("SYNC NOW", 0, SavesTone::Primary, locked)) + RunCloudSaveSync(account); + if (!view->cloud_saves_status.empty()) + SavesNote(view->cloud_saves_status, width); +} \ No newline at end of file diff --git a/runtime-recomp/src/game/custom_records.hpp b/runtime-recomp/src/game/custom_records.hpp index 882a43b4..c7afcd47 100644 --- a/runtime-recomp/src/game/custom_records.hpp +++ b/runtime-recomp/src/game/custom_records.hpp @@ -84,6 +84,7 @@ inline bool valid(std::span bytes) { // Normal guest hooks enqueue copies only. No disk access during replay. bool begin(const std::filesystem::path& path, bool restore, std::string& error); Bytes seed(); +bool begin_memory(std::span bytes, std::string& error); void submit(Bytes bytes); bool finish(std::string& error); bool persist(const std::filesystem::path& path, std::span bytes, std::string& error); diff --git a/runtime-recomp/src/game/custom_tracks.cpp b/runtime-recomp/src/game/custom_tracks.cpp index 72fda942..5920beb3 100644 --- a/runtime-recomp/src/game/custom_tracks.cpp +++ b/runtime-recomp/src/game/custom_tracks.cpp @@ -84,6 +84,11 @@ bool g_auto_boot_consumed = false; std::mutex g_mutex; std::vector g_tracks; +std::vector g_replay_tracks; + +const std::vector& active_tracks_locked() { + return g_replay_tracks.empty() ? g_tracks : g_replay_tracks; +} std::array g_sections{}; std::unordered_map g_resolved_level_ids; std::filesystem::path g_directory; @@ -383,6 +388,62 @@ std::vector tracks() { return g_tracks; } +namespace { +const Entry* replay_header(const Track& track) { + if (!track.level_links.empty()) + return nullptr; + const auto header = std::find_if(track.entries.begin(), track.entries.end(), + [](const auto& entry) { return entry.section == Section::LevelHeaders; }); + if (header == track.entries.end() || header->bytes.size() < 0xC8 || header->bytes[0] != kCustomTrackWorld || + header->bytes[0x4B] < 1 || header->bytes[0x4B] > 5 || header->bytes[0x4C] != 0) + return nullptr; + return &*header; +} +} // namespace + +unsigned replay_vehicles(const Track& track) { + const auto* header = replay_header(track); + return header ? header->bytes[0x4E] & 7U : 0; +} + +unsigned replay_laps(const Track& track) { + const auto* header = replay_header(track); + return header ? header->bytes[0x4B] : 0; +} + +std::vector installed_replay_tracks() { + std::scoped_lock lock(g_mutex); + std::vector choices; + for (const auto& track : g_tracks) + if (const auto vehicles = replay_vehicles(track)) + choices.push_back({track.id, track.name, vehicles}); + return choices; +} + +std::filesystem::path installed_replay_source(const std::string& id) { + std::scoped_lock lock(g_mutex); + const auto track = + std::find_if(g_tracks.begin(), g_tracks.end(), [&](const Track& candidate) { return candidate.id == id; }); + return track == g_tracks.end() ? std::filesystem::path{} : track->source; +} + +void begin_replay_track(Track track) { + std::scoped_lock lock(g_mutex); + g_replay_tracks.clear(); + g_replay_tracks.push_back(std::move(track)); + g_sections = {}; + g_resolved_level_ids.clear(); +} + +void retire_replay_track() { + std::scoped_lock lock(g_mutex); + if (g_replay_tracks.empty()) + return; + g_replay_tracks.clear(); + g_sections = {}; + g_resolved_level_ids.clear(); +} + std::size_t enabled_count() { std::scoped_lock lock(g_mutex); return static_cast( @@ -409,7 +470,7 @@ std::optional music_for_level(std::int32_t level_id) { if (level_id < 0) { return std::nullopt; } - for (const Track& track : g_tracks) { + for (const Track& track : active_tracks_locked()) { const auto resolved = g_resolved_level_ids.find(track.id); if (track.enabled && track.music && resolved != g_resolved_level_ids.end() && resolved->second == level_id) { return track.music; @@ -420,7 +481,7 @@ std::optional music_for_level(std::int32_t level_id) { std::optional water_for_level(std::int32_t level_id) { std::scoped_lock lock(g_mutex); - for (const auto& track : g_tracks) { + for (const auto& track : active_tracks_locked()) { const auto resolved = g_resolved_level_ids.find(track.id); if (track.enabled && track.water && resolved != g_resolved_level_ids.end() && resolved->second == level_id) return track.water; @@ -627,7 +688,7 @@ bool minimap_hidden(std::uint32_t header_offset) { return false; // Retail, or not a track's header. } const Track* track = nullptr; - for (const Track& candidate : g_tracks) { + for (const Track& candidate : active_tracks_locked()) { if (candidate.id == header->track_id) { track = &candidate; } @@ -749,9 +810,9 @@ std::int32_t track_override() { } bool owns_level_id(std::int32_t level_id) { - if (!dkr::session_content::local_assets_allowed()) - return false; std::scoped_lock lock(g_mutex); + if (g_replay_tracks.empty() && !dkr::session_content::local_assets_allowed()) + return false; return std::any_of(g_resolved_level_ids.begin(), g_resolved_level_ids.end(), [level_id](const auto& entry) { return entry.second == level_id; }); } @@ -874,7 +935,7 @@ std::vector level_links_for_object_map(std::uint32_t offset) if (entry.offset != offset || entry.track_id.empty()) { continue; } - for (const Track& track : g_tracks) { + for (const Track& track : active_tracks_locked()) { if (track.id != entry.track_id || !track.enabled) { continue; } @@ -901,7 +962,7 @@ std::int32_t level_race_type(std::int32_t level_id) { if (resolved != level_id) { continue; } - for (const Track& track : g_tracks) { + for (const Track& track : active_tracks_locked()) { if (track.id != track_id || !track.enabled) { continue; } @@ -1074,7 +1135,7 @@ std::int32_t level_model_arena_bytes(std::int32_t level_id) { if (resolved != level_id) { continue; } - for (const Track& track : g_tracks) { + for (const Track& track : active_tracks_locked()) { if (track.id != track_id) { continue; } @@ -1199,11 +1260,11 @@ std::vector build_extended_table(Section section, const std::int32 std::fprintf(stderr, "[custom-tracks] applying deferred rescan\n"); scan_locked(g_directory); } - if (!dkr::session_content::local_assets_allowed()) { + if (g_replay_tracks.empty() && !dkr::session_content::local_assets_allowed()) { const std::vector vanilla; return assemble_table(section, retail_table, vanilla, g_sections, g_resolved_level_ids, table_words); } - return assemble_table(section, retail_table, g_tracks, g_sections, g_resolved_level_ids, table_words); + return assemble_table(section, retail_table, active_tracks_locked(), g_sections, g_resolved_level_ids, table_words); } PreparedTracks prepare_tracks(std::vector tracks, const std::array, 7>& tables) { @@ -1301,7 +1362,7 @@ PreparedTracks prepare_tracks(std::vector tracks, const std::array installed_replay_tracks(); +[[nodiscard]] std::filesystem::path installed_replay_source(const std::string& id); +[[nodiscard]] unsigned replay_vehicles(const Track& track); +[[nodiscard]] unsigned replay_laps(const Track& track); +// Solo replay assets are frozen separately from the player's enabled library. +// Begin before loading guest resources and retire after the guest has joined. +void begin_replay_track(Track track); +void retire_replay_track(); [[nodiscard]] std::size_t enabled_count(); // Transient selection; library UI uses the persistent, error-reporting overload. void set_enabled(const std::string& id, bool enabled); diff --git a/runtime-recomp/src/game/dialog_style.hpp b/runtime-recomp/src/game/dialog_style.hpp new file mode 100644 index 00000000..ce3000c9 --- /dev/null +++ b/runtime-recomp/src/game/dialog_style.hpp @@ -0,0 +1,62 @@ +#pragma once + +#ifndef IMGUI_VERSION +#include "imgui.h" +#endif + +namespace dkr::runtime::ui { + +// The Launcher and Overlay shells draw their own edges and use zero window +// padding. Give separate dialogs a surface of their own at Begin time. +class ScopedDialogStyle { + public: + explicit ScopedDialogStyle(ImVec2 padding = {18.0F, 14.0F}, float rounding = 16.0F) { + constexpr ImVec4 surface{0.043F, 0.14F, 0.20F, 0.98F}; + constexpr ImVec4 title{0.04F, 0.25F, 0.35F, 1.0F}; + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, padding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, rounding); + ImGui::PushStyleVar(ImGuiStyleVar_PopupRounding, rounding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1.0F); + ImGui::PushStyleVar(ImGuiStyleVar_PopupBorderSize, 1.0F); + ImGui::PushStyleColor(ImGuiCol_WindowBg, surface); + ImGui::PushStyleColor(ImGuiCol_PopupBg, surface); + ImGui::PushStyleColor(ImGuiCol_TitleBg, title); + ImGui::PushStyleColor(ImGuiCol_TitleBgActive, title); + ImGui::PushStyleColor(ImGuiCol_TitleBgCollapsed, title); + ImGui::PushStyleColor(ImGuiCol_Border, {0.22F, 0.44F, 0.51F, 1.0F}); + } + + ~ScopedDialogStyle() { + ImGui::PopStyleColor(6); + ImGui::PopStyleVar(5); + } + + ScopedDialogStyle(const ScopedDialogStyle&) = delete; + ScopedDialogStyle& operator=(const ScopedDialogStyle&) = delete; +}; + +inline bool begin_dialog_modal(const char* name, bool* open, ImGuiWindowFlags flags, ImVec2 padding = {18.0F, 14.0F}) { + if (!ImGui::IsPopupOpen(name)) + return ImGui::BeginPopupModal(name, open, flags); + const ScopedDialogStyle style(padding); + return ImGui::BeginPopupModal(name, open, flags); +} + +inline bool begin_dialog_window(const char* name, bool* open, ImGuiWindowFlags flags) { + const ScopedDialogStyle style; + return ImGui::Begin(name, open, flags); +} + +inline bool begin_dialog_popup(const char* name, ImGuiWindowFlags flags = 0) { + if (!ImGui::IsPopupOpen(name)) + return ImGui::BeginPopup(name, flags); + const ScopedDialogStyle style({14.0F, 12.0F}, 12.0F); + return ImGui::BeginPopup(name, flags); +} + +inline bool begin_dialog_tooltip() { + const ScopedDialogStyle style({12.0F, 8.0F}, 10.0F); + return ImGui::BeginTooltip(); +} + +} // namespace dkr::runtime::ui diff --git a/runtime-recomp/src/game/directory_ui.inl b/runtime-recomp/src/game/directory_ui.inl index 769771b8..13eb0e78 100644 --- a/runtime-recomp/src/game/directory_ui.inl +++ b/runtime-recomp/src/game/directory_ui.inl @@ -1,5 +1,6 @@ // Uses the retained launcher's native controls, cards, fonts and focus handling. bool g_directory_friends_view = false; +std::string g_directory_website_lobby; const char* DirectoryPhase(const std::string& phase) { if (phase == "starting") return "Starting"; @@ -103,12 +104,38 @@ void DrawOlPublicLobbies(float width, const OnlineFrame& frame) { OlParagraph(snapshot->status, 15.F, kOlSoft, inner); return; } + if (OlButton("Find lobby from website")) { + constexpr std::string_view prefix = "https://positron-portal.com/dkr-r/#lobby="; + const char* clipboard = ImGui::GetClipboardText(); + const std::string_view link = clipboard != nullptr ? clipboard : ""; + const auto id = link.starts_with(prefix) ? link.substr(prefix.size()) : std::string_view{}; + const bool valid = id.size() == 32 && std::all_of(id.begin(), id.end(), [](char ch) { + return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f'); + }); + if (valid) + g_directory_website_lobby = id; + else + OlNotify("Copy a public lobby link from the DKR-R website first."); + } + if (!g_directory_website_lobby.empty()) { + if (OlButton("Show all public lobbies")) + g_directory_website_lobby.clear(); + const bool found = std::any_of(snapshot->rooms.begin(), snapshot->rooms.end(), + [](const auto& room) { return room.id == g_directory_website_lobby; }); + if (!g_directory_website_lobby.empty() && !found) { + PaddockGap(8.F); + OlParagraph("This lobby is no longer public or available.", 15.F, kOlSoft, inner); + return; + } + } if (snapshot->rooms.empty()) { OlParagraph("No public lobbies are available. Create a lobby and choose Public to host one.", 15.F, kOlSoft, inner); return; } for (const auto& lobby : snapshot->rooms) { + if (!g_directory_website_lobby.empty() && lobby.id != g_directory_website_lobby) + continue; const bool compatible = lobby.compatibility == dkr::online::compatibility(); const bool can_join = frame.launcher && frame.rom_ready && !frame.active && !snapshot->joining && compatible; diff --git a/runtime-recomp/src/game/display_settings/ui.inl b/runtime-recomp/src/game/display_settings/ui.inl index bdb8ac21..4c906c63 100644 --- a/runtime-recomp/src/game/display_settings/ui.inl +++ b/runtime-recomp/src/game/display_settings/ui.inl @@ -20,7 +20,8 @@ bool DrawDisplayChoices(float width, bool aspect_field) { bool changed = false; const auto list = choices(preference, w, h); std::vector resolutions{ - {std::string(dkr::localisation::source("Automatic - match window"))}, + {std::string(dkr::localisation::source("Automatic - match window")) + " (" + + std::string(dkr::localisation::source("Recommended")) + ")"}, {std::string(dkr::localisation::source("Automatic - sharp integer scaling"))}}; int selected = preference.height == 0 ? 0 : preference.height == -1 ? 1 : -1; for (const auto& item : list) { diff --git a/runtime-recomp/src/game/f3ddkr_rt64.cpp b/runtime-recomp/src/game/f3ddkr_rt64.cpp index e24a5f4d..84eb582a 100644 --- a/runtime-recomp/src/game/f3ddkr_rt64.cpp +++ b/runtime-recomp/src/game/f3ddkr_rt64.cpp @@ -6,6 +6,7 @@ #include "camera_rt64.hpp" #include "f3ddkr_execution_policy.hpp" #include "postrace_viewport_rt64.hpp" +#include "time_trial/session.hpp" #include "interpolation_state_policy.hpp" #include "hud_layout_policy.hpp" @@ -253,7 +254,7 @@ std::uint32_t PhysicalAddress(RT64::RSP& rsp, std::uint32_t address) { void SelectInterpolationGroup(RT64::RSP& rsp, std::uint32_t id, bool interpolate_vertices = false, bool interpolate_texcoords = false, bool interpolate_tiles = false, - std::uint8_t aspect_mode = G_EX_ASPECT_AUTO, bool preserve_vertex_interpolation = false, + std::uint8_t aspect_mode = G_EX_ASPECT_AUTO, bool preserve_identity = false, std::uint8_t water_scroll_tag = 0U, bool native_visual = false) { auto current_menu = ReadU32(rsp.state->RDRAM, current_menu_id_address()); #if defined(DKR_WATER_QUALIFICATION) @@ -266,7 +267,7 @@ void SelectInterpolationGroup(RT64::RSP& rsp, std::uint32_t id, bool interpolate #endif interpolate_tiles = dkr::runtime::interpolation::effective_tile_interpolation(interpolate_tiles, current_menu); const bool task_interpolation_allowed = dkr::runtime::presentation::task_interpolation_allowed(); - if (!task_interpolation_allowed && !preserve_vertex_interpolation) { + if (!task_interpolation_allowed && !preserve_identity) { id = G_EX_ID_IGNORE; interpolate_vertices = false; interpolate_texcoords = false; @@ -445,6 +446,7 @@ struct dkr::runtime::F3DDKRRT64Bridge::StateData { std::size_t hud_alignment_depth = 0U; struct HudWidgetScope { hud::groups::Transform transform; + std::uint32_t motion_identity = presentation::kIgnoredIdentity; }; std::array hud_widgets{}; std::size_t hud_widget_depth = 0; @@ -1303,8 +1305,12 @@ void dkr::runtime::F3DDKRRT64Bridge::FinishShadowScope(RT64::State* state) { // the shadow owner remains the same. The fixed canonical stream and // distributed dormant positions make that a bounded geometry morph; // topology diagnostics must never toggle interpolation for the page. - const bool interpolate_page_vertices = + const bool has_shadow_identity = dkr::runtime::presentation::shadow_page_vertex_interpolation(shadow_group.identity); + // Sequential export interpolates the camera and kart, so their + // canonical shadow vertices must move on the same sub-frame too. + const bool interpolate_page_vertices = + has_shadow_identity && (!time_trial::watching() || time_trial::exporting_video()); if (ShadowTraceEnabled() && page_drawn && (!interpolate_page_vertices || page_history.topology_signature != topology_signature)) { @@ -1409,7 +1415,7 @@ void dkr::runtime::F3DDKRRT64Bridge::FinishShadowScope(RT64::State* state) { SelectInterpolationGroup(rsp, dkr::runtime::presentation::make_shadow_page_group_identity( shadow_group.identity, page, history->interpolation_epoch), - interpolate_page_vertices, false, false, shadow_aspect, interpolate_page_vertices, 0U, + interpolate_page_vertices, false, false, shadow_aspect, has_shadow_identity, 0U, data.camera_shadow.has_value()); rsp.modelViewProjChanged = true; auto& workload = state->ext.workloadQueue->workloads[state->ext.workloadQueue->writeCursor]; @@ -2077,11 +2083,17 @@ void dkr::runtime::F3DDKRRT64Bridge::ApplyPresentationMarkers(RT64::State* state for (std::size_t index = 0U; index < markers.count; ++index) { const auto& marker = markers.markers[index]; if (marker.kind == PresentationMarkerKind::CameraWorldBegin || - marker.kind == PresentationMarkerKind::CameraWorldEnd) + marker.kind == PresentationMarkerKind::CameraWorldEnd) { + if (auto* online = active_->data_->online_view) + online->ghost_world_boundary(*state, marker.token, + marker.kind == PresentationMarkerKind::CameraWorldEnd); continue; + } if (active_->data_->camera && active_->data_->camera->replaced_command(std::uint32_t(command - rdram_begin)) && - marker.kind != PresentationMarkerKind::SplitViewport && marker.kind != PresentationMarkerKind::HudPass && - marker.kind != PresentationMarkerKind::HudWidget && marker.kind != PresentationMarkerKind::HudRect) + marker.kind != PresentationMarkerKind::SplitViewport && + marker.kind != PresentationMarkerKind::PostraceFullViewport && + marker.kind != PresentationMarkerKind::HudPass && marker.kind != PresentationMarkerKind::HudWidget && + marker.kind != PresentationMarkerKind::HudRect) continue; if (marker.kind == PresentationMarkerKind::TrackSelectPreview) { auto& data = *active_->data_; @@ -2121,6 +2133,11 @@ void dkr::runtime::F3DDKRRT64Bridge::ApplyPresentationMarkers(RT64::State* state auto& scope = data.hud_widgets[data.hud_widget_depth++]; scope.transform = data.online_view && data.online_view->focused_hud() ? hud::groups::Transform{} : marker.hud_transform; + scope.motion_identity = + marker.token != 0 + ? presentation::normalise_identity( + 0x54544855U ^ (presentation::task_scene_generation() * 0x9E3779B9U) ^ marker.token) + : presentation::kIgnoredIdentity; const auto& t = scope.transform; state->rdp->pushScissor(); auto& clip = state->rdp->scissorRectStack[state->rdp->scissorStackSize - 1]; @@ -2670,13 +2687,39 @@ void dkr::runtime::F3DDKRRT64Bridge::HudTextureRect(RT64::State* state, RT64::Di const auto rect = hud::groups::transform_rectangle(t, ulx, uly, lrx, lry, static_cast(command->p1(16, 16)), static_cast(command->p1(0, 16)), data.hud_rect_bias); - state->rdp->drawTexRect(rect.ulx, rect.uly, rect.lrx, rect.lry, tile, s, uv, rect.dsdx, rect.dtdy, flip); + auto& rdp = *state->rdp; + const auto& active_clip = rdp.scissorRectStack[rdp.scissorStackSize - 1]; + const bool expand_clip = time_trial::watching() && data.world_window_aspect > 4.F / 3.F && + active_clip.lry > active_clip.uly && rdp.scissorStackSize < RDP_EXTENDED_STACK_SIZE && + !dkr::sdk2::hud_hidden.load(std::memory_order_relaxed); + if (expand_clip) { + // Widen the text rectangle's clip without changing the projection + // and clip used by the minimap, animated HUD sprites or scene. + const auto gutter = + static_cast(std::lround(4.F * hud::fullscreen_gutter_authored(data.world_window_aspect))); + rdp.pushScissor(); + const auto stack = rdp.scissorStackSize - 1; + auto& clip = rdp.scissorRectStack[stack]; + clip.ulx = -gutter; + clip.lrx = rdp.colorImage.width * 4 + gutter; + rdp.extended.scissorLeftOriginStack[stack] = G_EX_ORIGIN_NONE; + rdp.extended.scissorRightOriginStack[stack] = G_EX_ORIGIN_NONE; + state->updateDrawStatusAttribute(RT64::DrawAttribute::Scissor); + } + rdp.drawTexRect(rect.ulx, rect.uly, rect.lrx, rect.lry, tile, s, uv, rect.dsdx, rect.dtdy, flip); + if (expand_clip) { + rdp.popScissor(); + state->updateDrawStatusAttribute(RT64::DrawAttribute::Scissor); + } *display_list = command; } void dkr::runtime::F3DDKRRT64Bridge::TrackTextureRect(RT64::State* state, RT64::DisplayList** display_list) { auto* command = *display_list; - if (!active_->data_->track_ui_cover || command->w0 != 0xD5000001U || command->w1 != 0x54524354U) { + // The guest emits these signed rectangles in both presentation modes. + // The optional widescreen scope changes clipping, but Accurate mode and + // archived tasks can decode the packet with their current native scissor. + if (command->w0 != 0xD5000001U || command->w1 != 0x54524354U) { RejectTask(display_list); return; } @@ -2685,7 +2728,8 @@ void dkr::runtime::F3DDKRRT64Bridge::TrackTextureRect(RT64::State* state, RT64:: const auto lrx = std::int16_t(command->p1(16, 16)), lry = std::int16_t(command->p1(0, 16)); ++command; RT64::ExtendedAlignment alignment{}; - alignment.leftOrigin = alignment.rightOrigin = G_EX_ORIGIN_NONE; + if (active_->data_->track_ui_cover) + alignment.leftOrigin = alignment.rightOrigin = G_EX_ORIGIN_NONE; state->rdp->drawTexRect(ulx, uly, lrx, lry, 0, std::int16_t(command->p0(16, 16)), std::int16_t(command->p0(0, 16)), std::int16_t(command->p1(16, 16)), std::int16_t(command->p1(0, 16)), false, alignment); *display_list = command; @@ -2827,7 +2871,21 @@ void dkr::runtime::F3DDKRRT64Bridge::Vertex(RT64::State* state, RT64::DisplayLis !data.interpolation_groups.has_rejected_scope(), water::enhanced::requested_quality.load(std::memory_order_relaxed) == water::enhanced::Quality::Original); #endif - rsp.setVertex(kScratchVertexAddress, count, destination); + const auto hud_motion = data.hud_widget_depth ? data.hud_widgets[data.hud_widget_depth - 1].motion_identity + : presentation::kIgnoredIdentity; + if (hud_motion != presentation::kIgnoredIdentity) { + auto& extended = rsp.extended; + auto& group = extended.modelMatrixIdStack[extended.modelMatrixIdStackSize - 1]; + const auto previous_group = group; + SelectInterpolationGroup(rsp, hud_motion, true, false, false, + ActiveAspectMode(data.interpolation_groups, data.matrix_aspect_override_active, + data.matrix_aspect_override)); + rsp.setVertex(kScratchVertexAddress, count, destination); + group = previous_group; + extended.modelMatrixIdStackChanged = true; + } else { + rsp.setVertex(kScratchVertexAddress, count, destination); + } #if defined(DKR_ENHANCED_WATER) data.flow_loads += flow_scope.active(); for (unsigned i = 0; i < count; ++i) diff --git a/runtime-recomp/src/game/game_main.cpp b/runtime-recomp/src/game/game_main.cpp index 290196b4..a3c43fc8 100644 --- a/runtime-recomp/src/game/game_main.cpp +++ b/runtime-recomp/src/game/game_main.cpp @@ -28,6 +28,7 @@ #include "save_manager.hpp" #include "runtime_save_routing.hpp" #include "startup_performance.hpp" +#include "time_trial/session.hpp" #include "virtual_pak.hpp" #include "runtime_legacy_mods.hpp" #include "runtime_code_mods.hpp" @@ -43,6 +44,7 @@ #include "netplay/session_chat/chat.hpp" #include "netplay/peer_relay/transport.hpp" #include "netplay/session_chat/settings.hpp" +#include "netplay/session_links/qualification.hpp" #include #endif #if defined(__ANDROID__) @@ -432,6 +434,16 @@ struct LaunchOptions { std::filesystem::path rom_path; std::filesystem::path config_directory; unsigned timeout_seconds = 0; + dkr::runtime::time_trial::Mode time_trial = dkr::runtime::time_trial::Mode::None; + std::filesystem::path replay_path; + std::filesystem::path ghost_replay; + std::filesystem::path ghost_export; + std::string time_trial_track; + std::filesystem::path time_trial_map; + dkr::runtime::time_trial::Adventure adventure = dkr::runtime::time_trial::Adventure::None; + unsigned time_trial_racer = dkr::runtime::time_trial::kDiddy; + const dkr::runtime::time_trial::Course* time_trial_course = &dkr::runtime::time_trial::kCourses.front(); + dkr::runtime::time_trial::Vehicle time_trial_vehicle = dkr::runtime::time_trial::Vehicle::Car; #if defined(DKR_EXPERIMENTAL_RACE_TEST) std::filesystem::path bootstrap_output; std::filesystem::path owned_check_invite; @@ -490,6 +502,77 @@ bool ParseLaunchOptions(int argc, char** argv, LaunchOptions& options, std::stri } options.owned_check_players = unsigned(value[0] - '0'); #endif + } else if (argument == "--adventure-category") { + const char* value = require_value("--adventure-category"); + if (!value) + return false; + options.adventure = dkr::runtime::time_trial::adventure_for(value); + if (options.adventure == dkr::runtime::time_trial::Adventure::None) { + error = "Choose any-percent, 100-percent or all-trophy-races."; + return false; + } + } else if (argument == "--time-trial-track" || argument == "--time-trial-map") { + const char* value = require_value(argv[index]); + if (!value) + return false; + if (argument == "--time-trial-track") + options.time_trial_track = value; + else + options.time_trial_map = std::filesystem::u8path(value); + } else if (argument == "--time-trial-ghost") { + const char* value = require_value("--time-trial-ghost"); + if (!value) + return false; + options.ghost_replay = std::filesystem::u8path(value); + } else if (argument == "--export-time-trial-ghost") { + const char* value = require_value("--export-time-trial-ghost"); + if (!value) + return false; + options.ghost_export = std::filesystem::u8path(value); + } else if (argument == "--time-trial-course") { + const char* value = require_value("--time-trial-course"); + if (!value) + return false; + options.time_trial_course = dkr::runtime::time_trial::course_for(value); + if (!options.time_trial_course) { + error = "Choose a supported retail Time Trial course."; + return false; + } + } else if (argument == "--time-trial-vehicle") { + const char* value = require_value("--time-trial-vehicle"); + if (!value) + return false; + namespace trial = dkr::runtime::time_trial; + const auto found = std::find(trial::kVehicleIds.begin(), trial::kVehicleIds.end(), std::string_view(value)); + if (found == trial::kVehicleIds.end()) { + error = "Time Trial vehicle must be car, hovercraft or plane."; + return false; + } + options.time_trial_vehicle = static_cast(found - trial::kVehicleIds.begin()); + } else if (argument == "--time-trial-racer") { + const char* value = require_value("--time-trial-racer"); + if (!value) + return false; + if (value[0] < '0' || value[0] > '9' || value[1]) { + error = "Time Trial racer must be an ID from 0 to 9."; + return false; + } + options.time_trial_racer = unsigned(value[0] - '0'); + } else if (argument == "--record-time-trial" || argument == "--self-test-time-trial" || + argument == "--verify-time-trial" || argument == "--watch-time-trial") { + using dkr::runtime::time_trial::Mode; + const char* value = require_value(argv[index]); + if (!value) + return false; + if (options.time_trial != Mode::None) { + error = "Select one Time Trial action."; + return false; + } + options.time_trial = argument == "--record-time-trial" ? Mode::Record + : argument == "--self-test-time-trial" ? Mode::SelfTest + : argument == "--verify-time-trial" ? Mode::Verify + : Mode::Watch; + options.replay_path = std::filesystem::u8path(value); } else if (argument == "--timeout") { const char* value = require_value("--timeout"); if (value == nullptr) { @@ -829,9 +912,45 @@ int DkrMain(int argc, char** argv) { // and portable roots must not accidentally select another profile later. const std::filesystem::path config_directory = std::filesystem::weakly_canonical(launch.config_directory); const unsigned timeout_seconds = launch.timeout_seconds; + namespace time_trial = dkr::runtime::time_trial; + if (launch.adventure != time_trial::Adventure::None && launch.time_trial != time_trial::Mode::Record) { + std::fprintf(stderr, "[adventure] --adventure-category requires --record-time-trial.\n"); + return 2; + } + if (!launch.ghost_export.empty() && launch.time_trial != time_trial::Mode::Verify) { + std::fprintf(stderr, "[ghost] Export requires --verify-time-trial.\n"); + return 2; + } + if (!launch.ghost_replay.empty() && + ((launch.time_trial != time_trial::Mode::Record && launch.time_trial != time_trial::Mode::SelfTest) || + launch.adventure != time_trial::Adventure::None || !launch.time_trial_track.empty())) { + std::fprintf(stderr, + "[ghost] Select a practice recording. The ghost replay supplies the course and vehicle.\n"); + return 2; + } + if (launch.time_trial != time_trial::Mode::None) { + const auto start_trial = [&] { + if (!launch.ghost_replay.empty()) + return time_trial::start_ghost(launch.ghost_replay, launch.replay_path, rom_error, + launch.time_trial_racer, launch.time_trial, launch.time_trial_map); + return time_trial::start(launch.time_trial, launch.replay_path, rom_error, nullptr, launch.time_trial_racer, + *launch.time_trial_course, launch.time_trial_vehicle, launch.adventure, + launch.time_trial_track, launch.time_trial_map, launch.ghost_export); + }; + if (rom_path.empty() || launch.config_directory.empty() || !config_directory.is_absolute() || + std::filesystem::exists(config_directory) || !start_trial()) { + std::fprintf(stderr, "[time-trial] Requires a ROM, new absolute profile and absolute replay path. %s\n", + rom_error.c_str()); + return 2; + } + } #if defined(DKR_EXPERIMENTAL_RACE_TEST) const bool rollback_bootstrap = !launch.bootstrap_output.empty(); const bool owned_check = !launch.owned_check_invite.empty(); + if (time_trial::active() && (rollback_bootstrap || owned_check)) { + std::fprintf(stderr, "[time-trial] Time Trial accepts only an offline session.\n"); + return 2; + } if (owned_check && (rollback_bootstrap || rom_path.empty() || !config_directory.is_absolute() || std::filesystem::exists(config_directory) || !launch.owned_check_invite.is_absolute() || timeout_seconds < 20 || timeout_seconds > 180)) { @@ -863,6 +982,11 @@ int DkrMain(int argc, char** argv) { } dkr::runtime::startup_performance::mark("persistent-log-ready"); dkr::crash_reports::start(config_directory, DKR_RELEASE_VERSION); + if (launch.time_trial != time_trial::Mode::None) { + // CLI trials require a disposable profile. Managed jobs have no user + // to answer this dialog, and render jobs must capture only the game. + dkr::crash_reports::choose(false, false); + } { dkr::runtime::startup_performance::ScopedPhase phase("rom-identity-cache-configure"); dkr::runtime::rom::configure_identity_cache(config_directory); @@ -901,7 +1025,8 @@ int DkrMain(int argc, char** argv) { dkr::runtime::startup_performance::ScopedPhase phase("pak-save-input-configure"); dkr::runtime::pak::configure(config_directory); dkr::runtime::saves::configure(config_directory); - dkr::runtime::saves::configure_recovery_locations(RecoverySaveLocations(argv[0])); + if (!time_trial::active()) + dkr::runtime::saves::configure_recovery_locations(RecoverySaveLocations(argv[0])); dkr::runtime::platform::configure_input(config_directory); #if DKR_RUNTIME_HAS_RT64 // Custom tracks are user content beside the other imported assets, so @@ -981,6 +1106,8 @@ int DkrMain(int argc, char** argv) { dkr::runtime::platform::shutdown(); return 5; } + dkr::runtime::netplay::links::HandoverQualification handover_check(owned_check); + auto start_retry_at = std::chrono::steady_clock::time_point{}; bool joined = launch.owned_check_host, invitation_written = false, ready = false, started = false, accepted = false; bool connection_test_requested = false, connection_tested = false; @@ -1014,11 +1141,18 @@ int DkrMain(int argc, char** argv) { const auto chat_started = std::chrono::steady_clock::now(); std::optional chat_release; auto report_at = std::chrono::steady_clock::now(); - const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60); + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(handover_check.enabled() ? 180 : 60); while (std::chrono::steady_clock::now() < deadline && !accepted) { dkr::runtime::vehicles::lighting::pump_owned_check(); dkr::runtime::platform::pump_window_events(nullptr); const auto state = online.view(); + std::string handover_error; + const bool handover_ready = handover_check.pulse(&online, handover_error); + if (!handover_error.empty()) { + rom_error = handover_error; + break; + } if (std::chrono::steady_clock::now() >= report_at) { std::fprintf(stderr, "[rollback][check] lobby state=%d local=%u status=%s\n", int(state.state), unsigned(state.local_slot), state.status.c_str()); @@ -1080,7 +1214,7 @@ int DkrMain(int argc, char** argv) { std::chrono::steady_clock::now() - chat_started >= std::chrono::seconds(25)) chat_release = std::chrono::steady_clock::now(); } - if (launch.owned_check_host) + if (state.host) for (const auto& pending : state.pending_joins) if (!online.approve_join(pending.request_id, rom_error)) break; @@ -1090,7 +1224,10 @@ int DkrMain(int argc, char** argv) { state.state == dkr::runtime::netplay::ConnectionState::Lobby)) { ready = online.set_ready(true, rom_error); } - if (launch.owned_check_host && ready && !started) { + if (state.host && ready && handover_ready && + state.state == dkr::runtime::netplay::ConnectionState::Hosting && !state.launch_countdown_active && + state.launch_stage == dkr::runtime::netplay::LaunchStage::Idle && + (!started || std::chrono::steady_clock::now() >= start_retry_at)) { unsigned occupants = 0; bool all_ready = true; for (const auto& racer : state.room.players) @@ -1131,8 +1268,10 @@ int DkrMain(int argc, char** argv) { const bool chat_ready = !check_chat || (chat_release && std::chrono::steady_clock::now() >= *chat_release); if (chat_ready && - (connection_tested || !(connection_test && std::string_view(connection_test) == "1"))) + (connection_tested || !(connection_test && std::string_view(connection_test) == "1"))) { started = online.request_start(rom_error); + start_retry_at = std::chrono::steady_clock::now() + std::chrono::seconds(1); + } } } accepted = online.consume_launch_request(); @@ -1234,7 +1373,14 @@ int DkrMain(int argc, char** argv) { .poll_input = dkr::runtime::platform::poll_input, .frame_boundary = dkr::runtime::netplay::on_frame_boundary, .physical_poll_allowed = []() { return dkr::runtime::netplay::physical_input_poll_allowed(); }, - .get_input = dkr::runtime::platform::get_input, + .get_input = + +[](int port, std::uint16_t* buttons, float* x, float* y) { + if (!time_trial::replaying()) + return dkr::runtime::platform::get_input(port, buttons, x, y); + *buttons = 0; + *x = *y = 0.0F; + return port == 0; + }, .set_rumble = dkr::runtime::platform::set_rumble, .get_connected_device_info = dkr::runtime::platform::get_connected_device_info, }; @@ -1286,6 +1432,8 @@ int DkrMain(int argc, char** argv) { .events_callbacks = events_callbacks, .save_write_allowed_callback = []() { + if (dkr::runtime::time_trial::active()) + return false; #if defined(DKR_EXPERIMENTAL_RACE_TEST) if (dkr_experimental_bootstrap_active()) return false; @@ -1321,10 +1469,11 @@ int DkrMain(int argc, char** argv) { // A lobby's accepted manifest, not later overlay preferences, owns // the simulation selection on every peer. const bool online_content = dkr::runtime::netplay::session().active(); - const bool content_enabled = online_content && dkr::runtime::netplay::session().view().host - ? dkr::session_content::host_enabled.load() - : prepared_mods ? prepared_mods->content_enabled - : dkr::session_content::next_enabled.load(); + const bool content_enabled = + !time_trial::active() && + (online_content && dkr::runtime::netplay::session().view().host ? dkr::session_content::host_enabled.load() + : prepared_mods ? prepared_mods->content_enabled + : dkr::session_content::next_enabled.load()); dkr::crash_reports::Gameplay quiet_reports; dkr::session_content::Session content_session(content_enabled, online_content); dkr::session_content::Preparation content_preparation(content_enabled); @@ -1335,7 +1484,8 @@ int DkrMain(int argc, char** argv) { online_magic_codes = static_cast(dkr::runtime::netplay::session().view().room.manifest.magic_codes_hash); } - dkr::runtime::magic_codes::begin_game_session(online_magic_codes); + dkr::runtime::magic_codes::begin_game_session(time_trial::active() ? std::optional{0} + : online_magic_codes); dkr::runtime::netplay::reset_runtime_state(); dkr::runtime::rev_a_asset_mutex::reset_statistics(); dkr::runtime::legacy::begin_session(nullptr); @@ -1408,12 +1558,28 @@ int DkrMain(int argc, char** argv) { !dkr::runtime::saves::shared::prepare_development(config_directory, developer_folder, rom_error)) throw dkr::mods::Error(rom_error); selecting_save_owner = true; - if (dkr::runtime::spectators::party_enabled(&dkr::runtime::netplay::session())) { + if (time_trial::active()) { + using dkr::runtime::saves::ReplaySave; + const auto seed = time_trial::uses_completed_adventure_save() ? ReplaySave::CompletedAdventure + : time_trial::uses_uninitialised_adventure_save() ? ReplaySave::MissingAdventure + : ReplaySave::Blank; + if (!dkr::runtime::saves::prepare_time_trial_save_context(rom_error, seed)) + throw dkr::mods::Error(rom_error); + ultramodern::set_save_storage_callbacks({dkr::runtime::saves::runtime_save_path, + dkr::runtime::saves::load_runtime_save, + dkr::runtime::saves::commit_runtime_save}); + dkr::runtime::pak::begin_session_directory({}); + if (!dkr::runtime::saves::records::begin_memory({}, rom_error)) + throw dkr::mods::Error(rom_error); + } else if (dkr::runtime::spectators::party_enabled(&dkr::runtime::netplay::session())) { auto party = dkr::runtime::spectators::party_link(&dkr::runtime::netplay::session()); - std::vector seed; + std::vector seed, shared_records; + bool owns_save = false; { std::scoped_lock lock(party->mutex); seed = party->seed; + shared_records = party->links.save_records; + owns_save = party->links.save_owner == party->local; } if (seed.size() != 512) throw dkr::mods::Error("Party bootstrap is missing its verified save seed."); @@ -1423,7 +1589,7 @@ int DkrMain(int argc, char** argv) { dkr::runtime::spectators::party_bootstrap_write}); dkr::runtime::pak::begin_session_directory({}); std::filesystem::path records; - if (online_save.host) { + if (owns_save && shared_records.empty()) { std::vector active; std::filesystem::path owner; if (!dkr::runtime::saves::read_online_adventure(true, online_save.launch_descriptor->match_id, @@ -1431,8 +1597,13 @@ int DkrMain(int argc, char** argv) { active != seed) throw dkr::mods::Error("The host online seed changed during party boot: " + rom_error); records = owner.parent_path() / "custom-records-v1.bin"; + if (!dkr::runtime::saves::records::begin(records, false, rom_error)) + throw dkr::mods::Error(rom_error); + shared_records = dkr::runtime::saves::records::seed(); + std::scoped_lock lock(party->mutex); + party->links.save_records = shared_records; } - if (!dkr::runtime::saves::records::begin(records, false, rom_error)) + if (!dkr::runtime::saves::records::begin_memory(shared_records, rom_error)) throw dkr::mods::Error(rom_error); } else { dkr::runtime::spectators::party_bootstrap_seed({}); @@ -1447,7 +1618,8 @@ int DkrMain(int argc, char** argv) { std::fprintf(stderr, "[save][selected] owner=%s path=%s progress=%s\n", online_save.active ? "online" : development_session ? "development" - : "personal", + : content_enabled ? "modded" + : "vanilla", std::string(utf8.begin(), utf8.end()).c_str(), dkr::runtime::saves::shared::describe(path).c_str()); } @@ -1455,15 +1627,18 @@ int DkrMain(int argc, char** argv) { dkr::runtime::saves::load_runtime_save, dkr::runtime::saves::commit_runtime_save}); dkr::runtime::pak::begin_session_directory(dkr::runtime::saves::runtime_pak_directory()); + const auto records_directory = online_save.active + ? dkr::runtime::saves::runtime_save_path().parent_path() + : config_directory / "saves"; if (!dkr::runtime::saves::records::begin( - development_session - ? std::filesystem::path{} - : dkr::runtime::saves::runtime_save_path().parent_path() / "custom-records-v1.bin", + development_session ? std::filesystem::path{} : records_directory / "custom-records-v1.bin", !development_session && (!online_save.active || online_save.host), rom_error)) throw dkr::mods::Error(rom_error); } } catch (const std::exception& error) { std::fprintf(stderr, "[legacy][launch] %s\n", error.what()); + if (time_trial::active()) + time_trial::retire(); #if DKR_RUNTIME_HAS_RT64 if (selecting_save_owner) { // No guest producer exists yet. A locked/invalid route is a @@ -1710,6 +1885,7 @@ int DkrMain(int argc, char** argv) { // X11 and Wayland compatibility while the recompiler owns its // worker. dkr::runtime::platform::pump_window_events(nullptr); + dkr::runtime::ui::show_run_return_cover(); dkr::runtime::service_online_wait_presentation(); #endif if (!timeout_requested && timeout_seconds != 0 && @@ -1725,6 +1901,10 @@ int DkrMain(int argc, char** argv) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } runtime_thread.join(); +#if DKR_RUNTIME_HAS_RT64 + if (time_trial::active() && !time_trial::preparing_ghost()) + dkr::runtime::ui::show_run_return_cover(true); +#endif dkr::runtime::modern_camera::reset_session(); #if defined(DKR_EXPERIMENTAL_RACE_TEST) if (owned_launch) { @@ -1830,6 +2010,22 @@ int DkrMain(int argc, char** argv) { } return 5; } + const bool return_from_time_trial = time_trial::active(); + if (time_trial::preparing_ghost() && time_trial::advance_ghost()) { + dkr::session_content::end(); + continue; + } + if (return_from_time_trial) + time_trial::finish_interrupted_recording(); + if (launch.time_trial == time_trial::Mode::Verify || launch.time_trial == time_trial::Mode::SelfTest || + time_trial::exporting_video() || launch.adventure != time_trial::Adventure::None) { + const int status = time_trial::status(); + time_trial::retire(); + dkr::runtime::platform::shutdown(); + return status; + } + if (return_from_time_trial) + time_trial::retire(); #if DKR_RUNTIME_HAS_RT64 #if defined(DKR_EXPERIMENTAL_RACE_TEST) if (owned_check) { @@ -1837,8 +2033,8 @@ int DkrMain(int argc, char** argv) { return owned_failed ? 5 : 0; } #endif - if (lifecycle_request == dkr::runtime::ui::LifecycleRequest::StopGame || !mod_failure.empty() || - !save_failure.empty() || + if (return_from_time_trial || lifecycle_request == dkr::runtime::ui::LifecycleRequest::StopGame || + !mod_failure.empty() || !save_failure.empty() || (return_from_owned && lifecycle_request == dkr::runtime::ui::LifecycleRequest::None)) { if (!mod_failure.empty()) dkr::runtime::ui::report_mod_error("Custom content stopped safely: " + mod_failure); @@ -1851,8 +2047,10 @@ int DkrMain(int argc, char** argv) { ? std::string("The previous online game did not finish safely. Review its error before joining.") : std::string{}); dkr::runtime::ui::reset_lifecycle_request(); - const bool software_launcher_return = dkr::runtime::launcher_surface_recovery( - owned_failed, return_from_owned, !mod_failure.empty() || !save_failure.empty()); + const bool software_launcher_return = + return_from_time_trial || + dkr::runtime::launcher_surface_recovery(owned_failed, return_from_owned, + !mod_failure.empty() || !save_failure.empty()); dkr::session_content::end(); const auto startup = dkr::runtime::ui::run_startup_screen( static_cast(dkr::runtime::platform::sdl_window()), rom_path, software_launcher_return); diff --git a/runtime-recomp/src/game/hud_layout_editor.cpp b/runtime-recomp/src/game/hud_layout_editor.cpp index 9926b5dc..9a48f6b2 100644 --- a/runtime-recomp/src/game/hud_layout_editor.cpp +++ b/runtime-recomp/src/game/hud_layout_editor.cpp @@ -1,4 +1,5 @@ #include "hud_layout_editor.hpp" +#include "dialog_style.hpp" #include "runtime_hud_layout.hpp" #include "imgui.h" #include "imgui_internal.h" @@ -359,10 +360,9 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { ImGui::SetNextWindowPos( {viewport->WorkPos.x + viewport->WorkSize.x * .5F, viewport->WorkPos.y + viewport->WorkSize.y * .5F}, ImGuiCond_Always, {.5F, .5F}); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {16, 12}); - if (ImGui::BeginPopupModal("HUD WORKSHOP", nullptr, - ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | - ImGuiWindowFlags_NoSavedSettings)) { + if (ui::begin_dialog_modal("HUD WORKSHOP", nullptr, + ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings, + {16.0F, 12.0F})) { ImGui::TextWrapped( "Single / two-player HUD. This is a schematic preview; native visibility and animations stay controlled by the game."); ImGui::BeginDisabled(e.moving); @@ -461,7 +461,7 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { [&] { e.draft.scale = hg::safe_scale(std::round(global) / 100); }); if (button("SIZE ALL GROUPS", -1)) ImGui::OpenPopup("Use global size everywhere?"); - if (ImGui::BeginPopupModal("Use global size everywhere?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("Use global size everywhere?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted("Clear every group size override? Positions stay unchanged."); if (button("CONFIRM")) { change([&] { @@ -531,7 +531,7 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { }); if (button("COPY TO OTHER SCENARIOS", -1)) ImGui::OpenPopup("Copy this group?"); - if (ImGui::BeginPopupModal("Copy this group?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("Copy this group?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted("Copy this group's placement to compatible scenarios only?"); if (button("COPY")) { change([&] { @@ -560,7 +560,7 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { ImGui::EndDisabled(); if (button("RESET GROUP", -1)) ImGui::OpenPopup("Reset this group?"); - if (ImGui::BeginPopupModal("Reset this group?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("Reset this group?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted("Restore native placement and inherited size for this group?"); if (button("RESET")) { change([&] { selected() = {}; }); @@ -573,7 +573,7 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { } if (button("RESET SCENARIO", -1)) ImGui::OpenPopup("Reset this scenario?"); - if (ImGui::BeginPopupModal("Reset this scenario?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("Reset this scenario?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted("Reset all groups for the selected scenario, player and screen profile?"); if (button("RESET")) { change([&] { hg::reset_scenario(e.draft, aspect(), scenario(), target()); }); @@ -608,7 +608,7 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { if (button("DELETE PRESET", -1)) ImGui::OpenPopup("Delete this preset?"); ImGui::EndDisabled(); - if (ImGui::BeginPopupModal("Delete this preset?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("Delete this preset?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted("Delete the selected saved preset? Applied settings stay unchanged."); if (button("DELETE") && !names.empty()) { delete_preset(names[e.preset]); @@ -626,7 +626,7 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { draw_keyboard(); if (!e.pending_preset.empty()) ImGui::OpenPopup("Replace saved preset?"); - if (ImGui::BeginPopupModal("Replace saved preset?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("Replace saved preset?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextWrapped("Replace the saved preset %s?", e.pending_preset.c_str()); if (button("REPLACE")) { e.message = save_preset(e.pending_preset, e.draft) ? "Preset saved." : "Could not write preset."; @@ -668,7 +668,7 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { ImGui::OpenPopup("Custom layout starting point"); e.select_base = false; } - if (ImGui::BeginPopupModal("Custom layout starting point", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("Custom layout starting point", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted("Choose a starting area. Existing group edits are retained."); if (button("START FROM ORIGINAL")) { change([] { e.draft.custom_fill = false; }); @@ -695,7 +695,7 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { ImGui::OpenPopup("HUD changes"); e.close_prompt = false; } - if (ImGui::BeginPopupModal("HUD changes", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("HUD changes", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted("Apply the preview, discard changes, or keep editing?"); if (button("APPLY")) { if (apply_layout(e.draft)) { @@ -723,7 +723,6 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { } else if (!ImGui::IsPopupOpen("HUD WORKSHOP")) { cancel(); } - ImGui::PopStyleVar(); } } // namespace @@ -858,7 +857,7 @@ bool draw_settings(bool modern, float width, void (*request_name)(), void (*draw } if (button("RESET HUD SETTINGS", std::min(width, ImGui::GetContentRegionAvail().x))) ImGui::OpenPopup("Reset HUD settings?"); - if (ImGui::BeginPopupModal("Reset HUD settings?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("Reset HUD settings?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted("Restore Original layout and 100% group size? Saved presets are retained."); if (button("RESET")) { changed = apply_settings({}); diff --git a/runtime-recomp/src/game/invite_ui.inl b/runtime-recomp/src/game/invite_ui.inl index 100f97af..2e08274a 100644 --- a/runtime-recomp/src/game/invite_ui.inl +++ b/runtime-recomp/src/game/invite_ui.inl @@ -389,9 +389,10 @@ void DrawInviteUi() { if (g_invite_intent.step == InviteStep::Stopping || g_invite_intent.step == InviteStep::Queued) { ImGui::SetNextWindowPos({ImGui::GetIO().DisplaySize.x * .5F, 20}, ImGuiCond_Always, {.5F, 0}); ImGui::SetNextWindowBgAlpha(.94F); - if (ImGui::Begin("##invite-progress", nullptr, - ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDecoration | - ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing)) { + if (dkr::runtime::ui::begin_dialog_window("##invite-progress", nullptr, + ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDecoration | + ImGuiWindowFlags_NoSavedSettings | + ImGuiWindowFlags_NoFocusOnAppearing)) { ImGui::TextUnformatted(g_invite_intent.step == InviteStep::Stopping ? "Returning safely to the launcher..." : "Preparing to join your friend's lobby..."); diff --git a/runtime-recomp/src/game/library_ui/automatic_ui.inl b/runtime-recomp/src/game/library_ui/automatic_ui.inl index e3d90227..27473fec 100644 --- a/runtime-recomp/src/game/library_ui/automatic_ui.inl +++ b/runtime-recomp/src/game/library_ui/automatic_ui.inl @@ -1,10 +1,8 @@ void DrawSkipLauncherSetting(float width) { if (PaddockCheckbox("##skip-launcher", "Skip launcher", &dkr::library_ui::skip_launcher, width)) SaveSettings(); - PaddockGap(6.F); - PaddockText(PaddockReading(13.F, false, 1.5F), PaddockRgb(0xABC0CC), + PaddockText(PaddockReading(13.F, false, 1.4F), PaddockRgb(0xABC0CC), dkr::localisation::text("play.skip_launcher_help"), width); - PaddockGap(8.F); } bool AutomaticStartHasMods() { @@ -31,13 +29,15 @@ bool AutomaticStartHasMods() { return dkr::runtime::magic_codes::selected_mask() != 0; } -bool DrawStartingContent(const dkr::mods::ModLaunchView& state, bool mods, bool syncing, double seconds) { +bool DrawStartingContent(const dkr::mods::ModLaunchView& state, bool mods, bool syncing, double seconds, + bool returning = false) { auto* draw = ImGui::GetWindowDrawList(); const auto at = ImGui::GetWindowPos(); const auto size = ImGui::GetWindowSize(); auto layout = dkr::library_ui::startup_layout(size.x, size.y, 0); const float scale = layout.scale, padding = 26.F * scale, inner = std::max(1.F, layout.panel - 2.F * padding); - const auto title = dkr::localisation::text(syncing ? "play.syncing_game" : "play.starting_game"); + const auto title = returning ? dkr::localisation::source("Returning to Launcher...") + : dkr::localisation::text(syncing ? "play.syncing_game" : "play.starting_game"); const auto loading = dkr::localisation::text(syncing ? "play.syncing_status" : "play.loading_mods"); const auto button = dkr::localisation::text("play.open_launcher"); const auto stage = @@ -54,7 +54,7 @@ bool DrawStartingContent(const dkr::mods::ModLaunchView& state, bool mods, bool const float mod_height = mods ? 14.F * scale + loading_height + 11.F * scale + 10.F * scale + (stage_height > 0 ? 11.F * scale + stage_height : 0) : 0; - const float caption = 20.F * scale + title_height + mod_height + 14.F * scale + button_height + 18.F * scale; + const float caption = 38.F * scale + title_height + mod_height + (returning ? 0.F : 14.F * scale + button_height); layout = dkr::library_ui::startup_layout(size.x, size.y, caption); ImGui::SetCursorPos({(size.x - layout.logo) * .5F, layout.top}); BrandBlock(layout.logo, layout.logo, false); @@ -71,6 +71,8 @@ bool DrawStartingContent(const dkr::mods::ModLaunchView& state, bool mods, bool y += height; }; line(heading, title, title_height); + if (returning) + return false; if (mods) { y += 14.F * scale; line(subheading, loading, loading_height); @@ -117,7 +119,8 @@ bool DrawStartingContent(const dkr::mods::ModLaunchView& state, bool mods, bool bool DrawAutomaticStart(dkr::library_ui::AutomaticStart& automatic, LauncherBackgroundTexture& background, SDL_Renderer* renderer, double scroll, bool software, dkr::launcher_themes::Theme theme, - double seconds, const dkr::mods::ModLaunchView* preview = nullptr, bool syncing = false) { + double seconds, const dkr::mods::ModLaunchView* preview = nullptr, bool syncing = false, + bool returning = false) { BeginMainWindow("DKR-R Starting", ImGuiWindowFlags_NoBackground); DrawLauncherBackdrop(background, renderer, scroll, software); dkr::launcher_themes::weather(ImGui::GetWindowDrawList(), ImGui::GetWindowPos(), ImGui::GetWindowSize(), theme, @@ -125,7 +128,8 @@ bool DrawAutomaticStart(dkr::library_ui::AutomaticStart& automatic, LauncherBack auto state = preview ? *preview : g_mod_launch.snapshot(); if (syncing) state.stage = "Getting everyone ready..."; - const bool pressed = DrawStartingContent(state, automatic.loading_mods() || syncing, syncing, seconds); + const bool pressed = + DrawStartingContent(state, !returning && (automatic.loading_mods() || syncing), syncing, seconds, returning); if (pressed && !syncing) { automatic.cancel(); g_mod_launch.cancel(); diff --git a/runtime-recomp/src/game/library_ui/handoff_ui.inl b/runtime-recomp/src/game/library_ui/handoff_ui.inl index 9995da97..198c00b7 100644 --- a/runtime-recomp/src/game/library_ui/handoff_ui.inl +++ b/runtime-recomp/src/game/library_ui/handoff_ui.inl @@ -140,3 +140,24 @@ bool DrawRuntimeStartingGame() { } return true; } + +bool DrawRuntimeReturningFromRun() { + const auto alpha = dkr::runtime::time_trial::launcher_return_opacity(); + if (alpha <= 0.F) + return false; + BeginMainWindow("DKR-R Returning", ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoInputs); + auto* draw = ImGui::GetWindowDrawList(); + const int first = draw->VtxBuffer.Size; + const double seconds = ImGui::GetTime(); + DrawRuntimeStartupClouds(seconds); + dkr::launcher_themes::weather(draw, ImGui::GetWindowPos(), ImGui::GetWindowSize(), dkr::launcher_themes::displayed, + seconds, dkr::launcher_themes::preferences.calendar); + DrawStartingContent({}, false, false, seconds, true); + for (int i = first; i < draw->VtxBuffer.Size; ++i) { + auto& colour = draw->VtxBuffer[i].col; + const unsigned opacity = (colour >> IM_COL32_A_SHIFT) & 255U; + colour = (colour & ~IM_COL32_A_MASK) | (unsigned(opacity * alpha) << IM_COL32_A_SHIFT); + } + ImGui::End(); + return true; +} diff --git a/runtime-recomp/src/game/library_ui/leaderboard_rankings.inl b/runtime-recomp/src/game/library_ui/leaderboard_rankings.inl new file mode 100644 index 00000000..5406da55 --- /dev/null +++ b/runtime-recomp/src/game/library_ui/leaderboard_rankings.inl @@ -0,0 +1,541 @@ +std::string LeaderboardPoints(std::int64_t milli) { + char formatted[32]; + std::snprintf(formatted, sizeof(formatted), "%.3f", static_cast(milli) / 1000.0); + std::string result(formatted); + while (result.ends_with('0')) + result.pop_back(); + if (result.ends_with('.')) + result.pop_back(); + return result; +} + +std::string RecordDate(std::int64_t seconds) { + const auto stamp = static_cast(seconds); + std::tm date{}; +#ifdef _WIN32 + if (gmtime_s(&date, &stamp)) + return {}; +#else + if (!gmtime_r(&stamp, &date)) + return {}; +#endif + char label[28]{}; + std::strftime(label, sizeof(label), "%d %b %Y", &date); + return label; +} + +std::int64_t RecordUnix(const dkr::store::Json& data, const char* key) { + const auto value = data.find(key); + if (value == data.end() || !value->is_number_integer()) + return 0; + return std::clamp(value->get(), 0, 253402300799); +} + +std::string RecordDuration(std::int64_t seconds) { + if (seconds >= 86400) { + const auto days = seconds / 86400; + return std::to_string(days) + (days == 1 ? " day" : " days"); + } + if (seconds >= 3600) { + const auto hours = seconds / 3600; + return std::to_string(hours) + (hours == 1 ? " hour" : " hours"); + } + if (seconds >= 60) { + const auto minutes = seconds / 60; + return std::to_string(minutes) + (minutes == 1 ? " minute" : " minutes"); + } + return std::to_string(std::max(seconds, 0)) + " sec"; +} + +void DrawTrackRecordHistory(float width, const dkr::store::Json& history, const std::string& board) { + if (!history.is_object()) + return; + const auto changes = history.find("changes"); + if (changes == history.end() || !changes->is_array()) + return; + const bool complete = history.value("complete", false); + OlHeading("World record history", 21.F, kOlCream, width); + if (changes->empty()) { + OlParagraph(complete ? "Record history appears after the first published run." + : "Publication dates are unavailable for these results.", + 15.F, kOlSoft, width); + return; + } + static std::string selected_board; + static std::int64_t selected_at = 0; + if (selected_board != board) { + selected_board = board; + selected_at = 0; + } + const auto at = [&](std::size_t index) { return RecordUnix((*changes)[index], "at"); }; + const auto ticks = [&](std::size_t index) { return LeaderboardNumber((*changes)[index], "ticks"); }; + const auto last = changes->size() - 1; + const auto latest = std::max(at(last), RecordUnix(history, "asOf")); + std::size_t selected = last; + for (std::size_t index = 0; index < changes->size(); ++index) + if (selected_at == at(index)) + selected = index; + + const auto chart_origin = ImGui::GetCursorScreenPos(); + constexpr float height = 150.F; + const float left = std::min(100.F, width * .40F); + const float right = std::max(left + 1.F, width - 11.F); + const auto font = OlRead(14.F); + const auto end = complete ? latest : at(last); + const double time_span = static_cast(std::max(end - at(0), 1)); + const double pace_span = static_cast(std::max(ticks(0) - ticks(last), 1)); + const auto chart_x = [&](std::int64_t stamp) { + return chart_origin.x + left + (right - left) * static_cast((stamp - at(0)) / time_span); + }; + const auto chart_y = [&](std::int64_t pace) { + return chart_origin.y + 18.F + 96.F * static_cast((ticks(0) - pace) / pace_span); + }; + + ImGui::Dummy({width, height}); + auto* draw = ImGui::GetWindowDrawList(); + const auto x0 = chart_origin.x + left; + const auto x1 = chart_origin.x + right; + const auto caption = [&](const std::string& label, ImVec2 pos) { + draw->AddText(font.font, font.size, pos, PaddockCol(kOlSoft), label.c_str()); + }; + for (const auto tick : std::array{ticks(0), ticks(last)}) { + const auto y = chart_y(tick); + draw->AddLine({x0, y}, {x1, y}, PaddockCol(kOlRing)); + caption(LeaderboardTime(tick), {chart_origin.x, y - 8.F}); + if (ticks(0) == ticks(last)) + break; + } + const float date_y = chart_origin.y + 129.F; + caption(RecordDate(at(0)), {x0, date_y}); + if (end != at(0) && x1 - x0 > 212.F) { + const auto label = RecordDate(end); + const auto span = font.font->CalcTextSizeA(font.size, FLT_MAX, 0.F, label.c_str()); + caption(label, {x1 - span.x, date_y}); + } + + float nearest = 16.F; + const auto pointer = ImGui::GetMousePos(); + const bool clicked = ImGui::IsItemHovered() && ImGui::IsMouseClicked(ImGuiMouseButton_Left); + for (std::size_t index = 0; index < changes->size(); ++index) { + const float x = chart_x(at(index)), y = chart_y(ticks(index)); + const float next_x = index != last ? chart_x(at(index + 1)) : chart_x(end); + draw->AddLine({x, y}, {next_x, y}, PaddockCol(kOlAmber), 2.F); + if (index != last) + draw->AddLine({next_x, y}, {next_x, chart_y(ticks(index + 1))}, PaddockCol(kOlAmber), 2.F); + draw->AddCircleFilled({x, y}, index == selected ? 5.5F : 3.F, PaddockCol(kOlAmber)); + if (clicked) { + const float distance = std::abs(pointer.x - x) + std::abs(pointer.y - y); + if (distance < nearest) { + nearest = distance; + selected = index; + selected_at = at(index); + } + } + } + { + const OlDisabled unavailable(selected == 0); + if (OlButton("Earlier record")) { + --selected; + selected_at = at(selected); + } + } + ImGui::SameLine(); + { + const OlDisabled unavailable(selected == last); + if (OlButton("Later record")) { + ++selected; + selected_at = at(selected); + } + } + const auto& event = (*changes)[selected]; + const auto expired = RecordUnix(event, "until"); + std::string detail = LeaderboardTime(ticks(selected)) + " | " + RecordDate(at(selected)); + if (expired || complete) + detail += " | " + std::string(expired ? "Stood for " : "Unbeaten for ") + + RecordDuration((expired ? expired : latest) - at(selected)); + OlParagraph(detail, 16.F, kOlCream, width, true); + if (const auto holders = event.find("holders"); holders != event.end() && holders->is_array()) { + for (const auto& holder : *holders) { + auto line = StoreText(holder, "name", 96); + const auto until = RecordUnix(holder, "until"); + if (until || complete) + line += " | " + std::string(until ? "Held for " : "Holding for ") + + RecordDuration((until ? until : latest) - RecordUnix(holder, "from")); + OlParagraph(line, 15.F, kOlSoft, width); + } + } + if (!complete || LeaderboardNumber(history, "earlierChanges")) + OlParagraph(complete ? "Showing the latest record changes." : "Some publication dates are unavailable.", 14.F, + kOlSoft, width); +} + +enum class OverallPlayerTab { Score, Runs }; + +dkr::store::Json g_overall_standings, g_overall_profile; +std::string g_overall_player, g_overall_focus; +OverallPlayerTab g_overall_tab = OverallPlayerTab::Score; +bool g_overall_runs_requested = false; +bool g_overall_show_custom = false; + +void SelectOverallPlayer(std::string id) { + g_overall_player = std::move(id); + g_overall_profile = nullptr; + g_overall_runs_requested = false; + g_overall_show_custom = false; +} + +void RefreshOverallRankings() { + RankedJob([] { + auto data = dkr::store::service().overall_rankings(); + return [data = std::move(data)]() mutable { + g_overall_standings = std::move(data); + g_overall_profile = nullptr; + g_overall_runs_requested = false; + }; + }); +} + +void RefreshOverallPlayer(const std::string& id, unsigned offset = 0) { + g_overall_runs_requested = true; + RankedJob([id, offset] { + auto data = dkr::store::service().overall_rankings(id, offset); + return [id, offset, data = std::move(data)]() mutable { + if (id != g_overall_player) + return; + if (offset && g_overall_profile.is_object()) { + for (auto& entry : data["events"]) + g_overall_profile["events"].push_back(std::move(entry)); + g_overall_profile["nextOffset"] = data["nextOffset"]; + } else { + g_overall_profile = std::move(data); + } + }; + }); +} + +std::string OverallPersonalBests(const dkr::store::Json& player) { + const auto count = player.find("personalBests"); + return count != player.end() && count->is_number_integer() + ? std::to_string(LeaderboardNumber(player, "personalBests")) + : "—"; +} + +void DrawOverallStandings(float width, const dkr::store::Json& players) { + DrawOlCard( + width, OlPanelLook{}, + [&](float inner) { + OlHeading("Top Players", 24.F, kOlCream, inner); + PaddockGap(4.F); + const bool compact = inner < 300.F; + constexpr auto flags = + ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_NoPadOuterX; + ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, {compact ? 3.F : 5.F, 4.F}); + if (ImGui::BeginTable("top-player-standings", 5, flags, {inner, 0.F})) { + ImGui::TableSetupColumn("Rank", ImGuiTableColumnFlags_WidthFixed, compact ? 34.F : 46.F); + ImGui::TableSetupColumn("Player", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("PBs", ImGuiTableColumnFlags_WidthFixed, compact ? 29.F : 34.F); + ImGui::TableSetupColumn("WRs", ImGuiTableColumnFlags_WidthFixed, compact ? 29.F : 38.F); + ImGui::TableSetupColumn("Points", ImGuiTableColumnFlags_WidthFixed, compact ? 58.F : 67.F); + + const auto cell = [](std::string_view text, float height, unsigned colour, bool right = false) { + const float width = ImGui::GetContentRegionAvail().x; + const auto type = OlRead(14.F, true, 1.2F); + const std::string label = PaddockEllipsize(type, text, width); + auto at = ImGui::GetCursorScreenPos(); + if (right) + at.x += std::max(0.F, width - PaddockMeasure(type, label)); + at.y += (height - type.line) * .5F; + PaddockDrawRun(ImGui::GetWindowDrawList(), type, at, PaddockCol(colour), label.data(), + label.data() + label.size()); + ImGui::Dummy({width, height}); + }; + + ImGui::TableNextRow(); + int column = 0; + for (const auto* header : {compact ? "#" : "Rank", "Player", "PBs", "WRs", "Points"}) { + ImGui::TableNextColumn(); + cell(dkr::localisation::source(header), 22.F, kOlSoft, column >= 2); + ++column; + } + constexpr float row_height = 34.F; + for (const auto& player : players) { + const auto id = StoreText(player, "id", 96); + if (id.empty()) + continue; + const auto name = StoreText(player, "name", 96); + const auto place = LeaderboardNumber(player, "place"); + const bool selected = g_overall_player == id; + ImGui::PushID(id.c_str()); + ImGui::TableNextRow(); + ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0, PaddockCol(selected ? 0x194650U : 0x123345U)); + ImGui::TableNextColumn(); + const auto at = ImGui::GetCursorScreenPos(); + const unsigned badge = place == 1 ? 0x644C26U + : place == 2 ? 0x40576BU + : place == 3 ? 0x67482FU + : 0x23495CU; + PaddockFill(ImGui::GetWindowDrawList(), {at.x + 2.F, at.y + 4.F}, {at.x + 30.F, at.y + 30.F}, + PaddockRound(5.F), PaddockCol(badge)); + const auto rank = std::to_string(place); + const auto digit = OlRead(14.F, true, 1.2F); + PaddockDrawRun( + ImGui::GetWindowDrawList(), digit, + {at.x + 16.F - PaddockMeasure(digit, rank) * .5F, at.y + (row_height - digit.line) * .5F}, + PaddockCol(place == 1 ? kOlCream : kOlInk), rank.data(), rank.data() + rank.size()); + ImGui::Dummy({32.F, row_height}); + + ImGui::TableNextColumn(); + const float name_width = ImGui::GetContentRegionAvail().x; + const auto caption = + PaddockEllipsize(OlRead(14.F, true, 1.2F), name, std::max(1.F, name_width - 14.F)); + if (g_overall_focus == id) { + ImGui::SetKeyboardFocusHere(); + g_overall_focus.clear(); + } + if (OlButton((caption + "###player").c_str(), OlTone::Plain, name_width, + caption != name ? name.c_str() : nullptr, row_height) && + !selected) + SelectOverallPlayer(id); + StoreControlFocus(); + + ImGui::TableNextColumn(); + cell(OverallPersonalBests(player), row_height, kOlInk, true); + ImGui::TableNextColumn(); + cell(std::to_string(LeaderboardNumber(player, "records")), row_height, kOlInk, true); + ImGui::TableNextColumn(); + cell(LeaderboardPoints(LeaderboardNumber(player, "total")), row_height, kOlCream, true); + ImGui::PopID(); + } + ImGui::EndTable(); + } + ImGui::PopStyleVar(); + if (g_overall_standings.value("tiedCutoff", false)) + OlParagraph("More players share the final rank shown.", 14.F, kOlSoft, inner); + }, + 13.F); +} + +void DrawOverallScoreBreakdown(float width, const dkr::store::Json& player) { + const auto points = player.find("points"); + const auto draw_category = [&](const char* label, const char* key, int cap) { + const auto earned = points == player.end() ? 0 : LeaderboardNumber(*points, key); + const std::string score = LeaderboardPoints(earned) + " / " + std::to_string(cap) + " pts"; + const auto caption = LocalisedUi::copy(label); + const auto value_type = OlRead(14.F, false, 1.25F); + const float value_width = PaddockMeasure(value_type, score) + 2.F; + const bool side_by_side = width >= PaddockMeasure(OlRead(15.F, true, 1.25F), caption) + value_width + 10.F; + OlParagraph(caption, 15.F, kOlInk, side_by_side ? width - value_width - 8.F : width, true, 1.25F); + if (side_by_side) + ImGui::SameLine(0.F, 8.F); + OlParagraph(score, 14.F, kOlSoft, side_by_side ? value_width : width, false, 1.25F); + const auto at = ImGui::GetCursorScreenPos(); + auto* draw = ImGui::GetWindowDrawList(); + const float fraction = std::clamp(static_cast(earned) / (1000.F * cap), 0.F, 1.F); + PaddockFill(draw, at, {at.x + width, at.y + 6.F}, PaddockRound(3.F), PaddockCol(0x254658U)); + if (fraction > 0.F) + PaddockFill(draw, at, {at.x + width * fraction, at.y + 6.F}, PaddockRound(3.F), PaddockCol(kOlGo)); + ImGui::Dummy({width, 6.F}); + }; + draw_category("Vanilla Tracks", "vanilla", 500); + draw_category("Custom Tracks", "custom", 250); + draw_category("Full Game", "fullGame", 250); + OlParagraph(std::to_string(LeaderboardNumber(player, "podiums")) + " podiums · " + + std::to_string(LeaderboardNumber(player, "coverage")) + " ranked events", + 14.F, kOlSoft, width); +} + +std::optional DrawOverallPlayerRuns(float width) { + if (!g_overall_profile.is_object()) { + if (!g_overall_runs_requested && !DialogJobRunning()) + RefreshOverallPlayer(g_overall_player); + OlParagraph(DialogJobRunning() ? "Loading ranked runs..." : "Ranked runs are unavailable.", 15.F, kOlSoft, + width); + if (!DialogJobRunning() && OlButton("Try again")) + RefreshOverallPlayer(g_overall_player); + return {}; + } + + std::optional next; + const auto events = g_overall_profile.find("events"); + if (events == g_overall_profile.end() || !events->is_array() || events->empty()) { + OlParagraph("No ranked runs to show.", 15.F, kOlSoft, width); + return {}; + } + for (const auto& event : *events) { + const auto kind = StoreText(event, "kind", 16); + const auto id = StoreText(event, "id", 96); + const auto vehicle = StoreText(event, "vehicle", 24); + const bool full = kind == "full-game"; + const auto& race = event["race"]; + ImGui::PushID((kind + "/" + id + "/" + vehicle).c_str()); + const auto at = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddLine(at, {at.x + width, at.y}, PaddockCol(kOlRing)); + ImGui::Dummy({width, 1.F}); + auto title = StoreText(event, "title", 120); + if (!full) + title += " · " + LeaderboardVehicle(vehicle); + OlParagraph(title, 16.F, kOlCream, width, true, 1.2F); + auto times = LeaderboardTime(LeaderboardNumber(race, "ticks")) + " | #" + + std::to_string(LeaderboardNumber(race, "place")); + if (const auto lap = event.find("lap"); lap != event.end()) + times += " | Best lap " + LeaderboardTime(LeaderboardNumber(*lap, "ticks")) + " | #" + + std::to_string(LeaderboardNumber(*lap, "place")); + OlParagraph(times, 14.F, kOlSoft, width, false, 1.2F); + if (OlButton("View Times", OlTone::Plain, 0.F, nullptr, 32.F)) + next = TrackQuery{id, full ? "" : vehicle, "", kind == "custom", false, 0, full}; + StoreControlFocus(); + if (const auto run = StoreText(race, "runId", 96); !run.empty()) { + const OlDisabled launch(DialogJobRunning() || !CanLaunchLeaderboardReplay()); + float used_width = OlButtonWidth("View Times"); + const auto action = [&](const char* label, LeaderboardReplayAction action_type) { + const float button_width = OlButtonWidth(label); + if (used_width + 6.F + button_width <= width) { + ImGui::SameLine(0.F, 6.F); + used_width += 6.F + button_width; + } else { + used_width = button_width; + } + if (OlButton(label, OlTone::Plain, std::min(width, button_width), nullptr, 32.F)) + WatchLeaderboardReplay(run, false, action_type, + action_type == LeaderboardReplayAction::RaceGhost + ? StoreText(g_overall_profile["player"], "name", 60) + : std::string{}); + StoreControlFocus(); + }; + action("Watch", LeaderboardReplayAction::Watch); + if (!full) + action("Race Ghost", LeaderboardReplayAction::RaceGhost); + } + ImGui::PopID(); + } + { + const OlDisabled busy(DialogJobRunning()); + if (const auto offset = LeaderboardNumber(g_overall_profile, "nextOffset"); offset && OlButton("More results")) + RefreshOverallPlayer(g_overall_player, static_cast(offset)); + } + if (const auto custom = g_overall_profile.find("customTracks"); + custom != g_overall_profile.end() && custom->is_array() && !custom->empty()) { + if (OlButton(g_overall_show_custom ? "Hide scoring tracks" : "Custom scoring tracks")) + g_overall_show_custom = !g_overall_show_custom; + if (g_overall_show_custom) { + for (const auto& track : *custom) { + const auto title = StoreText(track, "title", 120); + OlParagraph((title.empty() ? StoreText(track, "id", 96) : title) + " | " + + LeaderboardPoints(LeaderboardNumber(track, "points")) + " pts", + 14.F, kOlSoft, width); + } + } + } + return next; +} + +std::optional DrawOverallPlayerPanel(float width, const dkr::store::Json& player) { + std::optional next; + DrawOlCard( + width, OlPanelLook{}, + [&](float inner) { + const auto total = LeaderboardPoints(LeaderboardNumber(player, "total")) + " pts"; + const float total_width = std::ceil(PaddockMeasure(OlSignType(23.F, 1.3F), total)) + 4.F; + const bool inline_total = inner >= total_width + 148.F; + ImGui::BeginGroup(); + const float name_width = inline_total ? inner - total_width - 10.F : inner; + OlParagraph("#" + std::to_string(LeaderboardNumber(player, "place")) + " overall", 14.F, kOlSoft, + name_width, false, 1.2F); + OlHeading(StoreText(player, "name", 96), 23.F, kOlCream, name_width, 1.3F); + ImGui::EndGroup(); + if (inline_total) + ImGui::SameLine(0.F, 10.F); + OlHeading(total, 23.F, kOlAmber, inline_total ? total_width : inner, 1.3F); + + const auto tab = [&](const char* label, OverallPlayerTab target) { + if (OlButton(label, target == g_overall_tab ? OlTone::PlateStrong : OlTone::Plain, + std::min(inner, OlButtonWidth(label)), nullptr, 34.F)) + g_overall_tab = target; + StoreControlFocus(); + }; + tab("Score breakdown", OverallPlayerTab::Score); + if (OlButtonWidth("Score breakdown") + OlButtonWidth("Ranked runs") + 6.F <= inner) + ImGui::SameLine(0.F, 6.F); + tab("Ranked runs", OverallPlayerTab::Runs); + + OlPanelLook count_look; + count_look.fill = 0x123648; + const auto stat = [&](float available, const char* label, const std::string& value) { + DrawOlCard( + available, count_look, + [&](float inside) { + OlParagraph(label, 14.F, kOlSoft, inside, false, 1.2F); + OlHeading(value, 24.F, kOlCream, inside, 1.2F); + }, + 8.F); + }; + const bool pair_stats = inner >= 230.F; + const float stat_width = pair_stats ? (inner - 8.F) * .5F : inner; + stat(stat_width, "Posted PBs", OverallPersonalBests(player)); + if (pair_stats) + ImGui::SameLine(0.F, 8.F); + stat(stat_width, "World Records", std::to_string(LeaderboardNumber(player, "records"))); + PaddockGap(3.F); + + if (g_overall_tab == OverallPlayerTab::Score) + DrawOverallScoreBreakdown(inner, player); + else + next = DrawOverallPlayerRuns(inner); + }, + 13.F); + return next; +} + +std::optional DrawOverallRankings(float width) { + static bool show_points = false; + if (OlButton(show_points ? "Hide points explanation" : "How points work")) + show_points = !show_points; + StoreControlFocus(); + if (show_points) { + DrawOlFeature(width, "How points work", nullptr, [&](float inner) { + OlParagraph("Verified finishes earn points for placement (70%) and pace against the record (30%). " + "Solo boards count for 35%. Board weight grows to 100% at eight competitors.", + 15.F, kOlSoft, inner); + OlParagraph("Vanilla Tracks 500 | Custom Tracks 250 | Full Game 250", 16.F, kOlAmber, inner, true); + OlParagraph("Track scores use 75% full race and 25% best lap. Your best 10 custom tracks earn up to " + "200 points, and the next 20 earn up to 50. Adding a track keeps your existing points.", + 15.F, kOlSoft, inner); + }); + } + const auto players = g_overall_standings.find("players"); + if (players == g_overall_standings.end() || !players->is_array() || players->empty()) { + OlParagraph(DialogJobRunning() ? "Loading top players..." + : players == g_overall_standings.end() ? "Refresh to load the overall rankings." + : "Top players appear after the first published run.", + 15.F, kOlSoft, width); + return {}; + } + + const auto selected = [&] { + return std::ranges::find_if(*players, + [](const auto& player) { return StoreText(player, "id", 96) == g_overall_player; }); + }; + if (selected() == players->end()) + SelectOverallPlayer(StoreText(players->front(), "id", 96)); + + constexpr float gap = 12.F; + const bool columns = width >= 732.F; + const float standings_width = columns ? std::floor((width - gap) * .48F) : width; + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {ImGui::GetStyle().ItemSpacing.x, 6.F}); + ImGui::BeginGroup(); + DrawOverallStandings(standings_width, *players); + ImGui::EndGroup(); + if (columns) + ImGui::SameLine(0.F, gap); + else + PaddockGap(8.F); + + std::optional next; + if (const auto player = selected(); player != players->end()) { + ImGui::BeginGroup(); + next = DrawOverallPlayerPanel(columns ? width - standings_width - gap : width, *player); + ImGui::EndGroup(); + } + ImGui::PopStyleVar(); + return next; +} diff --git a/runtime-recomp/src/game/library_ui/leaderboards_page.inl b/runtime-recomp/src/game/library_ui/leaderboards_page.inl new file mode 100644 index 00000000..fe2936b4 --- /dev/null +++ b/runtime-recomp/src/game/library_ui/leaderboards_page.inl @@ -0,0 +1,2585 @@ +constexpr const char* kLeaderboardWebsite = "https://positron-portal.com/dkr-r/#leaderboards"; + +std::int64_t LeaderboardNumber(const dkr::store::Json& data, const char* key) { + const auto value = data.find(key); + if (value == data.end() || !value->is_number_integer()) + return 0; + return std::clamp(value->get(), std::int64_t(0), + std::int64_t(dkr::runtime::time_trial::kAdventureMaxUpdates * 2)); +} + +std::string LeaderboardTime(std::int64_t ticks) { + const auto millis = ticks * 1000 / 60; + char clock[16]{}; + std::snprintf(clock, sizeof(clock), "%d:%02d.%03d", int(millis / 60000), int(millis / 1000 % 60), + int(millis % 1000)); + return clock; +} + +namespace trial = dkr::runtime::time_trial; +#include "speedrunning_options.inl" + +struct LapReference { + std::array personal{}, best_segments{}; + unsigned world_best_lap = 0; +}; + +using AdventureReference = std::map>; +using AdventureSegments = std::map, std::int64_t>; + +struct TimeTrialRequest { + trial::Mode mode; + std::filesystem::path replay; + std::optional attempt = std::nullopt; + unsigned racer = trial::kDiddy; + const trial::Course* course = &trial::kCourses.front(); + trial::Vehicle vehicle = trial::Vehicle::Car; + trial::Adventure adventure = trial::Adventure::None; + std::string track; + std::filesystem::path ghost; + std::string ghost_name; + LapReference lap_reference; + unsigned prior_best = 0; + AdventureReference adventure_pb, adventure_record; + AdventureSegments adventure_segments; +}; +std::optional g_time_trial_request; +std::optional g_previous_time_trial_request; +std::optional g_local_run_confirmation; +std::filesystem::path g_ranked_playback_file; +unsigned g_run_prior_best = 0; +bool g_open_speedrunning_result = false; +LapReference g_run_lap_reference; +AdventureReference g_adventure_pb_splits, g_adventure_record_splits; +AdventureSegments g_adventure_segments; + +void DeleteRankedPlayback(const std::filesystem::path& file) { + if (file.empty()) + return; + std::error_code error; + std::filesystem::remove(file, error); + std::filesystem::remove(trial::portable_ghost_file(file), error); +} + +void QueueTimeTrialRequest(TimeTrialRequest request, bool signed_in) { + if (signed_in && request.mode == trial::Mode::Record && !request.attempt) + g_local_run_confirmation = std::move(request); + else + g_time_trial_request = std::move(request); +} + +void DrawLocalRunConfirmation() { + if (!g_local_run_confirmation) + return; + constexpr const char* title = "Start a local run?"; + if (!ImGui::IsPopupOpen(title)) + ImGui::OpenPopup(title); + if (!BeginPaddedModal(title, ImGuiWindowFlags_AlwaysAutoResize)) + return; + const auto catalogue = dkr::store::service().view()->speedrun_catalogue; + OlParagraph(catalogue && catalogue->value("canClaimLocal", false) + ? "This run will be saved locally. You can link an eligible run to your Discord account later." + : "This run will be saved locally. Sign in before starting a run to post it to the leaderboard.", + 15.F, kOlInk, 350.F); + if (OlButton("Cancel")) { + if (!g_ranked_playback_file.empty() && g_local_run_confirmation->ghost == g_ranked_playback_file) + DeleteRankedPlayback(std::exchange(g_ranked_playback_file, {})); + g_local_run_confirmation.reset(); + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (OlButton("Start local run", OlTone::Go)) { + g_time_trial_request = std::exchange(g_local_run_confirmation, std::nullopt); + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +std::string g_time_trial_message; +dkr::store::Json g_ranked_runs = nullptr; +std::string g_ranked_runs_owner; +bool g_ranked_runs_review = false; +std::chrono::steady_clock::time_point g_ranked_runs_received; + +bool LaunchTimeTrial(TimeTrialRequest& request) { + const auto start = [&] { + if (!request.ghost.empty()) + return trial::start_ghost(request.ghost, request.replay, g_time_trial_message, request.racer, request.mode, + {}, request.attempt ? &*request.attempt : nullptr, request.ghost_name); + return trial::start(request.mode, request.replay, g_time_trial_message, + request.attempt ? &*request.attempt : nullptr, request.racer, *request.course, + request.vehicle, request.adventure, request.track); + }; + if (!start()) { + if (!request.ghost.empty() || request.mode != trial::Mode::Record || request.track.empty() || !request.attempt) + return false; + // An installed custom track can differ from the version listed online. + request.attempt.reset(); + if (!start()) + return false; + } + g_run_lap_reference = request.lap_reference; + g_run_prior_best = request.prior_best; + g_adventure_pb_splits = request.adventure_pb; + g_adventure_record_splits = request.adventure_record; + g_adventure_segments = request.adventure_segments; + trial::set_finish_personal_best(request.prior_best); + return true; +} + +std::string RankedRunsOwner() { + const auto file = g_config_directory / "ranked-local.json"; + static std::mutex local_owner_mutex; + std::scoped_lock lock(local_owner_mutex); + static std::filesystem::path prior_file; + static std::string local_owner; + if (file != prior_file) { + prior_file = file; + local_owner.clear(); + try { + const auto local = dkr::store::Json::parse(dkr::updates::read_text(file, 4096)); + const auto port = LeaderboardNumber(local, "port"); + if (port > 1023 && port <= 65535 && StoreText(local, "token", 43).size() == 43) + local_owner = "local-ranked-" + std::to_string(port); + } catch (const std::exception&) { + // Ordinary profiles use the signed-in Mod Library account. + } + } + return local_owner.empty() ? StoreText(dkr::store::service().view()->user, "id", 96) : local_owner; +} + +std::filesystem::path NewTimeTrialFile(const std::filesystem::path& config, const std::string& prefix) { + auto directory = config / "speedruns"; + std::filesystem::create_directories(directory); + const auto stamp = std::chrono::system_clock::now().time_since_epoch().count(); + return directory / (prefix + "-" + std::to_string(stamp) + ".dkrreplay"); +} + +void RankedJob(std::function()> job) { + g_time_trial_message.clear(); + StartDialogJob([job = std::move(job)]() -> std::function { + try { + return job(); + } catch (const std::exception& failure) { + return [message = std::string(failure.what())] { g_time_trial_message = message; }; + } + }); +} + +#include "replay_library.inl" + +void ApplyReplayRetention(const trial::Result& result) { + const auto library = g_config_directory / "speedruns"; + if (!RunPreference(RunOption::Retention) || !result.complete || result.replay || + result.file.parent_path() != library) + return; + try { + const auto replays = ReadLocalReplayLibrary(library); + const auto saved = std::ranges::find(replays, result.file, &LocalReplay::file); + if (saved != replays.end() && saved->local_capture && !saved->personal_best && !saved->beat_ghost && + saved->posted_owner.empty() && + !dkr::library_ui::can_post_replay_attempt(saved->has_attempt, saved->practice, false)) + RemoveLocalReplay(saved->file); + } catch (const std::exception&) { + // Keep the recording when the library cannot classify it. + } +} + +std::filesystem::path TimeTrialRom(const TimeTrialRequest& request, const std::filesystem::path& selected, + const std::vector& catalogue) { + namespace rom = dkr::runtime::rom; + const auto& evidence = request.ghost.empty() ? request.replay : request.ghost; + if (request.mode == trial::Mode::Record && request.ghost.empty()) + return selected; + try { + const unsigned revision = ReadReplaySummary(evidence).at("rom").get(); + const auto required = revision == 77 ? rom::Revision::UsV77 : rom::Revision::UsV80; + if (rom::inspect(selected).revision == required) + return selected; + const auto found = std::ranges::find_if( + catalogue, [&](const auto& entry) { return rom::inspect(entry.path).revision == required; }); + if (found != catalogue.end()) + return found->path; + g_time_trial_message = revision == 77 ? "Add your US v1.0 ROM in Play to watch this replay." + : "Add your US v1.1 ROM in Play to watch this replay."; + } catch (const std::exception& error) { + g_time_trial_message = error.what(); + } + return {}; +} + +bool CanLaunchLeaderboardReplay(); + +double g_ranked_podium_started = -1; + +void DrawRankedPodium() { + const auto state = trial::progress(); + if (!state.finish_update || state.replay || !state.clock || !g_previous_time_trial_request || + g_previous_time_trial_request->mode != trial::Mode::Record) + return; + const auto& attempt = g_previous_time_trial_request->attempt; + const bool pb = !g_run_prior_best || state.clock < g_run_prior_best; + const bool celebration = speed::celebrates(state.podium_place, pb); + if (!celebration && !RunPreference(RunOption::FinishSummary)) + return; + const double now = ImGui::GetTime(); + if (g_ranked_podium_started < 0) { + g_ranked_podium_started = now; + if (celebration) + AchievementChime(RunPreference(RunOption::CueVolume) * .01F); + } + if (now - g_ranked_podium_started >= (celebration ? 4.5 : 2.7)) + return; + + const auto* view = ImGui::GetMainViewport(); + const bool record = state.podium_place == 1; + const std::string heading = !celebration ? "FINISH" + : record ? "WORLD RECORD RUN!" + : state.podium_place ? "PODIUM FINISH #" + std::to_string(state.podium_place) + : "PERSONAL BEST!"; + const auto art = record || !state.podium_place ? 0xFFCE6C : state.podium_place == 2 ? 0xCED9E9 : 0xF0A477; + const auto ink = PaddockCol(art); + const std::string time = RunClock(state.clock); + const std::string detail = + attempt && attempt->finish_targets ? attempt->finish_targets->title + " | " + time : time; + constexpr const char* basis = "Compared with the leaderboard at the start of this run"; + const auto flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoInputs | + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoFocusOnAppearing; + if (!celebration || RunPreference(RunOption::Celebration) == 1) { + const float width = std::min(view->WorkSize.x - 32.F, 350.F); + ImGui::SetNextWindowPos({view->WorkPos.x + view->WorkSize.x * .5F, view->WorkPos.y + 24.F}, 0, {.5F, 0.F}); + ImGui::SetNextWindowSize({width, 0.F}); + ImGui::SetNextWindowBgAlpha(.89F); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 12.F); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {14.F, 10.F}); + if (ImGui::Begin("##speedrunning-finish", nullptr, flags | ImGuiWindowFlags_AlwaysAutoResize)) { + OlHeading(heading, 22.F, art, width - 28.F); + OlParagraph(detail, 16.F, kOlInk, width - 28.F); + if (celebration && state.podium_place) + OlParagraph(basis, 13.F, kOlSoft, width - 28.F); + } + ImGui::End(); + ImGui::PopStyleVar(2); + return; + } + ImGui::SetNextWindowPos(view->Pos); + ImGui::SetNextWindowSize(view->Size); + ImGui::SetNextWindowBgAlpha(.93F); + ImGui::Begin("##ranked-podium", nullptr, flags); + const auto size = ImGui::GetWindowSize(); + const auto offset = ImGui::GetWindowPos(); + auto* draw = ImGui::GetWindowDrawList(); + const bool motion = + !RunPreference(RunOption::ReducedMotion) && !dkr::runtime::achievements::view()->preferences.reduced_motion; + for (unsigned i = 0; i < (record ? 65U : 32U); ++i) { + const auto x = float((i * 37U) % 97U) / 97.F; + const auto phase = float((i * 23U) % 113U) / 113.F; + const float y = motion ? std::fmod(phase + float(now) * .18F, 1.F) : phase; + draw->AddCircleFilled({offset.x + x * size.x, offset.y + y * size.y}, 1.6F + float(i % 4), ink, 4); + } + const auto title = PaddockSign(std::min(62.F, size.x * .074F)); + const auto ext = title.font->CalcTextSizeA(title.size, FLT_MAX, 0.F, heading.c_str()); + draw->AddText(title.font, title.size, {offset.x + (size.x - ext.x) * .5F, offset.y + size.y * .28F}, ink, + heading.c_str()); + ImGui::SetCursorPos({std::max(14.F, (size.x - ImGui::CalcTextSize(detail.c_str()).x) * .5F), size.y * .46F}); + ImGui::TextUnformatted(detail.c_str()); + if (state.podium_place) { + ImGui::SetCursorPos({std::max(14.F, (size.x - ImGui::CalcTextSize(basis).x) * .5F), size.y * .62F}); + ImGui::TextDisabled("%s", basis); + } + ImGui::End(); +} + +std::optional ReadFinishTargets(const dkr::store::Json& reply) { + const auto found = reply.find("finishTargets"); + if (found == reply.end() || !found->is_object()) + return {}; + trial::FinishTargets targets{StoreText(*found, "title", 120), unsigned(LeaderboardNumber(*found, "personal"))}; + const auto times = found->find("rivals"); + if (targets.title.empty() || times == found->end() || !times->is_array() || times->size() > targets.rivals.size()) + return {}; + for (std::size_t index = 0; index < times->size(); ++index) { + const auto& time = (*times)[index]; + if (!time.is_number_integer()) + return {}; + const auto ticks = time.get(); + if (ticks <= 0 || ticks > trial::kAdventureMaxUpdates * 2) + return {}; + targets.rivals[index] = unsigned(ticks); + } + return targets; +} + +std::string TrackAttemptBoard(const dkr::store::Json* catalogue, std::string_view id, const trial::Course* course, + trial::Vehicle vehicle, unsigned racer) { + if (course) + return trial::board_for(*course, vehicle, racer); + if (!catalogue || !catalogue->contains("boards") || !catalogue->value("canSubmitCustom", false)) + return {}; + for (const auto& entry : catalogue->at("boards")) { + if (!entry.value("ranked", false)) + continue; + if (StoreText(entry, "trackId", 96) == id && + StoreText(entry, "vehicle", 24) == trial::kVehicleIds[static_cast(vehicle)] && + StoreText(entry, "racer", 32) == trial::kRacers[racer].name) + return StoreText(entry, "id", 96); + } + return {}; +} + +std::optional RequestTrackAttempt(const std::string& board, std::string_view id, + const trial::Course* course, trial::Vehicle vehicle, unsigned racer) { + if (board.empty()) + return {}; + try { + const auto reply = dkr::store::service().ranked_attempt(board); + const auto board_id = StoreText(reply, "board", 96); + const auto engine = StoreText(reply, "engine", 64); + const auto ticket = StoreText(reply, "ticket", 160); + if (board_id != board) + return {}; + auto attempt = + course ? trial::parse_attempt(board_id, engine, ticket, *course, vehicle, racer) + : trial::parse_custom_attempt(board_id, engine, ticket, StoreText(reply, "releaseId", 96), + StoreText(reply, "releaseHash", 64), StoreText(reply, "trackId", 96), + StoreText(reply, "trackHash", 64), vehicle, racer); + if (!attempt || (!course && attempt->track_id != id)) + return {}; + attempt->finish_targets = ReadFinishTargets(reply); + return attempt; + } catch (const std::exception&) { + // The player can still race locally when the service is unavailable. + return {}; + } +} + +std::pair ReadRunReference(const std::filesystem::path& directory, const std::string& id, + const trial::Course* course, trial::Vehicle vehicle, unsigned racer, + std::string_view track_hash); + +TimeTrialRequest PrepareGhostRun(const std::filesystem::path& file, const std::filesystem::path& config, + std::optional local_racer, bool signed_in) { + const auto manifest = ReadReplaySummary(file); + const auto racer = local_racer ? *local_racer : manifest.value("racer", trial::kDiddy); + if (racer >= trial::kRacers.size()) + throw std::runtime_error("The replay racer is unsupported."); + TimeTrialRequest request{trial::Mode::Record, NewTimeTrialFile(config, "Ghost-Practice")}; + request.racer = racer; + request.ghost = file; + const auto rules = StoreText(manifest, "ruleset", 48); + const bool custom = rules == trial::kCustomRules || rules == trial::kCustomVariableLapsRules; + const auto id = StoreText(manifest, custom ? "trackId" : "course", 96); + const auto* course = custom ? nullptr + : rules == trial::kLegacyRules ? &trial::kCourses.front() + : trial::course_for(id); + if (!custom && !course) + return request; + const auto vehicle_id = rules == trial::kLegacyRules ? "car" : StoreText(manifest, "vehicle", 16); + const auto vehicle = std::ranges::find(trial::kVehicleIds, vehicle_id); + if (vehicle == trial::kVehicleIds.end()) + return request; + const auto chosen = static_cast(vehicle - trial::kVehicleIds.begin()); + const auto snapshot = dkr::store::service().view(); + const auto board = + signed_in ? TrackAttemptBoard(snapshot->speedrun_catalogue.get(), id, course, chosen, racer) : std::string{}; + request.attempt = RequestTrackAttempt(board, id, course, chosen, racer); + if (custom && request.attempt && request.attempt->track_hash != StoreText(manifest, "trackHash", 64)) + request.attempt.reset(); + std::tie(request.lap_reference, request.prior_best) = + ReadRunReference(config / "speedruns", course ? std::string(course->id) : id, course, chosen, racer, + StoreText(manifest, "trackHash", 64)); + return request; +} + +void RaceReplayGhost(const std::filesystem::path& file) { + RankedJob([file, config = g_config_directory, signed_in = !RankedRunsOwner().empty()] { + auto request = PrepareGhostRun(file, config, std::nullopt, signed_in); + return [request = std::move(request), signed_in]() mutable { + QueueTimeTrialRequest(std::move(request), signed_in); + }; + }); +} + +struct PublishedReplayTimes { + std::filesystem::path profile; + std::string owner; + std::optional> scores; + std::chrono::steady_clock::time_point refresh_at{}; + bool unavailable = false; +}; +PublishedReplayTimes g_published_replay_times; + +void SavePublishedReplayTimes(const std::filesystem::path& profile, const std::string& owner, + std::optional> scores) { + if (profile == g_config_directory && owner == RankedRunsOwner()) { + const bool unavailable = !scores; + g_published_replay_times = {profile, owner, std::move(scores), + std::chrono::steady_clock::now() + std::chrono::seconds(30), unavailable}; + } +} + +void RefreshPublishedReplayTimes(const std::string& owner) { + auto& status = g_published_replay_times; + if (status.profile != g_config_directory || status.owner != owner) + status = {g_config_directory, owner}; + const auto now = std::chrono::steady_clock::now(); + if (now < status.refresh_at || DialogJobRunning()) + return; + status.refresh_at = now + std::chrono::seconds(30); + StartDialogJob([profile = status.profile, owner]() -> std::function { + std::optional> scores; + try { + scores = dkr::store::service().published_replay_times(); + } catch (const std::exception&) { + // Keep the posting decision pending until the signed-in player's times are known. + } + return [profile, owner, scores = std::move(scores)]() mutable { + SavePublishedReplayTimes(profile, owner, std::move(scores)); + }; + }); +} + +std::function SubmitRankedReplay(const std::filesystem::path& file, const std::filesystem::path& profile, + bool personal_best, bool link_local = false, std::string expected_owner = {}) { + const auto owner = RankedRunsOwner(); + if (link_local && owner != expected_owner) + throw std::runtime_error("Your signed-in account changed. Confirm the Discord account again."); + auto metadata = ReadReplaySidecar(file); + if (owner.empty() || file.parent_path() != profile / "speedruns" || !OwnReplayFile(file, metadata)) + throw std::runtime_error("Sign in and select one of your eligible recordings to post it."); + const auto manifest = ReadReplaySummary(file); + if (link_local ? !IsLocalReplayCapture(manifest) : !ReplayHasRankedAttempt(manifest)) + throw std::runtime_error("Sign in and select one of your eligible recordings to post it."); + if (personal_best && !link_local) { + auto scores = dkr::store::service().published_replay_times(); + if (std::ranges::binary_search(scores, + dkr::store::PublishedReplayTime{StoreText(manifest, "board", 96), + LeaderboardNumber(manifest, "clockTicks")})) { + return [profile, owner, scores = std::move(scores)]() mutable { + SavePublishedReplayTimes(profile, owner, std::move(scores)); + }; + } + } + const auto reply = dkr::store::service().submit_ranked_replay(file, link_local); + const auto state = StoreText(reply.at("run"), "state", 32); + try { + metadata["postedOwner"] = owner; + WriteReplaySidecar(file, metadata); + } catch (const std::exception&) { + // The service has accepted the replay even if the local receipt could not be written. + } + return [file, profile, state, owner] { + if (profile == g_config_directory && owner == RankedRunsOwner()) { + g_time_trial_message = "Run submitted | " + state; + g_ranked_runs = nullptr; + for (auto& replay : g_local_replays) + if (replay.file == file) + replay.posted_owner = owner; + } + }; +} + +void DrawReplayResult(const LocalReplay& replay) { + if (replay.personal_best) + DrawRaceBadge("PERSONAL BEST", {.36F, .245F, .09F, 1.F}); + if (replay.beat_ghost) + DrawRaceBadge("GHOST BEATEN", {.11F, .29F, .24F, 1.F}); +} + +std::string LocalClaimBoard(const LocalReplay& replay, const dkr::store::Json& catalogue) { + if (replay.track_id.empty()) + return replay.board; + const auto vehicle = std::ranges::find(trial::kVehicleNames, replay.vehicle); + if (vehicle == trial::kVehicleNames.end() || !catalogue.contains("boards")) + return {}; + std::string board; + for (const auto& entry : catalogue.at("boards")) { + if (entry.value("ranked", false) && StoreText(entry, "trackId", 96) == replay.track_id && + StoreText(entry, "trackHash", 64) == replay.track_hash && + StoreText(entry, "vehicle", 24) == trial::kVehicleIds[vehicle - trial::kVehicleNames.begin()] && + StoreText(entry, "racer", 32) == replay.racer) { + if (!board.empty()) + return {}; + board = StoreText(entry, "id", 96); + } + } + return board; +} + +void DrawLocalReplayPosting(const LocalReplay& replay, float width, const dkr::store::Json* catalogue) { + const auto snapshot = dkr::store::service().view(); + const auto owner = RankedRunsOwner(); + if (!replay.posted_owner.empty()) { + OlParagraph(owner == replay.posted_owner ? "Submitted · View status in My Submitted Runs" + : "This run has already been linked to a Discord account.", + 14.F, kOlSoft, width); + return; + } + constexpr const char* popup = "Link this local run?"; + const bool confirming = ImGui::IsPopupOpen(popup); + if (!confirming && catalogue) { + if (const auto board = LocalClaimBoard(replay, *catalogue); !board.empty() && !owner.empty()) { + RefreshPublishedReplayTimes(owner); + const auto& scores = g_published_replay_times.scores; + if (scores && std::ranges::binary_search(*scores, dkr::store::PublishedReplayTime{board, replay.time})) { + OlParagraph("Already on the leaderboard", 14.F, kOlSoft, width); + return; + } + } + } + + const OlDisabled busy(DialogJobRunning()); + if (owner.empty() && !confirming) { + if (OlButton("Sign in with Discord to link", OlTone::Go)) + dkr::store::service().login(); + return; + } + + static std::string confirmed_owner; + if (OlButton("Link & Post to Leaderboard", OlTone::Go)) { + confirmed_owner = owner; + ImGui::OpenPopup(popup); + } + constexpr ImGuiWindowFlags flags = ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize; + if (!BeginPaddedModal(popup, flags)) + return; + const auto name = StoreText(snapshot->user, "displayName", 100); + const auto credit = name.empty() ? std::string("your signed-in Discord account") : name; + const auto text_width = std::min(435.F, ImGui::GetMainViewport()->WorkSize.x * .7F); + OlParagraph("Link " + replay.title + " to " + credit + + " and send it for verification? The recording can only be linked once.", + 16.F, kOlInk, text_width); + PaddockGap(10.F); + const bool cancel = OlButton("Cancel") || ImGui::IsKeyPressed(ImGuiKey_Escape, false) || + ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false) || confirmed_owner != owner; + ImGui::SameLine(); + if (OlButton("Link & Post", OlTone::Go) && !cancel) { + RankedJob([file = replay.file, profile = g_config_directory, owner] { + return SubmitRankedReplay(file, profile, false, true, owner); + }); + ImGui::CloseCurrentPopup(); + } else if (cancel) { + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +void DrawReplayPosting(const LocalReplay& replay, float width, bool explain = false) { + const bool merit = replay.personal_best || replay.beat_ghost; + if (replay.local_capture && (merit || !replay.posted_owner.empty())) { + const auto catalogue = dkr::store::service().view()->speedrun_catalogue; + if (!replay.posted_owner.empty() || (catalogue && catalogue->value("canClaimLocal", false))) { + DrawLocalReplayPosting(replay, width, catalogue.get()); + return; + } + } + if (!dkr::library_ui::can_post_replay_attempt(replay.has_attempt, replay.practice, merit)) { + if (!replay.has_attempt && (merit || explain)) + OlParagraph("Linking this local run is unavailable.", 14.F, kOlSoft, width); + else if (explain) + OlParagraph("You can post this run if it's your personal best.", 14.F, kOlSoft, width); + return; + } + const auto owner = RankedRunsOwner(); + if (owner.empty()) { + OlParagraph("Sign in to post this run.", 14.F, kOlSoft, width); + } else if (owner == replay.posted_owner) { + OlParagraph("Submitted · View status in My Submitted Runs", 14.F, kOlSoft, width); + } else { + if (merit) { + RefreshPublishedReplayTimes(owner); + const auto& status = g_published_replay_times; + if (!status.scores) { + if (explain || status.unavailable) + OlParagraph(status.unavailable ? "Could not check your published times." + : "Checking your published times...", + 14.F, kOlSoft, width); + return; + } + if (std::ranges::binary_search(*status.scores, + dkr::store::PublishedReplayTime{replay.board, replay.time})) { + OlParagraph("Already on the leaderboard", 14.F, kOlSoft, width); + return; + } + } + const OlDisabled busy(DialogJobRunning()); + if (OlButton("Post to Leaderboard", OlTone::Go)) + RankedJob([file = replay.file, profile = g_config_directory, best = merit] { + return SubmitRankedReplay(file, profile, best); + }); + } +} + +std::optional g_split_bounds; + +std::array ReplayLaps(const dkr::store::Json& manifest) { + std::array laps{}; + const auto splits = manifest.find("splits"); + if (splits == manifest.end() || !splits->is_array() || splits->size() > laps.size()) + return laps; + unsigned previous = 0; + for (std::size_t i = 0; i < splits->size(); ++i) { + if (!(*splits)[i].is_number_unsigned()) + return {}; + const auto time = (*splits)[i].get(); + if (time <= previous) + return {}; + laps[i] = time - previous; + previous = time; + } + return laps; +} + +std::pair ReadRunReference(const std::filesystem::path& directory, const std::string& id, + const trial::Course* course, trial::Vehicle vehicle, unsigned racer, + std::string_view track_hash) { + LapReference result; + unsigned best = 0; + try { + for (const auto& replay : ReadLocalReplayLibrary(directory)) { + if (!replay.valid || replay.racer != trial::kRacers[racer].name || + replay.vehicle != trial::kVehicleNames[static_cast(vehicle)] || + (course ? replay.course != course->name || !replay.track_id.empty() : replay.track_id != id) || + (!track_hash.empty() && !course && replay.track_hash != track_hash)) + continue; + const auto laps = ReplayLaps(ReadReplaySummary(replay.file)); + for (std::size_t i = 0; i < laps.size(); ++i) + if (laps[i] && (!result.best_segments[i] || laps[i] < result.best_segments[i])) + result.best_segments[i] = laps[i]; + if (replay.time > 0 && (!best || replay.time < best)) { + best = unsigned(replay.time); + result.personal = laps; + } + } + } catch (const std::exception&) { + // An unavailable reference should leave a run playable. + } + const auto catalogue = dkr::store::service().view()->speedrun_catalogue; + if (catalogue) { + const auto rows = catalogue->find(course ? "vanillaTracks" : "customTracks"); + if (rows != catalogue->end() && rows->is_array()) { + const auto row = + std::ranges::find_if(*rows, [&](const auto& item) { return StoreText(item, "id", 96) == id; }); + if (row != rows->end()) { + const auto leaders = row->find("leaders"); + if (leaders != row->end() && leaders->is_object()) { + const auto standings = leaders->find(trial::kVehicleIds[static_cast(vehicle)]); + if (standings != leaders->end() && standings->is_object()) { + const auto lap = standings->find("lap"); + if (lap != standings->end()) + result.world_best_lap = unsigned(LeaderboardNumber(*lap, "ticks")); + } + } + } + } + } + return {result, best}; +} + +AdventureReference ReadAdventureReference(const dkr::store::Json& run) { + AdventureReference reference; + const auto splits = run.find("splits"); + if (splits == run.end() || !splits->is_array() || splits->size() > 64) + return reference; + for (const auto& split : *splits) { + if (split.is_array() && split.size() == 2 && split[0].is_string() && split[1].is_number_integer()) { + const auto label = split[0].get(); + const auto ticks = split[1].get(); + if (label.size() <= 64 && ticks > 0 && ticks <= trial::kAdventureMaxUpdates * 2) + reference.try_emplace(label, ticks); + } + } + return reference; +} + +void DrawRunDelta(const char* label, std::int64_t actual, std::int64_t reference) { + if (!reference) + return; + const auto delta = actual - reference; + ImGui::SameLine(); + const auto colour = delta < 0 ? kOlGoText : delta > 0 ? kOlAmber : kOlSoft; + const bool words = RunPreference(RunOption::DeltaWords); + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(PaddockCol(colour)), "%s %s%s%s", label, + words ? "" + : delta < 0 ? "-" + : delta > 0 ? "+" + : "", + RunClock(std::abs(delta)).c_str(), + words ? delta < 0 ? " ahead" + : delta > 0 ? " behind" + : " even" + : ""); +} + +void DrawAdventureDelta(std::span splits) { + if (splits.empty()) + return; + const auto& split = splits.back(); + const auto comparison = RunPreference(RunOption::Comparison); + if (comparison < 2) { + const auto& reference = comparison == 0 ? g_adventure_pb_splits : g_adventure_record_splits; + if (const auto match = reference.find(split.label); match != reference.end()) + DrawRunDelta(comparison == 0 ? "PB" : "WR", split.clock, match->second); + } else if (comparison == 2) { + std::int64_t total = 0; + std::string previous; + for (const auto& stage : splits) { + const auto segment = g_adventure_segments.find({previous, std::string(stage.label)}); + if (segment == g_adventure_segments.end()) + return; + total += segment->second; + previous = stage.label; + } + DrawRunDelta("Best segments", split.clock, total); + } +} + +void DrawTimeTrialHud(bool video = false) { + g_split_bounds.reset(); + const auto state = trial::progress(); + const bool preparing = trial::preparing_ghost(); + if (!state.lap && !preparing && state.adventure == trial::Adventure::None) + return; + const bool splits = + video || (RunPreference(RunOption::Splits) && (!state.replay || RunPreference(RunOption::ReplaySplits))); + const bool gap = !video && state.ghost && RunPreference(RunOption::GhostGap) && state.ghost_gap.has_value(); + if (!preparing && !splits && !gap) + return; + const auto* viewport = ImGui::GetMainViewport(); + if (preparing) { + auto* draw = ImGui::GetBackgroundDrawList(); + draw->AddRectFilled(viewport->Pos, {viewport->Pos.x + viewport->Size.x, viewport->Pos.y + viewport->Size.y}, + IM_COL32(6, 18, 28, 240)); + } + const auto corner = RunOverlayCorner(*viewport, RunPreference(RunOption::SplitPosition)); + ImGui::SetNextWindowPos(video ? ImVec2{viewport->WorkPos.x + 16.F, viewport->WorkPos.y + 16.F} : corner.position, + ImGuiCond_Always, video ? ImVec2{} : corner.pivot); + if (video) + ImGui::SetNextWindowSizeConstraints({0.F, 0.F}, {viewport->WorkSize.x * .47F, viewport->WorkSize.y * .48F}); + const bool contrast = !video && RunPreference(RunOption::Contrast); + ImGui::SetNextWindowBgAlpha(video ? .78F : contrast ? 1.F : RunPreference(RunOption::Background) * .01F); + if (contrast) + ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(.025F, .055F, .085F, 1.F)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 9.F); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(12.F, 9.F)); + constexpr auto flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | + ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoSavedSettings; + if (ImGui::Begin("Time Trial HUD", nullptr, flags)) { + ImGui::SetWindowFontScale(video ? 1.F : std::array{.85F, 1.F, 1.24F}[RunPreference(RunOption::HudSize)]); + if (preparing) { + ImGui::TextUnformatted("Preparing ghost"); + if (state.finish_update) + ImGui::ProgressBar(float(state.updates) / float(state.finish_update), {205.F, 8.F}, ""); + ImGui::End(); + ImGui::PopStyleVar(2); + if (contrast) + ImGui::PopStyleColor(); + return; + } + if (gap) { + const auto delta = *state.ghost_gap; + const bool words = RunPreference(RunOption::DeltaWords); + ImGui::Text("Ghost %s%s%s", + words ? "" + : delta < 0 ? "-" + : delta > 0 ? "+" + : "", + RunClock(std::abs(delta)).c_str(), + words ? delta < 0 ? " ahead" + : delta > 0 ? " behind" + : " even" + : ""); + } + if (splits) { + const int detail = video ? 0 : RunPreference(RunOption::SplitDetail); + if (state.adventure != trial::Adventure::None) { + for (const auto& category : trial::kAdventureCategories) + if (category.goal == state.adventure) + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(PaddockCol(kOlAmber)), "%s", + category.title.data()); + } else { + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(PaddockCol(kOlAmber)), "%s | Lap %u / %u", + state.replay ? "Replay" + : state.ghost ? "Ghost Race" + : "Time Trial", + state.lap, state.lap_count); + } + const auto elapsed = + state.started ? (video ? LeaderboardTime(state.clock) : RunClock(state.clock)) : std::string("Ready"); + ImGui::TextUnformatted(elapsed.c_str()); + if (detail != 2 && state.adventure != trial::Adventure::None) { + const auto splits = trial::adventure_splits(); + if (!splits.empty()) + ImGui::Separator(); + if (video) { + for (const auto& split : std::span(splits).last(std::min(4, splits.size()))) { + const auto time = LeaderboardTime(split.clock); + ImGui::Text("%.*s %s", static_cast(split.label.size()), split.label.data(), time.c_str()); + } + } else { + const auto upcoming = trial::AdventureSplits::upcoming(state.adventure, splits); + const auto capacity = static_cast(std::clamp( + (viewport->WorkSize.y * .40F - 74.F) / ImGui::GetTextLineHeightWithSpacing(), 3.F, 30.F)); + const auto reserve = std::min({upcoming.size(), capacity - std::min(splits.size(), std::size_t{2}), + std::size_t(RunPreference(RunOption::Upcoming))}); + const auto recent = std::min(splits.size(), detail == 1 ? std::size_t{1} : capacity - reserve); + for (const auto& split : std::span(splits).last(recent)) { + const auto time = RunClock(split.clock); + ImGui::Text("%.*s %s", static_cast(split.label.size()), split.label.data(), time.c_str()); + if (!state.replay && &split == &splits.back()) + DrawAdventureDelta(splits); + } + if (reserve) { + ImGui::Separator(); + for (std::size_t row = 0; row < reserve; ++row) { + const auto stage = upcoming[row]; + if (row == 0) + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(PaddockCol(kOlAmber)), "Next %.*s", + int(stage.size()), stage.data()); + else + ImGui::TextDisabled("%.*s", int(stage.size()), stage.data()); + } + } + } + } + if (detail != 2 && state.recent_split && (video || RunPreference(RunOption::LapDelta))) { + ImGui::Text("Last lap %s", + (video ? LeaderboardTime(state.recent_split) : RunClock(state.recent_split)).c_str()); + if (!state.replay && state.completed_laps) { + const auto lap = state.completed_laps - 1; + switch (RunPreference(RunOption::Comparison)) { + case 0: + DrawRunDelta("PB", state.recent_split, g_run_lap_reference.personal[lap]); + break; + case 1: + DrawRunDelta("WR lap", state.recent_split, g_run_lap_reference.world_best_lap); + break; + case 2: + DrawRunDelta("Best lap", state.recent_split, g_run_lap_reference.best_segments[lap]); + break; + } + } + } + if (!video && detail != 2 && !state.finish_update && state.adventure == trial::Adventure::None && + state.lap <= state.lap_count) { + const auto next = std::max(1U, state.lap); + const auto rows = std::min(unsigned(RunPreference(RunOption::Upcoming)), state.lap_count + 1 - next); + for (unsigned step = 0; step < rows; ++step) + ImGui::TextDisabled( + "%s %s", step ? "Then" : "Next", + next + step == state.lap_count ? "Finish" : ("Lap " + std::to_string(next + step + 1)).c_str()); + } + if (state.finish_update && !state.replay && state.adventure == trial::Adventure::None) + ImGui::TextUnformatted("Recording the finish"); + if (!video && state.total_updates) + ImGui::ProgressBar(float(state.updates) / float(state.total_updates), {152.F, 8.F}, ""); + } + const auto pos = ImGui::GetWindowPos(), size = ImGui::GetWindowSize(); + g_split_bounds = ImVec4{pos.x, pos.y, pos.x + size.x, pos.y + size.y}; + } + ImGui::End(); + ImGui::PopStyleVar(2); + if (contrast) + ImGui::PopStyleColor(); +} + +bool g_theatre_controls = true; +bool g_theatre_inputs = false; +int g_theatre_controller_corner = -1; +std::atomic g_theatre_activity{}; + +void SeekReplaySeconds(int direction) { + const auto state = trial::progress(); + const auto transport = trial::theatre(); + const auto frame = transport.seeking ? transport.seek_to : state.updates; + const int step = speed::seek_seconds[RunPreference(RunOption::SeekStep)] * 30; + if (state.total_updates) + trial::theatre_seek(unsigned(std::clamp(int(frame) + direction * step, 1, int(state.total_updates)))); +} + +bool HandleTheatreInput(const SDL_Event& event) { + g_theatre_activity = SDL_GetTicks64(); + if (event.type == SDL_CONTROLLERBUTTONDOWN && event.cbutton.button == SDL_CONTROLLER_BUTTON_START) { + trial::theatre_play_pause(); + return true; + } + if (event.type != SDL_KEYDOWN || event.key.repeat) + return false; + switch (event.key.keysym.scancode) { + case SDL_SCANCODE_ESCAPE: + case SDL_SCANCODE_SPACE: + trial::theatre_play_pause(); + return true; + case SDL_SCANCODE_F8: + g_theatre_controls = !g_theatre_controls; + return true; + case SDL_SCANCODE_COMMA: + trial::theatre_step(-1); + return true; + case SDL_SCANCODE_PERIOD: + trial::theatre_step(1); + return true; + case SDL_SCANCODE_LEFT: + case SDL_SCANCODE_RIGHT: + if (event.key.keysym.mod & KMOD_CTRL) { + SeekReplaySeconds(event.key.keysym.scancode == SDL_SCANCODE_LEFT ? -1 : 1); + return true; + } + return false; + default: + return false; + } +} + +void PaintReplayController(ImDrawList* draw, ImVec2 base, const trial::Progress& state, float scale) { + const auto point = [&](float x, float y) { return ImVec2{base.x + x * scale, base.y + y * scale}; }; + const auto shell = PaddockCol(0xA2B0C7); + draw->AddRectFilled(point(9, 15), point(223, 76), shell, 29.F * scale); + draw->AddQuadFilled(point(12, 43), point(63, 57), point(48, 121), point(19, 116), shell); + draw->AddQuadFilled(point(91, 57), point(141, 57), point(134, 136), point(98, 136), shell); + draw->AddQuadFilled(point(172, 57), point(221, 43), point(213, 117), point(185, 120), shell); + const auto button = [&](const char* label, float x, float y, float radius, unsigned bit, unsigned color) { + const bool pressed = (state.buttons & bit) != 0; + draw->AddCircleFilled(point(x, y), radius * scale, PaddockCol(color)); + if (pressed) + draw->AddCircle(point(x, y), (radius + 2.F) * scale, PaddockCol(0xFFF0B0), 20, 2.6F * scale); + const auto size = ImGui::CalcTextSize(label); + draw->AddText(ImGui::GetFont(), ImGui::GetFontSize() * scale, point(x - size.x * .5F, y - size.y * .5F), + PaddockCol(0x102033), label); + }; + button("L", 40, 17, 10, 0x0020, 0xC4CFDD); + button("R", 187, 17, 10, 0x0010, 0xC4CFDD); + button("Z", 202, 101, 10, 0x2000, 0xC4CFDD); + button("A", 155, 60, 12, 0x8000, 0x5191F4); + button("B", 142, 41, 10, 0x4000, 0x5CD693); + button("", 115, 31, 6, 0x1000, 0xED6462); + button("", 184, 33, 6, 0x0008, 0xFFCD57); + button("", 173, 44, 6, 0x0002, 0xFFCD57); + button("", 195, 44, 6, 0x0001, 0xFFCD57); + button("", 184, 55, 6, 0x0004, 0xFFCD57); + const auto dpad = PaddockCol(0x344459); + draw->AddRectFilled(point(32, 53), point(63, 63), dpad); + draw->AddRectFilled(point(42, 43), point(53, 74), dpad); + const auto active = PaddockCol(0xFFF0B0); + if (state.buttons & 0x0800) + draw->AddRectFilled(point(42, 43), point(53, 53), active); + if (state.buttons & 0x0400) + draw->AddRectFilled(point(42, 63), point(53, 74), active); + if (state.buttons & 0x0200) + draw->AddRectFilled(point(32, 53), point(42, 63), active); + if (state.buttons & 0x0100) + draw->AddRectFilled(point(53, 53), point(63, 63), active); + draw->AddCircleFilled(point(115, 68), 20.F * scale, PaddockCol(0x64758E), 8); + const float x = 115.F + 12.F * std::clamp(float(state.stick_x) / 80.F, -1.F, 1.F); + const float y = 68.F - 12.F * std::clamp(float(state.stick_y) / 80.F, -1.F, 1.F); + draw->AddCircleFilled(point(x, y), 8.F * scale, PaddockCol(0xCED9E9)); + draw->AddCircle(point(x, y), 4.F * scale, PaddockCol(0x8999AF)); +} + +void DrawReplayController(const trial::Progress& state, float scale) { + PaintReplayController(ImGui::GetWindowDrawList(), ImGui::GetCursorScreenPos(), state, scale); + ImGui::Dummy({232.F * scale, 140.F * scale}); +} + +void DrawReplayInputViewer(const trial::Progress& state, bool video = false) { + if (!video && !g_theatre_inputs) + return; + const auto* view = ImGui::GetMainViewport(); + ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse; + if (video) { + if (state.adventure != trial::Adventure::None) { + // Full Game splits own the upper-left of the picture. Anchor the + // controls in the opposite corner with a bounded footprint. + ImGui::SetNextWindowPos( + {view->WorkPos.x + view->WorkSize.x - 16.F, view->WorkPos.y + view->WorkSize.y - 16.F}, + ImGuiCond_Always, {1.F, 1.F}); + ImGui::SetNextWindowSizeConstraints({0.F, 0.F}, {view->WorkSize.x * .47F, view->WorkSize.y * .43F}); + } else { + ImGui::SetNextWindowPos({view->WorkPos.x + 16.F, view->WorkPos.y + view->WorkSize.y * .43F}, + ImGuiCond_Always); + } + flags |= ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoSavedSettings; + } else { + const auto corner = RunPreference(RunOption::InputPosition); + auto anchor = RunOverlayCorner(*view, corner); + const auto scale = std::array{.78F, 1.F, 1.18F}[RunPreference(RunOption::InputSize)]; + const float height = 140.F * scale + 54.F; + const auto* existing = ImGui::FindWindowByName("Replay Controller"); + const auto intersects = [&](ImVec2 point, ImVec2 size) { + return g_split_bounds && point.x < g_split_bounds->z && point.x + size.x > g_split_bounds->x && + point.y < g_split_bounds->w && point.y + size.y > g_split_bounds->y; + }; + const auto space = ImVec2{232.F * scale + 28.F, height}; + const auto proposed = + ImVec2{anchor.position.x - anchor.pivot.x * space.x, anchor.position.y - anchor.pivot.y * space.y}; + const bool conflict = intersects(proposed, space); + if (conflict) { + anchor.position.y = anchor.pivot.y == 0.F ? g_split_bounds->w + 8.F : g_split_bounds->y - 8.F; + if (anchor.position.y - anchor.pivot.y * height < view->WorkPos.y || + anchor.position.y + (1.F - anchor.pivot.y) * height > view->WorkPos.y + view->WorkSize.y) + anchor = RunOverlayCorner(*view, corner ^ 1); + } + const bool reposition = + corner != g_theatre_controller_corner || (existing && intersects(existing->Pos, existing->Size)); + ImGui::SetNextWindowPos(anchor.position, reposition ? ImGuiCond_Always : ImGuiCond_FirstUseEver, anchor.pivot); + g_theatre_controller_corner = corner; + } + ImGui::SetNextWindowBgAlpha(!video && RunPreference(RunOption::Contrast) ? 1.F : .84F); + if (ImGui::Begin("Replay Controller", video ? nullptr : &g_theatre_inputs, flags)) + DrawReplayController(state, video ? .78F : std::array{.78F, 1.F, 1.18F}[RunPreference(RunOption::InputSize)]); + ImGui::End(); +} + +void DrawReplayTheatre() { + const auto state = trial::progress(); + if (!state.total_updates) + return; + auto transport = trial::theatre(); + // Let RT64 present through the launcher handoff before holding frame one. + if (transport.pause_on_open && !transport.buffering && state.updates) { + trial::theatre_complete_intro(); + transport = trial::theatre(); + } + const auto file = trial::watched_replay(); + const bool local = file.parent_path() == g_config_directory / "speedruns"; + if (local && g_refresh_replay_library && !DialogJobRunning()) + RefreshReplayLibrary(); + const auto* view = ImGui::GetMainViewport(); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 13.F); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {14.F, 13.F}); + if (transport.buffering) { + ImGui::SetNextWindowPos(view->GetCenter(), ImGuiCond_Always, {.5F, .5F}); + ImGui::SetNextWindowBgAlpha(.94F); + if (ImGui::Begin("Preparing replay", nullptr, + ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize)) { + const auto at = ImGui::GetCursorScreenPos(); + auto* draw = ImGui::GetWindowDrawList(); + const float phase = RunPreference(RunOption::ReducedMotion) ? 0.F : float(ImGui::GetTime() * 5.5); + draw->PathArcTo({at.x + 12.F, at.y + 12.F}, 9.F, phase, phase + 4.7F, 18); + draw->PathStroke(PaddockCol(kOlAmber), 0, 2.4F); + ImGui::Dummy({27.F, 24.F}); + ImGui::SameLine(); + ImGui::TextUnformatted("Preparing replay..."); + if (OlButton("Cancel", OlTone::Plain, 0.F, nullptr, 28.F)) + trial::theatre_exit(); + } + ImGui::End(); + ImGui::PopStyleVar(2); + return; + } + DrawReplayInputViewer(state); + constexpr const char* theatre_window = "Replay Theatre · F8 to show or hide"; + if (const auto* previous = ImGui::FindWindowByName(theatre_window)) { + const auto far_corner = ImVec2{previous->Pos.x + previous->Size.x, previous->Pos.y + previous->Size.y}; + if (ImGui::IsMouseHoveringRect(previous->Pos, far_corner)) + g_theatre_activity = SDL_GetTicks64(); + } + const bool auto_hidden = RunPreference(RunOption::PlaybackControls) && !transport.paused && !transport.seeking && + !transport.finished && SDL_GetTicks64() - g_theatre_activity.load() > 3000; + if (!g_theatre_controls || auto_hidden) { + ImGui::PopStyleVar(2); + return; + } + const float width = std::min(730.F, view->WorkSize.x - 24.F); + ImGui::SetNextWindowPos({view->WorkPos.x + view->WorkSize.x / 2.F, view->WorkPos.y + view->WorkSize.y - 14.F}, + ImGuiCond_FirstUseEver, {0.5F, 1.F}); + ImGui::SetNextWindowSize({width, 0.F}); + ImGui::SetNextWindowBgAlpha(.86F); + constexpr auto flags = ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize; + if (ImGui::Begin(theatre_window, &g_theatre_controls, flags)) { + static std::optional drag_target; + if (ImGui::IsWindowAppearing()) { + drag_target.reset(); + ImGui::SetWindowFocus(); + } + const auto time = RunClock(state.clock); + ImGui::Text("REPLAY THEATRE | %s", trial::kRacers[state.racer].name.data()); + ImGui::SameLine(); + ImGui::Text("%s | Frame %u / %u%s", time.c_str(), state.updates, state.total_updates, + transport.finished && !transport.seeking ? " | Finished" : ""); + if (local) { + const auto* replay = FindLocalReplay(file); + if (replay) { + DrawReplayResult(*replay); + DrawReplayPosting(*replay, ImGui::GetContentRegionAvail().x, true); + } + const bool posted = replay && !replay->posted_owner.empty() && replay->posted_owner == RankedRunsOwner(); + if (!posted && !g_time_trial_message.empty()) + OlParagraph(g_time_trial_message, 14.F, kOlSoft, ImGui::GetContentRegionAvail().x); + } + if (transport.seeking) { + ImGui::Text("Preparing frame %u | %s on arrival", transport.seek_to, + transport.paused ? "Pause" : "Play"); + ImGui::SameLine(); + if (OlButton("Cancel seek", OlTone::Plain, 0.F, nullptr, 28.F)) + trial::theatre_cancel_seek(); + } else if (transport.buffered < state.total_updates) { + ImGui::Text("Preparing replay %u / %u", transport.buffered, state.total_updates); + } else { + ImGui::TextUnformatted("Ready to seek"); + } + const unsigned first = 1, last = state.total_updates; + const unsigned destination = transport.seeking ? transport.seek_to : std::max(first, state.updates); + unsigned cursor = drag_target.value_or(destination); + ImGui::SetNextItemWidth(-1.F); + const bool changed = ImGui::SliderScalar("##replay-timeline", ImGuiDataType_U32, &cursor, &first, &last, "", + ImGuiSliderFlags_NoInput); + if (changed) { + drag_target = cursor; + trial::theatre_scrub(cursor); + } + if (!ImGui::IsItemActive() && drag_target) { + trial::theatre_seek(*drag_target); + drag_target.reset(); + } + const auto left = ImGui::GetItemRectMin(); + const auto right = ImGui::GetItemRectMax(); + if (transport.buffered > first && last > first) { + const auto x = left.x + (right.x - left.x) * float(transport.buffered - first) / float(last - first); + ImGui::GetWindowDrawList()->AddLine({left.x, right.y - 2.F}, {x, right.y - 2.F}, PaddockCol(kOlSoft), 2.F); + } + if (RunPreference(RunOption::LapMarkers) && last > 1) { + const auto marker = [&](unsigned frame) { + if (!frame || frame > last) + return; + const auto x = left.x + (right.x - left.x) * float(frame - 1) / float(last - 1); + ImGui::GetWindowDrawList()->AddLine({x, right.y - 3.F}, {x, right.y}, PaddockCol(kOlAmber), 2.F); + }; + if (state.adventure == trial::Adventure::None) { + for (const auto lap : std::span(state.lap_updates).first(state.lap_count)) + marker(lap); + } else { + for (const auto frame : trial::adventure_timeline_markers()) + marker(frame); + } + } + if (ImGui::IsItemActive() && drag_target) + ImGui::SetTooltip("Seek to frame %u", *drag_target); + { + if (OlButton("Start", OlTone::Plain, 0.F, nullptr, 32.F)) + trial::theatre_seek(1); + for (unsigned lap = 0; lap < state.lap_count && state.lap_updates[lap]; ++lap) { + ImGui::SameLine(); + const auto label = "Lap " + std::to_string(lap + 1); + if (OlButton(label.c_str(), OlTone::Plain, 0.F, nullptr, 32.F)) + trial::theatre_seek(state.lap_updates[lap]); + } + ImGui::SameLine(); + if (OlButton("Finish", OlTone::Plain, 0.F, nullptr, 32.F)) + trial::theatre_seek(state.finish_update); + const auto seconds = std::to_string(speed::seek_seconds[RunPreference(RunOption::SeekStep)]) + "s"; + ImGui::SameLine(); + if (OlButton(("-" + seconds).c_str(), OlTone::Plain, 0.F, nullptr, 32.F)) + SeekReplaySeconds(-1); + ImGui::SameLine(); + if (OlButton(("+" + seconds).c_str(), OlTone::Plain, 0.F, nullptr, 32.F)) + SeekReplaySeconds(1); + } + { + const char* action = transport.finished && !transport.seeking ? "Replay" + : transport.paused ? "Play" + : "Pause"; + if (OlButton(action, OlTone::Go, 0.F, nullptr, 32.F)) + trial::theatre_play_pause(); + const auto frame = transport.seeking ? transport.seek_to : state.updates; + ImGui::SameLine(); + { + const OlDisabled at_start(frame <= 1); + if (OlButton("-1 frame", OlTone::Plain, 0.F, nullptr, 32.F)) + trial::theatre_step(-1); + } + ImGui::SameLine(); + { + const OlDisabled at_end(!frame || frame == state.total_updates); + if (OlButton("+1 frame", OlTone::Plain, 0.F, nullptr, 32.F)) + trial::theatre_step(1); + } + } + if (width >= 630.F) + ImGui::SameLine(); + static const std::vector speeds{"0.5x", "1x", "1.5x", "2x"}; + const auto current = std::ranges::find(speed::playback_speeds, transport.speed); + int chosen = current == speed::playback_speeds.end() ? 1 : int(current - speed::playback_speeds.begin()); + if (SettingsDropdown("theatre-speed", {}, &chosen, speeds, 100.F, false, {}, 32.F)) + trial::theatre_speed(speed::playback_speeds[chosen]); + ImGui::SameLine(); + ImGui::Checkbox("Controller", &g_theatre_inputs); + ImGui::SameLine(); + if (OlButton("Exit", OlTone::Plain, 0.F, nullptr, 32.F)) + trial::theatre_exit(); + } + ImGui::End(); + ImGui::PopStyleVar(2); +} + +void DrawSpeedrunningRestartConfirmation() { + constexpr const char* title = "Restart this run?"; + if (!trial::restart_confirmation_pending() && !ImGui::IsPopupOpen(title)) + return; + if (trial::restart_confirmation_pending() && !ImGui::IsPopupOpen(title)) + ImGui::OpenPopup(title); + if (!BeginPaddedModal(title, ImGuiWindowFlags_AlwaysAutoResize)) + return; + if (!trial::restart_confirmation_pending()) { + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + return; + } + OlParagraph("The current attempt will be replaced.", 15.F, kOlInk, 330.F); + if (ImGui::IsWindowAppearing()) + ImGui::SetKeyboardFocusHere(); + if (OlButton("Keep racing")) { + trial::confirm_restart(false); + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (OlButton("Restart Run", OlTone::Go)) { + trial::confirm_restart(true); + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +enum class LeaderboardReplayAction { Watch, RaceGhost }; + +void WatchLeaderboardReplay(const std::string& id, bool own_run, + LeaderboardReplayAction action = LeaderboardReplayAction::Watch, + std::string ghost_name = {}) { + RankedJob([id, own_run, action, ghost_name = std::move(ghost_name), config = g_config_directory, + signed_in = !RankedRunsOwner().empty()] { + const auto directory = config / "speedrun-playback"; + CheckManagedReplayDirectory(directory); + std::filesystem::create_directories(directory); + const auto stamp = std::chrono::system_clock::now().time_since_epoch().count(); + const auto file = directory / (std::to_string(stamp) + ".dkrreplay"); + try { + dkr::store::service().save_ranked_replay(id, file, own_run); + auto request = action == LeaderboardReplayAction::RaceGhost + ? PrepareGhostRun(file, config, std::nullopt, signed_in) + : TimeTrialRequest{trial::Mode::Watch, file}; + request.ghost_name = ghost_name; + return [file, request = std::move(request), signed_in]() mutable { + DeleteRankedPlayback(std::exchange(g_ranked_playback_file, file)); + QueueTimeTrialRequest(std::move(request), signed_in); + }; + } catch (...) { + DeleteRankedPlayback(file); + throw; + } + }); +} + +void DrawSubmissionLimit(float width, const dkr::store::Json* catalogue) { + if (!catalogue) + return; + const auto limit = catalogue->find("submissionLimit"); + if (limit == catalogue->end() || !limit->is_object()) + return; + const auto runs = LeaderboardNumber(*limit, "maxRuns"); + const auto hours = LeaderboardNumber(*limit, "windowHours"); + if (runs > 0 && hours > 0) + OlParagraph("You can post up to " + std::to_string(runs) + " runs. Each submission counts for " + + std::to_string(hours) + " hours, including after approval.", + 15.F, kOlSoft, width); +} + +void DrawLocalReplays(float width, const dkr::store::Json* catalogue) { + static char search[121]{}; + static char title[121]{}; + static int filter = 0; + static std::filesystem::path selected; + static std::string selected_title; + static bool purge_bests = false; + static bool purge_unsubmitted = false; + const bool can_watch = CanLaunchLeaderboardReplay(); + if (g_replay_library_profile != g_config_directory) + g_local_replays.clear(); + if (g_refresh_replay_library && !DialogJobRunning()) + RefreshReplayLibrary(); + + DrawOlFeature(width, "My Replays", nullptr, [&](float inner) { + DrawSubmissionLimit(inner, catalogue); + if (OlButton("Refresh replays")) { + g_refresh_replay_library = true; + g_published_replay_times = {}; + } + ImGui::SameLine(); + { + const OlDisabled busy(g_local_replays.empty() || DialogJobRunning()); + if (OlButton("Purge replays")) { + purge_bests = false; + purge_unsubmitted = false; + ImGui::OpenPopup("Purge stored replays?"); + } + } + if (ImGui::BeginPopupModal("Purge stored replays?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + OlParagraph("Permanently remove local copies from this device. Leaderboard submissions stay online.", 15.F, + kOlInk, 340.F); + ImGui::Checkbox("Include personal bests", &purge_bests); + ImGui::Checkbox("Include runs I haven't posted", &purge_unsubmitted); + const auto count = std::ranges::count_if(g_local_replays, [&](const auto& replay) { + return dkr::library_ui::can_purge_replay(replay.personal_best, !replay.posted_owner.empty(), + purge_bests, purge_unsubmitted); + }); + OlParagraph(count ? std::to_string(count) + + (count == 1 ? " replay will be removed." : " replays will be removed.") + : "No replays match these choices.", + 15.F, kOlSoft, 340.F); + if (OlButton("Cancel")) + ImGui::CloseCurrentPopup(); + ImGui::SetItemDefaultFocus(); + ImGui::SameLine(); + { + const OlDisabled unavailable(count == 0 || DialogJobRunning()); + if (OlButton("Purge selected replays", OlTone::Danger)) { + RankedJob([profile = g_config_directory, + chosen = SelectReplayPurge(g_local_replays, purge_bests, purge_unsubmitted), + bests = purge_bests, unsubmitted = purge_unsubmitted] { + const auto [removed, skipped] = + PurgeLocalReplays(profile / "speedruns", chosen, bests, unsubmitted); + return [profile, removed, skipped] { + if (profile != g_config_directory) + return; + g_refresh_replay_library = true; + g_time_trial_message = + "Removed " + std::to_string(removed) + (removed == 1 ? " replay." : " replays."); + if (skipped) + g_time_trial_message += + " Skipped " + std::to_string(skipped) + " changed or unavailable."; + }; + }); + ImGui::CloseCurrentPopup(); + } + } + ImGui::EndPopup(); + } + PaddockGap(8.F); + ImGui::BeginGroup(); + const float search_width = std::min(300.F, inner); + SettingsLabel("Search replays", search_width); + OlInputOptions options; + options.hint = "Track, racer or title"; + options.height = kSettingsDropdownHeight; + if (OlInput("##find-replay", nullptr, search, sizeof(search), search_width, options) == + OlInputResult::Gamepad) { + RequestCustomTextKeyboard( + "Search replays", search, sizeof(search), + [](const std::string& text) { std::snprintf(search, sizeof(search), "%s", text.c_str()); }, true); + } + ImGui::EndGroup(); + if (inner >= 540.F) + ImGui::SameLine(); + ImGui::BeginGroup(); + SettingsDropdown("replay-type", "Replay type", &filter, {"All replays", "Local runs", "Leaderboard runs"}, + std::min(226.F, inner)); + ImGui::EndGroup(); + + const auto needle = dkr::runtime::texture_browser::lower_ascii(search); + bool rename = false, remove = false; + unsigned matches = 0; + std::vector ordered; + ordered.reserve(g_local_replays.size()); + for (const auto& replay : g_local_replays) + ordered.push_back(&replay); + switch (RunPreference(RunOption::ReplaySort)) { + case 1: + std::ranges::stable_sort(ordered, std::greater{}, &LocalReplay::personal_best); + break; + case 2: + std::ranges::stable_sort(ordered, {}, &LocalReplay::course); + break; + } + for (const auto* record : ordered) { + const auto& replay = *record; + const std::string kind = replay.has_attempt ? "Leaderboard run" : "Local run"; + if ((filter == 1 && replay.has_attempt) || (filter == 2 && !replay.has_attempt)) + continue; + const auto haystack = replay.title + " " + replay.course + " " + replay.racer + " " + replay.vehicle + " " + + PathUtf8(replay.file.filename()); + if (dkr::runtime::texture_browser::lower_ascii(haystack).find(needle) == std::string::npos) + continue; + ++matches; + const auto id = PathUtf8(replay.file.filename()); + ImGui::PushID(id.c_str()); + const ImVec2 divider = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled(divider, {divider.x + inner, divider.y + 1.F}, + ImGui::GetColorU32(ImGuiCol_Separator)); + ImGui::Dummy({inner, 1.F}); + const bool side_by_side = inner >= 755.F; + ImGui::BeginGroup(); + const float details_width = side_by_side ? inner - 415.F : inner; + OlParagraph(replay.title, 19.F, kOlInk, details_width); + if (replay.valid) { + std::string details; + const auto append = [&](const std::string& part) { + if (!part.empty()) { + if (!details.empty()) + details += " | "; + details += part; + } + }; + if (replay.title != replay.course) + append(replay.course); + append(replay.vehicle); + append(replay.racer); + append(kind); + const auto saved = ReplayDate(replay.saved); + if (!saved.empty()) + append("Saved " + saved); + OlParagraph(details, 15.F, kOlSoft, details_width); + OlParagraph("Finish " + LeaderboardTime(replay.time) + + (replay.best_lap ? " | Best lap " + LeaderboardTime(replay.best_lap) : ""), + 15.F, kOlInk, details_width); + DrawReplayResult(replay); + DrawReplayPosting(replay, details_width); + } else { + OlParagraph("Unsupported or incomplete replay", 15.F, kOlSoft, details_width); + } + ImGui::EndGroup(); + if (side_by_side) + ImGui::SameLine(inner - 392.F); + { + const OlDisabled busy(!replay.valid || !can_watch || DialogJobRunning()); + if (OlButton("Watch")) + g_time_trial_request = TimeTrialRequest{trial::Mode::Watch, replay.file}; + } + if (replay.can_ghost) { + ImGui::SameLine(); + const OlDisabled busy(!can_watch || DialogJobRunning()); + if (OlButton("Race Ghost")) + RaceReplayGhost(replay.file); + } + ImGui::SameLine(); + const OlDisabled busy(DialogJobRunning()); + if (OlButton("Rename")) { + selected = replay.file; + selected_title = replay.title; + std::snprintf(title, sizeof(title), "%s", replay.title.c_str()); + rename = true; + } + ImGui::SameLine(); + if (OlButton("Remove")) { + selected = replay.file; + selected_title = replay.title; + remove = true; + } + ImGui::PopID(); + } + if (!matches) + OlParagraph(g_local_replays.empty() ? "Recorded runs and downloaded replays will appear here." + : "No replays match your filters.", + 15.F, kOlSoft, inner); + if (rename) + ImGui::OpenPopup("Rename replay"); + if (remove) + ImGui::OpenPopup("Remove local copy?"); + if (ImGui::BeginPopupModal("Rename replay", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (OlInput("##replay-name", "Display title", title, sizeof(title), 310.F, {}) == OlInputResult::Gamepad) + RequestCustomTextKeyboard( + "Display title", title, sizeof(title), + [](const std::string& text) { std::snprintf(title, sizeof(title), "%s", text.c_str()); }, true); + const std::string name = title; + { + const OlDisabled disabled(name.find_first_not_of(" \t\r\n") == std::string::npos); + if (OlButton("Save name", OlTone::Go)) { + RankedJob([file = selected, name] { + RenameLocalReplay(file, name); + return [] { g_refresh_replay_library = true; }; + }); + ImGui::CloseCurrentPopup(); + } + } + ImGui::SameLine(); + if (OlButton("Cancel")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + if (ImGui::BeginPopupModal("Remove local copy?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + OlParagraph(selected_title, 17.F, kOlInk, 320.F); + if (OlButton("Cancel")) + ImGui::CloseCurrentPopup(); + ImGui::SetItemDefaultFocus(); + ImGui::SameLine(); + if (OlButton("Remove local copy")) { + RankedJob([file = selected] { + RemoveLocalReplay(file); + return [] { g_refresh_replay_library = true; }; + }); + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); + } + }); +} + +using TrackQuery = dkr::store::LeaderboardTrackQuery; +std::string g_track_return_focus; + +void DrawAdventureBoards(float width, const dkr::store::Json* catalogue, TrackQuery& query); +std::function DrawPracticeAdventure(float width, const dkr::store::Json* catalogue, bool signed_in); + +void DrawLatestRecording(float width) { + const auto result = trial::last_result(); + if (result.replay || result.message.empty()) + return; + DrawOlFeature(width, "Last run", nullptr, [&](float inner) { + OlParagraph(result.message, 15.F, kOlSoft, inner); + if (!result.complete) + return; + if (RunPreference(RunOption::FinishSummary)) + OlParagraph("Finish " + LeaderboardTime(result.clock) + + (result.best_lap ? " | Best lap " + LeaderboardTime(result.best_lap) : ""), + 16.F, kOlInk, inner); + if (const auto* replay = FindLocalReplay(result.file)) { + DrawReplayResult(*replay); + if (RunPreference(RunOption::PostPrompt)) + DrawReplayPosting(*replay, inner, true); + const OlDisabled busy(!CanLaunchLeaderboardReplay() || DialogJobRunning()); + if (OlButton("Watch Replay")) + g_time_trial_request = TimeTrialRequest{trial::Mode::Watch, result.file}; + } + }); + PaddockGap(8.F); +} + +void StartTrackRun(std::string id, const trial::Course* course, trial::Vehicle vehicle, unsigned racer, + std::string board, bool signed_in) { + RankedJob( + [id = std::move(id), course, vehicle, racer, board = std::move(board), signed_in, config = g_config_directory] { + auto request = TimeTrialRequest{trial::Mode::Record, NewTimeTrialFile(config, id + "-Practice")}; + request.attempt = RequestTrackAttempt(board, id, course, vehicle, racer); + request.racer = racer; + request.vehicle = vehicle; + if (course) + request.course = course; + else + request.track = id; + std::tie(request.lap_reference, request.prior_best) = + ReadRunReference(config / "speedruns", id, course, vehicle, racer, + request.attempt ? std::string_view(request.attempt->track_hash) : std::string_view{}); + return [request = std::move(request), signed_in]() mutable { + QueueTimeTrialRequest(std::move(request), signed_in); + }; + }); +} + +struct SpeedrunningSetup { + std::array courses; + std::array vehicles{}; + unsigned racer = trial::kDiddy; + int challenge = 0; +}; +SpeedrunningSetup g_run_setup; +std::filesystem::path g_run_setup_profile; + +void LoadSpeedrunningSetup() { + if (g_run_setup_profile == g_config_directory) + return; + g_run_setup_profile = g_config_directory; + g_run_setup = {}; + if (!RunPreference(RunOption::RememberSetup)) + return; + try { + const auto file = g_config_directory / "speedrunning-setup.json"; + const auto saved = dkr::store::Json::parse(dkr::updates::read_text(file, 4096)); + for (unsigned i = 0; i < 2; ++i) { + g_run_setup.courses[i] = StoreText(saved, i ? "custom" : "vanilla", 128); + g_run_setup.vehicles[i] = + std::min(2U, unsigned(LeaderboardNumber(saved, i ? "customVehicle" : "vanillaVehicle"))); + } + if (saved.contains("racer")) + g_run_setup.racer = + std::min(unsigned(trial::kRacers.size() - 1), unsigned(LeaderboardNumber(saved, "racer"))); + g_run_setup.challenge = int(LeaderboardNumber(saved, "challenge")); + } catch (const std::exception&) { + // Older profiles start with the existing default selections. + } +} + +void SaveSpeedrunningSetup() { + if (!RunPreference(RunOption::RememberSetup)) + return; + const dkr::store::Json setup{{"vanilla", g_run_setup.courses[0]}, + {"custom", g_run_setup.courses[1]}, + {"vanillaVehicle", g_run_setup.vehicles[0]}, + {"customVehicle", g_run_setup.vehicles[1]}, + {"racer", g_run_setup.racer}, + {"challenge", g_run_setup.challenge}}; + try { + dkr::updates::durable_write(g_config_directory / "speedrunning-setup.json", setup.dump()); + } catch (const std::exception&) { + std::fprintf(stderr, "[speedrunning] Could not save run setup.\n"); + } +} + +std::function DrawPracticeTracks(float width, const dkr::store::Json* catalogue, bool custom, bool signed_in) { + using dkr::runtime::custom_tracks::ReplayTrack; + static const auto vanilla = [] { + std::vector choices; + for (const auto& course : trial::kCourses) + choices.push_back({std::string(course.id), std::string(course.name), course.vehicles}); + return choices; + }(); + OlHeading(custom ? "Custom Tracks" : "Vanilla Tracks", width < 275.F ? 19.F : 24.F, kOlCream, width); + const auto installed = custom ? dkr::runtime::custom_tracks::installed_replay_tracks() : std::vector{}; + const auto& tracks = custom ? installed : vanilla; + if (tracks.empty()) { + OlParagraph("Install a compatible .dkrmap track to practise here.", 15.F, kOlSoft, width); + return {}; + } + auto& selected = g_run_setup.courses; + auto& vehicle = g_run_setup.vehicles[custom]; + auto& racer = g_run_setup.racer; + const auto current = std::ranges::find(tracks, selected[custom], &ReplayTrack::id); + int course_index = current == tracks.end() ? 0 : static_cast(current - tracks.begin()); + std::vector courses; + courses.reserve(tracks.size()); + for (const auto& track : tracks) + courses.emplace_back(track.name); + SettingsDropdown("run-course", "Course", &course_index, courses, std::min(360.F, width)); + const auto* track = &tracks[static_cast(course_index)]; + selected[custom] = track->id; + + std::vector vehicle_names; + std::vector available_vehicles; + int vehicle_index = 0; + for (unsigned i = 0; i < trial::kVehicleNames.size(); ++i) { + if (!(track->vehicles & (1U << i))) + continue; + if (i == vehicle) + vehicle_index = static_cast(available_vehicles.size()); + available_vehicles.push_back(i); + vehicle_names.emplace_back(std::string(dkr::localisation::source(trial::kVehicleNames[i]))); + } + SettingsDropdown("run-vehicle", "Vehicle", &vehicle_index, vehicle_names, std::min(360.F, width)); + vehicle = available_vehicles[static_cast(vehicle_index)]; + + static const auto racers = [] { + std::vector choices; + choices.reserve(trial::kRacers.size()); + for (const auto& entry : trial::kRacers) + choices.emplace_back(std::string(entry.name)); + return choices; + }(); + int racer_index = static_cast(racer); + SettingsDropdown("run-racer", "Racer", &racer_index, racers, std::min(360.F, width)); + racer = static_cast(racer_index); + const auto choice = static_cast(vehicle); + const auto* course = custom ? nullptr : trial::course_for(track->id); + auto board = signed_in ? TrackAttemptBoard(catalogue, track->id, course, choice, racer) : std::string{}; + return [id = track->id, course, choice, racer, board = std::move(board), signed_in] { + StartTrackRun(id, course, choice, racer, board, signed_in); + }; +} + +void DrawLeaderboardPractice(float width, const dkr::store::Json* catalogue) { + LoadSpeedrunningSetup(); + if (g_refresh_replay_library && !DialogJobRunning()) + RefreshReplayLibrary(); + DrawLatestRecording(width); + const bool ready = CanLaunchLeaderboardReplay(); + const bool can_launch = ready && !g_leaderboard_layout_check; + const bool signed_in = !RankedRunsOwner().empty(); + if (!ready) + OlParagraph("Select a US v1.0 or US v1.1 ROM in Play and leave any active lobby.", 15.F, kOlSoft, width); + constexpr float gap = 12.F; + constexpr float minimum_card = 242.F; + const bool row = width >= 3.F * minimum_card + 2.F * gap; + const float card = row ? std::floor((width - 2.F * gap) / 3.F) : width; + const auto draw_card = [&](int section) { + ImGui::PushID(section); + DrawOlCard( + card, OlPanelLook{}, + [&](float inner) { + const auto start = section == 2 ? DrawPracticeAdventure(inner, catalogue, signed_in) + : DrawPracticeTracks(inner, catalogue, section == 1, signed_in); + if (start) { + PaddockGap(6.F); + const OlDisabled busy(!can_launch || DialogJobRunning()); + if (OlButton("Start Run", OlTone::Go)) { + SaveSpeedrunningSetup(); + start(); + } + } + }, + 14.F); + ImGui::PopID(); + }; + if (row) { + const auto origin = ImGui::GetCursorScreenPos(); + float bottom = origin.y; + { + OlEqualProfileRow equal; + for (int section = 0; section < 3; ++section) { + ImGui::SetCursorScreenPos({origin.x + section * (card + gap), origin.y}); + equal.capture_next = true; + draw_card(section); + bottom = std::max(bottom, ImGui::GetItemRectMax().y); + } + } + ImGui::SetCursorScreenPos(origin); + ImGui::Dummy({width, bottom - origin.y}); + } else { + for (int section = 0; section < 3; ++section) { + if (section) + PaddockGap(gap); + draw_card(section); + } + } +} + +using LeaderboardChoices = std::vector>; + +std::string LeaderboardVehicle(std::string_view id) { + const auto vehicle = std::find(trial::kVehicleIds.begin(), trial::kVehicleIds.end(), id); + return vehicle == trial::kVehicleIds.end() + ? std::string(id) + : std::string(trial::kVehicleNames[vehicle - trial::kVehicleIds.begin()]); +} + +bool LeaderboardFilter(const char* label, const LeaderboardChoices& choices, std::string& value, float width) { + const auto selected = + std::find_if(choices.begin(), choices.end(), [&](const auto& entry) { return entry.first == value; }); + if (choices.empty()) + return false; + std::vector names; + names.reserve(choices.size()); + for (const auto& entry : choices) + names.emplace_back(std::string(dkr::localisation::source(entry.second))); + int index = selected == choices.end() ? 0 : static_cast(selected - choices.begin()); + ImGui::BeginGroup(); + const bool changed = SettingsDropdown(label, label, &index, names, width); + ImGui::EndGroup(); + if (changed) + value = choices[static_cast(index)].first; + return changed; +} + +bool CanLaunchLeaderboardReplay() { + return g_launcher_rom && !dkr::runtime::netplay::session().active() && !g_time_trial_request; +} + +void DrawLeaderboardRankRow(float width, const dkr::store::Json& entry, bool full_game) { + const auto place = LeaderboardNumber(entry, "place"); + const auto id = StoreText(entry, "id", 96); + const auto time = LeaderboardTime(LeaderboardNumber(entry, "ticks")); + const auto name = StoreText(entry, "name", 60); + const auto racer = StoreText(entry, "racer", 50); + constexpr float gap = 8.F; + constexpr float rank_width = 56.F; + constexpr float time_width = 97.F; + const float watch_width = OlButtonWidth("Watch"); + const float ghost_width = full_game ? 0.F : OlButtonWidth("Race Ghost", OlTone::Go); + const float actions_width = watch_width + (full_game ? 0.F : ghost_width + gap); + OlPanelLook look; + look.fill = place == 1 ? 0x143446 : 0x102D3E; + look.ring = place == 1 ? 0x947445 : kOlRing; + look.ring_width = 1.F; + look.radii = PaddockRound(9.F); + + ImGui::PushID(id.c_str()); + DrawOlCard( + width, look, + [&](float inner) { + const bool inline_actions = !id.empty() && inner >= rank_width + time_width + actions_width + 168.F; + const float time_right = inline_actions ? inner - actions_width - 20.F : inner; + const float time_left = time_right - time_width; + const ImVec2 start = ImGui::GetCursorScreenPos(); + const float badge_width = rank_width - gap; + PaddockFill(ImGui::GetWindowDrawList(), {start.x, start.y + 5.F}, {start.x + badge_width, start.y + 33.F}, + PaddockRound(6.F), PaddockCol(place == 1 ? 0x45371D : 0x1A4054)); + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 7.F); + OlParagraph("#" + std::to_string(place), 15.F, place == 1 ? kOlAmber : kOlInk, badge_width, true, 1.4F, + true); + + ImGui::SameLine(0.F, gap); + ImGui::SetCursorScreenPos({start.x + rank_width, start.y}); + ImGui::BeginGroup(); + const float name_width = std::max(1.F, time_left - rank_width - gap); + OlParagraph(name, 16.F, kOlInk, name_width, true, 1.3F); + if (!racer.empty()) + OlParagraph(racer, 14.F, kOlSoft, name_width, false, 1.25F); + ImGui::EndGroup(); + + ImGui::SameLine(); + ImGui::SetCursorScreenPos({start.x + time_left, start.y + 7.F}); + OlParagraph(time, 18.F, kOlCream, time_width, true, 1.3F); + if (id.empty()) + return; + + if (inline_actions) { + ImGui::SameLine(); + ImGui::SetCursorScreenPos({start.x + inner - actions_width, start.y + 7.F}); + } else { + PaddockGap(3.F); + } + const OlDisabled launch(DialogJobRunning() || !CanLaunchLeaderboardReplay()); + if (!full_game) { + if (OlButton("Race Ghost", OlTone::Go)) + WatchLeaderboardReplay(id, false, LeaderboardReplayAction::RaceGhost, name); + if (inner >= actions_width) + ImGui::SameLine(0.F, gap); + } + if (OlButton("Watch")) + WatchLeaderboardReplay(id, false); + }, + 11.F); + ImGui::PopID(); +} + +#include "leaderboard_rankings.inl" + +void DrawLeaderboardRanking(float width, const dkr::store::Json& ranking, TrackQuery& query) { + const auto& event = ranking["track"]; + DrawOlFeature(width, StoreText(event, "title", 120).c_str(), nullptr, [&](float inner) { + const auto detail = StoreText(event, query.custom ? "version" : "world", 80); + if (!detail.empty()) + OlParagraph(detail, 15.F, kOlSoft, inner); + PaddockGap(8.F); + auto& service = dkr::store::service(); + const OlDisabled loading(service.view()->speedrun_loading); + auto next = query; + next.offset = 0; + next.vehicle = StoreText(ranking, "vehicle", 24); + next.racer = StoreText(ranking, "racer", 96); + next.best_lap = StoreText(ranking, "score", 6) == "lap"; + LeaderboardChoices vehicles, racers{{"", "All racers"}}; + for (const auto& vehicle : ranking["vehicles"]) { + const auto id = vehicle.get(); + vehicles.emplace_back(id, LeaderboardVehicle(id)); + } + for (const auto& racer : ranking["racers"]) + racers.emplace_back(StoreText(racer, "id", 96), StoreText(racer, "name", 40)); + bool filters_changed = false; + if (!query.full_game) { + const float filter_width = std::min(220.F, inner); + filters_changed = LeaderboardFilter("Racer", racers, next.racer, filter_width); + if (!vehicles.empty()) { + if (2 * filter_width + ImGui::GetStyle().ItemSpacing.x <= inner) + ImGui::SameLine(); + if (LeaderboardFilter("Vehicle", vehicles, next.vehicle, filter_width)) { + next.racer.clear(); + filters_changed = true; + } + } + PaddockGap(8.F); + for (const bool lap : {false, true}) { + if (lap) + ImGui::SameLine(); + if (OlButton(lap ? "Best lap" : "Full race", next.best_lap == lap ? OlTone::Go : OlTone::Plain) && + next.best_lap != lap) { + next.best_lap = lap; + filters_changed = true; + } + } + } + if (filters_changed) { + query = next; + service.load_leaderboards({}, query); + return; + } + PaddockGap(8.F); + const auto& entries = ranking["entries"]; + if (entries.empty()) { + OlParagraph(ranking.value("ranked", false) ? "No verified runs have been published for this selection." + : "This track and vehicle are awaiting replay qualification.", + 15.F, kOlSoft, inner); + } else { + for (const auto& entry : entries) { + DrawLeaderboardRankRow(inner, entry, query.full_game); + PaddockGap(6.F); + } + } + if (const auto offset = LeaderboardNumber(ranking, "nextOffset"); offset && OlButton("More times")) { + next.offset = static_cast(offset); + service.load_leaderboards({}, next); + } + if (const auto history = ranking.find("history"); history != ranking.end() && history->is_object()) { + PaddockGap(10.F); + DrawTrackRecordHistory( + inner, *history, query.id + "/" + next.vehicle + "/" + next.racer + (next.best_lap ? "/lap" : "/race")); + } + }); + PaddockGap(12.F); +} + +void RefreshLeaderboardRuns(bool review) { + RankedJob([review, owner = RankedRunsOwner()] { + auto reply = dkr::store::service().ranked_runs(review); + const auto received = std::chrono::steady_clock::now(); + return [reply = std::move(reply), owner, received, review] { + if (owner == RankedRunsOwner()) { + g_ranked_runs_owner = owner; + g_ranked_runs_review = review; + g_ranked_runs = std::move(reply); + g_ranked_runs_received = received; + } + }; + }); +} + +#include "submitted_runs.inl" + +void DrawLeaderboardRuns(float width, bool review) { + if (!review) { + DrawSubmittedRuns(width); + return; + } + static std::string selected; + static char reason[601]{}; + DrawOlFeature(width, "Review Runs", nullptr, [&](float inner) { + const auto owner = RankedRunsOwner(); + const OlDisabled busy(DialogJobRunning()); + if (owner.empty()) { + OlParagraph("Sign in with Discord to see your submitted runs.", 15.F, kOlSoft, inner); + if (OlButton("Sign in with Discord", OlTone::Go)) + dkr::store::service().login(); + return; + } + const bool loaded = g_ranked_runs_owner == owner && g_ranked_runs_review && g_ranked_runs.contains("runs"); + if (!loaded) { + OlParagraph("Use Refresh to check for runs.", 15.F, kOlSoft, inner); + return; + } + if (g_ranked_runs["runs"].empty()) + OlParagraph("No verified runs are awaiting review.", 15.F, kOlSoft, inner); + for (const auto& run : g_ranked_runs["runs"]) { + const auto id = StoreText(run, "id", 96); + const auto state = StoreText(run, "state", 24); + const auto ticks = LeaderboardNumber(run, "ticks"); + if (id.empty()) + continue; + ImGui::PushID(id.c_str()); + PaddockGap(8.F); + OlParagraph(StoreText(run, "title", 100) + " | " + StoreText(run, "name", 60) + " | " + state + + (ticks ? " | " + LeaderboardTime(ticks) : ""), + 16.F, kOlInk, inner); + if (run.value("linkedLocal", false)) + OlParagraph("Linked local run", 14.F, kOlSoft, inner); + for (const char* field : {"notes", "reason"}) + if (const auto value = StoreText(run, field, 600); !value.empty()) + OlParagraph(value, 14.F, kOlSoft, inner); + if (state != "uploading") { + { + const OlDisabled launch(!CanLaunchLeaderboardReplay()); + if (OlButton("Watch replay")) + WatchLeaderboardReplay(id, true); + } + } + if (state == "verified") { + ImGui::SameLine(); + if (OlButton("Review") && selected != id) { + selected = id; + reason[0] = '\0'; + } + if (selected == id) { + if (run.value("videoRequired", false) && StoreText(run, "videoState", 24) != "ready") + OlParagraph("You can review the replay here while the website video is being prepared.", 14.F, + kOlSoft, inner); + OlInputOptions options; + options.hint = "Review note"; + if (OlInput("##review-note", nullptr, reason, sizeof(reason), std::min(430.F, inner), options) == + OlInputResult::Gamepad) { + RequestCustomTextKeyboard( + "Review note", reason, sizeof(reason), + [id](const std::string& text) { + if (selected == id) + std::snprintf(reason, sizeof(reason), "%s", text.c_str()); + }, + true); + } + const auto submit = [&](bool publish) { + RankedJob([id, publish, note = std::string(reason), owner = RankedRunsOwner()] { + dkr::store::service().review_ranked_run(id, publish, note); + auto rows = dkr::store::service().ranked_runs(true); + return [owner, rows = std::move(rows)] { + if (owner == RankedRunsOwner()) { + g_ranked_runs_review = true; + g_ranked_runs = std::move(rows); + g_time_trial_message = "Review saved."; + } + }; + }); + selected.clear(); + }; + if (OlButton("Publish", OlTone::Go)) + submit(true); + ImGui::SameLine(); + const OlDisabled no_note(reason[0] == '\0'); + if (OlButton("Reject")) + submit(false); + } + } + ImGui::PopID(); + } + }); +} + +const dkr::store::Snapshot& LeaderboardLayoutFixture() { + using Json = dkr::store::Json; + static const auto fixture = [] { + dkr::store::Snapshot value; + value.speedrun_catalogue = std::make_shared(Json::parse(R"json({ + "vanillaTracks":[ + {"id":"ancient-lake","title":"Ancient Lake","world":"Dino Domain","vehicles":["car","hovercraft","plane"]}, + {"id":"crescent-island","title":"Crescent Island","world":"Sherbet Island","vehicles":["car","hovercraft"]}, + {"id":"frosty-village","title":"Frosty Village","world":"Snowflake Mountain","vehicles":["car","plane"]} + ], + "boards":[{"id":"ancient-lake-car","kind":"vanilla","title":"Ancient Lake","vehicle":"car","ranked":true}], + "customTracks":[ + {"id":"splashdown","title":"Splashdown Pass","version":"1.0","qualified":false}, + {"id":"sherbet-land","title":"Sherbet Land","version":"1.0","qualified":false} + ], "nextCursor":"" + })json")); + value.speedrun_board = std::make_shared(Json::parse(R"json({ + "track":{"id":"ancient-lake","title":"Ancient Lake","world":"Dino Domain"}, + "vehicle":"car", "vehicles":["car","hovercraft","plane"], "racers":[{"id":"ancient-lake-car","name":"Diddy"}], + "score":"race", "ranked":true, + "entries":[{"place":1,"name":"Example Racer","racer":"Diddy","ticks":5300,"id":"fixture-one"}, + {"place":2,"name":"Deck Racer","racer":"Diddy","ticks":5350,"id":"fixture-two"}] + })json")); + return value; + }(); + return fixture; +} + +void DrawCatalogueLeaders(const dkr::store::Json& track, float width, bool full_game) { + const auto data = track.find("leaders"); + if (data == track.end() || !data->is_object()) + return; + const auto draw_score = [&](const char* label, const dkr::store::Json& vehicle, const char* kind, float available) { + const auto score = vehicle.find(kind); + if (score == vehicle.end() || !score->is_object() || LeaderboardNumber(*score, "ticks") <= 0) { + OlParagraph(std::string(label) + " —", 14.F, kOlSoft, available); + return; + } + const auto line = std::string(label) + " " + StoreText(*score, "name", 80) + " · " + + LeaderboardTime(LeaderboardNumber(*score, "ticks")); + const auto type = OlRead(14.F); + const auto badge_type = OlRead(12.F, true); + const auto place = LocalisedUi::copy("1st"); + const float spacing = 7.F; + const float icon_width = 14.F; + const float badge_width = spacing + icon_width + 4.F + PaddockMeasure(badge_type, place); + const auto lines = OlWrap(type, line, std::max(1.F, available - badge_width)); + const ImVec2 start = ImGui::GetCursorScreenPos(); + auto* draw = ImGui::GetWindowDrawList(); + PaddockTextStyle style; + style.colour = PaddockCol(kOlSoft); + PaddockDrawLines(draw, type, start, available, lines, style); + const float x = start.x + lines.back().width + spacing; + const float y = start.y + type.line * static_cast(lines.size() - 1); + const float top = y + (type.line - 11.F) * .5F; + const std::array crown{{ + {x, top + 2.F}, + {x + 4.F, top + 5.F}, + {x + 7.F, top}, + {x + 10.F, top + 5.F}, + {x + icon_width, top + 2.F}, + {x + 12.F, top + 10.F}, + {x + 2.F, top + 10.F}, + }}; + const auto gold = PaddockCol(kOlAmber); + draw->AddPolyline(crown.data(), static_cast(crown.size()), gold, ImDrawFlags_Closed, 1.4F); + PaddockDrawRun(draw, badge_type, {x + icon_width + 4.F, y + (type.line - badge_type.line) * .5F}, gold, + place.data(), place.data() + place.size()); + ImGui::Dummy({available, type.line * static_cast(lines.size())}); + }; + if (full_game) { + draw_score("Finish time", data->value("mixed", dkr::store::Json::object()), "race", width); + return; + } + const auto vehicles = track.value("vehicles", dkr::store::Json::array()); + if (vehicles.empty()) + return; + const auto columns = + std::min(static_cast(vehicles.size()), std::max(1U, static_cast(width / 185.F))); + if (!ImGui::BeginTable("TrackRecords", columns, ImGuiTableFlags_SizingStretchSame, {width, 0.F})) + return; + for (const auto& vehicle : vehicles) { + const auto& id = vehicle.get_ref(); + ImGui::TableNextColumn(); + const float available = ImGui::GetContentRegionAvail().x; + OlParagraph(LeaderboardVehicle(id), 14.F, kOlAmber, available, true); + const auto scores = data->value(id, dkr::store::Json::object()); + draw_score("Full race", scores, "race", available); + draw_score("Best lap", scores, "lap", available); + } + ImGui::EndTable(); +} + +template +void DrawLeaderboardTrackRow(float width, const std::string& title, const std::string& detail, DrawActions draw_actions, + const dkr::store::Json* records = nullptr, bool full_game = false) { + DrawOlCard(width, OlPanelLook{}, [&](float inner) { + const auto draw_details = [&](float available) { + OlParagraph(title, 18.F, kOlInk, available, true); + if (!detail.empty()) + OlParagraph(detail, 14.F, kOlSoft, available); + PaddockGap(4.F); + draw_actions(available); + }; + if (!records || inner < 440.F) { + draw_details(inner); + if (records) { + PaddockGap(8.F); + DrawCatalogueLeaders(*records, inner, full_game); + } + return; + } + if (!ImGui::BeginTable("TrackRow", 2, ImGuiTableFlags_SizingStretchProp, {inner, 0.F})) + return; + ImGui::TableSetupColumn("Track", ImGuiTableColumnFlags_WidthFixed, std::clamp(inner * .22F, 160.F, 300.F)); + ImGui::TableSetupColumn("Leaders", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableNextColumn(); + draw_details(ImGui::GetContentRegionAvail().x); + ImGui::TableNextColumn(); + DrawCatalogueLeaders(*records, ImGui::GetContentRegionAvail().x, full_game); + ImGui::EndTable(); + }); + PaddockGap(6.F); +} + +void StartAdventureRun(trial::Adventure goal, std::string board, bool signed_in, bool qualified) { + RankedJob([goal, board = std::move(board), signed_in, qualified, config = g_config_directory] { + std::optional attempt; + if (signed_in) { + try { + const auto reply = dkr::store::service().ranked_attempt(board); + attempt = trial::parse_adventure_attempt(StoreText(reply, "board", 96), StoreText(reply, "engine", 64), + StoreText(reply, "ticket", 160), goal); + if (attempt) + attempt->finish_targets = ReadFinishTargets(reply); + } catch (const std::exception&) { + attempt.reset(); + } + } + auto request = TimeTrialRequest{trial::Mode::Record, NewTimeTrialFile(config, board + "-Practice")}; + request.adventure = goal; + const bool load_record = attempt.has_value() || (qualified && !signed_in); + request.attempt = std::move(attempt); + try { + for (const auto& replay : ReadLocalReplayLibrary(request.replay.parent_path())) { + if (!replay.valid || replay.time <= 0 || replay.adventure_category != trial::adventure_id(goal) || + replay.ruleset != trial::kAdventureRules) + continue; + const auto manifest = ReadReplaySummary(replay.file); + const auto reference = ReadAdventureReference(manifest); + if (!request.prior_best || replay.time < request.prior_best) { + request.prior_best = unsigned(replay.time); + request.adventure_pb = reference; + } + const auto splits = manifest.find("splits"); + if (splits == manifest.end() || !splits->is_array() || reference.size() != splits->size()) + continue; + std::string previous; + std::int64_t previous_ticks = 0; + for (const auto& entry : *splits) { + const auto label = entry[0].get(); + const auto ticks = reference.at(label); + if (ticks <= previous_ticks) + break; + const auto segment = ticks - previous_ticks; + auto [slot, inserted] = request.adventure_segments.try_emplace({previous, label}, segment); + if (!inserted) + slot->second = std::min(slot->second, segment); + previous = label; + previous_ticks = ticks; + } + } + } catch (const std::exception&) { + // The comparison is optional when the local replay folder is unavailable. + } + if (load_record) { + try { + const auto standings = dkr::store::service().adventure_record(std::string(trial::adventure_id(goal))); + const auto& entries = standings.at("entries"); + if (entries.is_array() && !entries.empty()) + request.adventure_record = ReadAdventureReference(entries.front()); + } catch (const std::exception&) { + // A network outage should never prevent practising a route. + } + } + return [request = std::move(request), signed_in]() mutable { + QueueTimeTrialRequest(std::move(request), signed_in); + }; + }); +} + +struct AdventureBoardRow { + trial::Adventure goal; + std::string_view id, title, description; +}; +constexpr std::array kAdventureBoardRows{ + AdventureBoardRow{trial::Adventure::AnyPercent, "any-percent", "Any%", "Beat Wizpig in Future Fun Land."}, + AdventureBoardRow{trial::Adventure::HundredPercent, "100-percent", "100%", + "Complete the Adventure checklist and beat Wizpig."}, + AdventureBoardRow{trial::Adventure::AnyPercentGlitchless, "any-percent-glitchless", "Any% Glitchless", + "Defeat each boss without banned glitches."}, + AdventureBoardRow{trial::Adventure::AllTrophyRaces, "all-trophy-races", "All Trophy Races", + "Finish all five Trophy sets in Tracks Mode."}, + AdventureBoardRow{trial::Adventure::AllBosses, "all-bosses", "All Bosses", + "Win all six boss rematches from the completed Adventure slot."}, + AdventureBoardRow{trial::Adventure::AllMinigames, "all-minigames", "All Minigames", + "Win all four minigames in Tracks Mode."}, + AdventureBoardRow{trial::Adventure::TrophyDinoFirst, "all-trophy-races-dino-first", + "All Trophy Races - Dino Domain First", + "In Tracks Mode, race all five Trophy sets beginning in Dino Domain."}, + AdventureBoardRow{trial::Adventure::TrophyFutureFirst, "all-trophy-races-ffl-first", + "All Trophy Races - Future Fun Land First", + "In Tracks Mode, race all five Trophy sets beginning in Future Fun Land."}, + AdventureBoardRow{trial::Adventure::CarPercent, "car-percent", "Car%", + "Win each available car course in Tracks Mode."}, + AdventureBoardRow{trial::Adventure::HoverPercent, "hover-percent", "Hover%", + "Win each available hovercraft course in Tracks Mode."}, + AdventureBoardRow{trial::Adventure::PlanePercent, "plane-percent", "Plane%", + "Win each available plane course in Tracks Mode."}, + AdventureBoardRow{trial::Adventure::TTAmulet, "tt-amulet-no-wrong-warp", "T.T. Amulet - No Wrong Warp", + "Earn the four T.T. Amulet pieces through normal progression."}, +}; + +bool QualifiedAdventureBoard(const dkr::store::Json* catalogue, const std::string& board) { + return catalogue && catalogue->contains("boards") && + std::ranges::any_of(catalogue->at("boards"), [&](const auto& entry) { + return StoreText(entry, "id", 96) == board && entry.value("ranked", false); + }); +} + +std::function DrawPracticeAdventure(float width, const dkr::store::Json* catalogue, bool signed_in) { + OlHeading("Challenge Runs", width < 275.F ? 19.F : 24.F, kOlCream, width); + auto& selected = g_run_setup.challenge; + static const auto categories = [] { + std::vector choices; + choices.reserve(kAdventureBoardRows.size()); + for (const auto& row : kAdventureBoardRows) + choices.emplace_back(std::string(row.title)); + return choices; + }(); + selected = std::clamp(selected, 0, int(categories.size()) - 1); + SettingsDropdown("run-category", "Category", &selected, categories, std::min(360.F, width)); + const auto& category = kAdventureBoardRows[static_cast(selected)]; + PaddockGap(8.F); + OlParagraph(category.description, 15.F, kOlSoft, width); + const auto board = "adventure-" + std::string(category.id); + const bool qualified = QualifiedAdventureBoard(catalogue, board); + return + [goal = category.goal, board, signed_in, qualified] { StartAdventureRun(goal, board, signed_in, qualified); }; +} + +void DrawAdventureBoards(float width, const dkr::store::Json* catalogue, TrackQuery& query) { + const auto* catalogue_categories = + catalogue && catalogue->contains("adventureCatalogue") ? &catalogue->at("adventureCatalogue") : nullptr; + for (const auto& category : kAdventureBoardRows) { + const std::string board = "adventure-" + std::string(category.id); + const dkr::store::Json* records = nullptr; + if (catalogue_categories) { + const auto entry = std::ranges::find_if( + *catalogue_categories, [&](const auto& row) { return StoreText(row, "id", 96) == category.id; }); + if (entry != catalogue_categories->end()) + records = &*entry; + } + const bool qualified = QualifiedAdventureBoard(catalogue, board); + ImGui::PushID(category.id.data()); + DrawLeaderboardTrackRow( + width, std::string(category.title), std::string(category.description), + [&](float inner) { + if (!qualified) { + OlParagraph("Awaiting qualification", 14.F, kOlAmber, inner); + return; + } + if (g_track_return_focus == category.id) { + ImGui::SetKeyboardFocusHere(); + g_track_return_focus.clear(); + } + if (OlButton("View Times")) { + query = {}; + query.id = category.id; + query.full_game = true; + dkr::store::service().load_leaderboards({}, query); + } + }, + records, true); + ImGui::PopID(); + } +} + +#include "speedrunning_welcome.inl" + +void DrawLeaderboardsPage(float width, bool entered, bool live) { + enum Category { TopPlayers, Vanilla, Custom, FullGame, Runs }; + enum RunTab { NewRun, Replays, MySubmittedRuns, ReviewRuns, Options }; + static const std::vector labels{"Top Players", "Vanilla Tracks", "Custom Tracks", "Full Game", "Runs"}; + static int category = TopPlayers; + static RunTab run_tab = NewRun; + static std::string last_requested_owner; + static RunTab last_requested_tab = NewRun; + static std::string world, vehicle; + static char search[121]{}; + static TrackQuery query; + static bool back_to_profile = false; + auto& service = dkr::store::service(); + const auto published = service.view(); + const auto* snapshot = published.get(); + if (g_leaderboard_layout_check) { + snapshot = &LeaderboardLayoutFixture(); + category = g_launcher_layout_step == 3 ? Custom + : g_launcher_layout_step == 4 ? FullGame + : g_launcher_layout_step == 2 ? Vanilla + : Runs; + query = {g_launcher_layout_step == 2 ? "ancient-lake" : ""}; + run_tab = NewRun; + } else if (entered) { + const bool after_run = std::exchange(g_open_speedrunning_result, false); + category = after_run ? Runs : TopPlayers; + query = {}; + back_to_profile = false; + g_track_return_focus.clear(); + run_tab = after_run && RunPreference(RunOption::ReturnTo) ? Replays : NewRun; + last_requested_tab = NewRun; + SelectOverallPlayer({}); + g_overall_focus.clear(); + g_overall_tab = OverallPlayerTab::Score; + if (!DialogJobRunning()) + RefreshOverallRankings(); + g_refresh_replay_library = true; + g_published_replay_times = {}; + if (!snapshot->speedrun_catalogue) + service.load_leaderboards(); + } + const auto role = StoreText(snapshot->user, "role", 20); + const bool staff = role == "moderator" || role == "admin"; + const auto owner = RankedRunsOwner(); + const bool can_review = staff && !owner.empty(); + if (run_tab == ReviewRuns && !can_review) + run_tab = NewRun; + const bool showing_submissions = category == Runs && (run_tab == MySubmittedRuns || run_tab == ReviewRuns); + const float refresh = PaddockImportButtonWidth("Refreshing..."); + const float website = PaddockImportButtonWidth("Website"); + const float actions = refresh + website + 12.F; + DrawSharedPageHeader( + width, live ? "LEADERBOARDS" : "SPEEDRUNNING", + "Race for a personal best and watch how other players set theirs.", actions, [&] { + { + const OlDisabled loading(snapshot->speedrun_loading || DialogJobRunning() || + (showing_submissions && owner.empty())); + if (PaddockImportButton(snapshot->speedrun_loading ? "Refreshing...###speedrun-refresh" + : "Refresh###speedrun-refresh", + std::min(width, refresh), true)) { + if (showing_submissions) { + RefreshLeaderboardRuns(run_tab == ReviewRuns); + } else if (category == TopPlayers) { + RefreshOverallRankings(); + } else if (category == Runs && run_tab == Replays) { + g_refresh_replay_library = true; + service.load_leaderboards(); + } else { + service.load_leaderboards({}, query.id.empty() ? std::nullopt : std::optional(query)); + } + } + } + if (width >= actions) + ImGui::SameLine(0.F, 12.F); + else + PaddockGap(12.F); + if (PaddockImportButton("Website###speedrun-website", std::min(width, website), false, true)) + SDL_OpenURL(kLeaderboardWebsite); + }); + DrawLocalRunConfirmation(); + if (!live && !g_leaderboard_layout_check) + DrawSpeedrunningWelcome(entered, !owner.empty(), staff, snapshot->speedrun_catalogue.get()); + const int next = StoreTabLine(labels, category, width, "speedrun-category", true); + if (next != category) { + category = next; + query = {}; + back_to_profile = false; + g_track_return_focus.clear(); + run_tab = NewRun; + last_requested_tab = NewRun; + if (category == TopPlayers && g_overall_standings.is_null() && !DialogJobRunning()) + RefreshOverallRankings(); + world.clear(); + vehicle.clear(); + search[0] = '\0'; + } + if ((category != Runs || (run_tab != NewRun && run_tab != Options)) && !snapshot->speedrun_error.empty()) + OlParagraph(snapshot->speedrun_error, 15.F, kOlError, width); + if (!g_time_trial_message.empty()) + OlParagraph(g_time_trial_message, 15.F, kOlSoft, width); + PaddockGap(8.F); + if (category == TopPlayers) { + if (const auto selected = DrawOverallRankings(width)) { + query = *selected; + category = query.full_game ? FullGame : query.custom ? Custom : Vanilla; + back_to_profile = true; + service.load_leaderboards({}, query); + } + return; + } + if (category == Runs) { + std::vector run_tabs{"Run", "Replays", "My Submitted Runs"}; + if (can_review) + run_tabs.emplace_back("Review Runs"); + const int options_index = static_cast(run_tabs.size()); + run_tabs.emplace_back("Options"); + const int selected = + StoreTabLine(run_tabs, run_tab == Options ? options_index : run_tab, width, "speedrun-runs", true); + const auto next_tab = selected == options_index ? Options : static_cast(selected); + if (next_tab == Replays && run_tab != Replays) + g_refresh_replay_library = true; + run_tab = next_tab; + if (owner.empty() || (run_tab != MySubmittedRuns && run_tab != ReviewRuns)) { + last_requested_owner.clear(); + last_requested_tab = NewRun; + } else if (!DialogJobRunning() && (last_requested_tab != run_tab || last_requested_owner != owner)) { + last_requested_tab = run_tab; + last_requested_owner = owner; + RefreshLeaderboardRuns(run_tab == ReviewRuns); + } + PaddockGap(8.F); + if (run_tab == NewRun) + DrawLeaderboardPractice(width, snapshot->speedrun_catalogue.get()); + else if (run_tab == Replays) + DrawLocalReplays(width, snapshot->speedrun_catalogue.get()); + else if (run_tab == Options) + DrawSpeedrunningOptions(width); + else + DrawLeaderboardRuns(width, run_tab == ReviewRuns); + return; + } + if (!query.id.empty()) { + if (OlButton(back_to_profile ? "Back to player stats" + : category == FullGame ? "All categories" + : "All tracks") || + ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)) { + if (!back_to_profile) + g_track_return_focus = query.id; + query = {}; + if (std::exchange(back_to_profile, false)) { + g_overall_focus = g_overall_player; + category = TopPlayers; + return; + } + } else { + if (snapshot->speedrun_loading) + OlParagraph("Loading times...", 15.F, kOlSoft, width); + else if (snapshot->speedrun_board && StoreText(snapshot->speedrun_board->at("track"), "id", 96) == query.id) + DrawLeaderboardRanking(width, *snapshot->speedrun_board, query); + return; + } + } + if (category == FullGame) { + DrawAdventureBoards(width, snapshot->speedrun_catalogue.get(), query); + return; + } + if (!snapshot->speedrun_catalogue) { + if (snapshot->speedrun_loading) + OlParagraph("Loading leaderboards...", 15.F, kOlSoft, width); + return; + } + const auto& catalogue = *snapshot->speedrun_catalogue; + const auto tracks = + catalogue.value(category == Vanilla ? "vanillaTracks" : "customTracks", dkr::store::Json::array()); + constexpr float world_width = 224.F, vehicle_width = 160.F; + const float gap = ImGui::GetStyle().ItemSpacing.x; + const float filters_width = category == Vanilla ? world_width + vehicle_width + 2.F * gap : 0.F; + const float search_width = + std::min(category == Vanilla ? 300.F : 360.F, width >= filters_width + 176.F ? width - filters_width : width); + OlInputOptions options; + options.hint = "Track name"; + options.height = kSettingsDropdownHeight; + ImGui::BeginGroup(); + SettingsLabel("Search tracks", search_width); + if (OlInput("##find-track", nullptr, search, sizeof(search), search_width, options) == OlInputResult::Gamepad) { + RequestCustomTextKeyboard( + "Search tracks", search, sizeof(search), + [](const std::string& text) { std::snprintf(search, sizeof(search), "%s", text.c_str()); }, true); + } + ImGui::EndGroup(); + float row_width = search_width; + const auto draw_filter = [&](const char* label, const LeaderboardChoices& choices, std::string& value, + float preferred) { + const float field_width = std::min(preferred, width); + if (row_width > 0.F && row_width + gap + field_width <= width + 0.1F) { + ImGui::SameLine(); + row_width += gap; + } else { + row_width = 0.F; + } + LeaderboardFilter(label, choices, value, field_width); + row_width += field_width; + }; + if (category == Vanilla) { + LeaderboardChoices worlds{{"", "All worlds"}}; + for (const auto& track : tracks) { + auto name = StoreText(track, "world", 80); + if (!name.empty() && + std::none_of(worlds.begin(), worlds.end(), [&](const auto& entry) { return entry.first == name; })) + worlds.emplace_back(name, name); + } + draw_filter("World", worlds, world, world_width); + static const LeaderboardChoices vehicles{ + {"", "All vehicles"}, {"car", "Car"}, {"hovercraft", "Hovercraft"}, {"plane", "Plane"}}; + draw_filter("Vehicle", vehicles, vehicle, vehicle_width); + } + PaddockGap(8.F); + const auto needle = dkr::runtime::texture_browser::lower_ascii(search); + std::vector> matching; + for (const auto& track : tracks) { + const auto title = StoreText(track, "title", 120); + if (dkr::runtime::texture_browser::lower_ascii(title).find(needle) == std::string::npos) + continue; + const auto track_world = StoreText(track, "world", 80); + const auto supported = track.value("vehicles", dkr::store::Json::array()); + if (category == Vanilla && + ((!world.empty() && track_world != world) || + (!vehicle.empty() && std::find(supported.begin(), supported.end(), vehicle) == supported.end()))) + continue; + const auto& boards = catalogue["boards"]; + const bool qualified = + category == Custom ? track.value("qualified", false) + : std::any_of(boards.begin(), boards.end(), [&](const auto& board) { + return StoreText(board, "kind", 20) == "vanilla" && + StoreText(board, "title", 120) == title && board.value("ranked", false) && + (vehicle.empty() || StoreText(board, "vehicle", 24) == vehicle); + }); + matching.emplace_back(&track, qualified); + } + OlParagraph(matching.empty() ? "No tracks match these filters." + : std::to_string(matching.size()) + " of " + std::to_string(tracks.size()) + " tracks", + 14.F, kOlSoft, width); + for (const auto& [track, qualified] : matching) { + const auto id = StoreText(*track, "id", 96); + const auto title = StoreText(*track, "title", 120); + std::string detail = + category == Custom ? "Version " + StoreText(*track, "version", 40) : StoreText(*track, "world", 80); + for (const auto& choice : track->value("vehicles", dkr::store::Json::array())) + detail += " | " + LeaderboardVehicle(choice.get()); + ImGui::PushID(id.c_str()); + DrawLeaderboardTrackRow( + width, title, detail, + [&](float inner) { + if (!qualified) { + OlParagraph("Awaiting qualification", 14.F, kOlAmber, inner); + return; + } + const OlDisabled loading(snapshot->speedrun_loading); + if (g_track_return_focus == id) { + ImGui::SetKeyboardFocusHere(); + g_track_return_focus.clear(); + } + if (OlButton("View Times")) { + query = {id, category == Vanilla ? vehicle : std::string{}, {}, category == Custom}; + service.load_leaderboards({}, query); + } + }, + track->contains("leaders") ? track : nullptr); + ImGui::PopID(); + } + if (category == Custom) { + if (const auto cursor = StoreText(catalogue, "nextCursor", 96); !cursor.empty()) { + const OlDisabled busy(snapshot->speedrun_loading); + if (OlButton("More tracks")) + service.load_leaderboards(cursor); + } + } +} diff --git a/runtime-recomp/src/game/library_ui/navigation_check.inl b/runtime-recomp/src/game/library_ui/navigation_check.inl index be1b59fe..dbe8cab0 100644 --- a/runtime-recomp/src/game/library_ui/navigation_check.inl +++ b/runtime-recomp/src/game/library_ui/navigation_check.inl @@ -9,6 +9,8 @@ std::filesystem::path g_launcher_layout_root; int g_launcher_layout_step = 0; bool g_launcher_layout_sized = false; bool g_localisation_cycle_check = false; +bool g_leaderboard_layout_check = false; +bool g_leaderboard_navigation_requested = false; double g_launcher_layout_at = 0; constexpr std::array kLauncherLayoutPages{0, 6, 6, 6, 6, 6, 10, 1, 2, 3, 4, 5, 8, 9, 7, 10, 10, 10, 10, 10, 10, 10, 10, 3, 3, 3, 3, 6, 6, 6, @@ -19,15 +21,24 @@ bool g_surface_scroll_bottom = false; #include "handoff_check.inl" bool PlayLaunchLayoutCheck(); bool SaveDraftLayoutCheck(); +bool ModdedSaveDraftLayoutCheck(); void PlayLaunchCaptureCheck(); void SaveDraftCaptureCheck(); void LibrarySelectCheckView(int step, int& page) { + if (g_leaderboard_layout_check) { + if (step == 1 && !g_leaderboard_navigation_requested) { + g_page_navigation_request = dkr::library_ui::LeaderboardsPage; + g_leaderboard_navigation_requested = true; + } + return; + } if (SaveDraftLayoutCheck()) { page = kPageSaveManager; - g_saves_page.scope = 0; - g_saves_page.section = 1; - g_surface_scroll_bottom = true; + g_saves_page.scope = ModdedSaveDraftLayoutCheck() ? 2 : 0; + g_saves_page.section = SaveEditorSection::Progress; + g_saves_page.selected_slot = std::min(g_launcher_layout_step / 2, 2); + g_surface_scroll_bottom = false; return; } if (PlayLaunchLayoutCheck()) { @@ -51,7 +62,7 @@ void LibrarySelectCheckView(int step, int& page) { g_mods_page.section = g_mods_page.entry_section = step - 26; if (page == kPageSaveManager) { g_saves_page.scope = step == 32 ? 3 : step == 33 ? 1 : 0; - g_saves_page.section = step == 30 ? 1 : step == 31 ? 2 : 0; + g_saves_page.section = step == 31 ? SaveEditorSection::Files : SaveEditorSection::Progress; } if (page == kPageOnlineMp) { const std::array sections{OlSection::Play, OlSection::Settings, OlSection::Profile, @@ -93,7 +104,7 @@ bool LauncherLayoutCheckRoute(int& page) { // Captures only an explicitly authenticated, disposable launcher test profile. // Ordinary startup performs no pixel readback, window resize or image writes. -void LauncherLayoutCheckCapture(SDL_Renderer* renderer) { +void LauncherLayoutCheckCapture(SDL_Renderer* renderer, int current_page) { if (g_launcher_layout_root.empty() || g_launcher_layout_step >= int(kLauncherLayoutPages.size())) return; if (!g_launcher_layout_sized) { @@ -134,8 +145,10 @@ void LauncherLayoutCheckCapture(SDL_Renderer* renderer) { SDL_FreeSurface(surface); if (!saved) return; + const int page = + g_leaderboard_layout_check ? current_page : kLauncherLayoutPages[std::size_t(g_launcher_layout_step)]; std::fprintf(stderr, "[launcher-layout][isolated-check] step=%d page=%d width=%d height=%d captured\n", - g_launcher_layout_step, kLauncherLayoutPages[std::size_t(g_launcher_layout_step)], width, height); + g_launcher_layout_step, page, width, height); std::fprintf(stderr, "[localisation][isolated-check] step=%d language=%s atlas=%dx%d texture=%p\n", g_launcher_layout_step, dkr::localisation::active().data(), ImGui::GetIO().Fonts->TexWidth, ImGui::GetIO().Fonts->TexHeight, ImGui::GetIO().Fonts->TexID); @@ -147,7 +160,8 @@ void LauncherLayoutCheckCapture(SDL_Renderer* renderer) { PlayLaunchCaptureCheck(); ++g_launcher_layout_step; g_launcher_layout_at = PaddockClock(); - if (PlayLaunchLayoutCheck() && g_launcher_layout_step == 6) { + if ((PlayLaunchLayoutCheck() && g_launcher_layout_step == 6) || + (g_leaderboard_layout_check && g_launcher_layout_step == 5)) { SDL_Event quit{}; quit.type = SDL_QUIT; SDL_PushEvent(&quit); @@ -221,6 +235,8 @@ void LibraryNavigationCheckLauncherInit(const std::filesystem::path& root) { std::string_view(layout) == "wide" || std::string_view(layout) == "small" || std::string_view(layout) == "short")) g_launcher_layout_root = root; + const char* racing = std::getenv("DKR_OWNED_CHECK_LEADERBOARD_LAYOUT"); + g_leaderboard_layout_check = !g_launcher_layout_root.empty() && racing && std::string_view(racing) == "1"; const char* controls = std::getenv("DKR_LIBRARY_CONTROLS_CHECK"); g_library_controls_check = !g_launcher_layout_root.empty() && controls && std::string_view(controls) == "1"; } diff --git a/runtime-recomp/src/game/library_ui/play_launch_bar.inl b/runtime-recomp/src/game/library_ui/play_launch_bar.inl index 33fd69fa..33f8ea4a 100644 --- a/runtime-recomp/src/game/library_ui/play_launch_bar.inl +++ b/runtime-recomp/src/game/library_ui/play_launch_bar.inl @@ -9,11 +9,15 @@ extern int g_launcher_layout_step; bool PlayLaunchLayoutCheck() { const char* value = std::getenv("DKR_OWNED_CHECK_PLAY_LAUNCH"); return !g_launcher_layout_root.empty() && value && - (std::string_view(value) == "1" || std::string_view(value) == "save"); + (std::string_view(value) == "1" || std::string_view(value) == "save" || + std::string_view(value) == "save-modded"); } bool SaveDraftLayoutCheck() { const char* value = std::getenv("DKR_OWNED_CHECK_PLAY_LAUNCH"); - return PlayLaunchLayoutCheck() && std::string_view(value) == "save"; + return PlayLaunchLayoutCheck() && std::string_view(value).starts_with("save"); +} +bool ModdedSaveDraftLayoutCheck() { + return SaveDraftLayoutCheck() && std::string_view(std::getenv("DKR_OWNED_CHECK_PLAY_LAUNCH")) == "save-modded"; } struct PlayLaunchGeometry { ImVec2 button_min{}, button_max{}, clip_min{}, clip_max{}; @@ -78,18 +82,23 @@ void PlayLaunchCaptureCheck() { } struct SaveDraftGeometry { - ImRect panel, bounds; - float top = 0.F; - bool dirty = false; + ImRect panel, bounds, slots, editor, editor_body; + float top = 0.F, editor_scroll = 0.F; + int selected_slot = 0; + bool dirty = false, modded = false; }; SaveDraftGeometry g_save_draft_geometry; void SaveDraftCaptureCheck() { const auto& g = g_save_draft_geometry; - std::fprintf( - stderr, - "[save-draft][isolated-check] step=%d bar-left=%.1f bar-right=%.1f bar-top=%.1f bar-bottom=%.1f panel-left=%.1f panel-right=%.1f panel-bottom=%.1f dirty=%d\n", - g_launcher_layout_step, g.panel.Min.x, g.panel.Max.x, g.top, g.panel.Max.y, g.bounds.Min.x, g.bounds.Max.x, - g.bounds.Max.y, int(g.dirty)); + std::fprintf(stderr, + "[save-draft][isolated-check] step=%d bar-left=%.1f bar-right=%.1f bar-top=%.1f bar-bottom=%.1f " + "panel-left=%.1f panel-right=%.1f panel-bottom=%.1f dirty=%d slots-left=%.1f slots-right=%.1f " + "slots-bottom=%.1f editor-left=%.1f editor-right=%.1f editor-top=%.1f editor-bottom=%.1f " + "editor-scroll=%.1f editor-body-left=%.1f editor-body-right=%.1f slot=%d modded=%d\n", + g_launcher_layout_step, g.panel.Min.x, g.panel.Max.x, g.top, g.panel.Max.y, g.bounds.Min.x, + g.bounds.Max.x, g.bounds.Max.y, int(g.dirty), g.slots.Min.x, g.slots.Max.x, g.slots.Max.y, + g.editor.Min.x, g.editor.Max.x, g.editor.Min.y, g.editor.Max.y, g.editor_scroll, g.editor_body.Min.x, + g.editor_body.Max.x, g.selected_slot, int(g.modded)); } float PlayLaunchButtonWidth(float width) { diff --git a/runtime-recomp/src/game/library_ui/play_tools.inl b/runtime-recomp/src/game/library_ui/play_tools.inl index dc91e19b..a7747e80 100644 --- a/runtime-recomp/src/game/library_ui/play_tools.inl +++ b/runtime-recomp/src/game/library_ui/play_tools.inl @@ -1,41 +1,42 @@ const char* SessionModsCaption(bool enabled) { return enabled ? "Session mods: ON" : "Session mods: OFF"; } -float SessionModsWidth() { - return std::max(PaddockImportButtonWidth(SessionModsCaption(true)), - PaddockImportButtonWidth(SessionModsCaption(false))); -} -float PlayToolsHeight(float width) { - return PaddockImportButtonWidth("Achievements") + SessionModsWidth() + PaddockImportButtonWidth("Save Manager") + - 32.F <= - width - ? 56.F - : 192.F; -} -void DrawPlayTools(float width) { - const float achievements = PaddockImportButtonWidth("Achievements"); - const float saves = PaddockImportButtonWidth("Save Manager"); - const bool row = PlayToolsHeight(width) == 56.F; +constexpr float kPlayToolHeight = 40.F, kPlayToolGap = 8.F; +void DrawPlayTools(float width, bool live) { + const char* speedrun_label = live ? "Leaderboards###play-leaderboards" : "Speedrunning###play-leaderboards"; + const std::array widths{PaddockImportButtonWidth("Achievements", true), + PaddockImportButtonWidth(speedrun_label, true), + std::max(PaddockImportButtonWidth(SessionModsCaption(true), true), + PaddockImportButtonWidth(SessionModsCaption(false), true)), + PaddockImportButtonWidth("Save Manager", true)}; + const float widest = *std::max_element(widths.begin(), widths.end()); + const float full = widths[0] + widths[1] + widths[2] + widths[3] + 3.F * kPlayToolGap; + const int columns = width >= full ? 4 : width >= 2.F * widest + kPlayToolGap ? 2 : 1; + const int rows = 4 / columns; + const float fallback_width = std::min(widest, width); + const float row_width = columns == 4 ? full : float(columns) * fallback_width + float(columns - 1) * kPlayToolGap; const auto at = ImGui::GetCursorScreenPos(); - if (PaddockImportButton("Achievements###play-achievements", row ? achievements : width, false, false, 1)) + const float left = at.x + (width - row_width) * .5F; + float next = left; + const auto draw = [&](int i, const char* label, int icon) { + const float button_width = columns == 4 ? widths[std::size_t(i)] : fallback_width; + const float x = columns == 4 ? next : left + float(i % columns) * (fallback_width + kPlayToolGap); + next += button_width + kPlayToolGap; + ImGui::SetCursorScreenPos({x, at.y + float(i / columns) * (kPlayToolHeight + kPlayToolGap)}); + return PaddockImportButton(label, button_width, false, false, icon, true); + }; + if (draw(0, "Achievements###play-achievements", 1)) g_page_navigation_request = kPageAchievements; - ImGui::SetCursorScreenPos( - row ? ImVec2{at.x + achievements + (width - achievements - saves - SessionModsWidth()) * .5F, at.y} - : ImVec2{at.x, at.y + 68.F}); + if (draw(1, speedrun_label, 4)) + g_page_navigation_request = dkr::library_ui::LeaderboardsPage; const bool enabled = dkr::session_content::next_enabled.load(); const auto caption = std::string(SessionModsCaption(enabled)) + "###play-session-mods"; - if (PaddockImportButton(caption.c_str(), row ? SessionModsWidth() : width, false, false, 3)) { + if (draw(2, caption.c_str(), 3)) { dkr::session_content::next_enabled = !enabled; SaveSettings(); } - ImGui::SetCursorScreenPos(row ? ImVec2{at.x + width - saves, at.y} : ImVec2{at.x, at.y + 136.F}); - if (PaddockImportButton("Save Manager###play-saves", row ? saves : width, false, false, 2)) + if (draw(3, "Save Manager###play-saves", 2)) g_page_navigation_request = kPageSaveManager; ImGui::SetCursorScreenPos(at); - ImGui::Dummy({width, PlayToolsHeight(width)}); -} -void DrawPlayToolBack(float) { - if (PaddockTextLink("Back to Play")) - g_page_navigation_request = kPagePlay; - PaddockGap(16.F); + ImGui::Dummy({width, float(rows) * kPlayToolHeight + float(rows - 1) * kPlayToolGap}); } diff --git a/runtime-recomp/src/game/library_ui/policy.hpp b/runtime-recomp/src/game/library_ui/policy.hpp index faafe439..405c34f9 100644 --- a/runtime-recomp/src/game/library_ui/policy.hpp +++ b/runtime-recomp/src/game/library_ui/policy.hpp @@ -9,10 +9,13 @@ namespace dkr::library_ui { // Existing page identities stay stable. Only visual order changes. -inline constexpr int LibraryPage = 10, PageCount = 11; +inline constexpr int LibraryPage = 10, PageCount = 11, LeaderboardsPage = 14; inline constexpr std::array SidebarOrder{0, 5, LibraryPage, 6, 1, 2, 3, 7, 13, 11, 12}; +inline constexpr bool is_content_page(int page) { + return (page >= 0 && page < PageCount) || page == LeaderboardsPage; +} inline constexpr int sidebar_parent(int page) { - return page == 4 || page == 9 ? 0 : page; + return page == 4 || page == 9 || page == LeaderboardsPage ? 0 : page; } inline constexpr int TexturesSection = 4; // Preserve existing section identities used by links and import callbacks. @@ -35,6 +38,13 @@ inline bool configurable(std::string_view id, bool selected, bool approved, bool inline bool writes_locked(bool game, bool lobby, bool preparing, bool admission, bool vehicles) { return game || lobby || preparing || admission || vehicles; } +inline constexpr bool can_post_replay_attempt(bool has_attempt, bool practice, bool personal_best) { + return has_attempt && (!practice || personal_best); +} +inline constexpr bool can_purge_replay(bool personal_best, bool submitted, bool include_bests, + bool include_unsubmitted) { + return (!personal_best || include_bests) && (submitted || include_unsubmitted); +} // This conversion is for displayed status copy, never IDs, URLs or credentials. inline std::string visible_status(std::string value) { for (const auto& words : {std::pair{"Mod Store", "Mod Library"}, std::pair{"MOD STORE", "MOD LIBRARY"}}) { diff --git a/runtime-recomp/src/game/library_ui/replay_library.inl b/runtime-recomp/src/game/library_ui/replay_library.inl new file mode 100644 index 00000000..2ac853c7 --- /dev/null +++ b/runtime-recomp/src/game/library_ui/replay_library.inl @@ -0,0 +1,326 @@ +struct LocalReplay { + std::filesystem::path file; + std::filesystem::file_time_type saved; + std::string title, course, racer, vehicle, board, posted_owner, adventure_category, ruleset, track_id, track_hash; + std::int64_t time = 0, best_lap = 0; + bool practice = true; + bool valid = false; + bool can_ghost = false; + bool personal_best = false; + bool beat_ghost = false; + bool has_attempt = false; + bool local_capture = false; +}; + +std::vector g_local_replays; +std::filesystem::path g_replay_library_profile; +bool g_refresh_replay_library = true; + +constexpr std::size_t kReplayLibraryBytes = 3 * 1024 * 1024; + +dkr::store::Json ReadReplaySummary(const std::filesystem::path& file) { + const auto bytes = std::filesystem::file_size(file); + std::ifstream input(file, std::ios::binary); + std::array header{}; + if (bytes > kReplayLibraryBytes || !input.read(reinterpret_cast(header.data()), header.size()) || + std::string_view(reinterpret_cast(header.data()), 8) != "DKRREPL2") + throw std::runtime_error("This file is not a supported DKR-R replay."); + const auto length = std::uint32_t(header[8]) | (std::uint32_t(header[9]) << 8) | (std::uint32_t(header[10]) << 16) | + (std::uint32_t(header[11]) << 24); + if (!length || length > 65536 || length > bytes - header.size()) + throw std::runtime_error("The replay metadata is incomplete."); + std::string metadata(length, '\0'); + if (!input.read(metadata.data(), metadata.size())) + throw std::runtime_error("The replay metadata could not be read."); + auto manifest = dkr::store::Json::parse(metadata); + const auto rules = StoreText(manifest, "ruleset", 48); + const bool adventure = rules == trial::kAdventureRules || rules == trial::kAdventureOriginalRouteRules || + rules == trial::kAdventureMilestoneRules || rules == trial::kAdventureColdSaveRules || + rules == trial::kAdventureVisualRngRules || rules == trial::kAdventureSharedRngRules || + rules == trial::kLegacyAdventureRules; + const auto ticks = LeaderboardNumber(manifest, "ticks"); + const auto clock = LeaderboardNumber(manifest, "clockTicks"); + if ((!adventure && rules != trial::kLegacyRules && rules != trial::kVanillaRules && rules != trial::kCustomRules && + rules != trial::kCustomVariableLapsRules) || + !ticks || !clock || clock > ticks * 2 || bytes != header.size() + length + ticks * 4 || + !trial::supported_replay_rom(manifest.value("rom", 0U))) + throw std::runtime_error("The replay format or recording length is unsupported."); + return manifest; +} + +std::filesystem::path ReplaySidecar(std::filesystem::path file) { + return file += ".json"; +} + +bool ReplayLibraryFile(const std::filesystem::path& file) { + std::error_code ec; + return std::filesystem::symlink_status(file, ec).type() == std::filesystem::file_type::regular; +} + +dkr::store::Json ReadReplaySidecar(const std::filesystem::path& file) { + const auto path = ReplaySidecar(file); + if (ReplayLibraryFile(path)) { + try { + const auto text = dkr::updates::read_text(path, 4096); + auto metadata = dkr::store::Json::parse(text, nullptr, false); + if (metadata.is_object()) + return metadata; + } catch (const std::exception&) { + // Sidecar errors must not hide a playable replay. + } + } + return dkr::store::Json::object(); +} + +void WriteReplaySidecar(const std::filesystem::path& file, const dkr::store::Json& metadata) { + dkr::updates::durable_write(ReplaySidecar(file), metadata.dump()); +} + +void CheckManagedReplayDirectory(const std::filesystem::path& directory) { + std::error_code ec; + const auto state = std::filesystem::symlink_status(directory, ec).type(); + if (state != std::filesystem::file_type::directory && state != std::filesystem::file_type::not_found) + throw std::runtime_error("The replay folder is unavailable."); +} + +bool OwnReplayFile(const std::filesystem::path& file, const dkr::store::Json& metadata) { + const auto name = PathUtf8(file.filename()); + const auto origin = StoreText(metadata, "origin", 20); + return file.extension() == ".dkrreplay" && !name.starts_with("Replay-") && !name.starts_with("Imported-") && + origin != "Downloaded" && origin != "Imported" && ReplayLibraryFile(file); +} + +bool ReplayHasRankedAttempt(const dkr::store::Json& manifest) { + return !manifest.value("practice", true) && !StoreText(manifest, "board", 96).empty() && + !StoreText(manifest, "ticket", 160).empty(); +} + +bool IsLocalReplayCapture(const dkr::store::Json& manifest) { + return manifest.value("practice", false) && !manifest.contains("ticket") && !manifest.contains("board") && + !manifest.contains("engine") && !manifest.contains("releaseHash") && !manifest.at("checkpoints").empty(); +} + +std::vector ReadLocalReplayLibrary(const std::filesystem::path& directory) { + CheckManagedReplayDirectory(directory); + std::vector replays; + if (!std::filesystem::exists(directory)) + return replays; + const auto installed = dkr::runtime::custom_tracks::installed_replay_tracks(); + std::map records; + for (const auto& entry : std::filesystem::directory_iterator(directory)) { + const auto& file = entry.path(); + if (file.extension() != ".dkrreplay" || !ReplayLibraryFile(file)) + continue; + const auto metadata = ReadReplaySidecar(file); + if (!OwnReplayFile(file, metadata)) + continue; + LocalReplay item; + item.file = file; + std::error_code ec; + item.saved = entry.last_write_time(ec); + item.title = StoreText(metadata, "title", 120); + item.posted_owner = StoreText(metadata, "postedOwner", 96); + std::string record; + try { + const auto manifest = ReadReplaySummary(file); + const auto rules = StoreText(manifest, "ruleset", 48); + item.ruleset = rules; + if (rules.starts_with("adventure-")) { + const auto id = StoreText(manifest, "category", 40); + item.adventure_category = id; + const auto category = trial::adventure_for(id); + item.board = "adventure-" + id; + record = rules + ":" + id; + for (const auto& choice : trial::kAdventureCategories) + if (choice.goal == category) + item.course = choice.title; + } else { + const auto racer = manifest.value("racer", trial::kDiddy); + if (racer >= trial::kRacers.size()) + throw std::runtime_error("The replay racer is unsupported."); + item.racer = trial::kRacers[racer].name; + const auto vehicle = rules == trial::kLegacyRules ? "car" : StoreText(manifest, "vehicle", 16); + trial::Vehicle route_vehicle = trial::Vehicle::Car; + for (unsigned i = 0; i < trial::kVehicleIds.size(); ++i) { + if (trial::kVehicleIds[i] == vehicle) { + item.vehicle = trial::kVehicleNames[i]; + route_vehicle = static_cast(i); + } + } + if (item.vehicle.empty()) + throw std::runtime_error("The replay vehicle is unsupported."); + if (rules == trial::kLegacyRules) { + item.course = trial::kCourses.front().name; + item.board = trial::board_for(trial::kCourses.front(), route_vehicle, racer); + record = trial::kCourses.front().id; + } else if (rules == trial::kVanillaRules) { + if (const auto* course = trial::course_for(StoreText(manifest, "course", 64))) { + item.course = course->name; + item.board = trial::board_for(*course, route_vehicle, racer); + record = course->id; + } + } else { + item.track_id = StoreText(manifest, "trackId", 96); + item.track_hash = StoreText(manifest, "trackHash", 64); + item.course = item.track_id; + record = "custom:" + item.track_id + ":" + item.track_hash; + const auto found = + std::ranges::find(installed, item.course, &dkr::runtime::custom_tracks::ReplayTrack::id); + if (found != installed.end()) + item.course = found->name; + else + std::replace(item.course.begin(), item.course.end(), '-', ' '); + } + record += ":" + vehicle + ":" + std::to_string(racer); + const auto splits = manifest.value("splits", dkr::store::Json::array()); + const auto laps = + rules == trial::kCustomVariableLapsRules ? manifest.value("laps", 0U) : trial::kRetailLapCount; + if (laps > 0 && laps <= trial::kMaximumLapCount && splits.is_array() && splits.size() == laps) { + std::int64_t previous = 0; + for (const auto& value : splits) { + const auto end = value.get(); + if (end <= previous || end > LeaderboardNumber(manifest, "clockTicks")) { + item.best_lap = 0; + break; + } + const auto lap = end - previous; + item.best_lap = item.best_lap ? std::min(item.best_lap, lap) : lap; + previous = end; + } + } + } + item.time = LeaderboardNumber(manifest, "clockTicks"); + item.beat_ghost = item.time > 0 && item.time < LeaderboardNumber(metadata, "ghostTicks"); + item.has_attempt = ReplayHasRankedAttempt(manifest); + if (item.has_attempt) + item.board = StoreText(manifest, "board", 96); + item.practice = + manifest.value("practice", true) || PathUtf8(file.filename()).find("-Practice-") != std::string::npos; + item.valid = !item.course.empty(); + item.local_capture = item.valid && IsLocalReplayCapture(manifest) && + (!rules.starts_with("adventure-") || rules == trial::kAdventureRules); + item.can_ghost = item.valid && !rules.starts_with("adventure-"); + } catch (const std::exception&) { + // Keep malformed files visible so players can remove them. + } + if (item.title.empty()) + item.title = item.valid ? item.course : PathUtf8(file.filename()); + if (item.valid) { + const auto [best, inserted] = records.try_emplace(record, replays.size()); + if (inserted) { + item.personal_best = true; + } else { + auto& prior = replays[best->second]; + if (std::tie(item.time, item.saved, item.file) < std::tie(prior.time, prior.saved, prior.file)) { + prior.personal_best = false; + item.personal_best = true; + best->second = replays.size(); + } + } + } + replays.push_back(std::move(item)); + } + std::ranges::sort( + replays, [](const auto& a, const auto& b) { return a.saved != b.saved ? a.saved > b.saved : a.file > b.file; }); + return replays; +} + +const LocalReplay* FindLocalReplay(const std::filesystem::path& file) { + if (g_replay_library_profile != g_config_directory) + return nullptr; + const auto replay = std::ranges::find(g_local_replays, file, &LocalReplay::file); + return replay == g_local_replays.end() ? nullptr : &*replay; +} + +std::string LocalReplayDate(std::time_t time, const char* format) { + std::tm calendar{}; +#ifdef _WIN32 + if (localtime_s(&calendar, &time) != 0) + return {}; +#else + if (!localtime_r(&time, &calendar)) + return {}; +#endif + char date[40]{}; + std::strftime(date, sizeof(date), format, &calendar); + return date; +} + +std::string ReplayDate(std::filesystem::file_time_type saved) { + if (saved == std::filesystem::file_time_type::min()) + return {}; +#ifdef _MSC_VER + const auto stamp = std::chrono::clock_cast(saved); +#else + const auto stamp = std::chrono::file_clock::to_sys(saved); +#endif + const auto system_stamp = std::chrono::time_point_cast(stamp); + return LocalReplayDate(std::chrono::system_clock::to_time_t(system_stamp), "%Y-%m-%d"); +} + +void RenameLocalReplay(const std::filesystem::path& file, const std::string& title) { + CheckManagedReplayDirectory(file.parent_path()); + if (!ReplayLibraryFile(file)) + throw std::runtime_error("This replay is no longer in your library."); + auto metadata = ReadReplaySidecar(file); + metadata["title"] = title; + WriteReplaySidecar(file, metadata); +} + +void RemoveLocalReplay(const std::filesystem::path& file) { + CheckManagedReplayDirectory(file.parent_path()); + if (!ReplayLibraryFile(file) || !std::filesystem::remove(file)) + throw std::runtime_error("This replay could not be removed."); + for (const auto& sidecar : {ReplaySidecar(file), trial::portable_ghost_file(file)}) { + if (ReplayLibraryFile(sidecar)) { + std::error_code ec; + std::filesystem::remove(sidecar, ec); + } + } +} + +using ReplayPurgeSelection = std::map; + +ReplayPurgeSelection SelectReplayPurge(const std::vector& replays, bool include_bests, + bool include_unsubmitted) { + ReplayPurgeSelection selected; + for (const auto& replay : replays) { + if (dkr::library_ui::can_purge_replay(replay.personal_best, !replay.posted_owner.empty(), include_bests, + include_unsubmitted)) + selected.emplace(replay.file, replay.saved); + } + return selected; +} + +std::pair PurgeLocalReplays(const std::filesystem::path& directory, + const ReplayPurgeSelection& confirmed, bool include_bests, + bool include_unsubmitted) { + const auto current = SelectReplayPurge(ReadLocalReplayLibrary(directory), include_bests, include_unsubmitted); + std::size_t removed = 0; + for (const auto& [file, saved] : confirmed) { + const auto it = current.find(file); + if (it == current.end() || it->second != saved) + continue; + try { + RemoveLocalReplay(file); + ++removed; + } catch (const std::exception&) { + // Continue with other confirmed recordings when one is in use. + } + } + return {removed, confirmed.size() - removed}; +} + +void RefreshReplayLibrary() { + const auto profile = g_config_directory; + g_refresh_replay_library = false; + RankedJob([profile] { + auto replays = ReadLocalReplayLibrary(profile / "speedruns"); + return [profile, replays = std::move(replays)]() mutable { + if (profile == g_config_directory) { + g_replay_library_profile = profile; + g_local_replays = std::move(replays); + } + }; + }); +} diff --git a/runtime-recomp/src/game/library_ui/save_indicator.inl b/runtime-recomp/src/game/library_ui/save_indicator.inl index 2ff98aca..1613044f 100644 --- a/runtime-recomp/src/game/library_ui/save_indicator.inl +++ b/runtime-recomp/src/game/library_ui/save_indicator.inl @@ -26,52 +26,56 @@ PlaySavePreviewData PlayReadSavePreview(const std::filesystem::path& path) { return {{}, "Save preview unavailable. Check Save Manager."}; return {std::move(image), {}}; } -void DrawPlaySaveSummary(float width, bool live) { +void DrawPlaySaveSummary(float width, bool live, bool launching) { using namespace dkr::library_ui; namespace saves = dkr::runtime::saves; SaveScope scope = SaveScope::Vanilla; std::filesystem::path path; - bool shared_modded = false; const bool lobby = dkr::runtime::netplay::session().active(); if (live) { path = saves::runtime_save_path(); scope = running_save_scope(g_config_directory, path, saves::runtime_save_selection().online); - shared_modded = scope == SaveScope::Vanilla && dkr::session_content::running_modded.load(); - } else if (lobby) + } else if (lobby) { scope = SaveScope::Online; - else if (dkr::session_content::next_enabled.load()) { - const auto mods = g_legacy_imports.snapshot(); - for (const auto& catalogue : {mods.tracks, mods.characters}) - if (catalogue) - for (const auto& item : catalogue->tracks) - shared_modded |= item.enabled && !item.hidden; - for (const auto& item : g_code_library.view()->items) - shared_modded |= item.selected && item.enabled && item.approved && item.compatibility.empty(); - for (const auto& item : g_vehicle_library.view()->items) - shared_modded |= item.enabled; - for (const auto& item : dkr::runtime::custom_tracks::tracks()) - shared_modded |= item.enabled; - for (const auto& item : dkr::runtime::texture_packs::snapshot()) - shared_modded |= item.enabled && item.compatible; - shared_modded |= dkr::runtime::magic_codes::selected_mask() != 0; + } else if (dkr::session_content::next_enabled.load()) { + scope = SaveScope::Modded; + path = saves::personal_adventure_path(g_config_directory, true); + } + const char* heading = scope == SaveScope::Online ? "ONLINE ADVENTURE" + : scope == SaveScope::Modded ? "MODDED ADVENTURE" + : "VANILLA ADVENTURE"; + const auto heading_type = PaddockReading(16.F, true, 1.45F); + const auto heading_text = dkr::localisation::source(heading); + const float heading_width = std::ceil(PaddockMeasure(heading_type, heading_text)) + 8.F; + const float cloud_width = PlayCloudSwitchWidth() + kPlayCloudGap + kPlayCloudIconWidth; + const bool inline_cloud = width - heading_width >= 118.F + kPlayCloudGap + kPlayCloudIconWidth; + const bool cloud_locked = live || lobby || launching; + if (inline_cloud) { + ImGui::BeginGroup(); + auto position = ImGui::GetCursorScreenPos(); + position.y += (kPlayCloudControlHeight - heading_type.line) * 0.5F; + PaddockDrawRun(ImGui::GetWindowDrawList(), heading_type, position, PaddockCol(0xFFF6DA), heading_text.data(), + heading_text.data() + heading_text.size()); + ImGui::Dummy({heading_width, kPlayCloudControlHeight}); + ImGui::SameLine(0.F, 0.F); + DrawPlayCloudSaves(std::min(cloud_width, width - heading_width), cloud_locked); + ImGui::EndGroup(); + } else { + PaddockText(heading_type, PaddockRgb(0xFFF6DA), heading_text, width); + PaddockGap(4.F); + DrawPlayCloudSaves(width, cloud_locked); } - const auto indicator = shared_modded ? SaveScope::Modded : scope; - const char* heading = indicator == SaveScope::Online ? "ONLINE ADVENTURE" - : indicator == SaveScope::Modded ? "MODDED ADVENTURE" - : "OFFLINE ADVENTURE"; - PaddockText(PaddockReading(16.F, true, 1.45F), PaddockRgb(0xFFF6DA), dkr::localisation::source(heading), width); PaddockGap(6.F); const auto at = ImGui::GetCursorScreenPos(); auto* draw = ImGui::GetWindowDrawList(); draw->AddRectFilled(at, {at.x + 62.F, at.y + 22.F}, PaddockCol(0x041B26), 11.F); constexpr std::array colours{0x24D493, 0xFFC04D, 0x57CDE8}; for (int i = 0; i < 3; ++i) { - const bool active = int(indicator) == i + 1; + const bool active = int(scope) == i + 1; draw->AddCircleFilled({at.x + 11.F + 20.F * i, at.y + 11.F}, 6.F, PaddockCol(active ? colours[i] : 0x304752), 14); } - const auto save_caption = dkr::localisation::source( - shared_modded ? std::string_view("Modded game - shared personal save") : save_label(scope)); + const auto save_caption = dkr::localisation::source(save_label(scope)); const std::string label = dkr::localisation::format(live ? "save.using" : "save.next", {{"save", save_caption}}); const auto type = PaddockReading(14.F, true, 1.4F); const float label_width = std::max(1.F, width - 72.F); @@ -83,13 +87,13 @@ void DrawPlaySaveSummary(float width, bool live) { PaddockGap(6.F); std::string preview; if (scope == SaveScope::Vanilla) { - const auto& save = CachedSaveManagerView(); + const auto& save = CachedSaveManagerView().adventures[false]; preview = save.image ? dkr::localisation::save_preview(*save.image) - : std::string(dkr::localisation::source(save.adventure.exists + : std::string(dkr::localisation::source(save.info.exists ? "Save preview unavailable. Check Save Manager." - : "No offline Adventure save yet.")); - } else if (!live) { + : "No Vanilla Adventure save yet.")); + } else if (!live && scope == SaveScope::Online) { preview = std::string(dkr::localisation::source("The host supplies a separate online save when the match starts.")); } else if (path.empty()) @@ -119,12 +123,9 @@ void DrawPlaySaveSummary(float width, bool live) { : std::string(dkr::localisation::source("Reading this session's saved progress...")); } PaddockText(PaddockReading(14.F, false, 1.5F), PaddockRgb(0xB0C9CC), preview, width); - PaddockText( - PaddockReading(13.F, false, 1.5F), PaddockRgb(0xB0C9CC), - dkr::localisation::source( - live - ? "Ordinary offline mods share your personal Adventure. Online and development saves stay separate. Preview shows saved progress." - : "Ordinary offline mods share your personal Adventure. Online and development saves stay separate."), - width); + PaddockText(PaddockReading(13.F, false, 1.5F), PaddockRgb(0xB0C9CC), + dkr::localisation::source(live ? "Preview shows saved progress for this session." + : "Session Mods selects which Adventure save you use offline."), + width); PaddockGap(12.F); } diff --git a/runtime-recomp/src/game/library_ui/shared_page_ui.inl b/runtime-recomp/src/game/library_ui/shared_page_ui.inl index 56e62261..bfff35bc 100644 --- a/runtime-recomp/src/game/library_ui/shared_page_ui.inl +++ b/runtime-recomp/src/game/library_ui/shared_page_ui.inl @@ -1,3 +1,4 @@ +#include "leaderboards_page.inl" // One page router owns both surfaces. Live capability checks stay in each // service; presentation does not grant save/import/update permissions. struct SharedPlaySnapshot { @@ -18,12 +19,14 @@ bool LibraryContentInputCaptured() { void DrawSharedUiPage(float width, int page, bool live, const PlayPageContext* launcher = nullptr) { LibraryNavigationContentWindow(); const float top = ImGui::GetCursorPosY(); + static std::array previous_page{-1, -1}; // Paired SDL readbacks use the real live page branch inside the existing // authenticated, disposable layout harness. Normal startup cannot arm it. if (!live && !g_launcher_layout_root.empty()) { const char* surface = std::getenv("DKR_OWNED_CHECK_LAYOUT_SURFACE"); live = surface && std::string_view(surface) == "overlay"; } + const bool entered = std::exchange(previous_page[live ? 1 : 0], page) != page; g_store_in_game = live; if (DrawLibraryControlsFieldCheck(width)) { LibrarySurfaceProbe(live, page, width, ImGui::GetCursorPosY() - top); @@ -56,12 +59,12 @@ void DrawSharedUiPage(float width, int page, bool live, const PlayPageContext* l DrawSoundPage(width, live); else if (page == kPageControls) DrawControlsPage(width, live); - else if (page == kPageSaveManager) { - DrawPlayToolBack(width); + else if (page == kPageSaveManager) DrawSaveManagerPage(width, live); - } else if (page == kPageAchievements) { - DrawPlayToolBack(width); + else if (page == kPageAchievements) DrawAchievementsPage(width); + else if (page == dkr::library_ui::LeaderboardsPage) { + DrawLeaderboardsPage(width, entered, live); } else if (page == kPageOnlineMp) DrawOnlinePage(width, !live, live || play->rom_ready); else if (page == kPageModLibrary) @@ -87,6 +90,7 @@ void DrawSharedUiPage(float width, int page, bool live, const PlayPageContext* l ImGui::SetScrollY(ImGui::GetScrollMaxY()); LibrarySurfaceProbe(live, page, width, ImGui::GetCursorPosY() - top); g_launcher_rom = previous; - if (page != kPagePlay) + const bool save_workspace = page == kPageSaveManager && (g_saves_page.scope == 0 || g_saves_page.scope == 2); + if (page != kPagePlay && !save_workspace) ImGui::Dummy({0.F, 54.F}); } diff --git a/runtime-recomp/src/game/library_ui/speedrunning_options.inl b/runtime-recomp/src/game/library_ui/speedrunning_options.inl new file mode 100644 index 00000000..b8368759 --- /dev/null +++ b/runtime-recomp/src/game/library_ui/speedrunning_options.inl @@ -0,0 +1,335 @@ +namespace speed = dkr::runtime::speedrunning; +using RunOption = speed::Option; + +int RunPreference(RunOption key) { + return speed::options.get(key); +} + +std::string RunClock(std::int64_t ticks) { + auto time = LeaderboardTime(ticks); + if (RunPreference(RunOption::Precision) == 1) + time.pop_back(); + return time; +} + +struct RunCorner { + ImVec2 position, pivot; +}; + +RunCorner RunOverlayCorner(const ImGuiViewport& view, int corner) { + const auto inset = std::array{12.F, 22.F, 36.F}[RunPreference(RunOption::Inset)]; + const bool right = corner % 2, bottom = corner >= 2; + return {{view.WorkPos.x + (right ? view.WorkSize.x - inset : inset), + view.WorkPos.y + (bottom ? view.WorkSize.y - inset : inset + 24.F)}, + {float(right), float(bottom)}}; +} + +void SetRunPreference(RunOption key, int value) { + speed::options.set(key, value); + SaveSettings(); +} + +ImTextureID RunPreviewTexture() { +#if DKR_RUNTIME_HAS_RT64 + struct PreviewPixels { + int width = 0, height = 0; + std::unique_ptr rgba{nullptr, stbi_image_free}; + }; + static const auto pixels = [] { + PreviewPixels image; + image.rgba.reset(stbi_load_from_memory(reinterpret_cast(SpeedrunningHudPreview), + static_cast(SpeedrunningHudPreview_size), &image.width, + &image.height, nullptr, STBI_rgb_alpha)); + return image; + }(); + if (!pixels.rgba) + return {}; + if (!g_mod_store_renderer) + return reinterpret_cast( + dkr::store::overlay::image( + "speedrunning-hud-preview", pixels.width, pixels.height, + std::span(pixels.rgba.get(), std::size_t(pixels.width) * pixels.height * STBI_rgb_alpha)) + .id); + if (!g_speedrunning_preview_texture) { + auto* texture = SDL_CreateTexture(g_mod_store_renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, + pixels.width, pixels.height); + if (texture && SDL_UpdateTexture(texture, nullptr, pixels.rgba.get(), pixels.width * STBI_rgb_alpha) != 0) { + SDL_DestroyTexture(texture); + return {}; + } + if (texture) { + SDL_SetTextureScaleMode(texture, SDL_ScaleModeLinear); + SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND); + } + g_speedrunning_preview_texture = texture; + } + return reinterpret_cast(g_speedrunning_preview_texture); +#else + return {}; +#endif +} + +void PaintReplayController(ImDrawList* draw, ImVec2 base, const trial::Progress& state, float scale); + +void DrawRunHudPreview(float width, bool replay) { + const bool splits = RunPreference(RunOption::Splits) && (!replay || RunPreference(RunOption::ReplaySplits)); + const bool inputs = replay && RunPreference(RunOption::ReplayInputs); + const bool contrast = RunPreference(RunOption::Contrast); + const int detail = RunPreference(RunOption::SplitDetail); + const int upcoming = detail == 2 ? 0 : RunPreference(RunOption::Upcoming); + const int comparison = RunPreference(RunOption::Comparison); + OlHeading("HUD Preview", 18.F, kOlCream, width); + const ImVec2 origin = ImGui::GetCursorScreenPos(); + const float height = width * 9.F / 16.F; + const ImVec2 end{origin.x + width, origin.y + height}; + const float scale = std::clamp(width / 530.F, .54F, 1.4F); + auto* draw = ImGui::GetWindowDrawList(); + const auto type = OlRead(14.F * scale); + if (const auto texture = RunPreviewTexture()) + draw->AddImageRounded(texture, origin, end, {0.F, 0.F}, {1.F, 1.F}, IM_COL32_WHITE, 9.F); + else + draw->AddRectFilled(origin, end, IM_COL32(15, 45, 62, 255), 9.F); + draw->AddRect(origin, end, PaddockCol(kOlSoft, 87), 9.F); + draw->PushClipRect(origin, end, true); + const float inset = scale * std::array{6.F, 11.F, 17.F}[RunPreference(RunOption::Inset)]; + const auto card_origin = [&](int corner, float w, float h) { + return ImVec2{corner % 2 ? end.x - inset - w : origin.x + inset, + corner >= 2 ? end.y - inset - h : origin.y + inset}; + }; + if (splits) { + const auto clock = RunClock(replay ? 1036 : 8009); + const std::array comparisons{"PB", "WR", "Best segments", ""}; + const auto pace = + std::string(comparisons[comparison]) + (RunPreference(RunOption::DeltaWords) ? " 0.38 ahead" : " -0.38"); + std::array, 6> lines; + std::size_t rows = 0; + const auto add_line = [&](std::string_view text, unsigned color) { lines[rows++] = {text, color}; }; + add_line(replay ? "REPLAY · LAP 1 / 3" : "LIVE SPLITS", kOlAmber); + add_line(clock, kOlCream); + if (detail != 2) { + add_line(detail ? "Ancient Lake" : "Dino Domain · 2:13", kOlInk); + if (comparison != 3) + add_line(pace, kOlGoText); + if (upcoming) + add_line("Next · Fossil Canyon", kOlSoft); + if (upcoming == 2) + add_line("Then · Jungle Falls", kOlSoft); + } + const auto visible_lines = std::span(lines).first(rows); + const float padding = 7.F * scale; + float desired_width = scale * std::array{155.F, 177.F, 195.F}[RunPreference(RunOption::HudSize)]; + for (const auto& [value, color] : visible_lines) { + const auto measured = + type.font->CalcTextSizeA(type.size, FLT_MAX, 0.F, value.data(), value.data() + value.size()); + desired_width = std::max(desired_width, measured.x + 2.F * padding); + } + const float x = std::min(width - 2.F * inset, desired_width); + const float lh = type.size + 4.F * scale; + const float h = rows * lh + 12.F; + const auto pos = card_origin(RunPreference(RunOption::SplitPosition), x, h); + const int alpha = contrast ? 255 : RunPreference(RunOption::Background) * 255 / 100; + draw->AddRectFilled(pos, {pos.x + x, pos.y + h}, IM_COL32(6, 18, 31, alpha), 7.F); + auto line = ImVec2{pos.x + padding, pos.y + 6.F}; + draw->PushClipRect(pos, {pos.x + x, pos.y + h}, true); + for (const auto& [value, color] : visible_lines) { + draw->AddText(type.font, type.size, line, PaddockCol(color), value.data(), value.data() + value.size()); + line.y += lh; + } + draw->PopClipRect(); + } + if (inputs) { + int corner = RunPreference(RunOption::InputPosition); + if (splits && corner == RunPreference(RunOption::SplitPosition)) + corner ^= 1; + const float input_scale = scale * std::array{.40F, .50F, .60F}[RunPreference(RunOption::InputSize)]; + const ImVec2 size{232.F * input_scale, 140.F * input_scale}; + const auto point = card_origin(corner, size.x, size.y); + const int alpha = contrast ? 255 : 212; + draw->AddRectFilled(point, {point.x + size.x, point.y + size.y}, IM_COL32(6, 18, 31, alpha), 7.F); + const trial::Progress sample{.buttons = 0x8000, .stick_x = 25, .stick_y = 35}; + PaintReplayController(draw, point, sample, input_scale); + } + draw->PopClipRect(); + ImGui::Dummy({width, height}); +} + +void DrawRunOptionPanel(int group, int panel, float width) { + static constexpr std::array headings{ + std::array{"Timer display", "Split comparisons"}, std::array{"HUD layout", "Accessibility"}, + std::array{"Appearance", "Race information"}, std::array{"Replay overlays", "Playback"}, + std::array{"Finish details", "Celebrations"}, std::array{"Run setup", "Replay library"}, + }; + DrawOlCard( + width, OlPanelLook{}, + [&](float inner) { + OlHeading(headings[group][panel], 20.F, kOlCream, inner); + PaddockGap(4.F); + const auto id = [](RunOption key) { return speed::settings[static_cast(key)].key.data(); }; + const auto choice = [&](RunOption key, const char* title, std::initializer_list labels, + bool disabled = false) { + int value = RunPreference(key); + if (SettingsDropdown(id(key), title, &value, labels, inner, disabled)) + SetRunPreference(key, value); + }; + const auto toggle = [&](RunOption key, const char* title, const char* help) { + bool value = RunPreference(key) != 0; + if (OlSwitchRow(id(key), title, help, &value, inner, false)) + SetRunPreference(key, value); + }; + const auto range = [&](RunOption key, const char* title, int minimum) { + int value = RunPreference(key); + if (SettingsRange(id(key), title, &value, minimum, 100, inner, + [](int percent) { return SettingsRangeValue{std::to_string(percent), "%"}; })) + SetRunPreference(key, value); + }; + const std::initializer_list corners{"Top left", "Top right", "Bottom left", "Bottom right"}; + const std::initializer_list sizes{"Small", "Standard", "Large"}; + switch (group) { + case 0: + if (panel == 0) { + toggle(RunOption::Splits, "Show Live Splits", "Show the speedrunning timer and splits."); + const bool hidden = !RunPreference(RunOption::Splits); + choice(RunOption::SplitPosition, "Position", corners, hidden); + choice(RunOption::SplitDetail, "Detail", {"Detailed", "Compact", "Timer only"}, hidden); + choice(RunOption::Precision, "Time precision", {"Milliseconds", "Hundredths"}, hidden); + } else { + const bool timer = !RunPreference(RunOption::Splits) || RunPreference(RunOption::SplitDetail) == 2; + choice(RunOption::Comparison, "Compare against", + {"Personal Best", "World Record", "Best Segments", "Off"}, timer); + choice(RunOption::Upcoming, "Upcoming splits", {"Hide", "Next split", "Next two splits"}, timer); + } + break; + case 1: + if (panel == 0) { + choice(RunOption::HudSize, "Split HUD size", sizes); + choice(RunOption::Inset, "Screen-edge padding", {"Narrow", "Normal", "Wide"}); + range(RunOption::Background, "Background opacity", 55); + } else { + toggle(RunOption::Contrast, "High contrast HUD", "Use an opaque background and brighter text."); + toggle(RunOption::DeltaWords, "Label deltas ahead / behind", + "Use words as well as colour to show pace."); + toggle(RunOption::ReducedMotion, "Reduce overlay animations", + "Show static celebrations and loading indicators."); + } + break; + case 2: + if (panel == 0) { + choice(RunOption::GhostStyle, "Ghost appearance", {"Translucent racer", "Outline marker"}); + range(RunOption::GhostOpacity, "Ghost opacity", 0); + toggle(RunOption::GhostNames, "Show ghost racer names", + "Display the credited Discord name above leaderboard ghosts."); + } else { + choice(RunOption::GhostProximity, "When the ghost is close", {"Keep visible", "Fade out"}); + toggle(RunOption::GhostGap, "Show time gap to ghost", + "Compare your lap crossing with the ghost's."); + toggle(RunOption::GhostMarker, "Ghost marker on minimap", + "Show the ghost's position on the course map."); + } + break; + case 3: + if (panel == 0) { + toggle(RunOption::ReplayInputs, "Show controller inputs", + "Display the recorded N64 controller inputs."); + toggle(RunOption::ReplaySplits, "Show Live Splits in replays", + "Use your Live Splits layout during playback."); + const bool no_controller = !RunPreference(RunOption::ReplayInputs); + choice(RunOption::InputPosition, "Controller position", corners, no_controller); + choice(RunOption::InputSize, "Controller size", sizes, no_controller); + } else { + choice(RunOption::ReplaySpeed, "Starting speed", {"0.5x", "1x", "1.5x", "2x"}); + choice(RunOption::PlaybackControls, "Playback controls", {"Always show", "Auto-hide"}); + choice(RunOption::SeekStep, "Seek step", {"5 seconds", "10 seconds", "30 seconds"}); + toggle(RunOption::StartPaused, "Open replays paused", "Wait for Play after the replay loads."); + toggle(RunOption::LapMarkers, "Show timeline markers", + "Show lap or split markers on the timeline."); + } + break; + case 4: + if (panel == 0) { + toggle(RunOption::LapDelta, "Show lap time comparisons", + "Show your lap time and gap to the selected reference."); + toggle(RunOption::FinishSummary, "Show finish time card", "Show your time when the run ends."); + } else { + choice(RunOption::Celebration, "Podium celebrations", {"Full screen", "Compact", "Off"}); + choice(RunOption::CelebrationScope, "Celebrate", + {"Top-three pace", "Record pace only", "Personal bests and podiums"}, + RunPreference(RunOption::Celebration) == 2); + range(RunOption::CueVolume, "Speedrunning cue volume", 0); + } + break; + case 5: + if (panel == 0) { + choice(RunOption::ReturnTo, "After a run, open", {"Last Run", "Replays"}); + toggle(RunOption::RememberSetup, "Remember last run setup", + "Keep your last course, vehicle, racer, and challenge."); + toggle(RunOption::ConfirmRestart, "Confirm before restarting", + "Ask before replacing the current attempt."); + } else { + choice(RunOption::Retention, "Keep new local replays", + {"All completed runs", "Personal bests and pending posts"}); + choice(RunOption::ReplaySort, "Default replay order", + {"Newest first", "Personal bests first", "Track name"}); + toggle(RunOption::PostPrompt, "Offer to post eligible personal bests", + "Show the posting action in the Last Run card."); + } + break; + } + }, + 16.F); +} + +void DrawSpeedrunningOptions(float width) { + static int group = 0; + static const std::vector groups{"Live Splits", "HUD & Accessibility", "Ghosts", + "Replay Theatre", "Finish & Cues", "Run & Library"}; + group = StoreTabLine(groups, group, width, "speedrunning-options", true); + PaddockGap(8.F); + + constexpr float gap = 16.F; + constexpr float minimum_pair = 640.F; + const auto draw_row = [&](float row_width, std::span columns, auto&& draw_column) { + const auto at = ImGui::GetCursorScreenPos(); + float left = at.x, bottom = at.y; + for (std::size_t i = 0; i < columns.size(); ++i) { + ImGui::SetCursorScreenPos({left, at.y}); + ImGui::BeginGroup(); + draw_column(i, columns[i]); + ImGui::EndGroup(); + bottom = std::max(bottom, ImGui::GetItemRectMax().y); + left += columns[i] + gap; + } + ImGui::SetCursorScreenPos(at); + ImGui::Dummy({row_width, bottom - at.y}); + }; + const auto draw_settings = [&](float settings_width) { + if (settings_width >= minimum_pair) { + const float column = (settings_width - gap) * .5F; + draw_row(settings_width, std::array{column, column}, + [&](std::size_t panel, float size) { DrawRunOptionPanel(group, static_cast(panel), size); }); + } else { + DrawRunOptionPanel(group, 0, settings_width); + PaddockGap(gap); + DrawRunOptionPanel(group, 1, settings_width); + } + }; + const auto draw_preview = [&](float preview_width) { + DrawOlCard(preview_width, OlPanelLook{}, [&](float inner) { DrawRunHudPreview(inner, group == 3); }, 16.F); + }; + + const bool preview = group == 0 || group == 1 || group == 3; + if (preview && width >= 740.F) { + const float preview_width = (width - gap) * .46F; + draw_row(width, std::array{width - gap - preview_width, preview_width}, [&](std::size_t column, float size) { + if (column == 0) + draw_settings(size); + else + draw_preview(size); + }); + } else { + draw_settings(width); + if (preview) { + PaddockGap(gap); + draw_preview(width); + } + } +} diff --git a/runtime-recomp/src/game/library_ui/speedrunning_welcome.inl b/runtime-recomp/src/game/library_ui/speedrunning_welcome.inl new file mode 100644 index 00000000..fcd54c09 --- /dev/null +++ b/runtime-recomp/src/game/library_ui/speedrunning_welcome.inl @@ -0,0 +1,94 @@ +void DrawSpeedrunningWelcome(bool entered, bool signed_in, bool staff, const dkr::store::Json* catalogue) { + constexpr const char* popup = "Welcome to Speedrunning!"; + static std::filesystem::path acknowledged; + const auto marker = g_config_directory / "speedrunning-welcome-seen"; + std::error_code ec; + if (entered && acknowledged != marker && !std::filesystem::is_regular_file(marker, ec)) + ImGui::OpenPopup(popup); + if (!ImGui::IsPopupOpen(popup)) + return; + + const auto viewport = ImGui::GetMainViewport()->WorkSize; + const float modal_width = std::min(790.F, viewport.x - 38.F); + ImGui::SetNextWindowSize({modal_width, 0.F}, ImGuiCond_Always); + constexpr ImGuiWindowFlags flags = ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize; + if (!BeginPaddedModal(popup, flags)) + return; + + const float width = ImGui::GetContentRegionAvail().x; + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {10.F, 5.F}); + ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 0, 0)); + ImGui::BeginChild("Speedrunning guide", {width, std::min(405.F, viewport.y * .62F)}, false); + const float body = ImGui::GetContentRegionAvail().x; + OlParagraph("Fancy getting a time on the leaderboards? Use the tabs across the top to have a look around. " + "Here's how to get your first run posted.", + 16.F, kOlInk, body); + PaddockGap(9.F); + + const bool columns = body > 630.F; + const float column = columns ? (body - 22.F) / 2.F : body; + ImGui::BeginGroup(); + OlParagraph("Where to find things", 18.F, kOlAmber, column, true, 1.25F); + PaddockGap(3.F); + for (const auto* line : {"Top Players — See who's leading overall and how the points work.", + "Vanilla Tracks — Check the times for the original tracks.", + "Custom Tracks — Check the times for tracks made by the community.", + "Full Game — See runs for categories like Any%, 100% and All Trophy Races.", + "Runs — Start a run under Run. My Submitted Runs shows how your posts are getting on.", + "Replays (under Runs) — Watch your saved runs, race a ghost or post an eligible time."}) { + OlParagraph(line, 15.F, kOlSoft, column, false, 1.3F); + PaddockGap(2.F); + } + if (staff) + OlParagraph("Review Runs — This is where mods and admins can watch and review verified runs.", 15.F, kOlSoft, + column, false, 1.3F); + ImGui::EndGroup(); + + if (columns) + ImGui::SameLine(0.F, 22.F); + else + PaddockGap(8.F); + ImGui::BeginGroup(); + OlParagraph("Posting your first run", 18.F, kOlAmber, column, true, 1.25F); + PaddockGap(3.F); + for ( + const auto* step : + {"1. Sign in with Discord before you start a run you want to post. Once you're signed in, come back to the Launcher.", + "2. Go to Runs > Run, pick a track or a Full Game category and hit Start Run.", + "3. When you finish, hit Post to Leaderboard if it's there. You can also do this from Runs > Replays. " + "Check Runs > My Submitted Runs to see the status."}) { + OlParagraph(step, 15.F, kOlSoft, column, false, 1.3F); + PaddockGap(3.F); + } + ImGui::EndGroup(); + PaddockGap(10.F); + OlParagraph("Just having a go? You can race without signing in. Local runs stay on your device.", 15.F, kOlInk, + body); + if (catalogue && catalogue->value("canClaimLocal", false)) + OlParagraph("You can link an eligible local run to your Discord account from Runs > Replays.", 15.F, kOlSoft, + body); + ImGui::EndChild(); + ImGui::PopStyleColor(); + ImGui::PopStyleVar(); + + PaddockGap(10.F); + const bool dismiss = OlButton("Got it", OlTone::Go) || ImGui::IsKeyPressed(ImGuiKey_Escape, false) || + ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false); + bool login = false; + if (!signed_in) { + ImGui::SameLine(); + login = OlButton("Sign in with Discord"); + } + if (dismiss || login) { + acknowledged = marker; + try { + dkr::updates::durable_write(marker, "seen\n"); + } catch (const std::exception&) { + // Keep the acknowledgement for this session if the profile is read-only. + } + if (login) + dkr::store::service().login(); + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} diff --git a/runtime-recomp/src/game/library_ui/submitted_runs.inl b/runtime-recomp/src/game/library_ui/submitted_runs.inl new file mode 100644 index 00000000..9cecb8c8 --- /dev/null +++ b/runtime-recomp/src/game/library_ui/submitted_runs.inl @@ -0,0 +1,206 @@ +struct SubmissionQuota { + std::int64_t remaining; + std::int64_t limit; + std::int64_t next_slot; +}; + +std::optional ReadSubmissionQuota(const dkr::store::Json& listing) { + const auto quota = listing.find("submissionQuota"); + if (quota == listing.end() || !quota->is_object()) + return {}; + const auto limit = LeaderboardNumber(*quota, "maxRuns"); + const auto observed = RecordUnix(*quota, "observedAt"); + const auto releases = quota->find("releasesAt"); + if (limit <= 0 || observed <= 0 || releases == quota->end() || !releases->is_array() || + releases->size() > static_cast(limit)) + return {}; + const auto elapsed = + std::chrono::duration_cast(std::chrono::steady_clock::now() - g_ranked_runs_received) + .count(); + const auto now = observed + elapsed; + SubmissionQuota slots{limit, limit, 0}; + for (const auto& release : *releases) { + if (!release.is_number_integer()) + continue; + const auto stamp = release.get(); + if (stamp <= now) + continue; + --slots.remaining; + if (!slots.next_slot || stamp < slots.next_slot) + slots.next_slot = stamp; + } + return slots; +} + +void DrawSubmissionQuota(float width, const SubmissionQuota& quota) { + const auto time = quota.next_slot > 0 + ? LocalReplayDate(static_cast(quota.next_slot), "%d %b, %H:%M:%S") + : std::string{}; + const bool has_next_slot = !time.empty(); + constexpr float gap = 20.F; + const float meter_width = std::min(width, 294.F); + const bool inline_next = has_next_slot && width >= meter_width + gap + 215.F; + ImGui::BeginGroup(); + OlHeading(std::to_string(quota.remaining) + " / " + std::to_string(quota.limit), 27.F, kOlCream, meter_width, 1.2F); + OlParagraph("Submissions left", 14.F, kOlSoft, meter_width, true, 1.25F); + const auto meter = ImGui::GetCursorScreenPos(); + auto* draw = ImGui::GetWindowDrawList(); + const float fraction = static_cast(quota.remaining) / static_cast(quota.limit); + PaddockFill(draw, meter, {meter.x + meter_width, meter.y + 6.F}, PaddockRound(3.F), PaddockCol(0x254658U)); + if (quota.remaining > 0) + PaddockFill(draw, meter, {meter.x + meter_width * fraction, meter.y + 6.F}, PaddockRound(3.F), + PaddockCol(kOlGo)); + ImGui::Dummy({meter_width, 6.F}); + ImGui::EndGroup(); + if (has_next_slot) { + if (inline_next) + ImGui::SameLine(0.F, gap); + const float next_width = inline_next ? width - meter_width - gap : width; + ImGui::BeginGroup(); + OlParagraph("Next slot opens", 14.F, kOlSoft, next_width, true, 1.2F); + OlParagraph(time + " (local time)", 16.F, kOlInk, next_width, true, 1.2F); + ImGui::EndGroup(); + } +} + +struct SubmittedRunStatus { + std::string_view id; + const char* label; + PaddockTone tone; +}; + +constexpr std::array kSubmittedRunStatuses{ + SubmittedRunStatus{"uploading", "Upload incomplete", PaddockTone::Warning}, + SubmittedRunStatus{"queued", "Waiting for verification", PaddockTone::Neutral}, + SubmittedRunStatus{"verified", "Awaiting review", PaddockTone::Warning}, + SubmittedRunStatus{"published", "Published", PaddockTone::On}, + SubmittedRunStatus{"rejected", "Rejected", PaddockTone::Warning}, +}; + +void DrawSubmittedRun(float width, const dkr::store::Json& run, float status_width, float watch_width) { + const auto id = StoreText(run, "id", 96); + if (id.empty()) + return; + + const auto state = StoreText(run, "state", 24); + const auto badge = std::ranges::find(kSubmittedRunStatuses, state, &SubmittedRunStatus::id); + const auto label = + dkr::localisation::source(badge == kSubmittedRunStatuses.end() ? "Status unavailable" : badge->label); + const auto tone = badge == kSubmittedRunStatuses.end() ? PaddockTone::Neutral : badge->tone; + const auto verified_ticks = LeaderboardNumber(run, "ticks"); + const auto ticks = verified_ticks ? verified_ticks : LeaderboardNumber(run, "claimedTicks"); + const auto time = ticks > 0 ? LeaderboardTime(ticks) : std::string("—"); + const auto vehicle = StoreText(run, "vehicle", 24); + std::string metadata = + vehicle == "mixed" ? std::string(dkr::localisation::source("Full Game")) : LeaderboardVehicle(vehicle); + const auto submitted_at = RecordUnix(run, "createdAt"); + const auto date = submitted_at > 0 ? LocalReplayDate(static_cast(submitted_at), "%d %b %Y") : ""; + for (const auto& part : + {date, run.value("linkedLocal", false) ? std::string(dkr::localisation::source("Linked local run")) + : std::string{}}) { + if (!part.empty()) { + if (!metadata.empty()) + metadata += " · "; + metadata += part; + } + } + const auto title = StoreText(run, "title", 120); + OlPanelLook look; + look.ring_width = 1.F; + ImGui::PushID(id.c_str()); + DrawOlCard( + width, look, + [&](float inner) { + constexpr float gap = 10.F; + const float time_width = + std::min(inner, std::max(104.F, PaddockMeasure(OlSignType(19.F, 1.25F), time) + 4.F)); + const float action_width = time_width + status_width + watch_width + 2.F * gap; + const bool inline_actions = inner >= action_width + gap + 216.F; + const float title_width = inline_actions ? inner - action_width - gap : inner; + ImGui::BeginGroup(); + OlHeading(title, 20.F, kOlCream, title_width, 1.25F); + if (!metadata.empty()) + OlParagraph(metadata, 14.F, kOlSoft, title_width, false, 1.2F); + ImGui::EndGroup(); + if (inline_actions) + ImGui::SameLine(0.F, gap); + ImGui::BeginGroup(); + OlHeading(time, 19.F, kOlInk, time_width, 1.25F); + if (!verified_ticks && ticks > 0) + OlParagraph("Recorded time", 13.F, kOlSoft, time_width, false, 1.2F); + ImGui::EndGroup(); + + const auto badge_label = + PaddockEllipsize(PaddockReading(11.F, true, 1.5F), label, std::max(1.F, inner - 27.F)); + const auto size = PaddockBadgeSize(badge_label); + const float badge_width = size.x; + const bool inline_badge = time_width + gap + (inline_actions ? status_width : badge_width) <= inner; + if (inline_badge) + ImGui::SameLine(0.F, gap); + const auto origin = ImGui::GetCursorScreenPos(); + PaddockBadge(ImGui::GetWindowDrawList(), {origin.x, origin.y + (34.F - size.y) * .5F}, badge_label, tone); + ImGui::Dummy({inline_actions ? status_width : std::min(badge_width, inner), 34.F}); + + if (state != "uploading") { + const float used = + (inline_badge ? time_width + gap : 0.F) + (inline_actions ? status_width : badge_width); + if (used + gap + watch_width <= inner) + ImGui::SameLine(0.F, gap); + const OlDisabled launch(DialogJobRunning() || !CanLaunchLeaderboardReplay()); + if (OlButton("Watch replay", OlTone::Plain, std::min(watch_width, inner), nullptr, 34.F)) + WatchLeaderboardReplay(id, true); + StoreControlFocus(); + } + for (const auto* field : {"notes", "reason"}) + if (const auto value = StoreText(run, field, 600); !value.empty()) + OlParagraph(value, 14.F, kOlSoft, inner, false, 1.25F); + }, + 12.F); + ImGui::PopID(); +} + +void DrawSubmittedRuns(float width) { + const auto owner = RankedRunsOwner(); + const auto rows = g_ranked_runs.find("runs"); + const bool loaded = !owner.empty() && g_ranked_runs_owner == owner && !g_ranked_runs_review && + rows != g_ranked_runs.end() && rows->is_array(); + const auto quota = loaded ? ReadSubmissionQuota(g_ranked_runs) : std::nullopt; + + const auto spacing = ImGui::GetStyle().ItemSpacing; + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {spacing.x, 7.F}); + DrawOlCard( + width, OlPanelLook{}, + [&](float inner) { + OlHeading("My Submitted Runs", 24.F, kOlCream, inner); + if (owner.empty()) { + OlParagraph("Sign in with Discord to see your submitted runs.", 15.F, kOlSoft, inner); + const OlDisabled busy(DialogJobRunning()); + if (OlButton("Sign in with Discord", OlTone::Go)) + dkr::store::service().login(); + StoreControlFocus(); + return; + } + if (quota) + DrawSubmissionQuota(inner, *quota); + if (loaded) { + OlParagraph( + "The leaderboard host prepares videos for review. You can close DKR-R once your upload finishes.", + 14.F, kOlSoft, inner, false, 1.25F); + if (rows->empty()) + OlParagraph("You haven't submitted a run yet.", 15.F, kOlInk, inner); + } else { + OlParagraph(DialogJobRunning() ? "Loading submitted runs..." : "Use Refresh to check for runs.", 15.F, + kOlSoft, inner); + } + }, + 14.F); + if (loaded && !rows->empty()) { + float status_width = PaddockBadgeSize(dkr::localisation::source("Status unavailable")).x; + for (const auto& status : kSubmittedRunStatuses) + status_width = std::max(status_width, PaddockBadgeSize(dkr::localisation::source(status.label)).x); + const float watch_width = OlButtonWidth("Watch replay"); + for (const auto& run : *rows) + DrawSubmittedRun(width, run, status_width, watch_width); + } + ImGui::PopStyleVar(); +} diff --git a/runtime-recomp/src/game/lobby_controls.inl b/runtime-recomp/src/game/lobby_controls.inl index 13e85900..680f685e 100644 --- a/runtime-recomp/src/game/lobby_controls.inl +++ b/runtime-recomp/src/game/lobby_controls.inl @@ -227,7 +227,7 @@ void DrawOlPartyStart(float width, const OnlineFrame& frame) { if (host || watcher) { ImGui::SetCursorScreenPos(pair ? ImVec2{at.x + button + 10.F, at.y} : ImVec2{at.x, at.y + 62.F}); const bool disabled = OlPartyChanging(frame) || (!host && watcher && !live); - const bool waiting_ready = g_ol_party.save_ready && + const bool waiting_ready = !SharedSaveBusy() && g_ol_party.save_ready && std::count_if(frame.view.room.players.begin(), frame.view.room.players.end(), [](const auto& p) { return p.occupied; }) >= 2 && std::none_of(frame.view.room.players.begin(), frame.view.room.players.end(), diff --git a/runtime-recomp/src/game/localisation/imgui_ui.hpp b/runtime-recomp/src/game/localisation/imgui_ui.hpp index 0e5185cb..2a53523b 100644 --- a/runtime-recomp/src/game/localisation/imgui_ui.hpp +++ b/runtime-recomp/src/game/localisation/imgui_ui.hpp @@ -1,7 +1,9 @@ #pragma once #include "service.hpp" +#include "../dialog_style.hpp" #include "imgui.h" #include "imgui_internal.h" +#include #include #include #include @@ -66,6 +68,7 @@ template void UiTextColored(const ImVec4& colour, T&& f } } template void UiSetTooltip(T&& format, Args&&... args) { + const dkr::runtime::ui::ScopedDialogStyle style({12.0F, 8.0F}, 10.0F); if constexpr (sizeof...(Args) > 0) { SetTooltip(LocalisedUi::format_copy(std::forward(format)).data(), std::forward(args)...); } else { @@ -147,6 +150,12 @@ bool UiSelectable(T&& label, bool* selected, ImGuiSelectableFlags flags = 0, con return Selectable(shown.c_str(), selected, flags, size); } template bool UiBeginPopupModal(T&& label, bool* open = nullptr, ImGuiWindowFlags flags = 0) { + // Custom dialogs supply their chrome before calling BeginPopupModal. + std::optional dialog_style; + const auto& current = GetStyle(); + if ((current.WindowRounding <= 0.0F || current.WindowPadding.x <= 0.0F || current.WindowPadding.y <= 0.0F) && + IsPopupOpen(label)) + dialog_style.emplace(); // Popup identity must match existing OpenPopup()/IsPopupOpen() calls. const bool visible = BeginPopupModal(label, open, flags); if constexpr (LocalisedUi::caption_array) { diff --git a/runtime-recomp/src/game/localisation/literal_ui.inl b/runtime-recomp/src/game/localisation/literal_ui.inl index 665555d8..af459168 100644 --- a/runtime-recomp/src/game/localisation/literal_ui.inl +++ b/runtime-recomp/src/game/localisation/literal_ui.inl @@ -56,14 +56,14 @@ template bool UiPaddockTextLink(T&& label) { const auto shown = LocalisedUi::widget(std::forward(label)); return PaddockTextLink(shown.c_str()); } -template float UiPaddockSectionTabWidth(T&& label) { +template float UiPaddockSectionTabWidth(T&& label, bool compact = false) { // Section tabs are owned registry captions, including counted headings. const auto shown = dkr::localisation::label(std::string_view(label)); - return PaddockSectionTabWidth(shown.c_str()); + return PaddockSectionTabWidth(shown.c_str(), compact); } -template bool UiPaddockSectionTab(T&& label, bool open, float width = 0.F) { +template bool UiPaddockSectionTab(T&& label, bool open, float width = 0.F, bool compact = false) { const auto shown = dkr::localisation::label(std::string_view(label)); - return PaddockSectionTab(shown.c_str(), open, width); + return PaddockSectionTab(shown.c_str(), open, width, compact); } template bool UiPaddockCheckbox(const char* id, T&& label, bool* value, float width, diff --git a/runtime-recomp/src/game/localisation/settings_ui.inl b/runtime-recomp/src/game/localisation/settings_ui.inl index 20fb19e2..6137f931 100644 --- a/runtime-recomp/src/game/localisation/settings_ui.inl +++ b/runtime-recomp/src/game/localisation/settings_ui.inl @@ -10,12 +10,11 @@ void DrawLanguageSetting(float width) { if (preference() == choices[i].code) selected = int(i + 1); } - PaddockGap(14.F); const auto caption = text("common.language"); if (SettingsDropdown("launcher-language", caption, &selected, options, width)) { if (select(selected == 0 ? "auto" : choices[std::size_t(selected - 1)].code)) SaveSettings(); } - PaddockGap(6.F); + PaddockGap(5.F); PaddockText(PaddockReading(13.F, false, 1.5F), PaddockRgb(0xABC0CC), text("common.language_help"), width); } diff --git a/runtime-recomp/src/game/mod_library/website/assets/adventure-catalogue.js b/runtime-recomp/src/game/mod_library/website/assets/adventure-catalogue.js new file mode 100644 index 00000000..e1ea38cc --- /dev/null +++ b/runtime-recomp/src/game/mod_library/website/assets/adventure-catalogue.js @@ -0,0 +1,15 @@ +// Stage names and order from the community LiveSplit route templates. +export const adventureCatalogue = [ + {"id": "any-percent", "title": "Any%", "summary": "Beat the final Wizpig race.", "stages": ["Enter Wizpig 1", "Wizpig 1", "Dino 2", "Enter FFL", "T.T. Stomp", "Wizpig 2"]}, + {"id": "100-percent", "title": "100%", "summary": "Complete the Adventure checklist and beat Wizpig.", "stages": ["Overworld", "Fire Mountain", "Dino 2", "Snowflake 1", "Sherbet 1", "Darkwater Beach", "Sherbet Trophy", "Sherbet 2", "Icicle Pyramid", "Snow Trophy", "Snowflake 2", "Dino Trophy", "Dragon Trophy", "Dragon 1", "Smokey Castle", "Dragon 2", "Wizpig 1", "FFL", "Wizpig 2"]}, + {"id": "any-percent-glitchless", "title": "Any% Glitchless", "summary": "Complete the regular Adventure route.", "stages": ["Overworld", "Dino 1", "Fire Mountain", "Dino 2", "Dino Trophy", "Car Challenge", "Snow 1", "Icicle Pyramid", "Snow 2", "Snow Trophy", "Hover Challenge", "Sherbet 1", "Darkwater Beach", "Sherbet 2", "Sherbet Trophy", "Plane Challenge", "Dragon 1", "Smokey Castle", "Dragon 2", "Dragon Trophy", "Wizpig 1", "Future Fun Land 1", "Future Fun Land 2", "Wizpig 2"]}, + {"id": "all-bosses", "title": "All Bosses", "summary": "Win six boss rematches from a completed Adventure save.", "stages": ["Tricky", "Bluey", "Bubbler", "Smokey", "Wizpig 1", "Wizpig 2"]}, + {"id": "all-minigames", "title": "All Minigames", "summary": "Win all four minigames in Tracks Mode.", "stages": ["Darkwater Beach", "Fire Mountain", "Icicle Pyramid", "Smokey Castle"]}, + {"id": "all-trophy-races", "title": "All Trophy Races", "summary": "Finish all five Trophy sets in Tracks Mode.", "stages": ["Ancient Lake", "Fossil Canyon", "Jungle Falls", "Hot Top Volcano", "Whale Bay", "Pirate Lagoon", "Crescent Island", "Treasure Caves", "Everfrost Peak", "Walrus Cove", "Snowball Valley", "Frosty Village", "Boulder Canyon", "Greenwood Village", "Windmill Plains", "Haunted Woods", "Spacedust Alley", "Darkmoon Caverns", "Star City", "Spaceport Alpha"]}, + {"id": "all-trophy-races-dino-first", "title": "All Trophy Races – Dino Domain First", "summary": "Race all five Trophy sets, beginning in Dino Domain.", "stages": ["Ancient Lake", "Fossil Canyon", "Jungle Falls", "Hot Top Volcano", "Whale Bay", "Pirate Lagoon", "Crescent Island", "Treasure Caves", "Everfrost Peak", "Walrus Cove", "Snowball Valley", "Frosty Village", "Boulder Canyon", "Greenwood Village", "Windmill Plains", "Haunted Woods", "Spacedust Alley", "Darkmoon Caverns", "Star City", "Spaceport Alpha"]}, + {"id": "all-trophy-races-ffl-first", "title": "All Trophy Races – Future Fun Land First", "summary": "Race all five Trophy sets, beginning in Future Fun Land.", "stages": ["Spacedust Alley", "Darkmoon Caverns", "Star City", "Spaceport Alpha", "Boulder Canyon", "Greenwood Village", "Windmill Plains", "Haunted Woods", "Everfrost Peak", "Walrus Cove", "Snowball Valley", "Frosty Village", "Whale Bay", "Pirate Lagoon", "Crescent Island", "Treasure Caves", "Ancient Lake", "Fossil Canyon", "Jungle Falls", "Hot Top Volcano"]}, + {"id": "car-percent", "title": "Car%", "summary": "Complete the car course route.", "stages": ["Greenwood Village", "Walrus Cove", "Everfrost Peak", "Spacedust Alley", "Darkmoon Caverns", "Star City", "Spaceport Alpha", "Haunted Woods", "Windmill Plains", "Snowball Valley", "Frosty Village", "Treasure Caves", "Crescent Island", "Ancient Lake", "Fossil Canyon", "Jungle Falls"]}, + {"id": "hover-percent", "title": "Hover%", "summary": "Complete the hovercraft course route.", "stages": ["Everfrost Peak", "Boulder Canyon", "Spacedust Alley", "Darkmoon Caverns", "Greenwood Village", "Windmill Plains", "Star City", "Spaceport Alpha", "Haunted Woods", "Frosty Village", "Snowball Valley", "Walrus Cove", "Ancient Lake", "Fossil Canyon", "Jungle Falls", "Hot Top Volcano", "Crescent Island", "Treasure Caves", "Whale Bay", "Pirate Lagoon"]}, + {"id": "plane-percent", "title": "Plane%", "summary": "Complete the plane course route.", "stages": ["Windmill Plains", "Spaceport Alpha", "Star City", "Spacedust Alley", "Everfrost Peak", "Frosty Village", "Treasure Caves", "Hot Top Volcano", "Jungle Falls", "Fossil Canyon", "Ancient Lake"]}, + {"id": "tt-amulet-no-wrong-warp", "title": "T.T. Amulet – No Wrong Warp", "summary": "Earn the four T.T. Amulet pieces through normal progression.", "stages": ["Overworld", "Fire Mountain", "Hot Top Volcano", "Car Challenge", "Frosty Village", "Snowball Valley", "Icicle Pyramid", "Walrus Cove", "Everfrost Peak", "Hover Challenge", "Pirate Lagoon", "Crescent Island", "Whale Bay", "Darkwater Beach", "Treasure Caves", "Plane Challenge", "Windmill Planes", "Smokey Castle"]}, +]; diff --git a/runtime-recomp/src/game/mod_library/website/assets/api-store.js b/runtime-recomp/src/game/mod_library/website/assets/api-store.js index 95caea78..90fce945 100644 --- a/runtime-recomp/src/game/mod_library/website/assets/api-store.js +++ b/runtime-recomp/src/game/mod_library/website/assets/api-store.js @@ -14,7 +14,8 @@ let apiBase = ''; try { const configured = new URL((root.DKR_CONFIG || {}).apiBase); - if (configured.protocol !== 'https:' || configured.username || configured.password || configured.search || configured.hash) throw new Error(); + const loopback = configured.origin === root.location.origin && ['127.0.0.1','localhost'].includes(configured.hostname); + if ((!loopback && configured.protocol !== 'https:') || configured.username || configured.password || configured.search || configured.hash) throw new Error(); apiBase = configured.href.replace(/\/+$/, ''); D.configured = true; } catch (_) { D.error = 'The website library service address is missing or invalid. Reload this page or contact the site owner.'; } function notify() { listeners.forEach(function (callback) { try { callback(D); } catch (_) { /* UI failures do not affect store state. */ } }); } @@ -91,6 +92,16 @@ D.visibleReviews = function (id) { return (publicReviews.get(id) || []).slice(); }; D.ownReview = function (id) { return self ? ownReviews.find(function (review) { return review.itemId === id; }) || null : null; }; D.onChange = function (callback) { if (typeof callback !== 'function') throw new TypeError('Expected a listener.'); listeners.add(callback); return function () { listeners.delete(callback); }; }; + async function notificationRequest(path,body) { + const epoch = generation; + await ensureAuth(); + const token = auth && auth.getToken(); + if (invalidated(epoch)) throw staleError(); + if (!token || !self) throw new Error('Sign in to see your notifications.'); + return requestJSON('/v1/notifications' + path,token,body,epoch); + } + D.getNotifications = cursor => notificationRequest(cursor ? '?before=' + encodeURIComponent(cursor) : ''); + D.markNotifications = (operation,body) => notificationRequest('/' + operation,body); D.refresh = async function () { // Start loading synchronously: a login listener can immediately wait for // this refresh, even while its session-validation promise is pending. diff --git a/runtime-recomp/src/game/mod_library/website/assets/app.js b/runtime-recomp/src/game/mod_library/website/assets/app.js index 704b4657..8b077150 100644 --- a/runtime-recomp/src/game/mod_library/website/assets/app.js +++ b/runtime-recomp/src/game/mod_library/website/assets/app.js @@ -295,7 +295,7 @@ function listingOptions(value) { return options([['','Choose an existing listing']].concat(managedItems().filter(m=>!m.archived).map(m=>[m.id,m.title+' · '+category(m.category).short])),value); } function pagehead(title,subtitle,backAction,id) { const back=backAction||'store'; - const label={moderation:'Back to moderation',account:'Back to my account',admin:'Back to admin','review-request':'Back to request'}[back]||'Back to library'; + const label={moderation:'Back to moderation',account:'Back to my account',speedruns:'Back to leaderboards',admin:'Back to admin','review-request':'Back to request'}[back]||'Back to library'; const refresh=['account','request-status','moderation','review-request','admin','detail','editor','metadata-editor','publication-preview'].includes(s.view)?button('refresh-page',icon('refresh-cw')+'Refresh','quiet small'):''; return '
'+button(back,icon('arrow-left')+label,'quiet small',id,'data-page-focus')+refresh+'

'+esc(title)+'

'+(subtitle?'

'+subtitle+'

':'')+'
'; } @@ -354,7 +354,7 @@ function header() { const u=user(); - return ''; + return ''; } function footer() { return 'DKR-R Mod Library · Community creations, one starting grid.
DKR-R project'+textButton('help','Install help')+textButton('staff-login','Moderator login')+'Privacy
'; } function modcard(item) { @@ -472,6 +472,16 @@ return banner('Reports stay visible until a moderator acts. Negative feedback alone is not a reason to hide a review.')+'
'+(list(D.reports).length?D.reports.map(report=>{const review=report.review||list(D.reviews).find(v=>v.id===report.reviewId);if(!review)return '

Reported review unavailable

Refresh the moderation queue to load this report’s content.

';const m=D.item(review.itemId);return '

'+esc(m?m.title:report.itemTitle||'Mod review')+'

'+(report.status==='open'?'Open report':'Resolved')+'
'+stars(review.score)+'by '+esc(authorName(review))+' · '+esc(review.version||'Version not specified')+'

'+esc(review.text||'Rating only')+'

Report reason: '+esc(report.reason)+'

'+(report.status==='open'?'
'+area('Moderation reason','reason','','maxlength="1000" placeholder="Required if hiding the review."')+'
'+submit('Dismiss report','keep','quiet')+submit('Hide review','hide','red')+'
':'

Decision: '+esc(report.action||'Resolved')+' · '+esc(report.resolution||'')+'

'+(review.hidden?button('restore-review','Restore review','quiet small',report.id,'data-revision="'+esc(report.revision)+'" data-review-revision="'+esc(review.revision)+'"'):'Review is visible.'))+(m?button('reviews','View mod reviews','quiet small',review.itemId):'')+'
';}).join(''):empty('No reported reviews','Reported content will appear here for staff to assess.'))+'
'; } + const Racing = window.DKRRacingUI.create({root, config, Auth, view:()=>s.view, user, isStaff, esc, icon, button, pagehead, requireSignedIn, go, renderIcons}); + const Notifications = window.DKRNotificationsUI.create({ + root, user, esc, icon, button, renderIcons, + read:cursor=>D.getNotifications(cursor), + mark:(operation,body)=>D.markNotifications(operation,body), + signIn:()=>go('login',{loginMode:'player',returnTo:{view:s.view}}), + navigate:event=>event.type === 'run' ? Racing.openRunList(event.staff ? 'review' : 'mine',event.itemId) : + go(event.staff ? 'review-request' : 'request-status',{requestId:event.itemId}), + }); + const Community = window.DKRCommunityUI.create({root,state:()=>s,store:()=>D,esc,icon,button,banner,empty,categories:C.categories,category,image,dateText,user,isStaff,render,go,flash,perform}); function prepareEditor(mode,id,saved) { @@ -751,12 +761,12 @@ main.innerHTML=D&&D.loading?progress('Loading your account'):pagehead('Your account could not be loaded','')+banner(esc(D&&D.error||'The connection was interrupted. Refresh this page to reconnect to your account.')+'
'+button('refresh-page','Reconnect','quiet')+'
','error'); } else { if(needsUser&&!user()){s.returnTo={view:s.view,requestId:s.requestId};s.loginMode=['moderation','review-request','editor','metadata-editor','publication-preview','admin','batch'].includes(s.view)?'staff':'player';s.view='login';} - const pages={batch:batchPage,store:storePage,detail:detailPage,login:loginPage,denied:()=>deniedPage(false),request:requestPage,account:accountPage,'request-status':requestStatusPage,moderation:moderationPage,'review-request':reviewRequestPage,editor:editorPage,'metadata-editor':metadataPage,'publication-preview':publicationPreviewPage,admin:adminPage,help:helpPage}; + const pages={online:Racing.onlinePage,speedruns:Racing.speedrunsPage,'post-run':Racing.postPage,batch:batchPage,store:storePage,detail:detailPage,login:loginPage,denied:()=>deniedPage(false),request:requestPage,account:accountPage,'request-status':requestStatusPage,moderation:moderationPage,'review-request':reviewRequestPage,editor:editorPage,'metadata-editor':metadataPage,'publication-preview':publicationPreviewPage,admin:adminPage,help:helpPage}; main.innerHTML=(pages[s.view]||storePage)(); } } if(Auth&&Auth.signoutPending&&!Auth.completionWindow){main.insertAdjacentHTML('afterbegin',banner(esc(Auth.signoutWarning||'Sign-out could not be confirmed. Reconnect and finish signing out to remove remembered access from this device.')+'
'+button('retry-signout','Finish signing out','quiet')+'
','error'));} - renderIcons();applyBusy();if(focus)focusPage();Community.mounted(); + renderIcons();applyBusy();if(focus)focusPage();Community.mounted();Racing.mounted();Notifications.mounted(); } async function go(view,data,refresh) { if(view!==s.view){captureListingForm();if(Uploads&&Uploads.state.running&&uploadMatchesContext(uploadTarget,false))Uploads.pause();s.uploadOpenKind='';s.uploadJobsShown=false;s.uploadError='';s.uploadConnection='';} @@ -808,6 +818,8 @@ if(pendingWrite)return; try { if(await workflowAction(action,id,target))return; + if(await Racing.action(action,id,target))return; + if(await Notifications.action(action,id))return; if(action==='store'){await go('store');return;} if(action==='category'){s.category=id;s.tag='all';s.limit=6;s.view='store';clearFlash();render();restoreFocus(action,id);return;} if(action==='tag'){s.tag=id;s.limit=6;clearFlash();render();restoreFocus(action,id);return;} @@ -1015,5 +1027,7 @@ } catch(error){bootError=errorMessage(error);} finally {started=true;bootLoading=false;render();} } + const publicPage = {'#online':'online','#leaderboards':'speedruns','#post-run':'post-run'}[location.hash]; + if(publicPage||/^#lobby=[a-f0-9]{32}$/.test(location.hash))s.view=publicPage||'online'; initialise(); }()); diff --git a/runtime-recomp/src/game/mod_library/website/assets/notifications-ui.js b/runtime-recomp/src/game/mod_library/website/assets/notifications-ui.js new file mode 100644 index 00000000..b47e0704 --- /dev/null +++ b/runtime-recomp/src/game/mod_library/website/assets/notifications-ui.js @@ -0,0 +1,162 @@ +(function () { + 'use strict'; + + const modStatuses = { + pending:'Waiting for review',review:'Under review',changes:'Changes requested', + approved:'Approved for publication',rejected:'Rejected',published:'Published', + }; + const runStatuses = { + queued:'Waiting for verification',verified:'Ready for staff review',rejected:'Rejected',published:'Published', + }; + const timestamp = new Intl.DateTimeFormat(undefined,{dateStyle:'medium',timeStyle:'short'}); + + window.DKRNotificationsUI = { create({ root, user, esc, icon, button, read, mark, navigate, signIn, renderIcons }) { + let inbox = null; + let identity = ''; + let opened = false; + let busy = false; + let errorMessage = ''; + let generation = 0; + let updatedAt = 0; + let timer; + + function syncIdentity() { + const account = user(); + const key = account ? account.id + ':' + account.role : ''; + if (key !== identity) { + identity = key; + ++generation; + inbox = null; + opened = busy = false; + errorMessage = ''; + updatedAt = 0; + } + } + + function markup() { + syncIdentity(); + const unread = inbox?.unread || 0; + const label = 'Notifications' + (unread ? ', ' + unread + ' unread' : ''); + return '' + (opened ? panel() : ''); + } + + function panel() { + const entries = inbox?.events || []; + return '
' + + '

Notifications

' + + (inbox?.through && !busy ? button('notifications-read-all','Mark all as read','quiet small') : '') + '
' + + (errorMessage ? '

' + esc(errorMessage) + '

' : '') + + (!inbox && busy ? '

Loading notifications…

' : '') + + (entries.length ? '
    ' + entries.map(event => { + const status = event.staff ? (event.type === 'mod' ? 'Mod ready for review' : 'Run ready for review') : + (event.type === 'mod' ? modStatuses[event.status] : runStatuses[event.status]) || event.status; + const date = new Date(event.createdAt * 1000); + return '
  • '; + }).join('') + '
' : (inbox ? '

You have no notifications.

' : '')) + + (inbox?.nextCursor && !busy ? button('notifications-more','More notifications','quiet small') : '') + '
'; + } + + function render() { + const slot = root.querySelector('[data-notification-slot]'); + if (!slot) return; + const focused = slot.contains(document.activeElement) ? document.activeElement : null; + const action = focused?.dataset.action; + const id = focused?.dataset.id; + slot.innerHTML = markup(); + renderIcons(); + if (action) [...slot.querySelectorAll('[data-action]')].find(item => item.dataset.action === action && + item.dataset.id === id)?.focus({preventScroll:true}); + } + + async function update(operation, append = false) { + syncIdentity(); + if (!identity || busy) return false; + const token = ++generation; + busy = true; + errorMessage = ''; + if (opened) render(); + try { + const data = await operation(); + syncIdentity(); + if (token !== generation) return false; + inbox = append && inbox ? {...data,events:[...inbox.events,...data.events]} : data; + return true; + } catch (error) { + if (token === generation && opened) errorMessage = error.message || 'Notifications are temporarily unavailable.'; + return false; + } finally { + if (token === generation) { + updatedAt = Date.now(); + busy = false; + render(); + } + } + } + + function poll() { + syncIdentity(); + if (identity && !opened && document.visibilityState !== 'hidden' && Date.now()-updatedAt > 30000) + update(() => read()); + } + + function mounted() { + if (!timer) timer = setInterval(poll,15000); + poll(); + } + + function close(focus) { + if (!opened) return; + opened = false; + render(); + if (focus) root.querySelector('[data-action="notifications-toggle"]')?.focus({preventScroll:true}); + } + + async function action(name, id) { + if (!name.startsWith('notifications-')) return false; + if (name === 'notifications-toggle') { + if (!user()) await signIn(); + else if (opened) close(true); + else { + opened = true; + render(); + await update(() => read()); + } + } + if (name === 'notifications-more' && inbox?.nextCursor) + await update(() => read(inbox.nextCursor),true); + if (name === 'notifications-read-all' && inbox?.through) + await update(() => mark('read-all',{ through:inbox.through })); + if (name === 'notifications-item') { + const event = inbox?.events.find(row => row.id === Number(id)); + if (!event) return true; + const current = identity; + if (!event.read && !await update(() => mark('read',{id:event.id}))) return true; + if (current === identity) { + close(false); + await navigate(event); + } + } + return true; + } + + document.addEventListener('pointerdown',event => { + if (opened && !event.target.closest('[data-notification-slot]')) close(false); + }); + document.addEventListener('keydown',event => { + if (opened && event.key === 'Escape') { + event.preventDefault(); + close(true); + } + }); + document.addEventListener('visibilitychange',poll); + return { markup, action, mounted }; + } }; +}()); + diff --git a/runtime-recomp/src/game/mod_library/website/assets/racing-ui.js b/runtime-recomp/src/game/mod_library/website/assets/racing-ui.js new file mode 100644 index 00000000..b80ff60b --- /dev/null +++ b/runtime-recomp/src/game/mod_library/website/assets/racing-ui.js @@ -0,0 +1,797 @@ +(function () { + 'use strict'; + const activityPeriods = [['7','7 days'],['30','30 days'],['all','All time']]; + const sections = [['overall','Top Players'],['vanilla','Vanilla Tracks'],['custom','Custom Tracks'],['full-game','Full Game']]; + const phases = {waiting:'In lobby',testing:'Testing connection',starting:'Starting',loading:'Loading',racing:'Racing',returning:'Returning to lobby'}; + const states = {uploading:'Upload incomplete',queued:'Waiting for verification',verified:'Waiting for moderator review',published:'Published',rejected:'Rejected'}; + const clock = ticks => { + if (!Number.isSafeInteger(ticks)) return '—'; + const ms = Math.floor(ticks * 1000 / 60); + return Math.floor(ms / 60000) + ':' + String(Math.floor(ms / 1000) % 60).padStart(2, '0') + + '.' + String(ms % 1000).padStart(3, '0'); + }; + + window.DKRRacingUI = {create({ root, config, Auth, view, user, isStaff, esc, icon, button, pagehead, requireSignedIn, go, renderIcons }) { + const linkedRoom = /^#lobby=([a-f0-9]{32})$/.exec(location.hash)?.[1]; + let activityPeriod = 'all'; + let online, directoryError, directoryBusy = false, directoryTimer; + let catalogue, ranking, overall, profile, section = 'overall', listingTab = 'boards', runId = ''; + let playerId = '', playerPanel = 'score', profileError = ''; + let fromProfile = false, explainPoints = false, selectedRecord = null; + let privateRuns, quotaTimer, score = 'race'; + const quotaDate = new Intl.DateTimeFormat(undefined, { dateStyle:'medium', timeStyle:'medium' }); + let query = '', world = '', vehicle = '', availability = '', course = '', courseVehicle = '', racer = ''; + const vehicleNames = {car:'Car',hovercraft:'Hovercraft',plane:'Plane',mixed:'Mixed'}; + const matches = value => value.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase()); + let leaderboardBusy = false, leaderboardError = '', leaderSequence = 0; + let currentPage = '', onlineNotice = '', privateIdentity = ''; + + async function request(path, { fresh = false, method = 'GET', body, privateAccess = false, type = 'application/json' } = {}) { + const headers = { Accept:'application/json' }; + if (privateAccess) { + await Auth.ensureSession(); + const token = Auth.getToken(); + if (!token) throw new Error('Sign in again to continue.'); + headers.Authorization = 'Bearer ' + token; + } + if (body !== undefined) headers['Content-Type'] = type; + const reply = await fetch(apiURL(path), { method, body, headers, redirect:'error', + credentials:'omit', cache:fresh ? 'reload' : 'default', signal:AbortSignal.timeout(20000) }); + const data = await reply.json().catch(() => ({})); + if (reply.ok) return data; + const error = new Error(data.error?.message || 'The service is temporarily unavailable.'); + error.code = data.error?.code; + throw error; + } + + function refreshRegion(selector, template, focusAction) { + const region = root.querySelector(selector); + if (!region) return; + const focused = region.contains(document.activeElement) ? document.activeElement : null; + const action = focusAction || focused?.dataset.action; + const id = focusAction ? null : focused?.dataset.id; + region.innerHTML = template(); + if (region.hasAttribute('data-leaderboard-region')) updateSubmissionQuota(); + renderIcons(); + if (action) [...region.querySelectorAll('[data-action]')] + .find(node => node.dataset.action === action && (id == null || node.dataset.id === id))?.focus(); + } + + function onlinePage() { + return pagehead('DKR-R Online', 'See who’s online and find a public lobby.') + + '
' + onlineContent() + '
'; + } + const players = value => Number.isSafeInteger(value) && value >= 0 ? value.toLocaleString() : '—'; + function activityTime(value) { + return Number.isSafeInteger(value) && value > 0 ? new Intl.DateTimeFormat(undefined, { + weekday:'short', month:'short', day:'numeric', hour:'numeric', minute:'2-digit', timeZoneName:'short' + }).format(value) : ''; + } + function stat(label, count, detail = '') { + return '
' + label + '
' + players(count) + + '
' + (detail ? '
' + esc(detail) + '
' : '') + '
'; + } + function activityHistory(history, interval) { + if (!Array.isArray(history) || !history.length) return ''; + const valid = history.filter(point => Number.isSafeInteger(point.startsAt) && + Number.isSafeInteger(point.players) && point.players >= 0); + if (!valid.length) return ''; + const maximum = Math.max(1, ...valid.map(point => point.players)); + const date = new Intl.DateTimeFormat(undefined, interval === 'year' ? {year:'numeric',timeZone:'UTC'} : + interval === 'month' ? {month:'short',year:'numeric',timeZone:'UTC'} : {month:'short',day:'numeric',timeZone:'UTC'}); + const label = interval === 'year' ? 'Yearly peaks' : + interval === 'month' ? 'Monthly peaks' : 'Daily peaks · days with recorded activity (UTC)'; + return '

' + label + '

' + + '
    ' + valid.map(point => { + const tip = date.format(point.startsAt) + ' · ' + players(point.players) + ' online'; + return '
  1. '; + }).join('') + '

' + + esc(date.format(valid[0].startsAt)) + '' + + (valid.length > 1 ? '' + esc(date.format(valid.at(-1).startsAt)) + '' : '') + '

'; + } + function onlineStats(live) { + const stats = online?.stats; + const period = stats?.periods?.[activityPeriod]; + const lifetime = activityPeriod === 'all'; + const peakTime = activityTime(stats?.peak?.observedAt); + const busiest = period?.busiestHour; + const busiestTime = activityTime(busiest?.startsAt); + return '
' + stat('Public lobbies',live ? stats?.publicLobbies : undefined) + + stat('Racers in public lobbies',live ? stats?.publicRacers : undefined) + + stat('Spectators in public lobbies',live ? stats?.publicSpectators : undefined) + '
' + + '

Player activity

' + + '
' + + activityPeriods.map(([id,label]) => '').join('') + '
' + + '
' + + stat(lifetime ? 'All-time concurrent peak' : 'Peak concurrent players', period?.peak, + lifetime ? peakTime : '') + + stat('Days with activity',period?.activeDays) + + (lifetime ? '
Activity recorded since
' + + esc(stats?.trackedSince ? new Intl.DateTimeFormat(undefined,{dateStyle:'medium'}).format(stats.trackedSince) : 'Collecting activity') + '
' : + '
Busiest hour
' + esc(busiestTime || 'Collecting activity') + '
' + + (busiestTime ? '
' + players(busiest.players) + ' at peak
' : '') + '
' + + stat('New sign-ups',online?.newSignups?.[activityPeriod])) + '
' + activityHistory(period?.history,lifetime ? period?.interval || 'month' : 'day'); + } + function onlineContent() { + const age = online && Date.now() - online.serverTime; + const live = online && age < 90000 && !directoryError; + const count = players(live ? online.online : undefined); + const registered = players(online?.totalSignedUp); + const status = directoryError === 'disabled' ? 'The public lobby browser is currently disabled.' : + online && !live ? 'Last known rooms. Open DKR-R Online to check availability.' : + directoryError ? 'The lobby list could not be loaded.' : + online ? 'Updates every 30 seconds.' : 'Loading the public lobby list…'; + const rooms = online ? [...online.rooms] : []; + if (linkedRoom) rooms.sort((a, b) => Number(b.id === linkedRoom) - Number(a.id === linkedRoom)); + return '
' + + count + ' / ' + registered + '

Total online / Total signed up

' + + '

' + esc(status) + '

' + + button('online-refresh',icon('refresh-cw') + 'Refresh','quiet small') + '
' + onlineStats(live) + '
' + + '

Copy a link and use Find lobby from website in the launcher’s Public lobbies panel. The host approves requests to race or spectate.

' + + (onlineNotice ? '

' + esc(onlineNotice) + '

' : '') + + (rooms.length ? '
' + rooms.map(room => + '

' + esc(room.title) + + '

' + esc(phases[room.phase] || 'Updating') + '
' + + esc(room.racers) + ' / ' + esc(room.maxRacers) + ' racers · ' + esc(room.spectators) + ' / ' + + esc(room.maxSpectators) + ' spectators

' + + (live ? (room.canJoin && room.canSpectate ? 'Racing and spectator spots available' : + room.canJoin ? 'Racing spots available' : room.canSpectate ? 'Spectator spots available' : 'No places available right now') : + 'Check in the launcher for open spots') + '

' + + (live ? '
' + button('online-copy','Copy lobby link','quiet small',room.id) + '
' : '') + '
').join('') + '
' : + live ? '

No public lobbies are open right now.

' : '') + + (live && online.nextCursor ? button('online-more','More lobbies','quiet') : ''); + } + async function loadOnline({ more = false, fresh = false } = {}) { + if (directoryBusy) return; + directoryBusy = true; + try { + const suffix = more && online?.nextCursor ? '?cursor=' + encodeURIComponent(online.nextCursor) : ''; + const data = await request('online/public' + suffix, { fresh }); + if (!Array.isArray(data.rooms) || !Number.isSafeInteger(data.online) || !Number.isSafeInteger(data.serverTime)) + throw new Error('Invalid lobby list.'); + if (more && online) { + const rooms = new Map(online.rooms.map(room => [room.id, room])); + data.rooms.forEach(room => rooms.set(room.id, room)); + online = {...online, ...data, rooms:[...rooms.values()]}; + } else online = data; + directoryError = ''; + } catch (error) { + directoryError = error.code || 'unavailable'; + if (directoryError === 'disabled') online = null; + } finally { + directoryBusy = false; + if (view() === 'online') refreshRegion('[data-online-region]', onlineContent, more ? 'online-refresh' : undefined); + } + } + + function clearPrivateIfChanged() { + const account = user(); + const identity = account ? account.id + ':' + account.role : ''; + if (identity === privateIdentity) return; + privateIdentity = identity; + if (listingTab !== 'boards') { + ++leaderSequence; + listingTab = 'boards'; + leaderboardError = ''; + leaderboardBusy = false; + privateRuns = undefined; + } + } + function speedrunsPage() { + clearPrivateIfChanged(); + return pagehead('Leaderboards','Race for a personal best and watch how other players set theirs.') + + '
' + speedrunContent() + '
'; + } + function speedrunContent() { + if (leaderboardError) return '
' + esc(leaderboardError) + + '
' + button('run-refresh','Try again','quiet') + '
'; + if (listingTab !== 'boards') return runListContent(); + const nav = ''; + const tools = '
' + + (user() ? button('run-list','My runs','quiet','mine') : '') + + (isStaff() ? button('run-list','Review runs','quiet','review') : '') + '
'; + if (!catalogue) return nav + '
Loading leaderboards…
'; + if (course) return nav + tools + rankingContent(); + if (section === 'overall') return nav + tools + overallContent(); + if (section === 'vanilla') return nav + tools + vanillaContent(); + if (section === 'custom') return nav + tools + customContent(); + return nav + fullGameContent(); + } + + const points = milli => Number.isSafeInteger(milli) ? (milli/1000).toLocaleString(undefined,{maximumFractionDigits:3}) : '—'; + function overallContent() { + const explanation = '
How points work
' + + '

Verified results earn points for placing higher (70%) and getting closer to the record (30%). Solo boards count for 35%. Board weight grows to 100% at eight players.

' + + '

Track scores are 75% Full Race and 25% Best Lap. Each player contributes their best time in each, across all racers.

' + + '

Posted PBs count each current verified, published best time on a scored board. A Time Trial can have a race PB and a lap PB. World Records are the PBs holding or sharing first place.

' + + '
Vanilla Tracks · 500
Scores across populated boards, with equal weight per vehicle type.
' + + '
Custom Tracks · 250
Best 10 tracks for up to 200 points, plus the next 20 for up to 50. A new track can earn more points without reducing existing scores.
' + + '
Full Game · 250
Finish scores across populated Full Game categories.
'; + if (!overall) return explanation + '

Loading top players…

'; + const players = overall.players; + const selected = players.find(player=>player.id===playerId) || players[0]; + const rows = players.map(player => { + const active = player.id===selected.id; + return '' + esc(player.place) + '' + + button('overall-player',esc(player.name),'quiet small',player.id,'aria-pressed="'+active+'"') + + '' + esc(personalBestCount(player)) + '' + esc(player.records) + + '' + points(player.total) + ''; + }).join(''); + return explanation + '
' + + '

Top Players

' + (players.length ? + '' + + '' + + rows + '
RankPlayerPosted PBsWorld RecordsPoints
' : '

The first published run will appear here.

') + + (overall.tiedCutoff ? '

More players share the final rank shown.

' : '') + '
' + + (selected ? profileContent(selected) : '') + '
'; + } + + const personalBestCount = player => Number.isSafeInteger(player.personalBests) ? player.personalBests : '—'; + + function profileContent(player) { + const tabs = [['score','Score breakdown'],['runs','Ranked runs']].map(([id,label]) => + button('overall-panel',label,'quiet small',id,'aria-pressed="'+(playerPanel===id)+'"')).join(''); + const stats = '
Posted PBs
' + esc(personalBestCount(player)) + + '
World Records
' + esc(player.records) + '
'; + const scoreBreakdown = '
' + + [['Vanilla Tracks','vanilla',500],['Custom Tracks','custom',250],['Full Game','fullGame',250]].map(([name,id,cap]) => { + const value = player.points[id]; + return '
' + name + '' + points(value) + + ' / ' + cap + ' pts
'; + }).join('') + '

' + esc(player.podiums) + ' podiums · ' + + esc(player.coverage) + ' ranked events

'; + return '
' + + '

#' + esc(player.place) + + ' overall

' + esc(player.name) + + '

' + points(player.total) + ' pts
' + + '' + stats + + (playerPanel==='runs' ? profileRunsContent(player.id) : scoreBreakdown) + '
'; + } + + function profileRunsContent(id) { + if (profileError) return '

' + esc(profileError) + '

' + button('run-refresh','Try again','quiet small'); + if (profile?.player.id!==id) return '

Loading ranked runs…

'; + const {events,customTracks} = profile; + const custom = new Map(customTracks.map(track=>[track.id,track])); + return '
' + events.map(event => { + const customScore = event.kind==='custom' && custom.get(event.id); + const record = (label,result) => '
' + label + ' · #' + esc(result.place) + ' · ' + + clock(result.ticks) + '' + (result.place===1 ? 'World Record' : '') + + (result.hasVideo ? button('run-video','Watch Video','quiet small',result.runId) : '') + '
'; + return '
' + esc(event.title) + '' + + '

' + + esc(sections.find(([id]) => id===event.kind)?.[1]) + (event.kind==='full-game' ? '' : ' · ' + esc(vehicleNames[event.vehicle])) + + (customScore ? ' · Scoring track #' + esc(customScore.slot) + ' (' + points(customScore.points) + ' pts)' : '') + '

' + + record(event.kind==='full-game' ? 'Finish' : 'Full Race',event.race) + + (event.lap ? record('Best Lap',event.lap) : '') + '
'; + }).join('') + '
' + (profile.nextOffset!=null ? button('run-more-profile','More results','quiet') : ''); + } + + const recordDay = stamp => new Date(stamp*1000).toLocaleDateString(undefined,{day:'numeric',month:'short',year:'numeric',timeZone:'UTC'}); + function reignDuration(seconds) { + for (const [unit,size] of [['day',86400],['hour',3600],['minute',60]]) { + const count = Math.floor(seconds/size); + if (count>0) return count + ' ' + unit + (count===1 ? '' : 's'); + } + return Math.max(0,seconds) + ' sec'; + } + function recordHistoryContent(history) { + if (!Array.isArray(history?.changes)) return ''; + const events = history.changes; + const incomplete = '

Some publication dates are unavailable.

'; + if (!events.length) return '

World record history

' + + (history.complete ? '

History appears after the first published run.

' : incomplete) + '
'; + const first = events[0], last = events.at(-1); + const choice = events.findIndex(event=>event.at===selectedRecord); + const index = choice<0 ? events.length-1 : choice; + const chosen = events[index]; + const end = history.complete ? Math.max(last.at,history.asOf) : last.at; + const x = stamp => 12 + 976*(stamp-first.at)/Math.max(end-first.at,1); + const y = time => 9 + 78*(first.ticks-time)/Math.max(first.ticks-last.ticks,1); + const line = events.map((event,i)=>i ? 'H '+x(event.at)+' V '+y(event.ticks) : 'M '+x(event.at)+' '+y(event.ticks)).join(' ')+' H '+x(end); + const duration = chosen.until || history.complete ? ' · ' + (chosen.until ? 'Stood for ' : 'Unbeaten for ') + + reignDuration((chosen.until || end)-chosen.at) : ''; + return '

World record history

' + + '' + clock(last.ticks) + '
' + + '
' + clock(first.ticks) + '' + + (last.ticks!==first.ticks ? ''+clock(last.ticks)+'' : '') + + '
' + events.map((event,i) => '').join('') + + '
' + recordDay(first.at) + '' + (end!==first.at ? ''+recordDay(end)+'' : '') + + '
' + clock(chosen.ticks) + ' · ' + + recordDay(chosen.at) + esc(duration) + '' + chosen.holders.map(holder => '

' + esc(holder.name) + + (holder.until || history.complete ? ' · ' + (holder.until ? 'Held for ' : 'Holding for ') + + reignDuration((holder.until || end)-holder.from) : '') + '

').join('') + + '
' + (!history.complete ? incomplete : '') + + (history.earlierChanges ? '

Showing the latest record changes.

' : '') + '
'; + } + + function option(value, label, selected) { + return ''; + } + + function filterSelect(label, key, first, options, value) { + return ''; + } + + function trackFilters(trackWorlds = []) { + const search = ''; + const kind = section === 'custom' ? '' : + filterSelect('World', 'world', 'All worlds', trackWorlds.map(name => [name,name]), world) + + filterSelect('Vehicle', 'vehicle', 'All vehicles', Object.entries(vehicleNames).slice(0,3), vehicle); + return '
' + search + kind + filterSelect('Status', 'availability', 'All tracks', + [['ranked','Ranked'],['pending','Awaiting qualification']],availability) + '
'; + } + + function statusMatches(qualified) { + return !availability || qualified === (availability === 'ranked'); + } + + function trackScore(label, score) { + return '
' + label + '' + + (Number.isSafeInteger(score?.ticks) && score.ticks > 0 ? + '' + esc(score.name) + '' + + clock(score.ticks) + '' + icon('crown') + + '' : '—') + '
'; + } + + function trackRow(track, details, qualified, fullGame = false) { + const vehicles = track.vehicles || []; + const leaders = track.leaders || {}; + const records = fullGame ? trackScore('Finish time', leaders.mixed?.race) : + vehicles.map(id => '

' + + esc(vehicleNames[id]) + '

' + trackScore('Full race', leaders[id]?.race) + + trackScore('Best lap', leaders[id]?.lap) + '
').join(''); + const route = fullGame && track.stages.length ? '
Route splits' + + '
    ' + track.stages.map(stage => '
  1. ' + esc(stage) + '
  2. ').join('') + + '
' : ''; + return '

' + + esc(track.title) + '

' + esc(details) + + '

' + + (qualified ? button('run-course','View Times','quiet',track.id) : 'Awaiting qualification') + + route + '
' + + (records ? '
' + records + '
' : '') + '
'; + } + + function vanillaContent() { + const boards = catalogue.boards.filter(value => value.kind === 'vanilla'); + const tracks = catalogue.vanillaTracks || []; + const isRanked = track => boards.some(value => value.title === track.title && value.ranked && (!vehicle || value.vehicle === vehicle)); + const worlds = [...new Set(tracks.map(track => track.world))].filter(Boolean); + const matching = tracks.filter(track => matches(track.title) && (!world || track.world === world) && + (!vehicle || track.vehicles.includes(vehicle)) && statusMatches(isRanked(track))); + return trackFilters(worlds) + '

' + matching.length + ' of ' + tracks.length + ' tracks

' + + (matching.length ? '
' + matching.map(track => + trackRow(track, [track.world,...track.vehicles.map(id => vehicleNames[id])].join(' · '), isRanked(track)) + ).join('') + '
' : '

No tracks match these filters.

') + '
'; + } + + function customContent() { + const matching = catalogue.customTracks.filter(track => matches(track.title) && statusMatches(track.qualified)); + return trackFilters() + '

Tracks in the Mod Library

' + + matching.map(track => trackRow(track, ['Version ' + track.version,...(track.vehicles || []).map(id => vehicleNames[id])].join(' · '), + track.qualified)).join('') + + (matching.length ? '' : '

No loaded tracks match these filters.

') + + '
' + (catalogue.nextCursor ? button('run-more','More tracks','quiet') : '') + '
'; + } + + function rankingContent() { + if (!ranking) return '
Loading times…
'; + const videoEnabled = catalogue?.videoEnabled !== false; + const videoNotice = videoEnabled && catalogue?.hostedVideos ? + '

The leaderboard host prepares videos for review. You can close DKR-R once your upload finishes.

' : ''; + const filters = section === 'full-game' ? '' : + filterSelect('Racer','ranking-racer','All racers',ranking.racers.map(item => [item.id,item.name]),ranking.racer) + + (ranking.vehicles.length ? filterSelect('Vehicle','ranking-vehicle','',ranking.vehicles.map(id => [id,vehicleNames[id]]),ranking.vehicle) : ''); + return '

' + + esc(ranking.track.title) + '

' + esc(ranking.track.world || ranking.track.version || '') + + '

' + button('run-back',fromProfile ? 'Back to player stats' : section==='full-game' ? 'All categories' : 'All tracks','quiet small') + '
' + + '
' + filters + '
' + + (section === 'full-game' ? '' : '') + + videoNotice + + (ranking.entries.length ? '' + + (videoEnabled ? '' : '') + '' + + ranking.entries.map(entry => '' + + (videoEnabled ? '' : '') + + '').join('') + '
RankPlayerRacerTimeVideo
' + esc(entry.place) + '' + esc(entry.name) + '' + + esc(entry.racer || '—') + '' + clock(entry.ticks) + '' + (catalogue?.hostedVideos && !entry.hasVideo ? 'Video pending' : + button('run-video','Watch Video','quiet small',entry.id)) + '
' : + '

' + (ranking.ranked ? 'No verified runs have been published for this selection.' : 'This track and vehicle are awaiting replay qualification.') + + '

') + (ranking.nextOffset != null ? button('run-more-times','More times','quiet') : '') + + recordHistoryContent(ranking.history) + '
'; + } + + function fullGameContent() { + const categories = catalogue.adventureCatalogue || []; + return '
' + categories.map(category => { + const ranked = catalogue.boards.some(board => board.id === 'adventure-' + category.id && board.ranked); + return trackRow(category, category.summary, ranked, true); + }).join('') + + '
Shared rules and verification' + icon('chevron-down') + + '

The ranked launcher supports US v1.0 and US v1.1. Tracks routes get one completed save slot to unlock the courses. All Bosses uses that slot in Adventure. The other Adventure routes start from a new save. Each run uses its own save and blocks gameplay mods and Magic Codes.

' + + '

The clock starts in the Overworld for Adventure routes and in the first race for Tracks routes. It keeps running across menus, travel and races. The verifier checks the finish event and split times before staff review.

'; + } + function updateSubmissionQuota() { + clearTimeout(quotaTimer); + const panel = view() === 'speedruns' && root.querySelector('[data-submission-quota]'); + const quota = privateRuns?.submissionQuota; + if (!panel || !quota) return; + const now = quota.observedAt * 1000 + (performance.now() - privateRuns.receivedAt); + const active = quota.releasesAt.filter(stamp => stamp * 1000 > now); + panel.querySelector('strong').textContent = (quota.maxRuns - active.length) + ' of ' + quota.maxRuns + ' submissions left'; + const time = panel.querySelector('time'); + time.parentElement.hidden = active.length === 0; + if (active.length) { + const next = Math.min(...active) * 1000; + const date = new Date(next); + time.dateTime = date.toISOString(); + time.textContent = quotaDate.format(date); + quotaTimer = setTimeout(updateSubmissionQuota, Math.ceil(next - now)); + } + } + + function runListContent() { + const review = listingTab === 'review'; + const rows = privateRuns?.runs ?? []; + const quota = !review && !runId && privateRuns?.submissionQuota ? + '

' + + '
' : ''; + const videoStatus = { + queued:'Waiting for the video renderer', + rendering:'Preparing video…', + retrying:'Video render will retry automatically', + unavailable:'Video rendering is unavailable', + }; + return '

' + (listingTab === 'review' ? 'Review runs' : 'My runs') + + '

' + (runId ? button('run-list','Show all runs','quiet',listingTab) : '') + + button('run-refresh','Refresh','quiet') + button('run-back','Back to leaderboards','quiet') + '
' + quota + + (leaderboardBusy ? '

Loading runs…

' : rows.length ? + '
' + rows.map(run => '

' + + esc(run.title) + '

' + esc(states[run.state] || run.state) + + '

' + esc(run.category) + ' · ' + esc(run.vehicle) + ' · ' + clock(run.ticks ?? run.claimedTicks) + + (run.ticks == null ? ' (recorded)' : '') + '

' + esc(run.name) + ' · ' + + (run.linkedLocal ? 'Linked local run' : esc(run.platform) + ' ' + esc(run.arch)) + (run.rom === 77 ? ' · US v1.0' : ' · US v1.1') + '

' + + (run.notes ? '

' + esc(run.notes) + '

' : '') + (run.reason ? '

' + esc(run.reason) + '

' : '') + + (run.state === 'published' || review && run.videoState === 'ready' ? + '
' + button('run-video','Watch Video',review ? 'gold' : 'quiet',run.id) + '
' : + run.state === 'verified' && videoStatus[run.videoState] ? + '

' + videoStatus[run.videoState] + '

' : '') + + (review ? '
' + + (run.videoRequired && run.videoState !== 'ready' ? + '' : button('run-publish','Publish','gold',run.id)) + + button('run-reject','Reject','red',run.id) + '
' : '') + + '
').join('') + '
' : '

' + + (runId ? 'This run is no longer available in this list.' : 'No runs to show yet.') + '

'); + } + + async function loadLeaderboards({ more = false, focus } = {}) { + const seq = ++leaderSequence; + const playerOnly = listingTab==='boards' && !course && section==='overall' && playerPanel==='runs' && !!playerId; + leaderboardBusy = true; + leaderboardError = ''; + if (playerOnly) profileError = ''; + try { + if (listingTab !== 'boards') { + const endpoint = 'speedruns/' + listingTab + (runId ? '?run=' + encodeURIComponent(runId) : ''); + const data = await request(endpoint, { privateAccess:true }); + if (seq === leaderSequence) privateRuns = { ...data, receivedAt:performance.now() }; + } else if (course) { + const params = new URLSearchParams({score,kind:section}); + if (courseVehicle) params.set('vehicle',courseVehicle); + if (racer) params.set('racer',racer); + if (more && ranking?.nextOffset != null) params.set('offset',ranking.nextOffset); + const data = await request('speedruns/tracks/' + encodeURIComponent(course) + '?' + params); + if (seq === leaderSequence) ranking = more && ranking ? + {...data,history:ranking.history,entries:[...ranking.entries,...data.entries]} : data; + } else { + if (section==='overall') { + const path = playerOnly ? 'speedruns/overall/'+encodeURIComponent(playerId) + + (more && profile?.nextOffset!=null ? '?offset='+profile.nextOffset : '') : 'speedruns/overall'; + const [base,data] = await Promise.all([catalogue || request('speedruns'),request(path,{fresh:true})]); + if (seq === leaderSequence) { + catalogue = base; + if (playerOnly) profile = more && profile ? {...data,events:[...profile.events,...data.events]} : data; + else { + overall = data; + if (!overall.players.some(player=>player.id===playerId)) playerId = overall.players[0]?.id || ''; + } + } + } else { + const data = await request('speedruns' + (more && catalogue?.nextCursor ? '?cursor=' + encodeURIComponent(catalogue.nextCursor) : '')); + if (seq === leaderSequence) catalogue = more && catalogue ? {...catalogue, nextCursor:data.nextCursor, + customTracks:[...catalogue.customTracks, ...data.customTracks]} : data; + } + } + } catch (error) { + if (seq === leaderSequence) { + if (playerOnly) profileError = error.message; + else leaderboardError = error.message; + } + } finally { + if (seq === leaderSequence) { + leaderboardBusy = false; + if (view() === 'speedruns') refreshRegion('[data-leaderboard-region]',speedrunContent,focus); + } + } + } + + function postPage() { + return pagehead('Post a run', 'Choose Post to Leaderboard in the Launcher’s Replays tab. Once the upload finishes you can close DKR-R. The host prepares the video and Time Trial ghost for review. Track the submission in My runs.', 'speedruns'); + } + + function apiURL(path) { + const endpoint = new URL(config.apiBase, location.href); + const local = endpoint.origin === location.origin && ['127.0.0.1','localhost'].includes(endpoint.hostname); + if ((!local && endpoint.protocol !== 'https:') || endpoint.username || endpoint.password || endpoint.hash || endpoint.search) + throw new Error('The library address is invalid.'); + return new URL('/v1/' + path, endpoint); + } + + async function openRunVideo(id, target) { + if (!/^[A-Za-z0-9_-]{1,96}$/.test(id)) return; + const parent = target.closest('[data-leaderboard-region]'); + if (!parent) return; + const reviewCard = target.closest('[data-review-run]'); + const previous = parent.querySelector('[data-run-player]'); + const resumeAt = previous?.dataset.runPlayer === id ? previous.querySelector('video')?.currentTime : 0; + if (previous) previous.remove(); + const player = document.createElement('section'); + player.className = 'dkr-panel dkr-stack dkr-run-player'; + player.dataset.runPlayer = id; + const label = document.createElement('h2'); + label.className = 'dkr-subtitle'; + label.textContent = reviewCard ? 'Review video' : 'Verifier-rendered replay'; + const status = document.createElement('p'); + status.setAttribute('role', 'status'); + status.textContent = 'Checking for video…'; + const close = document.createElement('button'); + close.type = 'button'; + close.className = 'dkr-btn quiet'; + close.textContent = 'Close video'; + close.addEventListener('click', () => { player.remove(); target.focus(); }); + player.append(label, status, close); + if (reviewCard) target.parentElement.after(player); + else parent.append(player); + player.scrollIntoView({ block:'nearest' }); + close.focus({ preventScroll:true }); + try { + const path = 'speedruns/runs/' + encodeURIComponent(id) + '/video'; + const url = apiURL(path); + if (reviewCard) { + const { grant } = await request(path, {method:'POST', privateAccess:true}); + if (!player.isConnected) return; + url.searchParams.set('review',grant); + } + const ready = await fetch(url, { method:'HEAD', signal:AbortSignal.timeout(15000), redirect:'error' }); + if (!player.isConnected) return; + if (ready.status === 404) { + status.textContent = 'This run’s video is preparing or has not been rendered yet.'; + return; + } + if (!ready.ok) throw new Error(); + const video = document.createElement('video'); + video.controls = true; + video.preload = 'metadata'; + video.playsInline = true; + if (reviewCard) video.crossOrigin = 'anonymous'; + video.setAttribute('aria-label', 'Verifier-rendered gameplay'); + if (resumeAt > 0) video.addEventListener('loadedmetadata', () => { video.currentTime = resumeAt; }, {once:true}); + video.addEventListener('error', () => { + status.hidden = false; + status.textContent = 'The video could not be played. Open Watch Video again to retry.'; + }); + video.src = url.href; + status.hidden = true; + player.insertBefore(video, close); + } catch { + status.textContent = 'The run video is temporarily unavailable.'; + } + } + + async function openRunList(tab, id = '') { + if (!requireSignedIn({view:'speedruns'}, tab === 'review')) return; + if (view() !== 'speedruns') await go('speedruns', {}, false); + listingTab = tab; + runId = id; + privateRuns = undefined; + refreshRegion('[data-leaderboard-region]', speedrunContent); + await loadLeaderboards({focus:'run-back'}); + } + + function updateTrackFilter(target) { + const filter = target.dataset.boardFilter; + if (!filter || !catalogue) return; + if (filter === 'query') query = target.value; + if (filter === 'world') world = target.value; + if (filter === 'vehicle') vehicle = target.value; + if (filter === 'availability') availability = target.value; + const template = document.createElement('template'); + template.innerHTML = section === 'custom' ? customContent() : vanillaContent(); + root.querySelector('[data-track-results]')?.replaceWith(template.content.querySelector('[data-track-results]')); + renderIcons(); + } + root.addEventListener('input', event => { + if (event.target.dataset.boardFilter === 'query') updateTrackFilter(event.target); + }); + root.addEventListener('change', async event => { + const filter = event.target.dataset.boardFilter; + if (course && filter==='record') { + selectedRecord = Number(event.target.value); + refreshRegion('[data-leaderboard-region]',speedrunContent); + root.querySelector('[data-board-filter="record"]')?.focus({preventScroll:true}); + return true; + } + if (course && (filter === 'ranking-racer' || filter === 'ranking-vehicle')) { + if (filter === 'ranking-vehicle') { + courseVehicle = event.target.value; + racer = ''; + } else racer = event.target.value; + selectedRecord = null; + await loadLeaderboards(); + root.querySelector('[data-board-filter="' + filter + '"]')?.focus({preventScroll:true}); + } else if (filter !== 'query') updateTrackFilter(event.target); + }); + + async function action(action, id, target) { + if (action === 'online' || action === 'speedruns' || action === 'post-run') { await go(action); return true; } + if (action === 'online-period') { + if (activityPeriods.some(([value]) => value === id)) { + activityPeriod = id; + refreshRegion('[data-online-region]',onlineContent); + } + return true; + } + if (action === 'online-refresh' || action === 'online-more') { + await loadOnline({ fresh:action === 'online-refresh', more:action === 'online-more' }); return true; + } + if (action === 'online-copy') { + if (!/^[a-f0-9]{32}$/.test(id)) return true; + const url = 'https://positron-portal.com/dkr-r/#lobby=' + id; + try { + await navigator.clipboard.writeText(url); + onlineNotice = 'Link copied. In DKR-R Online, choose Find lobby from website.'; + } catch { + onlineNotice = 'Copy this link into the clipboard to find the lobby in DKR-R Online. ' + url; + } + refreshRegion('[data-online-region]',onlineContent); + return true; + } + if (action === 'overall-player') { + if (playerId===id) return true; + ++leaderSequence; + leaderboardBusy = false; + playerId = id; + playerPanel = 'score'; + profile = undefined; + profileError = ''; + refreshRegion('[data-leaderboard-region]',speedrunContent); + return true; + } + if (action === 'overall-panel' && (id==='score' || id==='runs')) { + playerId = playerId || overall?.players[0]?.id || ''; + playerPanel = id; + refreshRegion('[data-leaderboard-region]',speedrunContent); + if (id==='runs' && profile?.player.id!==playerId) await loadLeaderboards(); + return true; + } + if (action === 'record-point') { + selectedRecord = Number(id); + refreshRegion('[data-leaderboard-region]',speedrunContent); + return true; + } + if (action === 'run-course' || action === 'overall-track') { + fromProfile = action==='overall-track'; + if (fromProfile) section = target.dataset.kind; + course = id; + courseVehicle = fromProfile && section!=='full-game' ? target.dataset.vehicle : section === 'vanilla' ? vehicle : ''; + selectedRecord = null; + ranking = undefined; + racer = ''; + score = 'race'; + refreshRegion('[data-leaderboard-region]',speedrunContent); + await loadLeaderboards({focus:'run-back'}); + return true; + } + if (action === 'run-category' || action === 'run-back') { + if (action === 'run-category') { + section = id; + fromProfile = false; + playerId = ''; + playerPanel = 'score'; + profile = undefined; + profileError = ''; + query = world = vehicle = availability = ''; + } else if (fromProfile) { + section = 'overall'; + fromProfile = false; + } + ++leaderSequence; + const previous = course; + course = runId = ''; + ranking = undefined; + listingTab = 'boards'; + privateRuns = undefined; + leaderboardError = ''; + refreshRegion('[data-leaderboard-region]',speedrunContent); + if (previous) [...root.querySelectorAll('[data-action="run-course"]')] + .find(button => button.dataset.id === previous)?.focus({preventScroll:true}); + if (previous && section==='overall') [...root.querySelectorAll('[data-action="overall-track"]')] + .find(button=>button.dataset.id===previous)?.focus({preventScroll:true}); + if (!catalogue || section==='overall' && !overall) await loadLeaderboards(); + return true; + } + if (action === 'run-list') { await openRunList(id); return true; } + if (action === 'run-more' || action === 'run-more-times' || action === 'run-more-profile' || action === 'run-refresh') { + await loadLeaderboards({more:action !== 'run-refresh'}); + return true; + } + if (action === 'run-score' && (id === 'race' || id === 'lap')) { + score = id; + selectedRecord = null; + await loadLeaderboards({focus:'run-score'}); + return true; + } + if (action === 'run-video') { await openRunVideo(id, target); return true; } + if (action === 'run-publish' || action === 'run-reject') { + const reason = target.closest('article').querySelector('[data-review-note]').value; + target.disabled = true; + try { + await request('speedruns/runs/' + encodeURIComponent(id) + '/review', { method:'POST', privateAccess:true, + body:JSON.stringify({decision:action === 'run-publish' ? 'published' : 'rejected',reason}) }); + await loadLeaderboards(); + } finally { target.disabled = false; } + return true; + } + return false; + } + + function mounted() { + const next = view(); + if (!root.querySelector('[data-online-region],[data-leaderboard-region],[data-post-region]') && + ['online','speedruns','post-run'].includes(next)) return; + updateSubmissionQuota(); + if (next === currentPage) return; + currentPage = next; + clearInterval(directoryTimer); + if (next !== 'speedruns') { + ++leaderSequence; + section = 'overall'; + listingTab = 'boards'; + course = runId = playerId = ''; + playerPanel = 'score'; + ranking = profile = undefined; + profileError = ''; + fromProfile = false; + privateRuns = undefined; + leaderboardError = ''; + } + if (next === 'online' && root.querySelector('[data-online-region]')) { + loadOnline(); + directoryTimer = setInterval(() => { if (!document.hidden) loadOnline(); },30000); + } + if (next === 'speedruns' && !course && (!catalogue || !overall)) loadLeaderboards(); + } + root.addEventListener('toggle',event => { + if (event.target.matches('[data-points-explainer]')) explainPoints = event.target.open; + },true); + return { onlinePage, speedrunsPage, postPage, action, mounted, openRunList }; + }}; +}()); diff --git a/runtime-recomp/src/game/mod_library/website/assets/racing.css b/runtime-recomp/src/game/mod_library/website/assets/racing.css new file mode 100644 index 00000000..3fa5c89f --- /dev/null +++ b/runtime-recomp/src/game/mod_library/website/assets/racing.css @@ -0,0 +1,236 @@ +#dkr-mod-library .dkr-racing-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr)); + gap: 1rem; +} +#dkr-mod-library .dkr-racing-grid .dkr-panel { min-width: 0; overflow-wrap: anywhere; } +#dkr-mod-library .dkr-racing-count { color: var(--dkr-gold, #ffc15a); font-size: 1.5rem; } +#dkr-mod-library .dkr-racing-list { display: grid; grid-template-columns: minmax(0, 1fr); gap: .65rem; } +#dkr-mod-library .dkr-run-table { width: 100%; border-collapse: collapse; } +#dkr-mod-library .dkr-run-table th, #dkr-mod-library .dkr-run-table td { + text-align: left; + padding: .55rem; + border-bottom: 1px solid #31515d; + overflow-wrap: anywhere; +} +#dkr-mod-library .dkr-run-table th:last-child, #dkr-mod-library .dkr-run-table td:last-child { text-align: right; } +#dkr-mod-library .dkr-racing-file { width: 100%; max-width: 100%; } +#dkr-mod-library .dkr-online-stats { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 7.5rem), 1fr)); + gap: .9rem 1.25rem; + border-top: 1px solid #31515d; + margin: 0; + padding-top: .9rem; +} +#dkr-mod-library .dkr-online-stats dt { color: #abc4cd; font-size: .8rem; } +#dkr-mod-library .dkr-online-stats dd { margin: .25rem 0 0; } +#dkr-mod-library .dkr-online-stats dd:not(.dkr-small) { font-size: 1.25rem; font-weight: 700; } +#dkr-mod-library .dkr-online-history-stats { border: 0; padding: 0; } +#dkr-mod-library .dkr-online-periods { border-top: 1px solid #31515d; padding-top: .9rem; } +#dkr-mod-library .dkr-online-periods button[aria-pressed="true"] { + background: #b53722; + border-color: #ffc15a; + color: #fff1c1; +} +#dkr-mod-library .dkr-online-history { + background: #091d2a; + border: 1px solid #31515d; + border-radius: 8px; + padding: .65rem .8rem; +} +#dkr-mod-library .dkr-online-bars { + list-style: none; + display: flex; + align-items: end; + justify-content: space-between; + gap: clamp(2px, 1vw, 8px); + height: 3.25rem; + padding: 0; + margin: .55rem 0 .35rem; + border-bottom: 1px solid #31515d; +} +#dkr-mod-library .dkr-online-bars li { + flex: 1; + max-width: 3rem; + height: max(2px, var(--peak)); + background: #1abfa9; + border-radius: 3px 3px 0 0; +} + + +#dkr-mod-library .dkr-board-filters { + display: grid; + grid-template-columns: minmax(12rem,2fr) repeat(3,minmax(8rem,1fr)); + gap: .75rem; +} +#dkr-mod-library .dkr-ranking-filters { display: flex; flex-wrap: wrap; gap: .75rem; } +#dkr-mod-library .dkr-ranked-select { display:grid; gap:.375rem; min-width:0; font-size:.875rem; font-weight:600; color:#c9dee7; } +#dkr-mod-library .dkr-ranked-select-control { position:relative; min-width:0; } +#dkr-mod-library .dkr-ranked-select-control .dkr-select { appearance:none; width:100%; min-height:44px; padding-right:2.3rem; } +#dkr-mod-library .dkr-ranked-select-control > .dkr-icon { position:absolute; top:50%; right:.75rem; transform:translateY(-50%); color:#ffc15a; pointer-events:none; } +#dkr-mod-library .dkr-board-filters .dkr-search { min-width:0; } +#dkr-mod-library .dkr-board-filters .dkr-search:focus-within { outline:2px solid #ffc15a; outline-offset:2px; } +#dkr-mod-library .dkr-board-filters .dkr-search input:focus { outline:none; } +#dkr-mod-library .dkr-track-name { min-width:0; overflow-wrap:anywhere; } +#dkr-mod-library .dkr-track-name h2, #dkr-mod-library .dkr-track-name p { margin:0; } +#dkr-mod-library .dkr-track-name h2 { font-size:1.025rem; } +#dkr-mod-library .dkr-track-name p { margin-top:.25rem; } +#dkr-mod-library .dkr-track-row { + display:grid; grid-template-columns:clamp(10rem,22%,16rem) minmax(0,1fr); + align-items:start; gap:1rem 1.25rem; +} +#dkr-mod-library .dkr-track-actions { display:grid; justify-items:start; gap:.5rem; margin-top:.75rem; } +#dkr-mod-library .dkr-track-splits { font-size:.85rem; color:#c9dee7; } +#dkr-mod-library .dkr-track-splits summary { cursor:pointer; } +#dkr-mod-library .dkr-track-records { + display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,10rem),1fr)); + gap:.85rem 1rem; min-width:0; +} +#dkr-mod-library .dkr-track-vehicle { display:grid; align-content:start; gap:.35rem; min-width:0; } +#dkr-mod-library .dkr-track-vehicle h3 { color:#ffc15a; font-size:.9rem; margin:0; } +#dkr-mod-library .dkr-track-score { + display:flex; flex-wrap:wrap; align-items:baseline; gap:.2rem .5rem; min-width:0; font-size:.85rem; +} +#dkr-mod-library .dkr-track-keeper { overflow-wrap:anywhere; min-width:0; } +#dkr-mod-library .dkr-track-time { display:inline-flex; align-items:baseline; gap:.45rem; white-space:nowrap; font-variant-numeric:tabular-nums; } +#dkr-mod-library .dkr-first-place { + display:inline-flex; align-items:center; gap:.2rem; color:#ffc15a; font-size:.75rem; font-weight:700; +} +#dkr-mod-library .dkr-first-place .dkr-icon { width:.9rem; height:.9rem; } +#dkr-mod-library .dkr-first-place svg { width:100%; height:100%; } +#dkr-mod-library .dkr-full-category summary { display:flex; align-items:center; flex-wrap:wrap; gap:.6rem; cursor:pointer; list-style:none; } +#dkr-mod-library .dkr-full-category summary::-webkit-details-marker { display:none; } +#dkr-mod-library .dkr-full-category .dkr-track-name { display:grid; flex:1; min-width:min(100%,12rem); } +#dkr-mod-library .dkr-full-category[open] summary .dkr-icon { transform:rotate(180deg); } +#dkr-mod-library .dkr-full-category p { margin-top:.75rem; } +@media (max-width:800px) { + #dkr-mod-library .dkr-board-filters { grid-template-columns:repeat(2,minmax(0,1fr)); } +} +@media (max-width:660px) { + #dkr-mod-library .dkr-track-row { grid-template-columns:minmax(0,1fr); } +} +@media (max-width:440px) { + #dkr-mod-library .dkr-board-filters { grid-template-columns:1fr; } + #dkr-mod-library .dkr-run-table th, #dkr-mod-library .dkr-run-table td { padding:.4rem .23rem; font-size:.79rem; } +} + +#dkr-mod-library .dkr-notification-slot { position:relative; display:inline-flex; } +#dkr-mod-library .dkr-header-nav .dkr-notification-bell { position:relative; width:42px; justify-content:center; padding:8px; } +#dkr-mod-library .dkr-notification-badge { + position:absolute; top:-.37rem; right:-.33rem; min-width:1.15rem; padding:0 .22rem; + border:1px solid #ffe6aa; border-radius:1rem; background:#c74a22; color:#fff4d4; + text-align:center; font-size:.69rem; line-height:1.05rem; +} +#dkr-mod-library .dkr-notification-panel { + position:absolute; z-index:20; top:calc(100% + .5rem); right:0; + width:min(24rem,calc(100vw - 2rem)); display:grid; gap:.6rem; + background:#0b2637; box-shadow:0 8px 20px #0007; padding:1rem; +} +#dkr-mod-library .dkr-notification-panel h2 { font-size:1.1rem; margin:0; } +#dkr-mod-library .dkr-notification-panel ul { + list-style:none; margin:0; padding:0 0 .3rem; max-height:min(50vh,24rem); overflow-y:auto; +} +#dkr-mod-library .dkr-notification-item { + width:100%; display:grid; gap:.25rem; padding:.65rem .6rem; + background:#102f43; border:1px solid #31536a; border-radius:6px; margin-bottom:.35rem; text-align:left; + color:#e4eef2; overflow-wrap:anywhere; +} +#dkr-mod-library .dkr-notification-item:hover { background:#16445b; } +#dkr-mod-library .dkr-notification-item[data-unread=true] { border-color:#ab8548; } +#dkr-mod-library .dkr-notification-dot { + display:inline-block; height:.48rem; width:.48rem; border-radius:50%; background:#ffc15a; margin-right:.4rem; +} +@media (max-width:850px) { + #dkr-mod-library .dkr-header { position:relative; } + #dkr-mod-library .dkr-notification-slot { position:static; } + #dkr-mod-library .dkr-notification-panel { top:calc(100% - .45rem); right:.55rem; } +} + +.dkr-run-player video { + display: block; + width: 100%; + max-height: 70vh; + border-radius: .65rem; + background: #071420; +} +.dkr-adventure-splits { padding-inline-start: 1.5rem; } + +#dkr-mod-library .dkr-points { + border-left: 3px solid #f3b759; + padding: .55rem .9rem; + background: #102d3f; + border-radius: .35rem; +} +#dkr-mod-library .dkr-points summary { color: #ffd083; font-weight: 700; cursor: pointer; } +#dkr-mod-library .dkr-points[open] summary { margin-bottom: .55rem; } +#dkr-mod-library .dkr-points dl { + display: grid; grid-template-columns: minmax(9.5rem,auto) minmax(0,1fr); gap: .25rem .75rem; margin: 0; +} +#dkr-mod-library .dkr-points dt { font-weight: 700; } +#dkr-mod-library .dkr-points dd { margin: 0; } +#dkr-mod-library .dkr-overall-layout { + display: grid; grid-template-columns: minmax(0,1.12fr) minmax(0,1fr); gap: 1rem; align-items: start; +} +#dkr-mod-library .dkr-overall-layout > section { min-width: 0; } +#dkr-mod-library .dkr-overall-table { font-variant-numeric: tabular-nums; } +#dkr-mod-library .dkr-overall-table :is(th,td):nth-child(3), +#dkr-mod-library .dkr-overall-table :is(th,td):nth-child(4) { text-align: right; } +#dkr-mod-library .dkr-overall-table td:nth-child(4), +#dkr-mod-library .dkr-overall-counts > div:last-child dd { color: #ffc965; } +#dkr-mod-library .dkr-overall-table :is(th,td):last-child { text-align: right; } +#dkr-mod-library .dkr-overall-table button { overflow-wrap: anywhere; max-width: 100%; text-align: left; } +#dkr-mod-library :is(.dkr-overall-table,.dkr-overall-profile-tabs) button[aria-pressed=true] { + background: #a93e24; border-color: #f3b759; color: #fff6da; +} +#dkr-mod-library .dkr-overall-profile h2 { overflow-wrap: anywhere; } +#dkr-mod-library .dkr-overall-score { color: #ffc965; font-size: 1.35rem; font-variant-numeric: tabular-nums; } +#dkr-mod-library .dkr-overall-counts { + display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: .7rem; + margin: 0; padding: .65rem 0; border-block: 1px solid #31566b; +} +#dkr-mod-library .dkr-overall-counts dt { color: #b9d0dc; } +#dkr-mod-library .dkr-overall-counts dd { margin: .1rem 0 0; font-size: 1.15rem; font-weight: 700; } +#dkr-mod-library .dkr-profile-points { display: grid; gap: .65rem; } +#dkr-mod-library .dkr-profile-points span { color: #ffc965; font-variant-numeric: tabular-nums; } +#dkr-mod-library .dkr-profile-points progress { + display: block; appearance: none; width: 100%; height: .45rem; margin-top: .25rem; + overflow: hidden; border: 0; border-radius: .3rem; background: #061e2c; +} +#dkr-mod-library .dkr-profile-points progress::-webkit-progress-bar { background: #061e2c; } +#dkr-mod-library .dkr-profile-points progress::-webkit-progress-value { background: #2edfbd; } +#dkr-mod-library .dkr-profile-points progress::-moz-progress-bar { background: #2edfbd; } +#dkr-mod-library .dkr-overall-record { color: #ffc965; } +#dkr-mod-library .dkr-record-history { + border: 1px solid #305a70; background: #0c2434; border-radius: .55rem; padding: .75rem; +} +#dkr-mod-library .dkr-record-history h3 { margin: 0; } +#dkr-mod-library .dkr-record-history strong { color: #ffd083; font-variant-numeric: tabular-nums; } +#dkr-mod-library .dkr-record-plot { + display: grid; grid-template-columns: minmax(4.9rem,auto) minmax(0,1fr); + gap: .35rem; color: #b8d0da; font-size: .78rem; font-variant-numeric: tabular-nums; +} +#dkr-mod-library .dkr-record-axis { display: flex; flex-direction: column; justify-content: space-between; height: 126px; padding: 3px .25rem 10px; } +#dkr-mod-library .dkr-record-line { height: 126px; position: relative; } +#dkr-mod-library .dkr-record-line svg { display: block; width: 100%; height: 100%; } +#dkr-mod-library .dkr-record-line path { fill: none; vector-effect: non-scaling-stroke; } +#dkr-mod-library .dkr-record-grid { stroke: #325369; stroke-width: 1; } +#dkr-mod-library .dkr-record-step { stroke: #ffc965; stroke-width: 2.2; } +#dkr-mod-library .dkr-record-mark { + position: absolute; transform: translate(-50%,-50%); width: 1.5rem; height: 1.5rem; + border: 0; padding: 0; background: transparent; cursor: pointer; +} +#dkr-mod-library .dkr-record-mark::after { + content: ''; display: block; margin: auto; width: .6rem; height: .6rem; + border: 2px solid #ffc965; border-radius: 50%; background: #0c2434; +} +#dkr-mod-library .dkr-record-mark[aria-pressed=true]::after { background: #ffc965; } +#dkr-mod-library .dkr-record-dates { display: flex; flex-wrap: wrap; justify-content: space-between; gap: .25rem; } +#dkr-mod-library .dkr-record-history select { max-width: 100%; text-overflow: ellipsis; } +@media (max-width:850px) { + #dkr-mod-library .dkr-overall-layout { grid-template-columns: minmax(0,1fr); } +} +@media (max-width:480px) { + #dkr-mod-library .dkr-points dl { grid-template-columns: minmax(0,1fr); } + #dkr-mod-library .dkr-overall-table button { padding-inline: .35rem; } +} diff --git a/runtime-recomp/src/game/mod_library/website/assets/replay-format.js b/runtime-recomp/src/game/mod_library/website/assets/replay-format.js new file mode 100644 index 00000000..eeff9fd2 --- /dev/null +++ b/runtime-recomp/src/game/mod_library/website/assets/replay-format.js @@ -0,0 +1,138 @@ +// DKRREPL2 stores one applied controller sample per 30 Hz update. The race +// result ends at finishTick, and optional neutral input extends playback. +// The file is untrusted evidence. Only native re-simulation can verify its claims. +export const MAX_REPLAY_BYTES = 3 * 1024 * 1024; +export const ADVENTURE_RULES = 'adventure-us80-7'; +const originalRouteRules = 'adventure-us80-6'; +const milestoneRules = 'adventure-us80-5'; +const oldAdventureRules = [originalRouteRules,milestoneRules,'adventure-us80-4','adventure-us80-3','adventure-us80-2','adventure-us80-1']; +const tracksCategories = ['all-trophy-races-dino-first','all-trophy-races-ffl-first','car-percent','hover-percent','plane-percent']; +export const adventureCategories = ['any-percent','100-percent','all-trophy-races', + 'all-bosses','all-minigames','tt-amulet-no-wrong-warp','any-percent-glitchless',...tracksCategories]; +const adventureKeys = new Set(['board','engine','ruleset','releaseHash','rom','platform','arch','ticks', + 'finishTick','clockTicks','startSeed','checkpoints','notes','ticket','practice','category','splits']); +export const replayHash = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value); +export const replayId = value => typeof value === 'string' && /^[A-Za-z0-9_-]{1,96}$/.test(value); +const decoder = new TextDecoder('utf-8', { fatal: true }); +const manifestKeys = new Set(['board', 'engine', 'ruleset', 'releaseHash', 'rom', 'platform', 'arch', + 'ticks', 'clockTicks', 'startSeed', 'checkpoints', 'splits', 'notes']); +const rankedKeys = new Set([...manifestKeys, 'ticket', 'practice', 'racer', 'finishTick', 'course', 'vehicle', 'trackId', 'trackHash', 'laps']); +export const CUSTOM_RULES = 'custom-time-trial-us80-1'; +export const CUSTOM_VARIABLE_LAPS_RULES = 'custom-time-trial-us80-2'; +export const ancientLakeRacers = [ + ['ancient-lake-car-krunch', 'Krunch'], ['ancient-lake-car-bumper', 'Bumper'], + ['ancient-lake-car-tiptup', 'Tiptup'], ['ancient-lake-car-conker', 'Conker'], + ['ancient-lake-car-timber', 'Timber'], ['ancient-lake-car-banjo', 'Banjo'], + ['ancient-lake-car-drumstick', 'Drumstick'], ['ancient-lake-car-pipsy', 'Pipsy'], + ['ancient-lake-car-tt', 'T.T.'], ['ancient-lake-car', 'Diddy'] +]; +export const rankedTicket = value => typeof value === 'string' && /^[A-Za-z0-9_-]{24}\.[0-9]{1,12}\.[a-f0-9]{64}$/.test(value); +const tick = (value, maximum) => Number.isInteger(value) && value > 0 && value <= maximum; + +export function parseReplay(bytes) { + const invalid = () => { throw new Error('Choose a valid DKR-R replay made with a supported build.'); }; + if (bytes.byteLength < 16 || bytes.byteLength > MAX_REPLAY_BYTES || + !['DKRREPL1', 'DKRREPL2'].includes(decoder.decode(bytes.subarray(0, 8)))) invalid(); + const native = bytes[7] === 50; + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const size = view.getUint32(8, true); + if (size < 2 || size > 65536 || size > bytes.byteLength - 16) invalid(); + const manifest = JSON.parse(decoder.decode(bytes.subarray(12, 12 + size))); + if (native && [ADVENTURE_RULES, ...oldAdventureRules].includes(manifest?.ruleset)) { + if (!validAdventure(manifest, bytes, size)) invalid(); + return manifest; + } + if (size > 16384 || bytes.byteLength > 1024 * 1024) invalid(); + if (native && manifest?.practice === true) { + if (!validNative(manifest, bytes, size)) invalid(); + return manifest; + } + if (!manifest || Array.isArray(manifest) || typeof manifest !== 'object' || + Object.keys(manifest).some(key => !(native ? rankedKeys : manifestKeys).has(key)) || + (native && (manifest.practice !== false || !rankedTicket(manifest.ticket) || + !validNative(manifest, bytes, size))) || + !replayId(manifest.board) || !replayHash(manifest.engine) || !replayId(manifest.ruleset) || + (manifest.releaseHash !== null && !replayHash(manifest.releaseHash)) || + ![77, 80].includes(manifest.rom) || !['windows', 'linux'].includes(manifest.platform) || + !['x86_64', 'aarch64'].includes(manifest.arch) || + !tick(manifest.ticks, 216000) || !tick(manifest.clockTicks, manifest.ticks * (native ? 2 : 1)) || + !Number.isInteger(manifest.startSeed) || manifest.startSeed < 0 || manifest.startSeed > 0xffffffff || + bytes.byteLength !== 12 + size + 4 * manifest.ticks || + (manifest.notes !== undefined && (typeof manifest.notes !== 'string' || manifest.notes.length > 600))) invalid(); + const { ticks, clockTicks, checkpoints, splits } = manifest; + const finish = native ? manifest.finishTick ?? ticks : ticks; + if (!Array.isArray(checkpoints) || checkpoints.length !== Math.ceil(finish / 600)) invalid(); + if (checkpoints.some((entry, index) => !Array.isArray(entry) || entry.length !== 2 || + entry[0] !== Math.min((index + 1) * 600, finish) || !replayHash(entry[1]))) invalid(); + if (!Array.isArray(splits) || splits.length < 1 || splits.length > 32 || + splits.at(-1) !== clockTicks || + splits.some((value, index) => !tick(value, clockTicks) || (index && value <= splits[index - 1]))) invalid(); + return manifest; +} + +function validAdventure(manifest, bytes, size) { + const { ticks, clockTicks, checkpoints, category } = manifest; + const splits = manifest.splits; + const routeSplits = [ADVENTURE_RULES, originalRouteRules].includes(manifest.ruleset); + const nativeSplits = routeSplits || manifest.ruleset === milestoneRules; + const categories = routeSplits ? adventureCategories : adventureCategories.slice(0, nativeSplits ? 6 : 3); + const tracks = routeSplits && (tracksCategories.includes(category) || + (manifest.ruleset === ADVENTURE_RULES && ['all-trophy-races','all-minigames'].includes(category))); + const start = tracks ? 'Start' : 'Overworld'; + const uniqueLabels = new Set(); + const validSplits = nativeSplits ? + Array.isArray(splits) && splits.length >= 2 && splits.length <= 64 && + splits.every((entry, i) => { + if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string' || + !/^[A-Za-z0-9 .%-]{1,64}$/.test(entry[0]) || uniqueLabels.has(entry[0]) || + !tick(entry[1], clockTicks) || entry[1] % 2 || (i && entry[1] < splits[i-1][1])) return false; + uniqueLabels.add(entry[0]); + return true; + }) && splits[0][0] === start && splits[0][1] === 2 && splits.at(-1)[0] === 'Finish' && splits.at(-1)[1] === clockTicks : + splits === undefined; + return Object.keys(manifest).every(key => adventureKeys.has(key)) && + validSplits && categories.includes(category) && + (manifest.rom === 77 || manifest.rom === 80) && manifest.startSeed === 0x444b5252 && + tick(ticks, 648000) && ticks === manifest.finishTick && tick(clockTicks, 2 * ticks) && + clockTicks % 2 === 0 && bytes.byteLength === 12 + size + 4 * ticks && + Array.isArray(checkpoints) && checkpoints.length === Math.ceil(ticks / 1800) && + checkpoints.every((entry, i) => Array.isArray(entry) && entry.length === 2 && + entry[0] === Math.min((i + 1) * 1800, ticks) && replayHash(entry[1])) && + (manifest.notes === undefined || (typeof manifest.notes === 'string' && manifest.notes.length <= 600)) && + (manifest.practice === true || + (manifest.practice === false && [ADVENTURE_RULES, ...oldAdventureRules.slice(0,4)].includes(manifest.ruleset) && + manifest.releaseHash === null && + manifest.board === 'adventure-' + category && replayHash(manifest.engine) && rankedTicket(manifest.ticket) && + ['windows','linux'].includes(manifest.platform) && manifest.arch === 'x86_64')); +} + +function validNative(manifest, bytes, size) { + const { ticks, clockTicks, checkpoints, splits } = manifest; + const finish = manifest.finishTick ?? ticks; + const racer = manifest.racer ?? 9; + const legacy = manifest.ruleset === 'ancient-lake-us80-practice-2'; + const variable = manifest.ruleset === CUSTOM_VARIABLE_LAPS_RULES; + const custom = variable || manifest.ruleset === CUSTOM_RULES; + const laps = variable ? manifest.laps : 3; + if (variable ? (!tick(laps, 5) || laps === 3) : manifest.laps !== undefined) return false; + const vehicle = ['car','hovercraft','plane'].includes(manifest.vehicle); + if (!custom && (manifest.trackId !== undefined || manifest.trackHash !== undefined)) return false; + const target = custom ? manifest.course === undefined && replayId(manifest.trackId) && + replayHash(manifest.trackHash) && vehicle && (manifest.practice || replayHash(manifest.releaseHash)) : + legacy ? manifest.course === undefined && manifest.vehicle === undefined : + manifest.ruleset === 'vanilla-time-trial-us80-1' && + typeof manifest.course === 'string' && /^[a-z][a-z0-9-]{1,47}$/.test(manifest.course) && + vehicle && + (manifest.course !== 'ancient-lake' || manifest.vehicle !== 'car'); + return (manifest.rom === 77 || manifest.rom === 80) && manifest.startSeed === 0x444b5252 && target && + Number.isInteger(racer) && racer >= 0 && racer < ancientLakeRacers.length && + tick(finish, 54000) && tick(ticks, finish + 210) && ticks >= finish && + tick(clockTicks, 2 * finish) && clockTicks % 2 === 0 && + bytes.byteLength === 12 + size + 4 * ticks && + bytes.subarray(12 + size + 4 * finish).every(value => value === 0) && + Array.isArray(checkpoints) && checkpoints.length === Math.ceil(finish / 600) && + checkpoints.every((entry, i) => Array.isArray(entry) && entry.length === 2 && + entry[0] === Math.min((i + 1) * 600, finish) && replayHash(entry[1])) && + Array.isArray(splits) && splits.length === laps && splits.at(-1) === clockTicks && + splits.every((value, i) => tick(value, clockTicks) && value % 2 === 0 && (!i || value > splits[i - 1])); +} diff --git a/runtime-recomp/src/game/mod_library/website/index.html b/runtime-recomp/src/game/mod_library/website/index.html index ebe67d65..ba938cdc 100644 --- a/runtime-recomp/src/game/mod_library/website/index.html +++ b/runtime-recomp/src/game/mod_library/website/index.html @@ -7,14 +7,14 @@ - + DKR-R Mod Library - + @@ -22,7 +22,10 @@ - + + + +
diff --git a/runtime-recomp/src/game/mod_library/website/privacy.html b/runtime-recomp/src/game/mod_library/website/privacy.html index a238e3bc..16b1a8f8 100644 --- a/runtime-recomp/src/game/mod_library/website/privacy.html +++ b/runtime-recomp/src/game/mod_library/website/privacy.html @@ -14,6 +14,9 @@

What we keep

Download countersDisplay tracked website download requests for each mod.Visitors see aggregate totals. Temporary retry and rate-limit records stay in the private service. Ratings, reviews and datesHelp players choose mods and keep one rating per account for each mod.Visitors when the review is visible. Hidden reviews remain available to their author and staff. Mod requests and repliesCheck a suggested mod and tell you the outcome.The requester and staff. Private staff notes are visible only to staff. +Online player count and public lobby detailsShow how many signed-in players are connected, the number of active accounts, peak activity, and which lobbies are open to the public.Visitors see aggregate counts and peak times, plus public lobby titles and available places. Private lobbies and join credentials stay in the launcher. +Submission notifications and read statusTell you when your mod or run changes status and remember which notices you have read.You can see updates for your own submissions. Moderators and administrators can see items in their review queues. +Speedrun replays, game inputs and run detailsCheck the time, ruleset, ROM revision, track version, platform and recorded inputs before a run is published.You and authorised reviewers see pending runs. Visitors can download published replays and see the display name on the leaderboard. Temporary sign-in records, session hashes and optional remembered-device hashesComplete sign-in and protect account actions.The private account service. Staff upload records, filenames, file sizes, transfer checksums and statusResume interrupted transfers and connect completed files to the library.The private library service and authorised staff. Completed mod packages and cover images are served publicly by the web host. @@ -38,7 +41,8 @@

Requests, retention and deletion

The browser uses a fingerprint of a selected file's size and sample bytes to help match it when resuming an upload. It also checks the previously accepted file chunks against their stored checksums before resuming. These checks identify file contents, not your device. The website does not save the selected file's bytes in browser storage. Deleting a staff account removes the account link from retained upload records; it does not remove files used by published mods.

Published and rejected requests, published draft history and staff activity logs are removed after 180 days by scheduled cleanup. Unfinished requests and unpublished drafts stay available while work is pending. Expired sign-in, session and remembered-device records are removed by scheduled cleanup; expired credentials stop working immediately even before that cleanup runs.

You can delete your website account from account settings. This removes its Discord identity mapping, sessions, remembered devices, ratings, reviews, comments, comment reports and review reports you submitted and your mod requests. In retained staff history, your account name is replaced with “Deleted account”. Published mods and their creator credits stay in the catalogue unless staff remove or update them separately. An administrator must leave another active administrator before deleting their own account.

-

Account deletion removes the live application records. Private provider backups and infrastructure records can have their own retention periods. If you sign in again after deletion, a new website account is created.

+

Your submission notifications are kept for 90 days. Staff queue notifications stay available until the related review leaves the queue. Deleting your account removes your notification read state.

+

Deleting your account removes your runs from the leaderboard and makes their replay files unavailable through the website. Scheduled cleanup then removes those files and clears rejected submissions after 30 days. Private provider backups and infrastructure records can have their own retention periods. If you sign in again after deletion, a new website account is created.

Please keep personal information out of public reviews and comments. Mod requests are shared with the team that reviews them; include only the release information and links they need.

Questions or corrections

Contact the DKR-R Mod Library team through the community Discord for help with your account, a review or a request. Use account settings for deletion, and include the relevant mod or request title when asking about a correction.

diff --git a/runtime-recomp/src/game/mod_store.cpp b/runtime-recomp/src/game/mod_store.cpp index 1aa26638..29cf602f 100644 --- a/runtime-recomp/src/game/mod_store.cpp +++ b/runtime-recomp/src/game/mod_store.cpp @@ -7,9 +7,12 @@ #include "linux_keyring.hpp" #include "store_vehicle_adapter.hpp" #include "mod_store.hpp" +#include "cloud_saves/progress.hpp" #include "mod_store_install.hpp" +#include "mods/magic_code_package.hpp" #include "stb/stb_image.h" #include "updates/update_core.hpp" +#include "time_trial/ghost_file.hpp" #include #include #include @@ -50,6 +53,7 @@ #define DKR_PROFILE_WITH_KEYRING 1 #include "online_profile/linux_device_store.hpp" #include "atomic_snapshot.hpp" +#include "save_manager.hpp" namespace dkr::store { namespace { @@ -64,6 +68,9 @@ struct Error : std::runtime_error { Error(std::string message, unsigned s = 0, Json context = Json::object()) : std::runtime_error(std::move(message)), status(s), details(std::move(context)) {} }; +struct TransportFailure : Error { + using Error::Error; +}; std::string lower(std::string value) { for (auto& c : value) if (c >= 'A' && c <= 'Z') @@ -192,7 +199,16 @@ struct Request { std::uint64_t offset = 0, limit = MaxJson; unsigned timeout = 12000; std::string online_instance; + unsigned test_port = 0; }; +constexpr auto kReplayLimit = 3 * 1024 * 1024; +std::string local_ranked_origin(unsigned port) { + return "http://127.0.0.1:" + std::to_string(port); +} +bool local_ranked_request(const Request& request) { + return request.test_port > 1023 && request.test_port <= 65535 && + prefix(request.url, local_ranked_origin(request.test_port) + "/v1/speedruns"); +} using Sink = std::function; #ifdef _WIN32 @@ -233,16 +249,19 @@ std::string header(HINTERNET request, DWORD field) { return out; } Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { - if (!trusted_url(r.url, prefix(r.url, Api))) + const bool loopback = local_ranked_request(r); + if (!loopback && !trusted_url(r.url, prefix(r.url, Api))) throw Error("The library returned an unapproved file address."); auto url = wide(r.url); URL_COMPONENTS parts{}; parts.dwStructSize = sizeof(parts); parts.dwHostNameLength = parts.dwUrlPathLength = parts.dwExtraInfoLength = DWORD(-1); - if (!WinHttpCrackUrl(url.c_str(), DWORD(url.size()), 0, &parts) || parts.nScheme != INTERNET_SCHEME_HTTPS || - parts.nPort != 443) + if (!WinHttpCrackUrl(url.c_str(), DWORD(url.size()), 0, &parts) || + parts.nScheme != (loopback ? INTERNET_SCHEME_HTTP : INTERNET_SCHEME_HTTPS) || + parts.nPort != (loopback ? r.test_port : 443U)) throw Error("Use the secure library address."); - Internet session{WinHttpOpen(L"DKR-R-ModStore/1.0.7-beta8", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, + Internet session{WinHttpOpen(L"DKR-R-ModStore/1.0.7-beta8", + loopback ? WINHTTP_ACCESS_TYPE_NO_PROXY : WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0)}; if (!session.h) throw Error("The secure connection could not start."); @@ -251,16 +270,16 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { #ifdef WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3 tls |= WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3; #endif - if (!WinHttpSetOption(session, WINHTTP_OPTION_SECURE_PROTOCOLS, &tls, sizeof(tls))) + if (!loopback && !WinHttpSetOption(session, WINHTTP_OPTION_SECURE_PROTOCOLS, &tls, sizeof(tls))) throw Error("The secure connection could not start."); std::wstring host(parts.lpszHostName, parts.dwHostNameLength), path(parts.lpszUrlPath, parts.dwUrlPathLength); if (parts.dwExtraInfoLength) path.append(parts.lpszExtraInfo, parts.dwExtraInfoLength); - Internet connection{WinHttpConnect(session, host.c_str(), 443, 0)}; + Internet connection{WinHttpConnect(session, host.c_str(), parts.nPort, 0)}; const auto method = wide(r.method); Internet request{connection.h ? WinHttpOpenRequest(connection, method.c_str(), path.c_str(), nullptr, WINHTTP_NO_REFERER, - WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE) + WINHTTP_DEFAULT_ACCEPT_TYPES, loopback ? 0 : WINHTTP_FLAG_SECURE) : nullptr}; if (!request.h) throw Error("The library connection could not open."); @@ -269,8 +288,9 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { DWORD disable = WINHTTP_DISABLE_COOKIES; WinHttpSetOption(request, WINHTTP_OPTION_DISABLE_FEATURE, &disable, sizeof(disable)); std::string headers = "Accept: */*\r\n"; - if (prefix(r.url, Api)) { - headers += "Origin: https://positron-portal.com\r\n"; + if (loopback || prefix(r.url, Api)) { + if (!loopback) + headers += "Origin: https://positron-portal.com\r\n"; if (!r.online_instance.empty()) headers += "X-DKRR-Instance: " + r.online_instance + "\r\n"; if (!r.token.empty()) { @@ -283,7 +303,7 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { throw Error("Credentials cannot be sent to a file host."); headers += "Referer: https://positron-portal.com/dkr-r/index.html\r\n"; } - if (r.method == "POST") + if (r.method == "POST" || r.method == "PUT") headers += "Content-Type: " + r.type + "\r\n"; if (r.offset) { headers += "Range: bytes=" + std::to_string(r.offset) + "-\r\n"; @@ -291,12 +311,13 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { headers += "If-Range: " + r.etag + "\r\n"; } auto wh = wide(headers); - if (stop.stop_requested() || - !WinHttpSendRequest(request, wh.c_str(), DWORD(wh.size()), + if (stop.stop_requested()) + throw Error("Transfer paused."); + if (!WinHttpSendRequest(request, wh.c_str(), DWORD(wh.size()), r.body.empty() ? WINHTTP_NO_REQUEST_DATA : const_cast(r.body.data()), DWORD(r.body.size()), DWORD(r.body.size()), 0) || !WinHttpReceiveResponse(request, nullptr)) - throw Error("Could not reach the library. Check your connection and retry."); + throw TransportFailure("Could not reach the library. Check your connection and retry."); Response response; response.url = r.url; DWORD bytes = sizeof(response.status); @@ -323,7 +344,7 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { throw Error("Transfer paused."); DWORD read = 0; if (!WinHttpReadData(request, buffer.data(), DWORD(buffer.size()), &read)) - throw Error("The connection was interrupted. Retry to continue."); + throw TransportFailure("The connection was interrupted. Retry to continue."); if (!read) break; if (read > r.limit - total) @@ -344,7 +365,8 @@ Response http_once(const Request&, std::stop_token, const Sink&) { } #else Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { - if (!trusted_url(r.url, prefix(r.url, Api))) + const bool loopback = local_ranked_request(r); + if (!loopback && !trusted_url(r.url, prefix(r.url, Api))) throw Error("Unapproved library address."); static const bool initialized = [] { return curl_global_init(CURL_GLOBAL_DEFAULT) == CURLE_OK; }(); if (!initialized) @@ -373,8 +395,9 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { }; Transfer transfer{&r, &out, &sink, stop}; auto add = [&](std::string value) { cleanup.headers = curl_slist_append(cleanup.headers, value.c_str()); }; - if (prefix(r.url, Api)) { - add("Origin: https://positron-portal.com"); + if (loopback || prefix(r.url, Api)) { + if (!loopback) + add("Origin: https://positron-portal.com"); if (!r.online_instance.empty()) add("X-DKRR-Instance: " + r.online_instance); if (!r.token.empty() && r.token.size() == 43 && identifier(r.token)) @@ -384,7 +407,8 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { throw Error("Credentials cannot be sent to a file host."); add("Referer: https://positron-portal.com/dkr-r/index.html"); } - if (r.method == "POST") + const bool sends_body = r.method == "POST" || r.method == "PUT"; + if (sends_body) add("Content-Type: " + r.type); if (r.offset && !r.etag.empty() && r.etag.find_first_of("\r\n") == r.etag.npos) add("If-Range: " + r.etag); @@ -396,11 +420,15 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { curl_easy_setopt(cleanup.curl, CURLOPT_LOW_SPEED_TIME, 15L); curl_easy_setopt(cleanup.curl, CURLOPT_NOSIGNAL, 1L); curl_easy_setopt(cleanup.curl, CURLOPT_FOLLOWLOCATION, 0L); - curl_easy_setopt(cleanup.curl, CURLOPT_PROTOCOLS_STR, "https"); - if (r.method == "POST") { + curl_easy_setopt(cleanup.curl, CURLOPT_PROTOCOLS_STR, loopback ? "http" : "https"); + if (loopback) + curl_easy_setopt(cleanup.curl, CURLOPT_PROXY, ""); + if (sends_body) { curl_easy_setopt(cleanup.curl, CURLOPT_POST, 1L); curl_easy_setopt(cleanup.curl, CURLOPT_POSTFIELDS, r.body.data()); curl_easy_setopt(cleanup.curl, CURLOPT_POSTFIELDSIZE_LARGE, curl_off_t(r.body.size())); + if (r.method == "PUT") + curl_easy_setopt(cleanup.curl, CURLOPT_CUSTOMREQUEST, "PUT"); } std::string range; if (r.offset) { @@ -481,7 +509,7 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { if (transfer.error) std::rethrow_exception(transfer.error); if (code != CURLE_OK) - throw Error("The library connection was interrupted. Retry to continue."); + throw TransportFailure("The library connection was interrupted. Retry to continue."); return out; } #endif @@ -494,7 +522,8 @@ Response http(Request request, std::stop_token stop, const Sink& sink = {}) { if (response.status != 301 && response.status != 302 && response.status != 303 && response.status != 307 && response.status != 308) return response; - if (hops == 3 || request.method != "GET" || !request.token.empty() || prefix(request.url, Api)) + if (hops == 3 || request.test_port || request.method != "GET" || !request.token.empty() || + prefix(request.url, Api)) throw Error("The library returned an unsupported redirect.", response.status); auto next = response.location; if (next.starts_with('/') && !next.starts_with("//")) @@ -638,6 +667,7 @@ struct Service::Impl { std::mutex download_persist_mutex; std::condition_variable_any cv; Snapshot state; + std::mutex cloud_saves_mutex; dkr::runtime::AtomicSnapshot published{std::make_shared()}; std::filesystem::path root; std::string version, token, device, browser; @@ -665,8 +695,11 @@ struct Service::Impl { std::map preparation_stops; #include "mod_store/community_service.inl" // Workers are last: joined before the objects captured by their callbacks. - std::jthread worker, image_worker, download_worker, auth_worker; + std::jthread worker, image_worker, download_worker, auth_worker, cloud_save_worker; void publish() { + const bool cloud_active = !token.empty() && !state.cloud_saves_account.empty() && + state.cloud_saves_account == text(state.user, "id", 160); + cloud_saves::progress_writes.account(cloud_active ? std::optional(account) : std::nullopt); community_fence(); ++state.generation; published.store(std::make_shared(state)); @@ -713,6 +746,27 @@ struct Service::Impl { } catch (...) { /* A diagnostic must never replace the original failure. */ } } + Request ranked_request(std::string path, bool authenticated = false) { + const auto local = read_json(root.parent_path() / "ranked-local.json"); + const auto port = local.find("port"); + if (port != local.end() && port->is_number_integer()) { + const auto value = port->get(); + auto credential = text(local, "token", 43); + if (value < 1024 || value > 65535 || + (authenticated && (credential.size() != 43 || !identifier(credential)))) + throw Error("The local ranked test profile is invalid."); + Request request{local_ranked_origin(unsigned(value)) + path, + "GET", + {}, + authenticated ? std::move(credential) : std::string{}}; + request.test_port = unsigned(value); + return request; + } + std::lock_guard lock(mutex); + if (authenticated && token.empty()) + throw Error("Sign in to the Mod Library to submit a run."); + return {std::string(Api) + path, "GET", {}, authenticated ? token : std::string{}}; + } Json get(std::string path, std::stop_token stop, bool private_request = false) { std::string credential; { @@ -752,6 +806,8 @@ struct Service::Impl { token.clear(); ++account; state.user = nullptr; + state.cloud_sync = cloud_saves::SyncStatus::Idle; + state.cloud_saves_status.clear(); state.personal = Json::object(); state.staff = Json::object(); state.admin = Json::object(); @@ -1269,6 +1325,7 @@ Service::~Service() { p.image_worker.request_stop(); p.download_worker.request_stop(); p.auth_worker.request_stop(); + p.cloud_save_worker.request_stop(); p.community_tracking_worker.request_stop(); p.cv.notify_all(); } @@ -1280,6 +1337,7 @@ std::string download_key(const std::string& item, const std::string& release, co return item + "_" + release + (instance.empty() ? "" : "_" + instance); } void Service::gameplay(bool active) { + cloud_saves::progress_writes.gameplay(active); dkr::storage::gameplay(active); auto& p = *impl_; { @@ -1310,10 +1368,11 @@ void Service::configure(const std::filesystem::path& config, std::string version p.image_worker.request_stop(); p.download_worker.request_stop(); p.auth_worker.request_stop(); + p.cloud_save_worker.request_stop(); p.community_tracking_worker.request_stop(); p.cv.notify_all(); - for (auto* worker : - {&p.worker, &p.image_worker, &p.download_worker, &p.auth_worker, &p.community_tracking_worker}) + for (auto* worker : {&p.worker, &p.image_worker, &p.download_worker, &p.auth_worker, &p.cloud_save_worker, + &p.community_tracking_worker}) if (worker->joinable()) worker->join(); }); @@ -1322,15 +1381,19 @@ void Service::configure(const std::filesystem::path& config, std::string version p.worker = std::jthread([&p](std::stop_token stop) { p.run(stop); }); p.image_worker = std::jthread([&p](std::stop_token stop) { p.image_run(stop); }); p.download_worker = std::jthread([&p](std::stop_token stop) { p.download_run(stop); }); + p.cloud_save_worker = std::jthread([this](std::stop_token stop) { publish_progress(stop); }); p.community_tracking_worker = std::jthread([&p](std::stop_token stop) { p.community_tracking(stop); }); p.queue([&p](std::stop_token stop) { const auto preferences = read_json(p.root / "preferences.json"), cached = read_json(p.root / "catalogue.json"); + const auto cloud = read_json(p.root / "cloud-saves.json"); const auto saved = read_json(p.root / "downloads.json"); const auto receipts = read_json(p.root / "installations.json"); auto restored = dkr::store::history::restore(saved, receipts, [&](const std::string& path) { return dkr::store::history::member_present(p.root.parent_path(), path); }); p.update([&](Snapshot& s) { + if (cloud.value("enabled", false)) + s.cloud_saves_account = text(cloud, "account", 160); if (preferences.value("layout", 0) == 1) s.layout = 1; s.remember = preferences.contains("remember") && preferences["remember"] == true; @@ -1389,6 +1452,393 @@ void Service::refresh() { auto& p = *impl_; p.queue([&p](std::stop_token stop) { p.refresh(stop); }); } +void Service::load_leaderboards(std::string cursor, std::optional track) { + if ((!cursor.empty() && !identifier(cursor)) || + (track && (!identifier(track->id) || (!track->vehicle.empty() && !identifier(track->vehicle)) || + (!track->racer.empty() && !identifier(track->racer))))) + return; + auto& p = *impl_; + { + std::lock_guard lock(p.mutex); + if (!p.configured || p.state.speedrun_loading) + return; + p.state.speedrun_loading = true; + p.state.speedrun_error.clear(); + p.publish(); + } + if (!p.queue([&p, cursor = std::move(cursor), track = std::move(track)](std::stop_token stop) { + try { + std::string url = "/v1/speedruns"; + if (track) { + const char* kind = track->full_game ? "?kind=full-game" + : track->custom ? "?kind=custom" + : "?kind=vanilla"; + url += "/tracks/" + track->id + kind; + if (!track->vehicle.empty()) + url += "&vehicle=" + track->vehicle; + if (!track->racer.empty()) + url += "&racer=" + track->racer; + if (track->best_lap) + url += "&score=lap"; + if (track->offset) + url += "&offset=" + std::to_string(track->offset); + } else if (!cursor.empty()) { + url += "?cursor=" + cursor; + } + auto data = document(p.ranked_request(url), stop); + if (!track && (!data.contains("boards") || !data["boards"].is_array() || + !data.contains("customTracks") || !data["customTracks"].is_array())) + throw Error("The leaderboard service returned an invalid track list."); + if (track && (!data.contains("track") || !data["track"].is_object() || + data["track"].value("id", std::string{}) != track->id || !data.contains("entries") || + !data["entries"].is_array() || !data.contains("vehicles") || + !data["vehicles"].is_array() || !data.contains("racers") || !data["racers"].is_array())) + throw Error("The leaderboard service returned an invalid result list."); + p.update([&](Snapshot& state) { + state.speedrun_loading = false; + if (track) { + if (track->offset && state.speedrun_board) { + Json combined = *state.speedrun_board; + for (auto& row : data["entries"]) + combined["entries"].push_back(std::move(row)); + data["entries"] = std::move(combined["entries"]); + data["history"] = std::move(combined["history"]); + } + state.speedrun_board = std::make_shared(std::move(data)); + return; + } + if (!cursor.empty() && state.speedrun_catalogue) { + Json combined = *state.speedrun_catalogue; + for (auto& item : data["customTracks"]) + combined["customTracks"].push_back(std::move(item)); + combined["nextCursor"] = data["nextCursor"]; + data = std::move(combined); + } + state.speedrun_catalogue = std::make_shared(std::move(data)); + }); + } catch (const std::exception&) { + p.update([](Snapshot& state) { + state.speedrun_loading = false; + state.speedrun_error = "Leaderboards are unavailable. Try refreshing."; + }); + } + })) { + p.update([](Snapshot& state) { + state.speedrun_loading = false; + state.speedrun_error = "Wait for the current library request to finish."; + }); + } +} +Json Service::overall_rankings(const std::string& player, unsigned offset) { + if (!player.empty() && !identifier(player)) + throw Error("Invalid leaderboard player."); + auto path = std::string("/v1/speedruns/overall"); + if (!player.empty()) + path += "/" + player + "?offset=" + std::to_string(offset); + auto data = document(impl_->ranked_request(path), {}); + if (!data.is_object() || data.value("scoringVersion", 0) != 1 || + !(player.empty() + ? data.contains("players") && data["players"].is_array() + : data.contains("player") && data["player"].is_object() && text(data["player"], "id", 96) == player && + data.contains("events") && data["events"].is_array())) + throw Error("Overall rankings are unavailable. Try refreshing."); + return data; +} +Json Service::ranked_attempt(std::string board) { + auto request = impl_->ranked_request("/v1/speedruns/attempts", true); + request.method = "POST"; + request.body = Json{{"board", std::move(board)}}.dump(); + return document(request, {}); +} +Json Service::adventure_record(const std::string& category) { + if (!identifier(category)) + throw Error("Invalid Full Game category."); + return document(impl_->ranked_request("/v1/speedruns/tracks/" + category + "?kind=full-game", false), {}); +} +Json Service::submit_ranked_replay(const std::filesystem::path& path, bool link_local) { + const auto file = dkr::mods::read_file(path, kReplayLimit); + auto request = impl_->ranked_request(link_local ? "/v1/speedruns/runs/claim" : "/v1/speedruns/runs", true); + request.method = "POST"; + request.type = "application/octet-stream"; + request.body.assign(file.begin(), file.end()); + return document(request, {}); +} +Json Service::ranked_runs(bool review) { + return document(impl_->ranked_request(review ? "/v1/speedruns/review" : "/v1/speedruns/mine", true), {}); +} +std::vector Service::published_replay_times() { + auto request = impl_->ranked_request("/v1/speedruns/mine/published", true); + const auto route = request.url; + std::vector times; + for (;;) { + const auto page = document(request, {}); + const auto& scores = page.at("scores"); + const bool more = page.at("more").get(); + if (!scores.is_array() || scores.size() > 256 || (more && scores.empty())) + throw Error("The leaderboard returned an invalid time page."); + for (const auto& score : scores) { + const auto board = text(score, "board", 96); + const auto& ticks = score.at("ticks"); + if (!identifier(board) || !ticks.is_number_integer() || ticks.get() <= 0) + throw Error("The leaderboard returned an invalid time."); + PublishedReplayTime time{board, ticks.get()}; + if (!times.empty() && times.back() >= time) + throw Error("The leaderboard returned an invalid time order."); + times.push_back(std::move(time)); + } + if (!more) + return times; + const auto& [board, ticks] = times.back(); + request.url = route + "?afterBoard=" + board + "&afterTicks=" + std::to_string(ticks); + } +} +void Service::review_ranked_run(const std::string& id, bool publish, std::string reason) { + if (!identifier(id)) + throw Error("Invalid replay ID."); + auto request = impl_->ranked_request("/v1/speedruns/runs/" + id + "/review", true); + request.method = "POST"; + Json review{{"decision", publish ? "published" : "rejected"}, {"reason", std::move(reason)}}; + if (publish) + review["evidence"] = "replay"; + request.body = review.dump(); + (void)document(request, {}); +} +void Service::save_ranked_replay(const std::string& id, const std::filesystem::path& destination, bool own_run) { + if (!identifier(id)) + throw Error("Invalid replay ID."); + auto request = impl_->ranked_request("/v1/speedruns/runs/" + id + "/replay", own_run); + request.limit = kReplayLimit; + const auto file = http(std::move(request), {}); + if (file.status != 200 || !file.body.starts_with("DKRREPL2")) + throw Error("The replay could not be downloaded."); + const dkr::mods::Bytes replay(file.body.begin(), file.body.end()); + dkr::mods::write_new_file(destination, replay); + try { + namespace trial = dkr::runtime::time_trial; + auto ghost_request = impl_->ranked_request("/v1/speedruns/runs/" + id + "/ghost", own_run); + ghost_request.limit = trial::kMaxPortableGhostBytes; + const auto ghost = http(std::move(ghost_request), {}); + if (ghost.status == 200 && ghost.body.starts_with(trial::portable_ghost_prefix(dkr::mods::sha256(replay)))) + dkr::mods::write_new_file(trial::portable_ghost_file(destination), + dkr::mods::Bytes(ghost.body.begin(), ghost.body.end())); + } catch (const std::exception&) { + // Older runs and temporarily unavailable ghosts are still playable from their replay. + } +} +void Service::set_cloud_saves(const std::string& account, bool enabled) { + auto& p = *impl_; + std::scoped_lock operation(p.cloud_saves_mutex); + std::lock_guard lock(p.mutex); + if (p.gameplay || account.empty() || p.token.empty() || text(p.state.user, "id") != account) + throw Error("Sign in with Discord and return to the launcher to change Cloud Saves."); + auto state = read_json(p.root / "cloud-saves.json"); + if (text(state, "account") != account || (enabled && !state.value("enabled", false))) + state = {{"account", account}, {"common", Json::object()}}; + state["enabled"] = enabled; + try { + write_json(p.root / "cloud-saves.json", state); + } catch (const std::exception&) { + p.state.cloud_sync = cloud_saves::SyncStatus::Error; + p.state.cloud_saves_status = "Could not save the Cloud Saves setting on this device."; + p.publish(); + throw; + } + p.state.cloud_sync = cloud_saves::SyncStatus::Idle; + p.state.cloud_saves_account = enabled ? account : std::string{}; + p.state.cloud_saves_status = + enabled ? "Cloud Saves enabled for this device." : "Cloud Saves paused on this device."; + p.publish(); +} + +void Service::publish_progress(std::stop_token stop) { + while (auto batch = cloud_saves::progress_writes.take(stop)) { + std::string account; + { + std::lock_guard lock(impl_->mutex); + if (impl_->account != batch->account_generation) + continue; + account = impl_->state.cloud_saves_account; + } + try { + sync_cloud_saves(account, cloud_saves::SyncScope::PublishProgress, &*batch, stop); + } catch (const Error& error) { + if (!stop.stop_requested() && + (dynamic_cast(&error) || error.status >= 500 || error.status == 409)) + cloud_saves::progress_writes.retry(*batch); + } catch (const std::exception&) { + // The shared sync path publishes the failure for the launcher. + } + } +} + +void Service::sync_cloud_saves(const std::string& account, cloud_saves::SyncScope scope) { + sync_cloud_saves(account, scope, nullptr, {}); +} + +void Service::sync_cloud_saves(const std::string& account, cloud_saves::SyncScope scope, + const cloud_saves::ProgressBatch* progress, std::stop_token stop) { + namespace saves = dkr::runtime::saves; + using cloud_saves::Action; + using cloud_saves::SyncStatus; + auto& p = *impl_; + std::scoped_lock operation(p.cloud_saves_mutex); + std::string credential; + std::uint64_t generation; + { + std::lock_guard lock(p.mutex); + if (progress && progress->account_generation != p.account) + return; + if ((!progress && p.gameplay) || account.empty() || account != p.state.cloud_saves_account || + account != text(p.state.user, "id") || p.token.empty()) + throw Error("Enable Cloud Saves while signed in with Discord on this device."); + credential = p.token; + generation = p.account; + p.state.cloud_sync = SyncStatus::Syncing; + p.state.cloud_saves_status = "Syncing Cloud Saves..."; + p.publish(); + } + const auto check_account = [&] { + if (stop.stop_requested() || (!progress && p.gameplay) || generation != p.account || + account != p.state.cloud_saves_account || account != text(p.state.user, "id")) + throw Error("The signed-in account changed while syncing. Your local saves are still available."); + }; + unsigned uploaded = 0, downloaded = 0; + const auto reconcile = [&] { + constexpr std::string_view route = "/v1/launcher/cloud-saves"; + const auto make_request = [&](std::string suffix = {}) { + Request request{std::string(Api) + std::string(route) + std::move(suffix), "GET", {}, credential}; + request.timeout = 4500; + return request; + }; + auto state = read_json(p.root / "cloud-saves.json"); + if (text(state, "account") != account || !state.value("enabled", false)) + throw Error("Cloud Saves are disabled on this device."); + auto& common = state["common"]; + if (!common.is_object()) + common = Json::object(); + const auto inventory = document(make_request("?format=2"), stop); + if (text(inventory, "accountId") != account || !inventory.contains("saves") || !inventory["saves"].is_array() || + inventory["saves"].size() > saves::cloud_save_slots().size()) + throw Error("The Cloud Save service returned an invalid account or save inventory."); + std::map remote; + for (const auto& entry : inventory["saves"]) + if (!remote.emplace(text(entry, "key", 40), entry).second) + throw Error("Cloud Save inventory contains a duplicate save."); + + const bool modded_supported = inventory.value("moddedAdventure", false); + unsigned needs_recovery = 0, deferred = 0; + bool modded_unavailable = false; + for (const auto& slot : saves::cloud_save_slots()) { + if (!cloud_saves::includes_slot(scope, slot.key) || (progress && !progress->slots.contains(slot.key))) + continue; + const std::string key(slot.key); + if (key == "modded-adventure" && !modded_supported) { + modded_unavailable = true; + continue; + } + std::string error; + std::vector local; + if (!saves::read_cloud_save(key, local, error)) { + ++needs_recovery; + continue; + } + const auto found = remote.find(key); + const auto local_hash = local.empty() ? std::string{} : dkr::mods::sha256(local); + const auto cloud_hash = found == remote.end() ? std::string{} : text(found->second, "digest", 64); + const auto revision = found == remote.end() ? 0ULL : found->second.value("revision", 0ULL); + const auto size = found == remote.end() ? 0ULL : found->second.value("bytes", 0ULL); + if (found != remote.end() && (!hash_string(cloud_hash) || !revision || !size || size > slot.limit)) + throw Error("The cloud metadata for " + std::string(slot.label) + " is invalid."); + const auto action = cloud_saves::next_action(local_hash, cloud_hash, text(common, key.c_str(), 64), scope); + if (action == Action::Defer) { + ++deferred; + continue; + } + if (action == Action::None) { + if (!local_hash.empty()) + common[key] = local_hash; + continue; + } + + auto request = make_request("/" + key + "?revision=" + std::to_string(revision)); + { + std::lock_guard lock(p.mutex); + check_account(); + } + if (action == Action::Upload) { + request.method = "PUT"; + request.type = "application/octet-stream"; + request.body.assign(reinterpret_cast(local.data()), local.size()); + const auto result = document(request, stop); + if (text(result, "digest", 64) != local_hash || result.value("revision", 0ULL) != revision + 1) + throw Error("The cloud service did not confirm the uploaded save."); + common[key] = local_hash; + ++uploaded; + } else { + request.limit = slot.limit; + const auto result = http(request, stop); + const std::vector replacement(result.body.begin(), result.body.end()); + if (result.status != 200) + throw Error("The cloud image could not be downloaded. Sync again to retry.", result.status); + if (result.type != "application/octet-stream" || replacement.size() != size || + dkr::mods::sha256(replacement) != cloud_hash) + throw Error("The cloud image changed or could not be verified. Sync again to retry."); + std::lock_guard lock(p.mutex); + check_account(); + if (!saves::replace_cloud_save(key, local, replacement, error)) + throw Error(error); + common[key] = cloud_hash; + ++downloaded; + } + std::lock_guard lock(p.mutex); + check_account(); + write_json(p.root / "cloud-saves.json", state); + } + std::lock_guard lock(p.mutex); + check_account(); + write_json(p.root / "cloud-saves.json", state); + p.state.cloud_sync = needs_recovery || modded_unavailable ? SyncStatus::Error + : deferred ? SyncStatus::Idle + : SyncStatus::Synced; + p.state.cloud_saves_status = uploaded || downloaded + ? "Cloud Saves synced. Downloaded " + std::to_string(downloaded) + + " and uploaded " + std::to_string(uploaded) + " save files." + : "Cloud Saves checked."; + if (needs_recovery) + p.state.cloud_saves_status += + " Save Manager can help recover " + std::to_string(needs_recovery) + " local files."; + if (modded_unavailable) + p.state.cloud_saves_status += " Modded Adventure cloud sync is unavailable."; + if (deferred) + p.state.cloud_saves_status += scope == cloud_saves::SyncScope::PublishHostedOnline + ? " Newer cloud saves will be applied after leaving the lobby." + : " Newer cloud saves will be applied after play."; + p.publish(); + }; + try { + try { + reconcile(); + } catch (const Error& error) { + if (error.status != 409) + throw; + // Another device committed a newer revision. Recheck which copy to use. + reconcile(); + } + } catch (const std::exception& error) { + std::lock_guard lock(p.mutex); + if (generation == p.account && account == p.state.cloud_saves_account) { + const auto* http_error = dynamic_cast(&error); + p.state.cloud_sync = cloud_saves::sync_failure(dynamic_cast(&error) != nullptr, + http_error ? http_error->status : 0); + p.state.cloud_saves_status = p.state.cloud_sync == SyncStatus::Unreachable + ? "Could not reach Cloud Saves. Try again in a moment." + : error.what(); + p.publish(); + } + throw; + } +} + bool Service::refresh_names() { auto& p = *impl_; { @@ -1668,6 +2118,8 @@ void Service::login() { p.token = token; p.device = device; ++p.account; + p.state.cloud_sync = cloud_saves::SyncStatus::Idle; + p.state.cloud_saves_status.clear(); p.upload_proofs.clear(); p.state.personal = Json::object(); p.state.staff = Json::object(); @@ -1715,6 +2167,8 @@ void Service::logout() { ++p.account; p.browser.clear(); p.state.user = nullptr; + p.state.cloud_sync = cloud_saves::SyncStatus::Idle; + p.state.cloud_saves_status.clear(); p.state.personal = Json::object(); p.state.staff = Json::object(); p.state.admin = Json::object(); diff --git a/runtime-recomp/src/game/mod_store.hpp b/runtime-recomp/src/game/mod_store.hpp index 6505b138..3141b4e0 100644 --- a/runtime-recomp/src/game/mod_store.hpp +++ b/runtime-recomp/src/game/mod_store.hpp @@ -1,16 +1,24 @@ #pragma once +#include "cloud_saves/sync.hpp" #include #include #include #include #include #include +#include #include #include +#include #include +namespace dkr::cloud_saves { +struct ProgressBatch; +} + namespace dkr::store { using Json = nlohmann::json; +using PublishedReplayTime = std::pair; struct Download { std::string key, item, release, title, category, state = "Queued", error, digest, version, intent, instance; std::filesystem::path file; @@ -20,11 +28,22 @@ struct Image { unsigned width = 0, height = 0; std::vector rgba; }; +struct LeaderboardTrackQuery { + std::string id, vehicle, racer; + bool custom = false, best_lap = false; + unsigned offset = 0; + bool full_game = false; +}; struct Snapshot { std::shared_ptr items = std::make_shared(Json::array()); + std::shared_ptr speedrun_catalogue, speedrun_board; + std::string speedrun_error; + bool speedrun_loading = false; Json user = nullptr, personal = Json::object(), staff = Json::object(), admin = Json::object(); Json reviews = Json::object(), uploads = Json::array(), assets = Json::array(), upload = Json::object(); std::vector downloads; + std::string cloud_saves_account, cloud_saves_status; + cloud_saves::SyncStatus cloud_sync = cloud_saves::SyncStatus::Idle; std::string status, error, last_action; Json last_result; std::uint64_t generation = 0, mutation = 0; @@ -42,7 +61,18 @@ class Service { void configure(const std::filesystem::path&, std::string version); std::shared_ptr view() const; void refresh(); + void load_leaderboards(std::string cursor = {}, std::optional track = {}); + Json overall_rankings(const std::string& player = {}, unsigned offset = 0); + Json ranked_attempt(std::string board); + Json adventure_record(const std::string& category); + Json submit_ranked_replay(const std::filesystem::path&, bool link_local = false); + Json ranked_runs(bool review = false); + std::vector published_replay_times(); + void review_ranked_run(const std::string& id, bool publish, std::string reason); + void save_ranked_replay(const std::string& id, const std::filesystem::path& destination, bool own_run); void gameplay(bool active); + void set_cloud_saves(const std::string& account, bool enabled); + void sync_cloud_saves(const std::string& account, cloud_saves::SyncScope scope = cloud_saves::SyncScope::All); bool refresh_names(); void layout(int); void remember(bool); @@ -68,6 +98,10 @@ class Service { std::string take_browser_url(); private: + void sync_cloud_saves(const std::string& account, cloud_saves::SyncScope scope, + const cloud_saves::ProgressBatch* progress, std::stop_token stop); + void publish_progress(std::stop_token stop); + struct Impl; std::unique_ptr impl_; }; diff --git a/runtime-recomp/src/game/mod_store_style.inl b/runtime-recomp/src/game/mod_store_style.inl index 3784c585..71252659 100644 --- a/runtime-recomp/src/game/mod_store_style.inl +++ b/runtime-recomp/src/game/mod_store_style.inl @@ -95,15 +95,21 @@ std::string StoreSummary(const StoreJson& item) { } return value; } -int StoreTabLine(const std::vector& labels, int selected, float width, const char* id) { +int StoreTabLine(const std::vector& labels, int selected, float width, const char* id, + bool prefer_single_row = false) { if (labels.empty()) return 0; selected = std::clamp(selected, 0, int(labels.size()) - 1); + float normal_width = 8.F * static_cast(labels.size() - 1); + if (prefer_single_row) + for (const auto& label : labels) + normal_width += PaddockSectionTabWidth(label.c_str()); + const bool compact = prefer_single_row && normal_width > width; ImGui::PushID(id); const auto start = ImGui::GetCursorScreenPos(); float x = 0, y = 0, row_height = 0; for (int i = 0; i < int(labels.size()); ++i) { - const float size = std::min(width, PaddockSectionTabWidth(labels[i].c_str())); + const float size = std::min(width, PaddockSectionTabWidth(labels[i].c_str(), compact)); if (x > 0 && x + size > width) { x = 0; y += row_height + 8; @@ -111,12 +117,12 @@ int StoreTabLine(const std::vector& labels, int selected, float wid } ImGui::SetCursorScreenPos({start.x + x, start.y + y}); ImGui::PushID(i); - if (PaddockSectionTab((labels[i] + "###tab").c_str(), i == selected, size)) + if (PaddockSectionTab((labels[i] + "###tab").c_str(), i == selected, size, compact)) selected = i; StoreControlFocus(); row_height = std::max(row_height, ImGui::GetItemRectSize().y); ImGui::PopID(); - x += size + 8; + x += size + (compact ? 4.F : 8.F); } ImGui::SetCursorScreenPos({start.x, start.y + y + row_height + 16}); ImGui::PopID(); diff --git a/runtime-recomp/src/game/mod_store_ui.inl b/runtime-recomp/src/game/mod_store_ui.inl index 10849395..2c6eeac0 100644 --- a/runtime-recomp/src/game/mod_store_ui.inl +++ b/runtime-recomp/src/game/mod_store_ui.inl @@ -62,6 +62,7 @@ void StoreControlFocus() { g_mod_store.page_focus = id; } SDL_Renderer* g_mod_store_renderer = nullptr; +SDL_Texture* g_speedrunning_preview_texture = nullptr; bool g_store_in_game = false; constexpr std::array kStoreCategoryNames = { "All", "Tracks", "Characters", "Vehicles", "Custom Magic Codes", "Texture packs"}; @@ -167,6 +168,8 @@ int StoreCombo(const char* id, int current, const std::vector& raw_ #include "store_polish_controls.inl" void ReleaseModStoreTextures() { ReleaseVehicleTextures(); + if (g_speedrunning_preview_texture) + SDL_DestroyTexture(std::exchange(g_speedrunning_preview_texture, nullptr)); for (auto& [url, texture] : g_mod_store.textures) if (texture) SDL_DestroyTexture(texture); diff --git a/runtime-recomp/src/game/mods/legacy_mod_launch.cpp b/runtime-recomp/src/game/mods/legacy_mod_launch.cpp index dd5ab267..7dc9a4dd 100644 --- a/runtime-recomp/src/game/mods/legacy_mod_launch.cpp +++ b/runtime-recomp/src/game/mods/legacy_mod_launch.cpp @@ -1,6 +1,7 @@ #include "session_content/policy.hpp" #include "../shared_saves.hpp" #include "legacy_mod_launch.hpp" +#include "personal_adventure_paths.hpp" #include "vehicle_binding.hpp" #include "legacy_track_catalog.hpp" #include "../dkr_save_codec.hpp" @@ -65,12 +66,16 @@ std::shared_ptr prepare_mod_launch(const std::filesyste const DetailedLaunchProgress& detailed) { auto out = std::make_shared(); out->content_enabled = dkr::session_content::preparing(); - if (!online && !out->content_enabled) - return out; // The offline catalog is never consulted for online launches. The lobby's // separately verified, frozen RuntimeResources supply online assets. if (online) return out; + namespace saves = dkr::runtime::saves; + out->save_subfolder = saves::personal_adventure_subfolder(out->content_enabled); + out->save_path = saves::personal_adventure_path(config, out->content_enabled); + out->pak_directory = config; + if (!out->content_enabled) + return out; std::string personal_error; if (!dkr::runtime::saves::shared::prepare(config, personal_error)) throw Error(personal_error); @@ -117,9 +122,6 @@ std::shared_ptr prepare_mod_launch(const std::filesyste const auto identity = "dkr-offline-code-session-1\n" + out->fingerprint + "\n" + out->code->identity; out->fingerprint = sha256(View(reinterpret_cast(identity.data()), identity.size())); } - out->save_subfolder.clear(); - out->save_path = config / "saves" / "dkr.us.v77.bin"; - out->pak_directory = config; std::string save_error; if (!dkr::runtime::saves::shared::prepare(config, save_error)) throw Error(save_error); diff --git a/runtime-recomp/src/game/mods/online_mod_sync.cpp b/runtime-recomp/src/game/mods/online_mod_sync.cpp index 9c257c2c..d6039c9c 100644 --- a/runtime-recomp/src/game/mods/online_mod_sync.cpp +++ b/runtime-recomp/src/game/mods/online_mod_sync.cpp @@ -262,6 +262,10 @@ void ModSync::host_loop(std::shared_ptr bundle, std::stop_token st hosted = true; else if (hosted) break; + if (!network.host) { + pause(stop, std::chrono::milliseconds(20)); + continue; + } if (network.game_active) { peers.clear(); { @@ -800,3 +804,4 @@ void ModSync::client_loop(const SyncSettings& settings, const RuntimePreparation } } } // namespace dkr::mods::online +#include "netplay/session_links/mod_host.inl" diff --git a/runtime-recomp/src/game/mods/online_mod_sync.hpp b/runtime-recomp/src/game/mods/online_mod_sync.hpp index 0bd9c304..7c7913ec 100644 --- a/runtime-recomp/src/game/mods/online_mod_sync.hpp +++ b/runtime-recomp/src/game/mods/online_mod_sync.hpp @@ -79,6 +79,8 @@ class ModSync { bool prepare_host(SyncSettings settings, std::filesystem::path legacy, std::vector labs, std::string revision, bool custom_ai, RuntimePreparation prepare); bool watch_client(SyncSettings settings, RuntimePreparation prepare); + bool promote_cached_host(SyncSettings settings, std::string& error); + bool cached_host_active() const; void consent(bool accept, bool keep_offline = true, std::string approved_code_offer = {}); void cancel(); SyncView snapshot() const; diff --git a/runtime-recomp/src/game/mods/sdk2_tools_ui.inl b/runtime-recomp/src/game/mods/sdk2_tools_ui.inl index 40ab3852..a7402dea 100644 --- a/runtime-recomp/src/game/mods/sdk2_tools_ui.inl +++ b/runtime-recomp/src/game/mods/sdk2_tools_ui.inl @@ -85,7 +85,8 @@ void DrawSdk2Tools() { ImGui::PushStyleVar(ImGuiStyleVar_ButtonTextAlign, {0.5F, 0.5F}); ImGui::SetNextWindowSize({std::max(320.F, display.x - 48.F), std::max(240.F, display.y - 48.F)}, ImGuiCond_Appearing); - if (!ImGui::Begin("CUSTOM MAGIC CODE TOOLS", &open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar)) { + if (!dkr::runtime::ui::begin_dialog_window("CUSTOM MAGIC CODE TOOLS", &open, + ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar)) { ImGui::End(); ImGui::PopStyleVar(); if (!open) { diff --git a/runtime-recomp/src/game/netplay/direct_session.cpp b/runtime-recomp/src/game/netplay/direct_session.cpp index 6fa49eb8..ae1dd75d 100644 --- a/runtime-recomp/src/game/netplay/direct_session.cpp +++ b/runtime-recomp/src/game/netplay/direct_session.cpp @@ -4,6 +4,8 @@ #include "netplay/session_chat/settings.hpp" #include "netplay/peer_relay/owner_glue.hpp" #include "netplay/peer_relay/transport.hpp" +#include "netplay/session_links/registry.hpp" +#include "netplay/session_links/transport.hpp" #include "start_cancel_message.hpp" #include "online_stability/qualification_delivery.hpp" #include "../policy.hpp" @@ -301,6 +303,7 @@ void DirectSession::configure_session_save(std::vector canonical_s } void DirectSession::retire_transport_locked() { + links::forget(this); pending_invitation_.reset(); if (!transport_->quick_join()) { transport_->close(); @@ -5806,6 +5809,13 @@ void DirectSession::flush_outbound_locked() { } std::uint64_t& DirectSession::outbound_sequence(const PeerAddress& address, const secure::Key& key) { + // Pair-key counters survive a role change and optional direct-input routes. + { + auto party = dkr::runtime::spectators::party_link(this); + std::scoped_lock party_lock(party->mutex); + if (auto* p = party->peer(address); p && p->key == key) + return p->sequence; + } if (!is_host_) return next_sequence_; for (PeerRecord& peer : peers_) { @@ -5864,6 +5874,8 @@ void DirectSession::broadcast(protocol::MessageType type, std::spanaddress}); + } } proxy::configure(this, proxy::build_context(roster, now), std::move(addresses)); proxy::RouteTable table; @@ -5948,10 +5970,14 @@ void DirectSession::service_peer_relay_locked(dkr::runtime::spectators::PartyLin table.reachable.push_back(peer.sender_id); } } + if (!is_host_ && party.enabled && !party.local_watching()) + for (const auto& member : party.party.snapshot().members) + if (member.role == watch::Role::Racer && party.links.introduced.contains(member.id)) + table.introduced.push_back(member.id); for (auto& command : proxy::route(proxy::controls(this), table)) { auto payload = watch::link_encode(watch::LinkKind::Extension, command.bytes); const auto type = protocol::MessageType(watch::PartyMessageType); - if (!is_host_) { + if (!is_host_ && command.target == host_sender_id_) { send_with_key(host_address_, key_, type, payload); } else if (party.enabled) { if (const auto* peer = party.peer(command.target)) @@ -6095,6 +6121,8 @@ void DirectSession::pump_locked() { PeerAddress departed{}; while (transport_->take_peer_departure(departed)) { + if (!is_host_ && !(departed == host_address_) && links::retire_route(this, match_id_, departed)) + continue; { auto party = dkr::runtime::spectators::party_link(this); std::scoped_lock party_lock(party->mutex); @@ -6200,6 +6228,7 @@ void DirectSession::pump_locked() { if (!secure::inspect_packet(encrypted, packet_sender, packet_match) || packet_match != match_id_) continue; const secure::Key* receive_key = &key_; + std::optional introduced_key; bool provisional_mod_peer = false; if (is_host_) { PeerRecord* peer = peer_by_sender(packet_sender); @@ -6219,7 +6248,10 @@ void DirectSession::pump_locked() { } } } else if (packet_sender != host_sender_id_) { - continue; + introduced_key = links::receive_key(this, match_id_, packet_sender, source); + if (!introduced_key) + continue; + receive_key = &*introduced_key; } std::uint64_t opened_sender = 0U; std::uint64_t packet_sequence = 0U; @@ -6236,6 +6268,8 @@ void DirectSession::pump_locked() { if (provisional_mod_peer && packet.header.type != protocol::MessageType::ModControl && packet.header.type != protocol::MessageType::ModData) continue; + if (introduced_key && unsigned(packet.header.type) != dkr::runtime::spectators::PartyMessageType) + continue; // A fragmented authority snapshot must not age a delayed rollback // input out of the replay window. Keep authenticated sequence windows // per traffic lane while retaining one globally unique encryption @@ -6310,6 +6344,18 @@ void DirectSession::pump_locked() { if (!watch::link_decode(packet.payload, message)) continue; if (message.kind == watch::LinkKind::Extension) { + if (message.body.size() >= 6 && message.body[5] == 7) { + const bool admitted = party->enabled && party->party.find(packet_sender) && + (packet_sender == host_sender_id_ || party->peer(packet_sender)); + if (admitted) { + if (auto* peer = party->peer(packet_sender)) + peer->heard = std::chrono::steady_clock::now(); + if (packet_sender == host_sender_id_) + last_admission_response_ = std::chrono::steady_clock::now(); + party->links.receive(packet_sender, message.body); + } + continue; + } // Authentication/replay checks already ran. A provisional download // route is not an admitted lobby member and cannot publish metadata. const bool admitted = is_host_ ? (party->enabled ? party->peer(packet_sender) != nullptr @@ -6317,12 +6363,26 @@ void DirectSession::pump_locked() { : (packet_sender == host_sender_id_ && source == host_address_); if (admitted && message.body.size() >= 6 && message.body[5] == 4) dkr::chat::channel(this)->receive(packet_sender, message.body); - else if (admitted && message.body.size() >= 6 && (message.body[5] == 3 || message.body[5] == 6)) + else if ((admitted || (party->enabled && party->peer(packet_sender) && + party->links.introduced.contains(packet_sender))) && + message.body.size() >= 6 && message.body[5] == 6) + dkr::relay::control(this, packet_sender, message.body); + else if (admitted && message.body.size() >= 6 && message.body[5] == 3) dkr::relay::control(this, packet_sender, message.body); else dkr::online_stability::control(this)->receive(packet_sender, admitted, message.body); continue; } + if (!is_host_ && packet_sender != host_sender_id_) { + // Introductions authorize only immutable racer inputs. Room, + // stop, start and checkpoint authority remains with the host. + if (message.kind == watch::LinkKind::Runtime && party->links.introduced.contains(packet_sender)) { + if (auto* peer = party->peer(packet_sender); + peer && peer->address == source && party->admit_incoming(packet_sender, message.body)) + peer->heard = std::chrono::steady_clock::now(); + } + continue; + } if (is_host_) { auto* member = party->peer(packet_sender); if (!party->enabled || !member || member->address != source) @@ -6387,8 +6447,8 @@ void DirectSession::pump_locked() { break; } case watch::LinkKind::Ready: - if (!party->launch && !party->stopping && message.body.size() == 1 && message.body[0] <= 1 && - party->participant(packet_sender)) + if (!party->launch && !party->stopping && !links::busy(party->links) && message.body.size() == 1 && + message.body[0] <= 1 && party->participant(packet_sender)) party->ready[packet_sender] = message.body[0] != 0; break; case watch::LinkKind::Stop: @@ -6547,8 +6607,9 @@ void DirectSession::pump_locked() { if (!party->launch) { // The roster is part of the receipt. Re-arm when it moves on, or a // start validated against the previous roster is never acknowledged. - if (!gate->launch || gate->hash != start.descriptor_hash || - gate->roster != roster.generation) { + if (dkr::runtime::party_start::needs_prepare( + *gate, start.descriptor_hash, roster.generation, session_save_generation_, + manifest_.session_save_hash)) { gate->launch = launch; gate->hash = start.descriptor_hash; gate->roster = roster.generation; @@ -6681,6 +6742,7 @@ void DirectSession::pump_locked() { return; #include "../remove_member.inl" const auto now = std::chrono::steady_clock::now(); + service_session_links_locked(*party, now); auto queue = [&](watch::MemberId target, watch::LinkKind kind, std::vector body) { const auto traffic = kind == watch::LinkKind::Heartbeat ? TransportTrafficClass::Realtime : TransportTrafficClass::Control; @@ -6752,7 +6814,8 @@ void DirectSession::pump_locked() { party->ready.clear(); party->advertised = {}; } - if (party->ready_requested && !party->launch && party->participant(sender_id_)) + if (party->ready_requested && !party->launch && !links::busy(party->links) && + party->participant(sender_id_)) party->ready[sender_id_] = party->ready_value; party->ready_requested = false; // Within the DirectSession and PartyLink owner locks. @@ -6787,8 +6850,8 @@ void DirectSession::pump_locked() { }; if (party->start_requested) { party->start_requested = false; - if (!party->launch && !party->stopping && gate->phase != StartPhase::Countdown && - gate->phase != StartPhase::Committing) { + if (!party->launch && !party->stopping && !links::busy(party->links) && + gate->phase != StartPhase::Countdown && gate->phase != StartPhase::Committing) { std::string reason; bool all = true; for (const auto& m : party->party.snapshot().members) @@ -7065,6 +7128,10 @@ void DirectSession::pump_locked() { auto item = std::move(pending.front()); pending.pop_front(); party->outgoing_bytes -= item.bytes.size(); + if (!is_host_ && item.target && item.target != host_sender_id_ && + item.kind == watch::LinkKind::Runtime && item.traffic == TransportTrafficClass::Realtime && + item.bytes.size() > 4 && item.bytes[4] == 19 && !party->links.live_routes.contains(item.target)) + continue; auto payload = watch::link_encode(item.kind, item.bytes); bool blocked = false; auto send = [&](const PeerAddress& destination, const secure::Key& key) { @@ -7113,6 +7180,9 @@ void DirectSession::pump_locked() { send(peer->address, peer->key); } else if (!item.target || item.target == host_sender_id_) send(host_address_, key_); + else if (auto* peer = party->peer(item.target); + peer && party->links.introduced.contains(item.target)) + send(peer->address, peer->key); if (blocked) party->enqueue(std::move(item)); } @@ -7501,6 +7571,8 @@ void DirectSession::handle_join_request(const PeerAddress& source, std::spanenabled && links::busy(party->links)) + return; if (party_join && !party->enabled && !watch_join) party_join = false; if (party_join && watch_join && !party->allow_spectators && !party->peer(packet_sender)) { @@ -7619,11 +7691,14 @@ void DirectSession::handle_join_request(const PeerAddress& source, std::spanlinks.architectures, + [&](const auto& item) { return item.first != sender_id_ && !present.contains(item.first); }); } if (hello.manifest.architecture == manifest_.architecture) other_architecture_senders_.erase(packet_sender); else other_architecture_senders_.insert(packet_sender); + party->links.architectures.insert_or_assign(packet_sender, hello.manifest.architecture); PendingRecord* pending = pending_by_sender(packet_sender); if (pending && pending->mods_approved && (!(pending->address == source) || pending->key != peer_key || pending->client_public != client_public)) diff --git a/runtime-recomp/src/game/netplay/direct_session.hpp b/runtime-recomp/src/game/netplay/direct_session.hpp index 73e66e4d..9318c7fc 100644 --- a/runtime-recomp/src/game/netplay/direct_session.hpp +++ b/runtime-recomp/src/game/netplay/direct_session.hpp @@ -639,6 +639,8 @@ class DirectSession final { void pump_locked(); // Session chat's share of the pump. Requires mutex_ and party.mutex. void service_chat_locked(dkr::runtime::spectators::PartyLink& party); + void service_session_links_locked(dkr::runtime::spectators::PartyLink& party, + std::chrono::steady_clock::time_point now); // The peer relay's share of the pump (lobby roster for the relay, its control packets). // Requires mutex_ and party.mutex; `now` is the pump's clock reading. void service_peer_relay_locked(dkr::runtime::spectators::PartyLink& party, diff --git a/runtime-recomp/src/game/netplay/experimental_presentation.cpp b/runtime-recomp/src/game/netplay/experimental_presentation.cpp index 35488861..389f5fbb 100644 --- a/runtime-recomp/src/game/netplay/experimental_presentation.cpp +++ b/runtime-recomp/src/game/netplay/experimental_presentation.cpp @@ -1,6 +1,7 @@ #include "experimental_presentation.hpp" #include "experimental_checkpoint_hash.hpp" #include "experimental_performance.hpp" +#include "online_presentation/correction_lifetime.hpp" #include #include #include @@ -11,6 +12,7 @@ struct SubmissionDomain { std::uint64_t epoch = 0, generation = 0; std::size_t in_flight = 0, consumers = 0; bool alive = true; + CorrectionLifetime corrections; // Two queued immutable images + latest pending + publication candidate, // one decoder, INCLUDING cached capacity: 80 MiB vanilla / 120 MiB // with portable code storage. Slot count never grows into a FIFO. @@ -125,7 +127,7 @@ std::unique_ptr SubmissionPermit::acquire(std::shared_ptrdomain_; std::scoped_lock lock(domain.mutex); - if (!domain.alive || domain.epoch != snapshot->epoch() || domain.generation != snapshot->generation()) { + if (!domain.alive || domain.epoch != snapshot->epoch() || !domain.corrections.eligible(snapshot.get())) { // An unclaimed candidate must not run the counted-release destructor. permit->snapshot_.reset(); return {}; @@ -183,6 +185,7 @@ bool PresentationMailbox::begin_epoch(std::uint64_t epoch) { std::scoped_lock domain_lock(domain_->mutex); domain_->epoch = epoch_; domain_->generation = generation_; + domain_->corrections.reset(); } return true; } @@ -213,6 +216,11 @@ bool PresentationMailbox::publish(std::uint64_t epoch, RenderDescriptor descript // the race while its immutable image was being copied. if (epoch != epoch_ || generation != generation_ || (last_frame_ && descriptor.frame <= *last_frame_)) return false; + { + std::scoped_lock domain_lock(domain_->mutex); + if (!domain_->corrections.publish(candidate)) + return false; + } pending_ = std::move(candidate); last_frame_ = descriptor.frame; return true; @@ -259,15 +267,23 @@ bool PresentationMailbox::retire_for_restore(std::uint64_t epoch, std::uint32_t retire_locked(first); return true; } -void PresentationMailbox::retire_locked(std::uint32_t first) { - // Even a previously valid older lease is conservatively retired. A real - // renderer must recheck this generation before presentation and retain - // its last completed image while a replacement is being produced. +bool PresentationMailbox::retire_for_correction(std::uint64_t epoch, std::uint32_t first) { + std::scoped_lock lock(mutex_); + if (!epoch_ || epoch != epoch_ || generation_ == UINT64_MAX || first == UINT32_MAX) + return false; + retire_locked(first, true); + return true; +} +void PresentationMailbox::retire_locked(std::uint32_t first, bool correction) { + // An immutable picture survives only when it precedes every correction + // affecting its lease. Scene/resource retirement remains unconditional. ++generation_; - pending_.reset(); + if (!correction || (pending_ && pending_->descriptor().frame >= first)) + pending_.reset(); { std::scoped_lock domain_lock(domain_->mutex); domain_->generation = generation_; + domain_->corrections.retire(first, correction); } if (last_frame_ && first <= *last_frame_) last_frame_ = first ? std::optional(first - 1) : std::nullopt; @@ -275,7 +291,9 @@ void PresentationMailbox::retire_locked(std::uint32_t first) { bool PresentationMailbox::is_current(const std::shared_ptr& snapshot) const { std::scoped_lock lock(mutex_); const auto active = active_.lock(); - return snapshot && active == snapshot && snapshot->epoch() == epoch_ && snapshot->generation() == generation_; + std::scoped_lock domain_lock(domain_->mutex); + return snapshot && active == snapshot && snapshot->epoch() == epoch_ && + domain_->corrections.eligible(snapshot.get()); } bool PresentationMailbox::quiescent() const { std::scoped_lock lock(mutex_); diff --git a/runtime-recomp/src/game/netplay/experimental_presentation.hpp b/runtime-recomp/src/game/netplay/experimental_presentation.hpp index c1bf5c88..33dc694a 100644 --- a/runtime-recomp/src/game/netplay/experimental_presentation.hpp +++ b/runtime-recomp/src/game/netplay/experimental_presentation.hpp @@ -147,6 +147,7 @@ class PresentationMailbox final { // image or after a slow renderer's last publication. Retires any in-flight // candidate/lease without claiming that the GPU has finished consuming it. bool retire_for_restore(std::uint64_t epoch, std::uint32_t first_changed_frame); + bool retire_for_correction(std::uint64_t epoch, std::uint32_t first_changed_frame); bool is_current(const std::shared_ptr& snapshot) const; // Nonblocking status for an asynchronous restore/preparation owner. An // adapter requiring fully retired presentation MUST await this, keeping @@ -156,7 +157,7 @@ class PresentationMailbox final { BufferStatistics buffer_statistics() const; private: - void retire_locked(std::uint32_t first_changed_frame); + void retire_locked(std::uint32_t first_changed_frame, bool correction = false); // Serialize producers without holding the small consumer-state lock while // copying/hashing RAM. A correction may retire a candidate during that work. std::mutex producer_mutex_; diff --git a/runtime-recomp/src/game/netplay/experimental_runtime.cpp b/runtime-recomp/src/game/netplay/experimental_runtime.cpp index cd2719fb..c06e8e23 100644 --- a/runtime-recomp/src/game/netplay/experimental_runtime.cpp +++ b/runtime-recomp/src/game/netplay/experimental_runtime.cpp @@ -1,3 +1,4 @@ +#include "netplay/session_links/menu_control.hpp" #include "online_input_broker.hpp" #include "online_stability/startup_transport.hpp" #include "online_stability/flow_trace.hpp" @@ -427,10 +428,23 @@ bool run_party_runtime(ultramodern::renderer::WindowHandle window, const std::fi namespace party = dkr::runtime::spectators; auto hub = party::party_link(&lobby); const auto initial = party::party_link_view(&lobby); - std::vector seed; + std::vector seed, transferred_paks; + bool save_owner = false; + unsigned menu_owner_port = 0; { std::scoped_lock lock(hub->mutex); seed = hub->seed; + save_owner = hub->links.save_owner == initial.local; + if (initial.host) + transferred_paks = hub->links.save_paks; + if (const auto* owner = hub->party.find(hub->party.snapshot().host); owner && owner->port) + menu_owner_port = *owner->port; + else + for (const auto& member : hub->party.snapshot().members) + if (member.port) { + menu_owner_port = *member.port; + break; + } } if (!initial.enabled || !initial.admitted || seed.size() != 512 || bootstrap.empty()) { error = "The party launch is missing its verified local bootstrap/save."; @@ -452,10 +466,10 @@ bool run_party_runtime(ultramodern::renderer::WindowHandle window, const std::fi shared.confirmed_save = seed; std::atomic local_port{4}; std::atomic watching{true}; - ConfirmedSaveWriter save_writer([&, host = initial.host](const ConfirmedSaveSnapshot& s, std::string& e) { - // Only the authority stores the communal online bank. Observers never - // install host state into a personal save, records bank or controller Pak. - if (host && !launch.development) { + ConfirmedSaveWriter save_writer([&, owner = save_owner](const ConfirmedSaveSnapshot& s, std::string& e) { + // The original save owner retains the durable bank after host handover. + // The current host retains only the verified in-memory transfer state. + if (owner && !launch.development) { if (!saves::commit_online_adventure(true, launch.match_id, s.eeprom, e) || !saves::commit_experimental_online_paks(true, launch.match_id, s.paks, e)) return false; @@ -467,6 +481,11 @@ bool run_party_runtime(ultramodern::renderer::WindowHandle window, const std::fi return false; } } + if (initial.host) { + std::scoped_lock lock(hub->mutex); + hub->links.save_paks = s.paks; + hub->links.save_records = s.records; + } std::scoped_lock lock(shared.mutex); shared.confirmed_save = s.eeprom; e.clear(); @@ -557,6 +576,7 @@ bool run_party_runtime(ultramodern::renderer::WindowHandle window, const std::fi throw std::runtime_error("Party presentation epoch refused."); const auto revision = lobby.view().room.manifest.revision == Revision::UsV80 ? rom::Revision::UsV80 : rom::Revision::UsV77; + dkr::runtime::netplay::links::menu_control::CreationPort menu_controls(menu_owner_port); world = make_owned_game_for_revision( revision, bootstrap, bytes, epoch, shared.mailbox, [&](ConfirmedAudio a, std::string& e) { return shared.audio.push(a.rate, a.pcm, e); }, message, false, @@ -569,8 +589,9 @@ bool run_party_runtime(ultramodern::renderer::WindowHandle window, const std::fi throw std::runtime_error(message); std::fprintf(stderr, "[party][boot] owned world ready; bytes=%zu\n", world->contract().state_bytes); if (initial.host) { - std::vector paks; - if (!saves::read_experimental_online_paks(true, launch.match_id, paks, message) || + auto paks = transferred_paks; + if ((paks.empty() && + !saves::read_experimental_online_paks(save_owner, launch.match_id, paks, message)) || !world->install_initial_paks(epoch, paks, message)) throw std::runtime_error(message); } @@ -710,8 +731,9 @@ bool run_party_runtime(ultramodern::renderer::WindowHandle window, const std::fi report({true, wait, cursor.epoch, cursor.frame, runtime.confirmed(), stats.rollbacks, stats.replayed_frames, runtime.status(), cursor.epoch == 0}); if (now >= next_save) { - if (initial.host && !save_writer.submit(world->confirmed_save(), world->confirmed_paks(), message, - world->confirmed_records())) + if ((initial.host || save_owner) && + !save_writer.submit(world->confirmed_save(), world->confirmed_paks(), message, + world->confirmed_records())) throw std::runtime_error(message); next_save = now + std::chrono::seconds(5); } @@ -737,7 +759,7 @@ bool run_party_runtime(ultramodern::renderer::WindowHandle window, const std::fi else party::party_stop(&lobby, "Party simulation stopped."); } - if (world && initial.host) { + if (world && (initial.host || save_owner)) { std::string message; if (!save_writer.submit(world->confirmed_save(), world->confirmed_paks(), message, world->confirmed_records())) diff --git a/runtime-recomp/src/game/netplay/peer_relay/live_datagram.cpp b/runtime-recomp/src/game/netplay/peer_relay/live_datagram.cpp index 8c73664f..016addfd 100644 --- a/runtime-recomp/src/game/netplay/peer_relay/live_datagram.cpp +++ b/runtime-recomp/src/game/netplay/peer_relay/live_datagram.cpp @@ -196,8 +196,12 @@ void LiveDatagram::configure(const Context& context, const std::vector wanted; + const auto local = std::find_if(context.members.begin(), context.members.end(), + [&](const auto& member) { return member.id == context.local; }); for (const auto& member : context.members) - if (member.id && member.id != context.local && (context.local == context.host || member.id == context.host)) + if (member.id && member.id != context.local && + (context.local == context.host || member.id == context.host || + (local != context.members.end() && local->racer && member.racer))) wanted.insert(member.id); std::erase_if(s.peers, [&](const auto& p) { return !wanted.contains(p.first); }); for (const auto id : wanted) diff --git a/runtime-recomp/src/game/netplay/peer_relay/owner_glue.cpp b/runtime-recomp/src/game/netplay/peer_relay/owner_glue.cpp index 607ec8c2..992f670d 100644 --- a/runtime-recomp/src/game/netplay/peer_relay/owner_glue.cpp +++ b/runtime-recomp/src/game/netplay/peer_relay/owner_glue.cpp @@ -53,9 +53,14 @@ Context build_context(const RelayRoster& roster, Clock::time_point now) { std::vector route(std::vector controls, const RouteTable& table) { std::vector sends; for (auto& control : controls) { + const bool ice = + control.bytes.size() >= 6 && std::equal(control.bytes.begin(), control.bytes.begin() + 6, + std::array{'D', 'K', 'R', 'X', 1, 6}.begin()); + const bool introduced = ice && std::find(table.introduced.begin(), table.introduced.end(), control.target) != + table.introduced.end(); const bool deliverable = table.is_host ? std::find(table.reachable.begin(), table.reachable.end(), control.target) != table.reachable.end() - : control.target == table.host; + : control.target == table.host || introduced; if (deliverable) sends.push_back(std::move(control)); } diff --git a/runtime-recomp/src/game/netplay/peer_relay/owner_glue.hpp b/runtime-recomp/src/game/netplay/peer_relay/owner_glue.hpp index 3d280061..89356f00 100644 --- a/runtime-recomp/src/game/netplay/peer_relay/owner_glue.hpp +++ b/runtime-recomp/src/game/netplay/peer_relay/owner_glue.hpp @@ -69,7 +69,8 @@ Context build_context(const RelayRoster&, Clock::time_point now); struct RouteTable { bool is_host = false; Id host = 0; - std::vector reachable; // a host's reachable member ids + std::vector reachable; // a host's reachable member ids + std::vector introduced; // authenticated racer ICE peers, not additional relay authorities }; // The control packets that will be sent, in order: a host's to reachable members, // a client's to the host, nothing else. diff --git a/runtime-recomp/src/game/netplay/peer_relay/transport.cpp b/runtime-recomp/src/game/netplay/peer_relay/transport.cpp index 353e9808..3ab1d052 100644 --- a/runtime-recomp/src/game/netplay/peer_relay/transport.cpp +++ b/runtime-recomp/src/game/netplay/peer_relay/transport.cpp @@ -1,5 +1,6 @@ #include "../../session_log.hpp" #include "transport.hpp" +#include "netplay/session_links/transport.hpp" #include "live_datagram.hpp" #include "online_stability/traffic_meter.hpp" #include "online_stability/live_send_capacity.hpp" @@ -77,7 +78,7 @@ bool endpoint(std::string value, net::PeerAddress& address) { return false; } } -class Transport final : public net::SessionTransport { +class Transport final : public net::SessionTransport, public net::links::IntroducedTransport { public: Transport(const void* key, std::unique_ptr base, NetworkOptions options) : key_(key), base_(std::move(base)), options_(std::move(options)), events_(std::make_shared()), @@ -190,6 +191,25 @@ class Transport final : public net::SessionTransport { std::uint16_t local_port() const override { return base_->local_port(); } + std::string local_peer_name() const override { + return net::links::local_peer_name(*base_); + } + std::string peer_name(const net::PeerAddress& address) const override { + return net::links::peer_name(*base_, address); + } + bool introduce_peer(std::string_view endpoint, bool initiate, net::PeerAddress& address, + std::string& error) override { + return net::links::introduce_peer(*base_, endpoint, initiate, address, error); + } + bool prepare_host(std::string bootstrap, std::string& error) override { + return net::links::prepare_host(*base_, std::move(bootstrap), error); + } + bool alias_peer(const net::PeerAddress& address, std::string_view name, std::string& error) override { + return net::links::alias_peer(*base_, address, name, error); + } + bool apply_host_role(bool host, std::string_view remote, std::string& error) override { + return net::links::apply_host_role(*base_, host, remote, error); + } net::DatagramSendStatus send_status(const net::PeerAddress& to, std::span bytes, net::TransportTrafficClass traffic, std::string& error) override { // Checkpoint chunks have no repair: the sender advances after each accepted diff --git a/runtime-recomp/src/game/netplay/quick_join_transport.cpp b/runtime-recomp/src/game/netplay/quick_join_transport.cpp index c6d616d2..6678a1e7 100644 --- a/runtime-recomp/src/game/netplay/quick_join_transport.cpp +++ b/runtime-recomp/src/game/netplay/quick_join_transport.cpp @@ -4,6 +4,8 @@ #include "online_presentation/test_receive_delay.hpp" #include "online_stability/live_send_capacity.hpp" #include "session_transport.hpp" +#include "netplay/session_links/transport.hpp" +#include #include "callback_lifetime.hpp" #include "transport_send_policy.hpp" #include "social_executor.hpp" @@ -127,7 +129,7 @@ std::string signaling_ca_bundle() { return std::string(kPeerJsFallbackRoot); } -class QuickJoinTransport final : public SessionTransport { +class QuickJoinTransport final : public SessionTransport, public links::IntroducedTransport { public: QuickJoinTransport(bool host, std::string code) : host_(host), code_(std::move(code)) {} ~QuickJoinTransport() override { @@ -187,6 +189,9 @@ class QuickJoinTransport final : public SessionTransport { peers.swap(peers_); remote_to_identifier_.clear(); pinned_routes_.clear(); + authorized_remote_.clear(); + peer_aliases_.clear(); + preparing_host_.store(false); departed_peers_.clear(); retired.swap(retired_peers_); control_inbound_.clear(); @@ -236,7 +241,8 @@ class QuickJoinTransport final : public SessionTransport { void retain_peer_route(const PeerAddress& address) override { std::scoped_lock lock(mutex_); for (const auto& [id, peer] : peers_) { - if (peer->address == address && (pinned_routes_.contains(peer->remote_id) || pinned_routes_.size() < 16U)) { + if (peer->address == address && + (pinned_routes_.contains(peer->remote_id) || pinned_route_count_locked() < 16U)) { pinned_routes_[peer->remote_id] = {id, address}; return; } @@ -244,6 +250,19 @@ class QuickJoinTransport final : public SessionTransport { } void release_peer_route(const PeerAddress& address) override { std::scoped_lock lock(mutex_); + for (const auto& [id, peer] : peers_) + if (peer->address == address) { + authorized_remote_.erase(peer->remote_id); + if (const auto alias = peer_aliases_.find(id); alias != peer_aliases_.end()) { + authorized_remote_.erase(alias->second); + peer_aliases_.erase(alias); + } + } + for (const auto& [name, route] : pinned_routes_) + if (route.second == address) { + authorized_remote_.erase(name); + peer_aliases_.erase(route.first); + } std::erase_if(pinned_routes_, [&](const auto& entry) { return entry.second.second == address; }); } bool take_peer_departure(PeerAddress& address) override { @@ -302,8 +321,10 @@ class QuickJoinTransport final : public SessionTransport { return code_; } +#include "netplay/session_links/quick_join_api.inl" + bool rekey_quick_join(std::string bootstrap, std::string& error) override { - if (!host_ || !is_open() || rekey_status() == QuickJoinRekeyStatus::Pending) { + if ((!host_ && !preparing_host_.load()) || !is_open() || rekey_status() == QuickJoinRekeyStatus::Pending) { error = "Only an active host without a pending code replacement can rekey."; return false; } @@ -316,6 +337,7 @@ class QuickJoinTransport final : public SessionTransport { pending->bootstrap = std::move(bootstrap); pending->generation = next_signaling_generation_.fetch_add(1U) + 1U; pending_rekey_ = pending; + pending->quiet = preparing_host_.load(); } rekey_state_.store(QuickJoinRekeyStatus::Pending); pending->socket = make_signaling_socket(pending->generation, pending); @@ -644,6 +666,7 @@ class QuickJoinTransport final : public SessionTransport { friend struct QuickJoinTestAccess; CallbackLifetime callbacks_; struct PendingRekey { + bool quiet = false; std::string code; std::string bootstrap; std::uint64_t generation = 0U; @@ -690,16 +713,17 @@ class QuickJoinTransport final : public SessionTransport { pending->socket->close(); return; } - for (const auto& channel : channels) { - rtc::binary framed{static_cast(3U)}; - for (unsigned char c : pending->code) - framed.push_back(static_cast(c)); - try { - if (channel->isOpen()) - channel->send(std::move(framed)); - } catch (...) { + if (!pending->quiet) + for (const auto& channel : channels) { + rtc::binary framed{static_cast(3U)}; + for (unsigned char c : pending->code) + framed.push_back(static_cast(c)); + try { + if (channel->isOpen()) + channel->send(std::move(framed)); + } catch (...) { + } } - } if (previous) previous->close(); } @@ -710,6 +734,7 @@ class QuickJoinTransport final : public SessionTransport { PeerAddress address{}; std::atomic current{true}; std::atomic route_ready{false}; + std::atomic authority_route{false}; bool departure_reported = false; // mutex_ protected bool signals_released = false; // mutex_ protected std::vector held_signals; // mutex_ protected @@ -806,9 +831,10 @@ class QuickJoinTransport final : public SessionTransport { bool has_established_route() const { std::scoped_lock lock(mutex_); - return std::any_of(peers_.begin(), peers_.end(), [](const auto& entry) { + return std::any_of(peers_.begin(), peers_.end(), [this](const auto& entry) { const auto& peer = entry.second; return peer && peer->current.load(std::memory_order_acquire) && + (host_ || peer->authority_route.load(std::memory_order_acquire)) && peer->route_ready.load(std::memory_order_acquire) && peer->control_channel && peer->control_channel->isOpen(); }); @@ -879,7 +905,7 @@ class QuickJoinTransport final : public SessionTransport { failed_.load(std::memory_order_acquire)) return; peer->route_ready.store(false, std::memory_order_release); - if (!host_) { + if (!host_ && peer->authority_route.load(std::memory_order_acquire)) { std::uint64_t unscheduled = 0U; next_route_retry_ms_.compare_exchange_strong(unscheduled, steady_milliseconds() + 750U, std::memory_order_acq_rel); @@ -918,6 +944,7 @@ class QuickJoinTransport final : public SessionTransport { std::shared_ptr replaced; { std::scoped_lock lock(mutex_); + peer->authority_route.store(!host_ && peer->remote_id == remote_host_id_); if (peer->remote_id.size() > 128U || peer->connection_id.size() > 128U || retired_peers_.size() + pending_retirements_.load() >= 16U || (peers_.size() >= 16U && std::none_of(peers_.begin(), peers_.end(), [&](const auto& entry) { @@ -965,7 +992,7 @@ class QuickJoinTransport final : public SessionTransport { payload["serialization"] = "none"; } send_peer_signal(locked, Json{{"type", type == "offer" ? "OFFER" : "ANSWER"}, - {"dst", locked->remote_id}, + {"dst", signal_name(locked->identifier, locked->remote_id)}, {"payload", std::move(payload)}}); })); peer->connection->onLocalCandidate(callbacks_.wrap([this, weak_peer](rtc::Candidate candidate) { @@ -975,7 +1002,7 @@ class QuickJoinTransport final : public SessionTransport { send_peer_signal( locked, Json{{"type", "CANDIDATE"}, - {"dst", locked->remote_id}, + {"dst", signal_name(locked->identifier, locked->remote_id)}, {"payload", {{"connectionId", locked->connection_id}, {"type", "data"}, @@ -993,7 +1020,7 @@ class QuickJoinTransport final : public SessionTransport { return; if (state == rtc::PeerConnection::State::Connected) { locked->route_ready.store(true, std::memory_order_release); - if (!host_) { + if (!host_ && locked->authority_route.load(std::memory_order_acquire)) { next_route_retry_ms_.store(0U, std::memory_order_release); route_retry_requested_.store(false, std::memory_order_release); } @@ -1214,10 +1241,10 @@ class QuickJoinTransport final : public SessionTransport { std::scoped_lock lock(mutex_); if (!locked->current.load(std::memory_order_acquire) || closing_.load()) return; - if (kind == 2U && !host_) { + if (kind == 2U && !host_ && locked->authority_route.load(std::memory_order_acquire)) { bootstrap_.assign(bytes.begin(), bytes.end()); bootstrap_peer_ = locked->address; - } else if (kind == 3U && !host_) { + } else if (kind == 3U && !host_ && locked->authority_route.load(std::memory_order_acquire)) { const std::string replacement(bytes.begin(), bytes.end()); if (valid_quick_join_code(replacement)) { const std::string new_remote = "dkrr-31-" + normalize_code(replacement); @@ -1352,7 +1379,12 @@ class QuickJoinTransport final : public SessionTransport { if (connection_id.empty()) return; std::shared_ptr peer = find_peer(remote, connection_id); - if (!peer && type == "OFFER" && host_) { + bool introduced = false; + { + std::scoped_lock lock(mutex_); + introduced = authorized_remote_.contains(remote); + } + if (!peer && type == "OFFER" && (host_ || introduced)) { if (!payload.contains("sdp") || !payload["sdp"].is_object()) return; (void)create_peer(remote, connection_id, false, &payload["sdp"]); @@ -1379,7 +1411,7 @@ class QuickJoinTransport final : public SessionTransport { } } - bool host_ = false; +#include "netplay/session_links/quick_join_state.inl" #ifdef DKR_QUICK_JOIN_TESTING int construction_failure_stage_ = -1; std::function construction_hook_; diff --git a/runtime-recomp/src/game/netplay/session_chat/ui.inl b/runtime-recomp/src/game/netplay/session_chat/ui.inl index 57fcfdd3..8aea6d8c 100644 --- a/runtime-recomp/src/game/netplay/session_chat/ui.inl +++ b/runtime-recomp/src/game/netplay/session_chat/ui.inl @@ -59,7 +59,7 @@ void SessionChatKeyboard() { void SessionChatOptions(const dkr::chat::View& view) { if (OlButton("...##chat-options", OlTone::Plain, 38.F, "Chat options")) ImGui::OpenPopup("session-chat-options"); - if (ImGui::BeginPopup("session-chat-options")) { + if (dkr::runtime::ui::begin_dialog_popup("session-chat-options")) { if (view.host) { bool allow = dkr::chat::host_enabled.load(); if (ImGui::Checkbox("Allow lobby chat", &allow)) { diff --git a/runtime-recomp/src/game/netplay/session_links/handover_pump.inl b/runtime-recomp/src/game/netplay/session_links/handover_pump.inl new file mode 100644 index 00000000..8635d50f --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/handover_pump.inl @@ -0,0 +1,298 @@ +{ + std::string transfer_error; + // Capability flags are membership scoped. A stale UI request cannot move + // a member who left, nor overlap a race, seat swap, invitation or download. + if (links.request) { + const auto target = std::exchange(links.request, 0); + if (is_host_ && waiting && !roster.handover && !direct::busy(links)) { + const bool directory = method_ == ConnectionMethod::QuickJoin && dkr::online::hosting_mode(this) == 2; + if (directory && !dkr::online::view()->host_handover) { + links.status = "This directory has not enabled host handover yet."; + } else { + direct::Proposal p{links.scope, ++links.serial, target, links.save_owner, {}}; + p.state = digest_transfer(watch::wire::roster(roster)); + if (links.handover.offer(sender_id_, p, true, now, transfer_error)) { + reset_transfer(); + links.directory_required = directory; + links.directory_code = directory ? invite_ : std::string{}; + if (directory) { + const auto online = dkr::online::view(); + links.directory_public = online->public_desired && !online->hidden; + } + } else + links.status = transfer_error; + } + } + } + if (links.consent) { + const bool accept = *links.consent; + links.consent.reset(); + links.local_consent = accept; + if (const auto& p = links.handover.proposal(); p && p->successor == sender_id_) { + direct::Write value; + value.number(p->serial).number(accept, 1); + transfer_send(p->before.host, direct::Kind::Accept, std::move(value.bytes)); + } + } + if (links.cancel) { + links.cancel = false; + if (const auto& p = links.handover.proposal(); + p && links.handover.cancel(sender_id_, p->serial, "Host transfer cancelled.", transfer_error)) { + direct::Write value; + value.number(p->serial); + if (sender_id_ == p->before.host) + transfer_all(direct::Kind::Cancel, value.bytes); + else + transfer_send(p->before.host, direct::Kind::Cancel, std::move(value.bytes)); + } + } + const auto prior = links.handover.phase(); + links.handover.service(links.scope, waiting && !roster.handover, now); + if (links.handover.phase() == direct::Phase::Cancelled && prior != direct::Phase::Cancelled) { + if (const auto& p = links.handover.proposal(); p && sender_id_ == p->before.host) { + direct::Write v; + v.number(p->serial); + transfer_all(direct::Kind::Cancel, v.bytes); + } + links.status = links.handover.status(); + } + const auto proposal = links.handover.proposal(); + if (proposal && links.handover.phase() == direct::Phase::Preparing && sender_id_ == proposal->successor && + links.local_consent.value_or(false) && !links.registration_started) { + links.successor_keys = secure::generate_key_pair(); + links.successor_capability = secure::generate_key(); + const auto bootstrap = "dkr-r-quick-v1\n" + hex64(match_id_) + "\n" + hex64(sender_id_) + "\n" + + secure::encode_key(links.successor_keys.public_key) + "\n" + + secure::encode_key(links.successor_capability) + "\n" + + std::to_string(unix_seconds() + 21600U); + links.registration_started = direct::prepare_host(*transport_, bootstrap, transfer_error); + if (!links.registration_started) + links.status = transfer_error; + } + if (proposal && links.handover.phase() == direct::Phase::Preparing && sender_id_ == proposal->successor && + links.registration_started && + (!transport_->quick_join() || transport_->rekey_status() == QuickJoinRekeyStatus::Committed)) { + links.registration_ready = true; + links.successor_public = links.successor_keys.public_key; + links.successor_endpoint = transport_->quick_join() + ? direct::local_peer_name(*transport_) + : std::string("127.0.0.1:") + std::to_string(transport_->local_port()); + links.successor_invite = transport_->quick_join() ? transport_->quick_join_code() : links.successor_endpoint; + } + if (proposal && sender_id_ == proposal->before.host && links.registration_ready && links.prepared_bytes.empty() && + links.handover.phase() == direct::Phase::Preparing) { + auto room = lobby_payload(); + room.generation = roster.generation; + room.phase = RoomPhase::Waiting; + const auto snapshot = watch::wire::roster(roster), room_bytes = protocol::encode_lobby_state(room); + auto keys = links.keys; + for (const auto& peer : party->peers) + keys[{std::min(sender_id_, peer.id), std::max(sender_id_, peer.id)}] = peer.key; + direct::Write inventory; + inventory.number(keys.size(), 1); + for (const auto& [pair, key] : keys) + inventory.number(pair.first).number(pair.second).data(key); + links.inventory_bytes = std::move(inventory.bytes); + links.inventory_hash = digest_transfer(links.inventory_bytes); + direct::Write bundle; + bundle.number(proposal->serial) + .number(proposal->successor) + .number(proposal->save_owner) + .data(links.successor_public) + .data(links.successor_capability) + .text(links.successor_endpoint) + .text(links.successor_invite) + .number(manifest_class_hash(room_view_.manifest)) + .number(party->save_hash) + .number(party->save_generation, 4) + .data(links.inventory_hash) + .number(mod_manifest_bytes_, 4) + .number(snapshot.size(), 4) + .data(snapshot) + .number(room_bytes.size(), 4) + .data(room_bytes) + .data(party->seed) + .number(links.save_paks.size(), 4) + .data(links.save_paks) + .number(links.save_records.size(), 4) + .data(links.save_records) + .number(party->maximum_racers, 1) + .number(party->allow_spectators, 1) + .number(party->launch_serial); + bundle.number(roster.members.size(), 1); + for (const auto& member : roster.members) { + const auto architecture = links.architectures.find(member.id); + if (architecture == links.architectures.end() || architecture->second.empty() || + architecture->second.size() > 128) { + links.status = + "A member's platform identity is not available. Please rejoin before transferring the host."; + bundle.bytes.clear(); + break; + } + bundle.number(member.id).text(architecture->second); + } + if (!bundle.bytes.empty() && bundle.bytes.size() <= direct::MaximumTransferBytes && + links.handover.bind(sender_id_, proposal->serial, digest_transfer(bundle.bytes), transfer_error)) { + links.prepared_bytes = std::move(bundle.bytes); + links.expected_transfer = links.prepared_bytes.size(); + links.prepared_state = parse_transfer(true); + } else + links.status = + transfer_error.empty() ? "The transfer exceeds the bounded session save size." : transfer_error; + } + if (proposal && links.prepared_state && links.handover.phase() == direct::Phase::Preparing) { + bool routes = true; + for (const auto& member : proposal->before.members) { + if (member.id == sender_id_) + continue; + if (sender_id_ != proposal->successor && member.id != proposal->successor) + continue; + const auto* peer = party->peer(member.id); + const auto address = member.id == host_sender_id_ ? host_address_ : peer ? peer->address : PeerAddress{}; + if (!address) { + routes = false; + break; + } + for (const auto lane : + {TransportTrafficClass::Control, TransportTrafficClass::Authoritative, TransportTrafficClass::Realtime, + TransportTrafficClass::Replica, TransportTrafficClass::Checkpoint}) + routes = routes && transport_->traffic_ready(address, lane); + const auto sample = links.samples.find({sender_id_, member.id}); + routes = routes && sample != links.samples.end() && sample->second.observations && + now - sample->second.measured < std::chrono::seconds(5); + } + if (routes && + (sender_id_ != proposal->successor || + (links.inventory_ready && (manifest_.mod_manifest_hash.empty() || links.mod_ready))) && + (!links.directory_required || sender_id_ != proposal->successor || links.directory_accepted)) + links.handover.prepared(sender_id_, proposal->serial, links.handover.proposal()->state, true, now, + transfer_error); + } + if (proposal && links.directory_required && now >= links.directory_send && links.prepared_state && + !links.released) { + links.directory_send = now + std::chrono::seconds(2); + const auto current = links.handover.proposal(); + const auto online = dkr::online::view(); + if (online->connected && online->signed_in && online->host_handover && + (sender_id_ != current->successor || !links.directory_public || !online->hidden) && + ((sender_id_ == current->successor && links.handover.phase() == direct::Phase::Preparing) || + (sender_id_ == current->before.host && ((links.handover.complete() && !links.directory_committed) || + links.handover.phase() == direct::Phase::Preparing)))) { + dkr::online::respond(this, {{"type", sender_id_ == current->successor ? "transfer_accept" + : links.handover.complete() ? "transfer_commit" + : "transfer_prepare"}, + {"serial", std::to_string(current->serial)}, + {"epoch", hex64(match_id_)}, + {"digest", secure::encode_key(current->state)}, + {"code", links.directory_code}, + {"nextCode", links.successor_invite}, + {"sender", std::to_string(current->successor)}}); + } + } + if (now >= links.transfer_send && proposal) { + links.transfer_send = now + std::chrono::milliseconds(200); + const auto phase = links.handover.phase(); + const auto current = links.handover.proposal(); + if (sender_id_ == current->successor && links.released && !links.finished) { + bool realtime_ready = true; + for (const auto& member : party->party.snapshot().members) + if (member.port && member.id != sender_id_) { + const auto* peer = party->peer(member.id); + realtime_ready = realtime_ready && peer && peer->rtt_count && + now - peer->rtt_at < std::chrono::seconds(5) && + now - peer->heard < std::chrono::seconds(5); + } + if (realtime_ready) + transfer_send(current->before.host, direct::Kind::Activated, transfer_identity()); + } + if (sender_id_ == current->successor && phase == direct::Phase::Offered && links.local_consent) { + direct::Write value; + value.number(current->serial).number(*links.local_consent, 1); + transfer_send(current->before.host, direct::Kind::Accept, std::move(value.bytes)); + } + if (sender_id_ == current->before.host && phase == direct::Phase::Cancelled) { + direct::Write value; + value.number(current->serial); + transfer_all(direct::Kind::Cancel, value.bytes); + } + if (sender_id_ == current->before.host && phase == direct::Phase::Offered) { + direct::Write value; + value.number(current->serial).number(current->successor).number(current->save_owner).data(current->state); + value.number(links.directory_required, 1).number(links.directory_public, 1).text(links.directory_code); + transfer_all(direct::Kind::Offer, value.bytes); + } + if (phase == direct::Phase::Preparing) { + if (sender_id_ == current->successor && links.registration_ready) { + direct::Write value; + value.number(current->serial) + .data(links.successor_public) + .data(links.successor_capability) + .text(links.successor_endpoint) + .text(links.successor_invite); + transfer_send(current->before.host, direct::Kind::Registration, std::move(value.bytes)); + } + if (sender_id_ == current->before.host) { + direct::Write consent; + consent.number(current->serial).number(1, 1); + transfer_all(direct::Kind::Accept, consent.bytes); + if (links.prepared_state) { + direct::Write prepare; + prepare.number(current->serial) + .data(current->state) + .number(links.prepared_bytes.size(), 4) + .text(links.successor_endpoint); + transfer_all(direct::Kind::Prepare, prepare.bytes); + if (!links.handover.ready(current->successor)) + for (std::size_t at = 0; at < links.inventory_bytes.size(); at += direct::TransferChunk) { + direct::Write chunk; + chunk.number(current->serial) + .number(links.inventory_bytes.size(), 4) + .number(at, 4) + .data(std::span(links.inventory_bytes) + .subspan(at, + std::min(direct::TransferChunk, links.inventory_bytes.size() - at))); + transfer_send(current->successor, direct::Kind::Inventory, std::move(chunk.bytes)); + } + for (const auto& member : current->before.members) + if (member.id != sender_id_ && !links.handover.ready(member.id)) { + const auto offset = links.transfer_offsets[member.id]; + for (unsigned n = 0; + n < 8 && offset + n * direct::TransferChunk < links.prepared_bytes.size(); ++n) { + const auto at = offset + n * direct::TransferChunk, + count = std::min(direct::TransferChunk, links.prepared_bytes.size() - at); + direct::Write chunk; + chunk.number(current->serial) + .number(at, 4) + .data(std::span(links.prepared_bytes).subspan(at, count)); + transfer_send(member.id, direct::Kind::SaveChunk, std::move(chunk.bytes)); + } + } + } + } else if (links.handover.ready(sender_id_)) + transfer_send(current->before.host, direct::Kind::Prepared, transfer_identity()); + } + if (sender_id_ == current->before.host && links.handover.can_commit()) { + links.handover.commit(sender_id_, current->serial, current->state, transfer_error); + links.handover.acknowledge(sender_id_, current->serial, current->state, transfer_error); + } + if (sender_id_ == current->before.host && links.handover.phase() == direct::Phase::Committing) + transfer_all(direct::Kind::Commit, transfer_identity()); + if (sender_id_ == current->before.host && links.handover.complete() && + (!links.directory_required || links.directory_committed)) { + if (!links.released && apply_transfer()) + links.activated.insert(sender_id_); + if (links.released) { + transfer_all(direct::Kind::Release, transfer_identity()); + if (links.activated.size() == current->before.members.size()) { + if (!links.finished) { + links.finished = true; + links.finished_until = now + std::chrono::seconds(60); + links.status = "Host transferred. Ready to race."; + } + if (now < links.finished_until) + transfer_all(direct::Kind::Finished, transfer_identity()); + } + } + } + } +} diff --git a/runtime-recomp/src/game/netplay/session_links/handover_service.inl b/runtime-recomp/src/game/netplay/session_links/handover_service.inl new file mode 100644 index 00000000..90e7b7d1 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/handover_service.inl @@ -0,0 +1,409 @@ +// Native host-transfer coordinator. All calls run under the session owner lock. +auto digest_transfer = [](std::span bytes) { + direct::Digest result{}; + crypto_blake2b(result.data(), result.size(), bytes.data(), bytes.size()); + return result; +}; +const bool waiting = !party->launch && !party->running && !party->stopping && !launch_countdown_active_ && + launch_stage_ == LaunchStage::Idle && !connection_test_active_ && + pending_invitation_ == std::nullopt && + std::none_of(pending_joins_.begin(), pending_joins_.end(), [](const auto& p) { return p.active; }); +auto transfer_send = [&](direct::Id target, direct::Kind kind, std::vector bytes = {}) { + const auto& p = links.handover.proposal(); + if (!p) + return false; + return party->enqueue({target, watch::LinkKind::Extension, TransportTrafficClass::Control, + direct::encode({kind, match_id_, p->before.generation, std::move(bytes)})}); +}; +auto transfer_all = [&](direct::Kind kind, const std::vector& bytes) { + if (const auto& p = links.handover.proposal()) + for (const auto& m : p->before.members) + if (m.id != sender_id_) + transfer_send(m.id, kind, bytes); +}; +auto transfer_identity = [&] { + direct::Write out; + if (const auto& p = links.handover.proposal()) + out.number(p->serial).data(p->state); + return out.bytes; +}; +auto transfer_identity_ok = [&](direct::Read& r) { + const auto digest = r.data(32); + const auto& p = links.handover.proposal(); + return p && digest.size() == 32 && std::equal(digest.begin(), digest.end(), p->state.begin()); +}; +auto reset_transfer = [&] { + links.registration_started = links.registration_ready = links.prepared_state = links.released = links.finished = + false; + links.successor_endpoint.clear(); + links.successor_invite.clear(); + links.prepared_bytes.clear(); + links.assembly = {}; + links.expected_transfer = 0; + links.activated.clear(); + links.transfer_offsets.clear(); + links.transfer_send = {}; + links.local_consent.reset(); + links.inventory_assembly = {}; + links.inventory_bytes.clear(); + links.pending_keys.clear(); + links.inventory_hash = {}; + links.inventory_ready = false; + links.directory_required = links.directory_public = links.directory_accepted = links.directory_committed = false; + links.directory_code.clear(); + links.directory_send = {}; + links.mod_requested = links.mod_ready = false; +}; +auto parse_transfer = [&](bool install) -> bool { + const auto& p = links.handover.proposal(); + if (!p || links.prepared_bytes.empty() || digest_transfer(links.prepared_bytes) != p->state) + return false; + direct::Read r{links.prepared_bytes}; + if (r.number() != p->serial || r.number() != p->successor || r.number() != p->save_owner) + return false; + const auto pub = r.data(32), cap = r.data(32); + const auto endpoint = r.text(), invite = r.text(256); + const auto compatibility = r.number(), save_hash = r.number(), save_generation = r.number(4); + const auto inventory_hash = r.data(32); + const auto manifest_bytes = r.number(4); + const auto roster_bytes = r.data(r.number(4)), room_bytes = r.data(r.number(4)), seed = r.data(512); + const auto paks = r.data(r.number(4)), records = r.data(r.number(4)); + const auto maximum = r.number(1), spectators = r.number(1), launch_serial = r.number(); + std::map architectures; + const auto architecture_count = r.number(1); + if (architecture_count != party->party.snapshot().members.size()) + return false; + for (unsigned i = 0; i < architecture_count; ++i) { + const auto id = r.number(); + const auto architecture = r.text(128); + if (architecture.empty() || !party->party.find(id) || !architectures.emplace(id, architecture).second) + return false; + } + const auto own_architecture = architectures.find(sender_id_); + if (own_architecture == architectures.end() || own_architecture->second != manifest_.architecture) + return false; + if (!r.done() || pub.size() != 32 || cap.size() != 32 || inventory_hash.size() != 32 || seed.size() != 512 || + (!paks.empty() && paks.size() != 131072) || records.size() > 20 + 8192 * 76 || maximum < 1 || maximum > 4 || + spectators > 1) + return false; + watch::PartySnapshot prepared; + protocol::LobbyStatePayload room; + std::string error; + if (!watch::wire::roster(roster_bytes, prepared, error) || !protocol::decode_lobby_state(room_bytes, room, error) || + prepared.host != p->before.host || prepared.generation != p->before.generation || prepared.handover || + prepared.members != party->party.snapshot().members || prepared.controls != party->party.snapshot().controls || + compatibility != manifest_class_hash(room_view_.manifest) || !save_generation || + stable_hash(std::string_view(reinterpret_cast(seed.data()), seed.size())) != save_hash) + return false; + if (install) { + std::copy(pub.begin(), pub.end(), links.successor_public.begin()); + std::copy(cap.begin(), cap.end(), links.successor_capability.begin()); + links.successor_endpoint = endpoint; + links.successor_invite = invite; + links.save_owner = p->save_owner; + std::copy(inventory_hash.begin(), inventory_hash.end(), links.inventory_hash.begin()); + links.save_paks = paks; + links.save_records = records; + party->seed = seed; + party->maximum_racers = unsigned(maximum); + mod_manifest_bytes_ = std::uint32_t(manifest_bytes); + party->allow_spectators = spectators != 0; + party->launch_serial = launch_serial; + party->save_generation = std::uint32_t(save_generation); + party->save_hash = save_hash; + session_save_ = seed; + session_save_generation_ = party->save_generation; + const auto local_architecture = manifest_.architecture; + manifest_ = room_view_.manifest; + manifest_.architecture = local_architecture; + links.architectures = std::move(architectures); + other_architecture_senders_.clear(); + for (const auto& [id, architecture] : links.architectures) + if (id != sender_id_ && architecture != local_architecture) + other_architecture_senders_.insert(id); + manifest_.session_save_hash = save_hash; + room_view_.manifest = manifest_; + room_view_.name = room.room_name; + room_view_.visibility = room.visibility; + room_view_.rules = room.rules; + input_delay_ = room.input_delay_frames; + } + return true; +}; +auto apply_transfer = [&]() -> bool { + const auto& p = links.handover.proposal(); + if (!p || links.last_applied == p->serial) + return bool(p); + if (!links.prepared_state || !parse_transfer(true)) + return false; + std::string error; + const bool successor = sender_id_ == p->successor; + // Preserve the existing key's outbound nonce domain before adding a host + // route to PartyLink. Membership changes never reset replay or AEAD state. + if (!is_host_ && !party->peer(host_sender_id_)) { + watch::LinkPeer old; + old.id = host_sender_id_; + old.address = host_address_; + old.key = key_; + old.sequence = outbound_sequence(host_address_, key_); + old.heard = now; + party->peers.push_back(old); + } + auto* next = successor ? nullptr : party->peer(p->successor); + if (!successor && !next) + return false; + if (!direct::apply_host_role(*transport_, successor, links.successor_endpoint, error)) { + links.status = error; + return false; + } + if (!party->party.transfer_host(p->before.host, p->successor, p->before.generation + 1, error)) { + links.status = error; + return false; + } + for (const auto& peer : party->peers) { + direct::install(this, match_id_, peer.id, peer.address, peer.key); + links.introduced.try_emplace( + peer.id, direct::Introduction{peer.id, peer.key, direct::peer_name(*transport_, peer.address), now}); + } + if (successor) { + // Routing roles changed. Prove fresh realtime round trips in the new + // host role before publishing Finished or admitting the first Start. + for (auto& peer : party->peers) { + peer.rtt_count = peer.rtt_index = 0; + peer.rtts = {}; + peer.rtt_at = peer.ping_sent = {}; + peer.ping_window = {}; + } + links.keys = links.pending_keys; + host_key_pair_ = links.successor_keys; + invitation_capability_ = links.successor_capability; + invite_ = transport_->quick_join() ? links.successor_invite + : make_invite(advertised_host_.empty() ? "127.0.0.1" : advertised_host_); + const auto room = room_view_; + const auto* me = party->party.find(sender_id_); + if (!lobby_.create(hex64(match_id_), "dkr-r/" + invite_, room.name, room.visibility, std::to_string(sender_id_), + me ? me->name : local_name_, manifest_, room.rules, error)) { + links.status = error; + return false; + } + room_view_ = lobby_.room(); + room_view_.generation = party->party.snapshot().generation; + // Existing waiting members are projected from Party, not reassigned by + // the four-slot legacy lobby. Their controller leases stay unchanged. + peers_ = {}; + state_ = ConnectionState::Hosting; + } else { + host_address_ = next->address; + key_ = next->key; + host_public_ = links.successor_public; + invitation_capability_ = links.successor_capability; + invite_ = links.successor_invite; + state_ = ConnectionState::Lobby; + peers_ = {}; + } + is_host_ = successor; + host_sender_id_ = p->successor; + party->host = successor; + party->authority = p->successor; + party->ready.clear(); + party->advertised = {}; + last_admission_response_ = now; + last_client_request_ = now; + links.last_applied = p->serial; + links.released = true; + links.status = "Host transferred. Confirming every connection."; + return true; +}; +auto handle_transfer = [&](direct::Id source, const direct::Packet& packet) { + std::string error; + direct::Read r{packet.body}; + if (packet.kind == direct::Kind::Offer) { + if (source != host_sender_id_ || is_host_ || !waiting) + return; + direct::Proposal p; + p.before = links.scope; + p.serial = r.number(); + p.successor = r.number(); + p.save_owner = r.number(); + const auto digest = r.data(32); + const auto directory = r.number(1), public_room = r.number(1); + const auto code = r.text(); + if (!r.done() || digest.size() != 32 || directory > 1 || public_room > 1 || + (directory && !valid_quick_join_code(code)) || (!directory && !code.empty())) + return; + std::copy(digest.begin(), digest.end(), p.state.begin()); + for (auto& m : p.before.members) + m.capable = true; + if (links.handover.offer(source, p, waiting, now, error)) { + if (links.serial != p.serial) { + reset_transfer(); + links.serial = p.serial; + } + links.directory_required = directory != 0; + links.directory_public = public_room != 0; + links.directory_code = code; + for (const auto& m : p.before.members) + links.capable.insert(m.id); + links.scope = p.before; + } else + links.status = error; + return; + } + const auto proposal = links.handover.proposal(); + if (!proposal || packet.generation != proposal->before.generation) + return; + const auto serial = r.number(); + if (serial != proposal->serial) + return; + if (packet.kind == direct::Kind::Accept) { + const auto accepted = r.number(1); + if (!r.done() || accepted > 1 || (source != proposal->successor && source != proposal->before.host)) + return; + // Relayed consent is sufficient for observers, but the candidate + // must have accepted locally before opening a new host registration. + if (sender_id_ == proposal->successor && accepted && !links.local_consent.value_or(false)) + return; + if (links.handover.consent(proposal->successor, serial, accepted != 0, now, error) && + sender_id_ == proposal->before.host) { + direct::Write consent; + consent.number(serial).number(accepted, 1); + transfer_all(direct::Kind::Accept, consent.bytes); + } + } else if (packet.kind == direct::Kind::Registration) { + if (sender_id_ != proposal->before.host || source != proposal->successor || + links.handover.phase() != direct::Phase::Preparing || !links.prepared_bytes.empty()) + return; + const auto pub = r.data(32), cap = r.data(32); + const auto endpoint = r.text(), invite = r.text(256); + if (!r.done() || pub.size() != 32 || cap.size() != 32 || endpoint.empty() || invite.empty()) + return; + auto* peer = party->peer(source); + if (!peer || !direct::alias_peer(*transport_, peer->address, endpoint, error)) + return; + std::copy(pub.begin(), pub.end(), links.successor_public.begin()); + std::copy(cap.begin(), cap.end(), links.successor_capability.begin()); + links.successor_endpoint = endpoint; + links.successor_invite = invite; + links.registration_ready = true; + } else if (packet.kind == direct::Kind::Prepare) { + if (source != proposal->before.host || links.handover.phase() != direct::Phase::Preparing) + return; + const auto digest = r.data(32); + const auto total = r.number(4); + const auto endpoint = r.text(); + if (!r.done() || digest.size() != 32 || !total || total > direct::MaximumTransferBytes) + return; + direct::Digest hash; + std::copy(digest.begin(), digest.end(), hash.begin()); + if (links.expected_transfer) { + if (links.expected_transfer != total || proposal->state != hash) + return; + } else if (!links.handover.bind(source, serial, hash, error)) + return; + if (auto* peer = party->peer(proposal->successor); peer && links.successor_endpoint != endpoint) + if (!direct::alias_peer(*transport_, peer->address, endpoint, error)) + return; + links.successor_endpoint = endpoint; + links.expected_transfer = std::size_t(total); + } else if (packet.kind == direct::Kind::SaveChunk) { + if (source != proposal->before.host || !links.expected_transfer || + links.handover.phase() != direct::Phase::Preparing) + return; + const auto offset = r.number(4); + const auto data = r.data(r.bytes.size() - std::min(r.at, r.bytes.size())); + if (!r.done() || !links.assembly.accept(serial, links.expected_transfer, std::size_t(offset), data)) + return; + std::size_t through = 0; + for (bool v : links.assembly.received) { + if (!v) + break; + through += direct::TransferChunk; + } + through = std::min(through, links.expected_transfer); + direct::Write receipt; + receipt.number(serial).number(through, 4); + transfer_send(source, direct::Kind::SaveReceipt, std::move(receipt.bytes)); + if (links.assembly.complete() && !links.prepared_state) { + links.prepared_bytes = links.assembly.bytes; + links.prepared_state = parse_transfer(true); + } + } else if (packet.kind == direct::Kind::Inventory) { + if (source != proposal->before.host || sender_id_ != proposal->successor || !links.prepared_state || + links.handover.phase() != direct::Phase::Preparing) + return; + const auto total = r.number(4), offset = r.number(4); + const auto data = r.data(r.bytes.size() - std::min(r.at, r.bytes.size())); + if (!r.done() || total > 1 + 66 * 48 || + !links.inventory_assembly.accept(serial, std::size_t(total), std::size_t(offset), data)) + return; + if (links.inventory_assembly.complete() && + digest_transfer(links.inventory_assembly.bytes) == links.inventory_hash) { + direct::Read inventory{links.inventory_assembly.bytes}; + const auto count = inventory.number(1); + std::map keys; + if (count > 66) + return; + for (unsigned i = 0; i < count; ++i) { + const auto a = inventory.number(), b = inventory.number(); + const auto bytes = inventory.data(32); + if (a >= b || !party->party.find(a) || !party->party.find(b) || bytes.size() != 32 || + keys.contains({a, b})) + return; + secure::Key key; + std::copy(bytes.begin(), bytes.end(), key.begin()); + keys.emplace(direct::Pair{a, b}, key); + } + if (inventory.done()) { + links.pending_keys = std::move(keys); + links.inventory_ready = true; + } + } + } else if (packet.kind == direct::Kind::SaveReceipt) { + if (sender_id_ != proposal->before.host) + return; + const auto offset = r.number(4); + if (!r.done() || offset > links.prepared_bytes.size() || + (offset != links.prepared_bytes.size() && offset % direct::TransferChunk)) + return; + links.transfer_offsets[source] = std::max(links.transfer_offsets[source], std::size_t(offset)); + } else if (packet.kind == direct::Kind::Prepared) { + if (sender_id_ != proposal->before.host || !transfer_identity_ok(r) || !r.done()) + return; + links.handover.prepared(source, serial, proposal->state, true, now, error); + } else if (packet.kind == direct::Kind::Commit) { + if (source != proposal->before.host || !links.prepared_state || !links.handover.ready(sender_id_) || + !transfer_identity_ok(r) || !r.done()) + return; + if (links.handover.phase() == direct::Phase::Preparing) + for (const auto& member : proposal->before.members) + links.handover.prepared(member.id, serial, proposal->state, true, now, error); + if (links.handover.commit(source, serial, proposal->state, error)) + transfer_send(source, direct::Kind::Acknowledge, transfer_identity()); + } else if (packet.kind == direct::Kind::Acknowledge) { + if (sender_id_ == proposal->before.host && transfer_identity_ok(r) && r.done()) + links.handover.acknowledge(source, serial, proposal->state, error); + } else if (packet.kind == direct::Kind::Release) { + if (source != proposal->before.host || !transfer_identity_ok(r) || !r.done() || + (links.handover.phase() != direct::Phase::Committing && links.handover.phase() != direct::Phase::Committed)) + return; + if (apply_transfer() && sender_id_ != proposal->successor) + transfer_send(source, direct::Kind::Activated, transfer_identity()); + } else if (packet.kind == direct::Kind::Activated) { + if (sender_id_ == proposal->before.host && links.released && transfer_identity_ok(r) && r.done()) + links.activated.insert(source); + } else if (packet.kind == direct::Kind::Finished) { + if (source == proposal->before.host && links.released && transfer_identity_ok(r) && r.done()) { + for (const auto& member : proposal->before.members) + links.handover.acknowledge(member.id, serial, proposal->state, error); + links.finished = true; + links.status = "Host transferred. Ready to race."; + } + } else if (packet.kind == direct::Kind::Cancel) { + if (!r.done() || (source != proposal->before.host && source != proposal->successor)) + return; + if (links.handover.cancel(source, serial, "Host transfer cancelled. The original host is still in charge.", + error) && + sender_id_ == proposal->before.host) + transfer_all(direct::Kind::Cancel, packet.body); + } +}; diff --git a/runtime-recomp/src/game/netplay/session_links/menu_control.hpp b/runtime-recomp/src/game/netplay/session_links/menu_control.hpp new file mode 100644 index 00000000..a03b37b9 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/menu_control.hpp @@ -0,0 +1,33 @@ +#pragma once +#include + +namespace dkr::runtime::netplay::links::menu_control { +// Construction context only. Each owned world retains this agreed port; tick +// and replay never consult a live lobby or another thread's UI state. +inline thread_local unsigned construction_port = 0; +class CreationPort final { + unsigned previous_; + + public: + explicit CreationPort(unsigned port) : previous_(construction_port) { + construction_port = port < 4 ? port : 0; + } + ~CreationPort() { + construction_port = previous_; + } + CreationPort(const CreationPort&) = delete; + CreationPort& operator=(const CreationPort&) = delete; +}; +inline unsigned creating_port() { + return construction_port; +} +template +auto input(const Inputs& values, unsigned authority, unsigned guest_port, bool host_only, unsigned assigned) { + using Value = std::remove_cvref_t; + if (authority >= 4 || guest_port >= 4) + return Value{}; + if (host_only) + return guest_port == 0 ? values[authority] : Value{}; + return !assigned || (assigned & (1U << guest_port)) ? values[guest_port] : Value{}; +} +} // namespace dkr::runtime::netplay::links::menu_control diff --git a/runtime-recomp/src/game/netplay/session_links/mod_host.inl b/runtime-recomp/src/game/netplay/session_links/mod_host.inl new file mode 100644 index 00000000..4f3b9619 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/mod_host.inl @@ -0,0 +1,66 @@ +// Included at namespace scope by the retained mod-sync owner composition. +namespace dkr::mods::online { +bool ModSync::cached_host_active() const { + const auto current = snapshot(); + return running_.load() && current.phase == SyncPhase::HostReady && current.manifest && current.profile && + current.runtime; +} +bool ModSync::promote_cached_host(SyncSettings settings, std::string& error) { + auto ready = snapshot(); + if ((ready.phase != SyncPhase::Verified && ready.phase != SyncPhase::HostReady) || !ready.manifest || + !ready.profile || !ready.runtime || ready.profile->digest != identity(*ready.manifest)) { + error = "The successor has no matching verified mod session."; + return false; + } + if (!start(SyncPhase::HostPreparing)) { + error.clear(); + return false; + } + try { + thread_ = std::jthread([this, settings = std::move(settings), + ready = std::move(ready)](std::stop_token stop) mutable { + try { + const auto root = private_storage_path(settings.online_root) / "payloads"; + auto bundle = std::make_shared(); + bundle->manifest = *ready.manifest; + for (const auto& item : bundle->manifest.payloads) { + require_running(stop); + check_storage(root / item.digest, false); + auto bytes = std::make_shared(read_file(root / item.digest, std::size_t(item.size))); + if (bytes->size() != item.size || sha256(*bytes) != item.digest) + throw Error("A cached online mod changed. Host transfer was cancelled."); + bundle->payloads.emplace(item.digest, std::move(bytes)); + } + require_running(stop); + ready.phase = SyncPhase::HostReady; + ready.error.clear(); + ready.stage = "Shared session mods are ready for hosting"; + publish(ready); + host_loop(std::move(bundle), stop); + } catch (const std::exception& e) { + if (!stop.stop_requested()) { + ready.phase = SyncPhase::Verified; + ready.error = e.what(); + publish(std::move(ready)); + } + } catch (...) { + if (!stop.stop_requested()) { + ready.phase = SyncPhase::Verified; + ready.error = "The shared mod session could not be prepared for hosting."; + publish(std::move(ready)); + } + } + running_.store(false); + }); + } catch (const std::exception& e) { + running_.store(false); + ready.phase = SyncPhase::Verified; + ready.error = e.what(); + publish(std::move(ready)); + error = e.what(); + return false; + } + error.clear(); + return true; +} +} // namespace dkr::mods::online diff --git a/runtime-recomp/src/game/netplay/session_links/mod_owner_ui.inl b/runtime-recomp/src/game/netplay/session_links/mod_owner_ui.inl new file mode 100644 index 00000000..9bb034d7 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/mod_owner_ui.inl @@ -0,0 +1,36 @@ +// The frontend owns the existing mod worker. The network owner only consumes +// its readiness bit; it never scans, reads or prepares mod files under locks. +{ + namespace watch = dkr::runtime::spectators; + namespace links = dkr::runtime::netplay::links; + auto hub = watch::party_link(&session()); + bool candidate = false, requested = false; + { + std::scoped_lock lock(hub->mutex); + const auto& p = hub->links.handover.proposal(); + candidate = + hub->enabled && p && p->successor == hub->local && hub->links.handover.phase() == links::Phase::Preparing; + requested = hub->links.mod_requested; + } + if (candidate && !network.room.manifest.mod_manifest_hash.empty()) { + if (g_online_mod_sync->cached_host_active() && view.manifest && + identity(*view.manifest) == network.room.manifest.mod_manifest_hash) { + std::scoped_lock lock(hub->mutex); + hub->links.mod_ready = true; + } else if (requested && view.phase == SyncPhase::Verified && !view.error.empty()) { + std::scoped_lock lock(hub->mutex); + hub->links.status = view.error; + hub->links.cancel = true; + } else if (!requested && (view.phase == SyncPhase::Verified || view.phase == SyncPhase::HostReady)) { + std::string error; + if (g_online_mod_sync->promote_cached_host(OnlineModSettings(), error)) { + std::scoped_lock lock(hub->mutex); + hub->links.mod_requested = true; + } else if (!error.empty()) { + std::scoped_lock lock(hub->mutex); + hub->links.status = error; + hub->links.cancel = true; + } + } + } +} diff --git a/runtime-recomp/src/game/netplay/session_links/owner_service.inl b/runtime-recomp/src/game/netplay/session_links/owner_service.inl new file mode 100644 index 00000000..dc6c1df6 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/owner_service.inl @@ -0,0 +1,264 @@ +// Session links' explicit owner boundary. Requires mutex_ and party.mutex. +void DirectSession::service_session_links_locked(dkr::runtime::spectators::PartyLink& value, + std::chrono::steady_clock::time_point now) { + namespace watch = dkr::runtime::spectators; + auto* party = &value; + namespace direct = dkr::runtime::netplay::links; + auto& links = party->links; + const auto& roster = party->party.snapshot(); + if (links.scope.room != match_id_) { + direct::forget(this); + links.reset(); + links.save_owner = roster.host; + } + std::erase_if(links.capable, [&](auto id) { return !party->party.find(id); }); + std::erase_if(links.capacity, [&](const auto& entry) { return !party->party.find(entry.first); }); + const auto departed = [&](const auto& entry) { return !party->party.find(entry.first); }; + std::erase_if(links.pings, departed); + std::erase_if(links.rtts, departed); + std::erase_if(links.last_probe, departed); + std::erase_if(links.probe_results, departed); + std::erase_if(links.samples, [&](const auto& entry) { + return !party->party.find(entry.first.first) || !party->party.find(entry.first.second); + }); + links.capable.insert(sender_id_); + links.architectures.insert_or_assign(sender_id_, manifest_.architecture); + direct::Scope scope{match_id_, roster.host, roster.generation}; + for (const auto& m : roster.members) + scope.members.push_back({m.id, m.port ? int(*m.port) : -1, links.capable.contains(m.id)}); + links.scope = scope; + auto emit = [&](std::uint64_t target, direct::Kind kind, std::vector bytes = {}) { + const auto traffic = kind == direct::Kind::Ping || kind == direct::Kind::Pong ? TransportTrafficClass::Realtime + : TransportTrafficClass::Control; + return party->enqueue({target, watch::LinkKind::Extension, traffic, + direct::encode({kind, match_id_, roster.generation, std::move(bytes)})}); + }; +#include "handover_service.inl" + for (auto it = links.keys.begin(); it != links.keys.end();) { + if (!party->party.find(it->first.first) || !party->party.find(it->first.second)) { + crypto_wipe(it->second.data(), it->second.size()); + it = links.keys.erase(it); + } else + ++it; + } + for (auto it = links.introduced.begin(); it != links.introduced.end();) { + if (!party->party.find(it->first)) { + direct::revoke(this, it->first); + if (!is_host_) { + if (const auto* peer = party->peer(it->first)) + transport_->release_peer_route(peer->address); + std::erase_if(party->peers, [&](const auto& p) { return p.id == it->first; }); + } + it = links.introduced.erase(it); + } else + ++it; + } + if (now >= links.hello) { + links.hello = now + std::chrono::seconds(1); + direct::Write hello; + hello.number(direct::ProtocolVersion, 1); + if (!is_host_) + emit(host_sender_id_, direct::Kind::Hello, std::move(hello.bytes)); + } + for (unsigned work = 0; work < 32 && !links.incoming.empty(); ++work) { + auto incoming = std::move(links.incoming.front()); + links.incoming.pop_front(); + const auto source = incoming.source; + const auto& packet = incoming.packet; + const auto& transfer = links.handover.proposal(); + const bool transferring = + transfer && packet.kind >= direct::Kind::Offer && packet.generation == transfer->before.generation; + if (packet.room != match_id_ || (!transferring && packet.generation != roster.generation) || + !party->party.find(source)) + continue; + direct::Read read{packet.body}; + if (packet.kind == direct::Kind::Hello) { + const auto version = read.number(1); + const auto save_owner = !is_host_ && read.at < read.bytes.size() ? read.number() : 0; + if (version == direct::ProtocolVersion && read.done() && (is_host_ || source == host_sender_id_)) { + links.capable.insert(source); + if (is_host_) { + direct::Write hello; + hello.number(direct::ProtocolVersion, 1).number(links.save_owner); + emit(source, direct::Kind::Hello, std::move(hello.bytes)); + } else if (save_owner) + links.save_owner = save_owner; + } + } else if (packet.kind == direct::Kind::Introduce) { + if (is_host_ || source != host_sender_id_) + continue; + const auto id = read.number(); + const auto bytes = read.data(32); + const auto endpoint = read.text(); + const auto* remote = party->party.find(id); + if (!read.done() || !remote || id == sender_id_ || id == host_sender_id_ || bytes.size() != 32) + continue; + const bool racers = remote->role == watch::Role::Racer && !party->local_watching(); + const auto& proposal = links.handover.proposal(); + const bool transfer = proposal && links.handover.phase() == direct::Phase::Preparing && + (proposal->successor == id || proposal->successor == sender_id_); + if (!racers && !transfer) + continue; + secure::Key key; + std::copy(bytes.begin(), bytes.end(), key.begin()); + if (const auto old = links.introduced.find(id); old != links.introduced.end() && old->second.key != key) + continue; + PeerAddress address; + std::string error; + if (const auto old = links.introduced.find(id); + old != links.introduced.end() && old->second.endpoint != endpoint) + if (auto* peer = party->peer(id); + peer && !direct::alias_peer(*transport_, peer->address, endpoint, error)) + continue; + if (!direct::introduce_peer(*transport_, endpoint, sender_id_ < id, address, error)) + continue; + auto* peer = party->peer(id); + if (peer && (!(peer->address == address) || peer->key != key)) + continue; + if (!direct::install(this, match_id_, id, address, key)) + continue; + if (!peer) { + watch::LinkPeer value; + value.id = id; + value.address = address; + value.key = key; + value.heard = now; + party->peers.push_back(value); + } + links.capable.insert(id); + links.introduced.insert_or_assign(id, direct::Introduction{id, key, endpoint, now}); + transport_->retain_peer_route(address); + } else if (packet.kind == direct::Kind::Ping) { + const auto token = read.number(); + if (!read.done() || !token) + continue; + if (source != host_sender_id_ && !links.introduced.contains(source) && !is_host_) + continue; + direct::Write pong; + pong.number(token); + emit(source, direct::Kind::Pong, std::move(pong.bytes)); + } else if (packet.kind == direct::Kind::Pong) { + const auto token = read.number(); + if (!read.done()) + continue; + auto pending = links.pings.find(source); + if (pending == links.pings.end()) + continue; + const auto sent = pending->second.find(token); + if (sent == pending->second.end() || now < sent->second) + continue; + const auto elapsed = std::chrono::duration_cast(now - sent->second).count(); + pending->second.erase(sent); + if (elapsed > 5000) + continue; + auto& values = links.rtts[source]; + values.push_back(unsigned(elapsed)); + if (values.size() > 32) + values.pop_front(); + std::vector sorted(values.begin(), values.end()); + std::sort(sorted.begin(), sorted.end()); + auto& outcomes = links.probe_results[source]; + outcomes.push_back(true); + if (outcomes.size() > 32) + outcomes.pop_front(); + const auto losses = std::count(outcomes.begin(), outcomes.end(), false); + links.samples[{sender_id_, source}] = {sorted[(sorted.size() - 1) * 95 / 100], + unsigned(1000U * losses / outcomes.size()), unsigned(values.size()), + now}; + } else if (packet.kind == direct::Kind::Report) { + if (!is_host_) + continue; + const auto other = read.number(), p95 = read.number(2), loss = read.number(2), samples = read.number(1); + if (!read.done() || !party->party.find(other) || other == source || p95 > 5000 || loss > 1000 || + samples > 32) + continue; + links.samples[{source, other}] = {unsigned(p95), unsigned(loss), unsigned(samples), now}; + } else + handle_transfer(source, packet); + } + if (is_host_ && now >= links.introduce) { + links.introduce = now + std::chrono::seconds(1); + for (const auto& a : roster.members) + for (const auto& b : roster.members) { + if (a.id >= b.id || a.id == sender_id_ || b.id == sender_id_ || !links.capable.contains(a.id) || + !links.capable.contains(b.id)) + continue; + const bool racers = a.role == watch::Role::Racer && b.role == watch::Role::Racer; + const auto& proposal = links.handover.proposal(); + const bool transfer = proposal && links.handover.phase() == direct::Phase::Preparing && + (proposal->successor == a.id || proposal->successor == b.id); + if (!racers && !transfer) + continue; + auto* first = party->peer(a.id); + auto* second = party->peer(b.id); + if (!first || !second) + continue; + auto key = links.keys.find({a.id, b.id}); + if (key == links.keys.end()) + key = links.keys.emplace(direct::Pair{a.id, b.id}, secure::generate_key()).first; + const auto first_name = direct::peer_name(*transport_, first->address), + second_name = direct::peer_name(*transport_, second->address); + if (first_name.empty() || second_name.empty()) + continue; + direct::Write for_first; + for_first.number(b.id).data(key->second).text(second_name); + direct::Write for_second; + for_second.number(a.id).data(key->second).text(first_name); + emit(a.id, direct::Kind::Introduce, std::move(for_first.bytes)); + emit(b.id, direct::Kind::Introduce, std::move(for_second.bytes)); + } + } + if (now >= links.probe) { + links.probe = now + std::chrono::milliseconds(500); + links.live_routes.clear(); + auto probe = [&](std::uint64_t id, const PeerAddress& address) { + if (!transport_->traffic_ready(address, TransportTrafficClass::Control)) + return; + if (party->participant(sender_id_) && party->participant(id) && + transport_->traffic_ready(address, TransportTrafficClass::Realtime)) + links.live_routes.insert(id); + auto& pending = links.pings[id]; + std::erase_if(pending, [&](const auto& p) { + if (now - p.second <= std::chrono::seconds(5)) + return false; + auto& results = links.probe_results[id]; + results.push_back(false); + if (results.size() > 32) + results.pop_front(); + return true; + }); + if (pending.size() >= 12) + return; + const auto token = + std::uint64_t(std::chrono::duration_cast(now.time_since_epoch()).count()); + pending[token] = now; + direct::Write ping; + ping.number(token); + emit(id, direct::Kind::Ping, std::move(ping.bytes)); + }; + if (is_host_) { + for (const auto& peer : party->peers) + if (links.capable.contains(peer.id)) + probe(peer.id, peer.address); + } else { + if (links.capable.contains(host_sender_id_)) + probe(host_sender_id_, host_address_); + for (const auto& [id, intro] : links.introduced) + if (auto* peer = party->peer(id)) + probe(id, peer->address); + } + } + if (!is_host_ && now >= links.report) { + links.report = now + std::chrono::seconds(1); + for (const auto& [pair, sample] : links.samples) + if (pair.first == sender_id_ && now - sample.measured < std::chrono::seconds(5)) { + direct::Write report; + report.number(pair.second) + .number(sample.p95_ms, 2) + .number(sample.loss_per_mille, 2) + .number(sample.observations, 1); + emit(host_sender_id_, direct::Kind::Report, std::move(report.bytes)); + } + } +#include "handover_pump.inl" +} diff --git a/runtime-recomp/src/game/netplay/session_links/policy.cpp b/runtime-recomp/src/game/netplay/session_links/policy.cpp new file mode 100644 index 00000000..6dcacdb0 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/policy.cpp @@ -0,0 +1,270 @@ +#include "session_log.hpp" +#include "policy.hpp" +#include +#include +#include +#include +#include + +namespace dkr::runtime::netplay::links { +namespace { +bool fail(std::string& error, std::string reason) { + error = std::move(reason); + return false; +} +const Member* member(const Scope& scope, Id id) { + const auto at = + std::find_if(scope.members.begin(), scope.members.end(), [id](const Member& m) { return m.id == id; }); + return at == scope.members.end() ? nullptr : &*at; +} +std::size_t index(const Scope& scope, Id id) { + const auto at = + std::find_if(scope.members.begin(), scope.members.end(), [id](const Member& m) { return m.id == id; }); + return std::size_t(at - scope.members.begin()); +} +} // namespace + +bool valid(const Scope& scope) { + if (!scope.room || !scope.host || !scope.generation || scope.members.empty() || + scope.members.size() > MaximumMembers || !member(scope, scope.host)) + return false; + std::set ids; + std::set ports; + for (const auto& m : scope.members) + if (!m.id || !ids.insert(m.id).second || m.port < -1 || m.port >= int(MaximumRacers) || + (m.port >= 0 && !ports.insert(m.port).second)) + return false; + return scope.members.size() - ports.size() <= MaximumMembers - MaximumRacers; +} + +bool input_pair(const Scope& scope, Id a, Id b) { + const auto* first = member(scope, a); + const auto* second = member(scope, b); + return valid(scope) && a != b && first && second && first->port >= 0 && second->port >= 0 && first->capable && + second->capable; +} +bool input_owner(const Scope& scope, Id sender, unsigned port) { + const auto* owner = member(scope, sender); + return valid(scope) && port < MaximumRacers && owner && owner->capable && owner->port == int(port); +} + +std::optional recommend(const Scope& scope, const std::map& samples, + const std::map& capacities, Clock::time_point now) { + if (!valid(scope)) + return {}; + std::optional best, current; + for (const auto& candidate : scope.members) { + if (!candidate.capable) + continue; + const auto capacity = capacities.find(candidate.id); + if (capacity != capacities.end() && capacity->second.measured && + (capacity->second.sampled > now || now - capacity->second.sampled > std::chrono::seconds(10) || + capacity->second.step_p95_us >= 25000 || capacity->second.background_saturated)) + continue; + Recommendation score{candidate.id}; + score.capacity_measured = capacity != capacities.end() && capacity->second.measured; + bool measured = true; + for (const auto& racer : scope.members) { + if (racer.port < 0 || racer.id == candidate.id) + continue; + const auto at = samples.find({candidate.id, racer.id}); + if (at == samples.end() || at->second.observations < 8 || at->second.measured > now || + now - at->second.measured > std::chrono::seconds(5)) { + measured = false; + break; + } + score.worst_p95_ms = std::max(score.worst_p95_ms, at->second.p95_ms); + score.worst_loss_per_mille = std::max(score.worst_loss_per_mille, at->second.loss_per_mille); + } + if (!measured) + continue; + if (candidate.id == scope.host) + current = score; + const auto rank = [](const Recommendation& value) { + return std::tuple{value.worst_loss_per_mille, value.worst_p95_ms, value.member}; + }; + if (!best || rank(score) < rank(*best)) + best = score; + } + if (!best || best->member == scope.host) + return {}; + // Avoid presenting a recommendation from incomplete comparisons or tiny + // fluctuations. Missing host capacity is a separate, explicit reason. + if (current && best->worst_loss_per_mille >= current->worst_loss_per_mille && + best->worst_p95_ms + 20 >= current->worst_p95_ms) + return {}; + best->reason = !best->capacity_measured + ? "Shorter measured network paths. Processing headroom has not been measured." + : current ? "More consistent measured connections to the racers." + : "Measured connections and processing headroom are available on this player."; + return best; +} + +bool Handover::expected(Id authenticated, Id serial) const { + return proposal_ && proposal_->serial == serial && member(proposal_->before, authenticated); +} +bool Handover::offer(Id authenticated, Proposal value, bool waiting, Clock::time_point now, std::string& error) { + if (proposal_ && *proposal_ == value && authenticated == value.before.host && phase_ != Phase::Cancelled) { + error.clear(); + return true; + } + if (!waiting || phase_ == Phase::Offered || phase_ == Phase::Preparing || phase_ == Phase::Committing) + return fail(error, "Finish the current operation before transferring host."); + if (!valid(value.before) || authenticated != value.before.host || !value.serial || + value.serial <= highest_serial_ || value.successor == value.before.host || + !member(value.before, value.successor) || !value.save_owner || + value.before.generation == std::numeric_limits::max() || + std::all_of(value.state.begin(), value.state.end(), [](auto b) { return b == 0; }) || + !std::all_of(value.before.members.begin(), value.before.members.end(), [](const auto& m) { return m.capable; })) + return fail(error, "Every connected player must support this host transfer."); + highest_serial_ = value.serial; + proposal_ = std::move(value); + prepared_ = {}; + acknowledged_ = {}; + phase_ = Phase::Offered; + deadline_ = now + std::chrono::seconds(20); + status_ = "Waiting for the new host to accept."; + error.clear(); + return true; +} +bool Handover::consent(Id authenticated, Id serial, bool accept, Clock::time_point now, std::string& error) { + if (!expected(authenticated, serial) || authenticated != proposal_->successor) + return fail(error, "Only the proposed host can accept this transfer."); + if (!accept && (phase_ == Phase::Offered || phase_ == Phase::Preparing)) + return cancel(authenticated, serial, "The proposed host declined.", error); + if (accept && phase_ == Phase::Preparing) { + error.clear(); + return true; + } + if (!accept || phase_ != Phase::Offered || now > deadline_) + return fail(error, "That host transfer is no longer waiting for acceptance."); + phase_ = Phase::Preparing; + deadline_ = now + std::chrono::seconds(120); + status_ = "Preparing the new host connections."; + error.clear(); + return true; +} +bool Handover::bind(Id authenticated, Id serial, const Digest& digest, std::string& error) { + if (!expected(authenticated, serial) || authenticated != proposal_->before.host || phase_ != Phase::Preparing || + std::any_of(prepared_.begin(), prepared_.end(), [](bool b) { return b; }) || + std::all_of(digest.begin(), digest.end(), [](auto b) { return !b; })) + return fail(error, "The prepared host transfer cannot change after a readiness vote."); + proposal_->state = digest; + error.clear(); + return true; +} +bool Handover::prepared(Id authenticated, Id serial, const Digest& digest, bool routes_ready, Clock::time_point now, + std::string& error) { + if (!expected(authenticated, serial) || phase_ != Phase::Preparing || now > deadline_ || !routes_ready || + digest != proposal_->state) + return fail(error, "The host transfer state or connections are not ready."); + prepared_[index(proposal_->before, authenticated)] = true; + error.clear(); + return true; +} +bool Handover::can_commit() const { + return proposal_ && phase_ == Phase::Preparing && + std::all_of(prepared_.begin(), prepared_.begin() + proposal_->before.members.size(), + [](bool b) { return b; }); +} +bool Handover::commit(Id authenticated, Id serial, const Digest& digest, std::string& error) { + if (!expected(authenticated, serial) || authenticated != proposal_->before.host || digest != proposal_->state) + return fail(error, "Only the current host can commit the prepared transfer."); + if (phase_ == Phase::Committing || phase_ == Phase::Committed) { + error.clear(); + return true; + } + if (!can_commit()) + return fail(error, "Every connected player must prepare before host ownership changes."); + phase_ = Phase::Committing; + status_ = "Transferring host. Waiting for acknowledgements."; + error.clear(); + return true; +} +bool Handover::acknowledge(Id authenticated, Id serial, const Digest& digest, std::string& error) { + if (!expected(authenticated, serial) || digest != proposal_->state || + (phase_ != Phase::Committing && phase_ != Phase::Committed)) + return fail(error, "That acknowledgement does not belong to this host transfer."); + acknowledged_[index(proposal_->before, authenticated)] = true; + if (complete()) { + phase_ = Phase::Committed; + status_ = "Host transferred."; + } + error.clear(); + return true; +} +bool Handover::complete() const { + return proposal_ && (phase_ == Phase::Committing || phase_ == Phase::Committed) && + std::all_of(acknowledged_.begin(), acknowledged_.begin() + proposal_->before.members.size(), + [](bool b) { return b; }); +} +bool Handover::cancel(Id authenticated, Id serial, std::string reason, std::string& error) { + if (!expected(authenticated, serial) || + (authenticated != proposal_->before.host && authenticated != proposal_->successor) || + (phase_ != Phase::Offered && phase_ != Phase::Preparing)) + return fail(error, "A committed host transfer cannot be rolled back."); + dkr::runtime::session_log::write( + "[online][handover-cancel] at-us=%llu actor=%llu serial=%llu phase=%u reason=%s\n", + (unsigned long long)std::chrono::duration_cast(Clock::now().time_since_epoch()) + .count(), + (unsigned long long)authenticated, (unsigned long long)serial, unsigned(phase_), reason.c_str()); + phase_ = Phase::Cancelled; + status_ = std::move(reason); + error.clear(); + return true; +} +void Handover::service(const Scope& current, bool waiting, Clock::time_point now) { + if (!proposal_ || (phase_ != Phase::Offered && phase_ != Phase::Preparing)) + return; + if (current != proposal_->before || !waiting || now > deadline_) { + const auto reason = current != proposal_->before ? "scope" : !waiting ? "busy" : "deadline"; + dkr::runtime::session_log::write( + "[online][handover-cancel] reason=%s serial=%llu host=%llu/%llu generation=%llu/%llu members=%zu/%zu waiting=%u\n", + reason, (unsigned long long)proposal_->serial, (unsigned long long)current.host, + (unsigned long long)proposal_->before.host, (unsigned long long)current.generation, + (unsigned long long)proposal_->before.generation, current.members.size(), proposal_->before.members.size(), + unsigned(waiting)); + if (current != proposal_->before) + for (const auto& m : current.members) { + const auto* old = member(proposal_->before, m.id); + if (!old || *old != m) + dkr::runtime::session_log::write("[online][handover-cancel] member=%llu port=%d/%d capable=%u/%u\n", + (unsigned long long)m.id, m.port, old ? old->port : -2, + unsigned(m.capable), old ? unsigned(old->capable) : 0); + } + phase_ = Phase::Cancelled; + status_ = + current != proposal_->before + ? "Host transfer cancelled because the lobby changed. The original host is still in charge." + : !waiting + ? "Host transfer cancelled because another lobby operation started. The original host is still in charge." + : "Host transfer timed out. The original host is still in charge."; + } + // Once committed, never restore old authority because an ACK was lost. + // The owner must retransmit the commit and hold race start until complete. +} +bool Handover::ready(Id id) const { + return proposal_ && member(proposal_->before, id) && prepared_[index(proposal_->before, id)]; +} +bool Handover::acknowledged(Id id) const { + return proposal_ && member(proposal_->before, id) && acknowledged_[index(proposal_->before, id)]; +} +std::optional Handover::result() const { + if (!proposal_ || (phase_ != Phase::Committing && phase_ != Phase::Committed)) + return {}; + auto result = proposal_->before; + result.host = proposal_->successor; + ++result.generation; + return result; +} +void Handover::reset() { + phase_ = Phase::Idle; + proposal_.reset(); + prepared_ = {}; + acknowledged_ = {}; + deadline_ = {}; + highest_serial_ = 0; + status_.clear(); +} + +} // namespace dkr::runtime::netplay::links diff --git a/runtime-recomp/src/game/netplay/session_links/policy.hpp b/runtime-recomp/src/game/netplay/session_links/policy.hpp new file mode 100644 index 00000000..5cf7ad62 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/policy.hpp @@ -0,0 +1,108 @@ +#pragma once + +#include "netplay/secure_channel.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dkr::runtime::netplay::links { + +using Id = std::uint64_t; +using Clock = std::chrono::steady_clock; +using Digest = std::array; +inline constexpr unsigned MaximumMembers = 12, MaximumRacers = 4; + +struct Member { + Id id = 0; + int port = -1; + bool capable = false; + bool operator==(const Member&) const = default; +}; + +struct Scope { + Id room = 0, host = 0, generation = 0; + std::vector members; + bool operator==(const Scope&) const = default; +}; + +bool valid(const Scope&); +bool input_pair(const Scope&, Id first, Id second); +bool input_owner(const Scope&, Id sender, unsigned port); + +// A sample describes the complete authenticated endpoint path. It must not be +// populated with the RTT to a proxy or a signaling service. +struct Sample { + unsigned p95_ms = 0, loss_per_mille = 0, observations = 0; + Clock::time_point measured{}; +}; +struct Capacity { + unsigned step_p95_us = 0; + bool measured = false, background_saturated = false; + Clock::time_point sampled{}; +}; +struct Recommendation { + Id member = 0; + unsigned worst_p95_ms = 0, worst_loss_per_mille = 0; + std::string reason; + bool capacity_measured = false; +}; +using Pair = std::pair; +std::optional recommend(const Scope&, const std::map&, const std::map&, + Clock::time_point now); + +// The host can change independently of controller-port and persistent-save +// ownership. The prepared digest binds their full native session snapshot. +struct Proposal { + Scope before; + Id serial = 0, successor = 0, save_owner = 0; + Digest state{}; + bool operator==(const Proposal&) const = default; +}; +enum class Phase { Idle, Offered, Preparing, Committing, Committed, Cancelled }; + +class Handover final { + public: + bool offer(Id authenticated, Proposal, bool waiting, Clock::time_point now, std::string& error); + bool consent(Id authenticated, Id serial, bool accept, Clock::time_point now, std::string& error); + bool bind(Id authenticated, Id serial, const Digest&, std::string& error); + bool prepared(Id authenticated, Id serial, const Digest&, bool routes_ready, Clock::time_point now, + std::string& error); + bool commit(Id authenticated, Id serial, const Digest&, std::string& error); + bool acknowledge(Id authenticated, Id serial, const Digest&, std::string& error); + bool cancel(Id authenticated, Id serial, std::string reason, std::string& error); + void service(const Scope& current, bool waiting, Clock::time_point now); + void reset(); + Phase phase() const { + return phase_; + } + const std::optional& proposal() const { + return proposal_; + } + const std::string& status() const { + return status_; + } + bool can_commit() const; + bool complete() const; + bool frozen() const { + return phase_ == Phase::Committing; + } + bool ready(Id member) const; + bool acknowledged(Id member) const; + std::optional result() const; + + private: + bool expected(Id, Id serial) const; + Phase phase_ = Phase::Idle; + std::optional proposal_; + std::array prepared_{}, acknowledged_{}; + Clock::time_point deadline_{}; + Id highest_serial_ = 0; + std::string status_; +}; + +} // namespace dkr::runtime::netplay::links diff --git a/runtime-recomp/src/game/netplay/session_links/qualification.hpp b/runtime-recomp/src/game/netplay/session_links/qualification.hpp new file mode 100644 index 00000000..791dec93 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/qualification.hpp @@ -0,0 +1,106 @@ +#pragma once +#include "party_link.hpp" +#include +#include +#include + +namespace dkr::runtime::netplay::links { +// Opt-in only inside the existing disposable-profile --self-test-owned check. +// Ordinary launcher/overlay sessions never enable automatic consent. +class HandoverQualification { + bool enabled_ = false, reported_ = false; + Clock::time_point route_report_{}; + + public: + explicit HandoverQualification(bool disposable) { + const auto* value = disposable ? std::getenv("DKR_OWNED_CHECK_HANDOVER") : nullptr; + enabled_ = value && std::string_view(value) == "1"; + } + bool enabled() const { + return enabled_; + } + bool pulse(const void* session, std::string& error) { + if (!enabled_) + return true; + auto hub = dkr::runtime::spectators::party_link(session); + std::scoped_lock lock(hub->mutex); + auto& state = hub->links; + if (state.handover.phase() == Phase::Cancelled) { + error = state.handover.status(); + return false; + } + if (!hub->enabled || hub->party.snapshot().members.size() != 12) + return false; + if (Clock::now() >= route_report_ && !state.finished) { + route_report_ = Clock::now() + std::chrono::seconds(5); + std::fprintf( + stderr, + "[online][handover-check] phase=%u local=%llu registration=%u/%u prepared-state=%u bytes=%zu/%zu inventory=%u status=%s\n", + unsigned(state.handover.phase()), static_cast(hub->local), + unsigned(state.registration_started), unsigned(state.registration_ready), + unsigned(state.prepared_state), state.prepared_bytes.size(), state.expected_transfer, + unsigned(state.inventory_ready), state.status.c_str()); + if (const auto& p = state.handover.proposal()) + for (const auto& m : p->before.members) { + const auto sample = state.samples.find({hub->local, m.id}); + std::fprintf(stderr, "[online][handover-check] member=%llu prepared=%u pongs=%u age-ms=%lld\n", + static_cast(m.id), unsigned(state.handover.ready(m.id)), + sample == state.samples.end() ? 0 : sample->second.observations, + sample == state.samples.end() + ? -1 + : static_cast(std::chrono::duration_cast( + Clock::now() - sample->second.measured) + .count())); + } + } + if (state.last_applied && state.finished) { + const auto& p = state.handover.proposal(); + if (!p || state.save_owner != p->save_owner) { + error = "Host transfer changed the agreed save owner."; + return false; + } + for (const auto& before : p->before.members) { + const auto* member = hub->party.find(before.id); + if (!member || int(member->port ? *member->port : 255) != (before.port < 0 ? 255 : before.port)) { + error = "Host transfer changed a controller port."; + return false; + } + } + if (!reported_) { + reported_ = true; + std::fprintf( + stderr, + "[online][handover-check] complete members=12 ports-preserved=1 save-owner-preserved=1 host=%llu\n", + static_cast(hub->party.snapshot().host)); + } + if (hub->host && Clock::now() >= route_report_) { + route_report_ = Clock::now() + std::chrono::seconds(5); + for (const auto& m : hub->party.snapshot().members) + if (m.port && m.id != hub->local) { + const auto* peer = hub->peer(m.id); + const auto sample = state.samples.find({hub->local, m.id}); + std::fprintf( + stderr, "[online][handover-check] racer=%llu heartbeats=%u heard-ms=%lld direct-pongs=%u\n", + static_cast(m.id), peer ? peer->rtt_count : 0, + peer ? static_cast( + std::chrono::duration_cast(Clock::now() - peer->heard) + .count()) + : -1, + sample == state.samples.end() ? 0 : sample->second.observations); + } + } + return true; + } + const auto& proposal = state.handover.proposal(); + if (proposal && proposal->successor == hub->local && state.handover.phase() == Phase::Offered) + state.consent = true; + if (hub->host && !busy(state)) { + const auto target = std::find_if(hub->party.snapshot().members.begin(), hub->party.snapshot().members.end(), + [](const auto& m) { return m.port && *m.port == 1; }); + if (target != hub->party.snapshot().members.end()) + state.request = target->id; + } + return false; + } +}; +} // namespace dkr::runtime::netplay::links diff --git a/runtime-recomp/src/game/netplay/session_links/quick_join_api.inl b/runtime-recomp/src/game/netplay/session_links/quick_join_api.inl new file mode 100644 index 00000000..b9cf40f7 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/quick_join_api.inl @@ -0,0 +1,166 @@ +std::string local_peer_name() const override { + std::scoped_lock lock(mutex_); + return local_peer_id_; +} +std::string peer_name(const PeerAddress& address) const override { + std::scoped_lock lock(mutex_); + for (const auto& [id, peer] : peers_) + if (peer->address == address) { + const auto alias = peer_aliases_.find(id); + return alias == peer_aliases_.end() ? peer->remote_id : alias->second; + } + return {}; +} +std::string signal_name(std::uint64_t id, std::string_view fallback) const { + std::scoped_lock lock(mutex_); + const auto alias = peer_aliases_.find(id); + return alias == peer_aliases_.end() ? std::string(fallback) : alias->second; +} +std::size_t pinned_route_count_locked() const { + std::set ids; + for (const auto& [name, route] : pinned_routes_) + ids.insert(route.first); + return ids.size(); +} +bool introduce_peer(std::string_view name, bool initiate, PeerAddress& address, std::string& error) override { + if (name.empty() || name.size() > 128 || + name.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") != name.npos) { + error = "Invalid introduced Quick Join peer."; + return false; + } + bool exists = false; + { + std::scoped_lock lock(mutex_); + if (name == local_peer_id_ || + (authorized_remote_.size() >= 12 && !authorized_remote_.contains(std::string(name)))) { + error = "The introduced peer exceeds this lobby's limits."; + return false; + } + const std::string remote(name); + authorized_remote_.insert(remote); + auto pinned = pinned_routes_.find(remote); + if (pinned == pinned_routes_.end()) { + const auto id = next_peer_identifier_.fetch_add(1U, std::memory_order_relaxed); + pinned = pinned_routes_.emplace(remote, std::pair{id, quick_address(id)}).first; + } + address = pinned->second.second; + exists = std::any_of(peers_.begin(), peers_.end(), [&](const auto& p) { + const auto alias = peer_aliases_.find(p.first); + return (p.second->remote_id == name || (alias != peer_aliases_.end() && alias->second == name)) && + p.second->current.load() && + (p.second->route_ready.load() || + std::chrono::steady_clock::now() - p.second->created < std::chrono::seconds(10)); + }); + } + if (initiate && !exists) { + try { + create_offer(std::string(name)); + } catch (...) { + error = "The direct peer route could not be prepared."; + return false; + } + } + error.clear(); + return true; +} +bool prepare_host(std::string bootstrap, std::string& error) override { + if (host_) { + error = "This player is already hosting."; + return false; + } + preparing_host_.store(true); + if (!rekey_quick_join(std::move(bootstrap), error)) { + preparing_host_.store(false); + return false; + } + return true; +} +bool alias_peer(const PeerAddress& address, std::string_view name, std::string& error) override { + if (name.empty() || name.size() > 128 || + name.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") != name.npos) { + error = "Invalid introduced peer alias."; + return false; + } + std::scoped_lock lock(mutex_); + for (const auto& [id, peer] : peers_) + if (peer->address == address) { + if (const auto pinned = pinned_routes_.find(std::string(name)); + pinned != pinned_routes_.end() && pinned->second.first != id) { + error = "That peer name belongs to another lobby route."; + return false; + } + authorized_remote_.erase(peer->remote_id); + if (const auto prior = peer_aliases_.find(id); prior != peer_aliases_.end()) { + authorized_remote_.erase(prior->second); + if (prior->second != peer->remote_id) + pinned_routes_.erase(prior->second); + remote_to_identifier_.erase(prior->second + "\n" + peer->connection_id); + } + const std::string alias(name); + peer_aliases_[id] = alias; + authorized_remote_.insert(alias); + pinned_routes_[alias] = {id, address}; + remote_to_identifier_[alias + "\n" + peer->connection_id] = id; + error.clear(); + return true; + } + // Admission can reserve a route before ICE creates its Peer. A quiet + // successor registration may replace that name in the meantime. + // Preserve the authenticated logical address and move its reservation; + // waiting for a connection to the retired name cannot make progress. + const auto reserved = std::find_if(pinned_routes_.begin(), pinned_routes_.end(), + [&](const auto& p) { return p.second.second == address; }); + if (reserved != pinned_routes_.end()) { + const auto id = reserved->second.first; + const std::string alias(name); + if (const auto collision = pinned_routes_.find(alias); + collision != pinned_routes_.end() && collision->second.first != id) { + error = "That peer name belongs to another lobby route."; + return false; + } + for (auto it = pinned_routes_.begin(); it != pinned_routes_.end();) { + if (it->second.first == id) { + authorized_remote_.erase(it->first); + it = pinned_routes_.erase(it); + } else + ++it; + } + std::erase_if(remote_to_identifier_, [&](const auto& p) { return p.second == id; }); + peer_aliases_[id] = alias; + authorized_remote_.insert(alias); + pinned_routes_[alias] = {id, address}; + error.clear(); + return true; + } + error = "The introduced route is no longer available."; + return false; +} +bool apply_host_role(bool host, std::string_view remote, std::string& error) override { + std::scoped_lock lock(mutex_); + if (host && (!preparing_host_.load() || rekey_state_.load() != QuickJoinRekeyStatus::Committed)) { + error = "The successor's Quick Join registration is not ready."; + return false; + } + if (!host) { + const auto route = std::find_if(peers_.begin(), peers_.end(), [&](const auto& p) { + const auto alias = peer_aliases_.find(p.first); + return (p.second->remote_id == remote || (alias != peer_aliases_.end() && alias->second == remote)) && + p.second->route_ready.load(); + }); + if (route == peers_.end()) { + error = "The successor's connection is not ready."; + return false; + } + remote_host_id_ = std::string(remote); + } + for (const auto& [id, peer] : peers_) { + const auto alias = peer_aliases_.find(id); + const auto& name = alias == peer_aliases_.end() ? peer->remote_id : alias->second; + peer->authority_route.store(!host && name == remote, std::memory_order_release); + } + host_ = host; + preparing_host_.store(false); + route_retry_requested_.store(false); + error.clear(); + return true; +} diff --git a/runtime-recomp/src/game/netplay/session_links/quick_join_state.inl b/runtime-recomp/src/game/netplay/session_links/quick_join_state.inl new file mode 100644 index 00000000..b288896d --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/quick_join_state.inl @@ -0,0 +1,3 @@ +std::atomic host_{false}, preparing_host_{false}; +std::set authorized_remote_; +std::map peer_aliases_; diff --git a/runtime-recomp/src/game/netplay/session_links/registry.cpp b/runtime-recomp/src/game/netplay/session_links/registry.cpp new file mode 100644 index 00000000..f0fed6eb --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/registry.cpp @@ -0,0 +1,99 @@ +#include "registry.hpp" +#include +#include +#include + +namespace dkr::runtime::netplay::links { +namespace { +struct Remote { + std::uint64_t room; + PeerAddress address; + secure::Key key; +}; +struct Registry { + std::mutex mutex; + std::map> sessions; +}; +Registry& registry() { + static auto* const value = new Registry; + return *value; +} +void wipe(Remote& remote) { + volatile std::uint8_t* p = remote.key.data(); + for (unsigned i = 0; i < remote.key.size(); ++i) + p[i] = 0; +} +} // namespace +bool install(const void* owner, std::uint64_t room, std::uint64_t peer, const PeerAddress& address, + const secure::Key& key) { + if (!owner || !room || !peer || !address || std::all_of(key.begin(), key.end(), [](auto c) { return c == 0; })) + return false; + auto& r = registry(); + std::scoped_lock lock(r.mutex); + auto& peers = r.sessions[owner]; + if (peers.size() >= 11 && !peers.contains(peer)) + return false; + if (auto old = peers.find(peer); old != peers.end()) { + if (old->second.room == room && old->second.address == address && old->second.key == key) + return true; + wipe(old->second); + } + peers.insert_or_assign(peer, Remote{room, address, key}); + return true; +} +std::optional receive_key(const void* owner, std::uint64_t room, std::uint64_t peer, + const PeerAddress& address) { + auto& r = registry(); + std::scoped_lock lock(r.mutex); + const auto session = r.sessions.find(owner); + if (session == r.sessions.end()) + return {}; + const auto remote = session->second.find(peer); + if (remote == session->second.end() || remote->second.room != room || remote->second.address != address) + return {}; + return remote->second.key; +} +void revoke(const void* owner, std::uint64_t peer) { + auto& r = registry(); + std::scoped_lock lock(r.mutex); + const auto session = r.sessions.find(owner); + if (session == r.sessions.end()) + return; + const auto remote = session->second.find(peer); + if (remote != session->second.end()) { + wipe(remote->second); + session->second.erase(remote); + } + if (session->second.empty()) + r.sessions.erase(session); +} +void forget(const void* owner) { + auto& r = registry(); + std::scoped_lock lock(r.mutex); + const auto session = r.sessions.find(owner); + if (session == r.sessions.end()) + return; + for (auto& [id, remote] : session->second) + wipe(remote); + r.sessions.erase(session); +} +bool retire_route(const void* owner, std::uint64_t room, const PeerAddress& address) { + auto& r = registry(); + std::scoped_lock lock(r.mutex); + const auto session = r.sessions.find(owner); + if (session == r.sessions.end()) + return false; + bool removed = false; + for (auto it = session->second.begin(); it != session->second.end();) { + if (it->second.room == room && it->second.address == address) { + wipe(it->second); + it = session->second.erase(it); + removed = true; + } else + ++it; + } + if (session->second.empty()) + r.sessions.erase(session); + return removed; +} +} // namespace dkr::runtime::netplay::links diff --git a/runtime-recomp/src/game/netplay/session_links/registry.hpp b/runtime-recomp/src/game/netplay/session_links/registry.hpp new file mode 100644 index 00000000..3b108911 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/registry.hpp @@ -0,0 +1,15 @@ +#pragma once +#include "netplay/datagram_socket.hpp" +#include "netplay/secure_channel.hpp" +#include + +namespace dkr::runtime::netplay::links { +// Installed only by the native owner after an authenticated host introduction. +// This key grants no host privileges; the party decoder still checks message +// kind, current controller owner and immutable input lease after AEAD validation. +bool install(const void* session, std::uint64_t room, std::uint64_t peer, const PeerAddress&, const secure::Key&); +std::optional receive_key(const void* session, std::uint64_t room, std::uint64_t peer, const PeerAddress&); +void revoke(const void* session, std::uint64_t peer); +bool retire_route(const void* session, std::uint64_t room, const PeerAddress&); +void forget(const void* session); +} // namespace dkr::runtime::netplay::links diff --git a/runtime-recomp/src/game/netplay/session_links/state.hpp b/runtime-recomp/src/game/netplay/session_links/state.hpp new file mode 100644 index 00000000..cbac8784 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/state.hpp @@ -0,0 +1,183 @@ +#pragma once +#include "policy.hpp" +#include "transfer.hpp" +#include +#include +#include + +namespace dkr::runtime::netplay::links { +// Version 2 transfers the authenticated architecture inventory. Older local +// playtests retain the ordinary host route and cannot enter this handover. +inline constexpr std::uint8_t ProtocolVersion = 2; +enum class Kind : std::uint8_t { + Hello = 1, + Introduce, + Ping, + Pong, + Report, + Offer, + Accept, + Prepare, + Prepared, + Commit, + Acknowledge, + Release, + Cancel, + Registration, + SaveChunk, + SaveReceipt, + Activated, + Finished, + Inventory +}; +struct Packet { + Kind kind = Kind::Hello; + Id room = 0, generation = 0; + std::vector body; +}; +inline std::vector encode(const Packet& value) { + if (!value.room || !value.generation || value.body.size() > 11500) + return {}; + std::vector result{'D', 'K', 'R', 'X', 1, 7, std::uint8_t(value.kind)}; + for (const auto v : {value.room, value.generation}) + for (unsigned i = 0; i < 8; ++i) + result.push_back(std::uint8_t(v >> (i * 8))); + result.insert(result.end(), value.body.begin(), value.body.end()); + return result; +} +inline bool decode(std::span bytes, Packet& value) { + constexpr std::array magic{'D', 'K', 'R', 'X', 1, 7}; + if (bytes.size() < 23 || bytes.size() > 11523 || !std::equal(magic.begin(), magic.end(), bytes.begin()) || + bytes[6] < 1 || bytes[6] > unsigned(Kind::Inventory)) + return false; + value = {}; + value.kind = Kind(bytes[6]); + for (unsigned i = 0; i < 8; ++i) { + value.room |= Id(bytes[7 + i]) << (8 * i); + value.generation |= Id(bytes[15 + i]) << (8 * i); + } + value.body.assign(bytes.begin() + 23, bytes.end()); + return value.room && value.generation; +} +struct Write { + std::vector bytes; + Write& number(Id value, unsigned size = 8) { + for (unsigned i = 0; i < size; ++i) + bytes.push_back(std::uint8_t(value >> (8 * i))); + return *this; + } + Write& data(std::span value) { + bytes.insert(bytes.end(), value.begin(), value.end()); + return *this; + } + Write& text(std::string_view value) { + number(value.size(), 2); + bytes.insert(bytes.end(), value.begin(), value.end()); + return *this; + } +}; +struct Read { + std::span bytes; + std::size_t at = 0; + bool good = true; + Id number(unsigned size = 8) { + if (size > 8 || at > bytes.size() || size > bytes.size() - at) { + good = false; + return 0; + } + Id value = 0; + for (unsigned i = 0; i < size; ++i) + value |= Id(bytes[at++]) << (8 * i); + return value; + } + std::vector data(std::size_t size) { + if (at > bytes.size() || size > bytes.size() - at) { + good = false; + return {}; + } + std::vector result(bytes.begin() + at, bytes.begin() + at + size); + at += size; + return result; + } + std::string text(std::size_t maximum = 128) { + const auto size = number(2); + if (size > maximum) { + good = false; + return {}; + } + const auto value = data(size); + return {value.begin(), value.end()}; + } + bool done() const { + return good && at == bytes.size(); + } +}; +struct Incoming { + Id source; + Packet packet; +}; +struct Introduction { + Id remote = 0; + secure::Key key{}; + std::string endpoint; + Clock::time_point issued{}; +}; +struct State { + Scope scope; + std::set capable; + std::map keys; + std::map introduced; + std::set live_routes; + std::map samples; + std::map capacity; + std::map architectures; + std::map> pings; + std::map> rtts; + std::map last_probe; + std::map> probe_results; + std::deque incoming; + Handover handover; + Id save_owner = 0, request = 0, last_applied = 0, serial = 0; + std::optional consent; + std::optional local_consent; + bool cancel = false; + bool registration_started = false, registration_ready = false, prepared_state = false, released = false, + finished = false; + secure::KeyPair successor_keys{}; + secure::Key successor_capability{}, successor_public{}; + std::string successor_endpoint, successor_invite; + std::set activated; + std::vector prepared_bytes, save_paks, save_records; + TransferBuffer assembly; + TransferBuffer inventory_assembly; + std::vector inventory_bytes; + Digest inventory_hash{}; + std::map pending_keys; + bool inventory_ready = false; + std::map transfer_offsets; + std::size_t expected_transfer = 0; + Clock::time_point finished_until{}; + bool directory_required = false, directory_public = false, directory_accepted = false, directory_committed = false; + bool mod_requested = false, mod_ready = false; + std::string directory_code; + Clock::time_point directory_send{}; + Clock::time_point transfer_send{}; + Clock::time_point hello{}, introduce{}, probe{}, report{}; + std::string status; + bool receive(Id source, std::span bytes) { + Packet packet; + if (incoming.size() >= 96 || !decode(bytes, packet)) + return false; + incoming.push_back({source, std::move(packet)}); + return true; + } + void reset() { + *this = State{}; + } +}; +inline bool busy(const State& state) { + const auto phase = state.handover.phase(); + return phase == Phase::Offered || phase == Phase::Preparing || phase == Phase::Committing || + (phase == Phase::Committed && !state.finished); +} +} // namespace dkr::runtime::netplay::links diff --git a/runtime-recomp/src/game/netplay/session_links/transfer.hpp b/runtime-recomp/src/game/netplay/session_links/transfer.hpp new file mode 100644 index 00000000..93bfdbb1 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/transfer.hpp @@ -0,0 +1,35 @@ +#pragma once +#include "policy.hpp" +#include + +namespace dkr::runtime::netplay::links { +// Waiting-room transfers are bounded independently of racing input queues. +// No file paths, private host key or account credentials enter this bundle. +inline constexpr std::size_t MaximumTransferBytes = 1024 * 1024, TransferChunk = 640; +struct TransferBuffer { + std::vector bytes; + std::vector received; + Id serial = 0; + bool accept(Id token, std::size_t total, std::size_t offset, std::span chunk) { + if (!token || !total || total > MaximumTransferBytes || offset % TransferChunk || offset >= total || + chunk.size() != std::min(TransferChunk, total - offset)) + return false; + if (serial != token) { + serial = token; + bytes.assign(total, 0); + received.assign((total + TransferChunk - 1) / TransferChunk, false); + } + if (bytes.size() != total) + return false; + const auto slot = offset / TransferChunk; + if (received[slot]) + return std::equal(chunk.begin(), chunk.end(), bytes.begin() + offset); + std::copy(chunk.begin(), chunk.end(), bytes.begin() + offset); + received[slot] = true; + return true; + } + bool complete() const { + return !received.empty() && std::all_of(received.begin(), received.end(), [](bool v) { return v; }); + } +}; +} // namespace dkr::runtime::netplay::links diff --git a/runtime-recomp/src/game/netplay/session_links/transport.cpp b/runtime-recomp/src/game/netplay/session_links/transport.cpp new file mode 100644 index 00000000..5773085b --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/transport.cpp @@ -0,0 +1,73 @@ +#include "transport.hpp" +#include "netplay/session_transport.hpp" +#include + +namespace dkr::runtime::netplay::links { +std::string local_peer_name(const SessionTransport& transport) { + if (const auto* native = dynamic_cast(&transport)) + return native->local_peer_name(); + return {}; +} +std::string peer_name(const SessionTransport& transport, const PeerAddress& address) { + if (const auto* native = dynamic_cast(&transport)) + return native->peer_name(address); + return transport.quick_join() ? std::string{} : DatagramSocket::describe(address); +} +bool introduce_peer(SessionTransport& transport, std::string_view endpoint, bool initiate, PeerAddress& address, + std::string& error) { + if (auto* native = dynamic_cast(&transport)) + return native->introduce_peer(endpoint, initiate, address, error); + if (transport.quick_join()) { + error = "This transport does not support introduced peers."; + return false; + } + const auto colon = endpoint.rfind(':'); + if (colon == endpoint.npos) { + error = "Invalid introduced endpoint."; + return false; + } + unsigned port = 0; + for (const auto c : endpoint.substr(colon + 1)) { + if (c < '0' || c > '9' || port > 6553) { + error = "Invalid introduced port."; + return false; + } + port = port * 10 + unsigned(c - '0'); + } + if (!port || port > 65535) { + error = "Invalid introduced port."; + return false; + } + return DatagramSocket::resolve(endpoint.substr(0, colon), std::uint16_t(port), address, error); +} +bool prepare_host(SessionTransport& transport, std::string bootstrap, std::string& error) { + if (auto* native = dynamic_cast(&transport)) + return native->prepare_host(std::move(bootstrap), error); + if (!transport.quick_join() && transport.is_open()) { + error.clear(); + return true; + } + error = "This transport cannot prepare a host handover."; + return false; +} +bool alias_peer(SessionTransport& transport, const PeerAddress& address, std::string_view name, std::string& error) { + if (auto* native = dynamic_cast(&transport)) + return native->alias_peer(address, name, error); + if (!transport.quick_join()) { + error.clear(); + return true; + } + error = "This transport cannot prepare a peer alias."; + return false; +} +bool apply_host_role(SessionTransport& transport, bool host, std::string_view remote, std::string& error) { + if (auto* native = dynamic_cast(&transport)) + return native->apply_host_role(host, remote, error); + if (!transport.quick_join()) { + error.clear(); + return true; + } + error = "This transport cannot transfer host ownership."; + return false; +} +} // namespace dkr::runtime::netplay::links diff --git a/runtime-recomp/src/game/netplay/session_links/transport.hpp b/runtime-recomp/src/game/netplay/session_links/transport.hpp new file mode 100644 index 00000000..11a52ab2 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/transport.hpp @@ -0,0 +1,28 @@ +#pragma once +#include +#include + +namespace dkr::runtime::netplay { +class SessionTransport; +struct PeerAddress; +namespace links { +// Optional first-party interface. The frozen SessionTransport ABI is intact. +// Only the authenticated native owner may introduce routes or change roles. +class IntroducedTransport { + public: + virtual ~IntroducedTransport() = default; + virtual std::string local_peer_name() const = 0; + virtual std::string peer_name(const PeerAddress&) const = 0; + virtual bool introduce_peer(std::string_view, bool, PeerAddress&, std::string&) = 0; + virtual bool prepare_host(std::string, std::string&) = 0; + virtual bool alias_peer(const PeerAddress&, std::string_view, std::string&) = 0; + virtual bool apply_host_role(bool, std::string_view, std::string&) = 0; +}; +std::string local_peer_name(const SessionTransport&); +std::string peer_name(const SessionTransport&, const PeerAddress&); +bool introduce_peer(SessionTransport&, std::string_view, bool, PeerAddress&, std::string&); +bool prepare_host(SessionTransport&, std::string, std::string&); +bool alias_peer(SessionTransport&, const PeerAddress&, std::string_view, std::string&); +bool apply_host_role(SessionTransport&, bool, std::string_view, std::string&); +} // namespace links +} // namespace dkr::runtime::netplay diff --git a/runtime-recomp/src/game/online_directory.cpp b/runtime-recomp/src/game/online_directory.cpp index 640a232b..676fa559 100644 --- a/runtime-recomp/src/game/online_directory.cpp +++ b/runtime-recomp/src/game/online_directory.cpp @@ -185,6 +185,8 @@ void run(std::stop_token stop) { std::uint64_t host_revision = 0; auto changed_at = Clock::time_point{}, social_at = Clock::time_point{}; std::string social_context; + std::string retired_host_epoch; + auto pending_host_until = Clock::time_point{}; while (!stop.stop_requested()) { AccountView account; AccountRequest request; @@ -313,6 +315,7 @@ void run(std::stop_token stop) { s.ui.feature_enabled = true; s.ui.running_spectators = capabilities.value("runningSpectators", false); s.ui.social_profiles = capabilities.value("socialProfiles", false); + s.ui.host_handover = capabilities.value("hostHandover", false); s.ui.status = "Connecting to DKR-R Online..."; s.update(); } @@ -409,6 +412,28 @@ void run(std::stop_token stop) { s.social_requests.erase(found); } } + if (operation == "transfer_prepare" || operation == "transfer_accept" || + operation == "transfer_commit") { + const auto data = item.value("data", Json::object()); + std::lock_guard lock(s.bridge_mutex); + for (auto& [owner, bridge] : s.bridges) { + std::lock_guard own(bridge->mutex); + if (bridge->commands.size() < 32) + bridge->commands.push_back({{"type", "host_transfer_result"}, + {"operation", operation}, + {"ok", item.value("ok", false)}, + {"data", data}, + {"error", item.value("error", Json::object())}}); + } + if (operation == "transfer_commit" && item.value("ok", false)) { + retired_host_epoch = string(data, "epoch", 80); + host_id.clear(); + host_epoch.clear(); + last_state.clear(); + host_revision = 0; + } + continue; + } if (operation == "social") { std::vector members; const auto data = item.value("data", Json::object()); @@ -484,6 +509,17 @@ void run(std::stop_token stop) { s.outbox.push_back({{"type", "cancel"}, {"id", string(data, "id", 80)}}); } } + } else if (type == "host_transferred") { + host_id = string(item, "id", 80); + host_epoch = string(item, "epoch", 80); + host_revision = item.value("revision", std::uint64_t(0)); + last_state.clear(); + pending_host_until = now + std::chrono::seconds(120); + { + std::lock_guard lock(s.mutex); + s.ui.public_desired = string(item, "visibility") == "public" && !s.ui.hidden; + s.update(); + } } else if (type == "intent" || type == "revoke") { std::lock_guard lock(s.bridge_mutex); for (auto& [owner, bridge] : s.bridges) { @@ -553,6 +589,7 @@ void run(std::stop_token stop) { social_at = now + std::chrono::seconds(5); } if (!host.is_null()) { + pending_host_until = {}; host.erase("host"); const auto epoch = string(host, "epoch", 80), serialized = host.dump(); bool updating; @@ -561,7 +598,7 @@ void run(std::stop_token stop) { updating = std::any_of(s.pending.begin(), s.pending.end(), [](const auto& p) { return p.second == "room"; }); } - if (!updating && serialized != last_state && now >= changed_at) { + if (epoch != retired_host_epoch && !updating && serialized != last_state && now >= changed_at) { send(s, {{"type", "room"}, {"revision", epoch == host_epoch ? host_revision : 0}, {"state", host}}); @@ -571,7 +608,7 @@ void run(std::stop_token stop) { s.ui.updating = true; s.update(); } - } else if (!host_id.empty()) { + } else if (!host_id.empty() && now >= pending_host_until) { send(s, {{"type", "close"}}); host_id.clear(); host_epoch.clear(); diff --git a/runtime-recomp/src/game/online_directory.hpp b/runtime-recomp/src/game/online_directory.hpp index c0acb6fd..286ab3ff 100644 --- a/runtime-recomp/src/game/online_directory.hpp +++ b/runtime-recomp/src/game/online_directory.hpp @@ -49,6 +49,7 @@ struct View { std::vector rooms; std::vector members; bool social_profiles = false; + bool host_handover = false; }; std::shared_ptr view(); void connect(bool enabled); diff --git a/runtime-recomp/src/game/online_nameplates_rt64.cpp b/runtime-recomp/src/game/online_nameplates_rt64.cpp index 02e070d0..d0ddca1f 100644 --- a/runtime-recomp/src/game/online_nameplates_rt64.cpp +++ b/runtime-recomp/src/game/online_nameplates_rt64.cpp @@ -4,6 +4,7 @@ #include "local_scenery_policy.hpp" #include "generated/selawik_font.h" #include "presentation_identity.hpp" +#include "time_trial/session.hpp" #include "gbi/rt64_gbi_rdp.h" #define STBTT_STATIC #define STB_TRUETYPE_IMPLEMENTATION @@ -56,6 +57,10 @@ struct Nameplates::Impl { std::array names{}; std::array, 4> named{}; std::array position{}; + std::string ghost_name; + Label ghost{}; + Label ghost_outline{}; + bool outline = false; std::vector pixels; Plan plan; std::uint32_t scene = 0; @@ -65,6 +70,8 @@ struct Nameplates::Impl { float left, top, right, bottom; }; std::array boxes{}; + void draw_label(RT64::State&, const Label&, const hlslpp::float4x4&, IdentitySelector, float x, float y, float z, + float object_scale, float opacity, unsigned owner); Label raster(const stbtt_fontinfo& font, std::string_view text) { constexpr unsigned Width = 512; std::array alpha{}; @@ -137,6 +144,9 @@ void Nameplates::prepare(const Session& session, const Plan& plan, std::span decoder, + std::uint32_t scene) noexcept { + auto& p = *impl_; + p.plan = {}; + p.scene = scene ^ 0x47484F53U; + p.ready = false; + if ((name.empty() && !outline) || decoder.size() < kLabelTextureEnd) + return; + try { + if (p.ghost_name != name || p.outline != outline || p.pixels.empty()) { + p.built = false; + p.ghost_name.clear(); + p.pixels.clear(); + stbtt_fontinfo font{}; + if (!stbtt_InitFont(&font, reinterpret_cast(dkr_selawik_semibold_font), 0)) + return; + p.ghost = name.empty() ? Label{} : p.raster(font, name); + p.ghost_outline = outline ? p.raster(font, "<>") : Label{}; + p.ghost_name = name; + p.outline = outline; + } + if (!p.ghost.tiles && !p.ghost_outline.tiles) + return; + std::memcpy(decoder.data() + kLabelTextureBegin, p.pixels.data(), p.pixels.size()); + p.ready = true; + } catch (...) { + // Ghost names are optional, including when texture allocation fails. + } +} void Nameplates::begin_view(unsigned view) { impl_->view = view; impl_->occupied = 0; @@ -175,14 +214,31 @@ void Nameplates::draw(RT64::State& s, const dkr_owned_draw_event& e, const hlslp if (!p.ready || !select || e.token != p.view || owner == p.view || owner >= 4 || rank < 1 || rank > 8 || (p.plan.focus && p.view != p.plan.owner) || !dkr_owned_draw_event_valid(&e)) return; + const auto& label = p.plan.labels == Labels::NameAndPosition ? p.named[owner][rank - 1] : p.position[rank - 1]; + p.draw_label(s, label, camera, select, std::bit_cast(e.parameters[2]), std::bit_cast(e.parameters[3]), + std::bit_cast(e.parameters[4]), std::bit_cast(e.parameters[5]), 1.F, owner); +} +void Nameplates::draw_ghost(RT64::State& s, const time_trial::GhostNameplate& ghost, const hlslpp::float4x4& camera, + IdentitySelector select) { + auto& p = *impl_; + if (!p.ready || !select) + return; + if (ghost.outline) + p.draw_label(s, p.ghost_outline, camera, select, ghost.position[0], ghost.position[1], ghost.position[2], + ghost.scale, ghost.opacity, 1); + p.draw_label(s, p.ghost, camera, select, ghost.position[0], ghost.position[1], ghost.position[2], ghost.scale, + ghost.opacity, 0); +} +void Nameplates::Impl::draw_label(RT64::State& s, const Label& label, const hlslpp::float4x4& camera, + IdentitySelector select, float x, float y, float z, float object_scale, float opacity, + unsigned owner) { + if (!label.tiles) + return; auto& rsp = *s.rsp; auto& rdp = *s.rdp; if (rdp.colorCombinerStackSize >= RDP_EXTENDED_STACK_SIZE || rdp.primColorStackSize >= RDP_EXTENDED_STACK_SIZE || rdp.envColorStackSize >= RDP_EXTENDED_STACK_SIZE) return; - const float x = std::bit_cast(e.parameters[2]), y = std::bit_cast(e.parameters[3]), - z = std::bit_cast(e.parameters[4]); - const float object_scale = std::bit_cast(e.parameters[5]); if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z) || !std::isfinite(object_scale) || std::abs(x) > 32768 || std::abs(y) > 32768 || std::abs(z) > 32768 || object_scale <= 0 || object_scale > 64) return; @@ -194,13 +250,10 @@ void Nameplates::draw(RT64::State& s, const dkr_owned_draw_event& e, const hlslp if (!std::isfinite(nx) || !std::isfinite(ny) || !std::isfinite(nz) || std::abs(nx) > 4 || std::abs(ny) > 1.15F || nz < 0 || nz > 1) return; - const auto& label = p.plan.labels == Labels::NameAndPosition ? p.named[owner][rank - 1] : p.position[rank - 1]; - if (!label.tiles) - return; const auto& viewport = rsp.viewportStack[rsp.viewportStackSize - 1]; if (std::abs(float(viewport.scale.x)) < 1 || std::abs(float(viewport.scale.y)) < 1) return; - const float pixel_scale = 4.5F * float(p.plan.label_size) * .01F / FontHeight; + const float pixel_scale = 4.5F * float(plan.label_size) * .01F / FontHeight; const float half_width = float(label.width) * pixel_scale * .5F; const float screen_x = nx * float(viewport.scale.x) + float(viewport.translate.x); float screen_y = -ny * float(viewport.scale.y) + float(viewport.translate.y) - float(Height) * pixel_scale; @@ -208,8 +261,8 @@ void Nameplates::draw(RT64::State& s, const dkr_owned_draw_event& e, const hlslp // Bounded local placement, not a change to the actor's transform or rank. for (unsigned attempt = 0; attempt < 4; ++attempt) { bool overlap = false; - for (unsigned i = 0; i < p.occupied; ++i) { - const auto& b = p.boxes[i]; + for (unsigned i = 0; i < occupied; ++i) { + const auto& b = boxes[i]; overlap |= screen_x + half_width > b.left && screen_x - half_width < b.right && screen_y + height > b.top && screen_y < b.bottom; } @@ -217,10 +270,10 @@ void Nameplates::draw(RT64::State& s, const dkr_owned_draw_event& e, const hlslp break; screen_y -= height + 1; } - if (p.occupied < p.boxes.size()) - p.boxes[p.occupied++] = {screen_x - half_width, screen_y, screen_x + half_width, screen_y + height}; + if (occupied < boxes.size()) + boxes[occupied++] = {screen_x - half_width, screen_y, screen_x + half_width, screen_y + height}; anchor.y = (float(viewport.translate.y) - screen_y) / float(viewport.scale.y) * w; - const auto alpha = std::uint32_t(std::clamp((6000.F - w) / 1000.F, 0.F, 1.F) * 255.F); + const auto alpha = std::uint32_t(std::clamp((6000.F - w) / 1000.F, 0.F, 1.F) * opacity * 255.F); if (!alpha) return; NativeDrawScope restore(s); @@ -236,8 +289,8 @@ void Nameplates::draw(RT64::State& s, const dkr_owned_draw_event& e, const hlslp billboard[3] = anchor; // Native scenery owns placement bytes 1..128. Labels use 241..244, // retaining the native high bit and never matching canonical game draws. - select(rsp, local_scenery::native_identity(presentation::normalise_identity(p.scene ^ 0x4E414D45U), 0xF0U + owner, - p.view)); + select(rsp, + local_scenery::native_identity(presentation::normalise_identity(scene ^ 0x4E414D45U), 0xF0U + owner, view)); rsp.modelMatrixStack[2] = billboard; rsp.modelMatrixStackSize = 3; rsp.modelMatrixPhysicalAddressStack[2] = rsp.modelMatrixSegmentedAddressStack[2] = local_scenery::kVertexScratch; diff --git a/runtime-recomp/src/game/online_nameplates_rt64.hpp b/runtime-recomp/src/game/online_nameplates_rt64.hpp index 370da85c..7332428c 100644 --- a/runtime-recomp/src/game/online_nameplates_rt64.hpp +++ b/runtime-recomp/src/game/online_nameplates_rt64.hpp @@ -6,6 +6,9 @@ namespace RT64 { struct State; struct RSP; } // namespace RT64 +namespace dkr::runtime::time_trial { +struct GhostNameplate; +} namespace dkr::runtime::online_view { inline constexpr std::uint32_t kLabelTextureBegin = 0x00D00000U, kLabelTextureEnd = 0x00E00000U; class Nameplates final { @@ -14,8 +17,10 @@ class Nameplates final { Nameplates(); ~Nameplates(); void prepare(const Session&, const Plan&, std::span, std::uint32_t scene) noexcept; + void prepare_ghost(std::string_view, bool outline, std::span, std::uint32_t scene) noexcept; void begin_view(unsigned view); void draw(RT64::State&, const dkr_owned_draw_event&, const hlslpp::float4x4& camera, IdentitySelector); + void draw_ghost(RT64::State&, const time_trial::GhostNameplate&, const hlslpp::float4x4& camera, IdentitySelector); private: struct Impl; diff --git a/runtime-recomp/src/game/online_presentation/correction_lifetime.hpp b/runtime-recomp/src/game/online_presentation/correction_lifetime.hpp new file mode 100644 index 00000000..440ff613 --- /dev/null +++ b/runtime-recomp/src/game/online_presentation/correction_lifetime.hpp @@ -0,0 +1,42 @@ +#pragma once +#include +#include +#include + +namespace dkr::runtime::netplay::experimental { +// Accessed under SubmissionDomain::mutex. Weak records do not retain image RAM +// or acquire a final strong reference whose destructor takes that same mutex. +template class CorrectionLifetime final { + struct Entry { + std::weak_ptr image; + const Image* address = nullptr; + std::uint32_t frame = 0; + bool allowed = false; + }; + std::array entries_{}; + + public: + void reset() { + entries_ = {}; + } + bool publish(const std::shared_ptr& image) { + for (auto& entry : entries_) + if (entry.image.expired()) { + entry = {image, image.get(), image->descriptor().frame, true}; + return true; + } + return false; + } + bool eligible(const Image* image) const { + for (const auto& entry : entries_) + if (entry.address == image && !entry.image.expired()) + return entry.allowed; + return false; + } + void retire(std::uint32_t first, bool correction) { + for (auto& entry : entries_) + if (!entry.image.expired() && (!correction || entry.frame >= first)) + entry.allowed = false; + } +}; +} // namespace dkr::runtime::netplay::experimental diff --git a/runtime-recomp/src/game/online_stability/host_settings_service.inl b/runtime-recomp/src/game/online_stability/host_settings_service.inl index f320e2d4..e4bfafe9 100644 --- a/runtime-recomp/src/game/online_stability/host_settings_service.inl +++ b/runtime-recomp/src/game/online_stability/host_settings_service.inl @@ -14,8 +14,9 @@ stability::HostSettingsContext context; context.spectator_capable = party->enabled; context.playing = bool(party->launch) || state_ == ConnectionState::Running || state_ == ConnectionState::Loading; - context.transition = party->stopping || party->returned || state_ == ConnectionState::Loading || - launch_countdown_active_ || (!context.playing && lobby_.room().phase != RoomPhase::Waiting); + context.transition = party->stopping || party->returned || dkr::runtime::netplay::links::busy(party->links) || + state_ == ConnectionState::Loading || launch_countdown_active_ || + (!context.playing && lobby_.room().phase != RoomPhase::Waiting); context.occupied_ports = 1; if (party->enabled) { for (const auto& member : party->party.snapshot().members) diff --git a/runtime-recomp/src/game/online_stability/live_delay.cpp b/runtime-recomp/src/game/online_stability/live_delay.cpp index 6e3e64e3..62f40e33 100644 --- a/runtime-recomp/src/game/online_stability/live_delay.cpp +++ b/runtime-recomp/src/game/online_stability/live_delay.cpp @@ -189,7 +189,7 @@ void LiveDelay::send(Member target, DelayMessage m) { m.room = room_; m.epoch = epoch_; m.controls = controls_; - m.frame = m.kind == DelayKind::Hello ? clock_frontier_ : frame_; + m.frame = (m.kind == DelayKind::Hello || m.kind == DelayKind::Report) ? clock_frontier_ : frame_; (void)control_->send(target, encode(m)); } void LiveDelay::apply(unsigned value, Clock::time_point now) { @@ -204,6 +204,14 @@ void LiveDelay::apply(unsigned value, Clock::time_point now) { current_ = value; applied_at_ = now; } +void LiveDelay::record_report(Member source, const DelayMessage& message, Clock::time_point now) { + auto& report = reports_[source]; + if (now < report.at || now - report.at > std::chrono::seconds(2)) + report.cost = {}; + report.cost.observe(message.frame, message.work_us, message.replay_us, message.interval_us); + report.message = message; + report.at = now; +} void LiveDelay::receive(const Identity& id, Member source, const DelayMessage& m, Clock::time_point now) { if (m.room != room_ || m.epoch != epoch_ || m.controls != controls_ || !id.dynamic) return; @@ -231,7 +239,7 @@ void LiveDelay::receive(const Identity& id, Member source, const DelayMessage& m return; const auto previous = reports_.find(source); if (m.sequence && (previous == reports_.end() || m.sequence > previous->second.message.sequence)) - reports_[source] = {m, now}; + record_report(source, m, now); } return; } @@ -436,8 +444,8 @@ void LiveDelay::pulse(std::uint64_t epoch, std::uint64_t controls, std::uint32_t report.room = room_; report.epoch = epoch_; report.controls = controls_; - report.frame = frame_; - reports_[id.local] = {report, now}; + report.frame = clock_frontier_; + record_report(id.local, report, now); } else send(id.host, report); late_ = waits_ = samples_ = 0; @@ -491,6 +499,8 @@ void LiveDelay::pulse(std::uint64_t epoch, std::uint64_t controls, std::uint32_t if (m.interval_us >= 100000 && std::uint64_t(m.work_us) * 2 > m.interval_us && std::uint64_t(m.replay_us) * 10 > m.interval_us) busy = true; + pressure |= found->second.cost.pressure(m.owner_late[owner], m.replay_us); + busy |= found->second.cost.busy(m.owner_late[owner], m.replay_us); } auto [policy, inserted] = policies_.try_emplace(member); if (inserted) @@ -568,12 +578,13 @@ void LiveDelay::arrival(unsigned owner, std::uint32_t frame, bool repair) { if (repair) return; samples_ = std::min(255U, samples_ + 1); + // Replaying old ticks cannot make a fresh late arrival appear on time. + const auto late = frame < clock_frontier_ ? std::min(48U, clock_frontier_ - frame) : 0; if (owner_samples_[owner] < 255) { ++owner_samples_[owner]; - ++arrival_histogram_[owner][frame < frame_ ? std::min(48U, frame_ - frame) : 0]; + ++arrival_histogram_[owner][late]; } - if (frame < frame_) { - const auto late = std::min(48U, frame_ - frame); + if (late) { late_ = std::max(late_, late); owner_late_[owner] = std::max(owner_late_[owner], late); } diff --git a/runtime-recomp/src/game/online_stability/live_delay.hpp b/runtime-recomp/src/game/online_stability/live_delay.hpp index b713009e..7112b192 100644 --- a/runtime-recomp/src/game/online_stability/live_delay.hpp +++ b/runtime-recomp/src/game/online_stability/live_delay.hpp @@ -2,6 +2,7 @@ #include "control.hpp" #include "live_prediction.hpp" +#include "replay_cost.hpp" #include #include #include @@ -132,6 +133,7 @@ class LiveDelay final { struct Report { DelayMessage message; Clock::time_point at{}; + ReplayCost cost; }; struct Proposal { DelayMessage message; @@ -139,6 +141,7 @@ class LiveDelay final { }; void send(Member target, DelayMessage message); void receive(const Identity&, Member source, const DelayMessage&, Clock::time_point now); + void record_report(Member source, const DelayMessage&, Clock::time_point now); void apply(unsigned delay, Clock::time_point now); std::shared_ptr control_; unsigned fixed_ = 0, current_ = 0, window_ = 0, fill_ = 0, late_ = 0, waits_ = 0, samples_ = 0, local_owner_ = 4; diff --git a/runtime-recomp/src/game/online_stability/lobby_ui.inl b/runtime-recomp/src/game/online_stability/lobby_ui.inl index 30915646..dfad2e34 100644 --- a/runtime-recomp/src/game/online_stability/lobby_ui.inl +++ b/runtime-recomp/src/game/online_stability/lobby_ui.inl @@ -1,4 +1,155 @@ +void DrawOlSessionLinks(float width) { + namespace watch = dkr::runtime::spectators; + namespace links = dkr::runtime::netplay::links; + auto* session = &dkr::runtime::netplay::session(); + auto hub = watch::party_link(session); + struct Snapshot { + links::Scope scope; + std::map samples; + std::map capacity; + links::Handover handover; + std::set introduced; + std::string status; + bool finished = false, directory_public = false; + }; + Snapshot state; + watch::PartySnapshot roster; + bool host = false, waiting = false; + std::uint64_t local = 0; + { + std::scoped_lock lock(hub->mutex); + if (!hub->enabled) + return; + state.scope = hub->links.scope; + state.samples = hub->links.samples; + state.capacity = hub->links.capacity; + state.handover = hub->links.handover; + state.status = hub->links.status; + state.finished = hub->links.finished; + state.directory_public = hub->links.directory_public; + for (const auto& [id, intro] : hub->links.introduced) + state.introduced.insert(id); + roster = hub->party.snapshot(); + host = hub->host; + local = hub->local; + waiting = !hub->launch && !hub->running && !hub->stopping; + } + auto name = [&](std::uint64_t id) { + const auto at = + std::find_if(roster.members.begin(), roster.members.end(), [&](const auto& m) { return m.id == id; }); + return at == roster.members.end() ? std::string("Player") : at->name; + }; + DrawOlFeature( + width, "Session networking", "Direct racer input links keep spectators outside the racing input path.", + [&](float inner) { + const auto now = links::Clock::now(); + unsigned active = 0; + for (const auto& [pair, sample] : state.samples) + if (pair.first == local && links::input_pair(state.scope, pair.first, pair.second) && + sample.observations && now - sample.measured < std::chrono::seconds(2)) + ++active; + OlParagraph(std::to_string(active) + " measured direct racer connections", 14.F, kOlSoft, inner); + if (const auto best = links::recommend(state.scope, state.samples, state.capacity, now)) { + OlParagraph("Suggested host: " + name(best->member), 16.F, kOlCream, inner, true); + OlParagraph(best->reason, 14.F, kOlSoft, inner); + } + const auto phase = state.handover.phase(); + const bool active_transfer = phase == links::Phase::Offered || phase == links::Phase::Preparing || + phase == links::Phase::Committing || + (phase == links::Phase::Committed && !state.finished); + if (!state.status.empty()) + OlParagraph(state.status, 14.F, kOlSoft, inner); + if (active_transfer) { + OlParagraph(state.handover.status(), 15.F, kOlCream, inner, true); + const auto& proposal = state.handover.proposal(); + if (proposal && proposal->successor == local && phase == links::Phase::Offered) { + const bool hidden = state.directory_public && dkr::online::view()->hidden; + if (hidden) + OlParagraph("Turn off Appear offline before accepting this public lobby.", 14.F, kOlSoft, + inner); + { + const OlDisabled disabled(hidden); + if (OlButton("Accept hosting", OlTone::Go)) { + std::scoped_lock lock(hub->mutex); + hub->links.consent = true; + } + } + PaddockGap(6.F); + if (OlButton("Decline")) { + std::scoped_lock lock(hub->mutex); + hub->links.consent = false; + } + } + if (host && phase != links::Phase::Committing && OlButton("Cancel host transfer")) { + std::scoped_lock lock(hub->mutex); + hub->links.cancel = true; + } + } else if (host && waiting) { + const bool supported = state.scope.members.size() == roster.members.size() && + std::all_of(state.scope.members.begin(), state.scope.members.end(), + [](const auto& m) { return m.capable; }); + if (!supported) + OlParagraph("Waiting for every player to confirm host-transfer support.", 14.F, kOlSoft, inner); + for (const auto& member : roster.members) + if (member.id != local) { + ImGui::PushID(std::to_string(member.id).c_str()); + const OlDisabled disabled(!supported); + if (OlButton(("Transfer host to " + member.name).c_str())) { + bool owns_save = false; + { + std::scoped_lock lock(hub->mutex); + owns_save = hub->links.save_owner == local; + } + std::vector paks, records; + std::string error; + if (owns_save) { + std::vector seed; + std::filesystem::path owner; + if (!dkr::runtime::saves::read_online_adventure(true, state.scope.room, seed, owner, + error) || + !dkr::runtime::saves::read_experimental_online_paks(true, state.scope.room, paks, + error)) { + OlNotify(error); + ImGui::PopID(); + continue; + } + const auto path = owner.parent_path() / "custom-records-v1.bin"; + std::error_code ec; + if (std::filesystem::exists(path, ec)) { + const auto size = std::filesystem::file_size(path, ec); + if (ec || size > 20 + 8192 * 76) + error = "The online records could not be prepared for transfer."; + else { + std::ifstream input(path, std::ios::binary); + records.resize(std::size_t(size)); + if (!input.read(reinterpret_cast(records.data()), + std::streamsize(records.size())) || + !dkr::runtime::saves::records::valid(records)) + error = "The online records need recovery before transferring host."; + } + } + } + if (!error.empty()) + OlNotify(error); + else { + std::scoped_lock lock(hub->mutex); + if (owns_save) { + hub->links.save_paks = std::move(paks); + hub->links.save_records = std::move(records); + } + hub->links.request = member.id; + } + } + ImGui::PopID(); + PaddockGap(4.F); + } + } else if (!waiting) + OlParagraph("Host transfers are available after returning to the lobby.", 14.F, kOlSoft, inner); + }); + PaddockGap(12.F); +} void DrawOlJoiningProgress(float width, const OnlineFrame& frame) { + DrawOlSessionLinks(width); if (frame.view.host) return; // The host retains the existing approval cards. const auto rows = dkr::online_stability::control(&dkr::runtime::netplay::session())->joins(); diff --git a/runtime-recomp/src/game/online_stability/replay_cost.hpp b/runtime-recomp/src/game/online_stability/replay_cost.hpp new file mode 100644 index 00000000..c4ab456e --- /dev/null +++ b/runtime-recomp/src/game/online_stability/replay_cost.hpp @@ -0,0 +1,34 @@ +#pragma once +#include +#include +#include + +namespace dkr::online_stability { +// Estimate correction pressure from the existing report fields. Forward work +// excludes replay; no new protocol fields or guest state are introduced. +class ReplayCost final { + std::optional frontier_; + std::uint64_t tick_us_ = 0; + + public: + void observe(std::uint32_t frame, unsigned work, unsigned replay, unsigned interval) { + const auto previous = frontier_; + frontier_ = frame; + if (!previous || frame < *previous) { + tick_us_ = 0; + return; + } + const auto advanced = frame - *previous; + if (!advanced || advanced > 240 || interval < 100000 || interval > 2000000 || replay > work) + return; + const auto sample = std::min(1000000, (work - replay) / advanced); + tick_us_ = tick_us_ ? (3 * tick_us_ + sample + 3) / 4 : sample; + } + bool pressure(unsigned late, unsigned replay) const { + return late > 1 && replay >= 33333 && tick_us_ * late > 33333; + } + bool busy(unsigned late, unsigned replay) const { + return late && replay >= 16667 && tick_us_ * late > 16667; + } +}; +} // namespace dkr::online_stability diff --git a/runtime-recomp/src/game/online_view_rt64.cpp b/runtime-recomp/src/game/online_view_rt64.cpp index db926828..71cea72f 100644 --- a/runtime-recomp/src/game/online_view_rt64.cpp +++ b/runtime-recomp/src/game/online_view_rt64.cpp @@ -4,6 +4,7 @@ #include "hud_projection_rt64.hpp" #include "hud_reference_layout.hpp" #include "presentation_identity.hpp" +#include "time_trial/session.hpp" #include "hle/rt64_state.h" #include #include @@ -25,6 +26,7 @@ struct Pass::Impl { hud::LayoutMode hud_mode = hud::LayoutMode::Original; hlslpp::float4x4 camera{}; Nameplates names; + std::optional ghost; IdentitySelector select = nullptr; std::array widgets{}; std::array widget_elements{}; @@ -67,6 +69,7 @@ void Pass::prepare(const Session& session, std::span std::span decoder, std::uint32_t scene, float aspect, std::uint32_t framebuffer, hud::LayoutMode hud_mode) noexcept { auto& p = *impl_; + p.ghost.reset(); const auto eligibility = dkr::online_stability::view_eligibility(session.owner, session.players, events); p.race_type = eligibility.race_type; p.plan = dkr::online_stability::focus_plan(online_view::plan(session, events), eligibility, session.owner, @@ -102,6 +105,31 @@ void Pass::prepare(const Session& session, std::span p.names.prepare(session, p.plan, decoder, p.plan.focus ? presentation::normalise_identity(scene ^ 0x46554C4CU ^ session.owner) : scene); } +void Pass::prepare_ghost(time_trial::GhostNameplate ghost, std::span decoder, + std::uint32_t scene) noexcept { + auto& p = *impl_; + p.plan = {}; + p.phase = Impl::Phase::Shared; + p.camera_valid = false; + p.framebuffer = ghost.framebuffer; + p.names.prepare_ghost(ghost.name ? std::string_view(*ghost.name) : std::string_view{}, ghost.outline, decoder, + scene); + p.ghost = std::move(ghost); +} +void Pass::ghost_world_boundary(RT64::State& s, unsigned view, bool end) { + auto& p = *impl_; + if (!p.ghost || view != 0) + return; + if (!end) { + p.phase = Impl::Phase::World; + p.camera_valid = false; + p.names.begin_view(view); + return; + } + if (p.phase == Impl::Phase::World && p.camera_valid && p.main_image(s)) + p.names.draw_ghost(s, *p.ghost, p.camera, p.select); + p.phase = Impl::Phase::Shared; +} void Pass::selector(IdentitySelector value) noexcept { impl_->select = value; } @@ -240,7 +268,7 @@ void Pass::after_command(RT64::State& s, bool scissor, bool viewport) { } void Pass::camera_root(RT64::RSP& rsp, unsigned matrix) { auto& p = *impl_; - if (!p.plan.eligible || p.phase != Impl::Phase::World || matrix > 2) + if ((!p.plan.eligible && !p.ghost) || p.phase != Impl::Phase::World || matrix > 2) return; p.camera = rsp.modelMatrixStack[matrix]; p.camera_valid = true; diff --git a/runtime-recomp/src/game/online_view_rt64.hpp b/runtime-recomp/src/game/online_view_rt64.hpp index c5bf1289..c0bb6765 100644 --- a/runtime-recomp/src/game/online_view_rt64.hpp +++ b/runtime-recomp/src/game/online_view_rt64.hpp @@ -6,6 +6,9 @@ namespace RT64 { struct State; struct RSP; } // namespace RT64 +namespace dkr::runtime::time_trial { +struct GhostNameplate; +} namespace dkr::runtime::online_view { // One instance per owned renderer. No reference to live/replay RAM is retained. class Pass final { @@ -16,6 +19,8 @@ class Pass final { Pass& operator=(const Pass&) = delete; void prepare(const Session&, std::span, std::span decoder, std::uint32_t scene, float aspect, std::uint32_t framebuffer, hud::LayoutMode hud_mode) noexcept; + void prepare_ghost(time_trial::GhostNameplate, std::span decoder, std::uint32_t scene) noexcept; + void ghost_world_boundary(RT64::State&, unsigned view, bool end); bool focused() const noexcept; bool focused_hud() const noexcept; bool widget_active() const noexcept; diff --git a/runtime-recomp/src/game/owner_pump.inl b/runtime-recomp/src/game/owner_pump.inl index ada6f475..4eed7715 100644 --- a/runtime-recomp/src/game/owner_pump.inl +++ b/runtime-recomp/src/game/owner_pump.inl @@ -7,6 +7,30 @@ auto owner = directory::native::owner(this); const auto online = directory::view(); const auto now = std::chrono::steady_clock::now(); + { + auto party = watch::party_link(this); + std::scoped_lock party_lock(party->mutex); + auto bridge = directory::bridge(this); + std::lock_guard bridge_lock(bridge->mutex); + std::erase_if(bridge->commands, [&](const auto& command) { + if (command.value("type", std::string{}) != "host_transfer_result") + return false; + auto& links = party->links; + const auto& proposal = links.handover.proposal(); + const auto data = command.value("data", directory::Json::object()); + if (proposal && data.value("serial", std::string{}) == std::to_string(proposal->serial) && + data.value("digest", std::string{}) == secure::encode_key(proposal->state) && + command.value("ok", false)) { + if (command.value("operation", std::string{}) == "transfer_accept") + links.directory_accepted = true; + if (command.value("operation", std::string{}) == "transfer_commit") + links.directory_committed = true; + } else if (proposal && !command.value("ok", false)) + links.status = command.value("error", directory::Json::object()) + .value("message", std::string("Waiting for the directory host transfer.")); + return true; + }); + } const bool hosting = is_host_ && method_ == ConnectionMethod::QuickJoin && state_ != ConnectionState::Offline && state_ != ConnectionState::Failed; if (!hosting) { @@ -48,7 +72,8 @@ const bool starting = launch_countdown_active_ || launch_stage_ != LaunchStage::Idle || gate->phase == dkr::runtime::party_start::Phase::Countdown || gate->phase == dkr::runtime::party_start::Phase::Committing; - const bool testing = connection_test_active_ || dkr::runtime::rollback_check::active(this); + const bool testing = connection_test_active_ || dkr::runtime::rollback_check::active(this) || + dkr::runtime::netplay::links::busy(party->links); const bool returning = party->stopping || (owned_match_end_ && !owned_match_end_->resumed); const bool live = party->running || state_ == ConnectionState::Running; const bool loading = state_ == ConnectionState::Loading || bool(party->launch); diff --git a/runtime-recomp/src/game/party.cpp b/runtime-recomp/src/game/party.cpp index 276dc5cd..9a6b6abe 100644 --- a/runtime-recomp/src/game/party.cpp +++ b/runtime-recomp/src/game/party.cpp @@ -264,6 +264,20 @@ bool Party::valid(const PartySnapshot& value, std::string& error) { error.clear(); return true; } +bool Party::transfer_host(MemberId authenticated, MemberId successor, std::uint64_t generation, std::string& error) { + if (authenticated != state_.host || successor == authenticated || !find(successor) || state_.handover || + state_.generation == UINT64_MAX || generation != state_.generation + 1) + return no(error, "The prepared host transfer no longer matches this lobby."); + auto next = state_; + next.host = successor; + next.generation = generation; + for (auto& m : next.members) + m.host = m.id == successor; + if (!valid(next, error)) + return false; + state_ = std::move(next); + return true; +} bool Party::replace_verified(PartySnapshot value, std::string& error) { if (!valid(value, error)) return false; diff --git a/runtime-recomp/src/game/party.hpp b/runtime-recomp/src/game/party.hpp index eca767b0..d2f77c6f 100644 --- a/runtime-recomp/src/game/party.hpp +++ b/runtime-recomp/src/game/party.hpp @@ -65,6 +65,7 @@ class Party final { return state_; } bool replace_verified(PartySnapshot value, std::string& error); + bool transfer_host(MemberId authenticated, MemberId successor, std::uint64_t generation, std::string& error); static bool valid(const PartySnapshot& value, std::string& error); private: diff --git a/runtime-recomp/src/game/party_link.cpp b/runtime-recomp/src/game/party_link.cpp index 7d437669..bd9ca210 100644 --- a/runtime-recomp/src/game/party_link.cpp +++ b/runtime-recomp/src/game/party_link.cpp @@ -25,8 +25,8 @@ void party_cancel_swap(const void* s) { bool party_waiting_role(const void* s, MemberId id, bool racer, std::string& e) { auto h = party_link(s); std::scoped_lock lock(h->mutex); - if (!h->enabled || !h->host || h->launch || h->running || h->stopping) { - e = "Roles can only be assigned directly while waiting in the lobby."; + if (!h->enabled || !h->host || h->launch || h->running || h->stopping || net::links::busy(h->links)) { + e = "Finish the current race or host transfer before changing roles."; return false; } std::optional port; @@ -134,6 +134,7 @@ bool PartyLink::participant(MemberId id) const { return m && m->connected && (m->host || m->role == Role::Racer); } void PartyLink::reset_connection() { + links.reset(); queue_age.reset(); for (auto& p : peers) crypto_wipe(p.key.data(), p.key.size()); @@ -228,8 +229,11 @@ bool PartyLink::admit_incoming(MemberId sender, std::span by return false; if (host && !party.find(sender)) return false; - if (!host && sender != authority) - return false; + if (!host && sender != authority) { + const auto* owner = party.find(sender); + if (!owner || owner->role != Role::Racer || !peer(sender) || bytes.size() < 21 || bytes[4] != 19) + return false; + } incoming.push_back({sender, {bytes.begin(), bytes.end()}}); incoming_bytes += bytes.size(); return true; @@ -291,16 +295,63 @@ bool party_receive(const void* session, LinkIncoming& out) { p->incoming.pop_front(); return true; } +std::size_t party_retire_checkpoint(const void* session, MemberId target, std::uint64_t match, std::uint64_t transfer) { + auto p = party_link(session); + std::scoped_lock lock(p->mutex); + std::size_t retired = 0; + if (!target || !match || !transfer) + return 0; + // Only unsent observer chunks/history from this exact game and recipient. + // Racing inputs, repair, authority, lobby and other viewers retain priority + // and identity. Already submitted SCTP data remains bounded by its channel. + for (const auto lane : {3U, 4U}) + for (auto it = p->outgoing[lane].begin(); it != p->outgoing[lane].end();) { + const auto& b = it->bytes; + const bool envelope = + b.size() >= 29 && b[0] == 'D' && b[1] == 'P' && b[2] == 'R' && b[3] == 2 && b[4] == (lane == 4 ? 3 : 7); + const auto number = [&](unsigned at) { + std::uint64_t v = 0; + for (unsigned i = 0; i < 8; ++i) + v |= std::uint64_t(b[at + i]) << (8 * i); + return v; + }; + if (it->target == target && it->kind == LinkKind::Runtime && envelope && number(5) == match && + number(21) != transfer) { + retired += b.size(); + p->outgoing_bytes -= b.size(); + it = p->outgoing[lane].erase(it); + } else + ++it; + } + return retired; +} +bool party_direct_input(const void* session, MemberId target, std::span bytes, + net::TransportTrafficClass traffic) { + auto p = party_link(session); + std::scoped_lock lock(p->mutex); + if (!p->enabled || p->host || target == p->authority || target == p->local || p->local_watching() || + bytes.size() < 21 || bytes[4] != 19 || !p->links.introduced.contains(target) || + !p->links.live_routes.contains(target)) + return false; + const auto* remote = p->party.find(target); + const auto sample = p->links.samples.find({p->local, target}); + if (!remote || remote->role != Role::Racer || sample == p->links.samples.end() || !sample->second.observations || + std::chrono::steady_clock::now() - sample->second.measured > std::chrono::seconds(2)) + return false; + return p->enqueue({target, LinkKind::Runtime, traffic, {bytes.begin(), bytes.end()}}); +} void party_ready(const void* session, bool ready) { auto p = party_link(session); std::scoped_lock lock(p->mutex); + if (net::links::busy(p->links)) + return; p->ready_requested = true; p->ready_value = ready; } void party_start(const void* session) { auto p = party_link(session); std::scoped_lock lock(p->mutex); - if (p->host) + if (p->host && !net::links::busy(p->links)) p->start_requested = true; } void party_stop(const void* session, std::string reason) { diff --git a/runtime-recomp/src/game/party_link.hpp b/runtime-recomp/src/game/party_link.hpp index 0806ed19..50a83f1a 100644 --- a/runtime-recomp/src/game/party_link.hpp +++ b/runtime-recomp/src/game/party_link.hpp @@ -6,6 +6,8 @@ #include "online_stability/traffic_meter.hpp" #include "online_stability/ping_window.hpp" #include "online_stability/live_send_capacity.hpp" +#include "netplay/session_links/state.hpp" +#include "netplay/session_links/registry.hpp" #include #include #include @@ -81,6 +83,7 @@ struct LinkView { // Public/UI functions below NEVER call DirectSession while holding this lock. // No change to DirectSession's class layout or checked-out header is required. struct PartyLink { + net::links::State links; dkr::online_stability::PingWindow ping_window; dkr::online_stability::QueueAgeMeter queue_age; mutable std::recursive_mutex mutex; @@ -132,6 +135,9 @@ bool party_watching(const void* session); bool party_send(const void* session, MemberId target, std::span bytes, net::TransportTrafficClass traffic); bool party_receive(const void* session, LinkIncoming& out); +bool party_direct_input(const void* session, MemberId target, std::span bytes, + net::TransportTrafficClass traffic); +std::size_t party_retire_checkpoint(const void* session, MemberId target, std::uint64_t match, std::uint64_t transfer); void party_ready(const void* session, bool ready); void party_start(const void* session); void party_stop(const void* session, std::string reason); diff --git a/runtime-recomp/src/game/party_runtime.cpp b/runtime-recomp/src/game/party_runtime.cpp index 53e9860a..16f29aef 100644 --- a/runtime-recomp/src/game/party_runtime.cpp +++ b/runtime-recomp/src/game/party_runtime.cpp @@ -622,7 +622,9 @@ struct PartyRuntime::Impl { playback.request_resync("Loading the confirmed race"); held.reset(); admitted_at.reset(); - if (!server()) + const bool matching = (receiving || decoding.valid()) && last_offer && last_offer->next == at && + last_offer->control_generation == controls; + if (!server() && !matching) send(host, Msg::Need); } activated_release = std::pair{at, controls}; @@ -684,6 +686,10 @@ struct PartyRuntime::Impl { d.actions = held->magic_actions; if (!d.sender.begin(++transfer_serial, std::make_shared(wire))) throw std::runtime_error("Could not stage spectator checkpoint delivery."); + party_retire_checkpoint(key, id, match, d.sender.offer().transfer); + std::fprintf(stderr, "[party][checkpoint-send] peer=%llu transfer=%llu epoch=%llu frame=%u bytes=%zu\n", + static_cast(id), static_cast(transfer_serial), + static_cast(wire.next.epoch), wire.next.frame, wire.state->size()); } bool current_checkpoint() const { if (!encoded || !feed.covers(encoded->next)) @@ -864,13 +870,14 @@ struct PartyRuntime::Impl { body.n(controls).n(wire::ControllerSampleBytes, 1).data(wire::controller(sample)).data(command_bytes(c)); if (relay) racers(Msg::Input, body.b, Lane::Authoritative); - } else if (source != host) + } else if (source != host && (launch.development || !c.empty() || + !roster.accepts(source, sample.port, sample.lease, sample.cursor))) return; const auto result = driver->receive(cursor.epoch, sample.port, sample.cursor.frame - base, packed(sample.input), c); if (result == ex::InputResult::Accepted || result == ex::InputResult::Duplicate) { - if (result == ex::InputResult::Accepted && !server() && source == host && sample.port == 0 && - roster.accepts(host, 0, sample.lease, sample.cursor)) { + if (result == ex::InputResult::Accepted && !server() && source == host && + roster.accepts(host, sample.port, sample.lease, sample.cursor)) { const auto identity = dkr::online_stability::control(key)->identity(); unsigned rtt = 0; for (const auto& route : identity.routes) @@ -910,7 +917,7 @@ struct PartyRuntime::Impl { return; (void)r.n(); const bool from_host = source == host; - if (!server() && !from_host) + if (!server() && !from_host && type != Msg::LiveInputs) return; if (server() && !roster.find(source)) return; @@ -960,6 +967,9 @@ struct PartyRuntime::Impl { last_offer = offer; receiving = offer; active_transfer = offer.transfer; + std::fprintf(stderr, "[party][checkpoint-receive] transfer=%llu epoch=%llu frame=%u bytes=%u\n", + static_cast(offer.transfer), + static_cast(offer.next.epoch), offer.next.frame, offer.bytes); admitted_at.reset(); buffered.clear(); if (phase == Phase::Admission) @@ -983,6 +993,8 @@ struct PartyRuntime::Impl { if (result == CheckpointReceiver::Result::Rejected) throw std::runtime_error(e); if (result == CheckpointReceiver::Result::Complete) { + std::fprintf(stderr, "[party][checkpoint-receive] complete transfer=%llu bytes=%zu\n", + static_cast(chunk.transfer), receiver.received_bytes()); auto wire_state = receiver.take_verified(e); if (!wire_state) throw std::runtime_error(e); @@ -1070,7 +1082,7 @@ struct PartyRuntime::Impl { std::uint64_t(packet.first) + packet.count > freeze || std::uint64_t(packet.first) + packet.count > std::uint64_t(next().frame) + 49) return; - if (server()) + if (server() || !from_host) for (unsigned i = 0; i < packet.count; ++i) if (!roster.accepts(source, packet.owner, packet.lease, {packet.epoch, packet.first + i})) return; @@ -1375,8 +1387,22 @@ struct PartyRuntime::Impl { const auto bytes = dkr::online_stability::encode_live_inputs(live); if (server()) racers(Msg::LiveInputs, bytes, Lane::Realtime); - else + else { send(host, Msg::LiveInputs, bytes, Lane::Realtime); + for (auto id : required()) + if (id != local && id != host) { + Write direct; + direct.n('D', 1) + .n('P', 1) + .n('R', 1) + .n(2, 1) + .n(unsigned(Msg::LiveInputs), 1) + .n(match) + .n(++serial) + .data(bytes); + party_direct_input(key, id, direct.b, Lane::Realtime); + } + } return; // Exact old holes retain the independent authority repair lane. } Write body; @@ -1719,6 +1745,8 @@ struct PartyRuntime::Impl { // An observer cannot stop required racing peers with malformed // playback/seat requests. Required members still fail closed. if (server() && !required().contains(packet.source)) { + std::fprintf(stderr, "[party][observer-packet] rejected peer=%llu reason=%s\n", + static_cast(packet.source), e.what()); needing.erase(packet.source); deliveries.erase(packet.source); continue; @@ -1749,6 +1777,15 @@ struct PartyRuntime::Impl { if (!callback_error.empty()) throw std::runtime_error(callback_error); transfer(now); + if (phase != Phase::Admission && now >= admission_log && + ((!simulating() && playback.needs_baseline()) || (server() && !deliveries.empty()))) { + admission_log = now + std::chrono::seconds(5); + std::fprintf( + stderr, + "[party][checkpoint-progress] authority=%u receiving=%zu active=%u decoding=%u encoded=%u needing=%zu deliveries=%zu\n", + unsigned(server()), receiver.received_bytes(), unsigned(bool(receiving)), unsigned(decoding.valid()), + unsigned(bool(encoded)), needing.size(), deliveries.size()); + } std::erase_if(deliveries, [&](const auto& entry) { return !roster.find(entry.first); }); std::erase_if(requested_at, [&](const auto& entry) { return !roster.find(entry.first); }); if (server() && phase == Phase::Admission && all(prepared)) diff --git a/runtime-recomp/src/game/personal_adventure_paths.hpp b/runtime-recomp/src/game/personal_adventure_paths.hpp new file mode 100644 index 00000000..6019c47e --- /dev/null +++ b/runtime-recomp/src/game/personal_adventure_paths.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include +#include + +namespace dkr::runtime::saves { +inline constexpr std::string_view kModdedAdventureFolder = "modded"; +inline constexpr std::string_view kModdedAdventureDirectory = "saves/modded/"; + +inline std::filesystem::path personal_adventure_subfolder(bool modded) { + return modded ? std::filesystem::path(kModdedAdventureFolder) : std::filesystem::path{}; +} + +inline std::filesystem::path personal_adventure_path(const std::filesystem::path& root, bool modded) { + return root / "saves" / personal_adventure_subfolder(modded) / "dkr.us.v77.bin"; +} +} // namespace dkr::runtime::saves diff --git a/runtime-recomp/src/game/presentation_identity.cpp b/runtime-recomp/src/game/presentation_identity.cpp index b8d33b48..bf7e120e 100644 --- a/runtime-recomp/src/game/presentation_identity.cpp +++ b/runtime-recomp/src/game/presentation_identity.cpp @@ -17,6 +17,7 @@ #include "runtime_hud_layout.hpp" #include "runtime_netplay.hpp" #include "vehicle_context_policy.hpp" +#include "time_trial/session.hpp" #include #include @@ -210,6 +211,7 @@ thread_local dkr::runtime::presentation::RetainedMetadataTable g_active_matrix_map; thread_local std::unordered_map> g_active_marker_map; @@ -551,7 +553,8 @@ void NoteFree(std::uint32_t object) { } void RegisterCameraMatrix(std::uint8_t* rdram, std::uint32_t matrix_reference, std::uint8_t matrix_role) { - if (!dkr::runtime::enhancements::modern_presentation_enabled()) { + const bool modern = dkr::runtime::enhancements::modern_presentation_enabled(); + if (!modern && (matrix_role != 1U || !dkr::runtime::time_trial::ghost_nameplate_active())) { return; } if (!ValidRange(matrix_reference, 4U)) { @@ -566,6 +569,13 @@ void RegisterCameraMatrix(std::uint8_t* rdram, std::uint32_t matrix_reference, s } std::scoped_lock lock(g_identity_mutex); + if (!modern) { + // Accurate mode needs the ghost label's camera root without interpolation metadata. + MatrixBinding root{}; + root.camera_root = true; + g_matrix_maps[g_recording_buffer & 1U].insert_or_assign(Physical(matrix_address), root); + return; + } const std::uint32_t scene = g_scene_generation.load(std::memory_order_relaxed); std::uint32_t camera_id = 0U; if (!ActiveLogicalCamera(rdram, camera_id)) { @@ -642,6 +652,11 @@ void RegisterCameraMatrix(std::uint8_t* rdram, std::uint32_t matrix_reference, s dkr::runtime::presentation::MatrixInterpolation dkr::runtime::presentation::matrix_interpolation(std::uint32_t physical_matrix_address) { const std::uint32_t address = physical_matrix_address & kRdramMask; + if (g_active_replay) { + const auto& matrices = g_active_replay->matrices; + const auto found = std::ranges::lower_bound(matrices, address, {}, &OwnedMatrixBinding::address); + return found != matrices.end() && found->address == address ? found->interpolation : MatrixInterpolation{}; + } const MatrixBinding* binding = nullptr; if (g_active_owned_task) binding = g_active_owned_matrices.find(address); @@ -828,6 +843,18 @@ dkr::runtime::presentation::shadow_presentation_key(std::uint8_t* rdram, std::ui }; } +namespace { +const dkr::runtime::presentation::OwnedShadowBinding* ReplayShadow(std::uint64_t key) { + using dkr::runtime::presentation::OwnedShadowBinding; + if ((key >> 16U) != g_active_replay->scene) + return nullptr; + const auto& shadows = g_active_replay->shadows; + const auto token = static_cast(key); + const auto found = std::ranges::lower_bound(shadows, token, {}, &OwnedShadowBinding::token); + return found != shadows.end() && found->token == token ? &*found : nullptr; +} +} // namespace + bool dkr::runtime::presentation::shadow_owner_uses_rigid_actor_proxy(std::uint64_t shadow_history_key) { if (shadow_history_key == 0U) return false; @@ -835,6 +862,8 @@ bool dkr::runtime::presentation::shadow_owner_uses_rigid_actor_proxy(std::uint64 const auto* found = g_active_owned_shadow_policies.find(shadow_history_key); return found && found->required(); } + if (g_active_replay) + return shadow_owner_rigid_policy(shadow_history_key).required(); std::scoped_lock lock(g_identity_mutex); return g_rigid_actor_shadow_keys.contains(shadow_history_key); } @@ -846,6 +875,8 @@ bool dkr::runtime::presentation::shadow_owner_is_taj_carpet_actor(std::uint64_t const auto* found = g_active_owned_shadow_policies.find(shadow_history_key); return found && found->terrain_conforming_actor(); } + if (g_active_replay) + return shadow_owner_rigid_policy(shadow_history_key).magic_carpet(); std::scoped_lock lock(g_identity_mutex); return g_taj_carpet_shadow_keys.contains(shadow_history_key); } @@ -858,6 +889,10 @@ dkr::runtime::presentation::shadow_owner_rigid_policy(std::uint64_t shadow_histo const auto* found = g_active_owned_shadow_policies.find(shadow_history_key); return found ? *found : RigidShadowOwnerPolicy{}; } + if (g_active_replay) { + const auto* binding = ReplayShadow(shadow_history_key); + return binding ? binding->policy : RigidShadowOwnerPolicy{}; + } std::scoped_lock lock(g_identity_mutex); const auto found = g_rigid_shadow_owner_policies.find(shadow_history_key); return found != g_rigid_shadow_owner_policies.end() ? found->second @@ -872,13 +907,18 @@ dkr::runtime::presentation::shadow_owner_motion_sample(std::uint64_t shadow_hist const auto* found = g_active_owned_shadow_motion.find(shadow_history_key); return found ? *found : ShadowOwnerMotionSample{}; } + if (g_active_replay) { + const auto* binding = ReplayShadow(shadow_history_key); + return binding ? binding->motion : ShadowOwnerMotionSample{}; + } const auto found = g_active_shadow_owner_motion.find(shadow_history_key); return found != g_active_shadow_owner_motion.end() ? found->second : dkr::runtime::presentation::ShadowOwnerMotionSample{}; } dkr::runtime::presentation::TaskIdentityScope::TaskIdentityScope(std::uint8_t* rdram_snapshot, - std::uint32_t display_list_address) { + std::uint32_t display_list_address, + const ReplayPresentation* replay) { g_active_task_presentation_time = 0.0; g_active_matrix_map.clear(); g_active_marker_map.clear(); @@ -888,6 +928,17 @@ dkr::runtime::presentation::TaskIdentityScope::TaskIdentityScope(std::uint8_t* r g_active_task_scene_generation = 0U; g_active_owned_task = false; g_active_owned_shadow_policies.clear(); + g_active_replay = replay; + if (replay) { + for (const auto& located : replay->markers) + g_active_marker_map[located.address].push_back(located.marker); + // Archive playback normally presents authored pictures. Video export + // has a sequential timeline and can use the archived motion identities. + g_active_task_interpolation_allowed = time_trial::exporting_video() && replay->scene != 0U; + g_active_task_scene_generation = replay->scene; + g_active_task_presentation_time = replay->time; + return; + } if (rdram_snapshot == nullptr) { return; } @@ -937,6 +988,7 @@ dkr::runtime::presentation::TaskIdentityScope::TaskIdentityScope(std::uint8_t* r } dkr::runtime::presentation::TaskIdentityScope::~TaskIdentityScope() { + g_active_replay = nullptr; g_active_matrix_map.clear(); g_active_marker_map.clear(); g_active_detail.clear(); @@ -965,6 +1017,7 @@ dkr::runtime::presentation::TaskIdentityScope::TaskIdentityScope(std::span= 0 ? time : 0; if (markers.size() > 8192 || matrices.size() > 8192 || shadows.size() > 8192) { g_active_owned_matrices.clear(); @@ -1157,7 +1210,10 @@ bool dkr::runtime::presentation::record_presentation_marker(std::uint32_t comman std::uint16_t token, std::uint8_t variant, PresentationMarkerKind kind, hud::groups::Transform hud_transform) { - if (!dkr::runtime::enhancements::modern_presentation_enabled()) { + const bool world_boundary = + kind == PresentationMarkerKind::CameraWorldBegin || kind == PresentationMarkerKind::CameraWorldEnd; + if (!dkr::runtime::enhancements::modern_presentation_enabled() && + !(world_boundary && dkr::runtime::time_trial::ghost_nameplate_active())) { return false; } const std::uint32_t physical = Physical(command_address); @@ -1436,7 +1492,50 @@ extern "C" void dkr_presentation_task_submitted(std::uint8_t* rdram, recomp_cont } dkr::runtime::graphics_handoff::capture(rdram, static_cast(context->r4), static_cast(context->r5)); - if (!dkr::runtime::enhancements::modern_presentation_enabled()) { + if (dkr::runtime::time_trial::watching()) { + std::shared_ptr sidecar; + if (dkr::runtime::enhancements::modern_presentation_enabled()) + sidecar = std::make_shared(); + { + std::scoped_lock lock(g_identity_mutex); + const auto buffer = g_recording_buffer & 1U; + if (sidecar && g_marker_integrity[buffer].valid) { + for (const auto& [address, markers] : g_marker_maps[buffer]) + for (const auto& marker : markers) + sidecar->markers.push_back({address, marker}); + sidecar->scene = g_scene_generation.load(std::memory_order_relaxed); + sidecar->time = double(g_presentation_ticks.load(std::memory_order_relaxed)) / 60.0; + const bool capture_motion = dkr::runtime::time_trial::exporting_video(); + for (const auto& [address, binding] : g_matrix_maps[buffer]) { + if (!capture_motion && binding.world_projection.authored_fov <= 0.0F && !binding.camera_root) + continue; + sidecar->matrices.push_back( + {address, + {binding.matrix_identity, capture_motion && binding.interpolate_vertices, + capture_motion && binding.interpolate_texcoords, capture_motion && binding.interpolate_tiles, + capture_motion && binding.procedural_water, + capture_motion ? binding.water_scroll_tag : std::uint8_t{0}, binding.world_projection, + binding.camera_root}}); + } + for (const auto& [key, motion] : g_shadow_owner_motion_maps[buffer]) { + const auto policy = g_rigid_shadow_owner_policies.find(key); + if ((key >> 16U) == sidecar->scene && policy != g_rigid_shadow_owner_policies.end()) + sidecar->shadows.push_back({static_cast(key), policy->second, motion}); + } + std::ranges::sort(sidecar->matrices, {}, &dkr::runtime::presentation::OwnedMatrixBinding::address); + std::ranges::sort(sidecar->shadows, {}, &dkr::runtime::presentation::OwnedShadowBinding::token); + } + g_matrix_maps[buffer].clear(); + g_marker_maps[buffer].clear(); + g_detail_maps[buffer].clear(); + g_shadow_owner_motion_maps[buffer].clear(); + } + dkr::runtime::time_trial::theatre_graphics_submitted(rdram, static_cast(context->r4), + std::move(sidecar)); + return; + } + if (!dkr::runtime::enhancements::modern_presentation_enabled() && + !dkr::runtime::time_trial::ghost_nameplate_active()) { return; } SubmittedFrame frame{}; diff --git a/runtime-recomp/src/game/presentation_identity.hpp b/runtime-recomp/src/game/presentation_identity.hpp index f7884cd2..becf9879 100644 --- a/runtime-recomp/src/game/presentation_identity.hpp +++ b/runtime-recomp/src/game/presentation_identity.hpp @@ -2084,6 +2084,7 @@ struct LocatedPresentationMarker { std::uint32_t address; PresentationMarker marker; }; + std::vector camera_world_boundaries(); struct OwnedMatrixBinding { std::uint32_t address; @@ -2096,6 +2097,15 @@ struct OwnedShadowBinding { ShadowOwnerMotionSample motion; }; +// Presentation metadata retained with the same RDRAM snapshot as the replay frame. +struct ReplayPresentation { + std::vector markers; + std::vector matrices; + std::vector shadows; + std::uint32_t scene = 0; + double time = 0.0; +}; + // DKR flips gSPTaskNum immediately after gfxtask_run_xbus returns. A renderer // snapshot may therefore contain the parity of the next display-list buffer, // not the task being decoded. The frozen task's scene and data_ptr are the @@ -2121,7 +2131,8 @@ PresentationMarkerList active_presentation_markers(std::uint32_t command_address // the same N64 display-list buffer. class TaskIdentityScope { public: - TaskIdentityScope(std::uint8_t* rdram_snapshot, std::uint32_t display_list_address); + TaskIdentityScope(std::uint8_t* rdram_snapshot, std::uint32_t display_list_address, + const ReplayPresentation* replay = nullptr); // Private copied-image decode only. Does not consume the stable producer's // submission queue or install metadata from rewindable/live CPU globals. explicit TaskIdentityScope(std::span owned_markers); diff --git a/runtime-recomp/src/game/record_store.inl b/runtime-recomp/src/game/record_store.inl index 27434877..ec0fe45a 100644 --- a/runtime-recomp/src/game/record_store.inl +++ b/runtime-recomp/src/game/record_store.inl @@ -44,7 +44,7 @@ bool persist(const std::filesystem::path& path, std::span by error = "The custom-record store is full; export a copy before adding more records."; return false; } - return storage::write_atomic(path, encode(merged), ReadRecords, error); + return storage::write_progress(path, encode(merged), ReadRecords, error); } bool begin(const std::filesystem::path& path, bool restore, std::string& error) { if (!finish(error)) @@ -64,6 +64,18 @@ bool begin(const std::filesystem::path& path, bool restore, std::string& error) } return true; } +bool begin_memory(std::span bytes, std::string& error) { + Map next; + if (!bytes.empty() && !decode(bytes, next)) { + error = "The shared online records seed is invalid."; + return false; + } + if (!begin({}, false, error)) + return false; + std::scoped_lock lock(record_mutex); + record_seed = std::move(next); + return true; +} Bytes seed() { std::scoped_lock lock(record_mutex); return encode(record_seed); diff --git a/runtime-recomp/src/game/rt64_renderer.cpp b/runtime-recomp/src/game/rt64_renderer.cpp index 05e83272..4ffd82d8 100644 --- a/runtime-recomp/src/game/rt64_renderer.cpp +++ b/runtime-recomp/src/game/rt64_renderer.cpp @@ -8,6 +8,8 @@ #include "online_stability/battle_view.hpp" #include "vehicle_binding.hpp" #include "rt64_renderer.hpp" +#include "time_trial/session.hpp" +#include "time_trial/theatre_frames.hpp" #include "camera_rt64.hpp" #include "revision_addresses.hpp" #include "netplay/online_input_broker.hpp" @@ -524,7 +526,8 @@ dkr::runtime::RT64Renderer::RT64Renderer(std::uint8_t* rdram, ultramodern::rende // PresentEarly uses historical VIs during DL decode and ignores the // explicit updateScreen below. That native scheduler policy must not // choose an obsolete buffer after an owned scene/rollback boundary. - application_->enhancementConfig.presentation.mode = PresentationMode(owned_mode_); + application_->enhancementConfig.presentation.mode = + PresentationMode(owned_mode_ || time_trial::exporting_video()); dkr::runtime::startup_performance::report("rt64-application-create", application_started_at); }; create_application(); @@ -707,7 +710,8 @@ bool dkr::runtime::RT64Renderer::update_config(const ultramodern::renderer::Grap void dkr::runtime::RT64Renderer::enable_instant_present() { std::scoped_lock presentation_lock(presentation_mutex_); if (application_ != nullptr) { - application_->enhancementConfig.presentation.mode = PresentationMode(owned_mode_); + application_->enhancementConfig.presentation.mode = + PresentationMode(owned_mode_ || time_trial::exporting_video()); application_->updateEnhancementConfig(); } } @@ -722,9 +726,29 @@ void dkr::runtime::RT64Renderer::send_dl(const OSTask* task, std::uint8_t* rdram #else std::scoped_lock presentation_lock(presentation_mutex_); #endif - if (application_ == nullptr || rdram_snapshot == nullptr) { + if (application_ == nullptr || rdram_snapshot == nullptr) return; + if (time_trial::watching()) { + if (const auto stamp = time_trial::theatre_graphics_stamp(task->t.data_ptr)) { + if (!theatre_frames_) + theatre_frames_ = std::make_unique(time_trial::exporting_full_game_video()); + if (theatre_frames_->append(*task, *stamp, + std::span( + rdram_snapshot, time_trial::TheatreFrames::ImageBytes))) { + time_trial::theatre_buffered(stamp->progress.updates); + } else { + time_trial::theatre_archive_error(); + } + return; + } + if (theatre_frames_) + return; } + render_dl_locked(task, rdram_snapshot); +} + +void dkr::runtime::RT64Renderer::render_dl_locked(const OSTask* task, std::uint8_t* rdram_snapshot, + const presentation::ReplayPresentation* replay) { ApplyDisplayRequest(*application_, true); dkr::runtime::telemetry::record_graphics_task(); RT64::MipWaitFeedbackScope mipFeedback([this] { present_mipmap_loading(*application_); }); @@ -733,7 +757,7 @@ void dkr::runtime::RT64Renderer::send_dl(const OSTask* task, std::uint8_t* rdram // them. DKR relies on that during scene transitions and can free texture // allocations while the host graphics queue is still pending. Parse this // task from the submission-time snapshot, then restore live RDRAM for VI. - dkr::runtime::presentation::TaskIdentityScope identity_scope(rdram_snapshot, task->t.data_ptr); + dkr::runtime::presentation::TaskIdentityScope identity_scope(rdram_snapshot, task->t.data_ptr, replay); const bool detail_requested = enhancements::maximum_detail_enabled() && !detail::ordinary_events().empty(); std::uint8_t* decode_bytes = rdram_snapshot; const bool camera_requested = bool(camera::activation()); @@ -749,6 +773,16 @@ void dkr::runtime::RT64Renderer::send_dl(const OSTask* task, std::uint8_t* rdram render_provenance::Scope provenance( {rdram_snapshot, 0x800000}, {decode_bytes, decode_bytes == rdram_snapshot ? 0x800000U : camera_decoder_.size()}, task->t.data_ptr); + online_view::Pass* ghost_names = nullptr; + if (!replay) { + if (auto ghost = time_trial::ghost_nameplate(rdram_snapshot)) { + if (!ghost_nameplate_pass_) + ghost_nameplate_pass_ = std::make_unique(); + ghost_nameplate_pass_->prepare_ghost(std::move(*ghost), camera_decoder_, + presentation::task_scene_generation()); + ghost_names = ghost_nameplate_pass_.get(); + } + } static std::atomic_flag provenance_notice = ATOMIC_FLAG_INIT; if (!provenance_notice.test_and_set(std::memory_order_relaxed)) std::fprintf( @@ -803,18 +837,19 @@ void dkr::runtime::RT64Renderer::send_dl(const OSTask* task, std::uint8_t* rdram #if defined(__ANDROID__) { android_frame_budget::Scope decodeTiming(android_frame_budget::Region::Decoder); - f3ddkr_.process(*application_, *task, nullptr, nullptr, detail_requested ? &ordinary_models : nullptr, + f3ddkr_.process(*application_, *task, nullptr, ghost_names, + detail_requested ? &ordinary_models : nullptr, camera_requested ? camera_pass_.get() : nullptr); } android_frame_budget::report(); #else - f3ddkr_.process(*application_, *task, nullptr, nullptr, detail_requested ? &ordinary_models : nullptr, + f3ddkr_.process(*application_, *task, nullptr, ghost_names, detail_requested ? &ordinary_models : nullptr, camera_requested ? camera_pass_.get() : nullptr); #endif record_track_performance(rdram_snapshot, start); } else { track_capture_.count = 0; // A later opt-in capture must not span the idle gap. - f3ddkr_.process(*application_, *task, nullptr, nullptr, detail_requested ? &ordinary_models : nullptr, + f3ddkr_.process(*application_, *task, nullptr, ghost_names, detail_requested ? &ordinary_models : nullptr, camera_requested ? camera_pass_.get() : nullptr); } #if defined(__ANDROID__) @@ -892,6 +927,85 @@ void dkr::runtime::RT64Renderer::record_track_performance(std::uint8_t* snapshot capture.count = 0U; } +bool dkr::runtime::RT64Renderer::present_theatre_frame(std::chrono::steady_clock::time_point now) { + if (!theatre_frames_ || !theatre_frames_->last() || !time_trial::watching()) + return false; + if (time_trial::theatre_take_audio_reset()) + platform::clear_theatre_audio(); + const auto next = time_trial::theatre_next_frame(now); + if (!next) + return false; + const auto* packet = theatre_frames_->load(*next); + if (!packet) { + time_trial::theatre_archive_error(); + return false; + } + const auto previous = time_trial::progress().updates; + if (!time_trial::theatre_presented(packet->stamp.progress, *next)) + return false; + + auto& origin = *application_->core.VI_ORIGIN_REG; + const auto live = origin; + if (time_trial::exporting_video()) { + if (!ui::draw_replay_video_inputs(*application_)) { + time_trial::theatre_archive_error(); + return false; + } + + // Bind the archived display list and exact VI to this capture interval. + // Let the dedicated present thread hand off each swap independently. + origin = presentation::retail_ntsc_vi_origin(packet->stamp.framebuffer); + const auto vi = [&] { + CanonicalViPresentationScope vi_scope(*application_); + return application_->core.decodeVI(); + }(); + origin = live; + struct Capture { + unsigned frame; + unsigned pictures = 0; + bool ok = true; + } result{*next}; + RT64::PresentQueue::OfflineCapture capture{*next * 2 - 1, &result, [](void* context, std::uint32_t index) { + auto& result = *static_cast(context); + result.ok = + result.ok && index == result.pictures && + time_trial::export_video_picture(result.frame, index); + ++result.pictures; + }}; + auto& queue = *application_->presentQueue; + queue.offlineCapture.store(&capture, std::memory_order_release); + application_->state->offlineCaptureVI = &vi; + render_dl_locked(&packet->task, theatre_frames_->image(), packet->stamp.sidecar.get()); + application_->state->updateScreen(vi, true); + queue.waitForPresentId(application_->state->presentId); + queue.waitForIdle(); + application_->state->offlineCaptureVI = nullptr; + queue.offlineCapture.store(nullptr, std::memory_order_release); + + if (!result.ok || !result.pictures || + !time_trial::export_video_audio(*next, time_trial::theatre_take_audio())) { + time_trial::theatre_archive_error(); + return false; + } + return true; + } + + render_dl_locked(&packet->task, theatre_frames_->image(), packet->stamp.sidecar.get()); + origin = presentation::retail_ntsc_vi_origin(packet->stamp.framebuffer); + { + CanonicalViPresentationScope vi_scope(*application_); + application_->updateScreen(); + } + origin = live; + dkr::runtime::ui::draw(*application_); + if (time_trial::theatre_take_audio_reset()) + platform::clear_theatre_audio(); + auto samples = time_trial::theatre_take_audio(); + if (!samples.empty() && *next > previous) + platform::queue_theatre_audio(samples, time_trial::theatre().speed, previous, *next); + return true; +} + void dkr::runtime::RT64Renderer::update_screen() { #if defined(__ANDROID__) if (dkr::runtime::graphics_health::failed()) @@ -915,6 +1029,7 @@ void dkr::runtime::RT64Renderer::update_screen() { application_->sharedQueueResources->totalPresentations.load(std::memory_order_relaxed); if (completed > 0 && !first_successful_presentation_reported_) { first_successful_presentation_reported_ = true; + dkr::runtime::platform::startup_frame_presented(); #if defined(__ANDROID__) dkr::runtime::graphics_health::first_presentation.store(true); #endif @@ -960,6 +1075,10 @@ void dkr::runtime::RT64Renderer::update_screen() { // the settings UI from mutating renderer-owned caches concurrently. dkr::runtime::texture_packs::apply_pending(*application_, dkr::runtime::enhancements::modern_presentation_enabled()); + if (theatre_frames_ && theatre_frames_->last() && time_trial::watching()) { + present_theatre_frame(std::chrono::steady_clock::now()); + return; + } { CanonicalViPresentationScope vi_scope(*application_); application_->updateScreen(); @@ -971,7 +1090,8 @@ void dkr::runtime::RT64Renderer::update_screen() { // next overlay frame after the game present keeps UI work out of the // original graphics-completion critical section. dkr::runtime::ui::draw(*application_); - last_wait_presentation_ = std::chrono::steady_clock::now(); + if (!time_trial::theatre_holding_frame()) + last_wait_presentation_ = std::chrono::steady_clock::now(); observed_wait_generation_ = dkr::runtime::netplay::online_wait_generation(); observed_overlay_visible_ = dkr::runtime::ui::overlay_visible(); } @@ -982,7 +1102,10 @@ void dkr::runtime::RT64Renderer::service_online_wait_presentation() { return; #endif constexpr auto kWaitPresentationInterval = std::chrono::milliseconds(33); - if (!dkr::runtime::netplay::online_wait_active()) { + const bool waiting = dkr::runtime::netplay::online_wait_active(); + const bool replay = time_trial::watching(); + const bool restart = time_trial::restart_confirmation_pending(); + if (!waiting && !replay && !restart) { wait_replay_deferred_logged_ = false; return; } @@ -990,6 +1113,12 @@ void dkr::runtime::RT64Renderer::service_online_wait_presentation() { std::unique_lock presentation_lock(presentation_mutex_, std::try_to_lock); if (!presentation_lock.owns_lock()) return; + if (application_ && present_theatre_frame(std::chrono::steady_clock::now())) + return; + if (time_trial::exporting_video()) + return; + if (replay && !waiting && !time_trial::theatre_holding_frame() && !time_trial::theatre().buffering) + return; const bool queue_ready = application_ != nullptr && application_->state != nullptr && application_->workloadQueue != nullptr && application_->presentQueue != nullptr && application_->framebufferGraphicsWorker != nullptr && @@ -1053,7 +1182,7 @@ void dkr::runtime::RT64Renderer::service_online_wait_presentation() { application_->state->debuggerInspector.paused = previous_pause; const auto replay_elapsed = std::chrono::duration_cast(std::chrono::steady_clock::now() - replay_started); - if (replay_elapsed >= std::chrono::milliseconds(50) && replay_elapsed > slowest_wait_replay_) { + if (waiting && replay_elapsed >= std::chrono::milliseconds(50) && replay_elapsed > slowest_wait_replay_) { slowest_wait_replay_ = replay_elapsed; netplay::failure_recorder().record(netplay::FailureEventKind::ProgressWatchdog, 0U, static_cast(replay_elapsed.count()), 0U, diff --git a/runtime-recomp/src/game/rt64_renderer.hpp b/runtime-recomp/src/game/rt64_renderer.hpp index 4ca919a3..d6c9362b 100644 --- a/runtime-recomp/src/game/rt64_renderer.hpp +++ b/runtime-recomp/src/game/rt64_renderer.hpp @@ -26,6 +26,15 @@ class Registration; } // namespace dkr::runtime::netplay::experimental namespace dkr::runtime { +namespace presentation { +struct ReplayPresentation; +} +namespace time_trial { +class TheatreFrames; +} +namespace online_view { +class Pass; +} struct OwnedDecodeScratch; namespace camera { class RenderPass; @@ -63,6 +72,10 @@ class RT64Renderer final : public ultramodern::renderer::RendererContext { #endif private: + void render_dl_locked(const OSTask* task, std::uint8_t* rdram_snapshot, + const presentation::ReplayPresentation* replay = nullptr); + bool present_theatre_frame(std::chrono::steady_clock::time_point now); + std::unique_ptr theatre_frames_; void record_track_performance(std::uint8_t* snapshot, track_performance::Clock::time_point start); track_performance::Capture track_capture_{}; std::chrono::steady_clock::time_point last_android_report_{}; @@ -70,6 +83,7 @@ class RT64Renderer final : public ultramodern::renderer::RendererContext { std::unique_ptr application_; F3DDKRRT64Bridge f3ddkr_; std::unique_ptr camera_pass_; + std::unique_ptr ghost_nameplate_pass_; std::vector camera_decoder_; std::uint64_t present_count_ = 0; std::uint64_t interpolated_present_count_ = 0; diff --git a/runtime-recomp/src/game/runtime_camera_tuning_ui.inl b/runtime-recomp/src/game/runtime_camera_tuning_ui.inl index 5a45fe99..bb82b4fc 100644 --- a/runtime-recomp/src/game/runtime_camera_tuning_ui.inl +++ b/runtime-recomp/src/game/runtime_camera_tuning_ui.inl @@ -59,7 +59,7 @@ void DrawCameraTuningPanel() { const auto display = ImGui::GetIO().DisplaySize; ImGui::SetNextWindowSize({std::min(1120.F, display.x - 32.F), std::min(760.F, display.y - 32.F)}, ImGuiCond_Appearing); - if (!ImGui::Begin("MODERN CAMERA++", &open, ImGuiWindowFlags_NoCollapse)) { + if (!dkr::runtime::ui::begin_dialog_window("MODERN CAMERA++", &open, ImGuiWindowFlags_NoCollapse)) { ImGui::End(); if (!open) camplus::editor_open.store(false); diff --git a/runtime-recomp/src/game/runtime_hud_layout.cpp b/runtime-recomp/src/game/runtime_hud_layout.cpp index 6d7306fc..0e24a160 100644 --- a/runtime-recomp/src/game/runtime_hud_layout.cpp +++ b/runtime-recomp/src/game/runtime_hud_layout.cpp @@ -15,6 +15,7 @@ #include "hud_layout_config.hpp" #include "hud_basic_settings.hpp" #include "hud_reference_layout.hpp" +#include "time_trial/session.hpp" #include #include @@ -295,9 +296,11 @@ bool BeginHudPassForHolder(std::uint8_t* rdram, std::uint32_t holder) { const auto& state = g_frame_state; if (!g_group_frame || !state) return false; - const float host_aspect = state->viewport_height > 0 ? static_cast(state->viewport_width) / - static_cast(state->viewport_height) - : 4.0F / 3.0F; + // Keep the replay's sprite projection at its authored clip ratio. + // The texture-rectangle decoder widens the clip for repositioned text. + const float host_aspect = dkr::runtime::time_trial::watching() || state->viewport_height <= 0 + ? 4.0F / 3.0F + : static_cast(state->viewport_width) / state->viewport_height; return RecordHudMarker(rdram, holder, kHudPassMarkerBeginMode, dkr::runtime::hud::encode_hud_viewport_cover(host_aspect), dkr::runtime::hud::reference::kPassVariant); @@ -382,19 +385,29 @@ bool BeginWidget(std::uint8_t* rdram, std::uint32_t holder, dkr::runtime::hud::W : 4.0F / 3.0F; const bool v80 = dkr::runtime::revision_addresses::current().CurrentHud == dkr::runtime::revision_addresses::kUsV80.CurrentHud; + const auto mode = aspect > 4.0F / 3.0F && dkr::runtime::time_trial::watching() + ? dkr::runtime::hud::LayoutMode::FitToViewport + : state.mode; const auto transform = dkr::runtime::hud::reference::transform( - state.mode, aspect, + mode, aspect, dkr::runtime::hud::reference::anchor(element, widget, g_scenario, g_frame_layout == 1, g_general_pass_active, authored_x), static_cast(MEM_W(0, RdramAddress(dkr::runtime::hud_layout_symbols::for_revision(v80).hud_offset_x))), slides); - if (transform.identity()) + // The face model and its hands have separate fixed topology. Give + // each an identity for interpolation in sequential video playback. + const std::uint16_t stopwatch_token = + widget == dkr::runtime::hud::Widget::Stopwatch && element < dkr::runtime::hud::kElements.size() && + dkr::runtime::time_trial::exporting_video() + ? static_cast(1 + element + owner * dkr::runtime::hud::kElements.size()) + : 0; + if (transform.identity() && stopwatch_token == 0) return false; const auto command = static_cast(MEM_W(0, RdramAddress(holder))); if (!IsRdramPointer(command, 8)) return false; return dkr::runtime::presentation::record_presentation_marker( - command, 1, 0, 0, dkr::runtime::presentation::PresentationMarkerKind::HudWidget, transform); + command, 1, stopwatch_token, 0, dkr::runtime::presentation::PresentationMarkerKind::HudWidget, transform); } void EndWidget(std::uint8_t* rdram, std::uint32_t holder, bool& active) { if (active && rdram && IsRdramPointer(holder, 4)) { diff --git a/runtime-recomp/src/game/runtime_legacy_mods.cpp b/runtime-recomp/src/game/runtime_legacy_mods.cpp index fb542103..4a206a5b 100644 --- a/runtime-recomp/src/game/runtime_legacy_mods.cpp +++ b/runtime-recomp/src/game/runtime_legacy_mods.cpp @@ -9,6 +9,7 @@ #include "custom_records.hpp" #include "runtime_legacy_mods.hpp" #include "achievements.hpp" +#include "time_trial/session.hpp" #include "vehicle_binding.hpp" #include "vehicle_world.hpp" #include "vehicle_lighting/road_wheels.h" @@ -1950,7 +1951,7 @@ void install(legacy::ModWorld& world, std::uint8_t* ram) { extern "C" void dkr_achievements_observe(std::uint8_t* ram, unsigned revision) noexcept { using namespace dkr::runtime; - if (achievements::online_session()) + if (achievements::online_session() || time_trial::preparing_ghost()) return; try { auto sample = achievements::capture(ram, legacy::guest_memory_size(), revision); diff --git a/runtime-recomp/src/game/runtime_messages_ui.inl b/runtime-recomp/src/game/runtime_messages_ui.inl index 09f99591..32a876e1 100644 --- a/runtime-recomp/src/game/runtime_messages_ui.inl +++ b/runtime-recomp/src/game/runtime_messages_ui.inl @@ -11,7 +11,9 @@ void DrawTechnicalDetails(std::string_view diagnostic, const char* label = "Deta const auto caption = dkr::localisation::label(label); if (ImGui::CollapsingHeader(caption.c_str())) { const float height = std::clamp(ImGui::GetIO().DisplaySize.y * 0.22F, 70.0F, 180.0F); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {12.0F, 10.0F}); ImGui::BeginChild("##technical-text", {0.0F, height}, true); + ImGui::PopStyleVar(); PaddockText(PaddockReading(14.0F, false, 1.5F), PaddockRgb(0xB0C9CC), diagnostic, std::max(ImGui::GetContentRegionAvail().x, 1.0F)); ImGui::EndChild(); diff --git a/runtime-recomp/src/game/runtime_mipmap_modal.hpp b/runtime-recomp/src/game/runtime_mipmap_modal.hpp index f107521a..cde0ed7d 100644 --- a/runtime-recomp/src/game/runtime_mipmap_modal.hpp +++ b/runtime-recomp/src/game/runtime_mipmap_modal.hpp @@ -1,4 +1,5 @@ #pragma once +#include "dialog_style.hpp" #include "render/rt64_generated_mip_config.h" #include "imgui.h" #include @@ -13,9 +14,9 @@ inline void draw_mipmap_loading_modal() { ImGui::SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2{0.5F, 0.5F}); ImGui::SetNextWindowSize(ImVec2{std::max(160.0F, std::min(560.0F, viewport->WorkSize.x - 40.0F)), 0.0F}, ImGuiCond_Always); - if (ImGui::BeginPopupModal(title, nullptr, - ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | - ImGuiWindowFlags_NoSavedSettings)) { + if (begin_dialog_modal(title, nullptr, + ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoSavedSettings)) { if (!visible) ImGui::CloseCurrentPopup(); else { diff --git a/runtime-recomp/src/game/runtime_mod_library_ui.inl b/runtime-recomp/src/game/runtime_mod_library_ui.inl index 4a0af17c..d54348f9 100644 --- a/runtime-recomp/src/game/runtime_mod_library_ui.inl +++ b/runtime-recomp/src/game/runtime_mod_library_ui.inl @@ -1192,23 +1192,24 @@ void DrawDkrTrackDetails(const std::vector& tracks, bool rom_re // ------------------------------------------------------------ page controls -float PaddockImportButtonWidth(const char* label) { +float PaddockImportButtonWidth(const char* label, bool compact = false) { const auto caption = dkr::localisation::label(label); label = caption.c_str(); - const PaddockType type = PaddockSign(22.0F, 1.1F); - return std::ceil(2.0F + 12.0F + 30.0F + 12.0F + PaddockMeasure(type, label, PaddockLabelEnd(label)) + 20.0F + 2.0F); + const PaddockType type = compact ? PaddockSign(16.F, .8F) : PaddockSign(22.F, 1.1F); + return std::ceil((compact ? 50.F : 78.F) + PaddockMeasure(type, label, PaddockLabelEnd(label))); } // The painted "+ Import mods" sign (.mods-import-button). bool PaddockImportButton(const char* label, float forced_width = 0.0F, bool update_icon = false, - bool website_icon = false, int tool_icon = 0) { + bool website_icon = false, int tool_icon = 0, bool compact = false) { const auto caption = dkr::localisation::label(label); label = caption.c_str(); - const PaddockType type = PaddockSign(22.0F, 1.1F); + const PaddockType type = compact ? PaddockSign(16.F, .8F) : PaddockSign(22.F, 1.1F); const char* end = PaddockLabelEnd(label); - const float natural = PaddockImportButtonWidth(label); + const float natural = PaddockImportButtonWidth(label, compact); const float width = forced_width > 0.0F ? forced_width : natural; - const PaddockPress press = PaddockBeginPress(label, {width, 56.0F}); + const float height = compact ? 40.F : 56.F; + const PaddockPress press = PaddockBeginPress(label, {width, height}); ImDrawList* draw = ImGui::GetWindowDrawList(); PaddockPanelStyle panel; panel.radii = {8.0F, 18.0F, 8.0F, 8.0F}; @@ -1219,50 +1220,62 @@ bool PaddockImportButton(const char* label, float forced_width = 0.0F, bool upda panel.drop_offset = 4.0F; panel.highlight = PaddockRgb(0xFFFFFF, 38U); panel.highlight_width = 2.0F; + if (compact) { + panel.radii = {6.F, 12.F, 6.F, 6.F}; + panel.drop_offset = 3.F; + } PaddockPanel(draw, press.min, press.max, panel); - const float left = press.min.x + (width - natural) * 0.5F + 14.0F; - const ImVec2 symbol{left, press.min.y + 13.0F}; - PaddockFill(draw, symbol, {symbol.x + 30.0F, symbol.y + 30.0F}, PaddockRound(5.0F), PaddockCol(0x6F2B11)); + draw->PushClipRect(press.min, press.max, true); + const float icon_size = compact ? 21.F : 30.F; + const float left = press.min.x + (width - natural) * .5F + (compact ? 10.F : 14.F); + const ImVec2 symbol{left, press.min.y + (height - icon_size) * .5F}; + PaddockFill(draw, symbol, {symbol.x + icon_size, symbol.y + icon_size}, PaddockRound(5.F), PaddockCol(0x6F2B11)); + const auto icon = [&](float x, float y) -> ImVec2 { + const float scale = icon_size / 30.F; + return {symbol.x + x * scale, symbol.y + y * scale}; + }; // Two centred strokes, which a font glyph's baseline would not give // (.import-button-symbol). const ImU32 ink = PaddockCol(0xFFF3C9); if (website_icon) { - draw->AddRect({symbol.x + 7.F, symbol.y + 11.F}, {symbol.x + 19.F, symbol.y + 23.F}, ink, 2.F, 0, 2.F); - draw->AddLine({symbol.x + 13.F, symbol.y + 17.F}, {symbol.x + 23.F, symbol.y + 7.F}, ink, 2.F); - draw->AddLine({symbol.x + 16.F, symbol.y + 7.F}, {symbol.x + 23.F, symbol.y + 7.F}, ink, 2.F); - draw->AddLine({symbol.x + 23.F, symbol.y + 7.F}, {symbol.x + 23.F, symbol.y + 14.F}, ink, 2.F); + draw->AddRect(icon(7.F, 11.F), icon(19.F, 23.F), ink, 2.F, 0, 2.F); + draw->AddLine(icon(13.F, 17.F), icon(23.F, 7.F), ink, 2.F); + draw->AddLine(icon(16.F, 7.F), icon(23.F, 7.F), ink, 2.F); + draw->AddLine(icon(23.F, 7.F), icon(23.F, 14.F), ink, 2.F); } else if (tool_icon == 1) { - draw->AddLine({symbol.x + 9.F, symbol.y + 7.F}, {symbol.x + 21.F, symbol.y + 7.F}, ink, 2.F); - draw->PathArcTo({symbol.x + 15.F, symbol.y + 12.F}, 6.F, 0.F, 3.141593F, 16); + draw->AddLine(icon(9.F, 7.F), icon(21.F, 7.F), ink, 2.F); + draw->PathArcTo(icon(15.F, 12.F), icon_size * .2F, 0.F, 3.141593F, 16); draw->PathStroke(ink, 0, 2.F); - draw->AddLine({symbol.x + 9.F, symbol.y + 7.F}, {symbol.x + 9.F, symbol.y + 12.F}, ink, 2.F); - draw->AddLine({symbol.x + 21.F, symbol.y + 7.F}, {symbol.x + 21.F, symbol.y + 12.F}, ink, 2.F); - draw->AddLine({symbol.x + 15.F, symbol.y + 18.F}, {symbol.x + 15.F, symbol.y + 23.F}, ink, 2.F); - draw->AddLine({symbol.x + 10.F, symbol.y + 23.F}, {symbol.x + 20.F, symbol.y + 23.F}, ink, 2.F); + draw->AddLine(icon(9.F, 7.F), icon(9.F, 12.F), ink, 2.F); + draw->AddLine(icon(21.F, 7.F), icon(21.F, 12.F), ink, 2.F); + draw->AddLine(icon(15.F, 18.F), icon(15.F, 23.F), ink, 2.F); + draw->AddLine(icon(10.F, 23.F), icon(20.F, 23.F), ink, 2.F); } else if (tool_icon == 3) { const bool on = dkr::session_content::next_enabled.load(); - draw->AddRectFilled({symbol.x + 3.F, symbol.y + 9.F}, {symbol.x + 27.F, symbol.y + 21.F}, - PaddockCol(on ? 0x13B99B : 0x32576A), 6.F); - draw->AddCircleFilled({symbol.x + (on ? 21.F : 9.F), symbol.y + 15.F}, 4.F, ink, 16); + draw->AddRectFilled(icon(3.F, 9.F), icon(27.F, 21.F), PaddockCol(on ? 0x13B99B : 0x32576A), 6.F); + draw->AddCircleFilled(icon(on ? 21.F : 9.F, 15.F), icon_size * (4.F / 30.F), ink, 16); } else if (tool_icon == 2) { - draw->AddRect({symbol.x + 7.F, symbol.y + 7.F}, {symbol.x + 23.F, symbol.y + 23.F}, ink, 2.F, 0, 2.F); - draw->AddRect({symbol.x + 11.F, symbol.y + 7.F}, {symbol.x + 19.F, symbol.y + 13.F}, ink, 0.F, 0, 2.F); - draw->AddRect({symbol.x + 11.F, symbol.y + 17.F}, {symbol.x + 19.F, symbol.y + 23.F}, ink, 0.F, 0, 2.F); + draw->AddRect(icon(7.F, 7.F), icon(23.F, 23.F), ink, 2.F, 0, 2.F); + draw->AddRect(icon(11.F, 7.F), icon(19.F, 13.F), ink, 0.F, 0, 2.F); + draw->AddRect(icon(11.F, 17.F), icon(19.F, 23.F), ink, 0.F, 0, 2.F); + } else if (tool_icon == 4) { + draw->AddRectFilled(icon(6.F, 17.F), icon(11.F, 23.F), ink, 1.F); + draw->AddRectFilled(icon(12.5F, 8.F), icon(17.5F, 23.F), ink, 1.F); + draw->AddRectFilled(icon(19.F, 13.F), icon(24.F, 23.F), ink, 1.F); } else if (update_icon) { - draw->PathArcTo({symbol.x + 15.0F, symbol.y + 15.0F}, 8.0F, -1.4F, 3.8F, 20); + draw->PathArcTo(icon(15.0F, 15.0F), 8.0F, -1.4F, 3.8F, 20); draw->PathStroke(ink, 0, 2.0F); - draw->AddTriangleFilled({symbol.x + 13.0F, symbol.y + 4.0F}, {symbol.x + 22.0F, symbol.y + 8.0F}, - {symbol.x + 14.0F, symbol.y + 12.0F}, ink); + draw->AddTriangleFilled(icon(13.0F, 4.0F), icon(22.0F, 8.0F), icon(14.0F, 12.0F), ink); } else { - PaddockFill(draw, {symbol.x + 8.0F, symbol.y + 14.0F}, {symbol.x + 22.0F, symbol.y + 16.0F}, PaddockRound(1.0F), - ink); - PaddockFill(draw, {symbol.x + 14.0F, symbol.y + 8.0F}, {symbol.x + 16.0F, symbol.y + 22.0F}, PaddockRound(1.0F), - ink); + PaddockFill(draw, icon(8.0F, 14.0F), icon(22.0F, 16.0F), PaddockRound(1.0F), ink); + PaddockFill(draw, icon(14.0F, 8.0F), icon(16.0F, 22.0F), PaddockRound(1.0F), ink); } - const float text_top = press.min.y + (56.0F - type.line) * 0.5F; - PaddockDrawRun(draw, type, {symbol.x + 42.0F, text_top + 2.0F}, PaddockCol(0x632706), label, end); - PaddockDrawRun(draw, type, {symbol.x + 42.0F, text_top}, PaddockCol(0xFFF3C9), label, end); - PaddockEndPress(press, 18.0F); + const float text_top = press.min.y + (height - type.line) * .5F; + const float text_x = symbol.x + icon_size + (compact ? 8.F : 12.F); + PaddockDrawRun(draw, type, {text_x, text_top + 2.0F}, PaddockCol(0x632706), label, end); + PaddockDrawRun(draw, type, {text_x, text_top}, PaddockCol(0xFFF3C9), label, end); + draw->PopClipRect(); + PaddockEndPress(press, compact ? 12.F : 18.F); return press.pressed; } diff --git a/runtime-recomp/src/game/runtime_netplay.cpp b/runtime-recomp/src/game/runtime_netplay.cpp index e0852e20..0a0801ca 100644 --- a/runtime-recomp/src/game/runtime_netplay.cpp +++ b/runtime-recomp/src/game/runtime_netplay.cpp @@ -22,6 +22,7 @@ #include "online_roster_policy.hpp" #include "magic_code_policy.hpp" #include "presentation_random_policy.hpp" +#include "time_trial/session.hpp" #include "revision_addresses.hpp" #include "runtime_magic_codes.hpp" #include "runtime_platform.hpp" @@ -1962,7 +1963,8 @@ bool physical_input_poll_allowed() { void begin_presentation_random_scope() { const RuntimeSessionView view = g_session.runtime_view(); - if (host_authority_requested(view) && g_rollback_gameplay_ready.load(std::memory_order_acquire)) { + if (time_trial::active() || + (host_authority_requested(view) && g_rollback_gameplay_ready.load(std::memory_order_acquire))) { ++g_presentation_random_scope_depth; } } diff --git a/runtime-recomp/src/game/runtime_online_mods_ui.inl b/runtime-recomp/src/game/runtime_online_mods_ui.inl index 7b3bf4d1..4c1b0d1a 100644 --- a/runtime-recomp/src/game/runtime_online_mods_ui.inl +++ b/runtime-recomp/src/game/runtime_online_mods_ui.inl @@ -103,7 +103,8 @@ bool CreateOnlineLobby() { g_online_mod_notice.clear(); if (g_online_mod_sync) g_online_mod_sync->cancel(); - return FinishOnlineLobby(request, {}, 0); + g_online_mod_host_request = std::move(request); + return true; } std::vector labs; for (const auto& track : dkr::runtime::custom_tracks::tracks()) @@ -135,6 +136,9 @@ void PumpOnlineMods() { auto view = g_online_mod_sync->snapshot(); g_online_mod_notice.progress(view.stage); const auto network = session().view(); +// Cached, verified content is promoted by the existing worker, outside +// the network locks. Host transfer never enables local offline selections. +#include "netplay/session_links/mod_owner_ui.inl" if (g_stability_retry_requested && !dkr::lobby_stability::snapshot(g_online_mod_sync.get()).running) { g_stability_retry_requested = false; std::string error; @@ -170,15 +174,25 @@ void PumpOnlineMods() { if (view.phase == SyncPhase::Failed && !network.compatibility_sync_offer) ReportOnlinePreparationFailure(view.error); if (g_online_mod_host_request) { - if (network.state != ConnectionState::Offline || - g_online_mod_host_request->manifest.canonical_rom_hash != g_online_mod_identity.canonical_xxh3 || - g_online_mod_host_request->manifest.magic_codes_hash != dkr::runtime::magic_codes::selected_mask()) { + auto& pending = *g_online_mod_host_request; + if (session().active() || pending.manifest.canonical_rom_hash != g_online_mod_identity.canonical_xxh3 || + (pending.content_enabled && + pending.manifest.magic_codes_hash != dkr::runtime::magic_codes::selected_mask())) { g_online_mod_sync->cancel(); g_online_mod_host_request.reset(); g_online_action_status = "Preparation cancelled because the lobby, ROM or Magic Codes changed."; - } else if (view.phase == SyncPhase::HostReady) { - const bool modded = view.manifest && has_mods(*view.manifest); - const auto request = *g_online_mod_host_request; + } else if (!pending.content_enabled || view.phase == SyncPhase::HostReady) { + if (SharedSaveBusy()) + return; + if (!pending.cloud_account) { + pending.cloud_account = EnabledCloudSaveAccount(); + if (!pending.cloud_account->empty() && RunCloudSaveSync(*pending.cloud_account)) { + g_online_action_status = "Syncing Cloud Saves before creating the lobby..."; + return; + } + } + const bool modded = pending.content_enabled && view.manifest && has_mods(*view.manifest); + const auto request = std::move(pending); g_online_mod_host_request.reset(); if (modded && (!view.profile || !view.runtime)) { g_online_action_status = "Couldn't prepare the host's mods."; @@ -188,6 +202,9 @@ void PumpOnlineMods() { modded ? static_cast(encode(*view.manifest).size()) : 0)) { ReportOnlinePreparationFailure(g_online_action_status); g_online_mod_sync->cancel(); + } else if (!request.cloud_account->empty() && + dkr::store::service().view()->cloud_sync != dkr::cloud_saves::SyncStatus::Synced) { + g_online_action_status = "Cloud Saves could not finish. The lobby is using the local save."; } } else if (view.phase == SyncPhase::Failed) { g_online_action_status = view.error; diff --git a/runtime-recomp/src/game/runtime_online_ui.inl b/runtime-recomp/src/game/runtime_online_ui.inl index 600e92de..eae0806b 100644 --- a/runtime-recomp/src/game/runtime_online_ui.inl +++ b/runtime-recomp/src/game/runtime_online_ui.inl @@ -435,6 +435,7 @@ struct OlInputOptions { bool disabled = false; ImGuiInputTextFlags flags = 0; ImGuiInputTextCallback callback = nullptr; + float height = 44.0F; }; // A text field (.online-page input[type=text]). A controller cannot type into @@ -451,7 +452,7 @@ OlInputResult OlInput(const char* id, const char* label, char* buffer, std::size ImGui::PushFont(type.font); ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0F); ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0F); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {12.0F, std::max((44.0F - font_size) * 0.5F, 0.0F)}); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {12.0F, std::max((options.height - font_size) * 0.5F, 0.0F)}); ImGui::PushStyleColor(ImGuiCol_FrameBg, PaddockRgb(0x061D2C)); ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, PaddockRgb(0x061D2C)); ImGui::PushStyleColor(ImGuiCol_FrameBgActive, PaddockRgb(0x061D2C)); @@ -495,7 +496,7 @@ OlInputResult OlInput(const char* id, const char* label, char* buffer, std::size } ImGui::SameLine(0, 8); ImGui::BeginDisabled(options.disabled); - const bool keyboard = PaddockKeyboardButton(); + const bool keyboard = PaddockKeyboardButton(options.height); ImGui::EndDisabled(); ImGui::EndGroup(); ImGui::PopID(); @@ -1573,8 +1574,9 @@ void DrawOlHostCard(ImVec2 at, float width, float height, const OnlineFrame& fra g_online_page.section = OlSection::Settings; ImGui::EndGroup(); ImGui::SetCursorScreenPos({x, at.y + height - 2.0F - board.pad_bottom - 52.0F}); - if (OlCta("CREATE LOBBY", OlCtaColour::Green, inner, - !frame.launcher || !frame.rom_ready || frame.active || OnlineModSelectionLocked() || + const bool preparing_host = OnlineModSelectionLocked(); + if (OlCta(preparing_host ? "PREPARING LOBBY..." : "CREATE LOBBY", OlCtaColour::Green, inner, + !frame.launcher || !frame.rom_ready || frame.active || preparing_host || (dkr::online::view()->feature_enabled && !dkr::online::view()->connected) || (dkr::online::view()->public_desired && !dkr::online::view()->connected))) { g_online_page.join_attempted = false; @@ -3118,7 +3120,7 @@ void DrawOlStartBar(float width, const OnlineFrame& frame) { } if (view.host) { ImGui::SetCursorScreenPos(pair ? ImVec2{at.x + button + 10.0F, at.y} : ImVec2{at.x, at.y + 52.0F + 10.0F}); - const bool can_start = !frame.busy && total >= 2U && ready == total && saves_ready; + const bool can_start = !frame.busy && !SharedSaveBusy() && total >= 2U && ready == total && saves_ready; if (OlCta("START RACE", OlCtaColour::Red, button, !can_start)) { std::string error; if (!online.request_start(error)) diff --git a/runtime-recomp/src/game/runtime_platform.cpp b/runtime-recomp/src/game/runtime_platform.cpp index cec72d6e..99495b98 100644 --- a/runtime-recomp/src/game/runtime_platform.cpp +++ b/runtime-recomp/src/game/runtime_platform.cpp @@ -1,3 +1,4 @@ +#include "time_trial/session.hpp" #include "controller_feedback/service.hpp" #include "library_ui/surface_policy.hpp" #include "look_behind/policy.hpp" @@ -68,6 +69,9 @@ extern "C" bool dkr_handle_fullscreen_event(const SDL_Event* event); namespace { +#if DKR_RUNTIME_HAS_RT64 +void close_startup_cover(); +#endif std::atomic g_audio_buffers{0}; constexpr std::size_t kControllerCount = 4; std::array, kControllerCount> g_buttons{}; @@ -1322,6 +1326,7 @@ void dkr::runtime::platform::shutdown() { CancelSdl3InputProbe(); g_sdl3_input_client.stop(); std::scoped_lock lock(g_platform_mutex); + close_startup_cover(); if (g_cursor_hidden) { SDL_ShowCursor(SDL_ENABLE); g_cursor_hidden = false; @@ -1442,6 +1447,60 @@ ultramodern::renderer::WindowHandle dkr::runtime::platform::create_window() { #endif } +namespace { +SDL_Window* startup_cover = nullptr; +bool startup_cover_returning = false; +std::atomic startup_cover_ready{false}; +std::chrono::steady_clock::time_point startup_cover_timeout; + +void close_startup_cover() { + if (startup_cover) { + SDL_DestroyWindow(startup_cover); + startup_cover = nullptr; + } + startup_cover_returning = false; +} +} // namespace + +void dkr::runtime::platform::show_startup_cover(void* surface, bool returning) { +#if defined(_WIN32) || (defined(__linux__) && !defined(__ANDROID__)) + close_startup_cover(); + if (!surface || !g_window) + return; + int x, y, width, height; + SDL_GetWindowPosition(g_window, &x, &y); + SDL_GetWindowSize(g_window, &width, &height); + startup_cover = SDL_CreateWindow(returning ? "DKR-R Returning" : "DKR-R Starting", x, y, width, height, + SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALWAYS_ON_TOP | SDL_WINDOW_SKIP_TASKBAR | + SDL_WINDOW_TOOLTIP | SDL_WINDOW_HIDDEN); + if (!startup_cover) + return; + if (auto* pixels = SDL_GetWindowSurface(startup_cover)) { + if (SDL_BlitScaled(static_cast(surface), nullptr, pixels, nullptr) == 0) { + startup_cover_ready.store(false, std::memory_order_relaxed); + startup_cover_returning = returning; + startup_cover_timeout = std::chrono::steady_clock::now() + std::chrono::seconds(15); + SDL_ShowWindow(startup_cover); + if (SDL_UpdateWindowSurface(startup_cover) == 0) + return; + } + } + close_startup_cover(); +#else + (void)surface; + (void)returning; +#endif +} + +void dkr::runtime::platform::finish_run_return_cover() { + if (startup_cover_returning) + close_startup_cover(); +} + +void dkr::runtime::platform::startup_frame_presented() { + startup_cover_ready.store(true, std::memory_order_release); +} + ultramodern::renderer::WindowHandle dkr::runtime::platform::prepare_window_for_game() { #if defined(_WIN32) if (g_window && g_retire_launcher_window_for_game) { @@ -1500,6 +1559,8 @@ ultramodern::renderer::WindowHandle dkr::runtime::platform::prepare_window_for_g } void* dkr::runtime::platform::prepare_window_for_launcher(bool retire_game_surface) { + if (!startup_cover_returning) + close_startup_cover(); #if defined(_WIN32) if (retire_game_surface && g_window) { // Called only after both owned runtime workers and their GPU owners @@ -1550,6 +1611,9 @@ void* dkr::runtime::platform::prepare_window_for_launcher(bool retire_game_surfa } void dkr::runtime::platform::pump_window_events(void*) { + if (startup_cover && (startup_cover_ready.load(std::memory_order_acquire) || + std::chrono::steady_clock::now() >= startup_cover_timeout)) + close_startup_cover(); pump_input_backend_events(); if (dkr::runtime::ui::lifecycle_request() != dkr::runtime::ui::LifecycleRequest::None) { ultramodern::quit(); @@ -1557,6 +1621,11 @@ void dkr::runtime::platform::pump_window_events(void*) { } SDL_Event event{}; while (SDL_PollEvent(&event) != 0) { + if (startup_cover && event.type == SDL_WINDOWEVENT && event.window.windowID == SDL_GetWindowID(startup_cover)) { + if (event.window.event == SDL_WINDOWEVENT_EXPOSED) + SDL_UpdateWindowSurface(startup_cover); + continue; + } #if defined(DKR_IOS) if (event.type == SDL_APP_DIDENTERFOREGROUND) dkr::runtime::ios::import_inbox(); @@ -1875,9 +1944,8 @@ void dkr::runtime::platform::update_ui_gamepad_navigation() { #endif -void dkr::runtime::platform::queue_audio(std::int16_t* samples, std::size_t sample_count) { - if (!dkr::runtime::netplay::external_side_effects_allowed()) - return; +namespace { +void queue_audio_output(const std::int16_t* samples, std::size_t sample_count, bool mix_track_recording = true) { dkr::runtime::telemetry::record_audio_buffer(sample_count); const auto index = ++g_audio_buffers; #if DKR_RUNTIME_HAS_RT64 @@ -1945,7 +2013,7 @@ void dkr::runtime::platform::queue_audio(std::int16_t* samples, std::size_t samp } // Mixed before the equaliser and master volume, so it is heard // exactly as the game's own music would be. - const bool custom_music_active = dkr::runtime::custom_music::active(); + const bool custom_music_active = mix_track_recording && dkr::runtime::custom_music::active(); if (custom_music_active) { g_custom_music_buffer.assign(sample_count, 0.0F); dkr::runtime::custom_music::render(g_custom_music_buffer.data(), sample_count / 2U, g_audio_frequency); @@ -2000,6 +2068,83 @@ void dkr::runtime::platform::queue_audio(std::int16_t* samples, std::size_t samp #endif } +} // namespace + +void dkr::runtime::platform::queue_audio(std::int16_t* samples, std::size_t sample_count) { + if (time_trial::preparing_ghost()) + return; + if (!dkr::runtime::netplay::external_side_effects_allowed()) + return; +#if DKR_RUNTIME_HAS_RT64 + if (time_trial::watching() && sample_count != 0 && sample_count <= 8192 && (sample_count & 1U) == 0 && + custom_music::active()) { + std::scoped_lock lock(g_platform_mutex); + // Archive the host-rendered track recording on the same update as + // the guest's DMA audio. The DMA stereo pairs stay in R,L order. + g_custom_music_buffer.assign(sample_count, 0.0F); + custom_music::render(g_custom_music_buffer.data(), sample_count / 2U, g_audio_frequency); + g_audio_swap_buffer.resize(sample_count); + for (std::size_t i = 0; i < sample_count; ++i) { + const float mixed = samples[i] + g_custom_music_buffer[i ^ 1U]; + g_audio_swap_buffer[i] = static_cast(std::lround(std::clamp(mixed, -32768.0F, 32767.0F))); + } + if (time_trial::theatre_capture_audio(g_audio_swap_buffer)) + return; + } +#endif + if (!time_trial::theatre_capture_audio({samples, sample_count})) + queue_audio_output(samples, sample_count); +} + +void dkr::runtime::platform::queue_theatre_audio(std::span samples, unsigned speed, + unsigned previous, unsigned frame) { +#if DKR_RUNTIME_HAS_RT64 + unsigned rate; + { + std::scoped_lock lock(g_platform_mutex); + rate = g_audio_frequency; + } + const auto frames = samples.size() / 2; + const auto sample_at = [rate, speed](unsigned update) { return std::uint64_t(rate) * update * 100 / (30 * speed); }; + const auto output_frames = static_cast(sample_at(frame) - sample_at(previous)); + if (!frames || !output_frames) + return; + if (frames == output_frames) { + queue_audio_output(samples.data(), samples.size(), false); + return; + } + // The mixer now supplies one block per authored update. Account for + // the N64's 16-sample alignment and apply the selected viewing speed. + std::vector converted(output_frames * 2); + for (std::size_t i = 0; i < output_frames; ++i) { + const auto position = i * frames; + const auto first = position / output_frames; + const auto second = std::min(frames - 1, first + 1); + const auto weight = static_cast(position % output_frames) / static_cast(output_frames); + for (std::size_t channel = 0; channel < 2; ++channel) + converted[2 * i + channel] = static_cast( + std::lerp(samples[2 * first + channel], samples[2 * second + channel], weight)); + } + queue_audio_output(converted.data(), converted.size(), false); +#else + (void)samples; + (void)speed; + (void)previous; + (void)frame; +#endif +} + +void dkr::runtime::platform::clear_theatre_audio() { +#if DKR_RUNTIME_HAS_RT64 + std::scoped_lock lock(g_platform_mutex); + if (g_audio_device != 0) { + SDL_ClearQueuedAudio(g_audio_device); + SDL_PauseAudioDevice(g_audio_device, 1); + g_audio_playback_started = false; + } +#endif +} + void dkr::runtime::platform::request_ui_tone(float frequency_hz, std::uint32_t duration_ms) { const float clamped_frequency = std::clamp(frequency_hz, 80.0F, 4000.0F); const std::uint32_t clamped_duration = std::clamp(duration_ms, 20U, 500U); @@ -2049,6 +2194,13 @@ void dkr::runtime::platform::set_treble_gain(float decibels) { } std::size_t dkr::runtime::platform::audio_frames_remaining() { + // One authored replay update covers 735 samples at 22,050 Hz. A + // virtual AI residual of 192 selects the nearest 16-sample quantum + // (736) on the US v1.1 mixer. SDL drains on the independent playback + // clock, so its queued samples cannot provide this feedback. + constexpr std::size_t theatre_ai_residual_frames = 192U; + if (time_trial::watching()) + return theatre_ai_residual_frames; #if DKR_RUNTIME_HAS_RT64 std::scoped_lock lock(g_platform_mutex); if (g_audio_device != 0) { diff --git a/runtime-recomp/src/game/runtime_platform.hpp b/runtime-recomp/src/game/runtime_platform.hpp index badc33d9..5ffb5022 100644 --- a/runtime-recomp/src/game/runtime_platform.hpp +++ b/runtime-recomp/src/game/runtime_platform.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include "ultramodern/input.hpp" #include "ultramodern/renderer_context.hpp" #include "controller_assignment_policy.hpp" @@ -27,6 +28,9 @@ bool input_backend_switch_pending(); #if DKR_RUNTIME_HAS_RT64 ultramodern::renderer::WindowHandle create_window(); ultramodern::renderer::WindowHandle prepare_window_for_game(); +void show_startup_cover(void* surface, bool returning = false); +void finish_run_return_cover(); +void startup_frame_presented(); void* prepare_window_for_launcher(bool retire_game_surface = false); void pump_window_events(void*); void* sdl_window(); @@ -38,6 +42,8 @@ void pump_input_backend_events(); #endif void queue_audio(std::int16_t* samples, std::size_t sample_count); +void queue_theatre_audio(std::span samples, unsigned speed, unsigned previous, unsigned frame); +void clear_theatre_audio(); // Requests a short, presentation-only synthesized UI cue. Launcher cues use a // host-only audio path; in-game cues are mixed into the next host audio block. // Neither path advances or mutates DKR's emulated audio state. diff --git a/runtime-recomp/src/game/runtime_play_ui.inl b/runtime-recomp/src/game/runtime_play_ui.inl index fff7fec7..b7895562 100644 --- a/runtime-recomp/src/game/runtime_play_ui.inl +++ b/runtime-recomp/src/game/runtime_play_ui.inl @@ -403,55 +403,84 @@ void DrawLanguageSetting(float); #include "library_ui/automatic_ui.inl" #include "library_ui/handoff_ui.inl" -void DrawPlayLaunchOptions(float width, bool entered, bool live) { +void DrawPlayPortableSetting(float width, bool entered, bool live) { + if (!dkr::runtime::portable::supported()) + return; + // Inspect only on page entry or an explicit click, never per-frame I/O. + static bool portable_enabled = false; + static std::string portable_status; + if (entered) + portable_enabled = dkr::runtime::portable::enabled(); ImGui::BeginDisabled(live); - if (PaddockCheckbox("##skip-intro", "Skip intro", &g_skip_intro, width)) { - SaveSettings(); + if (PaddockCheckbox("##portable-mode", "Portable mode", &portable_enabled, width)) { + if (!dkr::runtime::portable::set_enabled(portable_enabled, portable_status)) + portable_enabled = dkr::runtime::portable::enabled(); + else + portable_status.clear(); + } + ImGui::EndDisabled(); + const auto help = PaddockReading(13.F, false, 1.4F); + PaddockText(help, PaddockRgb(0xB0C9CC), "Keep saves and settings beside DKR-R.", width); + if (!portable_status.empty()) + DrawIssue(portable_status, dkr::runtime::copy::Area::Portable); + if (portable_enabled != dkr::runtime::portable::enabled_at_startup()) { + PaddockGap(4.F); + PaddockText(help, PaddockRgb(0xFFAB14), "Restart DKR-R to apply.", width); + PaddockText(help, PaddockRgb(0xB0C9CC), "Existing saves aren't moved automatically.", width); + } + PaddockGap(6.F); +} + +void SettingsLabel(std::string_view label, float width); + +void DrawPlayLaunchOptions(float width, bool entered, bool live) { + constexpr float gap = 14.F; + const bool paired = width >= 318.F; + const float column = paired ? (width - gap) * .5F : width; + const auto at = ImGui::GetCursorScreenPos(); + const float fields_x = paired ? at.x + column + gap : at.x; + const auto draw_skip_intro = [&] { + ImGui::BeginDisabled(live); + if (PaddockCheckbox("##skip-intro", "Skip intro", &g_skip_intro, column)) + SaveSettings(); + ImGui::EndDisabled(); + }; + + ImGui::BeginGroup(); + DrawPlayPortableSetting(column, entered, live); + DrawSkipLauncherSetting(column); + ImGui::EndGroup(); + const float startup_bottom = ImGui::GetItemRectMax().y; + + if (paired) { + ImGui::SetCursorScreenPos({fields_x, at.y}); + } else { + PaddockGap(6.F); + draw_skip_intro(); + PaddockGap(10.F); } + + ImGui::BeginGroup(); + DrawLanguageSetting(column); + const float pair_top = std::max(startup_bottom, ImGui::GetCursorScreenPos().y) + 8.F; + float skip_y = pair_top; if (g_skip_intro) { - PaddockGap(12.0F); - if (SettingsDropdown("skip-intro-destination", "Start at", &g_skip_intro_destination, - {"Start menu", "Character select"}, width, false, {})) + ImGui::SetCursorScreenPos({fields_x, pair_top}); + SettingsLabel("Start at", column); + // Match the centres of the 42 px checkbox row and the 52 px field. + skip_y = ImGui::GetCursorScreenPos().y + 5.F; + if (SettingsDropdown("skip-intro-destination", {}, &g_skip_intro_destination, + {"Start menu", "Character select"}, column, live, {})) SaveSettings(); + PaddockGap(5.F); + PaddockText(PaddockReading(13.F, false, 1.4F), PaddockRgb(0xB0C9CC), "Offline launches only.", column); } - PaddockGap(8.0F); - if (g_skip_intro) - PaddockText(PaddockReading(14.0F, false, 1.5F), PaddockRgb(0xB0C9CC), "Offline launches only.", width); - PaddockGap(16.0F); - if (dkr::runtime::portable::supported()) { - // Inspect only on page entry or an explicit click, never per-frame I/O. - static bool portable_enabled = false; - static std::string portable_status; - if (entered) - portable_enabled = dkr::runtime::portable::enabled(); - if (PaddockCheckbox("##portable-mode", "Portable mode", &portable_enabled, width)) { - std::string error; - if (!dkr::runtime::portable::set_enabled(portable_enabled, error)) { - portable_enabled = dkr::runtime::portable::enabled(); - portable_status = std::move(error); - } else { - portable_status = "Restart DKR-R to apply. Existing saves aren't moved automatically."; - } - } - PaddockGap(8.0F); - PaddockText(PaddockReading(14.0F, false, 1.5F), PaddockRgb(0xB0C9CC), "Keep saves and settings beside DKR-R.", - width); - if (portable_enabled != dkr::runtime::portable::enabled_at_startup()) { - PaddockText(PaddockReading(14.0F, true, 1.5F), PaddockRgb(0xFFAB14), "Restart DKR-R to apply.", width); - } - if (!portable_status.empty()) { - if (dkr::runtime::copy::looks_like_error(portable_status)) - DrawIssue(portable_status, dkr::runtime::copy::Area::Portable); - else - PaddockText(PaddockReading(14.0F, false, 1.5F), PaddockRgb(0xB0C9CC), - "Existing saves aren't moved automatically.", width); - } - PaddockGap(16.0F); + ImGui::EndGroup(); + + if (paired) { + ImGui::SetCursorScreenPos({at.x, skip_y}); + draw_skip_intro(); } - ImGui::EndDisabled(); - DrawSkipLauncherSetting(width); - DrawLanguageSetting(width); - DrawPlaySaveSummary(width, live); } #include "library_ui/play_launch_bar.inl" @@ -525,19 +554,21 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live const std::size_t count = play.rom_catalog.size(); const ImVec2 at = ImGui::GetCursorScreenPos(); ImDrawList* draw = ImGui::GetWindowDrawList(); - // The pass fills the panel, but its lights and ROM controls remain a - // readable, centred group. Narrow panels retain their existing layout. - constexpr float pass_chrome = 2.0F * 2.0F + 24.0F * 2.0F + 42.0F + 20.0F; + constexpr float panel_padding = 20.F, column_gap = 24.F; + constexpr float light_width = 42.F, light_gap = 16.F; + constexpr float pass_chrome = 2.F * panel_padding + light_width + light_gap; constexpr float rom_picker_width = 560.0F; - const bool side = width >= 780.F; - const float options_width = side ? std::clamp(width * .36F, 330.F, 640.F) : std::max(1.F, width - 52.F); - const float slot_width = side ? width - options_width - 32.F : width; + const bool side = width >= 720.F; + const float inner = std::max(1.F, width - 2.F * panel_padding); + const float options_width = side ? std::clamp(inner * .48F, 318.F, 690.F) : inner; + const float slot_width = side ? width - options_width - panel_padding - column_gap : width; const float content_width = std::min(slot_width, rom_picker_width + pass_chrome); const float content_x = at.x + std::floor((slot_width - content_width) * .5F); ImDrawListSplitter pass_layers; pass_layers.Split(draw, 2); pass_layers.SetCurrentChannel(draw, 1); - const float body_x = content_x + 2.0F + 24.0F + 42.0F + 20.0F; + const float content_left = content_x + panel_padding; + const float body_x = content_left + light_width + light_gap; const float body_width = std::max(content_width - pass_chrome, 1.0F); const PaddockType heading = PaddockSign(19.0F, 1.0F, 0.0F); const PaddockType file_type = PaddockReading(15.0F, true, 1.5F); @@ -566,19 +597,20 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live const char* secondary = !state.removed.empty() ? "Undo##rom" : count > 0U && ready ? "Remove from list##rom" : nullptr; - const float primary_width = std::max(240.0F, PaddockRaceButtonWidth(primary, 19.0F, 0.12F)); - const float secondary_width = secondary != nullptr ? PlayTextButtonWidth(secondary) : 0.0F; - const bool actions_row = secondary == nullptr || primary_width + 16.0F + secondary_width <= body_width; - const float actions_height = actions_row ? 46.0F : 46.0F + 8.0F + 44.0F; + const float primary_width = std::max(168.F, PaddockRaceButtonWidth(primary, 19.F, .12F)); + const float secondary_width = secondary != nullptr ? PlayTextButtonWidth(secondary) : 0.F; + constexpr float action_gap = 12.F; + const float content_inner = std::max(1.F, content_width - 2.F * panel_padding); + const float actions_width = primary_width + (secondary ? action_gap + secondary_width : 0.F); + const bool actions_row = actions_width <= content_inner; + const float action_x = + actions_row ? std::max(content_left, body_x - std::max(0.F, actions_width - body_width)) : body_x; + const float actions_height = actions_row || !secondary ? 46.F : 46.F + 6.F + 44.F; const float pick_width = std::min(body_width, rom_picker_width); const float pick_height = 4.0F + pick_label.line + 6.0F + 60.0F + 8.0F; const auto no_rom = dkr::localisation::source("Choose a Diddy Kong Racing ROM to start."); const float detail_height = count > 0U ? pick_height : PaddockTextHeight(file_type, no_rom, body_width); const float meta_height = PaddockTextHeight(meta_type, meta, body_width); - const float body_height = - 6.0F + heading.line + 8.0F + detail_height + 2.0F + meta_height + 16.0F + actions_height; - const float height = 2.0F + 20.0F + std::max(112.0F, body_height) + 20.0F + 2.0F; - // The border turns green with the last light. const float since = static_cast(PaddockClock() - state.arrived_at); ImU32 border = PaddockRgb(ready ? 0x1AC2A3U : 0xE82E21U); @@ -590,7 +622,7 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live panel.fill = PaddockRgb(0x0B2E40, 245U); panel.border = border; panel.border_width = 2.0F; - DrawPlayLights(draw, {content_x + 2.0F + 24.0F, at.y + 2.0F + 20.0F}, ready, state.arrived_at); + DrawPlayLights(draw, {content_left, at.y + panel_padding}, ready, state.arrived_at); float y = at.y + 2.0F + 20.0F + 6.0F; const auto title = dkr::localisation::source(ready ? "Ready to race" : "ROM not loaded"); @@ -629,9 +661,9 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live PaddockTextStyle meta_style; meta_style.colour = PaddockCol(meta_colour); PaddockTextAt(draw, meta_type, {body_x, y}, body_width, meta, meta_style); - y += meta_height + 16.0F; + y += meta_height + 10.F; - ImGui::SetCursorScreenPos({body_x, y}); + ImGui::SetCursorScreenPos({action_x, y}); if (state.focus == PlayPageState::Focus::Browse && !ready) { if (nav) ImGui::SetKeyboardFocusHere(); @@ -642,12 +674,13 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live look.hover_in = 0.12F; look.ellipsis_spread = 0.12F; ImGui::BeginDisabled(live || lobby || launch_modal); - if (PaddockRaceButton(primary, {std::min(body_width, primary_width), 46.0F}, look)) { + const float action_width = std::clamp(content_left + content_inner - action_x, 1.F, primary_width); + if (PaddockRaceButton(primary, {action_width, 46.F}, look)) { OpenRomBrowser(play.selected_rom); } if (secondary != nullptr) { - ImGui::SetCursorScreenPos(actions_row ? ImVec2{body_x + primary_width + 16.0F, y + 1.0F} - : ImVec2{body_x - 8.0F, y + 46.0F + 8.0F}); + ImGui::SetCursorScreenPos(actions_row ? ImVec2{action_x + primary_width + action_gap, y + 1.F} + : ImVec2{body_x, y + 46.F + 6.F}); if (state.removed.empty()) { ImGui::BeginDisabled(lobby || launch_modal); if (PlayTextButton(secondary, true)) { @@ -664,23 +697,27 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live } ImGui::EndDisabled(); ImGui::PopStyleColor(); - const float options_x = side ? at.x + width - options_width - 26.F : at.x + 26.F; - const float tools_width = side ? options_x - at.x - 58.F : width - 52.F; - const float tools_height = PlayToolsHeight(tools_width); - const float left_height = height + tools_height + 16.F; - const float options_y = side ? at.y + 26.F : at.y + left_height + 8.F; + ImGui::SetCursorScreenPos({content_left, y + actions_height + 14.F}); + ImGui::BeginGroup(); + DrawPlaySaveSummary(content_inner, live, launch_modal); + ImGui::EndGroup(); + const float resume_bottom = ImGui::GetItemRectMax().y; + + const float options_x = side ? at.x + width - panel_padding - options_width : at.x + panel_padding; + const float options_y = side ? at.y + panel_padding : resume_bottom + 6.F; ImGui::SetCursorScreenPos({options_x, options_y}); ImGui::BeginGroup(); DrawPlayLaunchOptions(options_width, entered, live); ImGui::EndGroup(); - const float options_height = ImGui::GetItemRectSize().y; - const float final_height = - side ? std::max(left_height, options_height + 52.F) : left_height + options_height + 34.F; - ImGui::SetCursorScreenPos({at.x + 26.F, at.y + (side ? final_height : left_height) - 26.F - tools_height}); - DrawPlayTools(tools_width); + const float tools_y = std::max(resume_bottom, ImGui::GetItemRectMax().y) + 8.F; + const float tools_width = std::max(1.F, width - 36.F); + ImGui::SetCursorScreenPos({at.x + 18.F, tools_y + 10.F}); + DrawPlayTools(tools_width, live); + const float final_height = ImGui::GetItemRectMax().y + 18.F - at.y; + draw->AddLine({at.x + 18.F, tools_y}, {at.x + width - 18.F, tools_y}, PaddockCol(0x325365)); if (side) - draw->AddLine({options_x - 16.F, at.y + 26.F}, {options_x - 16.F, at.y + final_height - 26.F}, - PaddockCol(0x325365)); + draw->AddLine({options_x - column_gap * .5F, at.y + panel_padding}, + {options_x - column_gap * .5F, tools_y - 8.F}, PaddockCol(0x325365)); pass_layers.SetCurrentChannel(draw, 0); PaddockPanel(draw, at, {at.x + width, at.y + final_height}, panel); pass_layers.Merge(draw); diff --git a/runtime-recomp/src/game/runtime_quick_restart.cpp b/runtime-recomp/src/game/runtime_quick_restart.cpp index 0fbe4545..39c2f698 100644 --- a/runtime-recomp/src/game/runtime_quick_restart.cpp +++ b/runtime-recomp/src/game/runtime_quick_restart.cpp @@ -4,6 +4,7 @@ #include "game_payload.hpp" #include "runtime_enhancements.hpp" #include "runtime_input.hpp" +#include "time_trial/session.hpp" #include "revision_addresses.hpp" #include "recomp.h" @@ -63,6 +64,9 @@ extern "C" void dkr_quick_restart_poll(std::uint8_t* rdram, recomp_context* cont return; } + if (dkr::runtime::time_trial::request_restart()) + return; + const dkr::runtime::GamePayload* payload = dkr::runtime::active_payload(); if (payload == nullptr || payload->get_settings == nullptr || payload->leveltable_type == nullptr || payload->sound_clear_delayed == nullptr || payload->reset_delayed_text == nullptr || diff --git a/runtime-recomp/src/game/runtime_save_routing.cpp b/runtime-recomp/src/game/runtime_save_routing.cpp index 08639a7e..189abcb0 100644 --- a/runtime-recomp/src/game/runtime_save_routing.cpp +++ b/runtime-recomp/src/game/runtime_save_routing.cpp @@ -3,6 +3,7 @@ #include "netplay/netplay_types.hpp" #include "save_manager.hpp" #include "save_storage.hpp" +#include "shared_saves.hpp" #include "ultramodern/ultramodern.hpp" @@ -17,7 +18,8 @@ dkr::runtime::saves::RuntimeOnlineSaveStatus g_runtime_save_status; struct SaveContext { std::filesystem::path path, paks; std::shared_ptr lease; - bool online = false, host = false, loaded = false, incomplete = false, development = false; + bool online = false, host = false, loaded = false, incomplete = false, development = false, time_trial = false; + dkr::runtime::saves::ReplaySave replay_save = dkr::runtime::saves::ReplaySave::Blank; std::uint64_t match = 0, hash = 0; std::string failure; }; @@ -104,7 +106,7 @@ bool dkr::runtime::saves::prepare_runtime_save_context(const std::filesystem::pa std::uint64_t match, std::uint64_t hash, std::string& error, bool development) { std::scoped_lock lock(g_runtime_save_mutex); - if (g_context.lease) { + if (g_context.lease || g_context.time_trial) { error = "The previous save owner has not retired."; return false; } @@ -144,6 +146,19 @@ bool dkr::runtime::saves::prepare_runtime_save_context(const std::filesystem::pa error.clear(); return true; } + +bool dkr::runtime::saves::prepare_time_trial_save_context(std::string& error, ReplaySave seed) { + std::scoped_lock lock(g_runtime_save_mutex); + if (g_context.lease || g_context.time_trial) { + error = "The previous save owner has not retired."; + return false; + } + g_context = {}; + g_context.time_trial = true; + g_context.replay_save = seed; + return true; +} + void dkr::runtime::saves::retire_runtime_save_context() { std::scoped_lock lock(g_runtime_save_mutex); g_context = {}; @@ -152,6 +167,8 @@ void dkr::runtime::saves::retire_runtime_save_context() { } bool dkr::runtime::saves::runtime_save_context_ready() { std::scoped_lock lock(g_runtime_save_mutex); + if (g_context.time_trial) + return g_context.loaded && ultramodern::get_save_file_path().empty(); if (!g_context.lease || !g_context.loaded || !g_context.failure.empty()) return false; // Verify what init_saving actually loaded, not a second proposed route. @@ -189,6 +206,24 @@ dkr::runtime::saves::RuntimeSaveSelection dkr::runtime::saves::runtime_save_sele } bool dkr::runtime::saves::load_runtime_save(const std::filesystem::path& path, std::vector& buffer) { std::scoped_lock lock(g_runtime_save_mutex); + if (g_context.time_trial) { + if (!path.empty()) { + g_context.failure = "Time Trial cannot load a file-backed save."; + return false; + } + if (g_context.replay_save == ReplaySave::MissingAdventure) { + // Match the runtime's missing-file boot. Reads and writes stay in memory. + buffer.assign(codec::kImageSize, 0); + } else { + auto image = codec::blank_image(); + if (g_context.replay_save == ReplaySave::CompletedAdventure) + shared::complete(image, 0); + const auto bytes = codec::encode(image); + buffer.assign(bytes.begin(), bytes.end()); + } + g_context.loaded = true; + return true; + } std::vector bytes; if (!g_context.lease || storage::absolute(path) != g_context.path) { g_context.failure = "The runtime tried to load a save outside its launch scope."; @@ -217,6 +252,8 @@ bool dkr::runtime::saves::load_runtime_save(const std::filesystem::path& path, s } bool dkr::runtime::saves::commit_runtime_save(const std::filesystem::path& path, const std::vector& buffer) { std::scoped_lock lock(g_runtime_save_mutex); + if (g_context.time_trial) + return false; if (!g_context.lease || !g_context.loaded || storage::absolute(path) != g_context.path) { g_context.failure = "A stale save write was refused outside its launch scope."; return false; @@ -237,7 +274,7 @@ bool dkr::runtime::saves::commit_runtime_save(const std::filesystem::path& path, return true; } std::string error; - if (!storage::write_atomic(path, bytes, ValidRuntimeImage, error)) { + if (!storage::write_progress(path, bytes, ValidRuntimeImage, error)) { g_context.failure = error; std::fprintf(stderr, "[save][commit] %s\n", error.c_str()); return false; diff --git a/runtime-recomp/src/game/runtime_save_routing.hpp b/runtime-recomp/src/game/runtime_save_routing.hpp index c90dc051..91bdeb8f 100644 --- a/runtime-recomp/src/game/runtime_save_routing.hpp +++ b/runtime-recomp/src/game/runtime_save_routing.hpp @@ -23,6 +23,8 @@ bool prepare_runtime_save_context(const std::filesystem::path& root, const std:: const std::filesystem::path& offline_paks, bool online, bool host, std::uint64_t match_id, std::uint64_t expected_hash, std::string& error, bool development = false); +enum class ReplaySave { Blank, MissingAdventure, CompletedAdventure }; +bool prepare_time_trial_save_context(std::string& error, ReplaySave seed); void retire_runtime_save_context(); bool runtime_save_context_ready(); bool runtime_save_writes_allowed(); diff --git a/runtime-recomp/src/game/runtime_saves_ui.inl b/runtime-recomp/src/game/runtime_saves_ui.inl index b4eb76f0..e6f5baf8 100644 --- a/runtime-recomp/src/game/runtime_saves_ui.inl +++ b/runtime-recomp/src/game/runtime_saves_ui.inl @@ -3,25 +3,20 @@ // repairs, resets and the Save Builder go through dkr::runtime::saves exactly // as before. // -// SAVE MANAGER in the look of tools/launcher-html (pages/saves.js, -// styles/saves.css): the current save, then Overview / Edit progress / -// Transfer & Paks. Edits stay in a draft until they are applied, and every -// replacing action asks first. +// The slot list and editor share each scope's draft. File operations and +// quick actions keep the same confirmation and backup flow. + +enum class SaveEditorSection { Progress, Unlocks, Files }; struct SavesPageState { ImGuiContext* context = nullptr; int last_frame = -100; - int section = 0; // Overview, Edit progress, Transfer & Paks - int scope = 0; // Offline, Online, Modded, Recovery - int tab = 0; // Slot 1-3, Unlocks, Records - std::array courses_open{}; - std::array records_open{}; - bool all_backups = false; - // The save as it was loaded into the builder, to tell a draft's changes. - std::optional original; - // The slot summaries on Overview, read again with the view cache. - std::optional summary; - std::chrono::steady_clock::time_point summary_at{}; + SaveEditorSection section = SaveEditorSection::Progress; + int scope = 0; // Vanilla, Online, Modded, Recovery + bool personal_modded = false; + bool import_modded = false; + int selected_slot = 0; + bool scroll_editor_to_top = false; // The confirmation in flight. enum class Ask { None, @@ -45,9 +40,8 @@ struct SavesPageState { SavesPageState g_saves_page; constexpr unsigned kSavesAccent = 0x1AC2A3; -constexpr unsigned kSavesError = 0xFFAAA0; -enum class SavesTone { Plain, Primary, Danger }; +enum class SavesTone { Plain, Primary, Featured, Danger }; // .saves-button: a race button on the page's quiet #123e50, or the accent // primary, or the danger red. @@ -60,6 +54,9 @@ bool SavesRaceButton(const char* label, float width = 0.0F, SavesTone tone = Sav look.border = kSavesAccent; look.text = 0x062C30; look.text_shadow = false; + } else if (tone == SavesTone::Featured) { + look.fill = 0xAD481C; + look.border = kSetWarm; } else if (tone == SavesTone::Danger) { look.fill = 0x73171A; look.border = 0xD97773; @@ -116,76 +113,13 @@ std::string SavesBackupTime(const std::filesystem::path& path) { return text; } -bool SavesDraftDirty() { +bool SavesDraftDirty(const AdventureDraft& draft) { using dkr::runtime::saves::codec::encode; - return g_save_builder_image && g_saves_page.original && - encode(*g_save_builder_image) != encode(*g_saves_page.original); -} - -void SavesForgetDraft() { - g_save_builder_image.reset(); - g_saves_page.original.reset(); - g_saves_page.summary.reset(); + return draft.image && draft.original && encode(*draft.image) != encode(*draft.original); } // ------------------------------------------------------------ editor -// A row of quiet tabs over a hairline (.saves-tabs). -int SavesEditorTabs(const std::vector& labels, int current, float width) { - const PaddockType type = PaddockSign(17.0F, 1.2F, 0.0F); - const ImVec2 at = ImGui::GetCursorScreenPos(); - ImDrawList* draw = ImGui::GetWindowDrawList(); - float natural = 8.0F + 4.0F * static_cast(labels.size() - 1U); - std::vector widths; - for (const char* label : labels) { - widths.push_back(std::ceil(PaddockMeasure(type, label) + 28.0F)); - natural += widths.back(); - } - // flex: 1 0 auto shares the spare room between the tabs. - const float spare = std::max(width - natural, 0.0F) / static_cast(labels.size()); - int picked = -1; - float x = at.x + 4.0F; - for (std::size_t index = 0; index < labels.size(); ++index) { - const float tab_width = widths[index] + spare; - ImGui::SetCursorScreenPos({x, at.y + 4.0F}); - ImGui::PushID(static_cast(index)); - const PaddockPress press = PaddockBeginPress("##tab", {tab_width, 44.0F}); - ImGui::PopID(); - if (press.pressed) - picked = static_cast(index); - const bool selected = static_cast(index) == current; - const PaddockRadii radii{6.0F, 6.0F, 0.0F, 0.0F}; - if (selected) { - PaddockFill(draw, press.min, press.max, radii, PaddockCol(0x123E50)); - } else if (press.hover > 0.0F) { - PaddockFill(draw, press.min, press.max, radii, - PaddockApply(PaddockMix(PaddockRgb(0x174C60, 0U), PaddockRgb(0x174C60), press.hover))); - } - if (selected) { - draw->AddRectFilled({press.min.x, press.max.y - 3.0F}, press.max, PaddockCol(kSetWarm)); - } - const unsigned ink = selected ? 0xFFF0C2U : press.hover > 0.5F ? kSetText : kSetMuted; - const float text_width = PaddockMeasure(type, labels[index]); - PaddockDrawRun(draw, type, - {std::round(press.min.x + (tab_width - text_width) * 0.5F), - std::round(press.min.y + (44.0F - 3.0F - type.line) * 0.5F)}, - PaddockCol(ink), labels[index], labels[index] + std::strlen(labels[index])); - PaddockEndPress(press, 6.0F, 1.0F, false); - if (press.focused) { - draw->AddRect({press.min.x + 1.5F, press.min.y + 1.5F}, {press.max.x - 1.5F, press.max.y - 1.5F}, - PaddockCol(kSetFocus), 6.0F, 0, 3.0F); - } - x += tab_width + 4.0F; - } - const float bottom = at.y + 4.0F + 44.0F; - draw->AddRectFilled({at.x, bottom}, {at.x + width, bottom + 1.0F}, PaddockCol(kSetBorder)); - ImGui::SetCursorScreenPos(at); - ImGui::Dummy({width, bottom + 1.0F - at.y}); - return picked; -} - -// A grid of settings (.saves-setting-grid): three columns, two below 780 px of -// panel and one below 540 px. struct SavesGrid { int count = 0; ImVec2 origin{}; @@ -195,7 +129,7 @@ struct SavesGrid { float row_bottom = 0.0F; SavesGrid(float width, float panel) : origin(ImGui::GetCursorScreenPos()) { - per_row = panel <= 540.0F ? 1 : panel <= 780.0F ? 2 : 3; + per_row = panel < 375.0F ? 1 : panel < 545.0F ? 2 : 3; column = std::floor((width - 16.0F * static_cast(per_row - 1)) / static_cast(per_row)); row_top = row_bottom = origin.y; } @@ -219,14 +153,27 @@ struct SavesGrid { } }; -void DrawSavesSlotEditor(SavesPageState& state, float width, float panel, int slot_index) { +void DrawSavesSlotEditor(SavesPageState& state, float outer, int slot_index) { using namespace dkr::runtime::saves::codec; - AdventureSlot& slot = g_save_builder_image->slots[static_cast(slot_index)]; + AdventureSlot& slot = g_adventure_drafts[state.personal_modded].image->slots[static_cast(slot_index)]; ImGui::PushID(slot_index); - PaddockText(PaddockSign(19.0F, 1.45F, 0.0F), PaddockRgb(kSetText), "Racer initials", width); - PaddockGap(13.0F); + const auto paint = [](ImDrawList* draw, ImVec2 min, ImVec2 max) { + PaddockPanel(draw, min, max, {PaddockRound(9.0F), PaddockRgb(0x102E40), PaddockRgb(kSetBorder), 1.0F}); + }; + const auto title = [](const char* caption, float width) { + PaddockText(PaddockSign(19.0F, 1.2F, 0.0F), PaddockRgb(kSetText), caption, width); + PaddockGap(8.0F); + }; + + PaddockBox balloon_box(outer, {10.0F, 10.0F}); + const float width = balloon_box.Inner(); + title("Golden balloons", width); + const auto summary = ImGui::GetCursorScreenPos(); + const float initials_width = std::min(width, 290.0F); + PaddockText(PaddockReading(16.0F, true, 1.25F), PaddockRgb(kSetText), "Racer initials", initials_width); + PaddockGap(6.0F); { - // Three letter pickers, 280 px wide together (.saves-initials). + // Three letter pickers sized for the widest initial (.saves-initials). static const std::vector kLetters = [] { std::vector letters; for (char letter = 'A'; letter <= 'Z'; ++letter) @@ -238,7 +185,7 @@ void DrawSavesSlotEditor(SavesPageState& state, float width, float panel, int sl }(); std::string padded = sanitise_name(slot.name); padded.resize(3U, ' '); - const float cell = std::floor((std::min(width, 280.0F) - 16.0F) / 3.0F); + const float cell = std::floor((initials_width - 16.0F) / 3.0F); const ImVec2 at = ImGui::GetCursorScreenPos(); for (int character = 0; character < 3; ++character) { ImGui::SetCursorScreenPos({at.x + (cell + 8.0F) * static_cast(character), at.y}); @@ -261,26 +208,26 @@ void DrawSavesSlotEditor(SavesPageState& state, float width, float panel, int sl } ImGui::SetCursorScreenPos({at.x, at.y + 52.0F}); ImGui::Dummy({width, 0.0F}); - PaddockGap(20.0F); } - - SavesSeparator("Golden Balloons", width, false); + const float letters_bottom = ImGui::GetCursorScreenPos().y; + const bool inline_total = width >= initials_width + 170.0F; + const float total_width = inline_total ? width - initials_width - 16.0F : width; + if (inline_total) + ImGui::SetCursorScreenPos({summary.x + initials_width + 16.0F, summary.y + 24.0F}); + else + PaddockGap(8.0F); int hub = static_cast(hub_balloons(slot)); const unsigned bonus = bonus_balloons(slot); - SavesNote(bonus > 0U ? "Up to 7 on the central island and 8 in each world. Remove the bonus balloons before " - "lowering the central island." - : "Up to 7 on the central island and 8 in each world. The total updates automatically.", - width); { // The total (.saves-progress): a dark bar that fills amber. const ImVec2 at = ImGui::GetCursorScreenPos(); ImDrawList* draw = ImGui::GetWindowDrawList(); - PaddockFill(draw, at, {at.x + width, at.y + 32.0F}, PaddockRound(6.0F), PaddockCol(0x153E50)); + PaddockFill(draw, at, {at.x + total_width, at.y + 32.0F}, PaddockRound(6.0F), PaddockCol(0x153E50)); const float t = std::min(1.0F, static_cast(slot.balloons[0]) / static_cast(kMaximumTotalBalloons)); if (t > 0.0F) { - draw->PushClipRect(at, {at.x + width * t, at.y + 32.0F}, true); - PaddockFill(draw, at, {at.x + width, at.y + 32.0F}, PaddockRound(6.0F), PaddockCol(0x806000)); + draw->PushClipRect(at, {at.x + total_width * t, at.y + 32.0F}, true); + PaddockFill(draw, at, {at.x + total_width, at.y + 32.0F}, PaddockRound(6.0F), PaddockCol(0x806000)); draw->PopClipRect(); } std::string total = std::to_string(slot.balloons[0] - bonus) + " / " + std::to_string(kMaximumTotalBalloons); @@ -288,16 +235,20 @@ void DrawSavesSlotEditor(SavesPageState& state, float width, float panel, int sl total += " + " + std::to_string(bonus) + " bonus"; const PaddockType type = PaddockReading(16.0F, true, 1.0F); const float text_width = PaddockMeasure(type, total); - PaddockDrawRun(draw, type, - {std::round(at.x + (width - text_width) * 0.5F), std::round(at.y + (32.0F - type.line) * 0.5F)}, - PaddockCol(kSetText), total.data(), total.data() + total.size()); - ImGui::Dummy({width, 32.0F}); + PaddockDrawRun( + draw, type, + {std::round(at.x + (total_width - text_width) * 0.5F), std::round(at.y + (32.0F - type.line) * 0.5F)}, + PaddockCol(kSetText), total.data(), total.data() + total.size()); + ImGui::Dummy({total_width, 32.0F}); + const float total_bottom = ImGui::GetItemRectMax().y; + ImGui::SetCursorScreenPos({summary.x, std::max(letters_bottom, total_bottom)}); + ImGui::Dummy({width, 0.0F}); PaddockGap(18.0F); } constexpr std::array kAreas{ - {"DKR-R", "Dino Domain", "Sherbet Island", "Snowflake Mountain", "Dragon Forest", "Future Fun Land"}}; + {"Central island", "Dino Domain", "Sherbet Island", "Snowflake Mountain", "Dragon Forest", "Future Fun Land"}}; const auto count = [](int value) { return SettingsRangeValue{std::to_string(value), ""}; }; - SavesGrid balloons(width, panel); + SavesGrid balloons(width, width); for (std::size_t area = 0; area < kWorldCount; ++area) { balloons.Begin(); ImGui::PushID(static_cast(area)); @@ -318,26 +269,49 @@ void DrawSavesSlotEditor(SavesPageState& state, float width, float panel, int sl } balloons.Finish(width); - SavesSeparator("Bonus balloons", width, false); - SavesNote("Extra balloons from the Free Balloon magic code. They need a full central island.", width); - SavesGrid extra(width, panel); - extra.Begin(); + const auto bonus_row = ImGui::GetCursorScreenPos(); + const float remove_width = SettingsButtonWidth("Remove bonus balloons"); + const bool inline_bonus = width >= remove_width + 180.0F; int bonus_value = static_cast(bonus_balloons(slot)); const int bonus_limit = static_cast(maximum_bonus_balloons(slot)); - if (SettingsRange("##bonus-balloons", "Bonus balloons", &bonus_value, 0, bonus_limit, extra.column, count, {}, - bonus_limit == 0)) { + if (SettingsRange("##bonus-balloons", "Bonus balloons", &bonus_value, 0, bonus_limit, + inline_bonus ? width - remove_width - 9.0F : width, count, {}, bonus_limit == 0)) { set_balloon_total(slot, hub_balloons(slot), static_cast(bonus_value)); } - extra.End(); - extra.Finish(width); - if (SavesRaceButton("REMOVE BONUS BALLOONS", 0.0F, SavesTone::Plain, bonus_balloons(slot) == 0U, - "This slot has no bonus balloons.")) { + const float bonus_bottom = ImGui::GetCursorScreenPos().y; + if (inline_bonus) + ImGui::SetCursorScreenPos({bonus_row.x + width - remove_width, bonus_row.y}); + if (SettingsButton("Remove bonus balloons", remove_width, bonus_balloons(slot) == 0U)) set_balloon_total(slot, hub_balloons(slot), 0U); + ImGui::SetCursorScreenPos({bonus_row.x, std::max(bonus_bottom, ImGui::GetItemRectMax().y)}); + ImGui::Dummy({width, 0.0F}); + balloon_box.End(paint); + + PaddockGap(9.0F); + PaddockBox trophy_box(outer, {10.0F, 10.0F}); + title("Trophy races", width); + constexpr std::array kTrophies{"Dino Domain", "Sherbet Island", "Snowflake Mountain", + "Dragon Forest", "Future Fun Land"}; + SavesGrid trophies(width, width); + for (std::size_t world = 0; world < kTrophies.size(); ++world) { + trophies.Begin(); + ImGui::PushID(static_cast(world)); + const unsigned shift = static_cast(world) * 2; + int place = (slot.trophies >> shift) & 3; + if (SettingsDropdown("##trophy", kTrophies[world], &place, {"None", "Bronze", "Silver", "Gold"}, + trophies.column)) + slot.trophies = + static_cast((slot.trophies & ~(3U << shift)) | (static_cast(place) << shift)); + ImGui::PopID(); + trophies.End(); } - PaddockGap(20.0F); + trophies.Finish(width); - SavesSeparator("Amulets and keys", width, false); - SavesGrid keys(width, panel); + trophy_box.End(paint); + PaddockGap(9.0F); + PaddockBox keys_box(outer, {10.0F, 10.0F}); + title("Amulets and keys", width); + SavesGrid keys(width, width); keys.Begin(); int tt = slot.tt_amulet; if (SettingsRange("##tt-amulet", "T.T. amulet pieces", &tt, 0, kMaximumAmuletPieces, keys.column, count)) { @@ -369,36 +343,40 @@ void DrawSavesSlotEditor(SavesPageState& state, float width, float panel, int sl } keys.Finish(width); - bool& courses_open = state.courses_open[static_cast(slot_index)]; - if (SavesRaceButton(courses_open ? "HIDE COURSE PROGRESS (34)" : "SHOW COURSE PROGRESS (34)")) { - courses_open = !courses_open; - } - PaddockGap(16.0F); - if (courses_open) { - const auto& names = course_names(); - SavesGrid courses(width, panel); - for (std::size_t course = 0; course < kCourseCount; ++course) { + keys_box.End(paint); + PaddockGap(9.0F); + PaddockBox courses_box(outer, {10.0F, 10.0F}); + title("Course progress", width); + constexpr std::array kCourses{3, 1, 20, 5, 6, 8, 2, 21, 10, 4, 7, 19, 14, 13, 15, 22, 12, + 23, 11, 24, 9, 17, 18, 16, 26, 29, 27, 31, 0, 30, 28, 32, 25, 33}; + const auto& names = course_names(); + for (std::size_t group = 0; group <= kTrophies.size(); ++group) { + const char* title = group < kTrophies.size() ? kTrophies[group] : "Challenges and bosses"; + PaddockText(PaddockReading(16.0F, true), PaddockRgb(kSetWarm), title, width); + PaddockGap(8.0F); + SavesGrid courses(width, width); + // Course IDs index the Adventure save's course status array. + const std::size_t last = group < kTrophies.size() ? (group + 1) * 4 : kCourses.size(); + for (std::size_t index = group * 4; index < last; ++index) { + const int course = kCourses[index]; courses.Begin(); - ImGui::PushID(static_cast(course)); + ImGui::PushID(course); int status = slot.course_status[course]; if (SettingsDropdown("course", names[course], &status, - {"Not started", "Race won", "Silver Coins won", "Complete"}, courses.column)) { + {"Not started", "Race won", "Silver Coins won", "Complete"}, courses.column)) slot.course_status[course] = static_cast(status); - } ImGui::PopID(); courses.End(); } courses.Finish(width); + PaddockGap(14.0F); } - if (SavesRaceButton("MAX OUT THIS ADVENTURE")) { - state.ask = SavesPageState::Ask::MaxOut; - state.slot = slot_index; - } + courses_box.End(paint); ImGui::PopID(); } void DrawSavesUnlocks(SavesPageState& state, float width, float panel) { - auto& settings = g_save_builder_image->settings; + auto& settings = g_adventure_drafts[state.personal_modded].image->settings; SavesGrid grid(width, panel); grid.Begin(); SettingsCheck("##adventure-two", "Adventure Two", &settings.adventure_two, grid.column); @@ -436,234 +414,69 @@ void DrawSavesUnlocks(SavesPageState& state, float width, float panel) { state.ask = SavesPageState::Ask::UnlockAll; } -void DrawSavesRecords(SavesPageState& state, float width) { - using namespace dkr::runtime::saves::codec; - PaddockText(PaddockSign(19.0F, 1.45F, 0.0F), PaddockRgb(kSetText), - "Personal records are view-only. Race in Time Trial mode to set or improve them.", width); - PaddockGap(13.0F); - const std::array*>, 2> kLists{{ - {"Fastest laps", &g_save_builder_image->fastest_laps}, - {"Course times", &g_save_builder_image->course_times}, - }}; - for (std::size_t list = 0; list < kLists.size(); ++list) { - ImGui::PushID(static_cast(list)); - // The summary (.saves-records summary): a quiet bar with a marker. - const PaddockPress press = PaddockBeginPress("##records", {width, 44.0F}); - bool& open = state.records_open[list]; - if (press.pressed) - open = !open; - ImDrawList* draw = ImGui::GetWindowDrawList(); - PaddockFill(draw, press.min, press.max, PaddockRound(8.0F), - PaddockApply(PaddockMix(PaddockRgb(0x123E50), PaddockRgb(0x174C60), press.hover))); - const PaddockType type = PaddockSign(19.0F, 1.2F, 0.0F); - const ImVec2 marker{press.min.x + 16.0F + 4.0F, (press.min.y + press.max.y) * 0.5F}; - if (open) { - draw->AddTriangleFilled({marker.x - 4.5F, marker.y - 3.0F}, {marker.x + 4.5F, marker.y - 3.0F}, - {marker.x, marker.y + 4.0F}, PaddockCol(kSetText)); - } else { - draw->AddTriangleFilled({marker.x - 3.0F, marker.y - 4.5F}, {marker.x + 4.0F, marker.y}, - {marker.x - 3.0F, marker.y + 4.5F}, PaddockCol(kSetText)); - } - PaddockDrawRun(draw, type, {press.min.x + 36.0F, std::round(press.min.y + (44.0F - type.line) * 0.5F)}, - PaddockCol(kSetText), kLists[list].first, kLists[list].first + std::strlen(kLists[list].first)); - PaddockEndPress(press, 8.0F, 1.0F); - if (open) { - const auto& records = *kLists[list].second; - for (std::size_t index = 0; index < records.size(); ++index) { - const ImVec2 at = ImGui::GetCursorScreenPos(); - PaddockGap(12.0F); - PaddockText(PaddockReading(16.0F, false, 1.4F), PaddockRgb(kSetText), record_names()[index], width); - PaddockGap(4.0F); - std::string detail = "Time: " + (records[index].time != 0U ? FormatRecordTime(records[index].time) - : std::string("No personal record yet")); - if (records[index].time != 0U) { - detail += " Racer: " + - (records[index].initials.empty() ? std::string("---") : records[index].initials); - } - PaddockText(PaddockReading(16.0F, false, 1.45F), PaddockRgb(kSetMuted), detail, width); - PaddockGap(12.0F); - const float bottom = ImGui::GetCursorScreenPos().y; - draw->AddRectFilled({at.x, bottom - 1.0F}, {at.x + width, bottom}, PaddockCol(kSetBorder)); - } - } - PaddockGap(12.0F); - ImGui::PopID(); +bool LoadSavesEditorDraft(SavesPageState& state, bool valid) { + auto& draft = g_adventure_drafts[state.personal_modded]; + if (draft.image || !valid) + return draft.image.has_value(); + dkr::runtime::saves::codec::SaveImage image; + std::string error; + if (!dkr::runtime::saves::shared::load_draft(image, draft.revision, error, state.personal_modded)) { + g_save_manager_status = error; + return false; } + draft.original = image; + draft.image = std::move(image); + return true; } -void DrawSavesEditor(SavesPageState& state, float width, float panel, bool editable, bool exists) { - using namespace dkr::runtime::saves; - if (!editable) { - SavesSeparator("A valid save is needed", width, false); - SavesNote(exists ? "Restore a valid backup or import a working save from Overview before editing." - : "Start an adventure in the game, import a save, or create a fresh adventure from Overview.", - width); - if (SavesRaceButton("GO TO OVERVIEW")) - state.section = 0; - return; - } - if (!g_save_builder_image) { - codec::SaveImage image{}; - std::string error; - if (load_adventure(image, error)) { - // Opening the editor must not silently normalise existing progress. - g_save_builder_image = image; - state.original = image; - g_shared_draft_revision = dkr::runtime::saves::shared::revision(); - } else { - g_save_manager_status = error; - return; - } - } - if (!state.original) - state.original = *g_save_builder_image; - SavesNote("Manual edits use Apply Changes. Completion and unlock buttons save when confirmed.", width); - const int picked = SavesEditorTabs({"SLOT 1", "SLOT 2", "SLOT 3", "UNLOCKS", "RECORDS"}, state.tab, width); - if (picked >= 0) - state.tab = picked; - PaddockGap(20.0F); - if (state.tab < 3) - DrawSavesSlotEditor(state, width, panel, state.tab); - else if (state.tab == 3) - DrawSavesUnlocks(state, width, panel); - else - DrawSavesRecords(state, width); +struct SavesFooterLayout { + float discard_width; + float apply_width; + bool stacked; + float height; +}; - // The draft bar (.saves-draft-bar): it rides the bottom of the panel - // while the editor scrolls under it. - PaddockGap(20.0F); - const bool dirty = SavesDraftDirty(); - const ImVec2 natural = ImGui::GetCursorScreenPos(); +SavesFooterLayout MeasureSavesFooter(float width) { const float discard_width = PaddockRaceButtonWidth("DISCARD CHANGES"); const float apply_width = PaddockRaceButtonWidth("APPLY CHANGES"); - const bool wraps = width - discard_width - apply_width - 24.0F < 180.0F; - const float bar_height = 1.0F + 16.0F + (wraps ? 49.0F + 12.0F + 44.0F : std::max(49.0F, 44.0F)) + 16.0F; + const bool stacked = width - discard_width - apply_width - 24.0F < 150.0F; + return {discard_width, apply_width, stacked, stacked ? 106.0F : 66.0F}; +} + +void DrawSavesDraftBar(const SavesPageState& state, float width, float top, const SavesFooterLayout& layout, bool dirty, + bool locked, SavesPageState::Ask& ask) { ImGuiWindow* window = ImGui::GetCurrentWindow(); - const float visible_bottom = PanelFooterBounds(window).Max.y; - const float top = std::min(natural.y, visible_bottom - bar_height); + const auto panel = PanelFooterBounds(window); + const float left = ImGui::GetCursorScreenPos().x; DrawPanelFooterBackground(window, top, PaddockCol(0x0A202C), PaddockCol(kSetBorder)); - if (SaveDraftLayoutCheck()) - g_save_draft_geometry = { - PanelFooterBounds(window), - {{window->Pos.x + window->WindowBorderSize, window->Pos.y + window->WindowBorderSize}, - {window->Pos.x + window->Size.x - window->WindowBorderSize - window->ScrollbarSizes.x, - window->Pos.y + window->Size.y - window->WindowBorderSize - window->ScrollbarSizes.y}}, - top, - dirty}; - // Its own child window, so it stays above the editor it covers for both - // drawing and the pointer. - ImGui::SetCursorScreenPos({natural.x, top}); - ImGui::BeginChild("##draft-bar", {width, bar_height}, false, - ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | - ImGuiWindowFlags_NavFlattened | ImGuiWindowFlags_NoBackground); - ImGui::SetCursorScreenPos({natural.x, top + 17.0F}); - ImGui::BeginGroup(); - const float text_width = wraps ? width : width - discard_width - apply_width - 24.0F; - PaddockText(PaddockReading(17.0F, false, 1.5F), PaddockRgb(kSetText), - dirty ? "Unapplied changes" : "No pending changes", text_width); - PaddockText(PaddockReading(14.0F, false, 1.45F), PaddockRgb(kSetMuted), "Applying creates a backup first.", - text_width); - ImGui::EndGroup(); - const float buttons_y = wraps ? top + 17.0F + 49.0F + 12.0F : top + 17.0F + (49.0F - 44.0F) * 0.5F; - ImGui::SetCursorScreenPos({wraps ? natural.x : natural.x + width - apply_width - 12.0F - discard_width, buttons_y}); - if (SavesRaceButton("DISCARD CHANGES", discard_width, SavesTone::Plain, !dirty, - "There are no changes to discard.")) { - state.ask = SavesPageState::Ask::Discard; + if (SaveDraftLayoutCheck()) { + g_save_draft_geometry.panel = panel; + g_save_draft_geometry.bounds = { + {window->Pos.x + window->WindowBorderSize, window->Pos.y + window->WindowBorderSize}, + {window->Pos.x + window->Size.x - window->WindowBorderSize - window->ScrollbarSizes.x, + window->Pos.y + window->Size.y - window->WindowBorderSize - window->ScrollbarSizes.y}}; + g_save_draft_geometry.top = top; + g_save_draft_geometry.dirty = dirty; } - ImGui::SameLine(0.0F, 12.0F); - if (SavesRaceButton("APPLY CHANGES", apply_width, SavesTone::Primary, !dirty, "There are no changes to apply.")) { - state.ask = SavesPageState::Ask::Apply; - } - ImGui::EndChild(); - ImGui::SetCursorScreenPos({natural.x, natural.y + bar_height}); - ImGui::Dummy({width, 0.0F}); -} + ImGui::SetCursorScreenPos({left, top + (layout.stacked ? 10.0F : 17.0F)}); + const float text_width = layout.stacked ? width : width - layout.discard_width - layout.apply_width - 24.0F; + const std::string_view status = state.personal_modded + ? (dirty ? "Modded Adventure · Unsaved changes" : "Modded Adventure") + : (dirty ? "Vanilla Adventure · Unsaved changes" : "Vanilla Adventure"); + PaddockText(PaddockReading(16.0F, true, 1.25F), PaddockRgb(kSetText), status, text_width); -// ------------------------------------------------------------ overview - -void DrawSavesOverview(SavesPageState& state, float width, float panel, const SaveManagerViewCache& view, - bool editable) { - using namespace dkr::runtime::saves; - SavesNote( - "One personal save for normal play, with or without mods. Three Adventure slots, shared unlocks and records.", - width); - const bool busy = SharedSaveBusy(); - const auto button = [&](const char* label, bool disabled = false, SavesTone tone = SavesTone::Plain) { - return SavesRaceButton(label, 0, tone, busy || disabled); - }; - if (button("BACK UP SAVE", !editable, SavesTone::Primary)) - BeginSharedSaveJob( - [](std::string& error) { - std::filesystem::path created; - return backup_adventure(created, error); - }, - "Personal save backed up."); - PaddockGap(8); - if (button("EXPORT SAVE", !editable)) - ExportAdventureWithDialog(); - PaddockGap(8); - if (button("IMPORT SAVE")) - ImportAdventureWithDialog(); - PaddockGap(14); - if (!view.adventure.exists) { - if (button("CREATE PERSONAL SAVE")) - state.ask = SavesPageState::Ask::Reset; - return; - } - if (editable) { - if (!state.summary && view.image) - state.summary = view.image; - if (state.summary) { - SavesSeparator("Adventure slots", width); - for (unsigned i = 0; i < 3; ++i) { - const auto& slot = state.summary->slots[i]; - SavesNote("Slot " + std::to_string(i + 1) + " - " + (slot.name.empty() ? "---" : slot.name) + " - " + - std::to_string(slot.balloons[0] - codec::bonus_balloons(slot)) + " / 47 balloons" + - (codec::bonus_balloons(slot) > 0U - ? " + " + std::to_string(codec::bonus_balloons(slot)) + " bonus" - : ""), - width, 18, kSetText); - } - const auto& settings = state.summary->settings; - SavesNote(std::string("Drumstick: ") + (settings.drumstick ? "unlocked" : "locked") + " | T.T.: " + - (std::all_of(settings.tt_trials.begin(), settings.tt_trials.end(), [](bool x) { return x; }) - ? "unlocked" - : "locked") + - " | Adventure Two: " + (settings.adventure_two ? "unlocked" : "locked"), - width); - } - if (button("MAX OUT ENTIRE SAVE", false, SavesTone::Primary)) { - state.slot = -1; - state.ask = SavesPageState::Ask::MaxOut; - } - PaddockGap(8); - if (button("UNLOCK ALL RACERS AND MODES")) - state.ask = SavesPageState::Ask::UnlockAll; - SavesSeparator("Development tools", width); - SavesNote( - "Dev Menu uses a separate copy, not this personal save. New development copies start from your saved progress. You can refresh an existing copy below; its previous progress is kept.", - width); - if (button("COPY PERSONAL SAVE TO DEVELOPMENT")) - state.ask = SavesPageState::Ask::DevelopmentCopy; - } - SavesSeparator("Older progress and backups", width); - SavesNote( - "Older mod-set saves are kept. Choose one from Backups & Recovery if it contains the progress you want to keep. Nothing is merged or deleted automatically.", - width); - if (button("OPEN BACKUPS & RECOVERY")) { - state.scope = 3; - state.ask = SavesPageState::Ask::None; - } - PaddockGap(20); - if (button("RESET PERSONAL SAVE", false, SavesTone::Danger)) - state.ask = SavesPageState::Ask::Reset; - (void)panel; + const float buttons_y = top + (layout.stacked ? 48.0F : 11.0F); + const float actions_width = layout.discard_width + layout.apply_width + 12.0F; + ImGui::SetCursorScreenPos({left + std::max(0.0F, width - actions_width), buttons_y}); + if (SavesRaceButton("DISCARD CHANGES", layout.discard_width, SavesTone::Plain, locked || !dirty)) + ask = SavesPageState::Ask::Discard; + ImGui::SameLine(0.0F, 12.0F); + if (SavesRaceButton("APPLY CHANGES", layout.apply_width, SavesTone::Primary, locked || !dirty)) + ask = SavesPageState::Ask::Apply; + LibraryNavigationPinnedAction(!locked && dirty ? ImGui::GetItemID() : 0); } -// ------------------------------------------------------------ transfer - -// Complete manager actions and stored-save recovery. This replaces the old -// split-profile UI, but keeps the proven slot/record editor above unchanged. +// File tools shared by both Adventure saves. void SharedPakDialog(int port, bool importing) { if (SharedSaveBusy()) return; @@ -704,55 +517,156 @@ void SharedRawExportDialog(const std::filesystem::path& source) { } NFD_Quit(); } -void DrawSavesTransfer(float width, float panel, const SaveManagerViewCache& view) { +struct SavesFileActions { + float width; + float used = 0.0F; + + bool Button(const char* label, bool disabled = false, SettingsButtonTone tone = SettingsButtonTone::Plain) { + constexpr float gap = 8.0F; + const float size = std::min(width, SettingsButtonWidth(label)); + if (used > 0.0F && used + gap + size <= width) { + ImGui::SameLine(0.0F, gap); + used += gap; + } else { + if (used > 0.0F) + PaddockGap(gap); + used = 0.0F; + } + used += size; + return SettingsButton(label, size, disabled, tone); + } +}; + +void DrawSavesFiles(SavesPageState& state, float width, const AdventureView& adventure, + const SaveManagerViewCache& view) { using namespace dkr::runtime::saves; - SavesNote( - "Move your personal Adventure, custom-course records and Controller Paks together. Older save bundles can still be imported.", - width); - if (SavesRaceButton("EXPORT SAVE BUNDLE", 0, SavesTone::Plain, SharedSaveBusy())) - ExportSaveBundleWithDialog(); - PaddockGap(8); - if (SavesRaceButton("IMPORT SAVE BUNDLE", 0, SavesTone::Plain, SharedSaveBusy())) - ImportSaveBundleWithDialog(); - SavesSeparator("Controller Paks", width); - SavesNote("DKR-R virtual memory cards. Use DKR-R-format .mpk files, not an unrelated emulator format.", width); + const bool modded = state.personal_modded; + const bool busy = SharedSaveBusy(); + const bool valid = adventure.info.valid; + const auto heading = [](const char* label, float available) { + PaddockText(PaddockSign(20.0F, 1.2F, 0.0F), PaddockRgb(kSetText), label, available); + PaddockGap(9.0F); + }; + + constexpr float gap = 12.0F; + const bool side_by_side = width >= 460.0F; + const float column = side_by_side ? std::floor((width - gap) * 0.5F) : width; + const ImVec2 top = ImGui::GetCursorScreenPos(); + constexpr std::string_view adventure_help = "Back up, export or replace this Adventure."; + constexpr std::string_view bundle_help = + "Transfer this Adventure with shared custom-course records and Controller Paks."; + const auto note_type = PaddockReading(16.0F, false, 1.45F); + const float note_height = std::max(PaddockTextHeight(note_type, adventure_help, column), + PaddockTextHeight(note_type, bundle_help, column)); + const auto transfer_note = [&](std::string_view note) { + SavesNote(note, column); + if (side_by_side) + PaddockGap(note_height - PaddockTextHeight(note_type, note, column)); + }; + ImGui::BeginGroup(); + heading("Adventure save", column); + transfer_note(adventure_help); + SavesFileActions adventure_actions{column}; + if (adventure_actions.Button("Back up save", busy || !valid)) + BeginSharedSaveJob( + [modded](std::string& error) { + std::filesystem::path created; + return backup_adventure(created, error, modded); + }, + "Adventure backed up."); + if (adventure_actions.Button("Export save", busy || !valid)) + ExportAdventureWithDialog(adventure.info.path); + if (adventure_actions.Button("Import save", busy)) + ImportAdventureWithDialog(modded); + if (!adventure.info.exists && adventure_actions.Button("Create personal save", busy)) + state.ask = SavesPageState::Ask::Reset; + if (adventure.info.exists && !valid && adventure.info.size == 512 && + adventure_actions.Button("Back up & repair checksums", busy)) + state.ask = SavesPageState::Ask::Repair; + ImGui::EndGroup(); + const float first_bottom = ImGui::GetItemRectMax().y; + ImGui::SetCursorScreenPos(side_by_side ? ImVec2{top.x + column + gap, top.y} : ImVec2{top.x, first_bottom + 16.0F}); + ImGui::BeginGroup(); + heading("Save bundle", column); + transfer_note(bundle_help); + SavesFileActions bundle_actions{column}; + if (bundle_actions.Button("Export save bundle", busy)) + ExportSaveBundleWithDialog(modded); + if (bundle_actions.Button("Import save bundle", busy)) + ImportSaveBundleWithDialog(modded); + ImGui::EndGroup(); + ImGui::SetCursorScreenPos({top.x, std::max(first_bottom, ImGui::GetItemRectMax().y)}); + ImGui::Dummy({width, 0.0F}); + + SavesSeparator("Controller Paks", width, false); + SavesNote("Use DKR-R-format .mpk files for these virtual memory cards.", width); for (int port = 0; port < 4; ++port) { ImGui::PushID(port); const auto& pak = view.controller_paks[port]; - SavesNote("Controller " + std::to_string(port + 1) + ": " + - (!pak.exists ? "not created" - : pak.valid ? "ready" - : "needs recovery"), - width, 18, kSetText); - if (SavesRaceButton("BACK UP PAK", 0, SavesTone::Plain, SharedSaveBusy() || !pak.valid)) + const std::string label = "Controller " + std::to_string(port + 1) + ": " + + (!pak.exists ? "not created" + : pak.valid ? "ready" + : "needs recovery"); + const float actions_width = SettingsButtonWidth("Back up Pak") + SettingsButtonWidth("Export Pak") + + SettingsButtonWidth("Import Pak") + 16.0F; + constexpr float label_width = 192.0F; + const bool inline_actions = width >= label_width + gap + actions_width; + const ImVec2 row = ImGui::GetCursorScreenPos(); + SavesNote(label, inline_actions ? label_width : width, 16.0F, kSetText); + if (inline_actions) + ImGui::SetCursorScreenPos({row.x + label_width + gap, row.y}); + ImGui::BeginGroup(); + SavesFileActions pak_actions{inline_actions ? width - label_width - gap : width}; + if (pak_actions.Button("Back up Pak", busy || !pak.valid)) BeginSharedSaveJob( [port](std::string& error) { std::filesystem::path created; return backup_controller_pak(port, created, error); }, "Controller Pak backed up."); - PaddockGap(8); - if (SavesRaceButton("EXPORT PAK", 0, SavesTone::Plain, SharedSaveBusy() || !pak.valid)) + if (pak_actions.Button("Export Pak", busy || !pak.valid)) SharedPakDialog(port, false); - PaddockGap(8); - if (SavesRaceButton("IMPORT PAK", 0, SavesTone::Plain, SharedSaveBusy())) + if (pak_actions.Button("Import Pak", busy)) SharedPakDialog(port, true); - PaddockGap(18); + ImGui::EndGroup(); + ImGui::SetCursorScreenPos({row.x, ImGui::GetItemRectMax().y + 9.0F}); + ImGui::Dummy({width, 0.0F}); ImGui::PopID(); } - (void)panel; + + SavesSeparator("Recovery and development", width, false); + SavesNote("Dev Menu uses a separate copy. Refreshing it keeps a backup of its previous progress.", width); + SavesFileActions recovery_actions{width}; + if (recovery_actions.Button("Open Backups & Recovery", busy)) { + state.scope = 3; + state.ask = SavesPageState::Ask::None; + } + if (recovery_actions.Button("Copy personal save to development", busy || !valid)) + state.ask = SavesPageState::Ask::DevelopmentCopy; + if (adventure.info.exists) { + SavesSeparator("Reset Adventure", width, false); + if (SavesRaceButton("RESET ADVENTURE", 0.0F, SavesTone::Danger, busy)) + state.ask = SavesPageState::Ask::Reset; + } } + void DrawSavesConfirmations(SavesPageState& state) { using namespace dkr::runtime::saves; using Ask = SavesPageState::Ask; static Ask shown = Ask::None; - if (state.ask == Ask::None) + if (state.ask == Ask::None) { + shown = Ask::None; return; + } if (shown != state.ask) { shown = state.ask; ImGui::OpenPopup("##saves-confirm"); } std::string heading = "Confirm save change", detail, confirm = "CONFIRM"; + const bool modded = + state.ask == Ask::Import || state.ask == Ask::Bundle ? state.import_modded : state.personal_modded; + auto& draft = g_adventure_drafts[modded]; + const std::string adventure = modded ? "Modded Adventure" : "Vanilla Adventure"; bool replace = true; static std::filesystem::path preview_source; static std::string preview_text; @@ -762,18 +676,19 @@ void DrawSavesConfirmations(SavesPageState& state) { } switch (state.ask) { case Ask::Repair: - heading = "Repair personal save?"; + heading = "Repair " + adventure + "?"; detail = "Only checksums can be repaired. Damaged progress cannot be reconstructed. An unchanged original is preserved."; confirm = "REPAIR & KEEP ORIGINAL"; break; case Ask::Reset: - heading = "Reset personal save?"; - detail = "Reset all three slots, unlocks and records. Your current Adventure is backed up first."; + heading = "Reset " + adventure + "?"; + detail = + "Reset all three slots, unlocks and built-in records in this Adventure. The current Adventure is backed up first."; confirm = "BACK UP & RESET"; break; case Ask::Restore: - heading = "Use this as your personal save?"; + heading = "Restore into " + adventure + "?"; detail = preview_text; confirm = "BACK UP & USE THIS SAVE"; break; @@ -792,24 +707,25 @@ void DrawSavesConfirmations(SavesPageState& state) { break; case Ask::Discard: heading = "Discard editor changes?"; - detail = "Reload your current personal save. Nothing on disk will be replaced."; + detail = "Reload " + adventure + " from disk."; confirm = "DISCARD DRAFT"; replace = false; break; case Ask::Apply: heading = "Apply editor changes?"; - detail = "Save the draft to your personal Adventure. A backup is created first."; + detail = "Save the draft to " + adventure + ". A backup is created first."; confirm = "BACK UP & APPLY"; break; case Ask::Import: - heading = "Import personal save?"; + heading = "Import into " + adventure + "?"; detail = preview_text; confirm = "BACK UP & IMPORT"; break; case Ask::Bundle: - heading = "Import save bundle?"; + heading = "Import bundle into " + adventure + "?"; detail = - "Replace the personal Adventure and Controller Paks included in this bundle. Originals are preserved in a recoverable transaction."; + "Import the Adventure into " + adventure + + " and replace any shared records and Controller Paks included in the bundle. Originals are kept in Recovery."; confirm = "BACK UP & IMPORT BUNDLE"; break; case Ask::Pak: @@ -850,56 +766,60 @@ void DrawSavesConfirmations(SavesPageState& state) { if (!state.restore.empty() && (state.ask == Ask::Import || state.ask == Ask::Restore || state.ask == Ask::RepairUse || state.ask == Ask::Host)) SavesNote(PathUtf8(state.restore), inner, 14); - if (replace && state.ask != Ask::Host) - SavesNote("Normal play and mods use this personal save. Online and development saves stay separate.", inner); - if (SavesDraftDirty() && state.ask != Ask::Apply && state.ask != Ask::MaxOut && state.ask != Ask::UnlockAll) + if (replace && state.ask != Ask::Host && state.ask != Ask::Pak) + SavesNote("Selected save: " + adventure, inner); + if (replace && state.ask != Ask::Host && state.ask != Ask::Pak && SavesDraftDirty(draft) && + state.ask != Ask::Apply && state.ask != Ask::MaxOut && state.ask != Ask::UnlockAll) SavesNote("Your unapplied editor draft will be discarded after this succeeds.", inner); - const float height = 44; - const bool stack = PaddockRaceButtonWidth(confirm.c_str()) + PaddockRaceButtonWidth("CANCEL") + 12 > inner; - const float cell = stack ? inner : (inner - 12) * 0.5f; - bool close = false; - if (SavesRaceButton("CANCEL", cell)) - close = true; - if (!stack) - ImGui::SameLine(0, 12); + constexpr float gap = 12.0F; + const float cancel_width = PaddockRaceButtonWidth("CANCEL"); + const float confirm_width = PaddockRaceButtonWidth(confirm.c_str()); + const float actions_width = cancel_width + gap + confirm_width; + const bool stack = actions_width > inner; + if (!stack) { + const ImVec2 at = ImGui::GetCursorScreenPos(); + ImGui::SetCursorScreenPos({at.x + inner - actions_width, at.y}); + } + bool close = SavesRaceButton("CANCEL", std::min(inner, cancel_width)); + if (stack) + PaddockGap(8.0F); else - PaddockGap(10); - if (SavesRaceButton(confirm.c_str(), cell, SavesTone::Primary, SharedSaveBusy())) { + ImGui::SameLine(0.0F, gap); + const bool confirmed = confirm_width > inner + ? SettingsButton(confirm.c_str(), inner, SharedSaveBusy(), SettingsButtonTone::Selected) + : SavesRaceButton(confirm.c_str(), confirm_width, SavesTone::Primary, SharedSaveBusy()); + if (confirmed) { const auto source = state.restore; const auto port = state.slot; if (state.ask == Ask::Discard) { - SavesForgetDraft(); - g_shared_draft_revision.clear(); + draft = {}; } else if (state.ask == Ask::MaxOut || state.ask == Ask::UnlockAll || state.ask == Ask::Apply) { codec::SaveImage image; std::string error; - std::string expected = g_shared_draft_revision; + std::string expected = draft.revision; bool ready = false; - if (g_save_builder_image) { - image = *g_save_builder_image; + if (draft.image) { + image = *draft.image; ready = true; } else { - expected = shared::revision(); - ready = load_adventure(image, error); + ready = shared::load_draft(image, expected, error, modded); } if (ready) { if (state.ask == Ask::MaxOut) shared::complete(image, state.slot); if (state.ask == Ask::UnlockAll) shared::unlock(image); - BeginSharedSaveJob( - [image = std::move(image), expected](std::string& error) { - return shared::apply(image, expected, error); - }, - "Personal save updated and read-back verified. Existing Dev Menu copies are separate; use Copy Personal Save to Development to refresh one."); + BeginSharedSaveJob([image = std::move(image), expected, modded]( + std::string& error) { return shared::apply(image, expected, error, modded); }, + adventure + " saved and verified.", modded); } else g_save_manager_status = error; } else if (state.ask == Ask::Reset) - BeginSharedSaveJob([](std::string& error) { return shared::reset(error); }, - "Personal save reset. Previous progress and custom records are kept in Recovery."); + BeginSharedSaveJob([modded](std::string& error) { return shared::reset(error, modded); }, + adventure + " reset. Its previous progress is kept in Recovery.", modded); else if (state.ask == Ask::Bundle) - BeginSharedSaveJob([source](std::string& error) { return import_bundle(source, error); }, - "Save bundle imported. Original images are kept in the transaction archive."); + BeginSharedSaveJob([source, modded](std::string& error) { return import_bundle(source, error, modded); }, + "Save bundle imported. Original images are kept in the transaction archive.", modded); else if (state.ask == Ask::Pak) BeginSharedSaveJob( [source, port](std::string& error) { @@ -911,22 +831,22 @@ void DrawSavesConfirmations(SavesPageState& state) { "Online Adventure selected. Personal progress was not changed."); else if (state.ask == Ask::DevelopmentCopy) BeginSharedSaveJob( - [](std::string& error) { return shared::queue_development_copy(error); }, + [modded](std::string& error) { return shared::queue_development_copy(error, modded); }, "Personal save snapshot queued for the next offline development launch. Existing development progress will be preserved."); else if (state.ask == Ask::Repair) BeginSharedSaveJob( - [](std::string& error) { + [modded](std::string& error) { bool changed; std::filesystem::path original; return shared::prepare(g_config_directory, error) && - repair_adventure_checksums(changed, original, error); + repair_adventure_checksums(changed, original, error, modded); }, - "Checksum repair complete. Check your progress; the original was retained."); + "Checksum repair complete. The original was retained.", modded); else { const bool repair = state.ask == Ask::RepairUse; BeginSharedSaveJob( - [source, repair](std::string& error) { return shared::adopt(source, repair, error); }, - "Personal save replaced. Both the selected original and previous progress were retained."); + [source, repair, modded](std::string& error) { return shared::adopt(source, repair, error, modded); }, + adventure + " replaced. Both the selected original and previous progress were retained.", modded); } close = true; } @@ -936,7 +856,6 @@ void DrawSavesConfirmations(SavesPageState& state) { state.restore.clear(); } EndSettingsDialog(); - (void)height; } struct SharedSaveInventory { @@ -967,7 +886,7 @@ void DrawStoredSaves(SavesPageState& state, float width, bool locked) { std::map, std::size_t> groups; std::vector compact; for (auto& record : inventory.records) { - const auto bucket = record.scope == 0 ? 0 : record.scope == 1 ? 1 : 3; + const auto bucket = record.scope; const auto key = std::tuple{bucket, int(record.kind), record.content_hash}; const auto [it, added] = groups.emplace(key, compact.size()); if (added) @@ -982,14 +901,18 @@ void DrawStoredSaves(SavesPageState& state, float width, bool locked) { } if (pending.valid()) SavesNote("Reading saved progress...", width); - SavesNote( - state.scope == 1 - ? "Online Adventures are separate. The host can continue with different mods without switching saves." - : "Choose an older save to use as your personal Adventure. Original mod-set copies and backups are never removed automatically.", - width); + if (state.scope == 1) { + SavesNote("The host can continue the same Online Adventure with different mods.", width); + } else { + SavesNote("Choose which Adventure should receive the backup.", width); + const int target = + SettingsSectionSigns({"RESTORE TO VANILLA", "RESTORE TO MODDED"}, state.personal_modded, width); + if (target >= 0) + state.personal_modded = target == 1; + } bool found = false; for (const auto& record : inventory.records) { - if (state.scope == 1 ? (record.scope != 1) : (record.scope == 0 || record.scope == 1)) + if (record.scope != state.scope) continue; found = true; ImGui::PushID(PathUtf8(record.info.path).c_str()); @@ -999,7 +922,6 @@ void DrawStoredSaves(SavesPageState& state, float width, bool locked) { : record.kind == StoredSaveKind::ControllerPak ? "Controller Pak backup" : record.kind == StoredSaveKind::ExperimentalPaks ? "Online Controller Paks" : state.scope == 1 ? "Online Adventure" - : record.scope == 2 ? "Older mod-set Adventure" : "Adventure backup"; SavesNote(label, inner, 17, kSetText); SavesNote(record.preview, inner); @@ -1012,10 +934,9 @@ void DrawStoredSaves(SavesPageState& state, float width, bool locked) { if (development) SavesNote("Development image - contains tool-session progress, not ordinary play.", inner, 14, kSetWarm); if (adventure && !locked) { - if (SavesRaceButton(record.info.valid ? (state.scope == 1 ? "USE FOR HOSTING" : "USE AS PERSONAL SAVE") - : "REPAIR & USE COPY", - 0, SavesTone::Primary, - SharedSaveBusy() || (!record.info.valid && record.info.size != 512))) { + if (SavesRaceButton( + record.info.valid ? (state.scope == 1 ? "USE FOR HOSTING" : "RESTORE BACKUP") : "REPAIR & USE COPY", + 0, SavesTone::Primary, SharedSaveBusy() || (!record.info.valid && record.info.size != 512))) { state.restore = record.info.path; state.ask = !record.info.valid ? SavesPageState::Ask::RepairUse : state.scope == 1 ? SavesPageState::Ask::Host @@ -1050,6 +971,172 @@ void DrawStoredSaves(SavesPageState& state, float width, bool locked) { } } +#include "cloud_saves/ui.inl" + +void PaintSaveWorkspacePanel(ImDrawList* draw, ImVec2 min, ImVec2 max) { + PaddockPanel(draw, min, max, {PaddockRound(14), PaddockRgb(0x0B2B3B), PaddockRgb(kSetBorder), 1.0F}); +} + +float DrawSavesSlotList(SavesPageState& state, float width, float height, bool stacked, + const dkr::runtime::saves::codec::SaveImage* image) { + constexpr float gap = 8.0F, pad = 12.0F; + PaddockBox box(width, {pad, pad}, stacked ? 0.0F : height); + PaddockText(PaddockReading(17.0F, true, 1.25F), PaddockRgb(kSetText), "Adventure slots", box.Inner()); + PaddockGap(gap); + constexpr int count = static_cast(dkr::runtime::saves::codec::kAdventureSlotCount); + const float item_width = stacked ? (box.Inner() - gap * (count - 1)) / count : box.Inner(); + const auto row = ImGui::GetCursorScreenPos(); + const float heading_height = row.y - box.Origin().y; + const float row_height = + stacked ? 68.0F : std::clamp((height - heading_height - pad - gap * (count - 1)) / count, 60.0F, 72.0F); + for (int index = 0; index < count; ++index) { + if (stacked) + ImGui::SetCursorScreenPos({row.x + static_cast(index) * (item_width + gap), row.y}); + ImGui::PushID(index); + const auto press = PaddockBeginPress("##adventure-slot", {item_width, row_height}); + const bool active = index == state.selected_slot; + PaddockPanel(ImGui::GetWindowDrawList(), press.min, press.max, + {PaddockRound(9), + PaddockRgb(active ? 0xA33620 + : press.hovered ? 0x1C4F65 + : 0x12394B), + PaddockRgb(active ? kSetWarm : kSetBorder), 1.0F}); + const auto* slot = image ? &image->slots[static_cast(index)] : nullptr; + const bool named = slot && slot->name.find_first_not_of(' ') != std::string::npos; + const bool occupied = slot && (named || slot->balloons[0] || slot->trophies); + const std::string name = + named ? slot->name : std::string(dkr::localisation::source(occupied ? "Unnamed" : "Empty")); + const std::string progress = + occupied ? std::to_string(slot->balloons[0]) + " " + std::string(dkr::localisation::source("balloons")) + : std::string{}; + const auto slot_label = std::string(dkr::localisation::source("Slot")) + " " + std::to_string(index + 1); + const auto small_text = PaddockReading(13.0F, false, 1.2F); + const auto large = PaddockReading(16.0F, true, 1.15F); + auto* draw = ImGui::GetWindowDrawList(); + const float text_width = item_width - 18.0F; + const float x = press.min.x + 9.0F; + const PaddockTextStyle muted{PaddockCol(active ? 0xFFE1C5 : kSetMuted)}; + const PaddockTextStyle ink{PaddockCol(kSetText)}; + PaddockTextAt(draw, small_text, {x, press.min.y + 6.0F}, text_width, slot_label, muted); + PaddockTextAt(draw, large, {x, press.min.y + 25.0F}, text_width, name, ink); + PaddockTextAt(draw, small_text, {x, press.max.y - 20.0F}, text_width, progress, muted); + PaddockEndPress(press, 9.0F, 1.0F, true); + if (press.pressed) { + state.selected_slot = index; + state.section = SaveEditorSection::Progress; + state.scroll_editor_to_top = true; + } + ImGui::PopID(); + if (!stacked && index + 1 < count) + PaddockGap(gap); + } + return box.End(PaintSaveWorkspacePanel); +} + +void DrawSavesWorkspace(SavesPageState& state, float width, const SaveManagerViewCache& view, + const AdventureView& adventure, bool locked) { + constexpr float pad = 12.0F, gap = 12.0F; + const bool valid = adventure.info.valid; + const bool loaded = LoadSavesEditorDraft(state, valid); + const auto& draft = g_adventure_drafts[state.personal_modded]; + const auto* image = loaded ? &*draft.image : nullptr; + const auto footer = MeasureSavesFooter(width); + const auto start = ImGui::GetCursorScreenPos(); + const float bottom = PanelFooterBounds(ImGui::GetCurrentWindow()).Max.y; + const float footer_top = bottom - footer.height; + const bool stacked = width < 530.0F; + const float list_width = stacked ? width : std::clamp(width * 0.28F, 154.0F, 292.0F); + const float right_width = stacked ? width : width - list_width - gap; + const float workspace_height = std::max(180.0F, footer_top - start.y - gap); + + ImGui::PushID(state.personal_modded ? "modded-adventure" : "vanilla-adventure"); + const float list_height = DrawSavesSlotList(state, list_width, workspace_height, stacked, image); + const ImVec2 editor = {stacked ? start.x : start.x + list_width + gap, + stacked ? start.y + list_height + gap : start.y}; + const float editor_height = std::max(100.0F, start.y + workspace_height - editor.y); + PaintSaveWorkspacePanel(ImGui::GetWindowDrawList(), editor, {editor.x + right_width, editor.y + editor_height}); + ImGui::SetCursorScreenPos({editor.x + pad, editor.y + pad}); + const float inner = right_width - pad * 2.0F; + const int section = SettingsSectionSigns({"PROGRESS", "UNLOCKS", "FILES"}, int(state.section), inner, true); + if (section >= 0 && section != int(state.section)) { + state.section = static_cast(section); + state.scroll_editor_to_top = true; + } + if (SaveDraftLayoutCheck()) { + g_save_draft_geometry.slots = {start, {start.x + list_width, start.y + list_height}}; + g_save_draft_geometry.editor = {editor, {editor.x + right_width, editor.y + editor_height}}; + g_save_draft_geometry.selected_slot = state.selected_slot; + g_save_draft_geometry.modded = state.personal_modded; + } + PaddockGap(8.0F); + if (state.section == SaveEditorSection::Progress && valid && loaded) { + constexpr const char* all_label = "MAX OUT THIS SAVE"; + constexpr const char* slot_label = "Max out this slot"; + const float all_width = PaddockRaceButtonWidth(all_label); + const float slot_width = SettingsButtonWidth(slot_label); + const auto summary_type = PaddockReading(15.0F, true, 1.25F); + const std::string summary = + std::string(dkr::localisation::source(state.personal_modded ? "Modded Adventure" : "Vanilla Adventure")) + + " / Slot " + std::to_string(state.selected_slot + 1); + const float summary_width = PaddockMeasure(summary_type, summary) + 2.0F; + const float action_width = all_width + slot_width + gap; + const ImVec2 header = {editor.x + pad, ImGui::GetCursorScreenPos().y}; + const bool inline_summary = summary_width + action_width + gap <= inner; + ImGui::SetCursorScreenPos({header.x, header.y + (inline_summary ? 11.0F : 0.0F)}); + PaddockText(summary_type, PaddockRgb(kSetText), summary, inner); + const ImVec2 actions = {header.x + (inline_summary ? inner - action_width : 0.0F), + inline_summary ? header.y : ImGui::GetItemRectMax().y + 5.0F}; + ImGui::SetCursorScreenPos(actions); + if (SavesRaceButton(all_label, std::min(inner, all_width), SavesTone::Featured, locked)) { + state.slot = -1; + state.ask = SavesPageState::Ask::MaxOut; + } + if (action_width <= inner) + ImGui::SameLine(0.0F, gap); + else + ImGui::SetCursorScreenPos({actions.x, actions.y + 50.0F}); + if (SettingsButton(slot_label, std::min(inner, slot_width), locked)) { + state.slot = state.selected_slot; + state.ask = SavesPageState::Ask::MaxOut; + } + PaddockGap(10.0F); + } + const float body_top = ImGui::GetCursorScreenPos().y; + const float height = std::max(24.0F, editor.y + editor_height - pad - body_top); + ImGui::SetCursorScreenPos({editor.x + pad, body_top}); + const bool visible = ImGui::BeginChild("##adventure-editor", {inner, height}, false, + ImGuiWindowFlags_NavFlattened | ImGuiWindowFlags_NoBackground); + LibraryNavigationScrollWindow(ImGui::GetCurrentWindow()); + if (std::exchange(state.scroll_editor_to_top, false) || (SaveDraftLayoutCheck() && g_launcher_layout_step == 0)) + ImGui::SetScrollY(0.0F); + if (SaveDraftLayoutCheck()) { + g_save_draft_geometry.editor_scroll = ImGui::GetScrollY(); + g_save_draft_geometry.editor_body = ImGui::GetCurrentWindow()->OuterRectClipped; + } + if (visible) { + const float content_width = ImGui::GetContentRegionAvail().x - 4.0F; + ImGui::BeginDisabled(locked); + if (state.section == SaveEditorSection::Files) { + DrawSavesFiles(state, content_width, adventure, view); + } else if (!valid || !loaded) { + SavesNote(adventure.info.exists ? "This Adventure needs recovery." : "No Adventure save yet.", + content_width, 17.0F, kSetWarm); + if (SavesRaceButton("OPEN FILES")) + state.section = SaveEditorSection::Files; + } else if (state.section == SaveEditorSection::Progress) { + DrawSavesSlotEditor(state, content_width, state.selected_slot); + } else if (state.section == SaveEditorSection::Unlocks) { + DrawSavesUnlocks(state, content_width, content_width); + } + ImGui::EndDisabled(); + PaddockGap(8.0F); + } + ImGui::EndChild(); + ImGui::PopID(); + ImGui::SetCursorScreenPos({start.x, editor.y + editor_height}); + DrawSavesDraftBar(state, width, footer_top, footer, SavesDraftDirty(draft), locked, state.ask); +} + void DrawSaveManagerPage(float available_width, bool live) { using namespace dkr::runtime::saves; auto& state = g_saves_page; @@ -1058,79 +1145,63 @@ void DrawSaveManagerPage(float available_width, bool live) { const auto frame = ImGui::GetFrameCount(); const bool entered = state.context != ImGui::GetCurrentContext() || state.last_frame != frame - 1; if (entered || generation != g_shared_save_generation) { - state.summary.reset(); InvalidateSaveManagerViewCache(); ++g_shared_save_generation; generation = g_shared_save_generation; - // Preserve a dirty draft, but compare its revision at commit time. - // A clean draft can be safely reloaded after gameplay/return. - if (!SavesDraftDirty()) - SavesForgetDraft(); + for (auto& draft : g_adventure_drafts) + if (!SavesDraftDirty(draft)) + draft = {}; } state.context = ImGui::GetCurrentContext(); state.last_frame = frame; PumpSharedSaveJob(); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0}); + const auto heading = ImGui::GetCursorScreenPos(); DrawPageHeading("SAVE MANAGER"); - PaddockGap(14); + const auto after_heading = ImGui::GetCursorScreenPos(); + ImGui::SetCursorScreenPos({heading.x + width - 116.0F, heading.y + 12.0F}); + if (PaddockTextLink("Back to Play")) + g_page_navigation_request = kPagePlay; + ImGui::SetCursorScreenPos(after_heading); + PaddockGap(8); if (!g_save_manager_status.empty()) DrawFriendlyStatus(g_save_manager_status, width, dkr::runtime::copy::Area::Saves); const bool lobby = dkr::runtime::netplay::session().active(); const bool locked = live || lobby || SharedSaveBusy(); - const int current = state.scope == 0 ? 0 : state.scope == 1 ? 2 : 1; - const int picked = SettingsSectionSigns({"YOUR SAVE", "BACKUPS & RECOVERY", "ONLINE SAVES"}, current, width); - if (picked >= 0) { - state.scope = picked == 0 ? 0 : picked == 2 ? 1 : 3; + constexpr std::array scopes{0, 2, 1, 3, 4}; + const int current = static_cast(std::ranges::find(scopes, state.scope) - scopes.begin()); + const int picked = SettingsSectionSigns( + {"VANILLA SAVE", "MODDED SAVE", "ONLINE SAVES", "BACKUPS & RECOVERY", "CLOUD SAVES"}, current, width, true); + if (picked >= 0 && picked != current) { + state.scope = scopes[static_cast(picked)]; state.ask = SavesPageState::Ask::None; state.restore.clear(); + state.scroll_editor_to_top = true; + ImGui::SetScrollY(0.0F); } - PaddockGap(20); - SavesNote("Return to the launcher and leave your lobby before changing saves.", width); - if (state.scope != 0) + if (state.scope == 0 || state.scope == 2) + state.personal_modded = state.scope == 2; + PaddockGap(8); + if (live || lobby) + SavesNote("Return to the launcher and leave your lobby before changing saves.", width); + if (state.scope == 4) + DrawCloudSaves(width, locked); + else if (state.scope != 0 && state.scope != 2) DrawStoredSaves(state, width, locked); else { const auto& view = CachedSaveManagerView(); - const auto& info = view.adventure; + const auto& adventure = view.adventures[state.personal_modded]; if (!view.valid) { - SavesNote("Reading your personal save...", width); + SavesNote("Reading your Adventure save...", width); ImGui::PopStyleVar(); return; } - const bool valid = info.exists && info.valid; - SavesNote(valid ? "YOUR PERSONAL ADVENTURE" - : info.exists ? "YOUR SAVE NEEDS RECOVERY" - : "NO PERSONAL SAVE YET", - width, 19, valid ? kSavesAccent : kSetWarm); - if (lobby) - SavesNote("Leave the lobby before changing saves. You can export your personal save.", width); - if (SharedSaveBusy()) - SavesNote("Finishing the save operation. Launch is temporarily held until it is safe.", width); - { - ImGui::BeginDisabled(locked); - if (!info.valid && info.exists && info.size == 512) { - if (SavesRaceButton("BACK UP & REPAIR CHECKSUMS", 0, SavesTone::Primary)) - state.ask = SavesPageState::Ask::Repair; - PaddockGap(12); - } - ImGui::EndDisabled(); - const auto section = - SettingsSectionSigns({"OVERVIEW", "EDIT PROGRESS", "TRANSFER & PAKS"}, state.section, width); - if (section >= 0) - state.section = section; - PaddockGap(18); - ImGui::BeginDisabled(locked); - if (state.section == 1) - DrawSavesEditor(state, width, width, valid, info.exists); - else if (state.section == 2) - DrawSavesTransfer(width, width, view); - else - DrawSavesOverview(state, width, width, view, valid); - ImGui::EndDisabled(); - } + DrawSavesWorkspace(state, width, view, adventure, locked); } if (!g_shared_save_import.path.empty() && !locked) { state.restore = std::move(g_shared_save_import.path); state.slot = g_shared_save_import.port; + state.import_modded = g_shared_save_import.modded; state.ask = g_shared_save_import.kind == 1 ? SavesPageState::Ask::Bundle : g_shared_save_import.kind == 2 ? SavesPageState::Ask::Pak : SavesPageState::Ask::Import; diff --git a/runtime-recomp/src/game/runtime_settings_ui.inl b/runtime-recomp/src/game/runtime_settings_ui.inl index 88288a5e..a013d402 100644 --- a/runtime-recomp/src/game/runtime_settings_ui.inl +++ b/runtime-recomp/src/game/runtime_settings_ui.inl @@ -43,6 +43,7 @@ float SettingsHelp(std::string_view text, float width, unsigned colour = kSetMut // ------------------------------------------------------------ drop-down using SettingsChoice = dkr::localisation::Choice; +constexpr float kSettingsDropdownHeight = 52.0F; // The open list (.picker): a dark panel under its field, with a check on // the current choice. Returns the picked index, or -1. @@ -65,7 +66,8 @@ int DrawSettingsPicker(const char* popup, ImVec2 anchor_min, ImVec2 anchor_max, const float above = anchor_min.y - 6.0F - 12.0F; const bool flip = natural > below && above > below; const float height = std::min(natural, std::max(flip ? above : below, 120.0F)); - const ImVec2 at{anchor_min.x, flip ? anchor_min.y - 6.0F - height : anchor_max.y + 6.0F}; + const float left = std::clamp(anchor_min.x, 0.0F, std::max(0.0F, display.x - width - 12.0F)); + const ImVec2 at{left, flip ? anchor_min.y - 6.0F - height : anchor_max.y + 6.0F}; ImGui::SetNextWindowPos(at); ImGui::SetNextWindowSize({width, height}); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {6.0F, 6.0F}); @@ -164,10 +166,12 @@ int DrawSettingsPicker(const char* popup, ImVec2 anchor_min, ImVec2 anchor_max, return picked; } +// The default dropdown for launcher pages, with its label above the field. // A labelled drop-down: the field shows the current choice and opens the // list (dropdownRow). Returns true when the choice changed. bool SettingsDropdown(const char* id, std::string_view label, int* value, const std::vector& choices, - float width, bool disabled = false, std::string_view help = {}) { + float width, bool disabled = false, std::string_view help = {}, + float height = kSettingsDropdownHeight) { SettingsLabel(label, width); *value = std::clamp(*value, 0, std::max(static_cast(choices.size()) - 1, 0)); ImGui::PushID(id); @@ -175,7 +179,7 @@ bool SettingsDropdown(const char* id, std::string_view label, int* value, const const bool open = ImGui::IsPopupOpen(popup); if (disabled) ImGui::BeginDisabled(); - const PaddockPress press = PaddockBeginPress("##field", {width, 52.0F}); + const PaddockPress press = PaddockBeginPress("##field", {width, height}); if (disabled) ImGui::EndDisabled(); if (press.pressed && !disabled) @@ -195,10 +199,10 @@ bool SettingsDropdown(const char* id, std::string_view label, int* value, const choices.empty() ? dkr::localisation::source("Unavailable") : choices[static_cast(*value)].display_label(), width - 14.0F - 14.0F - 12.0F - 16.0F); - PaddockDrawRun(draw, type, {press.min.x + 15.0F, std::round(press.min.y + (52.0F - type.line) * 0.5F)}, + PaddockDrawRun(draw, type, {press.min.x + 15.0F, std::round(press.min.y + (height - type.line) * 0.5F)}, PaddockRgb(0xFFFFFF), shown.data(), shown.data() + shown.size()); if (!disabled) { - PaddockChevron(draw, {press.max.x - 14.0F - 2.0F - 6.0F, press.min.y + 52.0F * 0.5F - 3.0F}, 45.0F, 10.0F, + PaddockChevron(draw, {press.max.x - 14.0F - 2.0F - 6.0F, press.min.y + height * 0.5F - 3.0F}, 45.0F, 10.0F, PaddockRgb(0xFFFFFF), 2.5F); } OlFade(draw, first, disabled ? 0.6F : 1.0F); @@ -555,8 +559,8 @@ enum class SettingsButtonTone { inline float SettingsButtonWidth(std::string_view label) { const auto caption = dkr::localisation::label(label); - label = caption.c_str(); - return std::ceil(PaddockMeasure(PaddockReading(14.0F, true, 1.35F), label) + 28.0F + 2.0F); + const char* begin = caption.c_str(); + return std::ceil(PaddockMeasure(PaddockReading(14.0F, true, 1.35F), begin, PaddockLabelEnd(begin)) + 30.0F); } // .settings-button: the quiet action of the settings pages. width <= 0 sizes @@ -693,25 +697,26 @@ int SettingsSecondaryNav(const char* id, const std::vector& labels, // A row of painted section signs (.mods-section-nav), wrapping, with the // heavy hairline under it. Returns the picked index, or -1. -int SettingsSectionSigns(const std::vector& labels, int current, float width) { +int SettingsSectionSigns(const std::vector& labels, int current, float width, bool compact = false) { const ImVec2 at = ImGui::GetCursorScreenPos(); - const float tab_height = PaddockSectionTabHeight(); + const float tab_height = PaddockSectionTabHeight(compact); + const float gap = compact ? 6.0F : 10.0F; float x = at.x; float y = at.y; int picked = -1; for (std::size_t index = 0; index < labels.size(); ++index) { - const float tab = PaddockSectionTabWidth(labels[index]); + const float tab = std::min(width, PaddockSectionTabWidth(labels[index], compact)); if (x > at.x && x + tab > at.x + width) { x = at.x; - y += tab_height + 10.0F; + y += tab_height + gap; } ImGui::SetCursorScreenPos({x, y}); - if (PaddockSectionTab(labels[index], static_cast(index) == current)) { + if (PaddockSectionTab(labels[index], static_cast(index) == current, tab, compact)) { picked = static_cast(index); } - x += tab + 10.0F; + x += tab + gap; } - const float bottom = y + tab_height + 16.0F; + const float bottom = y + tab_height + (compact ? 8.0F : 16.0F); ImGui::GetWindowDrawList()->AddRectFilled({at.x, bottom}, {at.x + width, bottom + 2.0F}, PaddockCol(0x24495B)); ImGui::SetCursorScreenPos(at); ImGui::Dummy({width, bottom + 2.0F - at.y}); diff --git a/runtime-recomp/src/game/runtime_stubs.cpp b/runtime-recomp/src/game/runtime_stubs.cpp index 78f2b0c3..5ebb103b 100644 --- a/runtime-recomp/src/game/runtime_stubs.cpp +++ b/runtime-recomp/src/game/runtime_stubs.cpp @@ -15,6 +15,8 @@ #include "vi_presentation_policy.hpp" #include "widescreen_policy.hpp" #include "finish_presentation_policy.hpp" +#include "display_settings/policy.hpp" +#include "time_trial/session.hpp" #include "audio_event_queue.h" #include "track_select_draw_guest.h" #include "track_select_draw_policy.hpp" @@ -102,9 +104,10 @@ bool g_sky_cover_active = false; dkr::runtime::presentation::PostraceFrameGate g_postrace_frame_gate{}; bool g_postrace_world_framed = false; -float ExpandedCoverScale() { +float ExpandedCoverScale(bool use_replay_aspect = false) { using ultramodern::renderer::AspectRatio; - if (ultramodern::renderer::get_graphics_config().ar_option != AspectRatio::Expand) { + const bool replay = use_replay_aspect && dkr::runtime::time_trial::watching(); + if (!replay && ultramodern::renderer::get_graphics_config().ar_option != AspectRatio::Expand) { return 1.0F; } auto* window = static_cast(dkr::runtime::platform::sdl_window()); @@ -117,7 +120,9 @@ float ExpandedCoverScale() { if (width <= 0 || height <= 0) { return 1.0F; } - return std::max(1.0F, (static_cast(width) / static_cast(height)) / kOriginalAspect); + const float aspect = + replay ? dkr::display::view_aspect(width, height) : static_cast(width) / static_cast(height); + return std::max(1.0F, aspect / kOriginalAspect); } float ReadRdramFloat(std::uint8_t* rdram, std::uint32_t address) { @@ -402,9 +407,10 @@ extern "C" void dkr_split_screen_viewport_fill(std::uint8_t* rdram, recomp_conte rdram, context->r17, PresentationGroupMode::World, std::uint16_t(MEM_W(0, RdramAddress(dkr::runtime::revision_addresses::current().ActiveCameraId)) & 3U), 0U, PresentationMarkerKind::CameraWorldBegin); - const float cover = ExpandedCoverScale(); + const float cover = ExpandedCoverScale(true); const bool postrace = PostraceFullViewScope(rdram, cover); - g_postrace_world_framed = postrace && g_postrace_frame_gate.contracted_frame_submitted; + g_postrace_world_framed = + postrace && g_postrace_frame_gate.contracted_frame_submitted && !dkr::runtime::time_trial::watching(); if (postrace && !g_postrace_world_framed) { // Presentation-only viewport/scissor correction: leave the authored // viewport, camera, menu animation and shared simulation RAM intact. diff --git a/runtime-recomp/src/game/runtime_texture_packs.cpp b/runtime-recomp/src/game/runtime_texture_packs.cpp index 17d08812..59bd7097 100644 --- a/runtime-recomp/src/game/runtime_texture_packs.cpp +++ b/runtime-recomp/src/game/runtime_texture_packs.cpp @@ -1,3 +1,4 @@ +#include "time_trial/session.hpp" #include "storage/maintenance.hpp" #include "session_content/policy.hpp" #include "mod_store_install.hpp" @@ -1461,7 +1462,8 @@ void renderer_started() { } void apply_pending(RT64::Application& application, bool modern_profile) { - modern_profile = modern_profile && dkr::session_content::textures_allowed(); + // Recording restricts gameplay content. RT64 replacements only affect the picture. + modern_profile = modern_profile && (dkr::session_content::textures_allowed() || time_trial::recording()); std::vector replacements; std::vector previous_replacements; std::set replacement_ids; @@ -1492,6 +1494,12 @@ void apply_pending(RT64::Application& application, bool modern_profile) { directory = dkr::runtime::layout::windows_application_directory(directory / "DKR-R-Runtime.exe"); #endif const auto builtin = directory / "assets/ui/CustomTrackBackgrounds"; + if (time_trial::exporting_video()) { + const auto video_pack = directory / "assets/ui/RankedVideoTextures"; + std::error_code video_error; + if (std::filesystem::is_regular_file(video_pack / "rt64.json", video_error)) + replacements.emplace_back(video_pack); + } SDL_free(base); std::error_code error; if (std::filesystem::is_regular_file(builtin / "rt64.json", error)) diff --git a/runtime-recomp/src/game/runtime_ui.cpp b/runtime-recomp/src/game/runtime_ui.cpp index 3dc2d389..1cd27498 100644 --- a/runtime-recomp/src/game/runtime_ui.cpp +++ b/runtime-recomp/src/game/runtime_ui.cpp @@ -2,6 +2,7 @@ #include "launcher_themes/corner_atlas.hpp" #include "library_ui/control_layout.hpp" #include "library_ui/surface_policy.hpp" +#include "dialog_style.hpp" #include "launcher_themes/button_pattern_ui.hpp" #include "library_ui/handoff.hpp" #include "library_ui/launcher_fade.hpp" @@ -39,6 +40,9 @@ #include "sound_settings/policy.hpp" #include "overlay_settings/policy.hpp" #include "session_content/policy.hpp" +#include "time_trial/session.hpp" +#include "time_trial/options.hpp" +#include "time_trial/ghost_file.hpp" #include "analog_driving/settings.hpp" #include "look_behind/policy.hpp" #include "file_picker/client.hpp" @@ -52,6 +56,7 @@ #include "invite_handoff.hpp" #include #include "party_link.hpp" +#include "custom_records.hpp" #include "online_presentation/test_receive_delay.hpp" #include "online_stability/qualification_delivery.hpp" #include "runtime_ui.hpp" @@ -145,6 +150,8 @@ #include "runtime_texture_packs.hpp" #include "save_manager.hpp" #include "runtime_save_routing.hpp" +#include "personal_adventure_paths.hpp" +#include "cloud_saves/progress.hpp" #include "texture_pack_browser_policy.hpp" #include "ui_notification_policy.hpp" #include "virtual_pak.hpp" @@ -198,6 +205,7 @@ extern "C" bool dkr_show_metal_layer(void* ns_window_ptr, void* layer_ptr); #include #include #include +#include #include #include #include @@ -207,6 +215,13 @@ extern "C" bool dkr_show_metal_layer(void* ns_window_ptr, void* layer_ptr); #include #include +#if DKR_RUNTIME_HAS_RT64 +extern "C" { +extern const char SpeedrunningHudPreview[]; +extern const std::size_t SpeedrunningHudPreview_size; +} +#endif + namespace { // A single bounded checker texture replaces the old per-frame, per-strip @@ -458,6 +473,7 @@ struct OnlineHostRequest { dkr::runtime::netplay::CompatibilityManifest manifest; dkr::runtime::saves::OnlineSaveSeedMode save_mode; std::string room, name; + std::optional cloud_account; // Set once the pre-host check is scheduled. bool content_enabled = dkr::session_content::next_enabled.load(); }; std::optional g_online_mod_host_request; @@ -772,14 +788,15 @@ int g_shortcut_capture_count = 0; std::chrono::steady_clock::time_point g_shortcut_capture_deadline{}; std::string g_save_manager_status; bool g_play_offline_after_leave = false; +struct AdventureView { + dkr::runtime::saves::SaveInfo info; + std::optional image; +}; struct SaveManagerViewCache { bool valid = false; std::chrono::steady_clock::time_point next_refresh{}; - dkr::runtime::saves::SaveInfo adventure; + std::array adventures{}; std::array controller_paks{}; - std::vector adventure_backups; - std::optional image; - std::string preview; }; SaveManagerViewCache g_save_manager_view_cache; std::uint64_t g_save_cache_revision = 0; @@ -795,32 +812,26 @@ const SaveManagerViewCache& CachedSaveManagerView() { if (pending.valid() && pending.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { try { auto result = pending.get(); - if (result.first == g_save_cache_revision) { + if (result.first == g_save_cache_revision) g_save_manager_view_cache = std::move(result.second); - } } catch (const std::exception& e) { g_save_manager_status = e.what(); } } if (!pending.valid() && (!g_save_manager_view_cache.valid || now >= g_save_manager_view_cache.next_refresh)) { pending = std::async(std::launch::async, [generation = g_save_cache_revision] { + namespace saves = dkr::runtime::saves; SaveManagerViewCache view; - view.adventure = dkr::runtime::saves::adventure_info(); - dkr::runtime::saves::codec::SaveImage image; - std::string error; - if (view.adventure.valid && dkr::runtime::saves::load_adventure(image, error)) { - view.image = image; - for (unsigned i = 0; i < 3; ++i) { - if (i) - view.preview += " | "; - const auto& s = image.slots[i]; - view.preview += "Slot " + std::to_string(i + 1) + ": " + s.name + " (" + - std::to_string(s.balloons[0]) + " balloons)"; - } + for (const bool modded : {false, true}) { + auto& adventure = view.adventures[modded]; + adventure.info = saves::adventure_info(modded); + saves::codec::SaveImage image; + std::string error; + if (adventure.info.valid && saves::load_adventure(image, error, modded)) + adventure.image = std::move(image); } - for (int i = 0; i < 4; ++i) - view.controller_paks[i] = dkr::runtime::saves::controller_pak_info(i); - view.adventure_backups = dkr::runtime::saves::adventure_backups(); + for (int port = 0; port < saves::kControllerPakCount; ++port) + view.controller_paks[port] = saves::controller_pak_info(port); view.valid = true; view.next_refresh = std::chrono::steady_clock::now() + std::chrono::seconds(2); return std::pair{generation, std::move(view)}; @@ -834,8 +845,8 @@ bool g_online_compatibility_sync_requested = false; std::string g_controller_mapping_status; bool g_controller_mapping_popup_pending = false; bool g_controller_mapping_completion_saved = false; -std::optional g_save_builder_image; #include "shared_save_jobs.inl" +#include "cloud_saves/jobs.inl" bool HandleInputCaptureEvent(SDL_Event* event); @@ -1830,6 +1841,9 @@ void SaveSettings() { output << "online_local_view=" << unsigned(dkr::runtime::online_view::requested_layout.load()) << '\n'; output << "online_racer_labels=" << unsigned(dkr::runtime::online_view::requested_labels.load()) << '\n'; output << "online_label_size=" << dkr::runtime::online_view::requested_label_size.load() << '\n'; + namespace speed = dkr::runtime::speedrunning; + for (std::size_t i = 0; i < speed::settings.size(); ++i) + output << speed::prefix << speed::settings[i].key << '=' << speed::options.get(speed::Option(i)) << '\n'; output << "online_room_name=" << g_online_room_name << '\n'; output << "online_host_control=" << g_online_host_control << '\n'; output << "online_allow_spectators=" << (g_online_allow_spectators ? 1 : 0) << '\n'; @@ -1995,6 +2009,7 @@ bool LoadLegacyBindingSetting(const std::string& key, int number) { void LoadSettings() { dkr::library_ui::skip_launcher = false; + dkr::runtime::speedrunning::options.reset(); dkr::localisation::detect_system_language(); g_skip_intro = false; g_skip_intro_destination = 0; @@ -2087,6 +2102,8 @@ void LoadSettings() { dkr::runtime::online_view::requested_label_size = std::clamp(size, 75U, 150U); continue; } + if (dkr::runtime::speedrunning::options.parse(key, value)) + continue; bool controller_key = false; for (std::size_t player = 0; player < dkr::runtime::input::kPlayerCount; ++player) { const std::string expected = "player" + std::to_string(player + 1U) + ".controller_key"; @@ -3245,7 +3262,7 @@ void ImportMagicCodeWithDialog() { g_code_library.import_file(std::move(source)); } -bool ImportAdventureWithDialog() { +bool ImportAdventureWithDialog(bool modded) { if (SharedSaveBusy()) return false; if (NFD_Init() != NFD_OKAY) { @@ -3256,7 +3273,7 @@ bool ImportAdventureWithDialog() { const nfdfilteritem_t filters[] = {{"DKR Adventure save", "bin,eep"}}; const auto dialog = NFD_OpenDialogU8(&result, filters, 1, nullptr); if (dialog == NFD_OKAY) { - g_shared_save_import = {std::filesystem::u8path(result), 0, 0}; + g_shared_save_import = {std::filesystem::u8path(result), 0, 0, modded}; NFD_FreePathU8(result); } else if (dialog == NFD_ERROR) g_save_manager_status = NFD_GetError(); @@ -3301,7 +3318,7 @@ bool ExportAdventureWithDialog( return exported; } -bool ImportSaveBundleWithDialog() { +bool ImportSaveBundleWithDialog(bool modded) { if (SharedSaveBusy()) return false; if (NFD_Init() != NFD_OKAY) { @@ -3312,7 +3329,7 @@ bool ImportSaveBundleWithDialog() { const nfdfilteritem_t filters[] = {{"DKR-R save bundle", "dkrsave"}}; const auto dialog = NFD_OpenDialogU8(&result, filters, 1, nullptr); if (dialog == NFD_OKAY) { - g_shared_save_import = {std::filesystem::u8path(result), 1, 0}; + g_shared_save_import = {std::filesystem::u8path(result), 1, 0, modded}; NFD_FreePathU8(result); } else if (dialog == NFD_ERROR) g_save_manager_status = NFD_GetError(); @@ -3320,14 +3337,15 @@ bool ImportSaveBundleWithDialog() { return dialog == NFD_OKAY; } -bool ExportSaveBundleWithDialog() { +bool ExportSaveBundleWithDialog(bool modded) { if (NFD_Init() != NFD_OKAY) { g_save_manager_status = "The system file picker could not be initialized."; return false; } nfdchar_t* result = nullptr; const nfdfilteritem_t filters[] = {{"DKR-R save bundle", "dkrsave"}}; - const nfdresult_t dialog = NFD_SaveDialogU8(&result, filters, 1, nullptr, "dkr-port-save-garage.dkrsave"); + const nfdresult_t dialog = + NFD_SaveDialogU8(&result, filters, 1, nullptr, modded ? "dkr-modded.dkrsave" : "dkr-vanilla.dkrsave"); bool exported = false; if (dialog == NFD_OKAY) { auto destination = std::filesystem::u8path(result); @@ -3337,7 +3355,9 @@ bool ExportSaveBundleWithDialog() { } std::string error; exported = BeginSharedSaveJob( - [destination](std::string& error) { return dkr::runtime::saves::export_bundle(destination, error); }, + [destination, modded](std::string& error) { + return dkr::runtime::saves::export_bundle(destination, error, modded); + }, "Save bundle exported."); g_save_manager_status = exported ? "Exporting save bundle..." : error; } else if (dialog == NFD_ERROR) { @@ -3417,19 +3437,18 @@ bool BeginPaddedModal(const char* name, ImGuiWindowFlags flags = 0, const ImVec2 return BeginPaddockModalWindow(name, flags | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); } #endif - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, padding); - ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 18.0F); - // Fit smaller screens without changing normal-size layouts. Let the - // dialog scroll if needed so its actions remain reachable by controller. + // Fit smaller screens without changing normal-size layouts. Let the + // dialog scroll if needed so its actions remain reachable by controller. #if !defined(__ANDROID__) && !defined(DKR_IOS) flags &= ~(ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); const ImVec2 screen = ImGui::GetIO().DisplaySize; ImGui::SetNextWindowSizeConstraints({0.0F, 0.0F}, {std::max(screen.x - 24.0F, 1.0F), std::max(screen.y - 40.0F, 1.0F)}); #endif - const bool visible = ImGui::BeginPopupModal(name, nullptr, flags); - ImGui::PopStyleVar(2); - return visible; + if (!ImGui::IsPopupOpen(name)) + return ImGui::BeginPopupModal(name, nullptr, flags); + const dkr::runtime::ui::ScopedDialogStyle style(padding, 18.0F); + return ImGui::BeginPopupModal(name, nullptr, flags); } void DrawTexturePackImportModal() { @@ -6288,6 +6307,21 @@ bool OnlineNotificationActive() { return InviteUiVisible() || g_online_notifications.current(std::chrono::steady_clock::now()) != nullptr; } +void DrawSavingProgress() { + const auto* viewport = ImGui::GetMainViewport(); + const ImVec2 position{viewport->WorkPos.x + 16.F, viewport->WorkPos.y + viewport->WorkSize.y - 52.F}; + const auto caption = dkr::localisation::source("Saving Progress"); + const auto type = PaddockReading(14.F, true, 1.3F); + auto* draw = ImGui::GetForegroundDrawList(); + draw->AddRectFilled(position, {position.x + PaddockMeasure(type, caption) + 43.F, position.y + 36.F}, + PaddockCol(0x092737, 224), 8.F); + const float angle = float(std::fmod(ImGui::GetTime(), 1.0)) * 6.2831853F; + draw->PathArcTo({position.x + 16.F, position.y + 18.F}, 6.F, angle, angle + 4.6F, 16); + draw->PathStroke(PaddockCol(0x67DCC3), 0, 1.8F); + PaddockDrawRun(draw, type, {position.x + 30.F, position.y + (36.F - type.line) * 0.5F}, PaddockCol(0xFFF6DA), + caption.data(), caption.data() + caption.size()); +} + void DrawOnlineNotification() { DrawInviteUi(); const auto now = std::chrono::steady_clock::now(); @@ -7843,6 +7877,7 @@ void EndSettingsDialog(); bool SettingsDropdown(const char*, std::string_view, int*, std::initializer_list, float, bool, std::string_view); void DrawPlayUpdateButton(float); +#include "cloud_saves/play_ui.inl" #include "runtime_play_ui.inl" #include "runtime_online_ui.inl" #include "invite_ui.inl" @@ -8182,6 +8217,20 @@ void dkr::runtime::ui::configure(const std::filesystem::path& config_directory) dkr::runtime::netplay::session().configure_artifact_directory(config_directory / "netplay" / "replays"); RefreshCrtFilters(); LoadSettings(); + if (trial::exporting_video()) { + using namespace ultramodern::renderer; + auto graphics = get_graphics_config(); + graphics.rr_option = RefreshRate::Manual; + graphics.rr_manual_value = 60; + dkr::runtime::enhancements::set_texture_lod_bias_hundredths(0); + dkr::runtime::enhancements::set_generated_mipmaps_requested(true); + dkr::runtime::enhancements::set_anisotropy_level(16); + dkr::runtime::enhancements::set_presentation_profile(dkr::runtime::enhancements::PresentationProfile::Modern); + dkr::display::preference.aspect = dkr::display::Aspect::Wide; + dkr::display::preference.height = 0; + dkr::display::publish(); + set_graphics_config(graphics); + } if (!g_shared_online_policy_loaded) g_online_save_seed_mode = int(dkr::runtime::saves::OnlineSaveSeedMode::ContinuePreviousSession); dkr::store::installations().configure(g_config_directory, DKR_RELEASE_VERSION, mod_worker); @@ -8223,9 +8272,46 @@ void dkr::runtime::ui::persist_graphics_api_fallback() { std::fprintf(stderr, "[boot][settings] unavailable graphics API recovered to Automatic\n"); } +namespace { +using TransitionFrame = std::unique_ptr; +TransitionFrame run_return_frame(nullptr, SDL_FreeSurface); +bool run_return_cover_shown = false; + +TransitionFrame CaptureTransitionFrame(SDL_Renderer* renderer) { + TransitionFrame frame(nullptr, SDL_FreeSurface); + int width = 0, height = 0; + if (!SDL_GetRendererOutputSize(renderer, &width, &height) && width > 0 && width <= 8192 && height > 0 && + height <= 4320) { + frame.reset(SDL_CreateRGBSurfaceWithFormat(0, width, height, 32, SDL_PIXELFORMAT_RGBA32)); + if (frame && SDL_RenderReadPixels(renderer, nullptr, SDL_PIXELFORMAT_RGBA32, frame->pixels, frame->pitch)) + frame.reset(); + } + return frame; +} +} // namespace + +void dkr::runtime::ui::show_run_return_cover(bool force) { + if (!run_return_cover_shown && run_return_frame && (force || trial::launcher_return_opacity() >= 1.F)) { + dkr::runtime::platform::show_startup_cover(run_return_frame.get(), true); + run_return_cover_shown = true; + } +} + dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* window, const std::filesystem::path& preselected_rom, bool software_failure_recovery) { + if (trial::take_restart_request() && g_previous_time_trial_request) { + g_time_trial_request = std::exchange(g_previous_time_trial_request, std::nullopt); + } else { + if (g_previous_time_trial_request && g_previous_time_trial_request->mode == trial::Mode::Record) { + ApplyReplayRetention(trial::last_result()); + g_open_speedrunning_result = true; + if (!RunPreference(RunOption::RememberSetup)) + g_run_setup = {}; + } + g_previous_time_trial_request.reset(); + DeleteRankedPlayback(std::exchange(g_ranked_playback_file, {})); + } StartupResult result{}; dkr::runtime::startup::prepare_launch(false, false, false); if (window == nullptr) { @@ -8340,6 +8426,19 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* ImGui_ImplSDL2_InitForSDLRenderer(window, renderer); ImGui_ImplSDLRenderer2_Init(renderer); dkr::store::service().gameplay(false); + std::string cloud_sync_attempted; + const auto request_cloud_sync = [&](bool force, + dkr::cloud_saves::SyncScope scope = dkr::cloud_saves::SyncScope::All) { + if (SharedSaveBusy()) + return false; + const auto account = EnabledCloudSaveAccount(); + if (account.empty() || (!force && cloud_sync_attempted == account) || !RunCloudSaveSync(account, scope)) + return false; + if (scope == dkr::cloud_saves::SyncScope::All) + cloud_sync_attempted = account; + return true; + }; + bool cloud_return_pending = !preselected_rom.empty(); g_mod_store_renderer = renderer; g_store_in_game = false; g_character_portrait_renderer = renderer; @@ -8429,6 +8528,8 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* } int page = 0; + if (!dkr::runtime::time_trial::last_result().message.empty()) + page = dkr::library_ui::LeaderboardsPage; int last_rendered_page = -1; int sidebar_selection = 0; bool focus_content = true; @@ -8437,6 +8538,18 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* dkr::library_ui::startup_screen_seen, !preselected_rom.empty(), software_failure_recovery); dkr::library_ui::LauncherFade launch_fade; + TransitionFrame trial_handoff_image(nullptr, SDL_FreeSurface); + TransitionFrame next_return_frame(nullptr, SDL_FreeSurface); + bool return_frame_captured = false; + std::unique_ptr return_fade( + run_return_cover_shown && run_return_frame ? SDL_CreateTextureFromSurface(renderer, run_return_frame.get()) + : nullptr, + SDL_DestroyTexture); + if (return_fade) + SDL_SetTextureBlendMode(return_fade.get(), SDL_BLENDMODE_BLEND); + run_return_frame.reset(); + run_return_cover_shown = false; + double return_fade_started = -1; dkr::library_ui::runtime_intro.clear(); bool online_start_pending = false; bool launch_requested = false; @@ -8447,7 +8560,13 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* bool request_restart_popup = false; while (running) { g_legacy_imports.tick(); - dkr::runtime::saves::set_online_save_protection(dkr::runtime::netplay::session().active()); + const bool lobby_active = dkr::runtime::netplay::session().active(); + dkr::runtime::saves::set_online_save_protection(lobby_active); + if (cloud_return_pending) { + using dkr::cloud_saves::SyncScope; + if (request_cloud_sync(true, lobby_active ? SyncScope::PublishHostedOnline : SyncScope::All)) + cloud_return_pending = false; + } if (g_play_offline_after_leave && !dkr::runtime::netplay::session().active()) { g_play_offline_after_leave = false; launch_requested = true; @@ -8643,10 +8762,9 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* g_online_mod_identity = rom_ready ? online_manifest_identity : dkr::runtime::rom::Identity{}; PumpOnlineMods(); PumpInviteLauncher(rom_ready, online_manifest.has_value()); - if (rom_ready && !online_start_pending && dkr::runtime::netplay::session().consume_launch_request()) { + if (rom_ready && !online_start_pending && !SharedSaveBusy() && + dkr::runtime::netplay::session().consume_launch_request()) { dkr::runtime::startup_performance::mark("launcher-online-launch-requested"); - if (SharedSaveBusy()) - continue; online_start_pending = true; } if (online_start_pending && !dkr::runtime::netplay::session().active()) { @@ -8662,8 +8780,8 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* } constexpr int launcher_page_count = kMenuPageCount; constexpr int launcher_sidebar_count = kMenuPageCount + 3; - if (page >= launcher_page_count) { - page = 0; + if (!dkr::library_ui::is_content_page(page)) { + page = kPagePlay; } const auto launcher_events_started = std::chrono::steady_clock::now(); launcher_profile.add(LauncherProfile::Services, launcher_services_started, launcher_events_started); @@ -8804,9 +8922,10 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* { const auto preparation = g_mod_launch.snapshot(); - const bool busy = dkr::crash_reports::view().consent.choice == -1 || g_legacy_imports.snapshot().busy || - g_code_library.view()->busy || g_vehicle_library.view()->busy || - bool(g_vehicle_library.view()->pending) || dkr::store::installations().view()->busy; + const bool busy = SharedSaveBusy() || dkr::crash_reports::view().consent.choice == -1 || + g_legacy_imports.snapshot().busy || g_code_library.view()->busy || + g_vehicle_library.view()->busy || bool(g_vehicle_library.view()->pending) || + dkr::store::installations().view()->busy; const auto action = online_start_pending ? dkr::library_ui::AutomaticStart::Action::None @@ -8822,25 +8941,59 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* std::fprintf(stderr, "[launcher][automatic-start] showing launcher for selection, cancellation or recovery\n"); } + const bool trial_fade_finished = + g_time_trial_request && launch_fade.started() && launch_fade.finished(PaddockClock()); + const bool capture_return_frame = trial_fade_finished && !return_frame_captured; + if (trial_fade_finished && !capture_return_frame) { + auto trial = std::move(*g_time_trial_request); + g_time_trial_request.reset(); + if (dkr::runtime::netplay::session().active()) { + g_time_trial_message = "Leave your lobby to start Time Trial."; + } else if (!rom_ready) { + g_time_trial_message = "Select a US v1.0 or US v1.1 ROM in Play first."; + } else if (const auto trial_rom = TimeTrialRom(trial, selected_rom, rom_catalog); + !trial_rom.empty() && LaunchTimeTrial(trial)) { + g_time_trial_message.clear(); + result.start_game = true; + result.rom_path = trial_rom; + dkr::runtime::startup::prepare_launch(false, false, false, dkr::runtime::startup::Destination{}); + dkr::library_ui::runtime_intro.begin(false, launcher_theme.seconds()); + dkr::runtime::platform::show_startup_cover(trial_handoff_image.get()); + run_return_frame = std::move(next_return_frame); + dkr::runtime::time_trial::enable_launcher_return(); + g_ranked_podium_started = -1; + g_theatre_controls = true; + g_theatre_inputs = RunPreference(RunOption::ReplayInputs) != 0; + g_theatre_controller_corner = -1; + g_theatre_activity = SDL_GetTicks64(); + std::fprintf(stderr, "[startup][time-trial] shared starting screen\n"); + g_previous_time_trial_request = std::move(trial); + running = false; + continue; + } + trial_handoff_image.reset(); + next_return_frame.reset(); + return_frame_captured = false; + DeleteRankedPlayback(std::exchange(g_ranked_playback_file, {})); + } if (launch_requested && dkr::crash_reports::view().consent.choice == -1) launch_requested = false; - if (launch_requested) { + if (launch_requested && !SharedSaveBusy()) { launch_requested = false; - if (!dkr::runtime::netplay::session().active() && !dkr::store::installations().view()->busy && - dkr::store::installations().view()->ready && !g_legacy_imports.snapshot().busy && - !g_code_library.view()->busy && !g_mod_launch.snapshot().modal) { + if (!dkr::runtime::netplay::session().active() && !OnlineModSelectionLocked() && + !dkr::store::installations().view()->busy && dkr::store::installations().view()->ready && + !g_legacy_imports.snapshot().busy && !g_code_library.view()->busy && !g_mod_launch.snapshot().modal) { mod_launch_rom = selected_rom; - if (!SharedSaveBusy()) { - if (!automatic_start.active()) { - automatic_start.manual(AutomaticStartHasMods()); - std::fprintf(stderr, "[startup][manual] shared starting screen\n"); - } - g_mod_launch.start(g_config_directory, mod_launch_rom, false); + if (!automatic_start.active()) { + automatic_start.manual(AutomaticStartHasMods()); + std::fprintf(stderr, "[startup][manual] shared starting screen\n"); } + request_cloud_sync(true); + g_mod_launch.start(g_config_directory, mod_launch_rom, false); } } - if (const auto prepared = g_mod_launch.snapshot(); - prepared.modal && prepared.prepared && !prepared.busy && launch_fade.finished(PaddockClock())) { + if (const auto prepared = g_mod_launch.snapshot(); prepared.modal && prepared.prepared && !prepared.busy && + !SharedSaveBusy() && launch_fade.finished(PaddockClock())) { // The modal owns the selection while preparing; do not admit a // local bank if an online session began in the meantime. if (dkr::runtime::netplay::session().active()) { @@ -8848,8 +9001,6 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* rom_status = "Custom launch cancelled because an online lobby became active."; } else { dkr::runtime::startup_performance::mark("launcher-local-launch-requested"); - if (SharedSaveBusy()) - continue; result.start_game = true; result.rom_path = mod_launch_rom; result.mods = prepared.prepared; @@ -8918,7 +9069,23 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* // The opaque cloud backdrop (or opaque missing-asset fallback) covers // this entire undecorated window. Drawing ImGui's background underneath // it wastes a full software-rendered viewport every frame. - if (online_start_pending && launch_fade.started()) { + if (capture_return_frame) { + DrawAutomaticStart(automatic_start, launcher_background, renderer, launcher_background_scroll, + bounded_software_return, launcher_theme.theme(), launcher_theme.seconds(), nullptr, + false, true); + } else if (g_time_trial_request && launch_fade.started()) { + dkr::mods::ModLaunchView trial_status; + trial_status.stage = g_time_trial_request->mode == trial::Mode::Watch ? "Opening replay..." + : !g_time_trial_request->ghost.empty() ? "Loading ghost..." + : "Starting run..."; + if (DrawAutomaticStart(automatic_start, launcher_background, renderer, launcher_background_scroll, + bounded_software_return, launcher_theme.theme(), launcher_theme.seconds(), + &trial_status)) { + g_time_trial_request.reset(); + DeleteRankedPlayback(std::exchange(g_ranked_playback_file, {})); + launch_fade.clear(); + } + } else if (online_start_pending && launch_fade.started()) { if (DrawAutomaticStart(automatic_start, launcher_background, renderer, launcher_background_scroll, bounded_software_return, launcher_theme.theme(), launcher_theme.seconds(), nullptr, true)) { @@ -8939,6 +9106,12 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* launcher_theme.seconds(), dkr::launcher_themes::preferences.calendar); if (launcher_profile.enabled()) ImGui::GetWindowDrawList()->AddCallback(LauncherDrawProfileRange::end, &background_profile); + if (const int requested = std::exchange(g_page_navigation_request, -1); + dkr::library_ui::is_content_page(requested)) { + focus_content |= page != requested; + page = requested; + sidebar_selection = dkr::library_ui::sidebar_parent(page); + } #if defined(__ANDROID__) || defined(DKR_IOS) dkr::runtime::mobile::menu(page, false, request_restart_popup, request_quit_popup); dkr::runtime::mobile::begin_content(); @@ -8977,11 +9150,6 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* sidebar_layout.item_spacing_y, sidebar_layout.action_section_gap, sidebar_layout.action_gap, kSidebarOrder.size() - 3); ImGui::SetCursorPosY(sidebar_position.navigation); - if (g_page_navigation_request >= 0) { - page = g_page_navigation_request; - sidebar_selection = page; - g_page_navigation_request = -1; - } ImGui::PushItemFlag(ImGuiItemFlags_NoNav, true); ++g_race_button_sidebar; LibraryNavigationCheckRoute(false, page); @@ -9129,6 +9297,9 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* DrawLauncherFade(launch_fade, PaddockClock()); PumpDialogJob(); PumpSharedSaveJob(); + if (!launch_requested && !automatic_start.active() && !online_start_pending && !OnlineModSelectionLocked() && + !dkr::runtime::netplay::session().active()) + request_cloud_sync(false); PumpModStoreLauncher(); DrawTexturePackImportModal(); DrawPaddockLegacyModImportModal(); @@ -9192,17 +9363,43 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* #endif RenderLauncherDrawData(renderer, launcher_draw_data, launcher_profile, launcher_panel_cache, bounded_software_return); + if (capture_return_frame) { + // Prepare the matching cover off-screen while the normal start + // frame stays visible. The game and launcher never share textures. + next_return_frame = CaptureTransitionFrame(renderer); + return_frame_captured = true; + continue; + } // SDL's software backend normally executes its queued drawing inside // Present. Flush only in the opt-in profiler to separate those costs. if (launcher_profile.enabled()) SDL_RenderFlush(renderer); const auto launcher_draw_finished = std::chrono::steady_clock::now(); - if (!launch_requested && !automatic_start.active() && !online_start_pending) + if (!launch_requested && !automatic_start.active() && !online_start_pending && !g_time_trial_request) launch_fade.clear(); - if ((launch_requested && !automatic_start.active()) || (online_start_pending && !launch_fade.started())) + if (!g_time_trial_request) + trial_handoff_image.reset(); + if (g_time_trial_request && launch_fade.started() && !trial_handoff_image && + launch_fade.opacity(PaddockClock()) < .25F) { + trial_handoff_image = CaptureTransitionFrame(renderer); + } + if ((launch_requested && !automatic_start.active()) || + ((online_start_pending || g_time_trial_request) && !launch_fade.started())) launch_fade.capture(renderer, PaddockClock()); LibraryCaptureHandoff(renderer, launch_fade, automatic_start.active()); - LauncherLayoutCheckCapture(renderer); + LauncherLayoutCheckCapture(renderer, page); + if (return_fade) { + const double now = PaddockClock(); + if (return_fade_started < 0) + return_fade_started = now; + const double opacity = 1.0 - std::clamp((now - return_fade_started) / .24, 0.0, 1.0); + if (opacity > 0) { + SDL_SetTextureAlphaMod(return_fade.get(), static_cast(255 * opacity)); + SDL_RenderCopy(renderer, return_fade.get(), nullptr, nullptr); + } else { + return_fade.reset(); + } + } SDL_RenderPresent(renderer); const auto launcher_present_finished = std::chrono::steady_clock::now(); launcher_present_microseconds += static_cast( @@ -9210,6 +9407,7 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* .count()); ++launcher_rendered_frames; if (launcher_rendered_frames == 1U) { + dkr::runtime::platform::finish_run_return_cover(); if (software_failure_recovery && !(SDL_GetWindowFlags(window) & (SDL_WINDOW_HIDDEN | SDL_WINDOW_MINIMIZED))) { SDL_RaiseWindow(window); @@ -9277,6 +9475,7 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* ReleaseCharacterPortraits(); ReleaseModStoreTextures(); launch_fade.clear(); + return_fade.reset(); SDL_DestroyRenderer(renderer); const auto launcher_elapsed_microseconds = std::chrono::duration_cast( std::chrono::steady_clock::now() - launcher_animation_epoch) @@ -9353,6 +9552,28 @@ void dkr::runtime::ui::detach(RT64::Application& application) { } } +bool dkr::runtime::ui::draw_replay_video_inputs(RT64::Application& application) { + if (application.presentQueue == nullptr || application.framebufferGraphicsWorker == nullptr) + return false; + if (application.presentQueue->inspector == nullptr) + attach(application); + auto* inspector = application.presentQueue->inspector.get(); + if (inspector == nullptr) + return false; + inspector->newFrame(application.framebufferGraphicsWorker.get()); + ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4{.035F, .10F, .17F, 1.F}); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 10.F); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {10.F, 8.F}); + const auto state = dkr::runtime::time_trial::progress(); + if (state.adventure != dkr::runtime::time_trial::Adventure::None) + DrawTimeTrialHud(true); + DrawReplayInputViewer(state, true); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(); + inspector->endFrame(); + return true; +} + void dkr::runtime::ui::draw(RT64::Application& application) { // Publish only an atomic value; the raster worker snapshots it into the // next pass's push constants. No GPU resources or samplers are rebuilt. @@ -9363,6 +9584,9 @@ void dkr::runtime::ui::draw(RT64::Application& application) { if (application.presentQueue == nullptr || application.framebufferGraphicsWorker == nullptr) { return; } + if (dkr::runtime::time_trial::exporting_video()) + // Capture builds only the controller overlay before each authored present. + return; PumpFriendPresence(); if (!g_overlay_visible.load()) LibraryCancelAnalogueCapture(); @@ -9376,6 +9600,7 @@ void dkr::runtime::ui::draw(RT64::Application& application) { (dkr::runtime::netplay::session().runtime_view().active && dkr::runtime::netplay::session().runtime_view().state == dkr::runtime::netplay::ConnectionState::Loading); const bool show_overlay = g_overlay_visible.load(std::memory_order_acquire); + const bool show_time_trial = dkr::runtime::time_trial::active(); const bool show_fps = g_fps_overlay_enabled && dkr::runtime::enhancements::modern_presentation_enabled(); const bool show_crt = g_crt_enabled && g_crt_strength > 0.0F && dkr::runtime::enhancements::modern_presentation_enabled() && g_crt_filter_index >= 0 && @@ -9391,6 +9616,7 @@ void dkr::runtime::ui::draw(RT64::Application& application) { online_session_view.launch_countdown_active && online_session_view.launch_countdown_remaining_ms > 0U; const bool show_online_waiting = OnlineWaitingActive(online_session_view); const bool show_achievement_toast = AchievementToastVisible(); + const bool show_saving_progress = !show_overlay && dkr::cloud_saves::progress_writes.visible(); const bool show_mipmap_loading = RT64::mipLoadingVisible(); const bool show_camera_tuning = CameraTuningVisible(); const bool show_session_chat = @@ -9401,11 +9627,11 @@ void dkr::runtime::ui::draw(RT64::Application& application) { #if defined(__ANDROID__) || defined(DKR_IOS) false && // Touch Menu remains available, even when all other overlays are off. #endif - !show_starting_game && !show_achievement_toast && !show_overlay && !show_fps && !show_crt && - !show_online_error && !show_online_failure_modal && !show_online_notification && !show_network && + !show_starting_game && !show_achievement_toast && !show_saving_progress && !show_overlay && !show_fps && + !show_crt && !show_online_error && !show_online_failure_modal && !show_online_notification && !show_network && !show_controller_input && !show_online_countdown && !show_online_waiting && !show_mipmap_loading && - !show_camera_tuning && !show_session_chat && !keep_owned_ui && !dkr::sdk2::tools_open.load() && - !dkr::sdk2::debug_available()) { + !show_camera_tuning && !show_session_chat && !show_time_trial && !keep_owned_ui && + !dkr::sdk2::tools_open.load() && !dkr::sdk2::debug_available()) { if (application.presentQueue->inspector != nullptr) { detach(application); } @@ -9420,8 +9646,8 @@ void dkr::runtime::ui::draw(RT64::Application& application) { if (application.presentQueue->inspector == nullptr) { return; } - if (show_starting_game || show_overlay || show_camera_tuning || dkr::chat::typing.load() || - dkr::runtime::invites::dialog()) { + if (show_starting_game || show_overlay || dkr::runtime::time_trial::watching() || show_camera_tuning || + dkr::chat::typing.load() || dkr::runtime::invites::dialog()) { dkr::runtime::platform::update_ui_gamepad_navigation(); } RT64::Inspector* inspector = application.presentQueue->inspector.get(); @@ -9458,7 +9684,7 @@ void dkr::runtime::ui::draw(RT64::Application& application) { dkr::runtime::hud::set_viewport_extent(hud_viewport_width, hud_viewport_height); } ApplyStyle(); - if (DrawRuntimeStartingGame()) { + if (DrawRuntimeReturningFromRun() || DrawRuntimeStartingGame()) { DrawOnlineFailureModal(); if (show_online_error) DrawOnlineErrorNotification(); @@ -9502,7 +9728,14 @@ void dkr::runtime::ui::draw(RT64::Application& application) { } else if (sidebar_action == 2) { request_quit_popup = true; } - const bool focus_selected_page = g_overlay_focus_requested.exchange(false, std::memory_order_acq_rel); + bool focus_selected_page = g_overlay_focus_requested.exchange(false, std::memory_order_acq_rel); + if (const int requested = std::exchange(g_page_navigation_request, -1); + dkr::library_ui::is_content_page(requested)) { + focus_selected_page |= g_overlay_page.load(std::memory_order_relaxed) != requested; + g_overlay_page.store(requested, std::memory_order_relaxed); + sidebar_selection = dkr::library_ui::sidebar_parent(requested); + g_overlay_sidebar_selection.store(sidebar_selection, std::memory_order_release); + } #if defined(__ANDROID__) || defined(DKR_IOS) int mobile_page = g_overlay_page.load(std::memory_order_relaxed); dkr::runtime::mobile::menu(mobile_page, true, request_restart_popup, request_quit_popup); @@ -9541,12 +9774,6 @@ void dkr::runtime::ui::draw(RT64::Application& application) { ImGui::SetCursorPosY(sidebar_position.navigation); // The sidebar is a shoulder-button rail. Excluding its widgets from // ImGui navigation keeps the D-pad entirely inside the content panel. - if (g_page_navigation_request >= 0) { - sidebar_selection = g_page_navigation_request; - g_overlay_page = sidebar_selection; - g_overlay_sidebar_selection.store(sidebar_selection, std::memory_order_release); - g_page_navigation_request = -1; - } ImGui::PushItemFlag(ImGuiItemFlags_NoNav, true); ++g_race_button_sidebar; LibraryNavigationCheckOverlayRoute(); @@ -9706,6 +9933,16 @@ void dkr::runtime::ui::draw(RT64::Application& application) { #endif DrawPinnedAchievement(); DrawAchievementToast(); + if (show_saving_progress) + DrawSavingProgress(); + if (show_time_trial && !show_overlay) { + DrawTimeTrialHud(); + if (!show_starting_game && dkr::runtime::time_trial::watching()) + DrawReplayTheatre(); + } + if (show_time_trial) + DrawRankedPodium(); + DrawSpeedrunningRestartConfirmation(); dkr::store::overlay::end(); inspector->endFrame(); } @@ -9722,6 +9959,14 @@ bool dkr::runtime::ui::handle_runtime_event(SDL_Event* event) { if (event == nullptr) { return false; } + if (dkr::runtime::time_trial::watching() && HandleTheatreInput(*event)) + return true; + if (trial::restart_confirmation_pending() && + ((event->type == SDL_KEYDOWN && event->key.keysym.scancode == SDL_SCANCODE_ESCAPE) || + (event->type == SDL_CONTROLLERBUTTONDOWN && event->cbutton.button == SDL_CONTROLLER_BUTTON_B))) { + trial::confirm_restart(false); + return true; + } if (dkr::library_ui::runtime_intro_visible.load() && ((event->type == SDL_KEYDOWN && event->key.keysym.scancode == SDL_SCANCODE_ESCAPE) || (event->type == SDL_CONTROLLERBUTTONDOWN && event->cbutton.button == SDL_CONTROLLER_BUTTON_B))) { @@ -9806,8 +10051,8 @@ bool dkr::runtime::ui::handle_runtime_event(SDL_Event* event) { (event->type == SDL_CONTROLLERDEVICEREMOVED || (event->type == SDL_WINDOWEVENT && event->window.event == SDL_WINDOWEVENT_FOCUS_LOST))) dkr::runtime::hud::editor::interrupt_move(); - if (!dkr::runtime::hud::editor::active() && event->type == SDL_KEYDOWN && event->key.repeat == 0 && - event->key.keysym.scancode == SDL_SCANCODE_ESCAPE) { + if (!dkr::runtime::time_trial::watching() && !dkr::runtime::hud::editor::active() && event->type == SDL_KEYDOWN && + event->key.repeat == 0 && event->key.keysym.scancode == SDL_SCANCODE_ESCAPE) { toggle_overlay(); return true; } @@ -9865,7 +10110,8 @@ bool dkr::runtime::ui::handle_runtime_event(SDL_Event* event) { } bool dkr::runtime::ui::input_capture_active() { - return dkr::library_ui::runtime_intro_visible.load() || dkr::chat::captures_game_input() || + return dkr::library_ui::runtime_intro_visible.load() || dkr::runtime::time_trial::watching() || + trial::restart_confirmation_pending() || dkr::chat::captures_game_input() || #if defined(__ANDROID__) || defined(DKR_IOS) dkr::runtime::mobile::editing() || #endif diff --git a/runtime-recomp/src/game/runtime_ui.hpp b/runtime-recomp/src/game/runtime_ui.hpp index 7c8489f4..0f9ecbf4 100644 --- a/runtime-recomp/src/game/runtime_ui.hpp +++ b/runtime-recomp/src/game/runtime_ui.hpp @@ -61,6 +61,8 @@ StartupResult run_startup_screen(SDL_Window* window, const std::filesystem::path void attach(RT64::Application& application); void detach(RT64::Application& application); void draw(RT64::Application& application); +bool draw_replay_video_inputs(RT64::Application& application); +void show_run_return_cover(bool force = false); bool handle_runtime_event(SDL_Event* event); // Once per event pump, after the events: captures the pointer for the Modern // camera's mouse orbit while racing, and lets it go when anything needs it. diff --git a/runtime-recomp/src/game/runtime_ui_paddock.inl b/runtime-recomp/src/game/runtime_ui_paddock.inl index 7903ba1d..f18ce021 100644 --- a/runtime-recomp/src/game/runtime_ui_paddock.inl +++ b/runtime-recomp/src/game/runtime_ui_paddock.inl @@ -961,22 +961,22 @@ inline bool PaddockTextLink(const char* label) { return press.pressed; } -inline float PaddockSectionTabWidth(const char* label) { - const PaddockType type = PaddockSign(19.0F, 1.4F); - return std::ceil(7.0F + 9.0F + PaddockMeasure(type, label, PaddockLabelEnd(label)) + 32.0F + 4.0F); +inline float PaddockSectionTabWidth(const char* label, bool compact = false) { + const PaddockType type = PaddockSign(compact ? 14.0F : 19.0F, 1.4F); + return std::ceil(PaddockMeasure(type, label, PaddockLabelEnd(label)) + (compact ? 26.0F : 52.0F)); } -inline float PaddockSectionTabHeight() { - return std::ceil(PaddockSign(19.0F, 1.4F).line + 20.0F + 4.0F); +inline float PaddockSectionTabHeight(bool compact = false) { + return std::ceil(PaddockSign(compact ? 14.0F : 19.0F, 1.4F).line + 24.0F); } // A launcher-lettered tab with a turning chevron (.mods-section-nav button). // `stretch` > 0 widens it, label left-aligned (.texture-disclosure). -inline bool PaddockSectionTab(const char* label, bool open, float stretch = 0.0F) { - const PaddockType type = PaddockSign(19.0F, 1.4F); +inline bool PaddockSectionTab(const char* label, bool open, float stretch = 0.0F, bool compact = false) { + const PaddockType type = PaddockSign(compact ? 14.0F : 19.0F, 1.4F); const char* end = PaddockLabelEnd(label); - const float width = std::max(PaddockSectionTabWidth(label), stretch); - const float height = PaddockSectionTabHeight(); + const float width = std::max(PaddockSectionTabWidth(label, compact), stretch); + const float height = PaddockSectionTabHeight(compact); const PaddockPress press = PaddockBeginPress(label, {width, height}); const float opened = PaddockEase(PaddockTween(PaddockKey("open", press.id), open, 0.2F, 0.2F)); ImDrawList* draw = ImGui::GetWindowDrawList(); @@ -995,10 +995,10 @@ inline bool PaddockSectionTab(const char* label, bool open, float stretch = 0.0F PaddockPanel(draw, press.min, press.max, panel); const ImU32 text = PaddockApply(state(0xFFF2C8, 0xFFF7DC, 0xFFF5D5)); const float content_top = press.min.y + 12.0F; - const float chevron_x = press.min.x + 18.0F + 3.5F - 2.0F * (1.0F - opened); + const float chevron_x = press.min.x + (compact ? 8.0F : 18.0F) + 3.5F - 2.0F * (1.0F - opened); const float chevron_y = content_top + type.line * 0.5F - 2.0F * opened; PaddockChevron(draw, {chevron_x, chevron_y}, -45.0F + 90.0F * opened, 7.0F, text, 1.5F); - const float text_x = press.min.x + 18.0F + 7.0F + 9.0F; + const float text_x = press.min.x + (compact ? 18.0F : 34.0F); PaddockDrawRun(draw, type, {text_x, content_top + 2.0F}, PaddockCol(0x031623), label, end); PaddockDrawRun(draw, type, {text_x, content_top}, text, label, end); PaddockEndPress(press, 12.0F); @@ -1039,6 +1039,7 @@ inline bool PaddockSwitch(const char* id, bool* value, const char* on_label, con 24.0F + 12.0F + std::ceil(std::max(PaddockMeasure(type, on_label), PaddockMeasure(type, off_label))); const PaddockPress press = PaddockBeginPress(id, {width, 42.0F}); if (description != nullptr && ImGui::IsItemHovered()) { + const dkr::runtime::ui::ScopedDialogStyle style({12.0F, 8.0F}, 10.0F); ImGui::SetTooltip("%s", description); } bool changed = false; @@ -1113,14 +1114,14 @@ inline bool PaddockCheckbox(const char* id, const char* label, bool* value, floa enum class PaddockFieldResult { None, Edited, GamepadActivated }; -// A fixed-size keyboard affordance leaves room for the editable text instead -// of squeezing a word button into narrow fields. -inline bool PaddockKeyboardButton() { - const auto press = PaddockBeginPress("##keyboard", {44, 44}); +// The keyboard icon keeps its width in narrow fields. +inline bool PaddockKeyboardButton(float height = 44.0F) { + const auto press = PaddockBeginPress("##keyboard", {44.0F, height}); auto* draw = ImGui::GetWindowDrawList(); PaddockFill(draw, press.min, press.max, PaddockRound(8), PaddockCol(press.hovered ? 0x234E65 : 0x173A4E)); PaddockStroke(draw, press.min, press.max, PaddockRound(8), PaddockCol(0x476373), 1); - const ImVec2 a{press.min.x + 9, press.min.y + 13}, b{press.max.x - 9, press.max.y - 12}; + const float centre = (press.min.y + press.max.y) * 0.5F; + const ImVec2 a{press.min.x + 9, centre - 9}, b{press.max.x - 9, centre + 10}; draw->AddRect(a, b, PaddockCol(0xFFF0C2), 3); for (int y = 0; y < 2; ++y) for (int x = 0; x < 5; ++x) { @@ -1131,6 +1132,7 @@ inline bool PaddockKeyboardButton() { PaddockEndPress(press, 8, 1); if (press.hovered || press.focused) { const auto item = GImGui->LastItemData; + const dkr::runtime::ui::ScopedDialogStyle style({12.0F, 8.0F}, 10.0F); ImGui::SetTooltip("On-screen keyboard"); GImGui->LastItemData = item; } diff --git a/runtime-recomp/src/game/save_manager.cpp b/runtime-recomp/src/game/save_manager.cpp index e5b05e56..8bd695a0 100644 --- a/runtime-recomp/src/game/save_manager.cpp +++ b/runtime-recomp/src/game/save_manager.cpp @@ -54,6 +54,7 @@ std::mutex g_save_manager_mutex; std::vector g_staged_host_online_save; std::uint64_t g_staged_host_online_match_id = 0; std::string g_host_online_mod_profile; +void ConfigureCloudProgressRoutes(); bool ValidModProfile(std::string_view profile) { return profile.empty() || (profile.size() == 64 && std::all_of(profile.begin(), profile.end(), [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); @@ -65,8 +66,8 @@ std::filesystem::path HostOnlineSubfolder(std::string_view profile) { return folder; } -std::filesystem::path AdventurePath() { - return g_config_directory / "saves" / "dkr.us.v77.bin"; +std::filesystem::path AdventurePath(bool modded = false) { + return dkr::runtime::saves::personal_adventure_path(g_config_directory, modded); } std::string MatchIdText(std::uint64_t match_id) { @@ -221,8 +222,8 @@ bool WriteAtomic(const std::filesystem::path& destination, const std::vector roots) { @@ -463,7 +467,9 @@ std::vector dkr::runtime::saves::stored_ad continue; const bool active = storage::key(candidate) == storage::key(root); const std::string prefix = active ? "" : "Other profile/portable location: "; - admit(candidate / "saves" / "dkr.us.v77.bin", active ? 0 : 3, prefix + "Offline Adventure", + admit(personal_adventure_path(candidate, false), active ? 0 : 3, prefix + "Vanilla Adventure", + StoredSaveKind::Adventure); + admit(personal_adventure_path(candidate, true), active ? 2 : 3, prefix + "Modded Adventure", StoredSaveKind::Adventure); for (int channel = 0; channel < kControllerPakCount; ++channel) { const auto pak = candidate / ("controller-pak-" + std::to_string(channel + 1) + ".mpk"); @@ -514,10 +520,7 @@ std::vector dkr::runtime::saves::stored_ad const bool transaction = relative.starts_with("save-transactions/") && name.ends_with(".original"); if (!primary && !recovery && !preserved && !transaction) continue; - const int scope = recovery || !active ? 3 - : relative.starts_with("saves/online/") ? 1 - : relative.starts_with("saves/mods/") ? 2 - : 3; + const int scope = !recovery && active && relative.starts_with("saves/online/") ? 1 : 3; const auto kind = relative.find("custom-records-v1.bin") != std::string::npos ? StoredSaveKind::CustomRecords : relative.find("experimental-controller-paks.bin") != std::string::npos @@ -556,10 +559,10 @@ bool dkr::runtime::saves::export_stored_save(const std::filesystem::path& source return WriteAtomic(destination, bytes, validator, error); } -dkr::runtime::saves::SaveInfo dkr::runtime::saves::adventure_info() { +dkr::runtime::saves::SaveInfo dkr::runtime::saves::adventure_info(bool modded) { std::scoped_lock lock(g_save_manager_mutex); SaveInfo info{}; - info.path = AdventurePath(); + info.path = AdventurePath(modded); std::error_code error; info.exists = std::filesystem::exists(info.path, error); if (info.exists && !error) { @@ -575,11 +578,11 @@ std::filesystem::path dkr::runtime::saves::backup_directory() { return g_config_directory / "save-backups"; } -std::vector dkr::runtime::saves::adventure_backups() { +std::vector dkr::runtime::saves::adventure_backups(bool modded) { std::scoped_lock lock(g_save_manager_mutex); std::vector result; std::error_code error; - const auto directory = g_config_directory / "save-backups"; + const auto directory = g_config_directory / "save-backups" / personal_adventure_subfolder(modded); if (!std::filesystem::is_directory(directory, error)) { return result; } @@ -598,9 +601,9 @@ std::vector dkr::runtime::saves::adventure_backups() { return result; } -bool dkr::runtime::saves::backup_adventure(std::filesystem::path& created, std::string& error) { +bool dkr::runtime::saves::backup_adventure(std::filesystem::path& created, std::string& error, bool modded) { std::scoped_lock lock(g_save_manager_mutex); - return BackupUnlocked(created, error); + return BackupUnlocked(created, error, modded); } bool dkr::runtime::saves::export_adventure(const std::filesystem::path& destination, std::string& error) { @@ -612,9 +615,9 @@ bool dkr::runtime::saves::export_adventure(const std::filesystem::path& destinat return export_stored_adventure(source, destination, error); } -bool dkr::runtime::saves::import_adventure(const std::filesystem::path& source, std::string& error) { +bool dkr::runtime::saves::import_adventure(const std::filesystem::path& source, std::string& error, bool modded) { std::scoped_lock lock(g_save_manager_mutex); - const auto owner = storage::acquire(AdventurePath(), error); + const auto owner = storage::acquire(AdventurePath(modded), error); if (!owner) return false; std::vector bytes; @@ -623,39 +626,39 @@ bool dkr::runtime::saves::import_adventure(const std::filesystem::path& source, return false; } std::error_code equivalent_error; - if (std::filesystem::exists(AdventurePath(), equivalent_error)) { + if (std::filesystem::exists(AdventurePath(modded), equivalent_error)) { std::filesystem::path backup; std::vector current; - const bool current_valid = ReadAdventure(AdventurePath(), current); - if (current_valid && !BackupUnlocked(backup, error)) { + const bool current_valid = ReadAdventure(AdventurePath(modded), current); + if (current_valid && !BackupUnlocked(backup, error, modded)) { return false; } - if (!current_valid && !BackupRawAdventureUnlocked(backup, error)) { + if (!current_valid && !BackupRawAdventureUnlocked(backup, error, modded)) { return false; } } - return WriteAtomic(AdventurePath(), bytes, ReadAdventure, error); + return WriteAtomic(AdventurePath(modded), bytes, ReadAdventure, error); } -bool dkr::runtime::saves::reset_adventure(std::string& error) { +bool dkr::runtime::saves::reset_adventure(std::string& error, bool modded) { std::scoped_lock lock(g_save_manager_mutex); - const auto owner = storage::acquire(AdventurePath(), error); + const auto owner = storage::acquire(AdventurePath(modded), error); if (!owner) return false; std::error_code exists_error; - if (std::filesystem::exists(AdventurePath(), exists_error)) { + if (std::filesystem::exists(AdventurePath(modded), exists_error)) { std::filesystem::path backup; - if (!BackupUnlocked(backup, error)) { + if (!BackupUnlocked(backup, error, modded)) { return false; } } - return WriteAtomic(AdventurePath(), codec::blank_bytes(), ReadAdventure, error); + return WriteAtomic(AdventurePath(modded), codec::blank_bytes(), ReadAdventure, error); } -bool dkr::runtime::saves::load_adventure(codec::SaveImage& image, std::string& error) { +bool dkr::runtime::saves::load_adventure(codec::SaveImage& image, std::string& error, bool modded) { std::scoped_lock lock(g_save_manager_mutex); std::vector bytes; - if (!ReadAdventure(AdventurePath(), bytes)) { + if (!ReadAdventure(AdventurePath(modded), bytes)) { error = "No checksum-valid Adventure EEPROM is available to edit."; return false; } @@ -687,16 +690,17 @@ bool dkr::runtime::saves::commit_adventure(const codec::SaveImage& image, std::s } bool dkr::runtime::saves::repair_adventure_checksums(bool& changed, std::filesystem::path& original_backup, - std::string& error) { + std::string& error, bool modded) { std::scoped_lock lock(g_save_manager_mutex); changed = false; original_backup.clear(); - const auto owner = storage::acquire(AdventurePath(), error); + const auto owner = storage::acquire(AdventurePath(modded), error); if (!owner) return false; std::vector original; - if (!ReadFileBounded(AdventurePath(), kAdventureSaveSize, original) || original.size() != kAdventureSaveSize) { + if (!ReadFileBounded(AdventurePath(modded), kAdventureSaveSize, original) || + original.size() != kAdventureSaveSize) { error = "No 512-byte Adventure EEPROM is available to repair."; return false; } @@ -736,10 +740,10 @@ bool dkr::runtime::saves::repair_adventure_checksums(bool& changed, std::filesys } } - if (!BackupRawAdventureUnlocked(original_backup, error)) { + if (!BackupRawAdventureUnlocked(original_backup, error, modded)) { return false; } - if (!WriteAtomic(AdventurePath(), repaired, ReadAdventure, error)) { + if (!WriteAtomic(AdventurePath(modded), repaired, ReadAdventure, error)) { return false; } changed = true; @@ -965,9 +969,9 @@ bool dkr::runtime::saves::commit_experimental_online_paks(bool host, std::uint64 error = "Invalid confirmed online MemPak image; no file was changed."; return false; } - return WriteAtomic(g_config_directory / "saves" / OnlineAdventureSubfolder(host, match_id) / - "experimental-controller-paks.bin", - {images.begin(), images.end()}, ReadExperimentalOnlinePaks, error); + return storage::write_progress(g_config_directory / "saves" / OnlineAdventureSubfolder(host, match_id) / + "experimental-controller-paks.bin", + {images.begin(), images.end()}, ReadExperimentalOnlinePaks, error); } bool dkr::runtime::saves::commit_online_adventure(bool host, std::uint64_t match_id, std::span bytes, std::string& error) { @@ -976,7 +980,8 @@ bool dkr::runtime::saves::commit_online_adventure(bool host, std::uint64_t match error = "The confirmed online EEPROM cannot be persisted: " + error; return false; } - return WriteAtomic(OnlineAdventurePath(host, match_id), {bytes.begin(), bytes.end()}, ReadAdventure, error); + return storage::write_progress(OnlineAdventurePath(host, match_id), {bytes.begin(), bytes.end()}, ReadAdventure, + error); } dkr::runtime::saves::SaveInfo dkr::runtime::saves::controller_pak_info(int channel) { @@ -1074,13 +1079,13 @@ bool dkr::runtime::saves::import_controller_pak(int channel, const std::filesyst return WriteAtomic(ControllerPakPath(channel), bytes, ReadControllerPak, error); } -bool dkr::runtime::saves::export_bundle(const std::filesystem::path& destination, std::string& error) { +bool dkr::runtime::saves::export_bundle(const std::filesystem::path& destination, std::string& error, bool modded) { std::scoped_lock lock(g_save_manager_mutex); if (!ExportDestinationAllowed(destination, error)) return false; std::vector entries; std::vector image; - if (ReadAdventure(AdventurePath(), image)) { + if (ReadAdventure(AdventurePath(modded), image)) { entries.push_back({kBundleAdventureKind, 0U, image}); } for (int channel = 0; channel < kControllerPakCount; ++channel) { @@ -1114,8 +1119,95 @@ bool dkr::runtime::saves::export_bundle(const std::filesystem::path& destination return WriteAtomic(destination, bundle, ReadBundle, error); } -bool dkr::runtime::saves::import_bundle(const std::filesystem::path& source, std::string& error) { - return shared::apply_bundle(source, error); +bool dkr::runtime::saves::import_bundle(const std::filesystem::path& source, std::string& error, bool modded) { + return shared::apply_bundle(source, error, modded); +} + +namespace { +using dkr::runtime::saves::CloudSaveSlot; +using dkr::runtime::saves::storage::Validator; +constexpr std::size_t kCloudRecordLimit = 20 + 8192 * 76; +constexpr std::array kCloudSaveSlots{{ + {"offline-adventure", "Vanilla Adventure", 512}, + {"modded-adventure", "Modded Adventure", 512}, + {"offline-pak-1", "Controller Pak 1", kControllerPakSize}, + {"offline-pak-2", "Controller Pak 2", kControllerPakSize}, + {"offline-pak-3", "Controller Pak 3", kControllerPakSize}, + {"offline-pak-4", "Controller Pak 4", kControllerPakSize}, + {"modded-records", "Modded course records", kCloudRecordLimit}, + {"online-adventure", "Hosted Online Adventure", 512}, + {"online-records", "Hosted Online course records", kCloudRecordLimit}, + {"online-paks", "Hosted Online Controller Paks", kControllerPakSize * 4}, +}}; +struct CloudSaveTarget { + std::filesystem::path path; + Validator validate = nullptr; +}; +CloudSaveTarget CloudTarget(std::string_view key) { + const auto host = OnlineAdventurePath(true, 0).parent_path(); + if (key == "offline-adventure" || key == "modded-adventure") + return {dkr::runtime::saves::personal_adventure_path(g_config_directory, key == "modded-adventure"), + ReadAdventure}; + if (key.starts_with("offline-pak-") && key.size() == 13 && key.back() >= '1' && key.back() <= '4') + return {ControllerPakPath(key.back() - '1'), ReadControllerPak}; + if (key == "modded-records") + return {AdventurePath().parent_path() / "custom-records-v1.bin", ReadCustomRecords}; + if (key == "online-adventure") + return {host / AdventurePath().filename(), ReadAdventure}; + if (key == "online-records") + return {host / "custom-records-v1.bin", ReadCustomRecords}; + if (key == "online-paks") + return {host / "experimental-controller-paks.bin", ReadExperimentalOnlinePaks}; + return {}; +} + +void ConfigureCloudProgressRoutes() { + using dkr::runtime::saves::storage::key; + dkr::cloud_saves::ProgressWrites::Routes routes; + routes.reserve(kCloudSaveSlots.size()); + for (const auto& slot : kCloudSaveSlots) + routes.emplace_back(key(CloudTarget(slot.key).path), slot.key); + dkr::cloud_saves::progress_writes.configure(std::move(routes)); +} +} // namespace + +std::span dkr::runtime::saves::cloud_save_slots() { + return kCloudSaveSlots; +} +bool dkr::runtime::saves::read_cloud_save(std::string_view key, std::vector& bytes, std::string& error) { + std::scoped_lock lock(g_save_manager_mutex); + bytes.clear(); + const auto target = CloudTarget(key); + if (!target.validate) { + error = "Unknown Cloud Save type."; + return false; + } + if (!storage::writable_path(target.path, error)) + return false; + std::error_code ec; + const bool exists = std::filesystem::exists(target.path, ec); + if (!ec) { + if (!exists) + return true; + const auto lease = storage::acquire(target.path, error); + if (!lease) + return false; + std::scoped_lock transaction(lease->transaction); + if (target.validate(target.path, bytes)) + return true; + } + error = "This save needs recovery. Its original file was kept."; + return false; +} +bool dkr::runtime::saves::replace_cloud_save(std::string_view key, const std::vector& expected, + const std::vector& replacement, std::string& error) { + std::scoped_lock lock(g_save_manager_mutex); + const auto target = CloudTarget(key); + if (!target.validate || replacement.empty()) { + error = "Unknown or empty Cloud Save image."; + return false; + } + return storage::write_atomic(target.path, replacement, target.validate, error, &expected); } #include "shared_save_backend.inl" diff --git a/runtime-recomp/src/game/save_manager.hpp b/runtime-recomp/src/game/save_manager.hpp index d62593ee..1fc846cd 100644 --- a/runtime-recomp/src/game/save_manager.hpp +++ b/runtime-recomp/src/game/save_manager.hpp @@ -29,7 +29,7 @@ constexpr int kControllerPakCount = 4; void configure(const std::filesystem::path& config_directory); // Explicit, known profile/portable locations only; never a whole-drive scan. void configure_recovery_locations(std::vector roots); -SaveInfo adventure_info(); +SaveInfo adventure_info(bool modded = false); void set_online_save_protection(bool enabled); enum class StoredSaveKind { Adventure, ControllerPak, ExperimentalPaks, CustomRecords }; struct StoredAdventure { @@ -46,14 +46,15 @@ bool export_stored_adventure(const std::filesystem::path& source, const std::fil bool export_stored_save(const std::filesystem::path& source, const std::filesystem::path& destination, StoredSaveKind kind, std::string& error); std::filesystem::path backup_directory(); -std::vector adventure_backups(); -bool backup_adventure(std::filesystem::path& created, std::string& error); +std::vector adventure_backups(bool modded = false); +bool backup_adventure(std::filesystem::path& created, std::string& error, bool modded = false); bool export_adventure(const std::filesystem::path& destination, std::string& error); -bool import_adventure(const std::filesystem::path& source, std::string& error); -bool reset_adventure(std::string& error); -bool load_adventure(codec::SaveImage& image, std::string& error); +bool import_adventure(const std::filesystem::path& source, std::string& error, bool modded = false); +bool reset_adventure(std::string& error, bool modded = false); +bool load_adventure(codec::SaveImage& image, std::string& error, bool modded = false); bool commit_adventure(const codec::SaveImage& image, std::string& error); -bool repair_adventure_checksums(bool& changed, std::filesystem::path& original_backup, std::string& error); +bool repair_adventure_checksums(bool& changed, std::filesystem::path& original_backup, std::string& error, + bool modded = false); bool canonical_adventure_bytes(std::vector& bytes, std::string& error); SaveInfo previous_online_adventure_info(std::string_view mod_profile = {}); // Stages validated bytes without touching previous online progress. The host's @@ -85,7 +86,16 @@ bool import_controller_pak(int channel, const std::filesystem::path& source, std // filenames or extraction paths, so importing cannot traverse outside the // configured save directory. Adventure EEPROM and all present Controller Paks // are validated before any live file is replaced. -bool export_bundle(const std::filesystem::path& destination, std::string& error); -bool import_bundle(const std::filesystem::path& source, std::string& error); +bool export_bundle(const std::filesystem::path& destination, std::string& error, bool modded = false); +bool import_bundle(const std::filesystem::path& source, std::string& error, bool modded = false); + +struct CloudSaveSlot { + std::string_view key, label; + std::size_t limit; +}; +std::span cloud_save_slots(); +bool read_cloud_save(std::string_view key, std::vector& bytes, std::string& error); +bool replace_cloud_save(std::string_view key, const std::vector& expected, + const std::vector& replacement, std::string& error); } // namespace dkr::runtime::saves diff --git a/runtime-recomp/src/game/save_storage.hpp b/runtime-recomp/src/game/save_storage.hpp index 656985b6..a5e26148 100644 --- a/runtime-recomp/src/game/save_storage.hpp +++ b/runtime-recomp/src/game/save_storage.hpp @@ -1,4 +1,6 @@ #pragma once +#include "cloud_saves/progress.hpp" +#include "personal_adventure_paths.hpp" // Authored save-storage policy. Never use this for renderer/configuration files. #include @@ -73,8 +75,8 @@ inline bool writable_path(const std::filesystem::path& path, std::string& error) {key(target).lexically_relative(key(protected_root)).generic_string(), key(canonical_target).lexically_relative(key(protected_canonical_root)).generic_string()}) { if (relative == "saves/dkr.us.v77.bin" || relative.starts_with("saves/dkr.us.v77.bin.") || - relative.starts_with("controller-pak-") || relative.starts_with("save-backups/") || - relative.starts_with("save-history/")) { + relative.starts_with(kModdedAdventureDirectory) || relative.starts_with("controller-pak-") || + relative.starts_with("save-backups/") || relative.starts_with("save-history/")) { error = "Offline saves are protected while an online session is active."; return false; } @@ -274,14 +276,23 @@ inline bool durable_replace(const std::filesystem::path& path, std::spantransaction); Bytes previous; - if (validator && validator(path, previous)) { + const bool previous_valid = validator && validator(path, previous); + if (expected) { + std::error_code ec; + const bool exists = std::filesystem::exists(path, ec); + if (ec || (exists && !previous_valid) || *expected != previous) { + error = "This device's save changed during sync. Sync again before replacing it."; + return false; + } + } + if (previous_valid) { if (previous == bytes) { error.clear(); return true; @@ -340,6 +351,20 @@ inline bool write_atomic(const std::filesystem::path& path, const Bytes& bytes, return false; } } - return durable_replace(path, bytes, validator, error); + if (!durable_replace(path, bytes, validator, error)) + return false; + if (progress) { + try { + cloud_saves::progress_writes.committed(key(path)); + } catch (const std::exception&) { + // An optional upload signal cannot turn a committed save into a failure. + } + } + return true; +} + +inline bool write_progress(const std::filesystem::path& path, const Bytes& bytes, Validator validator, + std::string& error) { + return write_atomic(path, bytes, validator, error, nullptr, true); } } // namespace dkr::runtime::saves::storage diff --git a/runtime-recomp/src/game/shared_save_backend.inl b/runtime-recomp/src/game/shared_save_backend.inl index f3d6afd7..7a54913f 100644 --- a/runtime-recomp/src/game/shared_save_backend.inl +++ b/runtime-recomp/src/game/shared_save_backend.inl @@ -26,7 +26,7 @@ bool write_json(const std::filesystem::path& path, const Json& doc, std::string& std::filesystem::path transaction_destination(const Json& item) { const auto kind = item.at("kind").get(); if (kind == kBundleAdventureKind && item.at("channel") == 0) - return data_root() / "saves/dkr.us.v77.bin"; + return personal_adventure_path(data_root(), item.value("modded", false)); if (kind == kBundleRecordsKind && item.at("channel") == 0) return data_root() / "saves/custom-records-v1.bin"; const auto channel = item.at("channel").get(); @@ -124,9 +124,16 @@ bool recover_unlocked(std::string& error) { } } // namespace -std::string revision() { +bool load_draft(codec::SaveImage& image, std::string& revision, std::string& error, bool modded) { + const auto path = personal_adventure_path(data_root(), modded); std::vector bytes; - return storage::read_exact(adventure_info().path, 512, bytes) ? storage::content_id(bytes) : "missing"; + if (!ReadAdventure(path, bytes) || !codec::decode(bytes, image, &error)) { + error = "No checksum-valid Adventure save is available to edit."; + return false; + } + revision = storage::content_id(bytes); + error.clear(); + return true; } bool recover_transaction(std::string& error) { std::scoped_lock lock(operation_mutex); @@ -196,11 +203,11 @@ bool prepare(const std::filesystem::path& root, std::string& error) { std::fprintf(stderr, "[save][migration] original-images=%zu retained; personal save unchanged\n", records.size()); return true; } -bool queue_development_copy(std::string& error) { +bool queue_development_copy(std::string& error, bool modded) { if (!prepare(data_root(), error)) return false; std::scoped_lock lock(operation_mutex); - const auto personal = data_root() / "saves/dkr.us.v77.bin"; + const auto personal = personal_adventure_path(data_root(), modded); auto owner = storage::acquire(personal, error); if (!owner) return false; @@ -340,25 +347,22 @@ void complete(codec::SaveImage& image, int selected) { } unlock(image); } -bool apply(const codec::SaveImage& image, std::string_view expected, std::string& error) { +bool apply(const codec::SaveImage& image, std::string_view expected, std::string& error, bool modded) { if (!prepare(data_root(), error)) return false; std::scoped_lock lock(operation_mutex); - auto owner = storage::acquire(adventure_info().path, error); + const auto path = personal_adventure_path(data_root(), modded); + auto owner = storage::acquire(path, error); if (!owner) return false; - if (revision() != expected) { + std::vector original; + if (!storage::read_exact(path, codec::kImageSize, original) || storage::content_id(original) != expected) { error = "Your save changed since this editor was opened. Reload it before applying edits; no progress was replaced."; return false; } if (!codec::validate_editable_ranges(image, &error)) return false; - std::vector original; - if (!ReadAdventure(adventure_info().path, original)) { - error = "The current personal image is not valid; use Recovery before editing."; - return false; - } codec::SaveImage previous; if (!codec::decode(original, previous, &error)) return false; @@ -375,11 +379,10 @@ bool apply(const codec::SaveImage& image, std::string_view expected, std::string if (!codec::validate(proposed, &error)) return false; std::filesystem::path backup; - if (!backup_adventure(backup, error) || - !storage::write_atomic(adventure_info().path, proposed, ReadAdventure, error)) + if (!backup_adventure(backup, error, modded) || !storage::write_atomic(path, proposed, ReadAdventure, error)) return false; std::vector check; - if (!ReadAdventure(adventure_info().path, check) || check != proposed) { + if (!ReadAdventure(path, check) || check != proposed) { error = "The saved edit failed read-back verification. Its backup was retained."; return false; } @@ -387,7 +390,7 @@ bool apply(const codec::SaveImage& image, std::string_view expected, std::string error.clear(); return true; } -bool adopt(const std::filesystem::path& source, bool repair, std::string& error) { +bool adopt(const std::filesystem::path& source, bool repair, std::string& error, bool modded) { if (!prepare(data_root(), error)) return false; std::vector bytes; @@ -411,7 +414,7 @@ bool adopt(const std::filesystem::path& source, bool repair, std::string& error) const auto staged = data_root() / "save-recovery" / ("candidate-" + storage::content_id(bytes) + ".bin"); if (!storage::write_atomic(staged, bytes, ReadAdventure, error)) return false; - return import_adventure(staged, error); + return import_adventure(staged, error, modded); } bool export_raw(const std::filesystem::path& source, const std::filesystem::path& destination, std::string& error) { if (!ExportDestinationAllowed(destination, error)) @@ -453,7 +456,7 @@ std::string describe(const std::filesystem::path& path) { : "locked"); return text; } -bool apply_bundle(const std::filesystem::path& source, std::string& error) { +bool apply_bundle(const std::filesystem::path& source, std::string& error, bool modded) { if (!prepare(data_root(), error)) return false; std::scoped_lock lock(operation_mutex); @@ -472,6 +475,8 @@ bool apply_bundle(const std::filesystem::path& source, std::string& error) { for (std::size_t i = 0; i < entries.size(); ++i) { const auto& entry = entries[i]; Json item = {{"kind", entry.kind}, {"channel", entry.channel}}; + if (entry.kind == kBundleAdventureKind) + item["modded"] = modded; const auto dest = transaction_destination(item); auto owner = storage::acquire(dest, error); if (!owner) @@ -516,24 +521,10 @@ bool apply_bundle(const std::filesystem::path& source, std::string& error) { return false; return retire_transaction(dir, error); } -bool reset(std::string& error) { +bool reset(std::string& error, bool modded) { if (!prepare(data_root(), error)) return false; - std::vector entries{{kBundleAdventureKind, 0, codec::blank_bytes()}, - {kBundleRecordsKind, 0, records::encode({})}}; - std::vector bytes(kBundleMagic.begin(), kBundleMagic.end()); - AppendLE32(bytes, kBundleVersion); - AppendLE32(bytes, entries.size()); - for (const auto& entry : entries) { - AppendLE32(bytes, entry.kind); - AppendLE32(bytes, entry.channel); - AppendLE32(bytes, entry.bytes.size()); - AppendLE32(bytes, ImageChecksum(entry.bytes)); - bytes.insert(bytes.end(), entry.bytes.begin(), entry.bytes.end()); - } - const auto source = data_root() / "save-recovery" / ("fresh-" + Timestamp() + ".dkrsave"); - if (!storage::write_atomic(source, bytes, ReadBundle, error)) - return false; - return apply_bundle(source, error); + std::scoped_lock lock(operation_mutex); + return reset_adventure(error, modded); } } // namespace dkr::runtime::saves::shared diff --git a/runtime-recomp/src/game/shared_save_jobs.inl b/runtime-recomp/src/game/shared_save_jobs.inl index 66ed1dfc..5bb3953d 100644 --- a/runtime-recomp/src/game/shared_save_jobs.inl +++ b/runtime-recomp/src/game/shared_save_jobs.inl @@ -3,36 +3,46 @@ struct SharedSaveResult { bool ok = false; std::string message; + std::optional edited_adventure; }; std::future g_shared_save_job; -std::string g_shared_draft_revision; +struct AdventureDraft { + std::optional image; + std::optional original; + std::string revision; +}; +std::array g_adventure_drafts; std::uint64_t g_shared_save_generation = 1; struct SharedSaveImport { std::filesystem::path path; int kind = 0; int port = 0; + bool modded = false; }; SharedSaveImport g_shared_save_import; bool SharedSaveBusy() { return g_shared_save_job.valid(); } -bool BeginSharedSaveJob(std::function action, std::string success) { +bool BeginSharedSaveJob(std::function action, std::string success, + std::optional edited_adventure = std::nullopt) { if (SharedSaveBusy()) return false; g_save_manager_status = "Saving..."; - g_shared_save_job = std::async(std::launch::async, [action = std::move(action), success = std::move(success)] { - SharedSaveResult result; - try { - std::string error; - result.ok = action(error); - result.message = result.ok ? success : error; - } catch (const std::exception& e) { - result.message = e.what(); - } catch (...) { - result.message = "The save operation stopped. Original recovery images were retained."; - } - return result; - }); + g_shared_save_job = + std::async(std::launch::async, [action = std::move(action), success = std::move(success), edited_adventure] { + SharedSaveResult result; + result.edited_adventure = edited_adventure; + try { + std::string error; + result.ok = action(error); + result.message = result.ok ? success : error; + } catch (const std::exception& e) { + result.message = e.what(); + } catch (...) { + result.message = "The save operation stopped. Original recovery images were retained."; + } + return result; + }); return true; } void PumpSharedSaveJob() { @@ -41,8 +51,8 @@ void PumpSharedSaveJob() { const auto result = g_shared_save_job.get(); g_save_manager_status = result.message; if (result.ok) { - g_save_builder_image.reset(); - g_shared_draft_revision.clear(); + if (result.edited_adventure) + g_adventure_drafts[*result.edited_adventure] = {}; ++g_shared_save_generation; InvalidateSaveManagerViewCache(); } diff --git a/runtime-recomp/src/game/shared_saves.hpp b/runtime-recomp/src/game/shared_saves.hpp index 05d2d35b..8b3795e5 100644 --- a/runtime-recomp/src/game/shared_saves.hpp +++ b/runtime-recomp/src/game/shared_saves.hpp @@ -3,21 +3,21 @@ #include namespace dkr::runtime::saves::shared { -// One personal EEPROM. Content/network identities never select this file. +// Offline Adventure editing uses the selected Vanilla or Modded save. bool prepare(const std::filesystem::path& root, std::string& error); -std::string revision(); -bool apply(const codec::SaveImage& image, std::string_view expected, std::string& error); +bool load_draft(codec::SaveImage& image, std::string& revision, std::string& error, bool modded); +bool apply(const codec::SaveImage& image, std::string_view expected, std::string& error, bool modded = false); void complete(codec::SaveImage& image, int slot); void unlock(codec::SaveImage& image); -bool adopt(const std::filesystem::path& source, bool repair, std::string& error); +bool adopt(const std::filesystem::path& source, bool repair, std::string& error, bool modded = false); bool export_raw(const std::filesystem::path& source, const std::filesystem::path& destination, std::string& error); bool import_host(const std::filesystem::path& source, std::string& error); -bool apply_bundle(const std::filesystem::path& source, std::string& error); -bool reset(std::string& error); +bool apply_bundle(const std::filesystem::path& source, std::string& error, bool modded = false); +bool reset(std::string& error, bool modded = false); bool recover_transaction(std::string& error); // Development keeps its own write owner, but a new sandbox inherits personal // progress. Refreshing an existing sandbox is a separately confirmed action. bool prepare_development(const std::filesystem::path& root, const std::filesystem::path& folder, std::string& error); -bool queue_development_copy(std::string& error); +bool queue_development_copy(std::string& error, bool modded = false); std::string describe(const std::filesystem::path& path); } // namespace dkr::runtime::saves::shared diff --git a/runtime-recomp/src/game/start_gate.hpp b/runtime-recomp/src/game/start_gate.hpp index bfdb29ae..dac941ed 100644 --- a/runtime-recomp/src/game/start_gate.hpp +++ b/runtime-recomp/src/game/start_gate.hpp @@ -43,6 +43,11 @@ inline void forget(const void* owner) { std::scoped_lock lock(r.mutex); r.entries.erase(owner); } +inline bool needs_prepare(const Gate& value, std::uint64_t descriptor, std::uint64_t roster, + std::uint32_t save_generation, std::uint64_t save_hash) { + return !value.launch || value.hash != descriptor || value.roster != roster || + value.save_generation != save_generation || value.save_hash != save_hash; +} // Receipt/cancel metadata is inside the authenticated party envelope. It binds // the descriptor, current roster and verified EEPROM identity, never a slot claim. inline std::vector receipt(unsigned stage, const Gate& g) { diff --git a/runtime-recomp/src/game/texture_dump_ui.inl b/runtime-recomp/src/game/texture_dump_ui.inl index c3b08154..52ad4704 100644 --- a/runtime-recomp/src/game/texture_dump_ui.inl +++ b/runtime-recomp/src/game/texture_dump_ui.inl @@ -198,8 +198,7 @@ void DrawDumpPreviewCard(const dumping::Thumbnail& item, float width) { 166.F, kSetMuted); line(detail, item.preview_error.empty() ? item.status : "Preview unavailable", 190.F, item.preview_error.empty() ? kSetMuted : kSetWarm); - if (ImGui::IsWindowHovered() && ImGui::IsMouseHoveringRect(at, end)) { - ImGui::BeginTooltip(); + if (ImGui::IsWindowHovered() && ImGui::IsMouseHoveringRect(at, end) && dkr::runtime::ui::begin_dialog_tooltip()) { ImGui::PushTextWrapPos(320.F); ImGui::TextUnformatted(item.name.c_str()); if (!item.preview_error.empty()) @@ -492,8 +491,8 @@ void DrawTextureDumping(float width) { ImGui::SetNextWindowSize({std::min(850.F, display.x - 32.F), std::min(display.y - 32.F, display.y * .75F)}, ImGuiCond_Always); ImGui::SetNextWindowPos({display.x * .5F, display.y * .5F}, ImGuiCond_Always, {.5F, .5F}); - if (ImGui::BeginPopupModal("Choose texture sources##dump", nullptr, - ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings)) { + if (BeginPaddockModalWindow("Choose texture sources##dump", + ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings)) { const float inner = ImGui::GetContentRegionAvail().x; DetailText(state->busy ? "Loading installed sources..." : "Choose the sources to export.", inner, kSetMuted, 8.F); diff --git a/runtime-recomp/src/game/time_trial/adventure_rules.hpp b/runtime-recomp/src/game/time_trial/adventure_rules.hpp new file mode 100644 index 00000000..492b67f6 --- /dev/null +++ b/runtime-recomp/src/game/time_trial/adventure_rules.hpp @@ -0,0 +1,136 @@ +#pragma once + +#include "courses.hpp" + +#include +#include + +namespace dkr::runtime::time_trial { +enum class Adventure { + None, + AnyPercent, + HundredPercent, + AllTrophyRaces, + AllBosses, + AllMinigames, + TTAmulet, + AnyPercentGlitchless, + TrophyDinoFirst, + TrophyFutureFirst, + CarPercent, + HoverPercent, + PlanePercent, +}; + +struct AdventureCategory { + Adventure goal; + std::string_view id; + std::string_view title; +}; + +inline constexpr std::array kAdventureCategories{ + AdventureCategory{Adventure::AnyPercent, "any-percent", "Any%"}, + AdventureCategory{Adventure::HundredPercent, "100-percent", "100%"}, + AdventureCategory{Adventure::AllTrophyRaces, "all-trophy-races", "All Trophy Races"}, + AdventureCategory{Adventure::AllBosses, "all-bosses", "All Bosses"}, + AdventureCategory{Adventure::AllMinigames, "all-minigames", "All Minigames"}, + AdventureCategory{Adventure::TTAmulet, "tt-amulet-no-wrong-warp", "T.T. Amulet – No Wrong Warp"}, + AdventureCategory{Adventure::AnyPercentGlitchless, "any-percent-glitchless", "Any% Glitchless"}, + AdventureCategory{Adventure::TrophyDinoFirst, "all-trophy-races-dino-first", + "All Trophy Races - Dino Domain First"}, + AdventureCategory{Adventure::TrophyFutureFirst, "all-trophy-races-ffl-first", + "All Trophy Races - Future Fun Land First"}, + AdventureCategory{Adventure::CarPercent, "car-percent", "Car%"}, + AdventureCategory{Adventure::HoverPercent, "hover-percent", "Hover%"}, + AdventureCategory{Adventure::PlanePercent, "plane-percent", "Plane%"}, +}; + +inline constexpr std::string_view kAdventureRules = "adventure-us80-7"; +inline constexpr std::string_view kAdventureOriginalRouteRules = "adventure-us80-6"; +inline constexpr std::string_view kAdventureMilestoneRules = "adventure-us80-5"; +inline constexpr std::string_view kAdventureColdSaveRules = "adventure-us80-4"; +inline constexpr std::string_view kAdventureVisualRngRules = "adventure-us80-3"; +inline constexpr std::string_view kAdventureSharedRngRules = "adventure-us80-2"; +inline constexpr std::string_view kLegacyAdventureRules = "adventure-us80-1"; +inline constexpr unsigned kAdventureInterval = 1800; +inline constexpr unsigned kAdventureMaxUpdates = 30 * 60 * 60 * 6; + +constexpr Adventure adventure_for(std::string_view id) { + for (const auto& category : kAdventureCategories) + if (category.id == id) + return category.goal; + return Adventure::None; +} + +constexpr std::string_view adventure_id(Adventure goal) { + for (const auto& category : kAdventureCategories) + if (category.goal == goal) + return category.id; + return {}; +} + +constexpr bool tracks_route(Adventure goal, bool completed_save_rules = true) { + return (goal >= Adventure::TrophyDinoFirst && goal <= Adventure::PlanePercent) || + (completed_save_rules && (goal == Adventure::AllTrophyRaces || goal == Adventure::AllMinigames)); +} + +constexpr bool completed_save_route(Adventure goal) { + return tracks_route(goal) || goal == Adventure::AllBosses; +} + +// The original game exposes earned characters through the same two bits it +// uses for cheat state. Match init_title_screen_variables' EEPROM conditions. +constexpr unsigned earned_character_flags(unsigned eeprom) { + constexpr unsigned tt_trial_bits = 0xfffff0; + return (eeprom & 2U) | unsigned((eeprom & tt_trial_bits) == tt_trial_bits); +} + +constexpr bool trophy_route(Adventure goal) { + return goal == Adventure::AllTrophyRaces || goal == Adventure::TrophyDinoFirst || + goal == Adventure::TrophyFutureFirst; +} + +struct AdventureProgress { + unsigned balloons = 0; + unsigned keys = 0; + unsigned bosses = 0; + unsigned trophies = 0; + unsigned tt_amulet = 0; + unsigned wizpig_amulet = 0; +}; + +// The retail Adventure settings store the central-island and Future Fun +// Land Wizpig victories as separate bits. Gold is 3 in each world's two-bit +// trophy field. The four world keys occupy bits 1 through 4. +constexpr bool adventure_complete(Adventure goal, AdventureProgress progress, bool all_five_trophies = false) { + constexpr unsigned final_wizpig = 1U << 5; + constexpr unsigned four_gold_cups = 0xff; + constexpr unsigned four_world_keys = 0x1e; + const bool final_victory = (progress.bosses & final_wizpig) != 0; + const bool gold_cups = (progress.trophies & four_gold_cups) == four_gold_cups; + switch (goal) { + case Adventure::AnyPercent: + return final_victory; + case Adventure::AnyPercentGlitchless: + return final_victory && (progress.bosses & 0x3f) == 0x3f; + case Adventure::HundredPercent: + return final_victory && gold_cups && (progress.keys & four_world_keys) == four_world_keys && + progress.balloons == 47 && progress.tt_amulet == 4 && progress.wizpig_amulet == 4; + case Adventure::AllTrophyRaces: + return gold_cups && (!all_five_trophies || (progress.trophies & 0x300) == 0x300); + case Adventure::AllBosses: + return (progress.bosses & 0x3f) == 0x3f; + case Adventure::AllMinigames: + case Adventure::TTAmulet: + return progress.tt_amulet == 4 && (progress.keys & four_world_keys) == four_world_keys; + case Adventure::TrophyDinoFirst: + case Adventure::TrophyFutureFirst: + case Adventure::CarPercent: + case Adventure::HoverPercent: + case Adventure::PlanePercent: + case Adventure::None: + return false; + } + return false; +} +} // namespace dkr::runtime::time_trial diff --git a/runtime-recomp/src/game/time_trial/adventure_splits.hpp b/runtime-recomp/src/game/time_trial/adventure_splits.hpp new file mode 100644 index 00000000..9b04f459 --- /dev/null +++ b/runtime-recomp/src/game/time_trial/adventure_splits.hpp @@ -0,0 +1,229 @@ +#pragma once + +#include "adventure_rules.hpp" +#include +#include +#include +#include +#include +#include +#include + +namespace dkr::runtime::time_trial { +struct AdventureSplit { + std::string_view label; + unsigned clock; +}; + +struct AdventureRace { + unsigned level, vehicle, trophy_world, trophy_round; + bool won; +}; + +class AdventureSplits { + unsigned challenge_world_ = 0; + unsigned course_wins_ = 0; + unsigned first_trophy_world_ = 0; + unsigned event_wins_ = 0; + std::array trophy_rounds_{}; + + static constexpr std::array minigame_maps{11, 25, 26, 27}; + static constexpr std::array boss_maps{37, 46, 52, 53, 54, 55}; + static constexpr std::array minigame_names{"Fire Mountain", "Smokey Castle", "Darkwater Beach", + "Icicle Pyramid"}; + static constexpr std::array boss_names{"Wizpig 1", "Tricky", "Bluey", + "Bubbler", "Smokey", "Wizpig 2"}; + static constexpr unsigned trophy_courses[5][4] = { + {5, 3, 29, 7}, {8, 4, 10, 30}, {13, 6, 9, 28}, {19, 18, 20, 31}, {17, 32, 33, 15}, + }; + + static constexpr Vehicle route_vehicle(Adventure goal) { + return goal == Adventure::HoverPercent ? Vehicle::Hovercraft + : goal == Adventure::PlanePercent ? Vehicle::Plane + : Vehicle::Car; + } + + public: + std::vector entries; + + static std::vector upcoming(Adventure goal, std::span completed) { + std::vector route{tracks_route(goal) ? "Start" : "Overworld"}; + const auto append = [&](std::initializer_list stages) { route.insert(route.end(), stages); }; + if (trophy_route(goal)) { + for (unsigned set = 0; set < 5; ++set) { + const unsigned world = goal == Adventure::TrophyFutureFirst ? 4 - set : set; + for (unsigned level : trophy_courses[world]) + if (const auto course = std::ranges::find(kCourses, level, &Course::level); + course != kCourses.end()) + route.push_back(course->name); + } + } else if (goal >= Adventure::CarPercent) { + for (const auto& course : kCourses) + if (course.supports(route_vehicle(goal))) + route.push_back(course.name); + } else if (goal == Adventure::AllMinigames) { + route.insert(route.end(), minigame_names.begin(), minigame_names.end()); + } else if (goal == Adventure::AllBosses) { + append({"Tricky", "Bluey", "Bubbler", "Smokey", "Wizpig 1", "Wizpig 2"}); + } else if (goal == Adventure::TTAmulet) { + append({"Fire Mountain", "Car Challenge", "Icicle Pyramid", "Hover Challenge", "Darkwater Beach", + "Plane Challenge", "Smokey Castle"}); + } else if (goal == Adventure::AnyPercent) { + append({"Enter Wizpig 1", "Wizpig 1", "Dino 2", "Enter FFL", "Enter Wizpig 2", "Wizpig 2"}); + } else { + append({"Dino 1", "Fire Mountain", "Dino 2", + "Dino Trophy", "Car Challenge", "Snowflake 1", + "Icicle Pyramid", "Snowflake 2", "Snow Trophy", + "Hover Challenge", "Sherbet 1", "Darkwater Beach", + "Sherbet 2", "Sherbet Trophy", "Plane Challenge", + "Dragon 1", "Smokey Castle", "Dragon 2", + "Dragon Trophy", "Enter Wizpig 1", "Wizpig 1", + "Enter FFL", "Future Fun Land 1", "Future Fun Land 2"}); + if (goal == Adventure::HundredPercent) + route.push_back("Future Fun Land Trophy"); + append({"Enter Wizpig 2", "Wizpig 2"}); + } + route.push_back("Finish"); + std::erase_if(route, [&](auto stage) { + return std::ranges::find(completed, stage, &AdventureSplit::label) != completed.end(); + }); + return route; + } + + void mark(std::string_view label, unsigned clock) { + if (std::ranges::find(entries, label, &AdventureSplit::label) == entries.end()) + entries.push_back({label, clock}); + } + + void observe_race(Adventure goal, const AdventureRace& race, unsigned clock) { + const auto course = std::ranges::find(kCourses, race.level, &Course::level); + if (course == kCourses.end()) + return; + if (trophy_route(goal)) { + if (!race.trophy_world || race.trophy_world > trophy_rounds_.size() || race.trophy_round >= 4) + return; + if (trophy_courses[race.trophy_world - 1][race.trophy_round] != race.level) + return; + auto& rounds = trophy_rounds_[race.trophy_world - 1]; + if ((rounds & (1U << race.trophy_round)) == 0) { + if (!first_trophy_world_) + first_trophy_world_ = race.trophy_world; + rounds |= 1U << race.trophy_round; + mark(course->name, clock); + } + } else if (goal >= Adventure::CarPercent && !race.trophy_world && race.won && + race.vehicle == static_cast(route_vehicle(goal)) && + course->supports(route_vehicle(goal))) { + course_wins_ |= 1U << (course - kCourses.begin()); + mark(course->name, clock); + } + } + + bool wrong_first_trophy(Adventure goal) const { + return first_trophy_world_ && ((goal == Adventure::TrophyDinoFirst && first_trophy_world_ != 1) || + (goal == Adventure::TrophyFutureFirst && first_trophy_world_ != 5)); + } + + void observe_event_win(Adventure goal, unsigned level, unsigned clock) { + const std::span maps = goal == Adventure::AllMinigames + ? std::span{minigame_maps} + : std::span{boss_maps}; + const std::span names = goal == Adventure::AllMinigames + ? std::span{minigame_names} + : std::span{boss_names}; + const auto found = std::ranges::find(maps, level); + if (found != maps.end()) { + const auto index = found - maps.begin(); + event_wins_ |= 1U << index; + mark(names[index], clock); + } + } + + bool route_complete(Adventure goal, AdventureProgress progress, bool completed_save_rules = false) const { + if (trophy_route(goal)) { + const bool raced_every_round = + std::ranges::all_of(trophy_rounds_, [](unsigned rounds) { return rounds == 0xf; }); + return raced_every_round && !wrong_first_trophy(goal) && + (completed_save_rules || goal != Adventure::AllTrophyRaces || + adventure_complete(goal, progress, true)); + } + if (completed_save_rules && goal == Adventure::AllMinigames) + return event_wins_ == (1U << minigame_maps.size()) - 1; + if (completed_save_rules && goal == Adventure::AllBosses) + return event_wins_ == (1U << boss_maps.size()) - 1; + if (completed_save_rules && goal == Adventure::HundredPercent && + !adventure_complete(Adventure::AllTrophyRaces, progress, true)) + return false; + if (goal >= Adventure::CarPercent) { + for (unsigned index = 0; index < kCourses.size(); ++index) { + if (kCourses[index].supports(route_vehicle(goal)) && !(course_wins_ & (1U << index))) + return false; + } + return true; + } + return adventure_complete(goal, progress, true); + } + + void observe_future_fun_land(std::span flags, int race_type, unsigned clock) { + constexpr std::array future_courses{15U, 17U, 32U, 33U}; + const auto cleared = [&](unsigned flag) { + return std::ranges::all_of(future_courses, [&](unsigned course) { return flags[course] & flag; }); + }; + if (flags.size() > future_courses.back()) { + if (cleared(2)) + mark("Future Fun Land 1", clock); + if (cleared(4)) + mark("Future Fun Land 2", clock); + } + if (race_type == 8) + mark("Enter Wizpig 2", clock); + } + + // Use the cartridge's persistent objective bits for clears and its live + // gameplay mode for entries. Menu transitions and deaths cannot split. + void observe(AdventureProgress before, AdventureProgress now, int race_type, unsigned world, unsigned previous_taj, + unsigned taj, unsigned clock, Adventure goal = Adventure::None) { + static constexpr std::array bosses{ + "Wizpig 1", "Dino 1", "Sherbet 1", "Snowflake 1", "Dragon 1", "Wizpig 2", + "", "Dino 2", "Sherbet 2", "Snowflake 2", "Dragon 2", + }; + static constexpr std::array cups{ + "Dino Trophy", "Sherbet Trophy", "Snow Trophy", "Dragon Trophy", "Future Fun Land Trophy", + }; + static constexpr std::array boss_names{ + "Wizpig 1", "Tricky", "Bubbler", "Bluey", "Smokey", "Wizpig 2", + }; + static constexpr std::array challenges{ + "Fire Mountain", + "Darkwater Beach", + "Icicle Pyramid", + "Smokey Castle", + }; + static constexpr std::array taj_challenges{"Car Challenge", "Hover Challenge", "Plane Challenge"}; + if (race_type == 8 && world == 0) + mark("Enter Wizpig 1", clock); + if (race_type == 5 && world == 5) + mark("Enter FFL", clock); + if (race_type >= 64 && race_type <= 66 && world >= 1 && world <= challenges.size()) + challenge_world_ = world; + if (now.tt_amulet > before.tt_amulet && challenge_world_) + mark(challenges[challenge_world_ - 1], clock); + for (unsigned i = 0; i < bosses.size(); ++i) { + if (*bosses[i] && (now.bosses & ~before.bosses & (1U << i))) { + if (goal == Adventure::AllBosses && i < boss_names.size()) + mark(boss_names[i], clock); + else + mark(bosses[i], clock); + } + } + for (unsigned i = 0; i < cups.size(); ++i) { + const unsigned shift = 2 * i; + if (((now.trophies >> shift) & 3) == 3 && ((before.trophies >> shift) & 3) != 3) + mark(cups[i], clock); + } + for (unsigned i = 0; i < taj_challenges.size(); ++i) + if (taj & ~previous_taj & (8U << i)) + mark(taj_challenges[i], clock); + } +}; +} // namespace dkr::runtime::time_trial diff --git a/runtime-recomp/src/game/time_trial/courses.hpp b/runtime-recomp/src/game/time_trial/courses.hpp new file mode 100644 index 00000000..3a5ad867 --- /dev/null +++ b/runtime-recomp/src/game/time_trial/courses.hpp @@ -0,0 +1,58 @@ +#pragma once + +#include +#include + +namespace dkr::runtime::time_trial { +enum class Vehicle : unsigned { Car, Hovercraft, Plane }; + +inline constexpr std::array kVehicleIds{"car", "hovercraft", "plane"}; +inline constexpr std::array kVehicleNames{"Car", "Hovercraft", "Plane"}; +inline constexpr std::string_view kLegacyRules = "ancient-lake-us80-practice-2"; +inline constexpr std::string_view kVanillaRules = "vanilla-time-trial-us80-1"; +inline constexpr std::string_view kCustomRules = "custom-time-trial-us80-1"; +inline constexpr std::string_view kCustomVariableLapsRules = "custom-time-trial-us80-2"; +inline constexpr unsigned kRetailLapCount = 3; +inline constexpr unsigned kMaximumLapCount = 5; + +struct Course { + std::string_view id, name; + unsigned level, vehicles; + + constexpr bool supports(Vehicle vehicle) const { + const auto index = static_cast(vehicle); + return index < kVehicleIds.size() && (vehicles & (1U << index)) != 0; + } +}; + +// Retail Time Trial level IDs and the vehicles with save-record slots. +inline constexpr std::array kCourses{ + Course{"ancient-lake", "Ancient Lake", 5, 7}, + Course{"fossil-canyon", "Fossil Canyon", 3, 7}, + Course{"jungle-falls", "Jungle Falls", 29, 7}, + Course{"hot-top-volcano", "Hot Top Volcano", 7, 6}, + Course{"everfrost-peak", "Everfrost Peak", 13, 7}, + Course{"walrus-cove", "Walrus Cove", 6, 3}, + Course{"snowball-valley", "Snowball Valley", 9, 3}, + Course{"frosty-village", "Frosty Village", 28, 7}, + Course{"whale-bay", "Whale Bay", 8, 2}, + Course{"crescent-island", "Crescent Island", 10, 3}, + Course{"pirate-lagoon", "Pirate Lagoon", 4, 2}, + Course{"treasure-caves", "Treasure Caves", 30, 7}, + Course{"windmill-plains", "Windmill Plains", 20, 7}, + Course{"greenwood-village", "Greenwood Village", 18, 3}, + Course{"boulder-canyon", "Boulder Canyon", 19, 2}, + Course{"haunted-woods", "Haunted Woods", 31, 3}, + Course{"spacedust-alley", "Spacedust Alley", 17, 7}, + Course{"darkmoon-caverns", "Darkmoon Caverns", 32, 3}, + Course{"spaceport-alpha", "Spaceport Alpha", 15, 7}, + Course{"star-city", "Star City", 33, 7}, +}; + +constexpr const Course* course_for(std::string_view id) { + for (const auto& course : kCourses) + if (course.id == id) + return &course; + return nullptr; +} +} // namespace dkr::runtime::time_trial diff --git a/runtime-recomp/src/game/time_trial/ghost_file.hpp b/runtime-recomp/src/game/time_trial/ghost_file.hpp new file mode 100644 index 00000000..87d0fdc4 --- /dev/null +++ b/runtime-recomp/src/game/time_trial/ghost_file.hpp @@ -0,0 +1,20 @@ +#pragma once + +#include +#include +#include + +namespace dkr::runtime::time_trial { +inline constexpr std::string_view kPortableGhostSignature = "DKRPGH01"; +inline constexpr unsigned kGhostPoseBytes = 20; +inline constexpr unsigned kMaxPortableGhostBytes = 136 + 54000 * kGhostPoseBytes; + +// The replay digest covers the course, vehicle, racer, rules and recorded inputs. +inline std::string portable_ghost_prefix(std::string_view replay_digest) { + return std::string(kPortableGhostSignature).append(replay_digest); +} + +inline std::filesystem::path portable_ghost_file(std::filesystem::path replay) { + return replay.replace_extension(".dkrghost"); +} +} // namespace dkr::runtime::time_trial diff --git a/runtime-recomp/src/game/time_trial/options.hpp b/runtime-recomp/src/game/time_trial/options.hpp new file mode 100644 index 00000000..aadb261a --- /dev/null +++ b/runtime-recomp/src/game/time_trial/options.hpp @@ -0,0 +1,122 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace dkr::runtime::speedrunning { + +enum class Option { + Splits, + SplitPosition, + SplitDetail, + Comparison, + Upcoming, + Precision, + HudSize, + Inset, + Background, + Contrast, + DeltaWords, + ReducedMotion, + GhostNames, + GhostOpacity, + GhostGap, + GhostStyle, + GhostProximity, + GhostMarker, + ReplayInputs, + ReplaySplits, + InputPosition, + ReplaySpeed, + PlaybackControls, + InputSize, + SeekStep, + StartPaused, + LapMarkers, + LapDelta, + Celebration, + CelebrationScope, + FinishSummary, + CueVolume, + Retention, + ReturnTo, + PostPrompt, + RememberSetup, + ConfirmRestart, + ReplaySort, + Count +}; + +struct Setting { + std::string_view key; + int initial, maximum; +}; + +inline constexpr std::array(Option::Count)> settings{{ + {"splits", 1, 1}, {"split_position", 0, 3}, {"split_detail", 0, 2}, {"comparison", 0, 3}, + {"upcoming", 1, 2}, {"precision", 0, 1}, {"hud_size", 1, 2}, {"inset", 1, 2}, + {"background", 85, 100}, {"contrast", 0, 1}, {"delta_words", 0, 1}, {"reduced_motion", 0, 1}, + {"ghost_names", 1, 1}, {"ghost_opacity", 50, 100}, {"ghost_gap", 1, 1}, {"ghost_style", 0, 1}, + {"ghost_proximity", 0, 1}, {"ghost_marker", 1, 1}, {"replay_inputs", 1, 1}, {"replay_splits", 1, 1}, + {"input_position", 2, 3}, {"replay_speed", 1, 3}, {"playback_controls", 0, 1}, {"input_size", 1, 2}, + {"seek_step", 1, 2}, {"start_paused", 0, 1}, {"lap_markers", 1, 1}, {"lap_delta", 1, 1}, + {"celebration", 0, 2}, {"celebration_scope", 0, 2}, {"finish_summary", 1, 1}, {"cue_volume", 35, 100}, + {"retention", 0, 1}, {"return_to", 0, 1}, {"post_prompt", 1, 1}, {"remember_setup", 1, 1}, + {"confirm_restart", 0, 1}, {"replay_sort", 0, 2}, +}}; + +inline constexpr std::string_view prefix = "speedrunning_"; +inline constexpr std::array playback_speeds{50, 100, 150, 200}; +inline constexpr std::array seek_seconds{5, 10, 30}; + +class Preferences { + std::array, settings.size()> values_{}; + + public: + Preferences() { + reset(); + } + + void reset() { + for (std::size_t i = 0; i < settings.size(); ++i) + values_[i].store(settings[i].initial, std::memory_order_relaxed); + } + + int get(Option option) const { + return values_[static_cast(option)].load(std::memory_order_relaxed); + } + + void set(Option option, int value) { + const auto index = static_cast(option); + const int minimum = option == Option::Background ? 55 : 0; + values_[index].store(std::clamp(value, minimum, settings[index].maximum), std::memory_order_relaxed); + } + + bool parse(std::string_view key, std::string_view value) { + if (!key.starts_with(prefix)) + return false; + key.remove_prefix(prefix.size()); + const auto entry = std::ranges::find(settings, key, &Setting::key); + if (entry == settings.end()) + return false; + int number = 0; + const auto result = std::from_chars(value.data(), value.data() + value.size(), number); + if (result.ec == std::errc{} && result.ptr == value.data() + value.size()) + set(static_cast